Documentation
¶
Overview ¶
Package require applies existing RBAC permissions to HTTP routes and non-HTTP callers. HTTP helpers return ordinary Gin groups whose child routes inherit the permission check. Install authentication and org-resolution middleware on the parent router before registering protected routes. Public and global route classification stays with the listener's middleware.
Index ¶
- Constants
- func Access(ctx *gin.Context) (*authz.AccessContext, error)
- func AppConfigInApp(ctx context.Context, db *gorm.DB, appID, appConfigID string) error
- func AppInOrg(db *gorm.DB) gin.HandlerFunc
- func CollectionScope(ctx *gin.Context, column clause.Column) func(*gorm.DB) *gorm.DB
- func ComponentInOrg(db *gorm.DB) gin.HandlerFunc
- func CredentialIdentityRoute(router gin.IRouter) *gin.RouterGroup
- func HumanAccountRoute(router gin.IRouter, action string) *gin.RouterGroup
- func IdentityRoute(router gin.IRouter) *gin.RouterGroup
- func InstallWorkflowInOrg(db *gorm.DB) gin.HandlerFunc
- func IsDeclared(ctx *gin.Context) bool
- func IsNativeDeclared(ctx *gin.Context) bool
- func MCPAccess(ctx context.Context) (*authz.AccessContext, error)
- func MCPIdentityTool[In, Out any](server *mcp.Server, tool *mcp.Tool, handler mcp.ToolHandlerFor[In, Out])
- func MCPMiddleware(next mcp.MethodHandler) mcp.MethodHandler
- func MCPTool[In, Out any](server *mcp.Server, tool *mcp.Tool, rule MCPRule[In], ...)
- func NativeRoute(router gin.IRouter, rules ...Rule) *gin.RouterGroup
- func NotFederatedToken(ctx context.Context, action string) error
- func NotFederatedTokenRoute(router gin.IRouter, action string) *gin.RouterGroup
- func Org(ctx context.Context) (string, error)
- func OrgInstallOrLogStreamRoute(router gin.IRouter, paramName string) *gin.RouterGroup
- func OrgOrInstallRoute(router gin.IRouter) *gin.RouterGroup
- func OrgRoute(router gin.IRouter) *gin.RouterGroup
- func PathOrgMatches() gin.HandlerFunc
- func PermissionDeniedError(acct *app.Account, orgID string, perm permissions.Permission, scope string) stderr.ErrAuthorization
- func Read(ctx context.Context) (string, error)
- func ResourceRoute(router gin.IRouter, kind permissions.ResourceKind, paramName string) *gin.RouterGroup
- func Route(router gin.IRouter, kind permissions.ResourceKind, verb permissions.Permission, ...) *gin.RouterGroup
- func RunnerInOrg(db *gorm.DB) gin.HandlerFunc
- func ScopeFromPath(fullPath string) string
- func VisibleMatch[T any](authority *authz.Authority, operation permissions.OperationID, candidates []T, ...) (T, error)
- func WorkflowInOrg(db *gorm.DB) gin.HandlerFunc
- func Write(ctx context.Context) (string, error)
- type ConditionalOperation
- type MCPRule
- type RequirementDescription
- type RouteDescription
- type RouteRegistry
- type Rule
- func All(resolve func(*gin.Context) ([]authz.Requirement, error), ...) Rule
- func AnyOrganization(operations ...permissions.OperationID) Rule
- func Collection(operation permissions.OperationID, ...) Rule
- func Organization(operation permissions.OperationID) Rule
- func ParentOrChild(parentOp permissions.OperationID, ...) Rule
- func Point(operation permissions.OperationID, ...) Rule
Constants ¶
const AcceptedPermissionsHeader = "X-Nuon-Accepted-Permissions"
const MCPAuthorizationMetadata = "nuon.co/authorization"
Variables ¶
This section is empty.
Functions ¶
func Access ¶
func Access(ctx *gin.Context) (*authz.AccessContext, error)
Access retrieves the targets authorized by the route's rules, verifying that they belong to the request's current authority snapshot.
func AppConfigInApp ¶ added in v0.19.1297
AppConfigInApp returns not found unless appConfigID is a config of appID in the selected org. Config create bodies carry app_config_id, which AppInOrg never sees. An empty appConfigID is allowed because several creates treat it as optional.
func AppInOrg ¶ added in v0.19.1273
func AppInOrg(db *gorm.DB) gin.HandlerFunc
AppInOrg rejects requests whose :app_id is not an app in the selected org. Org-level "all" makes permission object checks succeed for arbitrary app IDs under the header org, so route handlers must also prove ownership.
func CollectionScope ¶
CollectionScope returns a GORM scope that filters a handler's query to the resources authorized by its route's Collection rule. Use it with db.Scopes; column identifies the declared resource, such as apps.id or a child's app_id. Qualify the column when joining tables, and apply the scope to each query that produces rows, counts or aggregates so filtering precedes pagination. Execute the scoped query before returning success, even for empty results: dry-run subqueries do not satisfy the route's collection-consumption check. Missing collection authority or prebuilt Raw SQL adds an error to the query.
func ComponentInOrg ¶ added in v0.19.1273
func ComponentInOrg(db *gorm.DB) gin.HandlerFunc
ComponentInOrg rejects requests whose :component_id is not in the selected org.
func CredentialIdentityRoute ¶
func CredentialIdentityRoute(router gin.IRouter) *gin.RouterGroup
CredentialIdentityRoute declares account-self operations on listeners whose credentials select the org themselves, such as the runner API. Like IdentityRoute it needs only an authenticated account, not an org capability.
func HumanAccountRoute ¶
func HumanAccountRoute(router gin.IRouter, action string) *gin.RouterGroup
HumanAccountRoute returns a group that rejects service-account credentials, including workload credentials, before the handler runs. Use it for account-self routes that only people perform, such as onboarding a new org. action completes "service accounts cannot <action>" in the error message.
func IdentityRoute ¶
func IdentityRoute(router gin.IRouter) *gin.RouterGroup
IdentityRoute declares account-self operations that need authentication but no selected organization. The listener must also classify the route as global.
func InstallWorkflowInOrg ¶ added in v0.19.1273
func InstallWorkflowInOrg(db *gorm.DB) gin.HandlerFunc
InstallWorkflowInOrg rejects requests whose :install_workflow_id is not in the selected org.
func IsDeclared ¶ added in v0.19.1239
IsDeclared reports whether the matched route was registered through Route or OrgRoute. It is available before authentication and does not mean access was granted; the later permission guard must still run.
func IsNativeDeclared ¶
func MCPIdentityTool ¶
func MCPIdentityTool[In, Out any](server *mcp.Server, tool *mcp.Tool, handler mcp.ToolHandlerFor[In, Out])
MCPIdentityTool registers an account-self tool that needs no selected org.
func MCPMiddleware ¶
func MCPMiddleware(next mcp.MethodHandler) mcp.MethodHandler
MCPMiddleware rejects undeclared tools before their handlers run. Install it before registering tools; each native registration wraps it with its declaration.
func MCPTool ¶
func MCPTool[In, Out any](server *mcp.Server, tool *mcp.Tool, rule MCPRule[In], handler mcp.ToolHandlerFor[In, Out])
MCPTool resolves and checks canonical resources before invoking a typed tool. The resolver uses Authority.Require/RequireCollection, shared with HTTP domains.
func NativeRoute ¶
func NativeRoute(router gin.IRouter, rules ...Rule) *gin.RouterGroup
NativeRoute runs all rules after inherited authentication and org resolution. Native authority and its identity must be present on ctx.Request.Context(). Nested groups extend their parent's checked targets with their own rules.
func NotFederatedToken ¶ added in v0.19.1263
NotFederatedToken rejects the request if it was made with a federated (OIDC-exchanged) token. action completes "federated tokens cannot <action>" in the error message.
func NotFederatedTokenRoute ¶ added in v0.19.1263
func NotFederatedTokenRoute(router gin.IRouter, action string) *gin.RouterGroup
NotFederatedTokenRoute returns a group that rejects federated tokens before the handler runs, so the restriction is visible at route registration instead of buried in the handler body.
require.NotFederatedTokenRoute(orgs, "create organizations").POST("", s.CreateOrg)
func Org ¶ added in v0.19.1159
Org returns the org ID from context. Empty org means the caller did not pass X-Nuon-Org-ID. Use for non-Gin callers (MCP tool handlers). It does not check permissions; use Read or Write for authorization.
func OrgInstallOrLogStreamRoute ¶ added in v0.19.1289
func OrgInstallOrLogStreamRoute(router gin.IRouter, paramName string) *gin.RouterGroup
OrgInstallOrLogStreamRoute is OrgOrInstallRoute plus a grant on the log stream named by paramName. A log-stream account holds that grant and no org or install grant.
func OrgOrInstallRoute ¶ added in v0.19.1273
func OrgOrInstallRoute(router gin.IRouter) *gin.RouterGroup
OrgOrInstallRoute is like OrgRoute, but also allows accounts that only have install-scoped grants when runnerguard has set an install-scoped runner on the request (job SA path). Org-wide grants still pass. Denials stay 403.
func OrgRoute ¶ added in v0.19.1239
func OrgRoute(router gin.IRouter) *gin.RouterGroup
OrgRoute returns a group requiring permission on the selected org, inferred using permissions.FromRequest: GET/HEAD read, POST create, PUT/PATCH update, and DELETE delete. Unsupported methods fail closed at request time. Use Route with KindOrg and an explicit verb when the operation differs from this mapping.
org := require.OrgRoute(api)
org.GET("/v1/orgs/current", handler)
func PathOrgMatches ¶ added in v0.19.1273
func PathOrgMatches() gin.HandlerFunc
PathOrgMatches rejects requests whose :org_id path param does not match the selected org from the auth header. Handlers often load the header org and ignore the path, which lets callers probe arbitrary org IDs with a 200.
func PermissionDeniedError ¶ added in v0.19.1239
func PermissionDeniedError(acct *app.Account, orgID string, perm permissions.Permission, scope string) stderr.ErrAuthorization
PermissionDeniedError phrases a 403 in terms of the access level the request needs rather than the raw permission key, so the message reads sensibly from any action that triggered the check.
func ResourceRoute ¶ added in v0.19.1273
func ResourceRoute(router gin.IRouter, kind permissions.ResourceKind, paramName string) *gin.RouterGroup
func Route ¶
func Route(router gin.IRouter, kind permissions.ResourceKind, verb permissions.Permission, paramName string) *gin.RouterGroup
Route returns a group requiring verb on the resource named by paramName in the request path, within the selected org. For KindOrg it checks the org itself and ignores paramName. The explicit verb is authoritative, regardless of the HTTP method. Resource denials return 404 to avoid disclosing existence; org denials return 403.
require.Route(api, permissions.KindStack, permissions.PermissionRead, "install_id").
GET("/v1/stacks/:install_id/config", handler)
func RunnerInOrg ¶ added in v0.19.1273
func RunnerInOrg(db *gorm.DB) gin.HandlerFunc
RunnerInOrg rejects requests whose :runner_id is not in the selected org.
func ScopeFromPath ¶ added in v0.19.1239
ScopeFromPath derives the denied-error scope from the route, naming the resource the request operates on: /v1/service-accounts/:id becomes "service accounts in this organization".
func VisibleMatch ¶
func VisibleMatch[T any](authority *authz.Authority, operation permissions.OperationID, candidates []T, target func(T) permissions.Target) (T, error)
VisibleMatch picks the record an org-wide name refers to. Names are unique only within an app, so when several records match, the caller sees just those its authority can read with operation. A single candidate is returned as is and is checked by the route's own requirement. It returns gorm.ErrRecordNotFound when no candidate is visible and a user error when several visible records match.
func WorkflowInOrg ¶ added in v0.19.1273
func WorkflowInOrg(db *gorm.DB) gin.HandlerFunc
WorkflowInOrg rejects requests whose :workflow_id is not in the selected org.
Types ¶
type ConditionalOperation ¶
type ConditionalOperation struct {
Operation permissions.OperationID `json:"operation"`
When string `json:"when"`
}
ConditionalOperation documents when a resolver adds an operation. The resolver evaluates the condition; this text is a client hint, not executable policy.
type MCPRule ¶
type MCPRule[In any] struct { // contains filtered or unexported fields }
MCPRule keeps a typed resolver and its discovery metadata together, allowing domain helpers to share one declaration across several tools.
func MCPResolve ¶
func MCPResolve[In any](description RequirementDescription, resolve func(context.Context, In, *authz.Authority) (*authz.AccessContext, error)) MCPRule[In]
type RequirementDescription ¶
type RequirementDescription struct {
Kind string `json:"kind"`
Operations []permissions.OperationID `json:"operations,omitempty"`
Conditional []ConditionalOperation `json:"conditional,omitempty"`
}
RequirementDescription describes a route check, independently of caller grants. All entries on a route apply. any_organization admits one listed operation; other kinds require every listed operation. Conditional operations also apply when their stated request or resource condition holds. These hints describe admission, not sufficient authority for every handler effect.
func RouteRequirements ¶
func RouteRequirements(ctx *gin.Context) []RequirementDescription
RouteRequirements is available before authentication; it never contains target IDs or the caller's effective permissions. A nil result means undeclared.
type RouteDescription ¶
type RouteDescription struct {
Listener string `json:"listener"`
Method string `json:"method"`
Path string `json:"path"`
Requirements []RequirementDescription `json:"requirements,omitempty"`
}
RouteDescription records registered admission checks, not an effective-access decision. Routes without requirements need a listener-specific disposition.
func RegisteredRoutes ¶
func RegisteredRoutes(ctx *gin.Context) []RouteDescription
RegisteredRoutes exposes a copy of this listener's captured contract to docs.
type RouteRegistry ¶
type RouteRegistry struct {
// contains filtered or unexported fields
}
RouteRegistry captures Gin's actual route declarations before serving traffic. Its first root middleware stops in-process probes before authentication, resource resolvers, or handlers. HTTP input cannot activate a probe.
func NewRouteRegistry ¶
func NewRouteRegistry(router *gin.Engine, listener string) *RouteRegistry
func (*RouteRegistry) Capture ¶
func (r *RouteRegistry) Capture() error
Capture runs once after all services register, before concurrent requests.
type Rule ¶
type Rule struct {
// contains filtered or unexported fields
}
func All ¶
func All(resolve func(*gin.Context) ([]authz.Requirement, error), operations ...permissions.OperationID) Rule
All authorizes a non-empty set of operation/target pairs when every check passes. Operations describe a fixed set; omit them when the resolver chooses at runtime.
func AnyOrganization ¶
func AnyOrganization(operations ...permissions.OperationID) Rule
AnyOrganization admits one of several org capabilities. When the operation depends on a request's principal type, the handler must check that specific capability after resolving the principal.
func Collection ¶
func Collection(operation permissions.OperationID, resources func(*gin.Context) (*authz.Resources, error)) Rule
Collection declares the operation and domain-owned resource query for a list. A nested list also declares a Point or Organization rule for its parent.
func Organization ¶
func Organization(operation permissions.OperationID) Rule
Organization checks a capability against the selected org. Denials return 403; resource-level rules return 404 to avoid disclosing existence.
func ParentOrChild ¶
func ParentOrChild(parentOp permissions.OperationID, parent func(*gin.Context) (permissions.Target, error), childOp permissions.OperationID, children func(*gin.Context) (*authz.Resources, error), child func(*gin.Context, *authz.Selection) (permissions.Target, error), ) Rule
ParentOrChild is the parent rule for a nested list. It admits callers that can perform parentOp on the parent, and callers whose narrower grants reach at least one child, so they can list what they see. Everyone else gets 404, as for a point read of the parent. child returns the target of one child of the resolved parent that the selection admits, or gorm.ErrRecordNotFound.
func Point ¶
func Point(operation permissions.OperationID, resolve func(*gin.Context) (permissions.Target, error)) Rule
Point checks one canonical resource. The resolver must establish ownership and ancestry from trusted data.
func (Rule) Describe ¶
func (r Rule) Describe(description RequirementDescription) Rule
Describe supplies the request-dependent part of a resolver's admission contract.