contexa-core contexa-identity contexa-iam

AI-Driven Zero Trust Pipeline

Spring Security decides who you are. Contexa adds post-authentication runtime control through continuous analysis and enforcement based on behavioral context.

The Post-Authentication Blind Spot

Traditional security stops at the gate. Firewalls, WAFs, and login forms verify identity — but once a session is established, the interior is often under-monitored. Stolen credentials, compromised sessions, and AI agents that pass authentication quickly all exploit this post-authentication blind spot.

Contexa combines Spring Security with Spring AI to build a unified zero-trust layer that continues operating after authentication, not just at login.

Traditional Security
Authentication Gate  PASS
No monitoring zone
Once inside, full access.
Stolen session = game over.
Contexa AI Zero Trust
Authentication Gate  PASS
HCAD Context Collection — request-time
AI Behavioral Analysis — continuous
Dynamic Authority Control — request-time authority switching
Automated Enforcement — active and next request paths

Traditional Auth

Guards the gate only.

  • Password / SSO / MFA at login
  • Session cookie = trusted forever
  • No post-auth monitoring
  • Stolen session = full access
Post-Auth Coverage: None

Rule-Based WAF

Catches known patterns.

  • Signature-based detection
  • Static IP / rate-limit rules
  • Cannot detect behavioral anomaly
  • AI agents bypass easily
Post-Auth Coverage: Pattern-only

Contexa AI Zero Trust

Understands behavioral context.

  • LLM-backed analysis evaluates post-authentication security events
  • HCAD behavioral baseline per user
  • Detects deviation, not just signatures
  • 5 enforcement actions with Spring Security
  • Cross-instance decision sharing through the runtime action store
Post-Auth Coverage: Full behavioral

"Rules ask: Does this violate a policy? — If no rule matches, it passes.
Contexa asks: Is this normal for this person? — If behavior deviates, it's caught."

Two Flows, One Defense

Contexa operates two complementary flows that together form a continuous zero-trust shield. Flow A runs in the background — analyzing events asynchronously. Flow B runs on every HTTP request — enforcing decisions through Spring Security's authority system. The action repository bridges the two; in distributed mode Redis and Redisson back the shared action state and cross-instance propagation.

Code anchors. Flow A begins when ZeroTrustEventPublisher.publishMethodAuthorization(...) emits a ZeroTrustSpringEvent, and ZeroTrustEventListener.handleZeroTrustEvent(...) forwards it into the background processor. Flow B begins when AISessionSecurityContextRepository.loadDeferredContext(...) loads the request security context and AbstractZeroTrustSecurityService.applyZeroTrustToContext(...) maps the stored action into Spring Security authorities.
Flow A
Event-Driven AI Analysis
Asynchronous · Background
1
Resource Access
User accesses @Protectable method or protected URL
AuthorizationManagerMethodInterceptor
2
Event Published
Security event with full request context (IP, session, user agent, resource, auth method)
ZeroTrustEventPublisher
3
Event Received & Deduplicated
Filters duplicate events via contextBindingHash. Routes to background processing.
ZeroTrustEventListener → SecurityPlaneAgent
4
Tiered AI Analysis
Layer 1 fast analysis (HCAD + RAG + baseline + LLM). If confidence insufficient, escalate to Layer 2 deep forensics.
ColdPathEventProcessor → L1/L2 Strategy
5
Decision & Store
Tiered analysis yields a SecurityDecision whose enforced action is persisted to the action repository. BLOCK can trigger cross-instance propagation, while ALLOW feeds baseline learning.
SecurityDecisionEnforcementHandler
WRITE ➔
Action Repository
ZeroTrust
Action
Repository
➔ READ
Flow B
Dynamic Authority Enforcement
Synchronous · Every Request
1
HTTP Request Arrives
Any authenticated request enters the Spring Security filter chain
2
AI Security Context Loaded
Replaces Spring Security's default SecurityContextRepository. Resolves the current ZeroTrustAction through ZeroTrustActionRepository; in distributed mode this shared state is Redis-backed.
AISessionSecurityContextRepository
3
Authority Switched
Dynamically replaces user's GrantedAuthority based on AI decision: BLOCK→ROLE_BLOCKED, CHALLENGE→ROLE_MFA_REQUIRED, etc.
adjustAuthoritiesByAction()
4
Access Control Filter
Routes based on action: BLOCK→403/Block-MFA, ESCALATE→423 locked, PENDING→response wrapped for in-flight interruption on the active request path
ZeroTrustAccessControlFilter (Order: 45)
5
Challenge Filter
If ROLE_MFA_REQUIRED detected, initializes adaptive MFA challenge with distributed lock
ZeroTrustChallengeFilter (Order: 50)
AI Analyzes → Shared Action State Bridges → Spring Enforces
This is how Contexa realizes continuous Zero Trust across request-time enforcement and asynchronous analysis.
Flow A analyzes. Flow B enforces. The shared action state bridges them —across time (async analysis completes, the next request picks it up) and, in distributed mode, across application instances via Redis-backed storage and Redisson-based signaling.

Real-World Scenario: Legitimate User vs. Account Takeover

Both users authenticate with valid credentials. Both pass MFA. Traditional security cannot distinguish them. Contexa's AI watches what happens after login.

Sarah — Legitimate User
Step 1 · Login
IP: Home office (known range)
Time: 10:00 AM (usual hours)
Device: Windows / Chrome (registered)
Authentication: PASS
Step 2 · Behavioral Context
Access pattern: Email → ERP → Reports
Request frequency: Normal pace
Navigation: Matches 6-month baseline
Pattern: Normal
Step 3 · AI Verdict
Context trust: 97%
Action: ALLOW
Normal access continues.
Baseline updated with new session data.
Attacker — Stolen Credentials
Step 1 · Login
IP: Similar range (VPN)
Time: 2:00 PM (within office hours)
Device: Windows / Chrome (mimicked)
Authentication: PASS
Step 2 · Behavioral Context
Access pattern: Login → HR Database directly
Request frequency: Bulk export 5,000 records
Navigation: Never accessed this path before
Pattern: Anomaly Detected
Step 3 · AI Verdict
Context trust: 12%
Action: BLOCK
Session terminated immediately.
All instances notified. Admin alerted via SSE.
No rule was written. No signature was matched.
The AI recognized that this behavior doesn't belong to this person —
even though the credentials were perfectly valid.

The Bridge — AISecurityContextRepository

This is the integration point where stored AI decisions meet Spring Security request processing. By replacing Spring Security's default HttpSessionSecurityContextRepository with AISessionSecurityContextRepository, Contexa applies previously stored zero-trust actions to the authentication context on subsequent requests — without changing application code.

Exact method chain. Spring Security calls loadDeferredContext(...), the repository resolves the request context lazily, AbstractZeroTrustSecurityService.applyZeroTrustToContext(...) loads the current action, adjustAuthoritiesByAction(...) maps that action into authorities, and saveContext(...) persists the updated security context when needed. In standalone mode the same contract is backed by in-memory implementations; in distributed mode Redis-backed repositories and broadcasters are used.

How It Works

Spring Security calls loadDeferredContext()
AISessionSecurityContextRepositoryreplaces HttpSessionSecurityContextRepository
ZeroTrustDeferredSecurityContextlazy-loads on first SecurityContext access
applyZeroTrustToContext()queries the action repository → adjustAuthoritiesByAction()
ZeroTrustAuthenticationTokentrustScore + threatScore + ZeroTrustAction

Authority Transformation

When Spring Security loads the request SecurityContext, adjustAuthoritiesByAction() dynamically replaces the user's authorities based on the currently stored zero-trust action:

AI Decision Granted Authority Enforcement Result
ALLOW Original authorities preserved Normal access, baseline learning
BLOCK ROLE_BLOCKED only 403 Forbidden, session invalidated
CHALLENGE ROLE_MFA_REQUIRED only MFA challenge, max 2 attempts
ESCALATE ROLE_REVIEW_REQUIRED only 423 Locked, auto-BLOCK after 300s
PENDING Original + ROLE_PENDING_ANALYSIS Response wrapped, in-flight interruption if the user becomes blocked while the response is still being written
Zero code changes required. Because authority transformation happens inside Spring Security's SecurityContextRepository, every existing @PreAuthorize, hasRole(), and isAuthenticated() expression automatically incorporates AI zero-trust state. @Protectable methods, URL-based policies, and SpEL expressions all benefit transparently.

ZeroTrustAction — The 5 Decisions

The LLM decides the action directly. The tiered AI analysis pipeline outputs a SecurityDecision containing a ZeroTrustAction — not a risk score that gets mapped to an action. Fields like riskScore and confidence exist in SecurityDecision for audit logging and learning purposes only.
Action HTTP TTL Authority Meaning & Next Step
ALLOW 200 1500s Request trusted. Proceed normally. Baseline learning triggered via SecurityLearningService.
BLOCK 403 permanent ROLE_BLOCKED Threat confirmed. Session invalidated, cross-instance propagation via Redisson RTopic. User redirected to /zero-trust/blocked.
CHALLENGE 401 1800s ROLE_MFA_REQUIRED Suspicious activity. MFA challenge initiated via ChallengeMfaInitializer. Max 2 attempts; failure escalates to BLOCK.
ESCALATE 423 300s ROLE_REVIEW_REQUIRED Human review required. Auto-promotes to BLOCK after 300s. SOAR integration via SoarApprovalNotifier.
PENDING_ANALYSIS 503 0s ROLE_PENDING_ANALYSIS AI analysis in progress. Response is wrapped with BlockableResponseWrapper so the stream can be interrupted if the user becomes blocked while data is still being written.

ZeroTrustAction also provides utility methods: isBlocking() returns true for BLOCK and ESCALATE; isAccessRestricted() returns true for BLOCK, CHALLENGE, and ESCALATE.

Flow A — Event-Driven AI Analysis Pipeline

When a user accesses a @Protectable resource, the security event flows through a three-stage handler chain, each with a specific order and responsibility. The event analysis pipeline runs asynchronously in the background while request handling continues on the direct servlet path.

Handler Chain

50
ORDER 50 ProcessingExecutionHandler
Selects processing strategy (AI_ANALYSIS mode). Delegates to ColdPathEventProcessor for tiered LLM analysis. Stores ProcessingResult in pipeline context.
|
55
ORDER 55 SecurityDecisionEnforcementHandler
Extracts the enforced action from the result. Persists it through ZeroTrustActionRepository. BLOCK: sets blockedFlag + broadcasts via BlockingSignalBroadcaster. ALLOW: schedules baseline learning, which flows into SecurityLearningService.learnBaselineOnly(...).
|
60
ORDER 60 AuditingHandler
Records complete audit log via CentralAuditFacade. Includes decision, risk score, confidence, reasoning, processing time.

AI Analysis — Layer 1 & Layer 2

ColdPathEventProcessor orchestrates a tiered AI strategy. Layer 1 performs fast contextual analysis, and when confidence is insufficient Layer 2 escalates to deeper forensic analysis. Both layers use SecurityPromptTemplate for structured prompt engineering.

LLM output is SecurityDecision, which contains the proposed action, the effective autonomousAction, and supporting fields such as riskScore and confidence. Those supporting fields are preserved for audit, calibration, and learning, while the resolved autonomous action is what the enforcement path consumes.

Layer 1 — Contextual Analysis

1
HCAD Context Collection
Builds SessionContext from session info, request patterns, device fingerprint, behavioral baseline vectors
|
2
RAG Search
Searches unified vector store (similarity threshold 0.5, top-k 5) for similar historical security events
|
3
Session History Analysis
Analyzes last 100 actions for anomalous patterns (unusual times, unfamiliar paths, rapid-fire requests)
|
4
LLM Evaluation (Tier 1)
Constructs a prompt via SecurityPromptTemplate, sends it to UnifiedLLMOrchestrator, and produces a SecurityDecision that carries the proposed and effective zero-trust action.

Layer 2 — Expert Investigation

Triggered when Layer 1 confidence is below the configured threshold. Uses Tier 2 LLM for full forensic analysis.

1
Extended Context
Reuses Layer 1 context + deeper behavioral embeddings from complete activity profile
|
2
Broader RAG Search
Extended search with top-k 10 for comprehensive threat context
|
3
Expert LLM Evaluation (Tier 2)
Full forensic analysis with broader context, deeper embeddings, and the same enforcement contract used by the rest of the runtime pipeline.
|
4
SOAR Integration (optional)
ApprovalService requests human approval via SoarApprovalNotifier for ESCALATE decisions

Flow B — Dynamic Authority Enforcement

On every HTTP request, Spring Security's filter chain enforces the current action resolved through ZeroTrustActionRepository. The key mechanism is authority replacement — the user's GrantedAuthority set is dynamically rewritten based on the current ZeroTrustAction.

Filter Chain Order

30
HCADFilter
Collects behavioral context: device fingerprint, session metadata, user agent, IP. Stores in request attributes for downstream use.
|
40
AISessionSecurityContextRepository
Replaces Spring Security's default. On loadDeferredContext(), wraps with ZeroTrustDeferredSecurityContext. On first access: resolves the current action through ZeroTrustActionRepository, calls adjustAuthoritiesByAction(), and creates ZeroTrustAuthenticationToken.
|
45
ZeroTrustAccessControlFilter
BLOCK: Redirect to /zero-trust/blocked or initiate Block-MFA (max 2 attempts via ChallengeMfaInitializer).
ESCALATE: Return 423 to /zero-trust/analysis-pending. TTL 5 min; auto-promotes to BLOCK.
PENDING_ANALYSIS: Wrap the response with BlockableResponseWrapper so an in-flight stream can be interrupted if the action changes while data is still being written.
|
50
ZeroTrustChallengeFilter
Detects ROLE_MFA_REQUIRED. Acquires distributed lock (30s). Initializes MFA state machine via ChallengeMfaInitializer. Redirects to MFA challenge page. Failure → auto-escalates to BLOCK.
|
Standard Spring Security Filters
All existing @PreAuthorize, hasRole(), URL-based authorization now operates on AI-adjusted authorities transparently.

Enforcement Infrastructure

AI makes the decision. Spring Security's filter chain and, in distributed mode, the shared runtime infrastructure enforce it on the active request path, across instances, and even while a response is still being written.

BLOCK Enforcement

Immediate denial with cross-instance propagation.

1
SecurityDecisionEnforcementHandler
Persists BLOCK through ZeroTrustActionRepository and sets blockedFlag. In distributed mode the stored action is Redis-backed.
|
2
BlockingSignalBroadcaster
Publishes BLOCK:{userId} via Redisson RTopic. All instances receive signal in real time.
|
3
BlockingDecisionRegistry
Receives RTopic signal. Updates local ConcurrentHashMap for O(1) lookup.
|
4
BlockableResponseWrapper
BlockableServletOutputStream checks block status on every write(). Even in-flight responses are terminated.
|
5
ZeroTrustAccessControlFilter
Returns 403. Clears authentication, invalidates session. IBlockedUserRecorder persists to DB.

CHALLENGE Enforcement

Requires additional authentication. Distributed lock prevents race conditions.

1
ZeroTrustChallengeFilter
Detects ROLE_MFA_REQUIRED. Acquires distributed lock (30s).
|
2
ChallengeMfaInitializer
Initializes MFA state machine. Generates secure session ID. Determines auto-factor (OTT, Passkey, TOTP). Redirects to MFA page.
|
3
MFA Verification
BlockMfaStateStore tracks attempts (max 2 in 1 hour). Success clears challenge.
|
4
Failure Escalation
MFA failure or timeout → auto-promotes to BLOCK.

ESCALATE Enforcement

Requires human review. Time-bounded with automatic promotion to BLOCK.

1
ZeroTrustAccessControlFilter
Returns 423 Locked. Grants ROLE_REVIEW_REQUIRED. TTL: 300 seconds.
|
2
SOAR Workflow
ApprovalService.requestApproval()SoarApprovalNotifier sends notification to security team.
|
3
Admin Override or Auto-Promotion
AdminOverrideService.approve() resolves. If TTL expires (300s) → auto-promotes to BLOCK.

Cross-Instance Propagation & Unblock

Blocking decisions propagate to all instances in real time. Blocked users can request unblock via MFA verification.

1
Redisson RTopic
Channel: contexa:security:block-signal. Signals: BLOCK:{userId}, UNBLOCK:{userId}.
|
2
BlockedUserService
Persists block to DB. Status tracking: BLOCKEDUNBLOCK_REQUESTEDRESOLVED.
|
3
Unblock Flow
ZeroTrustUnblockController: Block-MFA (max 2 attempts) → MFA verified → requestUnblockWithMfa().
Admin approves via BlockedUserService.resolveBlockById() → clears Redis keys → broadcasts UNBLOCK signal.

Monitoring, Learning & SSE

Every AI decision is streamed to dashboards in real time and fed back into the learning loop to improve future decisions.

Real-Time Stream

Server-Sent Events for live monitoring.

  • ZeroTrustSsePublisher broadcasts decisions
  • SSE endpoint: /api/aiam/sse/zero-trust/subscribe
  • Live action feed: ALLOW/BLOCK/CHALLENGE/ESCALATE
  • Analysis completion, unblock notifications

Admin Dashboard

Visual control center for security operators.

  • /zero-trust/blocked — blocked user page
  • /zero-trust/challenge-required — MFA challenge
  • /zero-trust/analysis-pending — review in progress
  • AdminOverrideService for decision overrides

Learning Loop

Every ALLOW decision improves baselines.

  • SecurityLearningServiceBaselineLearningService
  • EMA (Exponential Moving Average) baseline updates
  • SecurityDecisionPostProcessor vector storage
  • LFU eviction for IP/path frequency maps

SpEL Integration & Configuration

Zero Trust in SpEL Expressions

Spring Security's @PreAuthorize and @PostAuthorize annotations can reference zero-trust state through custom expression methods on AbstractAISecurityExpressionRoot.

ExpressionReturnsDescription
isZeroTrustAllowed()booleanCurrent user's ZeroTrustAction is ALLOW
isZeroTrustBlocked()booleanCurrent user's action is BLOCK
isZeroTrustChallenged()booleanCurrent user's action is CHALLENGE
getZeroTrustAction()ZeroTrustActionReturns the current ZeroTrustAction enum value

Configuration Reference

PropertyDefaultDescription
security.zerotrust.enabledtrueEnable/disable zero-trust pipeline
security.zerotrust.modeENFORCESHADOW (log only) or ENFORCE (full enforcement)
security.zerotrust.sampling.rate1.0Fraction of requests to analyze (0.0-1.0)
security.zerotrust.hotpath.enabledtrueEnable Layer 1 hot-path analysis
security.zerotrust.redis.updateIntervalSeconds30Redis action update interval
contexa.infrastructure.modeSTANDALONESTANDALONE (in-memory) or DISTRIBUTED (Redis+Kafka)