Let non-admin accounts be granted single services, starting with /receipt/
Test and deploy / test (push) Successful in 1m57s
Test and deploy / deploy (push) Successful in 1m42s

Access was admin or nothing, so letting a friend print receipts meant making
them a full admin. Users now carry a list of permissions (User.Permissions,
a JSON column), each a key from the registry in services/permissions.go;
admins pass every check. The only key so far is `receipt`.

GET /auth/validate/:permission answers like /auth/validate-admin (200/403/401,
with the same refresh-token fallback, now shared) plus 404 for an unknown key,
and reads the user row rather than the token, so a grant or revoke applies on
the next request. On 200 it returns the username in X-Auth-User.

nginx gets a permission gate beside the admin gate: a location sets
$auth_permission and auth_requests /internal/auth/validate. /receipt/ moves
onto it, forwarding X-Remote-User to the receipt server. 403 now goes to
/no-access rather than back to the login page. The variable must not be given
a server-level default: the subrequest re-runs the server rewrite phase and
would blank it.

The admin panel's Manage Users tab ticks permissions per user
(setUserPermissions, permissionTypes). The login page is no longer
admin-only in wording or destination: a non-admin lands on /account, which
lists the services they can open; /no-access is the same view with a notice.

/auth/validate-admin and every other admin-gated service are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-23 22:04:56 +01:00
co-authored by Claude Opus 5.5
parent efd74c1693
commit acf21c69c2
27 changed files with 1101 additions and 119 deletions
+1 -1
View File
@@ -155,7 +155,7 @@ func tokenVersionOf(v uint) uint {
// verifies the signature and expiry, reads the id claim, loads the row, and
// checks the token version. Every caller that used to hand-roll this sequence
// (handlers.Store.CheckToken, handlers.Store.RefreshToken,
// handlers.Store.tryRefreshAndValidateAdmin and the GraphQL refreshToken
// handlers.Store.tryRefreshAndValidate and the GraphQL refreshToken
// resolver) now goes through here, so the checks cannot drift apart.
//
// The returned error is always one of the sentinels above, wrapped or not, so
+49
View File
@@ -0,0 +1,49 @@
package services
import (
"slices"
"adam-french.co.uk/backend/models"
)
// Per-service permissions: how a non-admin account is let into one gated
// service (the receipt printer, say) without being made an admin.
//
// A permission is a key from PermissionTypes stored in models.User.Permissions.
// nginx gates a service on one key by asking GET /auth/validate/<key>
// (handlers.Store.ValidatePermission); admins pass every such check, so
// moving a service from the admin gate to a permission gate never locks an
// admin out. Services that are not listed here stay admin-only.
//
// Adding a grantable service is one entry below plus swapping that location's
// nginx gate from /internal/auth/admin-validate to the permission gate (see
// "Permission gate" in nginx/nginx_routes.conf.template).
// PermissionType describes one grantable service. Key is what is stored and
// what nginx names; Label and Path are for the admin panel's checkboxes and
// the signed-in user's /account list of links.
type PermissionType struct {
Key string
Label string
Path string
}
// PermissionTypes is the full set of grantable permissions, in display order.
// Removing an entry leaves the key in users' rows, where it is inert: the
// validate endpoint 404s an unknown key, so nothing can be gated on it.
var PermissionTypes = []PermissionType{
{Key: "receipt", Label: "Receipt printer", Path: "/receipt/"},
}
// ValidPermission reports whether key names a permission in PermissionTypes.
func ValidPermission(key string) bool {
return slices.ContainsFunc(PermissionTypes, func(p PermissionType) bool {
return p.Key == key
})
}
// HasPermission reports whether user may use the service gated on key. It
// reads the row, not a token, so Admin here is the current database value.
func HasPermission(user *models.User, key string) bool {
return user.Admin || slices.Contains(user.Permissions, key)
}
+54
View File
@@ -0,0 +1,54 @@
package services
import (
"testing"
"adam-french.co.uk/backend/models"
)
func TestValidPermission(t *testing.T) {
for _, p := range PermissionTypes {
if !ValidPermission(p.Key) {
t.Errorf("listed key %q reported invalid", p.Key)
}
}
for _, key := range []string{"", "admin", "Receipt", "receipt "} {
if ValidPermission(key) {
t.Errorf("unlisted key %q reported valid", key)
}
}
}
// Keys must be URL-path safe: nginx splices them into /auth/validate/<key>.
func TestPermissionKeysArePathSafe(t *testing.T) {
seen := map[string]bool{}
for _, p := range PermissionTypes {
if seen[p.Key] {
t.Errorf("duplicate key %q", p.Key)
}
seen[p.Key] = true
for _, r := range p.Key {
if !(r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || r == '-') {
t.Errorf("key %q has %q; use lowercase letters, digits and '-'", p.Key, r)
}
}
}
}
func TestHasPermission(t *testing.T) {
cases := []struct {
name string
user models.User
want bool
}{
{"admin passes without a grant", models.User{Admin: true}, true},
{"granted user passes", models.User{Permissions: []string{"receipt"}}, true},
{"other grant does not count", models.User{Permissions: []string{"other"}}, false},
{"no grants (NULL column) fails", models.User{}, false},
}
for _, c := range cases {
if got := HasPermission(&c.user, "receipt"); got != c.want {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
}
}
+6 -1
View File
@@ -29,6 +29,11 @@ var logQuietDrop = map[string]bool{
"/auth/check": true, // front-end session check
}
// logQuietDropPrefix is the permission gate's auth_request subrequest
// (/auth/validate/<key>), dropped on 2xx for the same reason as
// /auth/validate-admin above: it repeats on every request to a gated page.
const logQuietDropPrefix = "/auth/validate/"
// TrafficLogFormatter renders gin's log line. Signed to gin's LogFormatter
// signature so it plugs into gin.LoggerWithFormatter.
func TrafficLogFormatter(params gin.LogFormatterParams) string {
@@ -63,7 +68,7 @@ func TrafficLogFormatter(params gin.LogFormatterParams) string {
// All-quiet: drop heartbeat endpoints that succeeded. A 4xx/5xx on them
// is still interesting (an expired session raging against refresh, a
// broken admin gate) and is kept.
if logQuietDrop[path] && params.StatusCode < 400 {
if (logQuietDrop[path] || startsWith(path, logQuietDropPrefix)) && params.StatusCode < 400 {
return ""
}
+9
View File
@@ -25,6 +25,15 @@ func TestTrafficFormatterDropsQuietHeartbeats(t *testing.T) {
}
}
func TestTrafficFormatterDropsPermissionGate(t *testing.T) {
if out := TrafficLogFormatter(fmtParams("GET", "/auth/validate/receipt", 200, "172.28.0.6", time.Millisecond)); out != "" {
t.Fatalf("permission-gate 200 should be dropped, got %q", out)
}
if out := TrafficLogFormatter(fmtParams("GET", "/auth/validate/receipt", 403, "172.28.0.6", time.Millisecond)); out == "" {
t.Fatal("a refused permission check must stay visible")
}
}
func TestTrafficFormatterKeepsHeartbeatFailures(t *testing.T) {
out := TrafficLogFormatter(fmtParams("GET", "/auth/validate-admin", 401, "172.28.0.6", time.Millisecond))
if out == "" {