authz

package
v0.7.5 Latest Latest
Warning

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

Go to latest
Published: May 26, 2026 License: Apache-2.0 Imports: 14 Imported by: 0

Documentation

Overview

Package authz provides a generic Kratos middleware for authorization. It is engine-agnostic: any Authorizer implementation can be injected.

Example usage:

import (
    pkgauthz "github.com/Servora-Kit/servora/security/authz"
    fgaengine "github.com/Servora-Kit/servora/security/authz/openfga"
)

mw = append(mw, pkgauthz.Server(
    fgaengine.NewAuthorizer(fgaClient),
    pkgauthz.WithRulesFunc(iamv1.AuthzRules),
    pkgauthz.WithSubjectFunc(mySubjectExtractor),
))

Package authz provides a Kratos middleware for engine-agnostic authorization.

Engine model

The Authorizer interface exposes a single Check method that accepts a CheckRequest (Subject, Action, ResourceType, ResourceID, Attributes). Any authorization backend — OpenFGA, SpiceDB, Cedar, OPA, or custom — can implement this interface.

Batch and list capabilities are available via optional sub-interfaces in the batch and lister sub-packages, which engines may implement as needed.

Subject resolution

The middleware does NOT assume how a subject string is derived from the request context. Callers provide a WithSubjectFunc option that extracts the subject from ctx. This decouples authz from any specific authn scheme.

Audit integration

When WithAuditOnDeny is configured with an audit.Auditor, the middleware emits CloudEvents events on authorization denial or error. This is purely opt-in; without the option, the middleware is silent.

Future: contextual tuples / attributes

The CheckRequest.Attributes field (map[string]any) is reserved for request-level facts that participate in a decision but are not persisted: device trust, active session, time-of-day, request region, etc. Engines that support ABAC or contextual tuples can read from this field.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func MergeRules

func MergeRules(ms ...map[string]AuthzRule) map[string]AuthzRule

MergeRules merges multiple AuthzRule maps into one new map. Later maps take precedence on key conflicts (which should not occur in practice). Useful when a server registers services from multiple generated packages.

func Server

func Server(authorizer Authorizer, opts ...Option) middleware.Middleware

Server returns a Kratos middleware that performs authorization checks.

Behavior:

  • No transport in context → passthrough (non-server calls).
  • No rule for operation → fail-closed (403 AUTHZ_NO_RULE).
  • No rule + WithFailOpenOnMissingRule set → alertFn invoked, handler called.
  • AUTHZ_MODE_NONE → skip (public endpoint).
  • AUTHZ_MODE_CHECK, no subject → 403 AUTHZ_DENIED.
  • AUTHZ_MODE_CHECK, nil authorizer → 503 AUTHZ_UNAVAILABLE.
  • AUTHZ_MODE_CHECK, authorizer returned (true, nil) → handler called.
  • AUTHZ_MODE_CHECK, authorizer returned (false, nil) → 403 AUTHZ_DENIED; if WithAuditOnDeny is set, emits CloudEvents event with severity WARN.
  • AUTHZ_MODE_CHECK, authorizer returned (_, err) → 503 AUTHZ_CHECK_FAILED; if WithAuditOnDeny is set, emits CloudEvents event with severity ERROR.

Types

type Authorizer

type Authorizer interface {
	// Check returns whether the request described by req is authorized.
	Check(ctx context.Context, req CheckRequest) (allowed bool, err error)
}

Authorizer is the single-method interface for authorization decisions. Implementations may target any backend (OpenFGA, SpiceDB, Cedar, OPA, etc.).

type AuthzRule

type AuthzRule struct {
	Mode         authzpb.AuthzMode
	Action       string
	ResourceType string
	// ResourceIDField is the proto field name (or dot-path) to extract resource
	// ID from the request. When empty, a default resource ID is used
	// (singleton/platform-level checks).
	ResourceIDField string
}

AuthzRule describes the authorization requirement for a single RPC operation.

type CheckRequest added in v0.4.0

type CheckRequest struct {
	Subject      string
	Action       string
	ResourceType string
	ResourceID   string
	Attributes   map[string]any
}

CheckRequest describes a single authorization check.

type Option

type Option func(*serverConfig)

Option configures the Server middleware.

func WithAuditOnDeny added in v0.5.0

func WithAuditOnDeny(auditor audit.Auditor) Option

WithAuditOnDeny configures the middleware to emit CloudEvents audit events when authorization is denied or encounters an error.

  • Check returns (false, nil): emit event type "servora.authz.v1.denied", severity "WARN".
  • Check returns (_, err): emit event type "servora.authz.v1.denied", severity "ERROR".
  • Not configured (auditor is nil): silent, no events emitted.

func WithCheckTimeout added in v0.4.0

func WithCheckTimeout(d time.Duration) Option

WithCheckTimeout bounds the time spent in Authorizer.Check on each request. Zero (default) disables the deadline — the upstream context applies.

This protects business-RPC latency from a slow authorization backend.

func WithDefaultResourceID added in v0.5.0

func WithDefaultResourceID(id string) Option

WithDefaultResourceID overrides the fallback resource ID used when ResourceIDField is empty. Defaults to "default".

func WithFailOpenOnMissingRule added in v0.4.0

func WithFailOpenOnMissingRule(alertFn func(ctx context.Context, operation string)) Option

WithFailOpenOnMissingRule changes the missing-rule policy from fail-closed (default — return AUTHZ_NO_RULE 403) to fail-open: the handler is called, and the alertFn callback is invoked so the gap is visible (oncall page, Slack, log warning, etc.).

Use during development or staged rollouts. NEVER use in production for security-sensitive services.

func WithRules

func WithRules(rules map[string]AuthzRule) Option

WithRules sets the operation→rule mapping directly.

func WithRulesFunc

func WithRulesFunc(fn func() map[string]AuthzRule) Option

WithRulesFunc sets the operation→rule mapping via a single function (e.g. generated AuthzRules()). The function is called once during middleware construction. To merge rules from multiple packages, prefer WithRulesFuncs.

func WithRulesFuncs

func WithRulesFuncs(fns ...func() map[string]AuthzRule) Option

WithRulesFuncs merges the rule maps returned by one or more generator functions (e.g. userpb.AuthzRules, authnpb.AuthzRules) into a single rule set. Later entries take precedence on key conflicts (which should not occur in practice). This is the preferred alternative to combining WithRules + MergeRules.

func WithSubjectFunc added in v0.5.0

func WithSubjectFunc(fn func(context.Context) (string, bool)) Option

WithSubjectFunc sets the function used to extract the subject string from the request context. The function should return the subject identifier and a boolean indicating whether the subject was found. When not set or when the function returns false, the middleware returns 403 AUTHZ_DENIED.

Directories

Path Synopsis
Package batch defines the optional BatchAuthorizer sub-interface for authorization backends that support multi-check in a single round-trip.
Package batch defines the optional BatchAuthorizer sub-interface for authorization backends that support multi-check in a single round-trip.
Package lister defines the optional Lister sub-interface for authorization backends that can enumerate resources a subject is allowed to access.
Package lister defines the optional Lister sub-interface for authorization backends that can enumerate resources a subject is allowed to access.
Package noop provides a no-op Authorizer that always permits all requests.
Package noop provides a no-op Authorizer that always permits all requests.
Package openfga provides an OpenFGA-based Authorizer implementation for security/authz.
Package openfga provides an OpenFGA-based Authorizer implementation for security/authz.

Jump to

Keyboard shortcuts

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