Documentation
Complete guide to installing, configuring, and deploying Asguard.
Introduction
Asguard is a real-time fraud detection engine designed for modern enterprises. It combines deterministic rule-based scoring with probabilistic AI analysis to provide accurate, explainable risk assessments for financial transactions.
The system is built with Go 1.25+ and follows clean architecture principles, ensuring maintainability, testability, and scalability. It exposes a RESTful API that can be integrated into existing payment flows, e-commerce platforms, or financial systems.
Key Features
- Hybrid Scoring: Combines rule-based and AI-powered analysis for optimal accuracy
- Biometric Face Verification: Optional microservice for extracting facial embeddings and comparing them to stored references
- Low Latency: Sub-200ms response times for rule-based scoring; AI escalation adds ~500ms
- Explainable: Every decision includes detailed reasoning and confidence scores
- Stateless: No persistent storage of sensitive transaction data
- BYOK: Bring Your Own Key model for AI integration ensures data privacy
Use Cases
- Real-time payment authorization
- High-value transaction verification
- Cross-border payment screening
- Account takeover detection
- Merchant risk assessment
Quick Start
Installation
Prerequisites
- Go 1.25 or later
- Git
- Groq API key (get one at console.groq.com)
- Docker & Docker Compose (highly recommended for the face service; requires dlib models)
- dlib model files (
shape_predictor_5_face_landmarks.dat,dlib_face_recognition_resnet_model_v1.dat,mmod_human_face_detector.dat). Place them under./models/at the repo root. - Docker (optional, for containerized deployment)
Clone and Setup
git clone https://github.com/org-cyber/asguard.git
cd asguard/backend
go mod download
Configuration
Create a .env file in the backend/ directory:
ASGUARD_API_KEY=your-secure-api-key-min-32-chars
GROQ_API_KEY=gsk_your_groq_api_key_here
PORT=8081
ENV=development
.env file to version control. Use a secrets manager in production environments.
Running Locally
go run main.go
The server will start on http://localhost:8081. You should see:
2026/03/02 10:00:00 Starting Asguard server on :8081
2026/03/02 10:00:00 Environment: development
2026/03/02 10:00:00 Risk Engine: initialized
2026/03/02 10:00:00 AI Service: connected to Groq API
Verify Installation
curl http://localhost:8081/health
Expected response:
{
"status": "asguard health running",
"version": "1.0.0",
"timestamp": "2026-03-02T10:00:00Z"
}
Architecture
Asguard follows a layered architecture pattern with clear separation of concerns. The system is designed to be stateless, allowing for horizontal scaling and simple deployment.
Beginning with version 1.1.0 the platform includes an optional **facial verification microservice** (`asguard-face`) that runs alongside the transaction engine. It is a lightweight Go service that exposes two endpoints—one for extracting 128‑dimensional embeddings from images, and another for comparing them. This allows you to build passwordless login, KYC onboarding, or transaction‑level biometric checks.
Request Lifecycle
Every transaction analysis request flows through the following stages:
1. Authentication Layer
The APIKeyAuth middleware validates the x-api-key header against the configured ASGUARD_API_KEY. Invalid or missing keys result in a 401 Unauthorized response.
2. Handler Layer
Gin handlers parse and validate incoming JSON payloads. They extract transaction data (amount, currency, IP, device, location) and delegate to the service layer.
3. Risk Engine
The core scoring engine applies weighted rules to calculate a base risk score (0-100). Rules are evaluated in parallel where possible.
4. AI Escalation Gate
If the base score is ≥40 (MEDIUM risk threshold), the transaction is escalated to the AI service for enhanced analysis.
5. Response Assembly
Results are aggregated, formatted as JSON, and returned with appropriate HTTP status codes.
Risk Engine
The risk engine uses a weighted scoring system based on the following factors:
| Factor | Weight | Description |
|---|---|---|
| Transaction Amount | 25% | High-value transactions (>$100k) trigger elevated scrutiny |
| Currency Risk | 15% | Non-local or high-volatility currencies |
| Geolocation | 20% | Distance from user's typical location, high-risk jurisdictions |
| Device Fingerprint | 20% | New devices, emulators, or suspicious signatures |
| IP Reputation | 20% | VPNs, Tor exit nodes, known malicious IPs |
Risk Thresholds
- LOW (0-39): Approve automatically
- MEDIUM (40-69): AI analysis triggered, manual review recommended
- HIGH (70-100): Block automatically, AI analysis for audit trail
AI Integration
Asguard uses Groq's Llama-3.3-70b-versatile model for enhanced risk analysis. The AI service constructs detailed prompts including:
- Transaction context (amount, currency, location)
- Rule-based score and triggered factors
- Historical patterns (if available)
- Strict output formatting instructions
AI Prompt Structure
You are a fraud detection analyst. Analyze this transaction:
- Amount: $250,000 USD
- Location: Lagos, Nigeria (User typically transacts from London, UK)
- Device: New device fingerprint
- IP: 102.88.XX.XX (Residential ISP)
Rule-based score: 41/100 (MEDIUM)
Triggered rules: High amount, Foreign location, New device
Provide your assessment in this exact format:
RECOMMENDATION: [APPROVE/REVIEW/BLOCK]
CONFIDENCE: [0.0-1.0]
FRAUD_PROBABILITY: [0.0-1.0]
REASONING: [Brief explanation]
API Reference
Authentication
All API endpoints (except health check) require authentication via the x-api-key header.
curl -H "x-api-key: your-api-key" \
-H "Content-Type: application/json" \
http://localhost:8081/analyze
Security Headers
Asguard implements several security headers by default:
X-Content-Type-Options: nosniffX-Frame-Options: DENYX-XSS-Protection: 1; mode=blockStrict-Transport-Security: max-age=31536000(in production)
Endpoints
Health Check
Verify system status. No authentication required.
GET /health
Response:
{
"status": "asguard health running",
"version": "1.0.0",
"timestamp": "2026-03-02T10:00:00Z",
"uptime": "72h15m30s"
}
Analyze Transaction
Submit a transaction for risk analysis.
POST /analyze
Request Headers:
| Header | Value | Required |
|---|---|---|
| Content-Type | application/json | Yes |
| x-api-key | Your API key | Yes |
Request/Response Schemas
Analyze Request
{
"user_id": "user_12345", // string, required
"transaction_id": "txn_67890", // string, required, unique
"amount": 250000.00, // number, required, > 0
"currency": "USD", // string, required, ISO 4217
"ip_address": "192.168.1.1", // string, optional, IPv4/IPv6
"device_id": "device_abc123", // string, optional
"location": "Lagos, Nigeria", // string, optional
"timestamp": "2026-03-02T10:00:00Z" // string, optional, ISO 8601
}
Analyze Response
{
"transaction_id": "txn_67890",
"risk_score": 41,
"risk_level": "MEDIUM",
"reasons": [
"High transaction amount (>100k)",
"Foreign currency transaction (USD)",
"Unusual geolocation pattern"
],
"ai_triggered": true,
"ai_confidence": 0.85,
"ai_recommendation": "REVIEW",
"ai_fraud_probability": 0.45,
"ai_summary": "Large USD transaction from Lagos warrants manual review",
"processing_time_ms": 142,
"timestamp": "2026-03-02T10:00:00Z"
}
Error Responses
| Status | Code | Description |
|---|---|---|
| 400 | INVALID_REQUEST | Malformed JSON or validation error |
| 401 | UNAUTHORIZED | Missing or invalid API key |
| 429 | RATE_LIMITED | Too many requests |
| 500 | INTERNAL_ERROR | Server error |
| 503 | SERVICE_UNAVAILABLE | AI service temporarily unavailable |
Facial Verification & Face Service
The face service provides the biometric component of Asguard. Although it can be run independently of the backend, the two are often deployed together via docker-compose to enable combined fraud and identity workflows.
Setup
- Ensure the three dlib model files are present under
./models/at the project root. - Define environment variables:
MODELS_PATH=./models API_KEYS=dev1,dev2 PORT=8082 - Start the service manually or with Docker:
cd asguard-face MODELS_PATH=../../models API_KEYS=dev1 PORT=8082 go run main.go
Typical Use Cases
Common integration patterns include:
- Enrollment. Capture a user selfie, POST to
/v1/analyze, and store the returned embedding alongside their account. - Authentication/Validation. On each login or sensitive transaction, capture a fresh photo and POST to
/v1/comparealong with the stored reference embedding. Use the booleanmatchandconfidenceto make a decision.
API Details
Health Check
GET /health
No authentication required; returns service status.
Extract Embedding
POST /v1/analyze
Authorization: Bearer <API_KEY>
Content-Type: application/json
{
"image": "<base64>",
"quality_checks": true
}
Response includes embedding array, quality metrics and any warnings.
Compare Faces
POST /v1/compare
Authorization: Bearer <API_KEY>
Content-Type: application/json
{
"probe_image": "<base64>",
"reference_embedding": [...],
"threshold": 0.6
}
Response contains match, confidence, distance, and the threshold used.
Best Practices
- Always enable
quality_checksto filter out poor captures. - Store embeddings securely and treat them as sensitive biometric data.
- Use TLS for all service communication and rotate API keys regularly.
- Adjust the comparison threshold according to your tolerance for false positives/negatives; 0.6 is the default.
Docker Compose
The existing docker-compose.yml at the root already includes both services. When you run docker compose up --build, it mounts the ./models/ volume into the face container and binds ports 8081 (backend) and 8082 (face).
Deployment
Docker Deployment
Asguard includes Docker configurations for both development and production environments.
Development Mode
The development configuration includes hot-reloading via volume mounts:
cd backend
docker-compose -f docker-compose.dev.yml up --build
Production Build
docker build -t asguard:latest .
docker run -d \
--name asguard \
-p 8081:8081 \
-e ASGUARD_API_KEY=${ASGUARD_API_KEY} \
-e GROQ_API_KEY=${GROQ_API_KEY} \
-e ENV=production \
asguard:latest
Docker Compose (Production)
version: '3.8'
services:
asguard:
build: .
ports:
- "8081:8081"
environment:
- ASGUARD_API_KEY=${ASGUARD_API_KEY}
- GROQ_API_KEY=${GROQ_API_KEY}
- PORT=8081
- ENV=production
- LOG_LEVEL=info
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:8081/health"]
interval: 30s
timeout: 10s
retries: 3
deploy:
resources:
limits:
cpus: '2'
memory: 512M
reservations:
cpus: '0.5'
memory: 128M
Production Checklist
- Use strong, randomly generated API keys (minimum 32 characters)
- Enable TLS/SSL termination (via reverse proxy or load balancer)
- Configure rate limiting (recommended: 100 req/min per client)
- Set up log aggregation (structured JSON logging enabled by default)
- Monitor AI service latency and implement circuit breakers
- Regular security audits of rule configurations
Monitoring & Observability
Asguard exposes Prometheus-compatible metrics at /metrics (if enabled):
asguard_requests_total- Total requests by endpoint and statusasguard_request_duration_seconds- Request latency histogramasguard_risk_scores- Distribution of risk scoresasguard_ai_requests_total- AI service call countasguard_ai_latency_seconds- AI response time
/health endpoint for load balancer health checks. It returns 200 OK when the service is ready to accept traffic.
Development
Testing
Run the test suite:
go test ./... -v
Run with coverage:
go test ./... -coverprofile=coverage.out
go tool cover -html=coverage.out
Integration Tests
Integration tests require a valid Groq API key:
GROQ_API_KEY=test-key go test ./... -tags=integration
Contributing
We welcome contributions. Please follow these guidelines:
- Fork the repository and create a feature branch (
git checkout -b feature/amazing-feature) - Ensure your code follows Go conventions (
gofmt,golint) - Write tests for new functionality
- Update documentation for API changes
- Commit using conventional commits format
- Open a Pull Request with a detailed description
Code Style
- Use
gofmtfor formatting - Follow Effective Go guidelines
- Document all exported functions and types
- Keep functions focused and under 50 lines where possible