MKT_KSA_Geolocation_Security 2.0.1

Smart geolocation & behavioral security library for Rust
Documentation

MKT_KSA_Geolocation_Security

Production-grade geolocation and behavioral security system for Rust services and smart-city access control.

MKT KSA Geolocation Security Cover

[!WARNING] Security Release Advisory Version 2.0.0 is now considered deprecated for production use after final-stage operation exposed critical security findings. The only approved stable release is 2.0.1, which includes hardening, security corrections, and engineering stability improvements. Do not deploy or keep version 2.0.0 in active environments.

0. Release Safety Advisory

  • Version 2.0.0 has been retired from safe production recommendations due to critical security findings discovered after real operational usage.
  • Version 2.0.1 is the mandatory upgrade baseline and the most stable release in this repository line after hardening and cleanup.
  • Security verification for 2.0.1 includes strict local gates (fmt, clippy -D warnings, full tests, cargo audit) and GitHub security checks (Code Scanning, Dependabot, Secret Scanning).
  • Teams still running 2.0.0 should upgrade immediately to 2.0.1 and re-run post-upgrade validation.
  • Security advisory templates for release publication are available in:
    • docs/security-advisories/SECURITY_ADVISORY_TEMPLATE_EN.md
    • docs/security-advisories/SECURITY_ADVISORY_TEMPLATE_AR.md

Latest Status and Strategic Notice (2026-03-19)

Section 00 Update Banner

Development and Update Summary (Today, Yesterday, and Day Before)

  • Release baseline remains 2.0.1 and all recent hardening work is tracked under this version line.

  • Added global X-Request-ID propagation and strict request trace continuity on both error and success paths.

  • Added adaptive AI security blocking with retry semantics and risk reason reporting for blocked traffic.

  • Added strict API key enforcement with constant-time comparison and unified structured API error envelopes.

  • Added security correlation logging for blocked/denied decisions and success audit lines with latency metadata.

  • Added profile-aware runtime hardening (strict / ultra-strict) with tighter defaults and startup validation controls.

  • Automated profile-matrix smoke checks were retired from repository CI; deep profile runs are now executed on demand.

  • Added integration coverage for request-id propagation across multiple endpoints and success JSON trace envelope checks.

  • Active release target is now 2.0.1 due to security and engineering fixes.

  • Security hardening and architecture cleanup have been completed on main.

  • The active runtime database path is hardened SQLite (tokio-rusqlite) with migrations.

  • JWT authorization and rate limiting are centralized for all API routes.

  • Dashboard code and legacy stale reports were removed to reduce attack/documentation drift.

  • Repository entered strict hygiene mode: stale docs removed and active file-role map added.

Verified Implementation Status (2026-03-19)

  • Added adaptive AI hardening with burst-aware scoring (soft/hard thresholds), dynamic threshold lowering, and stricter smart-access indicators.
  • Preserved authorization contract stability by validating JWT before adaptive AI blocking, preventing false semantic drift on expected 401 paths.
  • Added dynamic Retry-After computation for rate-limit responses instead of static values.
  • Added HTTP runtime hardening knobs for timeout/capacity behavior (HTTP_CLIENT_REQUEST_TIMEOUT_SECONDS, HTTP_KEEP_ALIVE_SECONDS, HTTP_MAX_CONNECTIONS, and related controls).
  • Removed periodic security stress scripts/workflows from the repository baseline; extended pressure testing is now on-demand only.
  • Re-validated the strict path end-to-end (fmt, clippy -D warnings, full tests, live split execution) with no server 5xx in recent hardening runs.

Maintenance Policy (Important)

  • This repository is now in security-maintenance mode.
  • No new feature development is planned in this repository.
  • Future updates here will be limited to security fixes and critical stability corrections.
  • A new sovereign successor platform is under development and planned for announcement in 2026.
  • The successor project is being built from scratch with zero external dependencies and sovereign internal packages.

Successor Program Announcement

MKT KSA Integrated Cyber Defense Platform Announcement

Community Note

Community Signal

Crates Downloads GitHub Stars

  • The crate has been downloaded thousands of times.
  • Engagement feedback (issues/comments/reactions) has been significantly lower than expected.
  • Constructive security and production feedback is highly encouraged.

Vote, Like, and Comment

  • Vote and add reactions here (๐Ÿ‘ ๐Ÿ‘Ž โค๏ธ ๐Ÿš€): Issue #50
  • Write comments and integration feedback: Issue #50

Contents

Project Wiki (Bilingual)

1. What This Project Does

Section 01 Banner

MKT_KSA_Geolocation_Security combines multiple trust signals into one security decision:

  • Geolocation verification
  • Behavioral anomaly analysis
  • Device fingerprint analysis
  • Network concealment analysis (proxy/VPN risk)
  • Sensor signal anomaly analysis
  • Weather consistency checks
  • Smart composite access verification

The API layer is served through Actix Web, while core engines are reusable as a Rust library.

1.1 Project Goal

  • Provide a strict, engineering-grade geolocation security core for sovereign and enterprise workloads.
  • Reduce fraud risk by combining multiple signals into one verifiable trust decision.
  • Maintain a deterministic and auditable security posture under production pressure.

1.2 Key Features

  • Multi-signal trust evaluation: location, behavior, device, network, sensors, weather.
  • Centralized authorization controls: JWT validation + per-IP rate limiting.
  • Hardened runtime policy: SQLite-only profile with migration-managed schema.
  • Security-safe secret handling and runtime-generated internal engine keys.
  • API + library dual usage model for service integration and internal embedding.

1.3 Target Audiences

  • Sovereign and government entities.
  • Financial institutions and digital payment systems.
  • Critical infrastructure operators (energy, transport, utilities).
  • Healthcare and identity-sensitive platforms.
  • Security engineering teams building smart-city and fraud-resilient services.

2. Runtime and Security Posture

Section 02 Banner

  • Language: Rust 2021
  • Framework: Actix Web
  • Async runtime: Tokio
  • Active DB: SQLite only (DATABASE_URL=sqlite://...)
  • JWT: centralized decode/validation via JwtManager
  • Rate limiting: centralized per-IP checks before endpoint logic
  • Adaptive AI guard: centralized payload/path risk scoring with temporary IP lock and Retry-After signaling
  • Request correlation: global X-Request-ID propagation across error and success paths
  • Success trace envelope: JSON success responses include trace_id + data
  • Internal engine secrets: generated securely at runtime (no hardcoded secret literals)
  • Secret handling: secrecy + zeroize
  • Signing: HMAC-SHA512/HMAC-SHA384
  • Migrations: versioned SQL migrations in src/db/migrations

3. Complete Repository Role Map

Section 03 Banner

Root files

Path Role
Cargo.toml Package metadata, dependencies, features, crate types
Cargo.lock Deterministic dependency resolution
rust-toolchain.toml Toolchain lock and MSRV governance
README.md Primary English technical documentation
README_AR.md Primary Arabic technical documentation
SECURITY.md Vulnerability disclosure policy
CHANGELOG.md Release and maintenance history
CONTRIBUTING.md Contribution workflow and conventions
Dockerfile Containerized deployment entry
audit.toml cargo-audit configuration
cbindgen.toml C-ABI header generation config
.env.example Environment template
GeoLite2-City-Test.mmdb Test geolocation fixture

Directories

Directory Role
.github/ CI/CD, CodeQL, PR governance, code ownership
docs/ Security hardening reports and repository governance docs
examples/ Library usage examples
scripts/ CI/maintenance scripts
src/ Production source code
tests/ Integration and security surface tests
target/ Local build artifacts (non-source)

New Security Governance Files (2026-03-17)

Path Role
tests/api_request_id_propagation_integration.rs request-id propagation and success-trace regression testing

src/ detailed map

Path Role Interactions
src/main.rs Process bootstrap, engine wiring, server startup Builds AppState, registers API routes
src/lib.rs Public library entry and re-exports Exposes api/core/db/security/utils
src/app_state.rs Shared runtime state container Injected into all handlers
src/api/mod.rs Unified API route registration + auth gate helper Calls submodules and centralized authorization
src/api/*.rs Endpoint handlers by domain Use authorize_request, call core/db
src/core/*.rs Core analysis engines and domain logic Consumed by API and tests
src/db/mod.rs DB module wiring Exposes models/crud/migrations
src/db/models.rs DB model structs Used by CRUD and handlers
src/db/crud.rs SQLite DB operations Called by auth/alerts and bootstrap
src/db/migrations.rs + SQL files Schema versioning and migration execution Called on startup
src/security/*.rs JWT, policy, rate-limit, validation, secret/signing Used across API and core
src/security/ai_guard.rs Adaptive AI request risk scoring and temporary block orchestration Called by centralized authorization gateway
src/utils/*.rs Caching, precision math, helpers, logging Shared utilities

4. Module Interactions and Control Flow

Section 04 Banner

  1. main.rs loads environment and validates security-critical config (JWT_SECRET, DB policy).
  2. main.rs initializes engines and shared services, then constructs AppState.
  3. HTTP request hits /api/... route configured in src/api/mod.rs.
  4. authorize_request() enforces:
    • Authorization header presence
    • Rate limit policy
  • API key checks (when configured)
  • Adaptive AI guard risk checks
  • JWT decode/validation
  1. Handler calls the relevant core engine or DB layer.
  2. Response is returned as JSON (or HTTP error with strict status semantics).

4.1 Project Architecture Diagram

Project Architecture Diagram

The diagram maps real repository structure from entry and API layers to security controls, core engines, and data/support modules.

flowchart LR
  A[src/main.rs + src/api/mod.rs] --> B[src/api/* handlers]
  B --> C[src/security/* + security/ai_guard.rs]
  B --> D[src/core/*]
  D --> E[src/db/*]
  D --> F[src/utils/*]
  E --> G[SQLite + migrations]
  B --> H[Trace Envelope + Request ID]

5. API Reference and Invocation

Section 05 Banner

Base URL: http://127.0.0.1:8080 All endpoints are under /api. All endpoints require: Authorization: Bearer <JWT>.

5.1 Route table

Method Path Module Purpose
GET /api/users/{id} src/api/auth.rs Fetch user by UUID (self/admin check)
POST /api/geo/resolve src/api/geo.rs Cross-location validation
POST /api/device/resolve src/api/device.rs Device fingerprint analysis
POST /api/behavior/analyze src/api/behavior.rs Behavioral risk analysis
POST /api/sensors/analyze src/api/sensors.rs Sensor anomaly analysis
POST /api/network/analyze src/api/network.rs Network trust / concealment analysis
POST /api/alerts/trigger src/api/alerts.rs Persist and register a security alert
POST /api/weather/summary src/api/weather.rs Weather validation summary
POST /api/smart_access/verify src/api/smart_access.rs Composite smart access decision

5.2 Invocation examples

Get user:

curl -X GET "http://127.0.0.1:8080/api/users/<uuid>" \
  -H "Authorization: Bearer <jwt>"

Geo resolve:

curl -X POST "http://127.0.0.1:8080/api/geo/resolve" \
  -H "Authorization: Bearer <jwt>" \
  -H "Content-Type: application/json" \
  -d '{
    "ip_address":"8.8.8.8",
    "gps_data":[24.7136,46.6753,8,1.0],
    "os_info":"ios",
    "device_details":"iphone-15",
    "environment_context":"mobile-4g",
    "behavior_input":{
      "user_id":"00000000-0000-0000-0000-000000000000",
      "event_type":"login",
      "ip_address":"8.8.8.8",
      "device_id":"device-1",
      "timestamp":"2026-03-15T00:00:00Z"
    }
  }'

Device resolve:

curl -X POST "http://127.0.0.1:8080/api/device/resolve" \
  -H "Authorization: Bearer <jwt>" \
  -H "Content-Type: application/json" \
  -d '{"os":"android","device_info":"pixel-8","environment_data":"corp-wifi"}'

Behavior analyze:

curl -X POST "http://127.0.0.1:8080/api/behavior/analyze" \
  -H "Authorization: Bearer <jwt>" \
  -H "Content-Type: application/json" \
  -d '{
    "input":{
      "user_id":"00000000-0000-0000-0000-000000000000",
      "event_type":"payment",
      "ip_address":"8.8.4.4",
      "device_id":"device-1",
      "timestamp":"2026-03-15T00:00:00Z"
    }
  }'

Network analyze:

curl -X POST "http://127.0.0.1:8080/api/network/analyze" \
  -H "Authorization: Bearer <jwt>" \
  -H "Content-Type: application/json" \
  -d '{"ip":"1.1.1.1","conn_type":"WiFi"}'

Sensors analyze:

curl -X POST "http://127.0.0.1:8080/api/sensors/analyze" \
  -H "Authorization: Bearer <jwt>" \
  -H "Content-Type: application/json" \
  -d '{
    "reading":{"timestamp":1710000000,"accel":0.9,"gyro":0.3,"temp":25.0},
    "history":[{"timestamp":1709999900,"accel":0.8,"gyro":0.2,"temp":24.8}]
  }'

Weather summary:

curl -X POST "http://127.0.0.1:8080/api/weather/summary" \
  -H "Authorization: Bearer <jwt>" \
  -H "Content-Type: application/json" \
  -d '{"latitude":24.7136,"longitude":46.6753}'

Trigger alert:

curl -X POST "http://127.0.0.1:8080/api/alerts/trigger" \
  -H "Authorization: Bearer <jwt>" \
  -H "Content-Type: application/json" \
  -d '{
    "entity_id":"00000000-0000-0000-0000-000000000000",
    "entity_type":"user",
    "alert_type":"suspicious_login",
    "severity":"high",
    "details":{"ip":"8.8.8.8","reason":"impossible_travel"}
  }'

Smart access verify:

curl -X POST "http://127.0.0.1:8080/api/smart_access/verify" \
  -H "Authorization: Bearer <jwt>" \
  -H "Content-Type: application/json" \
  -d '{
    "geo_input":["8.8.8.8",[24.7136,46.6753,8,1.0]],
    "behavior_input":{
      "user_id":"00000000-0000-0000-0000-000000000000",
      "event_type":"entry_attempt",
      "ip_address":"8.8.8.8",
      "device_id":"device-1",
      "timestamp":"2026-03-15T00:00:00Z"
    },
    "os_info":"ios",
    "device_details":"iphone-15",
    "env_context":"office-gate"
  }'

6. Environment Variables

Section 06 Banner

Variable Required Description Example
API_KEY Yes Application key consumed by config layer API_KEY=change_me
JWT_SECRET Yes JWT signing/validation secret (32+ chars) JWT_SECRET=32+_chars_secret_here
DATABASE_URL Recommended SQLite path; if missing DB endpoints return 503 DATABASE_URL=sqlite://data/app.db
SECURITY_PROFILE Optional Security posture preset (strict or ultra) SECURITY_PROFILE=ultra
RATE_LIMIT_MAX_REQUESTS Optional Per-IP requests per minute in API gateway RATE_LIMIT_MAX_REQUESTS=60
AI_GUARD_BLOCK_THRESHOLD Optional Base AI block threshold (lower = stricter) AI_GUARD_BLOCK_THRESHOLD=55
AI_GUARD_BURST_WINDOW_SECONDS Optional Burst detection window for adaptive AI guard AI_GUARD_BURST_WINDOW_SECONDS=10
AI_GUARD_BURST_SOFT_LIMIT Optional Soft burst threshold before risk score boost AI_GUARD_BURST_SOFT_LIMIT=24
AI_GUARD_BURST_HARD_LIMIT Optional Hard burst threshold for aggressive blocking AI_GUARD_BURST_HARD_LIMIT=60
HTTP_CLIENT_REQUEST_TIMEOUT_SECONDS Optional Request timeout before 408 HTTP_CLIENT_REQUEST_TIMEOUT_SECONDS=30
HTTP_CLIENT_DISCONNECT_TIMEOUT_SECONDS Optional Grace period for client disconnect handling HTTP_CLIENT_DISCONNECT_TIMEOUT_SECONDS=10
HTTP_KEEP_ALIVE_SECONDS Optional Keep-alive timeout HTTP_KEEP_ALIVE_SECONDS=10
HTTP_WORKERS Optional Actix worker threads HTTP_WORKERS=8
HTTP_MAX_CONNECTIONS Optional Max accepted concurrent connections HTTP_MAX_CONNECTIONS=50000
HTTP_MAX_CONNECTION_RATE Optional Max accepted connection rate HTTP_MAX_CONNECTION_RATE=1024
HTTP_BACKLOG Optional Socket listen backlog HTTP_BACKLOG=4096
HTTP_SHUTDOWN_TIMEOUT_SECONDS Optional Graceful shutdown timeout HTTP_SHUTDOWN_TIMEOUT_SECONDS=45
BOOTSTRAP_ADMIN_PASSWORD_HASH Optional If set, seeds bootstrap-admin user on startup with provided hash BOOTSTRAP_ADMIN_PASSWORD_HASH=<argon2_hash>
LOG_LEVEL Optional Log verbosity LOG_LEVEL=info
GEO_PROVIDER Optional Geolocation source selector GEO_PROVIDER=ipapi

7. Build, Run, and Validate

Section 07 Banner

cargo fmt --all -- --check
cargo clippy --all-targets --all-features -- -D warnings
cargo test --all

Run:

API_KEY=change_me \
JWT_SECRET=replace_with_a_long_secret_32_chars_min \
DATABASE_URL=sqlite://data/app.db \
BOOTSTRAP_ADMIN_PASSWORD_HASH=replace_with_hash_if_needed \
cargo run

8. Current Hardening and Fix History

Section 08 Banner

Current 2.0.1 coverage includes the following fix/development scope:

  • Security hardening: SQLite-only hardened runtime posture with migration enforcement.
  • Security hardening: unified JWT and per-IP rate-limit enforcement through centralized API authorization flow.
  • Security hardening: runtime generation of internal engine secrets (removed hardcoded runtime secret literals).
  • Security hardening: optional bootstrap admin seeding only through BOOTSTRAP_ADMIN_PASSWORD_HASH.
  • Operational fixes: complete dashboard endpoint/module removal from API surface.
  • Operational fixes: replaced dummy endpoint behavior with real logic paths (weather/alerts).
  • Operational fixes: bounded in-memory alert store to protect runtime memory.
  • Repository hygiene and docs governance: removed stale legacy reports that no longer match active architecture/security posture.
  • Repository hygiene and docs governance: added authoritative repository file-role mapping document.
  • Repository hygiene and docs governance: rebuilt both primary READMEs with strict bilingual engineering structure.
  • Documentation UX: section-by-section visual banners for professional readability, with section names embedded.
  • Validation and quality gates: cargo fmt --check, cargo clippy --all-targets --all-features -- -D warnings, and cargo test --all are clean on this update path.
  • Security hardening (2026-03-19): adaptive burst-aware AI guard with dynamic risk/threshold logic and stronger smart-access route sensitivity.
  • Security hardening (2026-03-19): centralized authorization order refined to keep JWT semantics deterministic before AI blocking.
  • Security hardening (2026-03-19): dynamic per-IP Retry-After in rate-limit denials.
  • Runtime hardening (2026-03-19): environment-tunable HTTP timeout/capacity controls for sustained hostile load posture.

Recent security and maintenance milestones are documented in:

  • docs/SECURITY_HARDENING_2026-03-15.md
  • docs/GITHUB_ADVANCED_SCAN_2026-03-15.md
  • docs/REPOSITORY_FILE_ROLES_2026-03-15.md
  • CHANGELOG.md

9. Library Integration and C-ABI

Section 09 Banner

Build artifacts exported by this crate:

  • Rust library (rlib) for native Rust projects.
  • C-compatible dynamic library (cdylib) for FFI integration.
  • C-compatible static library (staticlib) for static linking scenarios.

9.1 Language support matrix (accurate scope)

Language Support Level How
Rust Direct native support Use crate API directly
C / C++ Direct via C-ABI Use generated header + shared/static lib
Python / Go / C# / Java / Node.js / others Indirect via FFI bridge Build language-specific bindings on top of C-ABI

Important: this project does not expose a full native SDK for every language out-of-the-box. Non-Rust languages are supported through C-ABI integration.

9.2 Current exported C-ABI surface

Current cbindgen export list is intentionally minimal and focused:

  • generate_adaptive_fingerprint
  • free_fingerprint_string

These symbols are exported from src/core/device_fp.rs and declared by cbindgen policy in cbindgen.toml.

9.3 C-ABI generation and invocation flow

Generate header:

cbindgen --config cbindgen.toml --crate MKT_KSA_Geolocation_Security --output mkt_ksa_geo_sec.h

Build shared library:

cargo build --release

Then consume the resulting library from C/C++ directly, or from other languages via their C-FFI layer (for example: Python ctypes, Go cgo, C# DllImport).

9.4 Why this was not explicit before

Earlier docs focused on architecture, API behavior, and security hardening tracks. This section now explicitly documents the language boundary and invocation method to remove ambiguity.

10. Detailed Folder and File Responsibilities

Section 10 Banner

.github/

  • workflows/: CI pipelines (rust, clippy, codeql, security-gates, release automation).
  • actions/secure-workspace/action.yml: shared workspace-hardening step used by workflows.
  • codeql/codeql-config.yml: controlled CodeQL scan scope.
  • CODEOWNERS: review ownership for sensitive paths.
  • pull_request_template.md: security and quality checklist.

docs/

  • SECURITY_HARDENING_2026-03-15.md: hardening implementation report.
  • GITHUB_ADVANCED_SCAN_2026-03-15.md: GitHub/code scanning summary and remediation trail.
  • REPOSITORY_FILE_ROLES_2026-03-15.md: source-of-truth for active repository file roles.
  • images/cover-mkt-ksa.svg: primary documentation hero visual.
  • images/banners/section-01.svg ... section-13.svg: section-level visual banners.

scripts/

  • ci/cleanup_workspace.sh: deterministic CI/local cleanup for stale advisory/cache residue.

examples/

  • using_lib.rs: practical example of library-level engine usage.

tests/

  • api_integration_auth_rate_limit_db.rs: integrated auth + rate-limit + DB behavior checks.
  • api_security_surface_integration.rs: endpoint security-surface checks and burst-rate behavior.
  • support/mod.rs: shared test support utilities.

src/api/

  • mod.rs: route registration and centralized authorization helper.
  • auth.rs: user retrieval endpoint with claim/role checks.
  • geo.rs: cross-location verification endpoint.
  • device.rs: device fingerprint endpoint.
  • behavior.rs: behavioral analysis endpoint.
  • network.rs: network trust/concealment endpoint.
  • sensors.rs: sensor anomaly endpoint.
  • alerts.rs: alert creation endpoint (memory + DB persistence path).
  • weather.rs: weather summary/validation endpoint.
  • smart_access.rs: composite smart-access decision endpoint.

src/core/

  • geo_resolver.rs: geolocation resolution and signature logic.
  • device_fp.rs: adaptive fingerprint generation and verification paths.
  • behavior_bio.rs: behavioral analytics and anomaly scoring.
  • network_analyzer.rs: proxy/vpn/connection analysis.
  • sensors_analyzer.rs: sensor telemetry anomaly detection.
  • weather_val.rs: weather provider integration and validation.
  • cross_location.rs: multi-signal verification orchestrator.
  • composite_verification.rs: composite smart access policy engine.
  • history.rs: timeline and anomaly history logic.
  • mod.rs: core module exports.

src/db/

  • models.rs: DB model definitions.
  • crud.rs: async SQLite data operations.
  • migrations.rs: migration runner.
  • migrations/0001_initial.sql: baseline schema.
  • migrations/0002_indexes.sql: index/performance schema upgrade.
  • mod.rs: DB module exports.

src/security/

  • jwt.rs: token generation/validation and claims policy checks.
  • ratelimit.rs: per-IP throttling controls.
  • policy.rs: authorization policy and role/status guards.
  • input_validator.rs: normalization and sanitization utilities.
  • secret.rs: secure wrappers for sensitive values.
  • signing.rs: HMAC signing and verification helpers.
  • mod.rs: security module exports.

src/utils/

  • cache.rs: caching helpers.
  • helpers.rs: generic utility helpers.
  • logger.rs: logging helpers.
  • precision.rs: deterministic precision/math helpers.
  • mod.rs: utils exports.

Root operational files

  • Cargo.toml: package metadata, dependency/runtime policy, and current version (2.0.1).
  • Cargo.lock: pinned dependency graph.
  • README.md / README_AR.md: authoritative primary docs.
  • CHANGELOG.md: chronological release details.
  • SECURITY.md: vulnerability disclosure policy.
  • CONTRIBUTING.md: contribution contract.
  • Dockerfile: container runtime recipe.
  • audit.toml: cargo-audit policy.
  • cbindgen.toml: C-ABI header generation config.
  • GeoLite2-City-Test.mmdb: test geo fixture used by geolocation-related paths.

11. Deep SRC Engineering Review

Section 11 Banner

This section provides an engineering-level review of every major unit under src/, not only core/.

11.1 SRC responsibility map

SRC Unit Primary Role Security Impact Runtime Impact
src/main.rs Bootstraps services and server runtime Enforces startup validation and secret policy Defines process lifecycle
src/lib.rs Public crate exports Limits exposed API surface Enables library embedding
src/app_state.rs Shared runtime state container Prevents scattered auth/security instances Coordinates global engine access
src/api/ HTTP entry points and route wiring Applies centralized authorization gate Handles external traffic path
src/core/ Domain trust engines Produces verification/risk outcomes Core decision latency driver
src/db/ SQLite models, CRUD, migrations Protects persistence consistency Controls storage reliability
src/security/ JWT, policies, rate limiting, signing Main enforcement boundary Controls request acceptance
src/utils/ Shared infrastructure helpers Reduces duplicated unsafe patterns Supports deterministic behavior

11.2 src/main.rs and process orchestration

  • Loads critical environment variables.
  • Validates security-sensitive startup requirements.
  • Initializes analyzers, DB, and route graph.
  • Wires AppState and starts Actix server.
flowchart TD
  A[main.rs startup] --> B[Load and validate env]
  B --> C[Initialize DB and migrations]
  C --> D[Initialize security and core engines]
  D --> E[Build AppState]
  E --> F[Register routes]
  F --> G[Start Actix runtime]

11.3 src/api/ request lifecycle

Request Processing Banner

  • Maps external endpoint contracts to internal engines.
  • Executes authorize_request() before endpoint logic.
  • Normalizes and forwards payload to domain modules.
  • Returns strict JSON + HTTP semantics.
flowchart LR
  A[HTTP Request] --> B[src/api/mod.rs route]
  B --> C[authorize_request]
  C --> D[src/security checks]
  D --> E[domain handler in src/api/*.rs]
  E --> F[src/core or src/db]
  F --> G[JSON response]

11.4 src/core/ trust computation engines

Trust Engine Banner

  • Hosts geolocation, behavior, device, sensor, network, weather, and composite verification logic.
  • Combines multi-signal evidence into deterministic decisions.
  • Serves both API execution and library usage paths.
flowchart LR
  A[Input signals] --> B[geo_resolver]
  A --> C[behavior_bio]
  A --> D[device_fp]
  A --> E[network_analyzer]
  A --> F[sensors_analyzer]
  A --> G[weather_val]
  B --> H[composite_verification]
  C --> H
  D --> H
  E --> H
  F --> H
  G --> H
  H --> I[Trust decision]

11.5 src/db/ persistence boundary

Storage Boundary Banner

  • Owns schema evolution through migrations.
  • Implements async CRUD for runtime endpoints.
  • Isolated boundary for alert/user persistence behavior.
flowchart TD
  A[src/api + src/core] --> B[src/db/crud.rs]
  B --> C[src/db/models.rs]
  B --> D[SQLite runtime]
  D --> E[src/db/migrations/*.sql]

11.6 src/security/ enforcement boundary

Security Workflow Banner

  • JWT generation/validation and claims checks.
  • Per-IP rate-limiting and abuse throttling.
  • Input validation/sanitization and policy guards.
  • Secret wrapping and signature verification.
flowchart LR
  A[Request enters API] --> B[jwt.rs]
  B --> C[policy.rs]
  C --> D[ratelimit.rs]
  D --> E[input_validator.rs]
  E --> F[signing.rs + secret.rs]
  F --> G[Authorized execution]

11.7 src/utils/ deterministic support layer

  • Caching, precision helpers, logging wrappers, shared helpers.
  • Keeps cross-module behavior consistent and reusable.
flowchart LR
  A[api/core/security/db] --> B[utils/cache]
  A --> C[utils/precision]
  A --> D[utils/logger]
  A --> E[utils/helpers]

12. Developer Guide

Section 12 Banner

12.1 Daily engineering flow

  1. Pull latest main and validate local toolchain.
  2. Implement change inside the narrowest possible module.
  3. Add or update tests in tests/.
  4. Run strict gates before any PR.
  5. Ensure docs and changelog reflect behavior changes.

12.2 Mandatory local gates

cargo fmt --all -- --check
cargo clippy --workspace --all-targets --all-features -- -D warnings
cargo test --workspace --all-targets --all-features
cargo audit --deny warnings

12.3 How to add a new endpoint safely

  1. Add handler under src/api/.
  2. Register route in src/api/mod.rs.
  3. Reuse centralized auth path (authorize_request).
  4. Keep core logic in src/core/, not inside handler.
  5. Use src/db/ through defined CRUD boundaries.
  6. Add integration test case in tests/.

12.4 Security-first coding checklist

  • Never hardcode runtime secrets.
  • Keep auth, policy, and rate-limit centralized.
  • Validate/sanitize user-controlled input.
  • Prefer deterministic logic over hidden side effects.
  • Keep privileged operations auditable in logs and tests.

13. AI and Intelligence Role

Section 13 Banner

The current production architecture is deterministic and security-auditable. AI is treated as an intelligence augmentation layer, not an unbounded decision authority.

13.1 Current state in 2.0.1

  • Security decisions are enforced by explicit policies and deterministic multi-signal logic.
  • Behavioral and anomaly analysis is implemented as transparent engine rules.
  • No opaque ML model is allowed to bypass security policy controls.

13.2 AI-ready integration boundary

flowchart LR
  A[Raw telemetry] --> B[Deterministic trust engines]
  B --> C[Policy enforcement]
  C --> D[Access decision]
  B --> E[AI/ML advisory layer optional]
  E --> F[Analyst insights and tuning]
  F --> C

13.3 Recommended AI usage model

  • Use AI for risk explanation, analyst support, and threshold tuning recommendations.
  • Keep final enforcement under deterministic policies in src/security/ and src/core/.
  • Log AI-assisted recommendations separately from hard enforcement outcomes.

License

Apache-2.0. See LICENSE.