Feat v0.7.7 api tokens ext permissions (#61)
All checks were successful
CI/CD / detect-changes (push) Successful in 4s
CI/CD / e2e-smoke (push) Has been skipped
CI/CD / test-frontend (push) Successful in 6s
CI/CD / test-runners (push) Has been skipped
CI/CD / test-go-pg (push) Successful in 2m48s
CI/CD / test-sqlite (push) Successful in 2m49s
CI/CD / build-and-deploy (push) Successful in 28s

Co-authored-by: Jeffrey Smith <jasafpro@gmail.com>
Co-committed-by: Jeffrey Smith <jasafpro@gmail.com>
This commit was merged in pull request #61.
This commit is contained in:
2026-04-02 19:11:47 +00:00
committed by xcaliber
parent e02b13dc12
commit e4f0bdbd36
34 changed files with 1769 additions and 58 deletions

View File

@@ -1,6 +1,7 @@
package middleware
import (
"context"
"log"
"net/http"
"os"
@@ -11,6 +12,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"armature/auth"
"armature/config"
"armature/database"
"armature/store"
@@ -184,9 +186,15 @@ func UserIDFromCookie(c *gin.Context, jwtSecret string) string {
// ─── Auth middleware ─────────────────────────────────────────
// Auth returns a Gin middleware that validates JWT bearer tokens and
// verifies the user is active with their current DB role.
func Auth(cfg *config.Config, users store.UserStore, cache *UserStatusCache) gin.HandlerFunc {
// Auth returns a Gin middleware that validates JWT bearer tokens or personal
// access tokens (PATs) and verifies the user is active.
func Auth(cfg *config.Config, users store.UserStore, cache *UserStatusCache, tokens ...store.APITokenStore) gin.HandlerFunc {
// Optional PAT store — passed as variadic to keep call sites compatible.
var tokenStore store.APITokenStore
if len(tokens) > 0 && tokens[0] != nil {
tokenStore = tokens[0]
}
return func(c *gin.Context) {
// Skip auth when running without a database (unmanaged mode)
if !database.IsConnected() {
@@ -217,6 +225,13 @@ func Auth(cfg *config.Config, users store.UserStore, cache *UserStatusCache) gin
return
}
// ── PAT path ──
if strings.HasPrefix(tokenString, "arm_pat_") && tokenStore != nil {
authenticatePAT(c, tokenString, tokenStore, users, cache)
return
}
// ── JWT path ──
claims, ok := parseAndValidateJWT(tokenString, cfg.JWTSecret)
if !ok {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
@@ -236,6 +251,33 @@ func Auth(cfg *config.Config, users store.UserStore, cache *UserStatusCache) gin
}
}
// authenticatePAT validates a personal access token and sets context values.
func authenticatePAT(c *gin.Context, tokenString string, tokenStore store.APITokenStore, users store.UserStore, cache *UserStatusCache) {
tokenHash := auth.HashToken(tokenString)
apiToken, err := tokenStore.GetByHash(c.Request.Context(), tokenHash)
if err != nil || apiToken == nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
"error": "invalid or expired token",
})
return
}
// Verify user is still active
if !verifyUserByID(c, apiToken.UserID, users, cache) {
return
}
c.Set("user_id", apiToken.UserID)
c.Set("auth_method", "pat")
c.Set("pat_permissions", apiToken.Permissions)
// Fire-and-forget: update last_used_at
go tokenStore.UpdateLastUsed(context.Background(), apiToken.ID)
c.Next()
}
// ─── CORS middleware ─────────────────────────────────────────
// CORS returns a middleware that sets cross-origin headers.
@@ -322,7 +364,7 @@ type TicketValidator interface {
// When ?token= is used, a deprecation notice is logged. The ticket
// path avoids exposing the JWT in server logs, proxy logs, and
// browser history.
func WsAuth(cfg *config.Config, users store.UserStore, cache *UserStatusCache, tickets TicketValidator) gin.HandlerFunc {
func WsAuth(cfg *config.Config, users store.UserStore, cache *UserStatusCache, tickets TicketValidator, tokens ...store.APITokenStore) gin.HandlerFunc {
return func(c *gin.Context) {
if !database.IsConnected() {
c.Next()
@@ -389,6 +431,12 @@ func WsAuth(cfg *config.Config, users store.UserStore, cache *UserStatusCache, t
return
}
// PAT support in WS auth
if strings.HasPrefix(tokenString, "arm_pat_") && len(tokens) > 0 && tokens[0] != nil {
authenticatePAT(c, tokenString, tokens[0], users, cache)
return
}
claims, ok := parseAndValidateJWT(tokenString, cfg.JWTSecret)
if !ok {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{

View File

@@ -30,10 +30,26 @@ func RequirePermission(perm string, stores store.Stores) gin.HandlerFunc {
}
// resolveAndCachePerms loads the user's effective permissions once per request.
// For PAT-authenticated requests, uses the token's stored permissions directly
// (git model: token retains permissions even if user later loses them).
func resolveAndCachePerms(c *gin.Context, stores store.Stores, userID string) (map[string]bool, error) {
if cached, exists := c.Get(permCacheKey); exists {
return cached.(map[string]bool), nil
}
// PAT path: use token's stored permissions directly
if c.GetString("auth_method") == "pat" {
if patPerms, exists := c.Get("pat_permissions"); exists {
perms := make(map[string]bool)
for _, p := range patPerms.([]string) {
perms[p] = true
}
c.Set(permCacheKey, perms)
return perms, nil
}
}
// JWT path: resolve from groups
perms, err := auth.ResolvePermissions(c.Request.Context(), stores, userID)
if err != nil {
return nil, err