policy

package
v2.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 17, 2026 License: Apache-2.0 Imports: 37 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const QuickIDParam = "quick_id"

QuickIDParam matches routes/metric.go

Variables

View Source
var (
	ErrNotFound              = errors.New("not found")
	ErrSystemPolicyImmutable = errors.New("cannot modify system policy")
	ErrSystemFlagNotAllowed  = errors.New("system flag is not allowed on custom policies")
)
View Source
var (
	ErrUserDisabled  = errors.New("user is disabled")
	ErrUserNotFound  = errors.New("user not found")
	ErrTokenExpired  = errors.New("service account expired")
	ErrTokenNotFound = errors.New("service account not found")
	ErrAccessDenied  = errors.New("access denied")
)

Functions

func BuiltInPolicies

func BuiltInPolicies() []policyTY.Policy

BuiltInPolicies returns system policies that should always exist.

func BusinessName

func BusinessName(kind string, item interface{}) string

BusinessName returns the policy resource name for an entity (not storage UUID when a path exists).

func FormatResource

func FormatResource(kind, name string) string

FormatResource builds "kind" or "kind:name".

func IsBuiltInPolicyID

func IsBuiltInPolicyID(id string) bool

IsBuiltInPolicyID reports whether id is a code-owned system policy.

func ItemAllowedForList

func ItemAllowedForList(kind string, patterns []string, item interface{}) bool

ItemAllowedForList reports whether one item's business name matches list patterns. Patterns may include "!" deny exclusions from ResourceNamesForList.

func MatchAction

func MatchAction(pattern, action string) bool

MatchAction returns true if pattern matches action. "*" matches any action; otherwise an exact match, ignoring case and surrounding space so a hand written or UI supplied "Get" behaves like "get". Actions are a closed vocabulary, so folding case cannot widen access to a different verb.

Resource *names* stay case sensitive: they are entity ids, compared exactly by storage, and folding them could merge two distinct entities.

func MatchResource

func MatchResource(pattern, resource string) bool

MatchResource returns true if pattern matches resource (same kind only). Resource format: "kind", "kind:name", or "*". For device-tree parent→child cascade (Allow or Deny), use the Cascade helpers.

func MatchResourceAllowCascade

func MatchResourceAllowCascade(pattern, resource string) bool

MatchResourceAllowCascade matches an Allow pattern against a resource. Device-tree parent allows grant children under the same path:

Allow node:gw.n     → field:gw.n.s.f, source:gw.n.s, metric:gw.n…
Allow gateway:gw    → node/source/field/metric under gw
Allow node:gw.*     → all sources/fields under that gateway

Named parent Allow also permits the child list API (filters scope rows). Kind-wide Allow on an ancestor (node / node:*) grants all of the child kind.

func MatchResourceDenyCascade

func MatchResourceDenyCascade(pattern, resource string) bool

MatchResourceDenyCascade matches a Deny pattern against a resource. Device-tree parent denies block children under the same path (same hierarchy as Allow). Named Deny does not block the kind-only collection resource (list entry check); list rows are filtered separately.

func ResourceFromQuickID

func ResourceFromQuickID(quickID string) (string, error)

ResourceFromQuickID maps a quick id (e.g. field:gw.n.s.f) to a policy resource string.

Types

type API

type API struct {
	// contains filtered or unexported fields
}

func New

func New(ctx context.Context, logger *zap.Logger, storage storageTY.Plugin) *API

func (*API) Allowed

func (a *API) Allowed(subject Subject, action, resource string) error

Allowed reports whether the subject may perform action on resource. resource should be FormatResource(kind, name) e.g. "field:gw.n.s.f" or "gateway" for list-all.

Rules:

  1. User must exist and not be disabled
  2. If service account: must exist, not expired, belong to user
  3. User policies must allow (ceiling)
  4. If token has restrictions, they must also allow (can only lower)

func (*API) AllowedKindWide

func (a *API) AllowedKindWide(subject Subject, action, kind string) error

AllowedKindWide reports whether the subject may perform action on *any* object of kind, i.e. it holds a kind-wide grant ("*", "kind" or "kind:*"), not merely a grant on some named object.

Needed for writes whose target cannot be named in advance - creating an object with a server generated id. Without this, "Allow update on user:self" would be enough to create new users, because a kind-only resource check is deliberately permissive (it answers "may you reach this collection endpoint?").

func (*API) AllowedMetricPath

func (a *API) AllowedMetricPath(subject Subject, fieldPath string) error

AllowedMetricPath checks get on metric:<fieldPath> (hierarchical match).

func (*API) AssignAdminToUsersWithoutPolicies

func (a *API) AssignAdminToUsersWithoutPolicies() error

AssignAdminToUsersWithoutPolicies grants the admin policy to users that have none. Only for the pre-RBAC migration, where every existing user was effectively an admin.

func (*API) AuthorizeActionRequest

func (a *API) AuthorizeActionRequest(subject Subject, r *http.Request) error

AuthorizeActionRequest enforces access for the /api/action* endpoints.

These endpoints take their targets from the query string or the request body, so a bare "action" resource in a policy must not be enough - every target is checked individually (like quickid), otherwise /api/action becomes a write channel into every field/node in the system.

GET  /api/action/node?id=<uuid>&id=<uuid>   -> action on node:<gatewayId.nodeId> for each id
GET  /api/action/gateway?id=<id>            -> action on gateway:<id> for each id
GET  /api/action?resource=<quickId>         -> action on the quick id target
POST /api/action  [{resource: <quickId>}]   -> action on every quick id in the body

Any denied target fails the whole request.

func (*API) AuthorizeBodyTargets

func (a *API) AuthorizeBodyTargets(subject Subject, r *http.Request, access *RequestAccess) error

AuthorizeBodyTargets authorizes the objects named in a write payload.

The path-based check in the middleware can only see the kind for collection endpoints - POST /api/gateway, POST /api/gateway/enable and DELETE /api/gateway all carry their targets in the body. A kind-only check is deliberately permissive (it answers "may you reach this endpoint?"), so without this second pass a grant on one named object would authorize writes to every object of that kind.

Two payload shapes cover the whole api:

{"id": "gw1", ...}        one entity  -> check kind:gw1
["gw1", "gw2"]            bulk ids    -> check kind:gw1 and kind:gw2

A payload that names no target (create with a server generated id) requires a kind-wide grant instead. Anything else falls back to the kind-level decision already made by the caller.

The body is restored so the handler can read it.

func (*API) AuthorizeMetricRequest

func (a *API) AuthorizeMetricRequest(subject Subject, r *http.Request) error

AuthorizeMetricRequest enforces metric access for GET (quick_id) or POST (body queries). Resource patterns use kind "metric" with the same hierarchical names as fields:

metric:*                          all metrics
metric:home-gw.*                  all fields under gateway
metric:home-gw.living-room.*      all under node
metric:home-gw.n.s.*              all under source
metric:home-gw.n.s.temperature    one field

Built-in policies that list bare "metric" still allow all (kind-only match).

func (*API) AuthorizeQuickIDRequest

func (a *API) AuthorizeQuickIDRequest(subject Subject, r *http.Request) error

AuthorizeQuickIDRequest enforces access for GET /api/quickid?id=... Bare "quickid" in a policy only opens the API; each requested id is checked against the underlying resource (field:/node:/…), including device-tree cascade. Any denied id fails the whole request (403).

func (*API) AuthorizeSleepingQueueRequest

func (a *API) AuthorizeSleepingQueueRequest(subject Subject, r *http.Request) error

AuthorizeSleepingQueueRequest checks the gateway/node named in the query. A kind-level grant on "gateway" must not be enough to read or clear another gateway's queue.

func (*API) Cache

func (a *API) Cache() *Cache

Cache exposes the in-memory cache for invalidation from other packages.

func (*API) Delete

func (a *API) Delete(IDs []string) (int64, error)

Delete removes policies. System policies are protected, and so are policies still attached to a user - detaching them silently would leave that user with an unresolvable policy id, and a user whose list becomes empty loses all access.

func (*API) EnsureBuiltInPolicies

func (a *API) EnsureBuiltInPolicies() error

EnsureBuiltInPolicies creates system policies if missing and warms cache. Built-in statements are reset on every start: they are code, not user data.

func (*API) EnsureServiceAccountActive

func (a *API) EnsureServiceAccountActive(userID, tokenID string) error

EnsureServiceAccountActive validates service account still valid for requests.

func (*API) EnsureUserActive

func (a *API) EnsureUserActive(userID string) (*userTY.User, error)

EnsureUserActive loads user from cache and verifies not disabled (for auth middleware).

func (*API) GetByID

func (a *API) GetByID(id string) (policyTY.Policy, error)

func (*API) GetEntityInterface

func (a *API) GetEntityInterface() interface{}

func (*API) Import

func (a *API) Import(data interface{}) error

func (*API) List

func (a *API) List(filters []storageTY.Filter, pagination *storageTY.Pagination) (*storageTY.Result, error)

func (*API) NotifyTokenDeleted

func (a *API) NotifyTokenDeleted(entityID, tokenID string)

NotifyTokenDeleted invalidates token cache.

func (*API) NotifyTokenUpdated

func (a *API) NotifyTokenUpdated(token *svcAccountTY.ServiceAccount)

NotifyTokenUpdated refreshes token cache.

func (*API) NotifyUserDeleted

func (a *API) NotifyUserDeleted(id string)

NotifyUserDeleted removes user from cache.

func (*API) NotifyUserUpdated

func (a *API) NotifyUserUpdated(user *userTY.User)

NotifyUserUpdated refreshes user cache after user write.

func (*API) ReportUsersWithoutPolicies

func (a *API) ReportUsersWithoutPolicies() error

ReportUsersWithoutPolicies logs users that cannot access anything and warms the user cache. It deliberately does not grant anything: an empty policy list means "no access", and silently promoting such a user to admin on every restart would undo an administrator's decision. Pre-RBAC installs are handled once by the 2.2.0-1 upgrade (see AssignAdminToUsersWithoutPolicies).

func (*API) ResolveBusinessName

func (a *API) ResolveBusinessName(kind, storageID string) (string, error)

ResolveBusinessName loads the entity by storage id and returns the policy resource name.

func (*API) ResolveResource

func (a *API) ResolveResource(access *RequestAccess)

ResolveResource rewrites access.Resource when path id is a storage UUID (or id) so policy match uses business names (e.g. gatewayId.nodeId) instead of UUID.

func (*API) ResourceNamesForList

func (a *API) ResourceNamesForList(subject Subject, kind string) (unrestricted bool, patterns []string, err error)

ResourceNamesForList returns whether list is unrestricted for this kind, and optional name patterns from user policies (intersected with token resources). Used for filtered list queries. unrestricted=true means no name filter needed.

func (*API) Save

func (a *API) Save(policy *policyTY.Policy) error

Save persists a user authored policy.

System policies are code: their statements are rewritten on every start, so accepting edits here would silently discard them. The System flag itself is never taken from the request - a client cannot mark a custom policy undeletable or create a policy with a built-in id.

func (*API) StorageFiltersForList

func (a *API) StorageFiltersForList(subject Subject, kind string) (unrestricted bool, filters []storageTY.Filter, err error)

StorageFiltersForList builds storage filters that enforce list resource patterns at query time (AND-ed with client filters). unrestricted means no extra filters. Patterns prefixed with "!" are Deny exclusions; others are Allow includes. Final query: (allow1 OR allow2 OR ...) AND (not deny1) AND (not deny2) ...

func (*API) ValidatePoliciesExist

func (a *API) ValidatePoliciesExist(ids []string) error

ValidatePoliciesExist ensures all policy ids exist.

type Cache

type Cache struct {
	// contains filtered or unexported fields
}

Cache holds users, policies, and service accounts in memory for fast auth checks. Call Invalidate* after any write so the next request reloads from storage.

func (*Cache) GetPolicy

func (c *Cache) GetPolicy(id string) (*policyTY.Policy, error)

GetPolicy returns a cached policy or loads it.

func (*Cache) GetToken

func (c *Cache) GetToken(tokenID string) (*svcAccountTY.ServiceAccount, error)

GetToken returns a cached service account by raw token id (Token.ID), or loads it.

func (*Cache) GetUser

func (c *Cache) GetUser(id string) (*userTY.User, error)

GetUser returns a cached copy or loads from storage.

func (*Cache) InvalidatePolicy

func (c *Cache) InvalidatePolicy(id string)

InvalidatePolicy drops a policy from cache.

func (*Cache) InvalidateToken

func (c *Cache) InvalidateToken(tokenID string)

InvalidateToken drops a service account from cache by Token.ID.

func (*Cache) InvalidateTokenByEntityID

func (c *Cache) InvalidateTokenByEntityID(entityID string)

InvalidateTokenByEntityID removes any cached token matching entity id.

func (*Cache) InvalidateUser

func (c *Cache) InvalidateUser(id string)

InvalidateUser drops a user from cache (call on delete).

func (*Cache) PutPolicy

func (c *Cache) PutPolicy(p *policyTY.Policy)

PutPolicy updates the cache after a write.

func (*Cache) PutToken

func (c *Cache) PutToken(t *svcAccountTY.ServiceAccount)

PutToken updates the cache after a write (keyed by Token.ID).

func (*Cache) PutUser

func (c *Cache) PutUser(u *userTY.User)

PutUser updates the cache after a write.

func (*Cache) WarmPolicies

func (c *Cache) WarmPolicies() error

WarmPolicies loads all policies into cache (startup).

type RequestAccess

type RequestAccess struct {
	Action   string
	Resource string // kind or kind:name
	Kind     string
	Name     string // path id or empty (may be UUID - fine for coarse check; handlers may re-check)
	Skip     bool   // if true, authorization middleware skips (auth routes already public)
}

RequestAccess maps an HTTP request to action + resource for authorization. name is empty for collection list/create; filled for path id when available.

func MapRequest

func MapRequest(r *http.Request) RequestAccess

MapRequest converts HTTP method + path to RBAC action/resource.

type Subject

type Subject struct {
	UserID           string
	ServiceAccountID string // raw Token.ID from JWT; empty for interactive login
}

Subject is the authenticated principal for an access check.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL