policy Package

Overview

Package policy provides policy-based authorization and access control for the incident management platform.

This package implements a comprehensive authorization system using Open Policy Agent (OPA) for policy evaluation, decision caching, and audit logging. It supports fine-grained access control with role-based (RBAC) and attribute-based (ABAC) authorization patterns.

Key Features:

  • Policy-based authorization using OPA (Open Policy Agent)
  • Role-based access control (RBAC) with predefined roles
  • Attribute-based access control (ABAC) with custom attributes
  • Field-level data redaction based on data classification
  • Policy decision caching for performance
  • Comprehensive audit logging of all authorization decisions
  • Hot-reloadable policy bundles for runtime policy updates
  • Multi-tenant isolation through group-based policies

Architecture:

The policy system follows a distributed authorization model:

┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Policy Engine   │◄──►│ OPA SDK         │◄──►│ Policy Bundle   │
│ (Orchestration) │    │ (Evaluation)     │    │ (Rules & Data)  │
└─────────────────┘    └──────────────────┘    └─────────────────┘
                                                      
┌─────────────────┐    ┌──────────────────┐    ┌─────────────────┐
│ Decision Cache  │    │ Audit Logger     │    │ Data Redactor   │
│ (Performance)   │    │ (Compliance)     │    │ (Privacy)       │
└─────────────────┘    └──────────────────┘    └─────────────────┘

Example usage:

// Create policy engine
engine, err := policy.NewEngine(db, &policy.Config{
	CacheTTL:     5 * time.Minute,
	PolicyBundle: policyRego,
})
if err != nil {
	log.Fatal(err)
}

// Evaluate authorization request
input := &policy.Input{
	Principal: policy.Principal{
		ID:   userID,
		Role: "incident_commander",
	},
	Resource: policy.Resource{
		Type: "incident",
		ID:   "INC-12345",
	},
	Context: policy.Context{
		Action: "write",
	},
}

decision, err := engine.EvaluateWithLogging(ctx, input)
if err != nil {
	return err
}

if !decision.Allow {
	return fmt.Errorf("access denied: %s", strings.Join(decision.Reasons, ", "))
}

Supported Roles:

  • admin: Full system access including policy management
  • incident_commander: Incident management and escalation control
  • viewer: Read access to non-sensitive incident data
  • readonly: Limited read access with automatic redaction

Data Classifications:

  • public: No restrictions, available to all authenticated users
  • internal: Company-internal data, restricted by role
  • confidential: Sensitive business data, admin and IC access only
  • pii: Personally identifiable information, requires consent
  • phi: Protected health information, HIPAA compliance required
  • legal_hold: Data under litigation hold, restricted access

Import Path: github.com/systmms/incidents/internal/policy

Constants

defaultMainPolicy (and others)

Default policy constants

const defaultMainPolicy const defaultRBACPolicy

ActionRead (and others)

Actions constants define the standard operations that can be performed on resources.

These action constants provide consistent naming across the authorization system and enable policy authors to write comprehensive rules covering all operations.

const ActionRead const ActionWrite const ActionDelete const ActionList const ActionAck const ActionExport const ActionAdmin

ResourceTypeIncident (and others)

Resource types define the categories of resources in the incident management system.

These constants ensure consistent resource type identification across the authorization system and help policy authors target specific resource categories.

const ResourceTypeIncident const ResourceTypeTimeline const ResourceTypeNote const ResourceTypeArtifact const ResourceTypeUser const ResourceTypePolicy const ResourceTypeAuditLog

Types

BundleAwareEngine

BundleAwareEngine extends the base engine with bundle management

{<nil> 375 type 0 [0x14000232680] 0}

Methods

NewBundleAwareEngine

NewBundleAwareEngine creates a new bundle-aware policy engine

{<nil> <nil> NewBundleAwareEngine 0x1400024ff60 <nil>}

BundleLoader

BundleLoader provides convenient methods for loading bundles

{<nil> 6012 type 0 [0x14000252c80] 0}

Methods

NewBundleLoader

NewBundleLoader creates a new bundle loader

{<nil> <nil> NewBundleLoader 0x140002611c0 <nil>}

Config

Config holds engine configuration parameters for policy evaluation and caching.

The configuration allows customization of policy bundle loading, cache behavior, and OPA evaluation paths for different deployment scenarios.

{<nil> 15649 type 0 [0x14000289180] 0}

Methods

DefaultConfig

DefaultConfig returns default engine configuration suitable for most deployments.

The default configuration provides:

  • 5-minute decision cache TTL for reasonable performance vs. policy freshness
  • Structured decision path for rich policy responses with metadata
  • No custom policy bundle (uses built-in default RBAC policy)
{<nil> <nil> DefaultConfig 0x1400028c2e0 <nil>}

Context

Context represents the circumstances of an authorization request.

The Context captures the operational environment and request details that influence policy decisions. This includes the action being performed, environmental factors, and request metadata for comprehensive evaluation.

{<nil> 50937 type 0 [0x14000247e80] 0}

ContextKey

ContextKey for storing values in context

{<nil> 38813 type 0 [0x140003d29c0] 0}

Constants

const ContextKeyDecision const ContextKeyPrincipal

DataClass

DataClass represents sensitivity levels

{<nil> 54579 type 0 [0x14000272cc0] 0}

Constants

const DataClassPublic const DataClassInternal const DataClassConfidential const DataClassPII const DataClassPHI const DataClassLegalHold

DatabaseLogger

DatabaseLogger implements the Logger interface using a database

{<nil> 30296 type 0 [0x14000389f40] 0}

Methods

NewDatabaseLogger

NewDatabaseLogger creates a new database logger

{<nil> <nil> NewDatabaseLogger 0x1400037e760 <nil>}

Decision

Decision represents a comprehensive policy evaluation result.

The Decision structure contains not only the allow/deny result but also rich metadata about why the decision was made, what data should be redacted, and any additional context from the policy evaluation.

This structured approach enables fine-grained access control with detailed audit trails and supports complex scenarios like partial access with redaction.

{<nil> 47644 type 0 [0x14000247700] 0}

Methods

GetDecision

GetDecision retrieves the policy decision from context

{<nil> <nil> GetDecision 0x14000486140 <nil>}
parseDecisionFromRegoResults

parseDecisionFromRegoResults parses OPA rego results into a Decision

{<nil> <nil> parseDecisionFromRegoResults 0x140002847e0 <nil>}

DecisionLog

DecisionLog represents an audit log entry for a policy decision

{<nil> 52641 type 0 [0x14000272440] 0}

DecisionLogFilter

DecisionLogFilter for querying decision logs

{<nil> 56654 type 0 [0x14000273640] 0}

EnforcementPoint

EnforcementPoint represents a manual policy enforcement point

{<nil> 46282 type 0 [0x14000246bc0] 0}

Methods

NewEnforcementPoint

NewEnforcementPoint creates a new enforcement point

{<nil> <nil> NewEnforcementPoint 0x140004adda0 <nil>}

Engine

Engine implements the policy evaluation engine using Open Policy Agent (OPA).

The Engine orchestrates policy evaluation, decision caching, audit logging, and policy bundle management. It provides thread-safe operations and maintains a local cache to optimize performance for repeated authorization checks.

The engine uses OPA SDK for policy evaluation, which supports the Rego policy language and provides extensive features for complex authorization scenarios.

{<nil> 13540 type 0 [0x14000288640] 0}

Methods

NewEngine

NewEngine creates a new policy engine with the specified database and configuration.

This constructor initializes the OPA SDK, sets up decision caching, and loads the initial policy bundle. If no configuration is provided, default settings are used including a 5-minute cache TTL and a basic RBAC policy.

The engine requires a database connection for audit logging and policy bundle metadata storage. If database is nil, audit logging will be disabled but policy evaluation will still function.

Returns an error if OPA initialization fails or the policy bundle cannot be loaded.

{<nil> <nil> NewEngine 0x140002858e0 <nil>}

Evaluator

Evaluator interface defines the contract for policy evaluation engines.

This interface abstracts the policy evaluation mechanism, allowing different implementations (OPA, custom engines, etc.) to be used interchangeably while maintaining consistent behavior for authorization checks.

{<nil> 55182 type 0 [0x14000272e80] 0}

Input

Input represents the complete input for policy evaluation.

The Input structure combines the Principal (who), Resource (what), and Context (how/when) to provide all necessary information for comprehensive authorization decisions. This follows the standard ABAC (Attribute-Based Access Control) pattern.

{<nil> 52283 type 0 [0x14000272300] 0}

Logger

Logger interface defines the contract for policy decision audit logging.

This interface abstracts the audit logging mechanism, allowing different storage backends (database, external systems, etc.) to be used while maintaining consistent audit trail functionality.

{<nil> 56182 type 0 [0x14000273380] 0}

Middleware

Middleware implements HTTP middleware for policy enforcement

{<nil> 39111 type 0 [0x140003d2ac0] 0}

Methods

NewMiddleware

NewMiddleware creates a new policy enforcement middleware

{<nil> <nil> NewMiddleware 0x140003bac60 <nil>}

MiddlewareConfig

MiddlewareConfig holds middleware configuration

{<nil> 39240 type 0 [0x140003d2ec0] 0}

Methods

DefaultMiddlewareConfig

DefaultMiddlewareConfig returns default middleware configuration

{<nil> <nil> DefaultMiddlewareConfig 0x140003bb060 <nil>}

PolicyBundle

PolicyBundle represents metadata about a loaded policy bundle

{<nil> 53789 type 0 [0x14000272980] 0}

PolicyEvaluator

PolicyEvaluator implements the Evaluator interface

{<nil> 27320 type 0 [0x14000355140] 0}

Methods

NewPolicyEvaluator

NewPolicyEvaluator creates a new policy evaluator

{<nil> <nil> NewPolicyEvaluator 0x14000351640 <nil>}

Principal

Principal represents the subject making an authorization request.

The Principal contains identity information and attributes about the entity (user, service account, or API key) requesting access to resources. This supports both human users and machine identities with flexible attribute systems for complex authorization scenarios.

{<nil> 48721 type 0 [0x14000247980] 0}

Methods

ExtractPrincipalFromRequest

ExtractPrincipalFromRequest extracts a Principal from HTTP request This assumes the auth middleware has already validated the JWT and stored user info

{<nil> <nil> ExtractPrincipalFromRequest 0x140003ab6e0 <nil>}
GetPrincipal

GetPrincipal retrieves the principal from context

{<nil> <nil> GetPrincipal 0x140004863a0 <nil>}
MustGetPrincipal

MustGetPrincipal retrieves the principal from context or panics

{<nil> <nil> MustGetPrincipal 0x14000486620 <nil>}
PrincipalFromUser

PrincipalFromUser converts an auth.User to a policy Principal

{<nil> <nil> PrincipalFromUser 0x140003aa4e0 <nil>}
defaultExtractPrincipal
{<nil> <nil> defaultExtractPrincipal 0x14000454360 <nil>}

RedactionMode

RedactionMode defines how to redact sensitive data

{<nil> 54185 type 0 [0x14000272bc0] 0}

Constants

const RedactionModeDrop const RedactionModeMask const RedactionModeHash const RedactionModeRange

Resource

Resource represents the resource being accessed in an authorization request.

The Resource structure describes what is being accessed, including its type, identity, and metadata. This supports fine-grained access control based on resource attributes and data classification levels.

{<nil> 49843 type 0 [0x14000247cc0] 0}

Methods

ExtractResourceFromRequest

ExtractResourceFromRequest extracts Resource information from HTTP request

{<nil> <nil> ExtractResourceFromRequest 0x140003b0920 <nil>}
defaultExtractResource
{<nil> <nil> defaultExtractResource 0x14000455260 <nil>}

cacheEntry

cacheEntry represents a cached policy decision with expiration timestamp.

{<nil> 14193 type 0 [0x140002889c0] 0}

redactionResponseWriter

redactionResponseWriter implements response redaction

{<nil> 44405 type 0 [0x1400021a040] 0}

Functions

ApplyRedaction

ApplyRedaction applies field redaction to a response based on policy decision

{<nil> <nil> ApplyRedaction 0x140003b6aa0 <nil>}

contains

{<nil> <nil> contains 0x140003b10c0 <nil>}

defaultOnDeny

{<nil> <nil> defaultOnDeny 0x140004557c0 <nil>}

extractIDFromPath

{<nil> <nil> extractIDFromPath 0x140003b6160 <nil>}

findSubstring

{<nil> <nil> findSubstring 0x140003b15e0 <nil>}

getClientIP

getClientIP extracts the client IP from the request

{<nil> <nil> getClientIP 0x1400047be60 <nil>}

redactJSON

redactJSON recursively redacts fields in JSON data

{<nil> <nil> redactJSON 0x140003b7460 <nil>}

Generated automatically from Go source code. Last updated: 2025-08-25T07:51:05-04:00