contexa-iam

Policy Management

PAP (Policy Administration Point) services for policy lifecycle management: CRUD operations, automatic role-based synchronization, Policy Center authoring flows, policy versioning, AI-assisted drafting, and business rule translation.

PolicyService

The primary service for policy CRUD, search, approval, validation, simulation, impact analysis, and version rollback. The Policy Center controller uses this service as the main orchestration entry point.

Java
public interface PolicyService {
    List<Policy> getAllPolicies();
    Page<Policy> searchPolicies(String keyword, Pageable pageable);
    Page<Policy> searchPolicies(String keyword,
                                Policy.ApprovalStatus approvalStatus,
                                Boolean activeFilter,
                                Pageable pageable);
    Policy findById(Long id);
    Policy createPolicy(PolicyDto policyDto);
    void updatePolicy(PolicyDto policyDto);
    void deletePolicy(Long id);
    void deletePolicy(Long id, String changeReason);
    void synchronizePolicyForPermission(Permission permission);
    void approvePolicy(Long id, String approver);
    void rejectPolicy(Long id, String rejector);
    List<PolicyConflictDto> detectConflicts(PolicyDto policyDto);
    PolicyValidationReport validateBeforeCreate(PolicyDto policyDto);
    List<PolicyVersion> getVersions(Long policyId);
    Policy rollbackPolicy(Long policyId, int versionNumber, String reason);
    PolicyImpactReport analyzeImpact(PolicyDto policyDto);
    SimulationReport simulate(PolicyDto candidatePolicy,
                              List<SimulationTestCase> testCases);
    AIPolicyValidationReport validateAIPolicy(Long policyId);
}

PolicyDto Structure

The PolicyDto is the transport shape used by Policy Center, classic controllers, version snapshots, and AI validation output.

FieldTypeDescription
idLongPolicy ID (null for creation)
nameStringUnique policy name
descriptionStringHuman-readable description
effectPolicy.EffectALLOW or DENY
priorityintEvaluation priority (lower = higher)
targetsList<TargetDto>Policy targets supplied by the client form
rulesList<RuleDto>Rule list containing one or more SpEL conditions
sourcePolicy.PolicySourceMANUAL, AI_GENERATED, AI_EVOLVED, or IMPORTED
approvalStatusPolicy.ApprovalStatusPending/approved state used for AI-generated policies
isActiveBooleanCurrent activation flag
friendlyDescriptionStringNatural-language description generated by PolicyEnrichmentService
approvedBy, approvedAtString, LocalDateTimeApproval metadata
confidenceScore, aiModel, reasoningDouble, String, StringAI generation metadata when present
createdAt, updatedAtLocalDateTimeTimestamps used in detail and version views
changeReasonStringOptional operator-supplied reason used during update/delete/rollback flows

PolicySynchronizationService

Automatically generates and updates policies when role-permission assignments change. Listens for RolePermissionsChangedEvent via Spring's @EventListener and executes asynchronously with @Async.

Java
public class PolicySynchronizationService {

    @Async
    @EventListener
    @Transactional
    public void handleRolePermissionsChange(
            RolePermissionsChangedEvent event) { ... }
}

Synchronization Flow

Policy Synchronization Pipeline
RolePermissionsChangedEvent Triggered when role-permission assignments change
Load Role Fetch role with permissions and managed resources
Build Targets Create targets from ManagedResource (URL or METHOD type)
Build Condition hasAuthority('ROLE_NAME') and (permission expressions)
Create PolicyDto Name: AUTO_POLICY_FOR_{roleName}, Priority: 500
Upsert Policy Existing policy by name? Update : Create new

Auto-generated policies use the naming convention AUTO_POLICY_FOR_{roleName} with a priority of 500. The condition expression combines the role authority check with individual permission authority checks joined by or.

PolicyBuilderService

The builder service still exists in the server layer for template lookup, visual-model conversion, and conflict analysis. In the current OSS UI, operators primarily use the integrated Policy Center create tab rather than a separate standalone builder template.

Java
public interface PolicyBuilderService {
    List<PolicyTemplateDto> getAvailableTemplates(PolicyContext context);
    Policy buildPolicyFromVisualComponents(VisualPolicyDto visualPolicyDto);
    List<PolicyConflictDto> detectConflicts(Policy newPolicy);
}

PolicyBuilderController and /admin/policy-builder still exist in server code, including /from-resource. However, the current OSS template bundle routes day-to-day authoring through /admin/policy-center.

PolicyEnrichmentService

Enriches policy entities with human-readable descriptions by delegating to PolicyTranslator. This service translates SpEL expressions in policy conditions into natural language descriptions.

Java
public class PolicyEnrichmentService {

    private final PolicyTranslator policyTranslator;

    public void enrichPolicyWithFriendlyDescription(Policy policy) {
        // Translates policy rules/conditions to human-readable text
        // Sets policy.friendlyDescription
    }
}

Example: A policy with condition hasAuthority('ROLE_ADMIN') and isAuthenticated() would be enriched to "(User has authority ROLE_ADMIN and User is authenticated)".

BusinessPolicyService

Provides bidirectional translation between business-level access rules and technical policy definitions, enabling non-technical administrators to manage authorization.

Java
public interface BusinessPolicyService {
    // Create a technical policy from a business rule definition
    Policy createPolicyFromBusinessRule(BusinessPolicyDto dto);

    // Update an existing policy from business rule changes
    Policy updatePolicyFromBusinessRule(Long policyId, BusinessPolicyDto dto);

    // Get the business rule representation for a technical policy
    BusinessPolicyDto getBusinessRuleForPolicy(Long policyId);

    // Translate an existing technical policy to business rule format
    BusinessPolicyDto translatePolicyToBusinessRule(Long policyId);
}

Policy Entity Model

Policy Entity Structure
Policy name (unique) | description | effect: ALLOW / DENY | priority: int | source | approvalStatus | isActive | friendlyDescription | approvedBy | approvedAt | confidenceScore | aiModel | reasoning
PolicyTarget (set) targetType: URL | METHOD -- targetIdentifier: URL pattern or method signature -- httpMethod: GET, POST, ANY, etc.
PolicyRule (set) description: String
PolicyCondition (set per rule) expression: String (SpEL) | authorizationPhase: PRE_AUTHORIZE / POST_AUTHORIZE

Policy Authoring Flow

The current OSS policy authoring experience is centered on Policy Center, with related admin policy routes and detail editing supporting the same lifecycle.

Five-Step Workflow

  1. Name & Description —Set the policy name, description, and effect (ALLOW/DENY)
  2. Targets —Define URL patterns or method identifiers this policy applies to
  3. Rules —Configure ALLOW/DENY rules with priority ordering
  4. Conditions —Write SpEL expressions for each rule
  5. Condition Picker —Select from compatible condition templates

From-Resource Mode

When policy creation starts from a selected resource in the Policy Center integrated resources area, or from the legacy /admin/policy-builder/from-resource route, the builder enters from-resource mode:

  • Resource target information is pre-filled
  • Only compatible condition templates are shown (filtered by ConditionCompatibilityService)
  • Domain-specific variables and ABAC applicability are considered

Condition Template System

Condition templates are reusable SpEL expression patterns that simplify policy creation.

Three-Tier Classification

TierNameScopeExamples
1UNIVERSALAll resourcesTime-based restrictions, IP range checks
2CONTEXT_DEPENDENTDomain-specificUser ownership verification, department checks
3CUSTOM_COMPLEXAdvancedMulti-factor conditions, composite rules

AI Auto-Generation

The AutoConditionTemplateService exists to generate condition templates through admin/maintenance flows and AI-backed generation services. In the current OSS tree, this is not wired as an always-on startup step for Policy Center authoring:

  • Batch generation based on resource types and access patterns
  • Complexity scoring (1-10 scale) for each template
  • SpEL safety validation to block dangerous patterns

Condition Compatibility

ConditionCompatibilityService filters conditions per resource:

  • Domain compatibility —matches condition domain to resource domain
  • Available variables —ensures referenced SpEL variables exist in the evaluation context
  • ABAC applicability —checks if Attribute-Based Access Control conditions are relevant

Business Policy Service

BusinessPolicyService translates business-level authorization rules into technical SpEL policy conditions, persists the policy, records a version snapshot, updates linked resource status when permission-backed targets are involved, and reloads runtime authorization mappings.

SpEL Expression Conversion

Input TypeGenerated SpELExample
Role-basedhasAuthority('ROLE_NAME')hasAuthority('ROLE_ADMIN')
CRUD-basedhasAuthority('READ') / hasAuthority('WRITE') ...hasAuthority('READ')
Manual permissionhasAuthority('PERMISSION_NAME')hasAuthority('USER_EXPORT')
AI action#ai.isAllowed(), #ai.needsChallenge(), #ai.hasActionIn(...)#ai.isAllowed() and hasAuthority('ROLE_USER')
Custom SpELValidated and used directlyisAuthenticated() and hasIpAddress('10.0.0.0/8')

Safety Validation

Custom SpEL expressions are validated before storage to block:

  • System-level method calls
  • Reflection-based access
  • Runtime class loading
  • File system operations

Policy Creation Flow

Business Policy Creation Pipeline
BusinessPolicyDto UI form input
Policy Entity Create from DTO
Enrichment Human-readable description
Save to DB Persist policy
Hot-Reload authorizationManager.reload()

Policy Wizard: Quick Grant Guide

The quick-create flow inside Policy Center is the fastest way to author a simple policy. Use it when you need straightforward role-based access with selected roles, stored permissions, CRUD actions, or a saved SecuritySpel expression, without editing the full manual form.

When to Use the Wizard

  • Simple role-based permission grants without complex conditions
  • Granting access to a single resource for one or more roles
  • Quick setup during initial resource onboarding
  • No need for time-based, IP-based, or AI-assisted conditions

Step-by-Step Guide

Policy Wizard: 4-Step Quick Grant
1
Start from Policy Center Resources
Open /admin/policy-center?tab=create, review a resource in the integrated resources area, define its permission when needed, and continue into the quick-create panel with the resource context preselected.
2
Select Permissions
Choose stored permissions, CRUD actions, or a saved SecuritySpel shortcut. The quick panel keeps the selected resource or manual target context while you compose the request.
3
Select Target Roles
Pick one or more roles that the new policy condition should match. The quick panel also supports selecting CRUD permissions or a stored SecuritySpel expression.
4
Confirm and Commit
Review the summary and click "Grant". In the current flow, permission definition happens first, then Policy Center saves the policy, records a version, updates linked resource status, and reloads authorization mappings.

What the Wizard Auto-Creates

When you confirm, the quick flow persists a policy and updates the linked runtime metadata shown below:

Permission Linked to resource
Policy Effect, target, and rule condition from the quick-create request
Version + Reload Version snapshot, resource status sync, authorization reload

Policy Authoring: Advanced Policy Creation

The advanced authoring flow is exposed primarily through the Policy Center create tab. The legacy /admin/policy-builder controller path still exists in server code, but the current OSS bundle centers operator workflows on Policy Center.

When to Use the Builder

  • Policies with time-based, IP-based, or ownership conditions
  • AI-assisted authorization expressions (#ai.isAllowed())
  • Multi-rule policies with different condition combinations
  • DENY policies or priority-sensitive configurations
  • Policies requiring custom SpEL expressions

Step-by-Step Guide

Policy Authoring: 5-Step Advanced Creation
1
Name and Description
Set a unique policy name, human-readable description, and the policy effect (ALLOW or DENY). Choose the priority level (lower number = higher priority).
2
Targets
Define URL patterns (e.g., /api/users/**) or method identifiers this policy applies to. Specify HTTP methods (GET, POST, ANY). In from-resource mode, this step is pre-filled.
3
Rules
Configure one or more rules. Each rule can have its own description and contains conditions evaluated together. Rules are evaluated in priority order.
4
Conditions
Write SpEL expressions for each rule. Conditions define who can access the target and under what circumstances. Manual mode binds each condition to an authorizationPhase and the server validates dangerous custom SpEL patterns before persistence.
5
Condition Picker
Browse and select from compatible condition templates (UNIVERSAL, CONTEXT_DEPENDENT, CUSTOM_COMPLEX). The system recommends templates based on the target resource context.

Context-Aware Mode (from-resource)

When launched from a selected Policy Center resource or the legacy /admin/policy-builder/from-resource route, the builder enters from-resource mode:

  • Pre-filled target: The resource URL pattern or method signature is automatically set as the policy target
  • Filtered conditions: ConditionCompatibilityService filters condition templates to show only those compatible with the resource domain
  • Domain-specific variables: Available SpEL context variables are displayed based on the resource type
  • ABAC applicability: Attribute-Based Access Control conditions are shown only when relevant to the resource

Condition Template Selection

TierNameWhen to UseAI Recommendation
1UNIVERSALConditions that apply to any resource: time-based, IP range, authentication levelRecommended for general access control
2CONTEXT_DEPENDENTDomain-specific conditions: ownership checks, department verification, data sensitivityRecommended based on resource domain analysis
3CUSTOM_COMPLEXMulti-factor conditions: combined role + AI + time checks, composite authorization rulesAI generates based on security posture analysis

AI-Assisted Condition Recommendation

Policy authoring can use AI-assisted draft generation and condition suggestions backed by the resource, role, permission, template, and existing policy data already loaded into Policy Center. In OSS, the AI result feeds the existing business-rule and manual authoring model rather than introducing a separate policy language or a dedicated AI action editor.

  • The selected resource metadata such as type, identifier, and HTTP method
  • Existing policies and validation data already loaded for similar targets
  • The currently selected roles, CRUD permissions, and stored SpEL shortcuts
  • Stored condition templates and compatibility results for the resource context

Suggested conditions can be reviewed, edited, or replaced before the policy is saved.

Wizard vs. Builder: Decision Guide

Which Tool Should You Use?

Policy Center Quick Mode

  • Simple role-to-permission grants
  • No custom conditions needed
  • Single resource or manual target, one or more roles
  • ALLOW effect only
  • 4-step quick-create flow
  • Uses the current quick-create request model in Policy Center

Best for: Initial resource onboarding, straightforward access grants, and quick OSS authoring from the integrated Policy Center flow.

VS

Policy Center Manual / AI Mode

  • Complex multi-condition policies
  • Time, IP, AI, ownership conditions
  • Multiple rules per policy
  • ALLOW or DENY effects
  • 5 steps, full control
  • Assisted condition suggestions

Best for: Production security policies, compliance requirements, fine-grained access control.

AI Policy Approval Workflow

Policies generated by the AI engine follow an approval workflow to ensure human oversight before enforcement.

Approval Lifecycle

AI-Generated Policy Approval Flow
AI Generates Policy source = AI_GENERATED or AI_EVOLVED, approvalStatus = PENDING
PENDING Review Policy is visible in Policy Center list and detail flows but is not loaded into active authorization mappings
APPROVED Admin approves -- Policy becomes enforceable when isActive = true
REJECTED Admin rejects -- Policy is archived and never enforced

Enforcement Rules

CustomDynamicAuthorizationManager only evaluates policies that meet all of the following criteria:

  • isActive = true -- the policy is currently enabled
  • approvalStatus is neither PENDING nor REJECTED -- AI-generated policies must be APPROVED, while manual policies typically remain NOT_REQUIRED

Policies created through the normal quick/manual Policy Center flows typically use source = MANUAL and approvalStatus = NOT_REQUIRED. They can be enforced as soon as they are saved and activated.

Admin Review Process

  1. Open /admin/policy-center?tab=list and filter the policy list by approvalStatus = PENDING
  2. Review the policy details in the list/detail flow: name, description, targets, rules, and conditions
  3. Check the generated friendlyDescription, reasoning, and source metadata for accuracy
  4. Use the Policy Center simulator or /admin/policy-center/api/simulate to preview the impact before approval
  5. Use validation, AI validation, and impact-analysis results to review conflicts before approval
  6. Approve or reject the policy through /admin/policies/{id}/approve or /admin/policies/{id}/reject while working from the Policy Center list/detail flow

Condition Template Examples

The following examples illustrate common condition templates used in policy rules. Each template is a SpEL expression that is evaluated at authorization time.

CategoryDescriptionSpEL Expression
Time-based Allow access only during business hours (9 AM to 6 PM) T(java.time.LocalTime).now().isAfter(T(java.time.LocalTime).of(9,0)) and T(java.time.LocalTime).now().isBefore(T(java.time.LocalTime).of(18,0))
IP Range Allow access only from internal network hasIpAddress('10.0.0.0/8')
Ownership Allow access if AI approves and user has permission on the resource #ai.isAllowed() and hasPermission(#id, 'USER', 'READ')
AI Assessment Allow access if AI analysis passes without requiring a challenge #ai.isAllowed() and !#ai.needsChallenge()
Combined (Role + AI) Allow admin access unconditionally, or require AI approval with permission check for others hasAnyAuthority('ROLE_ADMIN') or (#ai.isAllowed() and hasPermission(#id, 'DOCUMENT', 'UPDATE'))
Role-based Allow access for users with a specific role hasAuthority('ROLE_MANAGER')
Authentication Level Require full authentication (not remember-me) isFullyAuthenticated()

Policy Center REST API

The current Policy Center server surface is centered on /admin/policy-center, with analysis APIs under /admin/policy-center/api/, form submission under /admin/policy-center/create-policy, and business-rule creation under /admin/api/policies/build-from-business-rule.

Policy CRUD

MethodEndpointDescription
POST/api/quick-createQuick-create a policy from a simplified request body.
POST/create-policyCreate a policy from the Policy Center manual authoring form using a full PolicyDto payload.
POST/api/batch-createBatch-create policies for multiple resources in one request.
POST/api/validateValidate a policy definition without saving.
POST/api/validate-quickValidate a quick-create policy definition.

Policy Analysis

MethodEndpointDescription
POST/api/simulateSimulate a policy against a test request to preview the decision.
POST/api/impact-analysisAnalyze the impact of a policy change on existing resources.
GET/api/{policyId}/ai-validationGet the AI-generated validation report for a policy.
GET/api/matrixGenerate a policy matrix report (role x resource x action).

Policy Versioning

The versioning endpoints are implemented and active. The current OSS Policy Center template does not render a dedicated version-history panel, so operators typically consume these endpoints from automation, custom tooling, or future UI extensions.

MethodEndpointDescription
GET/api/{policyId}/versionsList all versions of a policy with timestamps and change summaries.
POST/api/{policyId}/rollback/{versionNumber}Rollback a policy to a previous version.
GET/api/{policyId}/versions/{versionNumber}Load a single stored version snapshot for inspection.
GET/api/{policyId}/versions/compare?v1=...&v2=...Compare two stored versions and list field-level changes.

Resource & Permission Queries

MethodEndpointDescription
GET/api/rolesList available roles for policy target assignment.
GET/api/resourcesList registered resources (URL, METHOD types).
GET/api/available-permissionsList available permissions and existing role-permission mappings used by the quick-create panel.
GET/api/conditionsList stored condition templates, optionally filtered by keyword.
GET/api/statsGet aggregate counts for roles, permissions, conditions, policies, and resource status buckets.
GET/api/policy-summariesGet lightweight policy summaries containing the policy id, name, and effect.
GET/api/spel-permissionsGet registered SecuritySpel expressions available to quick-create and SpEL-based policy authoring.

Migration & Maintenance

MethodEndpointDescription
POST/api/reset-policy-statusReset policy link status for selected resources.
POST/api/migrate-to-crudMigrate legacy SpEL expressions to CRUD-based permissions.
POST/api/cleanup-old-permissionsClean up orphaned permission entries.
POST/refresh-resourcesTrigger a resource cache refresh from the database.