Merge Fix 04 (HIGH A-4): scope-aware ActorRole revoke

This commit is contained in:
shankar0123
2026-05-11 11:16:24 +00:00
13 changed files with 715 additions and 32 deletions
+70 -3
View File
@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strings"
"time"
@@ -72,7 +73,11 @@ type AuthPermissionService interface {
// effective-permissions query the GUI's /v1/auth/me handler uses.
type AuthActorRoleService interface {
Grant(ctx context.Context, caller *authsvc.Caller, ar *authdomain.ActorRole) error
Revoke(ctx context.Context, caller *authsvc.Caller, actorID string, actorType domain.ActorType, roleID string) error
// Audit 2026-05-11 A-4 — Revoke takes optional scope filtering so
// callers that hold multiple scoped variants of the same role can
// drop one variant selectively. opts.ScopeType == "" preserves the
// legacy "revoke all" semantic.
Revoke(ctx context.Context, caller *authsvc.Caller, actorID string, actorType domain.ActorType, roleID string, opts repository.ActorRoleRevokeOptions) error
ListForActor(ctx context.Context, caller *authsvc.Caller, actorID string, actorType domain.ActorType) ([]*authdomain.ActorRole, error)
EffectivePermissions(ctx context.Context, caller *authsvc.Caller, actorID string, actorType domain.ActorType) ([]repository.EffectivePermission, error)
// ListKeys (Bundle 1 Phase 7) returns every actor in the tenant
@@ -496,6 +501,22 @@ func (h AuthHandler) AssignRoleToKey(w http.ResponseWriter, r *http.Request) {
}
// RevokeRoleFromKey handles DELETE /api/v1/auth/keys/{id}/roles/{role_id}.
//
// Audit 2026-05-11 A-4 — two operating modes selected by presence of
// the optional `?scope_type=` / `?scope_id=` query parameters:
//
// - No query params: legacy "revoke every scope variant of this role
// from this actor" semantic. Preserves pre-A-4 GUI behaviour
// (KeysPage before Fix 12 fires plain DELETE with no scope; one
// button per role row).
//
// - `scope_type=global` (no scope_id) or
// `scope_type=profile&scope_id=<id>` /
// `scope_type=issuer&scope_id=<id>`: drop ONLY the matching variant.
// Returns HTTP 404 when no row matches the scope (operator
// feedback for typos). Validation mirrors AssignRoleToKey:
// `scope_id` MUST be empty with `scope_type=global`, MUST be
// present with `profile` / `issuer`, anything else → 400.
func (h AuthHandler) RevokeRoleFromKey(w http.ResponseWriter, r *http.Request) {
caller, err := callerFromRequest(r)
if err != nil {
@@ -504,7 +525,19 @@ func (h AuthHandler) RevokeRoleFromKey(w http.ResponseWriter, r *http.Request) {
}
keyID := r.PathValue("id")
roleID := r.PathValue("role_id")
if err := h.actors.Revoke(r.Context(), caller, keyID, domain.ActorTypeAPIKey, roleID); err != nil {
// Parse + validate optional scope filter. Empty query string is
// the legacy path; mismatched filter is rejected before the call
// reaches the service.
scopeTypeRaw := r.URL.Query().Get("scope_type")
scopeIDRaw := r.URL.Query().Get("scope_id")
opts, derr := parseRevokeScope(scopeTypeRaw, scopeIDRaw)
if derr != nil {
Error(w, http.StatusBadRequest, derr.Error())
return
}
if err := h.actors.Revoke(r.Context(), caller, keyID, domain.ActorTypeAPIKey, roleID, opts); err != nil {
writeAuthError(w, err)
return
}
@@ -515,6 +548,40 @@ func (h AuthHandler) RevokeRoleFromKey(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNoContent)
}
// parseRevokeScope translates the (scope_type, scope_id) query string
// into an ActorRoleRevokeOptions. Empty inputs → legacy "revoke all"
// option (zero value); any combination missing required halves →
// validation error. Audit 2026-05-11 A-4 — mirrors AssignRoleToKey's
// scope validation so the assign / revoke pair stays symmetric.
func parseRevokeScope(scopeType, scopeID string) (repository.ActorRoleRevokeOptions, error) {
scopeType = strings.TrimSpace(scopeType)
scopeID = strings.TrimSpace(scopeID)
if scopeType == "" {
if scopeID != "" {
return repository.ActorRoleRevokeOptions{}, fmt.Errorf("scope_id requires scope_type")
}
return repository.ActorRoleRevokeOptions{}, nil
}
switch authdomain.ScopeType(scopeType) {
case authdomain.ScopeTypeGlobal:
if scopeID != "" {
return repository.ActorRoleRevokeOptions{}, fmt.Errorf("scope_id must be empty when scope_type=global")
}
return repository.ActorRoleRevokeOptions{ScopeType: authdomain.ScopeTypeGlobal}, nil
case authdomain.ScopeTypeProfile, authdomain.ScopeTypeIssuer:
if scopeID == "" {
return repository.ActorRoleRevokeOptions{}, fmt.Errorf("scope_id is required when scope_type is profile or issuer")
}
sid := scopeID
return repository.ActorRoleRevokeOptions{
ScopeType: authdomain.ScopeType(scopeType),
ScopeID: &sid,
}, nil
default:
return repository.ActorRoleRevokeOptions{}, fmt.Errorf("invalid scope_type — must be global, profile, or issuer")
}
}
// Me handles GET /api/v1/auth/me. Returns the current actor's effective
// permissions plus admin flag (back-compat with /v1/auth/check). No
// permission required: every authenticated caller can read their own.
@@ -596,7 +663,7 @@ func writeAuthError(w http.ResponseWriter, err error) {
Error(w, http.StatusForbidden, err.Error())
case errors.Is(err, authsvc.ErrInvalidPermission):
Error(w, http.StatusBadRequest, err.Error())
case errors.Is(err, repository.ErrAuthNotFound):
case errors.Is(err, repository.ErrAuthNotFound), errors.Is(err, repository.ErrActorRoleNotFound):
Error(w, http.StatusNotFound, "Not found")
case errors.Is(err, repository.ErrAuthDuplicateName), errors.Is(err, repository.ErrAuthRoleInUse), errors.Is(err, repository.ErrAuthReservedActor):
Error(w, http.StatusConflict, err.Error())
+143 -2
View File
@@ -122,6 +122,13 @@ type fakeAuthActorSvc struct {
revokeErr error
roles []*authdomain.ActorRole
effective []repository.EffectivePermission
// Audit 2026-05-11 A-4 — capture Revoke opts so tests can assert
// that the handler forwards scope_type / scope_id correctly.
revokeOpts repository.ActorRoleRevokeOptions
revokeCall struct {
actorID, roleID string
called bool
}
}
func newFakeAuthActorSvc() *fakeAuthActorSvc {
@@ -134,7 +141,11 @@ func (f *fakeAuthActorSvc) Grant(_ context.Context, _ *authsvc.Caller, ar *authd
f.roles = append(f.roles, ar)
return nil
}
func (f *fakeAuthActorSvc) Revoke(_ context.Context, _ *authsvc.Caller, _ string, _ domain.ActorType, _ string) error {
func (f *fakeAuthActorSvc) Revoke(_ context.Context, _ *authsvc.Caller, actorID string, _ domain.ActorType, roleID string, opts repository.ActorRoleRevokeOptions) error {
f.revokeCall.called = true
f.revokeCall.actorID = actorID
f.revokeCall.roleID = roleID
f.revokeOpts = opts
return f.revokeErr
}
func (f *fakeAuthActorSvc) ListForActor(_ context.Context, _ *authsvc.Caller, _ string, _ domain.ActorType) ([]*authdomain.ActorRole, error) {
@@ -440,7 +451,7 @@ func TestAuthHandler_AssignRoleSelfRoleAssignReturns403(t *testing.T) {
}
func TestAuthHandler_RevokeRoleFromKey(t *testing.T) {
h, _, _, _ := newAuthHandlerWithFakes()
h, _, _, actorSvc := newAuthHandlerWithFakes()
req := withAuthCtx(httptest.NewRequest(http.MethodDelete, "/api/v1/auth/keys/alice/roles/r-viewer", nil), "admin", auth.ActorTypeAPIKey)
req.SetPathValue("id", "alice")
req.SetPathValue("role_id", "r-viewer")
@@ -449,6 +460,136 @@ func TestAuthHandler_RevokeRoleFromKey(t *testing.T) {
if rec.Code != http.StatusNoContent {
t.Errorf("revoke should be 204; got %d", rec.Code)
}
// Audit 2026-05-11 A-4 — no scope params → legacy "revoke all
// variants" semantic propagates as the zero-value
// ActorRoleRevokeOptions to the service layer.
if actorSvc.revokeOpts.ScopeType != "" {
t.Errorf("legacy DELETE forwarded a scope filter: ScopeType=%q", actorSvc.revokeOpts.ScopeType)
}
if actorSvc.revokeOpts.ScopeID != nil {
t.Errorf("legacy DELETE forwarded a scope_id: %v", actorSvc.revokeOpts.ScopeID)
}
}
// =============================================================================
// Audit 2026-05-11 A-4 — scope-aware revoke handler tests.
// =============================================================================
func TestAuthHandler_RevokeRoleFromKey_A4_ScopedProfile(t *testing.T) {
h, _, _, actorSvc := newAuthHandlerWithFakes()
req := withAuthCtx(httptest.NewRequest(http.MethodDelete,
"/api/v1/auth/keys/alice/roles/r-operator?scope_type=profile&scope_id=p-acme", nil),
"admin", auth.ActorTypeAPIKey)
req.SetPathValue("id", "alice")
req.SetPathValue("role_id", "r-operator")
rec := httptest.NewRecorder()
h.RevokeRoleFromKey(rec, req)
if rec.Code != http.StatusNoContent {
t.Fatalf("scoped revoke should be 204; got %d body=%s", rec.Code, rec.Body.String())
}
if actorSvc.revokeOpts.ScopeType != authdomain.ScopeTypeProfile {
t.Errorf("ScopeType = %q; want profile", actorSvc.revokeOpts.ScopeType)
}
if actorSvc.revokeOpts.ScopeID == nil || *actorSvc.revokeOpts.ScopeID != "p-acme" {
t.Errorf("ScopeID = %v; want p-acme", actorSvc.revokeOpts.ScopeID)
}
}
func TestAuthHandler_RevokeRoleFromKey_A4_ScopedGlobal(t *testing.T) {
h, _, _, actorSvc := newAuthHandlerWithFakes()
req := withAuthCtx(httptest.NewRequest(http.MethodDelete,
"/api/v1/auth/keys/alice/roles/r-operator?scope_type=global", nil),
"admin", auth.ActorTypeAPIKey)
req.SetPathValue("id", "alice")
req.SetPathValue("role_id", "r-operator")
rec := httptest.NewRecorder()
h.RevokeRoleFromKey(rec, req)
if rec.Code != http.StatusNoContent {
t.Fatalf("scoped revoke (global) should be 204; got %d body=%s", rec.Code, rec.Body.String())
}
if actorSvc.revokeOpts.ScopeType != authdomain.ScopeTypeGlobal {
t.Errorf("ScopeType = %q; want global", actorSvc.revokeOpts.ScopeType)
}
if actorSvc.revokeOpts.ScopeID != nil {
t.Errorf("ScopeID must be nil for scope_type=global; got %v", actorSvc.revokeOpts.ScopeID)
}
}
func TestAuthHandler_RevokeRoleFromKey_A4_RejectsScopeIDWithGlobal(t *testing.T) {
h, _, _, actorSvc := newAuthHandlerWithFakes()
req := withAuthCtx(httptest.NewRequest(http.MethodDelete,
"/api/v1/auth/keys/alice/roles/r-operator?scope_type=global&scope_id=p-acme", nil),
"admin", auth.ActorTypeAPIKey)
req.SetPathValue("id", "alice")
req.SetPathValue("role_id", "r-operator")
rec := httptest.NewRecorder()
h.RevokeRoleFromKey(rec, req)
if rec.Code != http.StatusBadRequest {
t.Errorf("global+scope_id should be 400; got %d body=%s", rec.Code, rec.Body.String())
}
if actorSvc.revokeCall.called {
t.Error("service should NOT have been called on validation error")
}
}
func TestAuthHandler_RevokeRoleFromKey_A4_RejectsMissingScopeID(t *testing.T) {
h, _, _, actorSvc := newAuthHandlerWithFakes()
req := withAuthCtx(httptest.NewRequest(http.MethodDelete,
"/api/v1/auth/keys/alice/roles/r-operator?scope_type=profile", nil),
"admin", auth.ActorTypeAPIKey)
req.SetPathValue("id", "alice")
req.SetPathValue("role_id", "r-operator")
rec := httptest.NewRecorder()
h.RevokeRoleFromKey(rec, req)
if rec.Code != http.StatusBadRequest {
t.Errorf("profile-without-scope_id should be 400; got %d body=%s", rec.Code, rec.Body.String())
}
if actorSvc.revokeCall.called {
t.Error("service should NOT have been called on validation error")
}
}
func TestAuthHandler_RevokeRoleFromKey_A4_RejectsScopeIDWithoutScopeType(t *testing.T) {
h, _, _, _ := newAuthHandlerWithFakes()
req := withAuthCtx(httptest.NewRequest(http.MethodDelete,
"/api/v1/auth/keys/alice/roles/r-operator?scope_id=p-acme", nil),
"admin", auth.ActorTypeAPIKey)
req.SetPathValue("id", "alice")
req.SetPathValue("role_id", "r-operator")
rec := httptest.NewRecorder()
h.RevokeRoleFromKey(rec, req)
if rec.Code != http.StatusBadRequest {
t.Errorf("scope_id-without-scope_type should be 400; got %d body=%s", rec.Code, rec.Body.String())
}
}
func TestAuthHandler_RevokeRoleFromKey_A4_RejectsInvalidScopeType(t *testing.T) {
h, _, _, _ := newAuthHandlerWithFakes()
req := withAuthCtx(httptest.NewRequest(http.MethodDelete,
"/api/v1/auth/keys/alice/roles/r-operator?scope_type=bogus", nil),
"admin", auth.ActorTypeAPIKey)
req.SetPathValue("id", "alice")
req.SetPathValue("role_id", "r-operator")
rec := httptest.NewRecorder()
h.RevokeRoleFromKey(rec, req)
if rec.Code != http.StatusBadRequest {
t.Errorf("bogus scope_type should be 400; got %d", rec.Code)
}
}
func TestAuthHandler_RevokeRoleFromKey_A4_ScopedNotFoundReturns404(t *testing.T) {
h, _, _, actorSvc := newAuthHandlerWithFakes()
actorSvc.revokeErr = repository.ErrActorRoleNotFound
req := withAuthCtx(httptest.NewRequest(http.MethodDelete,
"/api/v1/auth/keys/alice/roles/r-operator?scope_type=profile&scope_id=p-globex", nil),
"admin", auth.ActorTypeAPIKey)
req.SetPathValue("id", "alice")
req.SetPathValue("role_id", "r-operator")
rec := httptest.NewRecorder()
h.RevokeRoleFromKey(rec, req)
if rec.Code != http.StatusNotFound {
t.Errorf("ErrActorRoleNotFound should be 404; got %d", rec.Code)
}
}
func TestAuthHandler_RevokeReservedActorReturns409(t *testing.T) {