π‘οΈπ MKT_KSA_Geolocation_Security
Smart Saudi Geolocation & Security Library β MKT KSA πΈπ¦
π Rust | π°οΈ Smart Security | ποΈ Smart City Ready | π Apache 2.0 | Developed by Mansour Bin Khalid (KSA πΈπ¦)
π Table of Contents
- πΊοΈ Project Overview
- π Main Files
- π§© Constants & Public Functions
- π Config & Endpoints
- π§ Architecture
- π οΈ Verification Examples
- βοΈ Core Engine Modules
- π‘ Sensors Analyzer
- βοΈ Weather Validation
- π History Service
- π Cross-Validation Engine
- β οΈ Dependency Audit
- β Test Results
- β Features
- π§ Developer Guide
- π System State
πΊοΈ Project Overview
MKT_KSA_Geolocation_Security is an advanced security library for smart cities, sovereign sectors, and technology enterprises. It leverages geolocation verification, behavioral analytics, device fingerprinting, AI, and a modular, extensible architecture β with full English documentation for every module and function.
π Main Files
| File Name | Path | Role (English) |
|---|---|---|
| main.rs | src/main.rs | Main entry point, initializes server & modules |
| models.rs | src/db/models.rs | DB models |
| crud.rs | src/db/crud.rs | DB CRUD functions |
| mod.rs (db) | src/db/mod.rs | DB module index |
| ratelimit.rs | src/security/ratelimit.rs | Rate limiting module (DoS protection) |
| input_validator.rs | src/security/input_validator.rs | Input validation tools |
| policy.rs | src/security/policy.rs | Policy engine |
| jwt.rs | src/security/jwt.rs | JWT management |
| mod.rs (security) | src/security/mod.rs | Security module index |
| geo_resolver.rs | src/core/geo_resolver.rs | Geolocation resolver engine |
| behavior_bio.rs | src/core/behavior_bio.rs | Behavioral analytics engine |
| device_fp.rs | src/core/device_fp.rs | Device fingerprinting |
| network_analyzer.rs | src/core/network_analyzer.rs | Network analysis & concealment detection |
| sensors_analyzer.rs | src/core/sensors_analyzer.rs | Sensors data analysis engine |
| weather_val.rs | src/core/weather_val.rs | Weather validation engine |
| cross_location.rs | src/core/cross_location.rs | Cross-validation engine |
| history.rs | src/core/history.rs | History management & anomaly detection |
| mod.rs (core) | src/core/mod.rs | Core engine module index |
| auth.rs | src/api/auth.rs | Auth endpoints |
| alerts.rs | src/api/alerts.rs | Security alerts endpoints |
| geo.rs | src/api/geo.rs | Geolocation endpoints |
| device.rs | src/api/device.rs | Device endpoints |
| behavior.rs | src/api/behavior.rs | Behavior analytics endpoints |
| network.rs | src/api/network.rs | Network analysis endpoints |
| sensors.rs | src/api/sensors.rs | Sensors endpoints |
| weather.rs | src/api/weather.rs | Weather endpoints |
| dashboard.rs | src/api/dashboard.rs | Dashboard endpoints |
| smart_access.rs | src/api/smart_access.rs | Smart access endpoint |
| mod.rs (api) | src/api/mod.rs | API module index |
| mod.rs (utils) | src/utils/mod.rs | Utils module index |
| helpers.rs | src/utils/helpers.rs | General helper functions |
| logger.rs | src/utils/logger.rs | Logger module |
| cache.rs | src/utils/cache.rs | Cache module |
| Cargo.toml | Cargo.toml | Dependency management file |
π§© Constants & Public Functions
Constants
| Constant Name | Default Value | Defined In |
|---|---|---|
| MAX_ACCURACY_THRESHOLD | 50.0 | geo_resolver.rs |
| MIN_SIGNAL_STRENGTH | 30 | geo_resolver.rs |
| QUANTUM_SECURITY_LEVEL | 90 | geo_resolver.rs |
| MAX_HISTORY_SIZE | 100 | geo_resolver.rs |
Public Functions & Main Structs
| Function/Struct Name | Signature | Defined In | Description (English) |
|---|---|---|---|
| get_user_by_id | async fn get_user_by_id(pool, user_id) | db/crud.rs | Fetch user from DB |
| verify_smart_access | async fn verify_smart_access(...) | core/composite_verification.rs | Smart composite security check |
| process | async fn process(input: BehaviorInput) | core/behavior_bio.rs | Analyze user/device behavior |
| generate_fingerprint | async fn generate_fingerprint(os, device, env) | core/device_fp.rs | Generate adaptive device fingerprint |
| analyze | async fn analyze(provider: &dyn NetworkInfoProvider) | core/network_analyzer.rs | Analyze network & detect concealment tools |
| fetch_and_validate | async fn fetch_and_validate(lat, lng) | core/weather_val.rs | Fetch & validate weather data |
| validate | async fn validate(input: CrossValidationInput) | core/cross_location.rs | Full cross-validation |
| log_event | async fn log_event(event: &HistoryEvent) | core/history.rs | Log historical event |
| detect_timeline_anomalies | async fn detect_timeline_anomalies(entity_id, window) | core/history.rs | Detect timeline anomalies |
| check | async fn check(ip) | security/ratelimit.rs | Rate limiting check |
| sign_location | fn sign_location(location: &GeoLocation) | core/geo_resolver.rs | Digitally sign location data |
| verify_signature | fn verify_signature(location: &GeoLocation) | core/geo_resolver.rs | Verify digital signature |
| config | fn config(cfg: &mut ServiceConfig) | api/mod.rs | Register all API routes |
Main Traits
| Trait Name | Signature | Defined In | Description (English) |
|---|---|---|---|
| AiModel | trait AiModel: detect_fraud, analyze_movement, ... | core/geo_resolver.rs | AI models for geolocation |
| Blockchain | trait Blockchain: store_location, verify_location, ... | core/geo_resolver.rs | Blockchain integration |
| BehavioralModel | trait BehavioralModel: analyze | core/behavior_bio.rs | Behavioral analysis models |
| AnomalyDetector | trait AnomalyDetector: detect | core/behavior_bio.rs | Behavioral anomaly detection |
| SecurityMonitor | trait SecurityMonitor: scan_environment, ... | core/device_fp.rs | Device security monitoring |
| QuantumEngine | trait QuantumEngine: get_secure_key, ... | core/device_fp.rs | Post-quantum crypto engine |
| AiProcessor | trait AiProcessor: generate_ai_signature | core/device_fp.rs | AI processor for fingerprinting |
| NetworkInfoProvider | trait NetworkInfoProvider: get_connection_type, ... | core/network_analyzer.rs | Network info provider |
| AiNetworkAnalyzer | trait AiNetworkAnalyzer: analyze | core/network_analyzer.rs | AI network analyzer |
| SensorAnomalyDetector | trait SensorAnomalyDetector: analyze | core/sensors_analyzer.rs | Sensor anomaly detection |
| WeatherProvider | trait WeatherProvider: get_weather, ... | core/weather_val.rs | Weather data provider |
| ScoringStrategy | trait ScoringStrategy: calculate_score | core/cross_location.rs | Trust scoring strategy |
π Config & Endpoints
Environment Keys (.env / config)
| Key Name | Role | Example |
|---|---|---|
| API_KEY | Main authentication key | API_KEY=your_secret_key |
| DATABASE_URL | DB connection string | DATABASE_URL=mysql://... |
| LOG_LEVEL | Logging verbosity | LOG_LEVEL=debug |
| GEO_PROVIDER | Geolocation provider | GEO_PROVIDER=ipapi |
API Endpoints
| Path | Method | Role (English) | Defined In |
|---|---|---|---|
| /api/auth/login | POST | User login | api/auth.rs |
| /api/auth/user | GET | Fetch user data | api/auth.rs |
| /api/alerts/trigger | POST | Trigger security alert | api/alerts.rs |
| /api/geo/resolve | POST | Geolocation resolve | api/geo.rs |
| /api/device/resolve | POST | Device resolve/register | api/device.rs |
| /api/behavior/analyze | POST | Behavior analysis | api/behavior.rs |
| /api/network/analyze | POST | Network analysis | api/network.rs |
| /api/sensors/analyze | POST | Sensors data analysis | api/sensors.rs |
| /api/weather/summary | GET | Weather summary | api/weather.rs |
| /api/dashboard | GET | Dashboard summary | api/dashboard.rs |
| /api/smart_access | POST | Smart composite access check | api/smart_access.rs |
π§ Architecture
graph TD
A[main.rs π§©\nEntry] --> B[API Layer π]
A --> C[Core Engines π§ ]
A --> D[DB Layer ποΈ]
B -->|Endpoints| E[π /auth, /alerts, /users, ...]
C --> F[GeoResolver π]
C --> G[BehaviorEngine π§ ]
C --> H[DeviceFingerprint π±]
C --> I[NetworkAnalyzer ππ]
C --> J[SensorsAnalyzer π‘]
C --> K[WeatherEngine βοΈ]
C --> L[CrossValidator π]
C --> M[CompositeVerifier π‘οΈ]
C --> N[HistoryService π]
D --> O[CRUD + Models βοΈ]
B --> P[Security Layer π]
P --> Q[InputValidator π₯]
P --> R[JWT Manager π]
P --> S[Policy Engine βοΈ]
P --> T[RateLimiter π¦]
Description: The diagram shows the interaction of main units (API, core engine, DB, security layer) highlighting new engines (sensors, weather, cross-validation, history) up to the smart composite security layer.
π οΈ Verification Examples
Full Composite Security Check
let allowed_zones = vec!;
let allowed_hours = Some;
let access_granted = composite_verifier.verify_smart_access.await?;
if !access_granted
Geo Verification Only
let geo_location = geo_resolver.resolve.await?;
if let Some = &geo_location.city
Behavior Verification Only
let behavior_result = behavior_engine.process.await?;
if behavior_result.risk_level as u8 < 3 else
Device Verification Only
let device_fp = device_fp_engine.generate_fingerprint.await?;
if device_fp.security_level >= 5 else
Role Verification Only
let role_row: = exec_first.await?;
if role_row.is_some else
βοΈ Core Engine Modules
π History Service
- Description: Manages, stores, and analyzes historical events and behaviors for users/devices, with anomaly detection and DB integration.
- Key functions: log_event, get_entity_history, detect_timeline_anomalies
π Cross-Validation Engine
- Description: Advanced orchestrator combining results from verification engines (geo, behavior, device, etc.) to issue a final, signed verdict.
- Key functions: validate, sign_verdict
π‘ Sensors Analyzer
- Description: Analyzes sensor data (e.g., accelerometer, gyroscope) for anomalies/tampering, issuing a digitally signed analysis certificate.
- Key functions: analyze (SensorsAnalyzerEngine)
βοΈ Weather Validation
- Description: Aggregates and validates weather data from multiple providers, comparing results and providing unified, reliable data.
- Key functions: fetch_and_validate (WeatherEngine)
β οΈ Dependency Audit
| Dependency | Type | Direct? | Indirect? | Security/Category Notes |
|---|---|---|---|---|
| actix-web | External | Yes | No | Main web framework |
| actix-rt | External | Yes | No | Async runtime |
| ammonia | External | Yes | No | HTML sanitization |
| anyhow | External | Yes | No | Error handling |
| async-trait | External | Yes | No | Async trait support |
| config | External | Yes | No | Config management |
| futures | External | Yes | No | Async utilities |
| log | External | Yes | No | Logging |
| mysql_async | External | Yes | No | Database (MySQL) |
| tokio | External | Yes | No | Async runtime |
| uuid | External | Yes | No | UUIDs |
| aes-gcm | External | Yes | No | Advanced encryption |
| secrecy | External | Yes | No | Secure secret handling |
| zeroize | External | Yes | No | Secure memory zeroing |
| hex | External | Yes | No | Hex encoding/decoding |
| hmac | External | Yes | No | HMAC signatures |
| sha2 | External | Yes | No | SHA2 hashing |
| blake3 | External | Yes | No | BLAKE3 hashing |
| base64 | External | Yes | No | Base64 encoding |
| jsonwebtoken | External | Yes | No | JWT tokens |
| pqcrypto-mlkem | External | Yes | No | Post-quantum crypto |
| unicode-normalization | External | Yes | No | Unicode normalization |
| validator | External | Yes | No | Input validation |
| regex | External | Yes | No | Regex |
| getrandom | External | Yes | No | Random number generation |
| lru | External | Yes | No | LRU cache |
| rayon | External | Yes | No | Parallel processing |
| once_cell | External | Yes | No | One-time initialization |
| lazy_static | External | Yes | No | Static constants |
| cfg-if | External | Yes | No | Conditional compilation |
| rand | External | Yes | No | Random number generation |
| chrono | External | Yes | No | Date/time handling |
| serde_json | External | Yes | No | JSON |
| reqwest | External | Yes | No | HTTP requests (Rustls) |
| serde | External | Yes | No | Serialization |
| serde_derive | External | Yes | No | Serde derive |
| thiserror | External | Yes | No | Custom errors |
| maxminddb | External | Yes | No | GeoIP database |
| pqcrypto-traits | External | Yes | No | Post-quantum crypto traits |
| proptest | Dev | Yes | No | Property-based testing |
| rstest | Dev | Yes | No | Scenario-based testing |
| assert-json-diff | Dev | Yes | No | JSON diff assertions |
Security Notes:
- All dependencies are carefully selected, with no reliance on OpenSSL (all crypto is Rust-native or Rustls).
- All packages are up-to-date and secure as of the latest update.
- It is recommended to run
cargo auditandcargo updateregularly. - No deprecated or high-risk packages are used.
β Test Results
; ; ; ; ;
- All tests passed (35 tests).
β Features & Target Audiences
π― Library Purpose & Security Strength
- Purpose:
- To provide a comprehensive smart security verification platform for smart cities, sovereign entities, financial institutions, and technology companies, with full support for customization and integration.
- Designed to be a standard for geolocation and behavioral security in high-sensitivity environments, with scalability and easy integration into any modern system.
- Security Strength:
- The library is built on a modular, multi-layered architecture, combining geolocation verification, behavioral analytics, device fingerprinting, network analysis, tamper detection, cross-validation, and weather/sensor auditing.
- All operations are backed by advanced encryption (AES-GCM, HMAC, Post-Quantum), secure secret management (secrecy, zeroize), and digital signatures.
- No reliance on OpenSSL; only secure, modern Rust libraries are used.
- Supports smart city policies, concealment tool detection (VPN/Proxy/Tor), and provides historical logging and anomaly analysis.
π Main Features
- π Multi-source composite verification: (geo, behavior, device, network, sensors, weather).
- π§ AI integration & adaptive security: AI support and adaptive security algorithms.
- π°οΈ Advanced concealment detection: VPN/Proxy/Tor detection and advanced methods.
- ποΈ Smart city & enterprise policies: advanced zones/permissions/times support.
- β‘ Modular, flexible architecture: pluggable and customizable for any engine or logic.
- π Full English documentation: every part is fully documented in English.
- π Secret management & post-quantum crypto: secrecy and post-quantum crypto support.
- π¦ Rate limiting: built-in RateLimiter module.
- π Easy integration: REST API or direct Rust Traits.
- π Historical logging & anomaly analysis: advanced history module.
- βοΈ Weather data auditing: weather module for environmental checks.
- π‘ Sensor data analysis: supports smart device and IoT scenarios.
π€ Target Audiences
- Sovereign and Governmental Entities:
- Sovereign agencies, security sectors, command and control centers, smart cities, cybersecurity, passports, traffic, civil defense, municipalities, emergency systems.
- Financial and Banking Institutions:
- Banks, insurance companies, digital payment providers, stock exchanges.
- Large and Medium Technology Companies:
- Cloud service providers, AI companies, cybersecurity, IoT, smart city solutions.
- Transport and Logistics Companies:
- Delivery companies, smart transport, fleet management, aviation, airports.
- Healthcare Sector:
- Hospitals, digital health systems, emergency medical management.
- Education Sector:
- Universities, smart schools, secure digital exam systems.
- Identity and Access Applications:
- Access control systems, multi-factor authentication (MFA), digital identity solutions.
- Energy and Utilities Companies:
- Electricity, water, oil & gas, smart infrastructure networks.
- Industrial and Control Sector:
- Smart factories, SCADA systems, industrial robotics.
- Any developer or organization seeking modern, customizable, and integrable security solutions.
π§ Developer Guide
π Basic Integration Steps
-
Set up environment variables (.env/config):
API_KEY=your_secret_key DATABASE_URL=mysql://user:pass@host/db -
Initialize core engines in your app:
- Call public functions like:
verify_smart_access,process,generate_fingerprint
- Call public functions like:
-
Customize security logic:
- Inject your own AI model or custom verification logic via Traits
- Easily customize policies (zones, times, permissions)
-
Use API endpoints or direct Rust integration:
- Call REST API (/users/{id}, /alerts/trigger)
- Or bind functions directly in code
Quick Integration Example (Rust)
let allowed_zones = vec!;
let allowed_hours = Some; // 6 AM to 6 PM
let access_granted = composite_verifier.verify_smart_access.await?;
if !access_granted
π‘ Advanced Tips
- All engines are pluggable or replaceable
- Full customization (session/device/role)
- All examples, functions, and constants are fully documented in English