You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airavata.apache.org by la...@apache.org on 2026/07/22 06:51:38 UTC

(airavata-custos) 01/29: Add token-verified route gate for unlinked callers

This is an automated email from the ASF dual-hosted git repository.

lahirujayathilake pushed a commit to branch pearc26
in repository https://gitbox.apache.org/repos/asf/airavata-custos.git

commit d5785188e14b8a5f4991da1e3f5a9dda1404d21d
Author: lahiruj <la...@gmail.com>
AuthorDate: Thu Jul 16 00:51:07 2026 -0400

    Add token-verified route gate for unlinked callers
---
 cmd/server/main.go              |   2 +-
 pkg/identity/identity.go        |  15 ++++
 pkg/identity/middleware.go      |  46 ++++++++++--
 pkg/identity/middleware_test.go | 158 ++++++++++++++++++++++++++++++++++++++++
 pkg/identity/verifier.go        |   3 +
 5 files changed, 217 insertions(+), 7 deletions(-)

diff --git a/cmd/server/main.go b/cmd/server/main.go
index f7cc37762..5a517a669 100644
--- a/cmd/server/main.go
+++ b/cmd/server/main.go
@@ -149,7 +149,7 @@ func run() error {
 
 	// identity.Middleware sits in front of the router-backed server, so every
 	// gated route sees a verified caller + privilege set on ctx.
-	authed := identity.Middleware(verifier, svc, router.PublicPaths(), srv)
+	authed := identity.Middleware(verifier, svc, router.PublicPaths(), router.TokenPathMatcher(), srv)
 	handler := server.LoggingMiddleware(authed)
 
 	httpServer := &http.Server{
diff --git a/pkg/identity/identity.go b/pkg/identity/identity.go
index b270c9aec..03d7c95ca 100644
--- a/pkg/identity/identity.go
+++ b/pkg/identity/identity.go
@@ -54,6 +54,7 @@ type ctxKey string
 const (
 	callerKey     ctxKey = "caller"
 	privilegesKey ctxKey = "privileges"
+	claimsKey     ctxKey = "claims"
 )
 
 type privilegeSet map[models.PrivilegeKey]struct{}
@@ -71,6 +72,20 @@ func CallerFromContext(ctx context.Context) *Caller {
 	return nil
 }
 
+// WithClaims attaches the verified token claims to ctx. The middleware sets
+// it for every verified request, linked or not.
+func WithClaims(ctx context.Context, claims *Claims) context.Context {
+	return context.WithValue(ctx, claimsKey, claims)
+}
+
+// ClaimsFromContext returns the verified token claims, or nil if none are set.
+func ClaimsFromContext(ctx context.Context) *Claims {
+	if claims, ok := ctx.Value(claimsKey).(*Claims); ok {
+		return claims
+	}
+	return nil
+}
+
 // withPrivileges attaches the caller's effective privilege set to ctx;
 // RequirePrivilege wrappers only read it.
 func withPrivileges(ctx context.Context, keys []models.PrivilegeKey) context.Context {
diff --git a/pkg/identity/middleware.go b/pkg/identity/middleware.go
index 9e984aa9b..cde53d75e 100644
--- a/pkg/identity/middleware.go
+++ b/pkg/identity/middleware.go
@@ -18,6 +18,7 @@
 package identity
 
 import (
+	"context"
 	"encoding/json"
 	"errors"
 	"log/slog"
@@ -27,10 +28,17 @@ import (
 	"github.com/apache/airavata-custos/pkg/models"
 )
 
+// TokenVerifier validates a raw bearer token into Claims. Satisfied by
+// JWTVerifier; tests substitute a stub.
+type TokenVerifier interface {
+	Verify(ctx context.Context, rawToken string) (*Claims, error)
+}
+
 // Middleware verifies the bearer token once, resolves the caller, and
 // attaches Caller + privilege set to the request context. Public paths
-// bypass verification entirely.
-func Middleware(verifier *JWTVerifier, resolver UserResolver, publicPaths []string, next http.Handler) http.Handler {
+// bypass verification entirely. A verified-but-unlinked caller proceeds
+// with Claims only when isTokenPath matches the request.
+func Middleware(verifier TokenVerifier, resolver UserResolver, publicPaths []string, isTokenPath func(*http.Request) bool, next http.Handler) http.Handler {
 	publicSet := make(map[string]struct{}, len(publicPaths))
 	for _, path := range publicPaths {
 		publicSet[path] = struct{}{}
@@ -50,8 +58,13 @@ func Middleware(verifier *JWTVerifier, resolver UserResolver, publicPaths []stri
 			writeJSONError(w, http.StatusUnauthorized, "invalid_token", "Invalid or expired bearer token")
 			return
 		}
-		caller, privileges, err := resolver.ResolveCaller(req.Context(), claims)
+		ctx := WithClaims(req.Context(), claims)
+		caller, privileges, err := resolver.ResolveCaller(ctx, claims)
 		if errors.Is(err, ErrNotLinked) {
+			if isTokenPath != nil && isTokenPath(req) {
+				next.ServeHTTP(w, req.WithContext(ctx))
+				return
+			}
 			writeJSONError(w, http.StatusUnauthorized, "identity_not_linked", "OIDC identity is not linked to a portal user")
 			return
 		}
@@ -60,21 +73,25 @@ func Middleware(verifier *JWTVerifier, resolver UserResolver, publicPaths []stri
 			writeJSONError(w, http.StatusServiceUnavailable, "auth_lookup_failed", "Identity resolution failed")
 			return
 		}
-		ctx := WithCaller(req.Context(), caller)
+		ctx = WithCaller(ctx, caller)
 		ctx = withPrivileges(ctx, privileges)
 		next.ServeHTTP(w, req.WithContext(ctx))
 	})
 }
 
 // Router is the only path that lets HTTP routes hit the mux. The mux
-// field is unexported on purpose: callers must go through RequirePrivilege, RequireAuth, or Public.
+// field is unexported on purpose: callers must go through RequirePrivilege,
+// RequireAuth, RequireToken, or Public.
 type Router struct {
 	mux         *http.ServeMux
+	tokenMux    *http.ServeMux
 	publicPaths []string
 }
 
 // NewRouter wraps mux.
-func NewRouter(mux *http.ServeMux) *Router { return &Router{mux: mux} }
+func NewRouter(mux *http.ServeMux) *Router {
+	return &Router{mux: mux, tokenMux: http.NewServeMux()}
+}
 
 // RequirePrivilege registers an authenticated handler. The wrapper checks privilege
 // against the caller's privilege set in ctx; absent → 403.
@@ -114,6 +131,23 @@ func (r *Router) RequireScoped(pattern string, authorize func(http.ResponseWrite
 	})
 }
 
+// RequireToken registers a handler reachable with a verified token whose
+// identity is not yet linked to a user. Handlers read ClaimsFromContext;
+// CallerFromContext may be nil.
+func (r *Router) RequireToken(pattern string, handler http.HandlerFunc) {
+	r.mux.HandleFunc(pattern, handler)
+	r.tokenMux.HandleFunc(pattern, func(http.ResponseWriter, *http.Request) {})
+}
+
+// TokenPathMatcher reports whether a request targets a RequireToken route,
+// with the same pattern semantics as the real mux.
+func (r *Router) TokenPathMatcher() func(*http.Request) bool {
+	return func(req *http.Request) bool {
+		_, pattern := r.tokenMux.Handler(req)
+		return pattern != ""
+	}
+}
+
 // PublicPaths returns the path components of every Public() registration,
 // suitable for handing to Middleware.
 func (r *Router) PublicPaths() []string { return r.publicPaths }
diff --git a/pkg/identity/middleware_test.go b/pkg/identity/middleware_test.go
new file mode 100644
index 000000000..4fbea2626
--- /dev/null
+++ b/pkg/identity/middleware_test.go
@@ -0,0 +1,158 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package identity
+
+import (
+	"context"
+	"errors"
+	"net/http"
+	"net/http/httptest"
+	"testing"
+
+	"github.com/apache/airavata-custos/pkg/models"
+)
+
+type stubVerifier struct {
+	claims *Claims
+	err    error
+}
+
+func (s *stubVerifier) Verify(context.Context, string) (*Claims, error) { return s.claims, s.err }
+
+type stubResolver struct {
+	caller     *Caller
+	privileges []models.PrivilegeKey
+	err        error
+}
+
+func (s *stubResolver) ResolveCaller(context.Context, *Claims) (*Caller, []models.PrivilegeKey, error) {
+	return s.caller, s.privileges, s.err
+}
+
+func newTestRouter(t *testing.T) (*Router, *Claims, *Caller) {
+	t.Helper()
+	router := NewRouter(http.NewServeMux())
+	claims := &Claims{Sub: "sub-1", Email: "a@b.c", Name: "A B", GivenName: "A", FamilyName: "B"}
+	return router, claims, &Caller{UserID: "user-1"}
+}
+
+func serve(router *Router, verifier TokenVerifier, resolver UserResolver, method, target string) *httptest.ResponseRecorder {
+	handler := Middleware(verifier, resolver, router.PublicPaths(), router.TokenPathMatcher(), router)
+	rec := httptest.NewRecorder()
+	req := httptest.NewRequest(method, target, nil)
+	req.Header.Set("Authorization", "Bearer token")
+	handler.ServeHTTP(rec, req)
+	return rec
+}
+
+func TestUnlinkedCallerReachesTokenRouteWithClaims(t *testing.T) {
+	router, claims, _ := newTestRouter(t)
+	var got *Claims
+	var gotCaller *Caller
+	router.RequireToken("GET /access-requests/events/{code}", func(w http.ResponseWriter, req *http.Request) {
+		got = ClaimsFromContext(req.Context())
+		gotCaller = CallerFromContext(req.Context())
+	})
+
+	rec := serve(router, &stubVerifier{claims: claims}, &stubResolver{err: ErrNotLinked}, http.MethodGet, "/access-requests/events/PEARC26")
+
+	if rec.Code != http.StatusOK {
+		t.Fatalf("status = %d, want 200; body %s", rec.Code, rec.Body.String())
+	}
+	if got == nil || got.Sub != "sub-1" || got.GivenName != "A" {
+		t.Fatalf("claims on context = %+v, want the verified claims", got)
+	}
+	if gotCaller != nil {
+		t.Fatalf("caller on context = %+v, want nil for unlinked", gotCaller)
+	}
+}
+
+func TestUnlinkedCallerStill401OnNonTokenRoute(t *testing.T) {
+	router, claims, _ := newTestRouter(t)
+	router.RequireToken("GET /access-requests/me", func(http.ResponseWriter, *http.Request) {})
+	router.RequireAuth("GET /me", func(http.ResponseWriter, *http.Request) {})
+
+	rec := serve(router, &stubVerifier{claims: claims}, &stubResolver{err: ErrNotLinked}, http.MethodGet, "/me")
+
+	if rec.Code != http.StatusUnauthorized {
+		t.Fatalf("status = %d, want 401", rec.Code)
+	}
+}
+
+func TestUnlinkedCallerMethodMismatchIsNotATokenPath(t *testing.T) {
+	router, claims, _ := newTestRouter(t)
+	router.RequireToken("POST /access-requests", func(http.ResponseWriter, *http.Request) {})
+
+	rec := serve(router, &stubVerifier{claims: claims}, &stubResolver{err: ErrNotLinked}, http.MethodGet, "/access-requests")
+
+	if rec.Code != http.StatusUnauthorized {
+		t.Fatalf("status = %d, want 401", rec.Code)
+	}
+}
+
+func TestLinkedCallerOnTokenRouteGetsCallerAndClaims(t *testing.T) {
+	router, claims, caller := newTestRouter(t)
+	var gotCaller *Caller
+	var gotClaims *Claims
+	router.RequireToken("GET /access-requests/me", func(w http.ResponseWriter, req *http.Request) {
+		gotCaller = CallerFromContext(req.Context())
+		gotClaims = ClaimsFromContext(req.Context())
+	})
+
+	rec := serve(router, &stubVerifier{claims: claims}, &stubResolver{caller: caller}, http.MethodGet, "/access-requests/me")
+
+	if rec.Code != http.StatusOK {
+		t.Fatalf("status = %d, want 200", rec.Code)
+	}
+	if gotCaller == nil || gotCaller.UserID != "user-1" {
+		t.Fatalf("caller = %+v, want user-1", gotCaller)
+	}
+	if gotClaims == nil || gotClaims.Sub != "sub-1" {
+		t.Fatalf("claims = %+v, want the verified claims", gotClaims)
+	}
+}
+
+func TestLinkedCallerUnaffectedOnRegularRoutes(t *testing.T) {
+	router, claims, caller := newTestRouter(t)
+	router.RequireToken("POST /access-requests", func(http.ResponseWriter, *http.Request) {})
+	var hasPriv bool
+	router.RequirePrivilege("GET /users", models.PrivilegeKey("core:users:read"), func(w http.ResponseWriter, req *http.Request) {
+		hasPriv = HasPrivilege(req.Context(), models.PrivilegeKey("core:users:read"))
+	})
+
+	resolver := &stubResolver{caller: caller, privileges: []models.PrivilegeKey{"core:users:read"}}
+	rec := serve(router, &stubVerifier{claims: claims}, resolver, http.MethodGet, "/users")
+
+	if rec.Code != http.StatusOK {
+		t.Fatalf("status = %d, want 200", rec.Code)
+	}
+	if !hasPriv {
+		t.Fatal("privilege set missing on context")
+	}
+}
+
+func TestInvalidTokenIs401EvenOnTokenRoute(t *testing.T) {
+	router, _, _ := newTestRouter(t)
+	router.RequireToken("GET /access-requests/me", func(http.ResponseWriter, *http.Request) {})
+
+	rec := serve(router, &stubVerifier{err: errors.New("expired")}, &stubResolver{}, http.MethodGet, "/access-requests/me")
+
+	if rec.Code != http.StatusUnauthorized {
+		t.Fatalf("status = %d, want 401", rec.Code)
+	}
+}
diff --git a/pkg/identity/verifier.go b/pkg/identity/verifier.go
index fc0ccaeee..1b5bdca6b 100644
--- a/pkg/identity/verifier.go
+++ b/pkg/identity/verifier.go
@@ -32,6 +32,9 @@ type Claims struct {
 	Sub           string `json:"sub"`
 	Email         string `json:"email"`
 	EmailVerified bool   `json:"email_verified"`
+	Name          string `json:"name"`
+	GivenName     string `json:"given_name"`
+	FamilyName    string `json:"family_name"`
 }
 
 // NewJWTVerifier resolves the provider's discovery doc and builds a verifier