ARTEX/server/routes.go
Marco Azarmaneche eb045647cf fix(server): apply the route permission and test the production chain
requirePerm now applies the recorded permission instead of only checking
that one exists: a perm.Authenticated pattern answers 401 without a valid
session. requireAuth exempts /api/auth/ by prefix, so a wildcard pattern
such as "GET /api/{kind}/items" would otherwise be public for
/api/auth/items.

Handler builds its chain with handlerFor, and TestUntaggedRouteIsForbidden
uses handlerFor, so removing requirePerm from the production chain fails
the test. A wildcard route is tested with a path under /api/auth/.

TestNoRawRouteRegistration allows only root.Handle("/api/", ...) and
root.HandleFunc("/", ...) in server.go; any other root route would skip
requireAuth.

TestHandlerDeniesAuthenticatedRoutesWithoutSession checks every
authenticated route through the real Handler.
2026-12-03 01:18:22 +02:00

58 lines
1.8 KiB
Go

package server
import (
"net/http"
"github.com/Autumn-27/artex/server/perm"
)
// apiMux is the /api/ mux plus the permission recorded for each pattern.
// Routes are added with Server.handle. requirePerm applies the recorded
// permission and denies a pattern that has none, so a route added with a
// plain HandleFunc call answers 403 instead of being served.
type apiMux struct {
*http.ServeMux
perms map[string]perm.Perm
}
func newAPIMux() *apiMux {
return &apiMux{ServeMux: http.NewServeMux(), perms: map[string]perm.Perm{}}
}
// handle registers h for pattern and records the permission it needs.
func (s *Server) handle(mux *apiMux, pattern string, p perm.Perm, h http.HandlerFunc) {
if p == 0 {
panic("server: route " + pattern + " registered without a permission")
}
mux.perms[pattern] = p
mux.HandleFunc(pattern, h)
}
// requirePerm runs after requireAuth and applies the permission recorded for
// the pattern that would serve the request:
// - no recorded permission: 403, so a route added with a plain HandleFunc
// call is denied instead of served;
// - perm.Authenticated: 401 without a valid session. requireAuth exempts
// paths by prefix (/api/auth/...), and a wildcard pattern such as
// "GET /api/{kind}/items" also matches /api/auth/items; this check keeps
// such a route behind a session.
//
// Requests that match no pattern (404, 405) go to the mux unchanged.
func (s *Server) requirePerm(mux *apiMux) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, pattern := mux.Handler(r); pattern != "" {
switch p := mux.perms[pattern]; p {
case perm.Public:
case perm.Authenticated:
if !s.sessionOK(extractToken(r)) {
writeErr(w, 401, "Unauthorized")
return
}
default:
writeErr(w, 403, "Forbidden")
return
}
}
mux.ServeHTTP(w, r)
})
}