Initial commit

This commit is contained in:
Michael committed 2026-08-06 18:26:45 +12:00
commit b6014c6ffc
47 files changed
+4329

No files matched your search

+81
View File
@@ -0,0 +1,81 @@
package auth
import (
"fmt"
"net/http"
"time"
"github.com/golang-jwt/jwt/v5"
)
const (
SessionCookieName = "session"
sessionTTL = 7 * 24 * time.Hour
)
// SessionClaims is the app's own JWT payload minted after a successful OIDC
// login. Subject is our internal user UUID, not the OIDC sub.
type SessionClaims struct {
Email string `json:"email"`
jwt.RegisteredClaims
}
// MintSessionJWT signs a new session token for the given internal user ID.
func MintSessionJWT(secret, userID, email string) (string, error) {
now := time.Now()
claims := SessionClaims{
Email: email,
RegisteredClaims: jwt.RegisteredClaims{
Subject: userID,
Issuer: "vlog-backend",
IssuedAt: jwt.NewNumericDate(now),
ExpiresAt: jwt.NewNumericDate(now.Add(sessionTTL)),
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(secret))
}
// ParseSessionJWT verifies and decodes a session token, returning the claims.
func ParseSessionJWT(secret, tokenString string) (*SessionClaims, error) {
claims := &SessionClaims{}
token, err := jwt.ParseWithClaims(tokenString, claims, func(t *jwt.Token) (interface{}, error) {
if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", t.Header["alg"])
}
return []byte(secret), nil
})
if err != nil {
return nil, err
}
if !token.Valid {
return nil, fmt.Errorf("invalid token")
}
return claims, nil
}
// SetSessionCookie writes the signed session JWT as an httpOnly cookie.
func SetSessionCookie(w http.ResponseWriter, token string, secure bool) {
http.SetCookie(w, &http.Cookie{
Name: SessionCookieName,
Value: token,
Path: "/",
HttpOnly: true,
Secure: secure,
SameSite: http.SameSiteLaxMode,
MaxAge: int(sessionTTL.Seconds()),
})
}
// ClearSessionCookie logs the user out client-side.
func ClearSessionCookie(w http.ResponseWriter, secure bool) {
http.SetCookie(w, &http.Cookie{
Name: SessionCookieName,
Value: "",
Path: "/",
HttpOnly: true,
Secure: secure,
SameSite: http.SameSiteLaxMode,
MaxAge: -1,
})
}
+42
View File
@@ -0,0 +1,42 @@
package auth
import (
"context"
"net/http"
)
type contextKey string
const userIDContextKey contextKey = "userID"
// RequireAuth reads the session cookie, verifies the JWT, and injects the
// internal user ID into the request context. Responds 401 if missing/invalid.
// This is the only route guard the app needs — every non-auth API route is
// wrapped with it.
func RequireAuth(jwtSecret string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie(SessionCookieName)
if err != nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
claims, err := ParseSessionJWT(jwtSecret, cookie.Value)
if err != nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
ctx := context.WithValue(r.Context(), userIDContextKey, claims.Subject)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// UserIDFromContext returns the authenticated user's internal UUID. Only
// valid on requests that passed through RequireAuth.
func UserIDFromContext(ctx context.Context) (string, bool) {
id, ok := ctx.Value(userIDContextKey).(string)
return id, ok
}
+153
View File
@@ -0,0 +1,153 @@
// Package auth implements the OIDC authorization-code login flow and the
// app's own JWT session cookie that replaces the OIDC tokens after login.
package auth
import (
"context"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"net/http"
"time"
"github.com/coreos/go-oidc/v3/oidc"
"golang.org/x/oauth2"
)
const (
stateCookieName = "oidc_state"
verifierCookieName = "oidc_verifier"
oidcCookieTTL = 5 * time.Minute
)
// OIDCClaims is the subset of ID token claims we care about.
type OIDCClaims struct {
Sub string `json:"sub"`
Email string `json:"email"`
Name string `json:"name"`
}
// Authenticator wraps the discovered OIDC provider + oauth2 config for the
// authorization-code flow.
type Authenticator struct {
provider *oidc.Provider
verifier *oidc.IDTokenVerifier
oauthConfig oauth2.Config
// secureCookies controls the Secure flag on the short-lived login
// cookies; false only makes sense for local http:// development.
secureCookies bool
}
func NewAuthenticator(ctx context.Context, issuerURL, clientID, clientSecret, redirectURL string, secureCookies bool) (*Authenticator, error) {
provider, err := oidc.NewProvider(ctx, issuerURL)
if err != nil {
return nil, fmt.Errorf("discover oidc provider: %w", err)
}
return &Authenticator{
provider: provider,
verifier: provider.Verifier(&oidc.Config{ClientID: clientID}),
oauthConfig: oauth2.Config{
ClientID: clientID,
ClientSecret: clientSecret,
RedirectURL: redirectURL,
Endpoint: provider.Endpoint(),
Scopes: []string{oidc.ScopeOpenID, "profile", "email"},
},
secureCookies: secureCookies,
}, nil
}
// BeginLogin generates state + a PKCE verifier, stashes both in short-lived
// cookies, and redirects the browser to the provider's authorize endpoint.
func (a *Authenticator) BeginLogin(w http.ResponseWriter, r *http.Request) {
state := randomToken()
verifier := oauth2.GenerateVerifier()
setShortLivedCookie(w, stateCookieName, state, a.secureCookies)
setShortLivedCookie(w, verifierCookieName, verifier, a.secureCookies)
authURL := a.oauthConfig.AuthCodeURL(state, oauth2.S256ChallengeOption(verifier))
http.Redirect(w, r, authURL, http.StatusFound)
}
// HandleCallback validates state, exchanges the code for tokens, and returns
// the verified ID token claims. It also clears the short-lived cookies.
func (a *Authenticator) HandleCallback(ctx context.Context, w http.ResponseWriter, r *http.Request) (*OIDCClaims, error) {
defer clearCookie(w, stateCookieName)
defer clearCookie(w, verifierCookieName)
stateCookie, err := r.Cookie(stateCookieName)
if err != nil {
return nil, errors.New("missing state cookie")
}
verifierCookie, err := r.Cookie(verifierCookieName)
if err != nil {
return nil, errors.New("missing verifier cookie")
}
if r.URL.Query().Get("state") != stateCookie.Value {
return nil, errors.New("state mismatch")
}
code := r.URL.Query().Get("code")
if code == "" {
return nil, errors.New("missing code")
}
token, err := a.oauthConfig.Exchange(ctx, code, oauth2.VerifierOption(verifierCookie.Value))
if err != nil {
return nil, fmt.Errorf("exchange code: %w", err)
}
rawIDToken, ok := token.Extra("id_token").(string)
if !ok {
return nil, errors.New("no id_token in token response")
}
idToken, err := a.verifier.Verify(ctx, rawIDToken)
if err != nil {
return nil, fmt.Errorf("verify id_token: %w", err)
}
var claims OIDCClaims
if err := idToken.Claims(&claims); err != nil {
return nil, fmt.Errorf("parse id_token claims: %w", err)
}
if claims.Sub == "" {
return nil, errors.New("id_token missing sub")
}
return &claims, nil
}
func randomToken() string {
b := make([]byte, 32)
if _, err := rand.Read(b); err != nil {
panic(err) // crypto/rand failing is unrecoverable
}
return base64.RawURLEncoding.EncodeToString(b)
}
func setShortLivedCookie(w http.ResponseWriter, name, value string, secure bool) {
http.SetCookie(w, &http.Cookie{
Name: name,
Value: value,
Path: "/",
HttpOnly: true,
Secure: secure,
SameSite: http.SameSiteLaxMode,
MaxAge: int(oidcCookieTTL.Seconds()),
})
}
func clearCookie(w http.ResponseWriter, name string) {
http.SetCookie(w, &http.Cookie{
Name: name,
Value: "",
Path: "/",
HttpOnly: true,
MaxAge: -1,
})
}