Refactor authentication middleware and enhance security headers

This commit is contained in:
2025-02-25 13:39:24 -06:00
parent 8759bd2454
commit 0ba5eee981
6 changed files with 382 additions and 271 deletions

View File

@ -1,34 +1,13 @@
/*
Copyright © 2025 Wiki Cafe <mail@wiki.cafe>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cmd
import (
"log"
"net/http"
"net/url"
"context"
"git.coopcloud.tech/wiki-cafe/member-console/internal/auth"
"git.coopcloud.tech/wiki-cafe/member-console/internal/middleware"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/gorilla/sessions"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"golang.org/x/oauth2"
)
var startCmd = &cobra.Command{
@ -46,79 +25,23 @@ var startCmd = &cobra.Command{
// Create a new HTTP request router
httpRequestRouter := http.NewServeMux()
// Add to Run function
store := sessions.NewCookieStore(
[]byte(viper.GetString("session-secret")),
)
store.Options = &sessions.Options{
HttpOnly: true,
Secure: viper.GetString("env") == "production",
SameSite: http.SameSiteLaxMode,
MaxAge: 86400 * 7, // 1 week
}
// OIDC Provider
provider, err := oidc.NewProvider(context.Background(), viper.GetString("issuer-url"))
// Set up authentication
authConfig, err := auth.Setup()
if err != nil {
log.Fatal("Failed to initialize OIDC provider:", err)
log.Fatalf("Failed to set up authentication: %v", err)
}
// OAuth2 Config
oauthConfig := &oauth2.Config{
ClientID: viper.GetString("client-id"),
ClientSecret: viper.GetString("client-secret"),
RedirectURL: viper.GetString("hostname") + "/callback",
Endpoint: provider.Endpoint(),
Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
}
// Register auth handlers
authConfig.RegisterHandlers(httpRequestRouter)
authConfig := &middleware.AuthConfig{
Store: store,
OAuthConfig: oauthConfig,
Verifier: provider.Verifier(&oidc.Config{ClientID: oauthConfig.ClientID}),
}
// Register handlers
httpRequestRouter.HandleFunc("/login", middleware.LoginHandler(authConfig))
httpRequestRouter.HandleFunc("/callback", middleware.CallbackHandler(authConfig))
// Update the logout handler to include Keycloak integration
httpRequestRouter.HandleFunc("/logout", func(w http.ResponseWriter, r *http.Request) {
// 1. Get session and immediately expire it
session, _ := authConfig.Store.Get(r, "auth-session")
session.Values["authenticated"] = false
session.Options.MaxAge = -1 // Immediate deletion
session.Save(r, w)
// 2. Keycloak logout parameters
keycloakLogoutURL, err := url.Parse(viper.GetString("issuer-url") + "/protocol/openid-connect/logout")
if err != nil {
log.Printf("Error parsing logout URL: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
// 3. Build logout URL with post_logout_redirect_uri and id_token_hint
q := keycloakLogoutURL.Query()
q.Set("post_logout_redirect_uri", viper.GetString("hostname"))
q.Set("client_id", viper.GetString("client-id"))
// Retrieve ID token from session if available
if idToken, ok := session.Values["id_token"].(string); ok {
q.Set("id_token_hint", idToken)
}
keycloakLogoutURL.RawQuery = q.Encode()
// 4. Redirect to Keycloak for global session termination
http.Redirect(w, r, keycloakLogoutURL.String(), http.StatusFound)
})
// Update middleware stack
// Create middleware stack
stack := middleware.CreateStack(
middleware.SecureHeaders,
middleware.Logging,
middleware.AuthMiddleware(authConfig),
authConfig.Middleware(),
)
// Create HTTP server
server := http.Server{
Addr: ":" + port,
Handler: stack(httpRequestRouter),
@ -132,19 +55,21 @@ var startCmd = &cobra.Command{
}
func init() {
// Register the port flag with Cobra
// Register flags with Cobra
startCmd.Flags().StringP("port", "p", "", "Port to listen on")
startCmd.Flags().String("client-id", "", "OIDC Client ID")
startCmd.Flags().String("client-secret", "", "OIDC Client Secret")
startCmd.Flags().String("issuer-url", "", "Identity Provider Issuer URL")
startCmd.Flags().String("hostname", "", "Address at which is the server exposed.")
startCmd.Flags().String("hostname", "", "Address at which the server is exposed")
startCmd.Flags().String("session-secret", "", "Session encryption secret")
startCmd.Flags().String("env", "", "Environment (development/production)")
// Bind the flags to Viper
// Bind all flags to Viper
viper.BindPFlags(startCmd.Flags())
// Set a default value for the port if no flag or env variable is provided
// Set default values
viper.SetDefault("port", "8080")
viper.SetDefault("env", "development")
// Add the command to the root command
rootCmd.AddCommand(startCmd)

316
internal/auth/auth.go Normal file
View File

@ -0,0 +1,316 @@
package auth
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"fmt"
"log"
"net/http"
"net/url"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/gorilla/sessions"
"github.com/spf13/viper"
"golang.org/x/oauth2"
)
// Config holds all auth-related configuration
type Config struct {
Store *sessions.CookieStore
OAuthConfig *oauth2.Config
Verifier *oidc.IDTokenVerifier
Provider *oidc.Provider
SessionName string
}
// Setup initializes the auth configuration
func Setup() (*Config, error) {
// Create cookie store
store := sessions.NewCookieStore(
[]byte(viper.GetString("session-secret")),
)
store.Options = &sessions.Options{
HttpOnly: true,
Secure: viper.GetString("env") == "production",
SameSite: http.SameSiteLaxMode,
MaxAge: 86400 * 7, // 1 week
}
// Initialize OIDC provider
ctx := context.Background()
provider, err := oidc.NewProvider(ctx, viper.GetString("issuer-url"))
if err != nil {
return nil, fmt.Errorf("failed to initialize OIDC provider: %w", err)
}
// Create OAuth2 config
oauthConfig := &oauth2.Config{
ClientID: viper.GetString("client-id"),
ClientSecret: viper.GetString("client-secret"),
RedirectURL: viper.GetString("hostname") + "/callback",
Endpoint: provider.Endpoint(),
Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
}
// Create auth config
config := &Config{
Store: store,
OAuthConfig: oauthConfig,
Provider: provider,
Verifier: provider.Verifier(&oidc.Config{ClientID: oauthConfig.ClientID}),
SessionName: "auth-session",
}
return config, nil
}
// RegisterHandlers adds all auth-related handlers to the router
func (c *Config) RegisterHandlers(mux *http.ServeMux) {
mux.HandleFunc("/login", c.LoginHandler)
mux.HandleFunc("/callback", c.CallbackHandler)
mux.HandleFunc("/logout", c.LogoutHandler)
mux.HandleFunc("/logout-callback", c.LogoutCallbackHandler)
}
// Middleware returns an auth middleware function
func (c *Config) Middleware() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Skip authentication for public routes
if r.URL.Path == "/login" || r.URL.Path == "/callback" ||
r.URL.Path == "/logout" || r.URL.Path == "/logout-callback" {
next.ServeHTTP(w, r)
return
}
session, err := c.Store.Get(r, c.SessionName)
if err != nil {
http.Redirect(w, r, "/login", http.StatusFound)
return
}
if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
http.Redirect(w, r, "/login", http.StatusFound)
return
}
next.ServeHTTP(w, r)
})
}
}
// LoginHandler initiates the OIDC authentication flow
func (c *Config) LoginHandler(w http.ResponseWriter, r *http.Request) {
state := generateRandomString(32)
nonce := generateRandomString(32)
codeVerifier := generateRandomString(32)
hash := sha256.Sum256([]byte(codeVerifier))
codeChallenge := base64.RawURLEncoding.EncodeToString(hash[:])
session, _ := c.Store.Get(r, c.SessionName)
session.Values["state"] = state
session.Values["nonce"] = nonce
session.Values["code_verifier"] = codeVerifier
if err := session.Save(r, w); err != nil {
log.Printf("Error saving session: %v", err)
http.Error(w, "Server error", http.StatusInternalServerError)
return
}
authURL := c.OAuthConfig.AuthCodeURL(
state,
oidc.Nonce(nonce),
oauth2.SetAuthURLParam("code_challenge", codeChallenge),
oauth2.SetAuthURLParam("code_challenge_method", "S256"),
)
http.Redirect(w, r, authURL, http.StatusFound)
}
// CallbackHandler processes the OIDC callback
func (c *Config) CallbackHandler(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
session, err := c.Store.Get(r, c.SessionName)
if err != nil {
http.Error(w, "Session error", http.StatusInternalServerError)
return
}
// Validate state
state := r.URL.Query().Get("state")
if savedState, ok := session.Values["state"].(string); !ok || state != savedState {
log.Printf("State mismatch: got %s, expected %s", state, savedState)
http.Error(w, "Invalid state", http.StatusBadRequest)
return
}
// Exchange code
code := r.URL.Query().Get("code")
codeVerifier, ok := session.Values["code_verifier"].(string)
if !ok {
http.Error(w, "No code verifier found", http.StatusBadRequest)
return
}
token, err := c.OAuthConfig.Exchange(
ctx,
code,
oauth2.VerifierOption(codeVerifier),
)
if err != nil {
log.Printf("Token exchange failed: %v", err)
http.Error(w, "Token exchange failed", http.StatusInternalServerError)
return
}
// Verify ID token
rawIDToken, ok := token.Extra("id_token").(string)
if !ok {
http.Error(w, "Missing ID token", http.StatusInternalServerError)
return
}
idToken, err := c.Verifier.Verify(ctx, rawIDToken)
if err != nil {
log.Printf("ID token verification failed: %v", err)
http.Error(w, "Invalid ID token", http.StatusInternalServerError)
return
}
// Verify nonce
var claims struct {
Nonce string `json:"nonce"`
}
if err := idToken.Claims(&claims); err != nil {
http.Error(w, "Could not parse claims", http.StatusInternalServerError)
return
}
if claims.Nonce != session.Values["nonce"].(string) {
http.Error(w, "Invalid nonce", http.StatusBadRequest)
return
}
// Authenticate session
session.Values["authenticated"] = true
session.Values["id_token"] = rawIDToken
// Store user info
var userInfo struct {
Email string `json:"email"`
Name string `json:"name"`
Username string `json:"preferred_username"`
}
if err := idToken.Claims(&userInfo); err == nil {
session.Values["email"] = userInfo.Email
session.Values["name"] = userInfo.Name
session.Values["username"] = userInfo.Username
}
if err := session.Save(r, w); err != nil {
log.Printf("Error saving session: %v", err)
http.Error(w, "Server error", http.StatusInternalServerError)
return
}
http.Redirect(w, r, "/", http.StatusFound)
}
// LogoutHandler handles user logout
func (c *Config) LogoutHandler(w http.ResponseWriter, r *http.Request) {
// Generate logout state for verification
state := generateRandomString(32)
// Get session
session, err := c.Store.Get(r, c.SessionName)
if err != nil {
http.Error(w, "Session error", http.StatusInternalServerError)
return
}
// Store logout state for verification
session.Values["logout_state"] = state
if err := session.Save(r, w); err != nil {
log.Printf("Error saving logout state: %v", err)
http.Error(w, "Server error", http.StatusInternalServerError)
return
}
// Build logout URL
keycloakLogoutURL, err := url.Parse(viper.GetString("issuer-url") + "/protocol/openid-connect/logout")
if err != nil {
log.Printf("Error parsing logout URL: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
// Add query parameters
q := keycloakLogoutURL.Query()
// Use logout-callback for completing the logout flow
q.Set("post_logout_redirect_uri", viper.GetString("hostname")+"/logout-callback")
q.Set("client_id", viper.GetString("client-id"))
q.Set("state", state)
// Add id_token_hint if available
if idToken, ok := session.Values["id_token"].(string); ok {
q.Set("id_token_hint", idToken)
}
keycloakLogoutURL.RawQuery = q.Encode()
// Log for debugging
log.Printf("Redirecting to logout URL: %s", keycloakLogoutURL.String())
// Redirect to Keycloak
http.Redirect(w, r, keycloakLogoutURL.String(), http.StatusFound)
}
// LogoutCallbackHandler handles the redirect after Keycloak logout
func (c *Config) LogoutCallbackHandler(w http.ResponseWriter, r *http.Request) {
// Get session
session, err := c.Store.Get(r, c.SessionName)
if err != nil {
http.Error(w, "Session error", http.StatusInternalServerError)
return
}
// Verify state parameter
returnedState := r.URL.Query().Get("state")
log.Printf("Received logout state: %s", returnedState)
savedState, ok := session.Values["logout_state"].(string)
if !ok {
log.Printf("No logout state found in session")
http.Error(w, "Invalid session state", http.StatusBadRequest)
return
}
log.Printf("Saved logout state: %s", savedState)
if returnedState != savedState {
log.Printf("State mismatch: %s != %s", returnedState, savedState)
http.Error(w, "Invalid state", http.StatusBadRequest)
return
}
// Clear the session completely
session.Options.MaxAge = -1
if err := session.Save(r, w); err != nil {
log.Printf("Error clearing session: %v", err)
http.Error(w, "Server error", http.StatusInternalServerError)
return
}
// Redirect to login page
http.Redirect(w, r, "/login", http.StatusFound)
}
// Helper function to generate random strings
func generateRandomString(n int) string {
b := make([]byte, n)
if _, err := rand.Read(b); err != nil {
panic(err)
}
return base64.RawURLEncoding.EncodeToString(b)
}

View File

@ -1,123 +0,0 @@
package middleware
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"net/http"
"github.com/coreos/go-oidc/v3/oidc"
"github.com/gorilla/sessions"
"golang.org/x/oauth2"
)
type AuthConfig struct {
Store *sessions.CookieStore
OAuthConfig *oauth2.Config
Verifier *oidc.IDTokenVerifier
}
func AuthMiddleware(config *AuthConfig) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Skip authentication for public routes
if r.URL.Path == "/login" || r.URL.Path == "/callback" {
next.ServeHTTP(w, r)
return
}
session, _ := config.Store.Get(r, "auth-session")
if auth, ok := session.Values["authenticated"].(bool); !ok || !auth {
http.Redirect(w, r, "/login", http.StatusFound)
return
}
next.ServeHTTP(w, r)
})
}
}
func generateRandomString(n int) string {
b := make([]byte, n)
rand.Read(b)
return base64.RawURLEncoding.EncodeToString(b)
}
func LoginHandler(config *AuthConfig) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
state := generateRandomString(32)
nonce := generateRandomString(32)
codeVerifier := generateRandomString(32)
hash := sha256.Sum256([]byte(codeVerifier))
codeChallenge := base64.RawURLEncoding.EncodeToString(hash[:])
session, _ := config.Store.Get(r, "auth-session")
session.Values["state"] = state
session.Values["nonce"] = nonce
session.Values["code_verifier"] = codeVerifier
session.Save(r, w)
authURL := config.OAuthConfig.AuthCodeURL(
state,
oidc.Nonce(nonce),
oauth2.SetAuthURLParam("code_challenge", codeChallenge),
oauth2.SetAuthURLParam("code_challenge_method", "S256"),
)
http.Redirect(w, r, authURL, http.StatusFound)
}
}
func CallbackHandler(config *AuthConfig) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
session, _ := config.Store.Get(r, "auth-session")
// Validate state
state := r.URL.Query().Get("state")
if savedState, ok := session.Values["state"].(string); !ok || state != savedState {
http.Error(w, "Invalid state", http.StatusBadRequest)
return
}
// Exchange code
codeVerifier := session.Values["code_verifier"].(string)
token, err := config.OAuthConfig.Exchange(
ctx,
r.URL.Query().Get("code"),
oauth2.VerifierOption(codeVerifier),
)
if err != nil {
http.Error(w, "Token exchange failed", http.StatusInternalServerError)
return
}
// Verify ID token
rawIDToken, ok := token.Extra("id_token").(string)
if !ok {
http.Error(w, "Missing ID token", http.StatusInternalServerError)
return
}
idToken, err := config.Verifier.Verify(ctx, rawIDToken)
if err != nil {
http.Error(w, "Invalid ID token", http.StatusInternalServerError)
return
}
// Verify nonce
var claims struct {
Nonce string `json:"nonce"`
}
if err := idToken.Claims(&claims); err != nil || claims.Nonce != session.Values["nonce"].(string) {
http.Error(w, "Invalid nonce", http.StatusBadRequest)
return
}
// Authenticate session
session.Values["authenticated"] = true
// session.Values["id_token"] = rawIDToken
session.Save(r, w)
http.Redirect(w, r, "/", http.StatusFound)
}
}

View File

@ -6,11 +6,27 @@ import (
"github.com/gorilla/sessions"
)
// SecureHeaders is a middleware function that adds secure headers to the HTTP response
// SecurityHeaders adds security and cache-control headers to all responses
func SecureHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Security-Policy", "default-src 'self'")
w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
// Set strict cache control headers
w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Expires", "0")
// Add security headers with updated CSP
w.Header().Set("Content-Security-Policy",
"default-src 'self'; "+
"script-src 'self' https://unpkg.com/htmx.org@* 'unsafe-inline'; "+
"style-src 'self' 'unsafe-inline'; "+
"img-src 'self' data:; "+
"connect-src 'self'; "+
"frame-ancestors 'none'; "+
"form-action 'self'")
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)
})
}

View File

@ -9,6 +9,8 @@
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f9f9f9;
color: #333;
}
header {
background-color: #f0f2f5;
@ -21,21 +23,39 @@
.user-info {
display: flex;
align-items: center;
gap: 12px;
}
.user-info span {
margin-right: 1rem;
font-weight: 600;
}
.btn-logout {
background-color: #f44336;
color: white;
.btn {
padding: 8px 16px;
border: none;
border-radius: 4px;
cursor: pointer;
text-decoration: none;
font-weight: 500;
transition: background-color 0.2s ease;
}
.btn-account {
background-color: #4285f4;
color: white;
}
.btn-account:hover {
background-color: #3367d6;
}
.btn-logout {
background-color: #f44336;
color: white;
}
.btn-logout:hover {
background-color: #d32f2f;
}
.content {
padding: 2rem;
max-width: 1200px;
margin: 0 auto;
}
</style>
<script src="https://unpkg.com/htmx.org"></script>
</head>
@ -43,9 +63,14 @@
<header>
<div class="user-info">
<span>Welcome, User!</span>
<a href="/logout" class="btn-logout">Logout</a>
<a href="http://localhost:8080/realms/master/account" class="btn btn-account">Account</a>
<a href="/logout" class="btn btn-logout">Logout</a>
</div>
</header>
<!-- Rest of your protected content -->
<div class="content">
<!-- Rest of your protected content -->
<h1>Dashboard</h1>
<p>This is your protected dashboard content.</p>
</div>
</body>
</html>

View File

@ -1,48 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f2f5;
}
.login-container {
background: white;
padding: 2rem;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
text-align: center;
}
.login-button {
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
.login-button:hover {
background-color: #45a049;
}
</style>
</head>
<body>
<div class="login-container">
<h1>Welcome</h1>
<p>Please log in to continue</p>
<button class="login-button" onclick="window.location.href='/login'">
Login with Keycloak
</button>
</div>
</body>
</html>