Enterprise ABAC Gateway
Zero-trust reverse proxy that evaluates attribute-based policies with embedded OPA and revokes tokens across the fleet in real time.
At a glance
- Embedded Open Policy Agent for attribute-based decisions
- Sub-5ms authorization path on the proxy hot path
- Distributed token revocation propagated through Redis
- Drops in front of any upstream without modifying it
- Mock upstream included for local policy tests
From the repository
README
High-performance, zero-trust reverse proxy and authorization gateway built in Go with an embedded Open Policy Agent (OPA) engine, sub-5ms decision latency, real-time distributed token revocation via Redis Pub/Sub, and cryptographic tamper-evident audit logging.
📌 Executive Overview
Modern cloud-native and multi-tenant platforms require authorization paradigms far more granular than static Role-Based Access Control (RBAC). In high-assurance environments, authorization must dynamically synthesize who the requester is (Subject), what action they seek to perform (Action), what data classification applies (Resource), and real-time operational context (Environment).
The Enterprise Fine-Grained ABAC Gateway acts as a centralized Policy Enforcement Point (PEP) and Policy Decision Point (PDP) fronting backend microservices. Engineered to comply with NIST SP 800-162 (ABAC), NIST SP 800-207 (Zero-Trust Architecture), and RFC 7519 (JSON Web Tokens), it eliminates authorization latency by compiling Rego policies directly into the Go process memory space, avoiding out-of-process network hops while maintaining distributed consistency across cluster instances.
🌟 Key Capabilities
- ⚡ Sub-5ms Decision Latency SLA ($T_{\text{eval}} \le 5.0\text{ ms (p99)}$): In-memory attribute resolution and local policy compilation in Go via embedded OPA eliminate blocking database roundtrips during hot-path authorization.
- 🎯 Four-Dimensional Vector Evaluation ($S, A, R, E$): Computes decisions dynamically across Subject (roles, tenant, clearance, MFA status), Action (verb, idempotency classification), Resource (classification, tenant owner, lifecycle tags), and Environment (client IP/CIDR, business hours, device trust posture).
- 🔄 Real-Time Distributed Invalidation ($\le 100\text{ ms}$): Emergency token revocations (JTI) and role changes propagate immediately across all gateway instances via Redis Pub/Sub, updating in-memory LRU caches in under 100ms.
- 🔒 Cryptographic Tamper-Evident Audit Chain: Every authorization outcome (
ALLOW/DENY) is recorded in an append-only SHA-256 hash chain ($\text{Hash}n = \text{SHA-256}(\text{Hash}{n-1} + \text{Snapshot}_n)$) persisted asynchronously to PostgreSQL for SOC 2 Type II and ISO 27001 audit trails. - 🏢 Ironclad Multi-Tenant Isolation: Complete isolation between tenant organizations enforced cryptographically and logically at the route and policy layers, with default-deny fail-closed semantics.
- 🚨 Emergency Break-Glass Protocol: Governed bypass paths for critical incidents with mandatory audit obligations and automatic tenant boundary containment.
📐 System Architecture
The gateway is partitioned into an ultra-low latency Data Plane (HTTP Reverse Proxy & In-Memory PDP), an isolated Control Plane (Admin API for policy and revocation management), and resilient State & Persistence Tiers (Redis 7 & PostgreSQL 16).
Interactive Architecture Diagram (Archify)

Figure 1: High-level System Architecture diagram generated with Archify.
👉 🔍 Click Here to Open Interactive Archify Diagram (Supports dark/light themes, clickable nodes, and deep component inspection)
Native System Architecture Map
Component Breakdown & Trust Boundaries
| Component | Layer | Description | Security & Reliability Guarantees |
|---|---|---|---|
Auth Middleware (proxy/auth_middleware.go) | Perimeter Ingress | Validates HMAC-signed JWT tokens, verifies issuer/audience, enforces clock skew leeway ($\pm 30\text{s}$), and checks local JTI blacklist. | Rejects expired, tampered, or blacklisted tokens at the boundary before policy execution begins. |
ABAC Interceptor (proxy/abac_interceptor.go) | Enforcement (PEP) | Intercepts HTTP requests, coordinates attribute resolution and policy evaluation, and decides whether to forward or fail closed. | Enforces default-deny semantics. Traps and logs all denial reasons for security auditability. |
Attribute Resolver (engine/resolver.go) | Context Enrichment | Synthesizes the four evaluation vectors ($S, A, R, E$) combining JWT claims, URI parameters, and cached tenant metadata. | In-memory lookup avoids blocking SQL queries on the authorization hot path. |
Embedded OPA Engine (engine/opa.go) | Decision (PDP) | In-process Open Policy Agent evaluator running pre-compiled Rego policies (rbac_fallback.rego & abac_enterprise.rego). | Evaluates complex multi-attribute rules in memory with strict $\le 5.0\text{ms}$ p99 latency SLA. |
Reverse Proxy (proxy/reverse_proxy.go) | Data Plane Forwarder | High-throughput Go reverse proxy forwarding authorized requests to target backend microservices. | Preserves upstream headers, injects authenticated subject context, and streams responses. |
PubSub Listener (cache/pubsub_listener.go) | Invalidation Sync | Subscribes to Redis abac:v1:invalidate channel to propagate token and policy changes to in-memory caches. | Guarantees distributed cache invalidation across all gateway replicas in $\le 100\text{ms}$. |
Audit Logger & Chainer (audit/logger.go) | Audit Pipeline | Bounded asynchronous worker pool that computes continuous SHA-256 hash chains for every decision. | Non-blocking ring buffer ensures audit writes never throttle proxy traffic while ensuring zero dropped events under normal loads. |
Admin API (cmd/admin_api) | Control Plane | Dedicated management service on port 8082 for emergency token revocations (POST /admin/revoke) and health monitoring. | Authenticated via strict static admin credentials (ABAC_ADMIN_KEY), isolated from public data plane traffic. |
🔄 Core Workflow & Request Lifecycle
Every inbound request traverses a three-phase pipeline: Ingress & Token Verification, In-Memory Attribute Resolution & Policy Decision, and Authorized Proxying & Cryptographic Audit Logging.
Interactive Workflow Diagram (Archify)

Figure 2: End-to-End Request Lifecycle & Policy Decision Pipeline generated with Archify.
👉 🔍 Click Here to Open Interactive Archify Workflow
Native Sequence Diagram
Request Lifecycle Step-by-Step
- Ingress Handshake & Token Parsing: The client transmits an HTTP request with an
Authorization: Bearer <JWT>header to the gateway data plane (:8080). - Cryptographic Signature Verification:
AuthMiddlewareverifies HMAC-SHA256 signature integrity, issuer, audience, and timestamp expiration with a configurable 30-second leeway. - Revocation Blacklist Check: The token's unique identifier (
jti) is checked against the local in-memory LRU blacklist. If absent locally, Redis is queried. Revoked tokens are rejected with401 Unauthorized. - Four-Vector Assembly: The
Resolverextracts Subject attributes ($S$) from claims, parses Action ($A$) from HTTP method and path, extracts Resource ($R$) from request parameters, and captures Environment ($E$) from client IP, time of day, and compliance headers. - In-Process Rego Evaluation: The embedded OPA engine executes compiled rules against the assembled input vector. The evaluator determines
allow: true/false, denial reasons, and obligations in $<5\text{ms}$. - Traffic Forwarding: On
ALLOW, the reverse proxy forwards the request to the upstream microservice (:8081) and streams the response back to the client. OnDENY, a403 Forbiddenresponse is returned immediately. - Asynchronous Audit Chaining: The authorization decision, attribute snapshot, and latency metrics are enqueued into a bounded channel. Worker routines calculate the rolling SHA-256 tamper-evident hash and persist it to PostgreSQL.
🧠 Multi-Dimensional Attribute Matrix ($S, A, R, E$)
Access decisions adhere to the formal function:
$$\text{Decision} = f(\text{Subject}, \text{Action}, \text{Resource}, \text{Environment}) \in {\text{ALLOW}, \text{DENY}}$$
┌────────────────────────────────────────────────────────────────────────┐
│ EVALUATION INPUT VECTOR │
├───────────────────┬───────────────────┬────────────────┬───────────────┤
│ SUBJECT (S) │ ACTION (A) │ RESOURCE (R) │ENVIRONMENT (E)│
├───────────────────┼───────────────────┼────────────────┼───────────────┤
│ • Subject ID │ • HTTP Method │ • Resource ID │ • Client IP │
│ • Tenant ID │ • Route Path │ • Target Tenant│ • CIDR Trust │
│ • Roles │ • Classification: │ • Data Class: │ • Time of Day │
│ • Clearance Level │ - READ │ - PUBLIC │ • Geo Region │
│ • MFA Verified │ - WRITE │ - CONFID. │ • Device Trust│
│ • Break-Glass Flag│ - EXPORT │ - RESTRICT.│ • Status Post.│
└───────────────────┴───────────────────┴────────────────┴───────────────┘
Policy Rules Implemented in Rego
- Tenant Isolation: Cross-tenant access is unconditionally denied unless explicit inter-tenant data sharing agreements exist.
- Clearance vs. Classification: A Subject with clearance level $L_S$ cannot access a Resource with classification $L_R$ where $L_S < L_R$.
- MFA Enforcement: Writing or exporting
RESTRICTEDresources strictly requiresmfa_authenticated == true. - Environmental Boundaries: Access from untrusted CIDRs or outside business hours (08:00–18:00 UTC) is rejected unless authorized via emergency break-glass.
- Device Posture: Non-compliant client devices are rejected from performing state-modifying actions.
🔗 Tamper-Evident Cryptographic Audit Trail
To meet the stringent requirements of SOC 2 Type II, ISO 27001, and HIPAA, the gateway implements a continuous cryptographic hash chain for all decision events.
$$\text{Audit Hash}n = \text{SHA-256}(\text{Audit Hash}{n-1} + \text{DecisionData}_n)$$
Properties & Guarantees
- Strict Determinism: Canonical JSON serialization guarantees identical hash generation across distributed instances.
- Tamper Detection: Modifying, inserting, or deleting any historical log record breaks the cryptographic chain from that point forward, instantly detectable via verification queries.
- Non-Blocking Architecture: Decisions are emitted across a buffered Go channel (
chan *AuditRecord, capacity 5,000) to decouple proxy latency from database write times.
-- Schema excerpt: access_audit_log
CREATE TABLE IF NOT EXISTS access_audit_log (
id BIGSERIAL PRIMARY KEY,
tenant_id UUID NOT NULL REFERENCES tenants(id),
prev_hash VARCHAR(64) NOT NULL,
current_hash VARCHAR(64) NOT NULL,
decision VARCHAR(16) NOT NULL, -- 'ALLOW' or 'DENY'
subject_id VARCHAR(64) NOT NULL,
action VARCHAR(32) NOT NULL,
resource_id VARCHAR(128) NOT NULL,
attribute_snapshot JSONB NOT NULL, -- Full S, A, R, E vector
latency_ns BIGINT NOT NULL,
timestamp TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
💻 Tech Stack & Standards
| Layer / Domain | Technology | Version | Purpose & Rationale |
|---|---|---|---|
| Core Language | Go | 1.22+ / 1.27 | High-throughput concurrent network I/O, garbage collection tuned for low latency, zero external runtime dependencies. |
| Policy Engine | Open Policy Agent (OPA) | v0.70.0 | Embedded Rego engine executing compiled policies in-process inside the Go binary. |
| Perimeter Routing | Chi | v5.1.0 | Idiomatic, composable, lightweight HTTP routing with minimal allocations. |
| Caching & Pub/Sub | Redis | 7.0 Alpine | Sub-millisecond distributed token blacklist, attribute vector caching, and realtime invalidation bus. |
| Audit & Primary DB | PostgreSQL | 16 Alpine | Robust relational tenant storage and append-only tamper-evident audit ledger. |
| Security Standards | NIST SP 800-162 / 800-207 | Current | Architectural guidelines for Attribute-Based Access Control and Zero-Trust Architectures. |
| Token Standard | RFC 7519 (JWT) | jwt/v5 | Stateles cryptographic tokens with custom claims for clearance, MFA status, and tenant binding. |
| Testing & CI | Go Test & Testify | v1.12.1 | Complete test suite including end-to-end proxy tests, sub-5ms benchmarks, race detector, and tenant isolation tests. |
| Containerization | Docker & Compose | Compose v2 | Hermetic local stack initialization for PostgreSQL, Redis, and mock upstream services. |
📁 Project Directory Structure
.
├── cmd/
│ ├── gateway/ # Data Plane: Reverse proxy & ABAC interceptor (:8080)
│ │ └── main.go
│ └── admin_api/ # Control Plane: Policy & token revocation service (:8082)
│ └── main.go
├── internal/
│ ├── admin/ # Control plane HTTP handlers & revocation logic
│ │ └── api.go
│ ├── audit/ # Tamper-evident audit logging & SHA-256 hash chaining
│ │ ├── hash_chain.go # Cryptographic link computation & verification
│ │ └── logger.go # Non-blocking bounded channel worker pool
│ ├── cache/ # Distributed permission cache & blacklist
│ │ ├── redis_cache.go # Redis client, key namespaces, vector TTLs
│ │ └── pubsub_listener.go # Real-time invalidation subscriber (<100ms sync)
│ ├── domain/ # Domain structs & evaluation models
│ │ ├── attributes.go # Subject, Action, Resource, Environment structs
│ │ └── decision.go # Decision outcome, reasons, obligations, metrics
│ ├── engine/ # Embedded policy evaluation engine
│ │ ├── compiler.go # Rego syntax validation & compilation
│ │ ├── opa.go # Embedded OPA Go SDK runtime
│ │ └── resolver.go # In-memory attribute resolution (JWT + Redis)
│ ├── proxy/ # Gateway network layer
│ │ ├── abac_interceptor.go # Synchronous authorization check interceptor
│ │ ├── auth_middleware.go # JWT extraction, signature check, claims unpacking
│ │ └── reverse_proxy.go # High-performance HTTP reverse proxy
│ └── repository/ # PostgreSQL database layer
│ ├── audit_repo.go # Append-only audit trail repository
│ ├── db.go # Connection pool tuning & lifecycle management
│ ├── revocation_repo.go # Persistent token revocation fallback
│ └── tenant_repo.go # Tenant metadata & resource hierarchies
├── policies/ # Declarative Rego policy bundles
│ ├── abac_enterprise.rego # Environmental, clearance, MFA, and data-classification rules
│ └── rbac_fallback.rego # Baseline role-to-action bindings
├── migrations/ # PostgreSQL schema definitions
│ └── 001_init_abac_schema.sql # Tenants, policies, revoked tokens, and audit tables
├── docs/ # Architecture and interactive visual documentation
│ ├── architecture.html # Interactive Archify System Architecture diagram
│ ├── architecture.json # Archify architecture diagram configuration
│ ├── workflow.html # Interactive Archify Request Lifecycle diagram
│ ├── workflow.json # Archify workflow diagram configuration
│ └── assets/ # Static visual assets for GitHub & documentation
│ ├── architecture.png # High-resolution System Architecture preview
│ └── workflow.png # High-resolution Request Lifecycle preview
├── docker/ # Docker support files
│ └── mock-upstream/
│ └── default.conf # Nginx configuration for upstream microservice
├── tests/ # Comprehensive test suite
│ ├── audit_trail_test.go # Cryptographic hash link & non-blocking queue tests
│ ├── e2e_proxy_test.go # End-to-end authorized reverse proxy forwarding
│ ├── multi_tenant_isolation_test.go # Tenant boundary breach prevention verification
│ ├── policy_evaluation_test.go # Sub-5ms p99 latency SLA benchmarks
│ └── token_revocation_test.go # <100ms distributed cache invalidation tests
├── docker-compose.yml # Local development stack (Postgres, Redis, Mock Upstream)
├── Makefile # Build, test, migration, and benchmark tasks
├── go.mod # Go module definition
└── README.md # Repository documentation
🚀 Quick Start & Local Setup
Prerequisites
- Go: 1.22 or newer installed (
go version) - Docker & Docker Compose: Installed and running
- Make: GNU Make (or execute makefile commands directly)
- curl & jq: For testing and inspecting responses
1. Clone the Repository
git clone https://github.com/your-org/enterprise-abac-gateway.git
cd enterprise-abac-gateway
2. Configure Environment Variables
Create your local .env configuration file or export variables:
# Gateway Data Plane (:8080)
export ABAC_GATEWAY_ADDR=":8080"
export ABAC_UPSTREAM_URL="http://127.0.0.1:8081"
export ABAC_POLICY_DIR="policies"
# Control Plane Admin API (:8082)
export ABAC_ADMIN_ADDR=":8082"
export ABAC_ADMIN_KEY="super-secret-admin-key-change-me"
# Security & JWT Tokens
export ABAC_JWT_SECRET="enterprise-abac-secret-key-32bytes-minimum!"
export ABAC_JWT_ISSUER="kavaryx-auth"
export ABAC_JWT_AUDIENCE="kavaryx-api"
# Datastores
export ABAC_REDIS_ADDR="127.0.0.1:6380"
export ABAC_DB_DSN="postgres://abac:abac_dev_password@127.0.0.1:5433/abac_gateway?sslmode=disable"
3. Start Infrastructure Dependencies
Start PostgreSQL 16, Redis 7, and the mock upstream Nginx service in the background:
# Using Makefile
make up
# Or directly with Docker Compose
docker compose up -d --wait
4. Apply Database Migrations
Apply the initial database schema to PostgreSQL:
# Using Makefile
make migrate
# Or directly using psql via Docker
docker compose exec -T postgres psql -U abac -d abac_gateway < migrations/001_init_abac_schema.sql
5. Build & Run the Gateway
Start the Gateway data plane:
go run ./cmd/gateway/main.go
In a separate terminal, launch the Admin API control plane:
go run ./cmd/admin_api/main.go
🧪 Verification & Operational Scenarios
Scenario 1: Authorized Request (Happy Path)
Send a valid JWT token matching tenant, role, and clearance attributes:
# Generate a test token or use the test helper
curl -i -X GET http://localhost:8080/records/1 \
-H "Authorization: Bearer <VALID_JWT_TOKEN>" \
-H "X-Device-Posture: COMPLIANT"
Expected Response: HTTP/1.1 200 OK forwarded from the upstream backend.
Scenario 2: Cross-Tenant Breach Prevention
When a Subject from Tenant A attempts to access records belonging to Tenant B:
curl -i -X GET http://localhost:8080/tenants/tenant-b/records/1 \
-H "Authorization: Bearer <TENANT_A_JWT_TOKEN>"
Expected Response:
HTTP/1.1 403 Forbidden
Content-Type: application/json
{
"error": "access denied by policy",
"reasons": ["cross-tenant access prohibited without bilateral delegation agreement"]
}
Scenario 3: Real-Time Token Revocation via Admin API
When a security event occurs, revoke a compromised token ID (jti) through the Admin API:
curl -i -X POST http://localhost:8082/admin/revoke \
-H "X-Admin-Key: super-secret-admin-key-change-me" \
-H "Content-Type: application/json" \
-d '{
"jti": "token-compromised-uuid-1234",
"subject_id": "user-8821",
"expires_at": "2026-10-15T12:00:00Z",
"reason": "Suspected credential leakage"
}'
Outcome:
- Revocation persists in Redis and PostgreSQL.
- Invalidation event broadcasts over Redis Pub/Sub channel
abac:v1:invalidate. - Within $\le 100\text{ms}$, all active Gateway replicas flush their local caches.
- Subsequent requests using that token are rejected immediately with
401 Unauthorized.
Scenario 4: Verifying the Tamper-Evident Audit Chain
Query the PostgreSQL audit ledger to verify sequential SHA-256 hash integrity:
SELECT
id,
decision,
subject_id,
action,
resource_id,
prev_hash,
current_hash,
timestamp
FROM access_audit_log
ORDER BY id DESC
LIMIT 5;
⚡ Performance Benchmarks & Testing
The test suite validates compliance with the sub-5ms latency SLA, multi-tenant boundaries, concurrent throughput, and cryptographic determinism.
# Run the complete test suite
make test
# Run tests with the Go race detector enabled
make test-race
# Run sub-5ms policy evaluation benchmarks
make benchmark
Benchmark Results
=== RUN TestEvaluationMeetsSubFiveMillisecondP99
policy_evaluation_test.go:330: evaluation latency: p50=0.04ms p99=2.78ms max=4.94ms timeouts=0 (0.00%)
--- PASS: TestEvaluationMeetsSubFiveMillisecondP99 (0.68s)
=== RUN TestHashChainDetectsTampering
--- PASS: TestHashChainDetectsTampering (0.01s)
--- PASS: TestHashChainDetectsTampering/edited_field (0.00s)
--- PASS: TestHashChainDetectsTampering/edited_snapshot (0.00s)
--- PASS: TestHashChainDetectsTampering/deleted_record (0.00s)
--- PASS: TestHashChainDetectsTampering/forged_prev_hash (0.00s)
=== RUN TestTenantIsolationEveryCrossTenantRequestDenied
--- PASS: TestTenantIsolationEveryCrossTenantRequestDenied (0.02s)
PASS
ok enterprise-abac-gateway/tests 6.138s
🛡️ Security & Zero-Trust Best Practices
- Fail-Closed by Default: If policies cannot be evaluated or database audit connections fail, the gateway unconditionally rejects traffic rather than serving unaccountable requests.
- Key Rotation & Leeway: Keep JWT signing secrets strictly separated by environment. Clock skew leeway is capped at 30 seconds to prevent replay windows.
- Control Plane Isolation: Keep port 8082 (
cmd/admin_api) restricted to private VPC networks or behind internal VPN gateways. - Regular Hash Audits: Periodically run offline hash chain verifiers against
access_audit_logto prove log continuity for compliance auditors.
🤝 Contributing
Contributions are welcome! Please follow these steps:
- Fork the repository and create a feature branch (
git checkout -b feat/advanced-obligation-handler). - Implement your changes with accompanying unit and integration tests.
- Ensure all tests pass with zero race conditions:
make test-race. - Run
go vet ./...andmake tidy. - Submit a pull request with a detailed description of the design rationale.
📄 License
This project is licensed under the MIT License — see the LICENSE file for details.