-
Notifications
You must be signed in to change notification settings - Fork 3
BCH-1315: AuthZ Phase 3 — AuthZen HTTP driver + batch Evaluations + /me/permissions #428
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ccf-lisa
wants to merge
3
commits into
main
Choose a base branch
from
lisa/feat/bch-1315
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,116 @@ | ||
| package handler | ||
|
|
||
| import ( | ||
| "errors" | ||
| "net/http" | ||
| "sort" | ||
|
|
||
| "github.com/compliance-framework/api/internal/api/middleware" | ||
| "github.com/compliance-framework/api/internal/authz" | ||
| "github.com/labstack/echo/v4" | ||
| "go.uber.org/zap" | ||
| ) | ||
|
|
||
| // PermissionsHandler serves GET /me/permissions: the set of (resource, action) pairs the | ||
| // authenticated subject may perform, computed in a single batch PDP call over the manifest | ||
| // vocabulary. The UI uses it to hide actions the user can't take (BCH-1318). It holds | ||
| // facts only — no policy logic — and reuses the PEP's subject derivation. | ||
| type PermissionsHandler struct { | ||
| pdp authz.PDP | ||
| manifest *authz.Manifest | ||
| failMode authz.FailMode | ||
| logger *zap.SugaredLogger | ||
| } | ||
|
|
||
| // NewPermissionsHandler constructs the handler. A nil logger becomes a no-op; an empty | ||
| // fail mode defaults to fail-closed. | ||
| func NewPermissionsHandler(pdp authz.PDP, manifest *authz.Manifest, failMode authz.FailMode, logger *zap.SugaredLogger) *PermissionsHandler { | ||
| if logger == nil { | ||
| logger = zap.NewNop().Sugar() | ||
| } | ||
| if failMode == "" { | ||
| failMode = authz.FailClosed | ||
| } | ||
| return &PermissionsHandler{pdp: pdp, manifest: manifest, failMode: failMode, logger: logger} | ||
| } | ||
|
|
||
| // Register mounts the route on a group that already enforces authentication. | ||
| func (h *PermissionsHandler) Register(g *echo.Group) { | ||
| g.GET("/permissions", h.GetPermissions) | ||
| } | ||
|
|
||
| type permissionsSubject struct { | ||
| Type string `json:"type"` | ||
| ID string `json:"id"` | ||
| } | ||
|
|
||
| type permissionsResponse struct { | ||
| Subject permissionsSubject `json:"subject"` | ||
| Permissions map[string][]string `json:"permissions"` | ||
| } | ||
|
|
||
| // GetPermissions enumerates every manifest resource × action for the current subject, | ||
| // asks the PDP for all decisions in one batch, and returns the allowed map. Resources are | ||
| // always present (so the UI knows the full vocabulary) with their allowed actions; ordering | ||
| // is deterministic (resources sorted, actions in manifest order). | ||
| func (h *PermissionsHandler) GetPermissions(c echo.Context) error { | ||
| subject := middleware.SubjectFromContext(c) | ||
| subjectView := permissionsSubject{Type: subject.Type, ID: subject.ID} | ||
|
|
||
| resources := make([]string, 0, len(h.manifest.Resources)) | ||
| for name := range h.manifest.Resources { | ||
| resources = append(resources, name) | ||
| } | ||
| sort.Strings(resources) | ||
|
|
||
| // Pre-seed every resource with an empty allow-list so the response shape is stable | ||
| // regardless of decisions or fail mode. | ||
| perms := make(map[string][]string, len(resources)) | ||
| for _, r := range resources { | ||
| perms[r] = []string{} | ||
| } | ||
|
|
||
| type pair struct{ resource, action string } | ||
| reqs := make([]authz.EvalRequest, 0) | ||
| index := make([]pair, 0) | ||
| for _, resource := range resources { | ||
| for _, action := range h.manifest.Resources[resource].Actions { | ||
| // Type-level capability check (no resource instance / request context), which | ||
| // is exactly what UI hints need; instance-level checks stay on the PEP. | ||
| reqs = append(reqs, authz.EvalRequest{ | ||
| Subject: subject, | ||
| Action: action, | ||
| Resource: authz.Resource{Type: resource}, | ||
| }) | ||
| index = append(index, pair{resource, action}) | ||
| } | ||
| } | ||
|
|
||
| decisions, err := h.pdp.Evaluations(c.Request().Context(), reqs) | ||
| if err != nil { | ||
| if errors.Is(err, authz.ErrUnavailable) { | ||
| h.logger.Warnw("authz PDP unavailable for /me/permissions", "failMode", h.failMode, "error", err) | ||
| if h.failMode == authz.FailOpen { | ||
| for _, r := range resources { | ||
| perms[r] = append([]string{}, h.manifest.Resources[r].Actions...) | ||
| } | ||
| } | ||
| // Fail closed leaves the pre-seeded empty lists (UI hides everything). | ||
| return c.JSON(http.StatusOK, permissionsResponse{Subject: subjectView, Permissions: perms}) | ||
| } | ||
| h.logger.Errorw("authz evaluation failed for /me/permissions", "error", err) | ||
| return echo.NewHTTPError(http.StatusInternalServerError, "authorization error") | ||
| } | ||
| if len(decisions) != len(index) { | ||
| h.logger.Errorw("authz returned wrong decision count for /me/permissions", | ||
| "want", len(index), "got", len(decisions)) | ||
| return echo.NewHTTPError(http.StatusInternalServerError, "authorization error") | ||
| } | ||
|
|
||
| for i, d := range decisions { | ||
| if d.Allow { | ||
| perms[index[i].resource] = append(perms[index[i].resource], index[i].action) | ||
| } | ||
| } | ||
| return c.JSON(http.StatusOK, permissionsResponse{Subject: subjectView, Permissions: perms}) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,160 @@ | ||
| package handler | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/json" | ||
| "fmt" | ||
| "net/http" | ||
| "net/http/httptest" | ||
| "testing" | ||
|
|
||
| "github.com/compliance-framework/api/internal/authn" | ||
| "github.com/compliance-framework/api/internal/authz" | ||
| "github.com/golang-jwt/jwt/v5" | ||
| "github.com/labstack/echo/v4" | ||
| "github.com/stretchr/testify/assert" | ||
| "github.com/stretchr/testify/require" | ||
| ) | ||
|
|
||
| // stubPDP answers Evaluations from an allow predicate (or an error), recording the batch | ||
| // size so the test can assert a single batched enumeration. | ||
| type stubPDP struct { | ||
| allow func(action string) bool | ||
| err error | ||
| lastBatch int | ||
| } | ||
|
|
||
| func (s *stubPDP) Evaluate(context.Context, authz.Subject, string, authz.Resource, map[string]any) (authz.Decision, error) { | ||
| return authz.Decision{}, nil | ||
| } | ||
|
|
||
| func (s *stubPDP) Evaluations(_ context.Context, reqs []authz.EvalRequest) ([]authz.Decision, error) { | ||
| s.lastBatch = len(reqs) | ||
| if s.err != nil { | ||
| return nil, s.err | ||
| } | ||
| out := make([]authz.Decision, len(reqs)) | ||
| for i, r := range reqs { | ||
| out[i] = authz.Decision{Allow: s.allow(r.Action)} | ||
| } | ||
| return out, nil | ||
| } | ||
|
|
||
| func newPermissionsCtx(t *testing.T, subject string) (echo.Context, *httptest.ResponseRecorder) { | ||
| t.Helper() | ||
| e := echo.New() | ||
| req := httptest.NewRequest(http.MethodGet, "/api/me/permissions", nil) | ||
| rec := httptest.NewRecorder() | ||
| c := e.NewContext(req, rec) | ||
| if subject != "" { | ||
| c.Set("user", &authn.UserClaims{RegisteredClaims: jwt.RegisteredClaims{Subject: subject}}) | ||
| } | ||
| return c, rec | ||
| } | ||
|
|
||
| func manifestForTest(t *testing.T) *authz.Manifest { | ||
| t.Helper() | ||
| m, err := authz.DefaultManifest() | ||
| require.NoError(t, err) | ||
| return m | ||
| } | ||
|
|
||
| func decodeResp(t *testing.T, rec *httptest.ResponseRecorder) permissionsResponse { | ||
| t.Helper() | ||
| var resp permissionsResponse | ||
| require.NoError(t, json.Unmarshal(rec.Body.Bytes(), &resp)) | ||
| return resp | ||
| } | ||
|
|
||
| // TestPermissionsAllowedSubset: a PDP that only allows "read" yields exactly the read | ||
| // actions per resource, in one batched call, with every resource present in the response. | ||
| func TestPermissionsAllowedSubset(t *testing.T) { | ||
| m := manifestForTest(t) | ||
| pdp := &stubPDP{allow: func(action string) bool { return action == "read" }} | ||
| h := NewPermissionsHandler(pdp, m, authz.FailClosed, nil) | ||
|
|
||
| c, rec := newPermissionsCtx(t, "alice@acme.com") | ||
| require.NoError(t, h.GetPermissions(c)) | ||
| assert.Equal(t, http.StatusOK, rec.Code) | ||
|
|
||
| resp := decodeResp(t, rec) | ||
| assert.Equal(t, "user", resp.Subject.Type) | ||
| assert.Equal(t, "alice@acme.com", resp.Subject.ID) | ||
|
|
||
| // Every manifest resource is present; only "read" survives where it's a declared action. | ||
| totalActions := 0 | ||
| for name, def := range m.Resources { | ||
| got, ok := resp.Permissions[name] | ||
| require.Truef(t, ok, "resource %q missing from response", name) | ||
| totalActions += len(def.Actions) | ||
| hasRead := false | ||
| for _, a := range def.Actions { | ||
| if a == "read" { | ||
| hasRead = true | ||
| } | ||
| } | ||
| if hasRead { | ||
| assert.Equalf(t, []string{"read"}, got, "resource %q allowed actions", name) | ||
| } else { | ||
| assert.Emptyf(t, got, "resource %q should have no allowed actions", name) | ||
| } | ||
| } | ||
| assert.Equal(t, totalActions, pdp.lastBatch, "should enumerate every resource×action in one batch") | ||
| } | ||
|
|
||
| func TestPermissionsFailClosed(t *testing.T) { | ||
| m := manifestForTest(t) | ||
| pdp := &stubPDP{err: fmt.Errorf("pdp gone: %w", authz.ErrUnavailable)} | ||
| h := NewPermissionsHandler(pdp, m, authz.FailClosed, nil) | ||
|
|
||
| c, rec := newPermissionsCtx(t, "alice@acme.com") | ||
| require.NoError(t, h.GetPermissions(c)) | ||
| assert.Equal(t, http.StatusOK, rec.Code) | ||
|
|
||
| resp := decodeResp(t, rec) | ||
| for name := range m.Resources { | ||
| assert.Emptyf(t, resp.Permissions[name], "fail-closed must deny %q", name) | ||
| } | ||
| } | ||
|
|
||
| func TestPermissionsFailOpen(t *testing.T) { | ||
| m := manifestForTest(t) | ||
| pdp := &stubPDP{err: fmt.Errorf("pdp gone: %w", authz.ErrUnavailable)} | ||
| h := NewPermissionsHandler(pdp, m, authz.FailOpen, nil) | ||
|
|
||
| c, rec := newPermissionsCtx(t, "alice@acme.com") | ||
| require.NoError(t, h.GetPermissions(c)) | ||
| assert.Equal(t, http.StatusOK, rec.Code) | ||
|
|
||
| resp := decodeResp(t, rec) | ||
| for name, def := range m.Resources { | ||
| assert.ElementsMatchf(t, def.Actions, resp.Permissions[name], | ||
| "fail-open must advertise the full vocabulary for %q", name) | ||
| } | ||
| } | ||
|
|
||
| // TestPermissionsInternalError: a non-unavailable PDP error is a 500, not a silent allow. | ||
| func TestPermissionsInternalError(t *testing.T) { | ||
| m := manifestForTest(t) | ||
| pdp := &stubPDP{err: fmt.Errorf("boom")} | ||
| h := NewPermissionsHandler(pdp, m, authz.FailClosed, nil) | ||
|
|
||
| c, _ := newPermissionsCtx(t, "alice@acme.com") | ||
| err := h.GetPermissions(c) | ||
| require.Error(t, err) | ||
| he, ok := err.(*echo.HTTPError) | ||
| require.True(t, ok, "want *echo.HTTPError") | ||
| assert.Equal(t, http.StatusInternalServerError, he.Code) | ||
| } | ||
|
|
||
| // TestPermissionsAnonymousSubject: no claims → anonymous subject, still answered. | ||
| func TestPermissionsAnonymousSubject(t *testing.T) { | ||
| m := manifestForTest(t) | ||
| pdp := &stubPDP{allow: func(string) bool { return false }} | ||
| h := NewPermissionsHandler(pdp, m, authz.FailClosed, nil) | ||
|
|
||
| c, rec := newPermissionsCtx(t, "") | ||
| require.NoError(t, h.GetPermissions(c)) | ||
| resp := decodeResp(t, rec) | ||
| assert.Equal(t, "anonymous", resp.Subject.Type) | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.