-
Notifications
You must be signed in to change notification settings - Fork 3
feat(authz): central authorization layer — PDP interface, manifest, builtin driver (BCH-1313) #426
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
Closed
Closed
Changes from all 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,88 +1,21 @@ | ||
| package middleware | ||
|
|
||
| import ( | ||
| "errors" | ||
| "net/http" | ||
| "strings" | ||
|
|
||
| "github.com/compliance-framework/api/internal/authn" | ||
| "github.com/compliance-framework/api/internal/authz" | ||
| "github.com/compliance-framework/api/internal/config" | ||
| "github.com/compliance-framework/api/internal/service/relational" | ||
| "github.com/compliance-framework/api/internal/service/sso" | ||
| "github.com/labstack/echo/v4" | ||
| "go.uber.org/zap" | ||
| "gorm.io/gorm" | ||
| ) | ||
|
|
||
| // RequireAdminGroups enforces that SSO-authenticated users belong to the provider's configured | ||
| // admin groups. Password-based logins bypass this middleware (treated as super admins). | ||
| // | ||
| // It is now a thin wrapper over the central authorization PEP: it builds an | ||
| // Authorizer for the configured driver and enforces the "admin" resource. The | ||
| // builtin driver reproduces this exact rule (see internal/authz). New routes | ||
| // should construct one Authorizer via NewAuthorizerFromConfig and call | ||
| // Authorize("admin", ...) directly rather than using this helper. | ||
| func RequireAdminGroups(db *gorm.DB, cfg *config.Config, logger *zap.SugaredLogger) echo.MiddlewareFunc { | ||
| return func(next echo.HandlerFunc) echo.HandlerFunc { | ||
| return func(c echo.Context) error { | ||
| claims, ok := c.Get("user").(*authn.UserClaims) | ||
| if !ok || claims == nil { | ||
| return echo.NewHTTPError(http.StatusUnauthorized, "missing authentication claims") | ||
| } | ||
|
|
||
| var user relational.User | ||
| if err := db.Where("email = ?", claims.Subject).First(&user).Error; err != nil { | ||
| if errors.Is(err, gorm.ErrRecordNotFound) { | ||
| return echo.NewHTTPError(http.StatusForbidden, "user not found") | ||
| } | ||
| logger.Errorw("Failed to load user for admin enforcement", "email", claims.Subject, "error", err) | ||
| return echo.NewHTTPError(http.StatusInternalServerError, "failed to load user") | ||
| } | ||
|
|
||
| if strings.ToLower(user.AuthMethod) != "sso" { | ||
| // Password (or other non-SSO) users bypass group enforcement. | ||
| return next(c) | ||
| } | ||
| if cfg == nil || cfg.SSO == nil || !cfg.SSO.Enabled { | ||
| // Without SSO config we cannot enforce provider-based admin groups; allow request. | ||
| return next(c) | ||
| } | ||
|
|
||
| var link relational.SSOUserLink | ||
| if err := db. | ||
| Where("user_id = ? AND deleted_at IS NULL", user.ID.String()). | ||
| Order("last_sync DESC"). | ||
| First(&link).Error; err != nil { | ||
| logger.Warnw("Missing SSO link for admin enforcement", "userID", user.ID.String(), "error", err) | ||
| return echo.NewHTTPError(http.StatusForbidden, "missing SSO link for user") | ||
| } | ||
|
|
||
| providerConfig := cfg.SSO.GetProvider(link.Provider) | ||
| if providerConfig == nil { | ||
| logger.Warnw("Provider config not found for admin enforcement", "provider", link.Provider) | ||
| // SSO IS enabled and this provider is unknown - we should fail. | ||
| return echo.NewHTTPError(http.StatusForbidden, "provider configuration not found") | ||
| } | ||
|
|
||
| if len(providerConfig.RequiredAdminGroups) == 0 { | ||
| return next(c) | ||
| } | ||
|
|
||
| groupSet := make(map[string]struct{}) | ||
| for _, g := range sso.DeserializeStringArray(link.Groups) { | ||
| normalized := strings.TrimSpace(strings.ToLower(g)) | ||
| if normalized != "" { | ||
| groupSet[normalized] = struct{}{} | ||
| } | ||
| } | ||
|
|
||
| for _, required := range providerConfig.RequiredAdminGroups { | ||
| normalized := strings.TrimSpace(strings.ToLower(required)) | ||
| if _, ok := groupSet[normalized]; !ok { | ||
| logger.Warnw("User missing required admin group", | ||
| "userID", user.ID.String(), | ||
| "requiredGroup", required, | ||
| "provider", link.Provider, | ||
| ) | ||
| return echo.NewHTTPError(http.StatusForbidden, "missing required admin groups") | ||
| } | ||
| } | ||
|
|
||
| return next(c) | ||
| } | ||
| } | ||
| return NewAuthorizerFromConfig(db, cfg, logger).Authorize(authz.ResourceAdmin, "manage") | ||
| } | ||
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,177 @@ | ||
| package middleware | ||
|
|
||
| import ( | ||
| "net/http" | ||
|
|
||
| "github.com/compliance-framework/api/internal/authn" | ||
| "github.com/compliance-framework/api/internal/authz" | ||
| "github.com/compliance-framework/api/internal/config" | ||
| "github.com/labstack/echo/v4" | ||
| "go.uber.org/zap" | ||
| "gorm.io/gorm" | ||
| ) | ||
|
|
||
| // Authorizer is CCF's Policy Enforcement Point (PEP). It builds an authz.Subject | ||
| // from the request's authenticated claims, asks the configured PDP for a | ||
| // decision, and enforces it. It supplies facts only and holds no policy logic. | ||
| // | ||
| // Enforcement outcomes: | ||
| // - allow -> the request proceeds; | ||
| // - explicit deny -> 403 (the PDP reason is logged, never echoed); | ||
| // - evaluator error, fail open -> the request proceeds; | ||
| // - evaluator error, fail closed-> 500 (an evaluator error is an internal | ||
| // failure; 403 is reserved for an explicit policy deny). | ||
| type Authorizer struct { | ||
| pdp authz.PDP | ||
| logger *zap.SugaredLogger | ||
| failMode authz.FailMode | ||
| } | ||
|
|
||
| // NewAuthorizer builds an Authorizer around an already-constructed PDP. | ||
| func NewAuthorizer(pdp authz.PDP, logger *zap.SugaredLogger, failMode authz.FailMode) *Authorizer { | ||
| if logger == nil { | ||
| logger = zap.NewNop().Sugar() | ||
| } | ||
| return &Authorizer{pdp: pdp, logger: logger, failMode: failMode} | ||
| } | ||
|
|
||
| // NewAuthorizerFromConfig constructs an Authorizer for the driver named in | ||
| // cfg.AuthZ (defaulting to the builtin engine, failing closed) using the | ||
| // embedded authorization manifest. A misconfigured driver or an unloadable | ||
| // manifest is fatal: the server must not start enforcing with the wrong engine. | ||
| func NewAuthorizerFromConfig(db *gorm.DB, cfg *config.Config, logger *zap.SugaredLogger) *Authorizer { | ||
| if logger == nil { | ||
| logger = zap.NewNop().Sugar() | ||
| } | ||
|
|
||
| driver := config.AuthZDriverBuiltin | ||
| failMode := authz.FailClosed | ||
| if cfg != nil && cfg.AuthZ != nil { | ||
| if cfg.AuthZ.Driver != "" { | ||
| driver = cfg.AuthZ.Driver | ||
| } | ||
| failMode = authz.ParseFailMode(cfg.AuthZ.FailMode) | ||
| } | ||
|
|
||
| manifest, err := authz.DefaultManifest() | ||
| if err != nil { | ||
| logger.Fatalw("authz: failed to load authorization manifest", "error", err) | ||
| } | ||
|
|
||
| pdp, err := authz.Open(driver, authz.Options{ | ||
| DB: db, | ||
| Config: cfg, | ||
| Logger: logger, | ||
| Manifest: manifest, | ||
| }) | ||
| if err != nil { | ||
| logger.Fatalw("authz: failed to initialize authorization driver", "driver", driver, "error", err) | ||
| } | ||
|
|
||
| logger.Debugw("authz: enforcement initialized", "driver", driver, "failMode", string(failMode)) | ||
| return NewAuthorizer(pdp, logger, failMode) | ||
| } | ||
|
|
||
| type authorizeOptions struct { | ||
| allowPublic bool | ||
| resourceIDParam string | ||
| } | ||
|
|
||
| // AuthorizeOption customizes a single Authorize middleware. | ||
| type AuthorizeOption func(*authorizeOptions) | ||
|
|
||
| // WithPublicAccess lets anonymous requests reach the PDP with the allow_public | ||
| // fact set, for routes that opt into public access (e.g. public agent ingest). | ||
| func WithPublicAccess(allow bool) AuthorizeOption { | ||
| return func(o *authorizeOptions) { o.allowPublic = allow } | ||
| } | ||
|
|
||
| // WithResourceIDParam names the route param holding the resource instance id | ||
| // (e.g. "id"); its value is passed to the PDP as Resource.ID. | ||
| func WithResourceIDParam(name string) AuthorizeOption { | ||
| return func(o *authorizeOptions) { o.resourceIDParam = name } | ||
| } | ||
|
|
||
| // Authorize returns middleware that enforces (resource, action) for the request | ||
| // through the configured PDP. It must run after an authentication middleware has | ||
| // populated the request context with user or agent claims. | ||
| func (a *Authorizer) Authorize(resource, action string, opts ...AuthorizeOption) echo.MiddlewareFunc { | ||
| var o authorizeOptions | ||
| for _, opt := range opts { | ||
| opt(&o) | ||
| } | ||
|
|
||
| return func(next echo.HandlerFunc) echo.HandlerFunc { | ||
| return func(c echo.Context) error { | ||
| if c.Request().Method == http.MethodOptions { | ||
| // CORS preflight is handled by the global CORS middleware; never | ||
| // gate it here. | ||
| return next(c) | ||
| } | ||
|
|
||
| subject := subjectFromContext(c) | ||
|
|
||
| res := authz.Resource{Type: resource} | ||
| if o.resourceIDParam != "" { | ||
| res.ID = c.Param(o.resourceIDParam) | ||
| } | ||
|
|
||
| reqCtx := map[string]any{ | ||
| "allow_public": o.allowPublic, | ||
| "method": c.Request().Method, | ||
| } | ||
|
|
||
| if a.pdp == nil { | ||
| a.logger.Errorw("authz: no PDP configured; denying", "resource", resource, "action", action) | ||
| return echo.NewHTTPError(http.StatusForbidden, "forbidden") | ||
| } | ||
|
|
||
| decision, err := a.pdp.Evaluate(c.Request().Context(), subject, action, res, reqCtx) | ||
| if err != nil { | ||
| a.logger.Errorw("authz: evaluation error", | ||
| "resource", resource, "action", action, "subjectType", subject.Type, "error", err) | ||
| if a.failMode == authz.FailOpen { | ||
| return next(c) | ||
| } | ||
| return echo.NewHTTPError(http.StatusInternalServerError, "authorization check failed") | ||
| } | ||
|
|
||
| if !decision.Allow { | ||
| a.logger.Warnw("authz: request denied", | ||
| "resource", resource, "action", action, | ||
| "subjectType", subject.Type, "subjectID", subject.ID, | ||
| "reason", decision.Reason) | ||
| return echo.NewHTTPError(http.StatusForbidden, "forbidden") | ||
| } | ||
|
|
||
| return next(c) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // subjectFromContext builds an authz.Subject from the authenticated claims an | ||
| // upstream authn middleware stored in the request context, or an anonymous | ||
| // subject when none are present. | ||
| func subjectFromContext(c echo.Context) authz.Subject { | ||
| if claims, ok := c.Get("user").(*authn.UserClaims); ok && claims != nil { | ||
| return authz.Subject{ | ||
| Type: authz.SubjectUser, | ||
| ID: claims.Subject, | ||
| Props: map[string]any{ | ||
| "email": claims.Subject, | ||
| }, | ||
| } | ||
| } | ||
| if claims, ok := c.Get("agent_claims").(*authn.AgentClaims); ok && claims != nil { | ||
| return authz.Subject{ | ||
| Type: authz.SubjectAgent, | ||
| ID: claims.Subject, | ||
| Props: map[string]any{ | ||
| "service_account": claims.Subject, | ||
| "agent_id": claims.AgentID, | ||
| "auth_method": claims.AuthMethod, | ||
| }, | ||
| } | ||
| } | ||
| return authz.Subject{Type: authz.SubjectAnonymous} | ||
| } |
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.