This repository has been archived on 2026-04-03. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
core/server/middleware/permissions.go
Jeffrey Smith f32eefab14 Feat v0.7.7 API tokens + extension permissions (#61)
Personal access tokens (PATs) for programmatic API access with
SHA-256 hashing, permission scoping (git model), and Settings/Admin UI.
Extension-declared user permissions with dynamic registry, gate_permission
manifest field, permissions Starlark module, and grouped admin UI.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 18:20:16 +00:00

71 lines
2.2 KiB
Go

package middleware
import (
"net/http"
"github.com/gin-gonic/gin"
"armature/auth"
"armature/store"
)
const permCacheKey = "resolved_permissions"
// RequirePermission returns middleware that enforces a named permission.
// Permission resolution is cached in the request context — computed at most
// once per request regardless of how many RequirePermission middlewares are
// chained. Admins receive permissions through the Admins group.
func RequirePermission(perm string, stores store.Stores) gin.HandlerFunc {
return func(c *gin.Context) {
userID := c.GetString("user_id")
perms, err := resolveAndCachePerms(c, stores, userID)
if err != nil || !perms[perm] {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
"error": "permission required: " + perm,
})
return
}
c.Next()
}
}
// 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
}
c.Set(permCacheKey, perms)
return perms, nil
}
// GetResolvedPermissions returns the cached permission set for the current
// request. Returns nil if not yet resolved (i.e. RequirePermission was not
// earlier in the chain). Callers in handlers can use this for conditional
// logic without triggering an extra DB round-trip.
func GetResolvedPermissions(c *gin.Context) map[string]bool {
if cached, exists := c.Get(permCacheKey); exists {
return cached.(map[string]bool)
}
return nil
}