mirror of
https://github.com/BaaRai/ARTEX.git
synced 2026-12-03 13:11:05 +00:00
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.
This commit is contained in:
parent
fe121a2cea
commit
eb045647cf
3 changed files with 100 additions and 15 deletions
|
|
@ -7,9 +7,9 @@ import (
|
|||
)
|
||||
|
||||
// apiMux is the /api/ mux plus the permission recorded for each pattern.
|
||||
// Routes are added with Server.handle. requirePerm denies a request whose
|
||||
// pattern has no recorded permission, so a route added with a plain
|
||||
// HandleFunc call answers 403 instead of being served.
|
||||
// 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
|
||||
|
|
@ -28,13 +28,27 @@ func (s *Server) handle(mux *apiMux, pattern string, p perm.Perm, h http.Handler
|
|||
mux.HandleFunc(pattern, h)
|
||||
}
|
||||
|
||||
// requirePerm runs after requireAuth. It answers 403 when the pattern that
|
||||
// would serve the request has no recorded permission. Requests that match no
|
||||
// pattern (404, 405) go to the mux unchanged.
|
||||
func (mux *apiMux) requirePerm() http.Handler {
|
||||
// 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 != "" {
|
||||
if _, ok := mux.perms[pattern]; !ok {
|
||||
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
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ import (
|
|||
"path/filepath"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
|
|
@ -70,8 +71,10 @@ func TestEveryRouteHasPermission(t *testing.T) {
|
|||
}
|
||||
|
||||
// No file in the package registers an API route without Server.handle. The
|
||||
// only allowed direct calls are the one inside handle and the root mux that
|
||||
// splits /api/ from the web UI.
|
||||
// only allowed direct calls are the one inside handle and the two root mux
|
||||
// routes that split /api/ from the web UI: root.Handle("/api/", ...) and
|
||||
// root.HandleFunc("/", ...). Any other root route, such as
|
||||
// root.HandleFunc("GET /api/leak", ...), would skip requireAuth.
|
||||
func TestNoRawRouteRegistration(t *testing.T) {
|
||||
files, err := filepath.Glob("*.go")
|
||||
if err != nil {
|
||||
|
|
@ -102,7 +105,7 @@ func TestNoRawRouteRegistration(t *testing.T) {
|
|||
recv, _ := sel.X.(*ast.Ident)
|
||||
switch {
|
||||
case name == "routes.go" && recv != nil && recv.Name == "mux":
|
||||
case name == "server.go" && recv != nil && recv.Name == "root":
|
||||
case name == "server.go" && recv != nil && recv.Name == "root" && rootRouteAllowed(sel.Sel.Name, call):
|
||||
default:
|
||||
t.Errorf("%s: raw %s call; register API routes with s.handle", fset.Position(call.Pos()), sel.Sel.Name)
|
||||
}
|
||||
|
|
@ -111,8 +114,47 @@ func TestNoRawRouteRegistration(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
// rootRouteAllowed reports whether a root mux call registers one of the two
|
||||
// allowed patterns.
|
||||
func rootRouteAllowed(method string, call *ast.CallExpr) bool {
|
||||
if len(call.Args) == 0 {
|
||||
return false
|
||||
}
|
||||
lit, ok := call.Args[0].(*ast.BasicLit)
|
||||
if !ok || lit.Kind != token.STRING {
|
||||
return false
|
||||
}
|
||||
pattern, err := strconv.Unquote(lit.Value)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return (method == "Handle" && pattern == "/api/") || (method == "HandleFunc" && pattern == "/")
|
||||
}
|
||||
|
||||
// The real handler answers 401 without a session for every authenticated
|
||||
// route, so the permission check is part of the production chain.
|
||||
func TestHandlerDeniesAuthenticatedRoutesWithoutSession(t *testing.T) {
|
||||
s := &Server{jwtKey: []byte("0123456789abcdef0123456789abcdef")}
|
||||
h := s.Handler()
|
||||
wildcard := regexp.MustCompile(`\{[^}]*\}`)
|
||||
for pattern, p := range s.apiRoutes().perms {
|
||||
if p != perm.Authenticated {
|
||||
continue
|
||||
}
|
||||
method, path, _ := strings.Cut(pattern, " ")
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, httptest.NewRequest(method, wildcard.ReplaceAllString(path, "x"), nil))
|
||||
if rec.Code != 401 {
|
||||
t.Errorf("%s without a session: status %d, want 401", pattern, rec.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A route added to the mux without a permission is denied with 403, even
|
||||
// with a valid session. Unknown paths and methods behave as before.
|
||||
// with a valid session, and an authenticated route needs a session even when
|
||||
// its path falls under the /api/auth/ prefix that requireAuth exempts.
|
||||
// Unknown paths and methods behave as before. The routes go through
|
||||
// handlerFor, the same chain Handler builds.
|
||||
func TestUntaggedRouteIsForbidden(t *testing.T) {
|
||||
s := &Server{jwtKey: []byte("0123456789abcdef0123456789abcdef")}
|
||||
tok, err := signJWT(s.jwtKey)
|
||||
|
|
@ -131,7 +173,12 @@ func TestUntaggedRouteIsForbidden(t *testing.T) {
|
|||
reached = true
|
||||
w.WriteHeader(204)
|
||||
})
|
||||
h := s.requireAuth(mux.requirePerm())
|
||||
wildcardReached := false
|
||||
s.handle(mux, "GET /api/{kind}/items/list", perm.Authenticated, func(w http.ResponseWriter, _ *http.Request) {
|
||||
wildcardReached = true
|
||||
w.WriteHeader(204)
|
||||
})
|
||||
h := s.handlerFor(mux)
|
||||
for _, tc := range []struct {
|
||||
method, path string
|
||||
bearer bool
|
||||
|
|
@ -158,6 +205,24 @@ func TestUntaggedRouteIsForbidden(t *testing.T) {
|
|||
t.Errorf("%s %s bearer=%v: status=%d reached=%v, want %d", tc.method, tc.path, tc.bearer, rec.Code, reached, tc.want)
|
||||
}
|
||||
}
|
||||
|
||||
// "GET /api/{kind}/items/list" matches /api/auth/items/list, which requireAuth
|
||||
// exempts by prefix. The recorded permission still requires a session.
|
||||
for _, tc := range []struct {
|
||||
bearer bool
|
||||
want int
|
||||
}{{false, 401}, {true, 204}} {
|
||||
wildcardReached = false
|
||||
r := httptest.NewRequest("GET", "/api/auth/items/list", nil)
|
||||
if tc.bearer {
|
||||
r.Header.Set("Authorization", "Bearer "+tok)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, r)
|
||||
if rec.Code != tc.want || wildcardReached != tc.bearer {
|
||||
t.Errorf("GET /api/auth/items/list bearer=%v: status=%d reached=%v, want %d", tc.bearer, rec.Code, wildcardReached, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandleWithoutPermissionPanics(t *testing.T) {
|
||||
|
|
|
|||
|
|
@ -1137,12 +1137,18 @@ func (s *Server) apiRoutes() *apiMux {
|
|||
}
|
||||
|
||||
func (s *Server) Handler() http.Handler {
|
||||
mux := s.apiRoutes()
|
||||
return s.handlerFor(s.apiRoutes())
|
||||
}
|
||||
|
||||
// handlerFor builds the production handler around an API mux. Handler uses
|
||||
// it with the real route table; tests use it with their own routes, so they
|
||||
// exercise the same chain.
|
||||
func (s *Server) handlerFor(mux *apiMux) http.Handler {
|
||||
// /api/* goes through CORS, JWT and the route permission check (routes.go);
|
||||
// everything else is served by the embedded frontend (public — auth is
|
||||
// enforced client-side and on the API). With the
|
||||
// no-embed build the webui handler just 404s (run `next dev` separately).
|
||||
api := cors(s.requireAuth(mux.requirePerm()))
|
||||
api := cors(s.requireAuth(s.requirePerm(mux)))
|
||||
root := http.NewServeMux()
|
||||
root.Handle("/api/", api)
|
||||
webui := s.webuiHandler()
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue