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.
Once inside, full access.
Stolen session = game over.
Traditional Auth
Guards the gate only.
- Password / SSO / MFA at login
- Session cookie = trusted forever
- No post-auth monitoring
- Stolen session = full access
Rule-Based WAF
Catches known patterns.
- Signature-based detection
- Static IP / rate-limit rules
- Cannot detect behavioral anomaly
- AI agents bypass easily
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
"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.
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.
@Protectable method or protected URLSecurityDecision whose enforced action is persisted to the action repository. BLOCK can trigger cross-instance propagation, while ALLOW feeds baseline learning.Action
Repository
SecurityContextRepository. Resolves the current ZeroTrustAction through ZeroTrustActionRepository; in distributed mode this shared state is Redis-backed.GrantedAuthority based on AI decision: BLOCK→ROLE_BLOCKED, CHALLENGE→ROLE_MFA_REQUIRED, etc.ROLE_MFA_REQUIRED detected, initializes adaptive MFA challenge with distributed lockReal-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.
Time: 10:00 AM (usual hours)
Device: Windows / Chrome (registered)
Authentication: PASS
Request frequency: Normal pace
Navigation: Matches 6-month baseline
Pattern: Normal
Action: ALLOW
Baseline updated with new session data.
Time: 2:00 PM (within office hours)
Device: Windows / Chrome (mimicked)
Authentication: PASS
Request frequency: Bulk export 5,000 records
Navigation: Never accessed this path before
Pattern: Anomaly Detected
Action: BLOCK
All instances notified. Admin alerted via SSE.
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.
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
loadDeferredContext()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 |
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
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
ColdPathEventProcessor for tiered LLM analysis. Stores ProcessingResult in pipeline context.ZeroTrustActionRepository. BLOCK: sets blockedFlag + broadcasts via BlockingSignalBroadcaster. ALLOW: schedules baseline learning, which flows into SecurityLearningService.learnBaselineOnly(...).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.
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
SessionContext from session info, request patterns, device fingerprint, behavioral baseline vectorsSecurityPromptTemplate, 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.
ApprovalService requests human approval via SoarApprovalNotifier for ESCALATE decisionsFlow 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
loadDeferredContext(), wraps with ZeroTrustDeferredSecurityContext. On first access: resolves the current action through ZeroTrustActionRepository, calls adjustAuthoritiesByAction(), and creates ZeroTrustAuthenticationToken./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.
ROLE_MFA_REQUIRED. Acquires distributed lock (30s). Initializes MFA state machine via ChallengeMfaInitializer. Redirects to MFA challenge page. Failure → auto-escalates to BLOCK.@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.
ZeroTrustActionRepository and sets blockedFlag. In distributed mode the stored action is Redis-backed.BLOCK:{userId} via Redisson RTopic. All instances receive signal in real time.ConcurrentHashMap for O(1) lookup.BlockableServletOutputStream checks block status on every write(). Even in-flight responses are terminated.IBlockedUserRecorder persists to DB.CHALLENGE Enforcement
Requires additional authentication. Distributed lock prevents race conditions.
ROLE_MFA_REQUIRED. Acquires distributed lock (30s).BlockMfaStateStore tracks attempts (max 2 in 1 hour). Success clears challenge.ESCALATE Enforcement
Requires human review. Time-bounded with automatic promotion to BLOCK.
ROLE_REVIEW_REQUIRED. TTL: 300 seconds.ApprovalService.requestApproval() → SoarApprovalNotifier sends notification to security team.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.
contexa:security:block-signal. Signals: BLOCK:{userId}, UNBLOCK:{userId}.BLOCKED → UNBLOCK_REQUESTED → RESOLVED.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.
ZeroTrustSsePublisherbroadcasts 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 progressAdminOverrideServicefor decision overrides
Learning Loop
Every ALLOW decision improves baselines.
SecurityLearningService→BaselineLearningService- EMA (Exponential Moving Average) baseline updates
SecurityDecisionPostProcessorvector 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.
| Expression | Returns | Description |
|---|---|---|
isZeroTrustAllowed() | boolean | Current user's ZeroTrustAction is ALLOW |
isZeroTrustBlocked() | boolean | Current user's action is BLOCK |
isZeroTrustChallenged() | boolean | Current user's action is CHALLENGE |
getZeroTrustAction() | ZeroTrustAction | Returns the current ZeroTrustAction enum value |
Configuration Reference
| Property | Default | Description |
|---|---|---|
security.zerotrust.enabled | true | Enable/disable zero-trust pipeline |
security.zerotrust.mode | ENFORCE | SHADOW (log only) or ENFORCE (full enforcement) |
security.zerotrust.sampling.rate | 1.0 | Fraction of requests to analyze (0.0-1.0) |
security.zerotrust.hotpath.enabled | true | Enable Layer 1 hot-path analysis |
security.zerotrust.redis.updateIntervalSeconds | 30 | Redis action update interval |
contexa.infrastructure.mode | STANDALONE | STANDALONE (in-memory) or DISTRIBUTED (Redis+Kafka) |