| Crates.io | MKT_KSA_Geolocation_Security |
| lib.rs | MKT_KSA_Geolocation_Security |
| version | 1.0.2 |
| created_at | 2025-08-06 23:06:15.744408+00 |
| updated_at | 2026-01-25 16:30:21.261538+00 |
| description | Smart geolocation & behavioral security library for Rust |
| homepage | |
| repository | https://github.com/mktmansour/MKT-KSA-Geolocation-Security |
| max_upload_size | |
| id | 1784425 |
| size | 570,818 |
Ω ΩΨͺΨ¨Ψ© Ψ§ΩΨͺΨΩΩ Ψ§ΩΨ¬ΨΊΨ±Ψ§ΩΩ ΩΨ§ΩΨ£Ω ΩΩ Ψ§ΩΨ³ΨΉΩΨ―Ω Ψ§ΩΨ°ΩΩΨ© β MKT KSA πΈπ¦ Smart Saudi Geolocation & Security Library
π Rust | π°οΈ Smart Security | ποΈ Smart City Ready | π Apache 2.0 | Developed by Mansour Bin Khalid (KSA πΈπ¦)
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.
| 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 |
| precision.rs | src/utils/precision.rs | Precision utilities (time/numeric/geospatial) |
| 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 |
| signing.rs | src/security/signing.rs | High-security signing (HMAC) utilities |
| Cargo.toml | Cargo.toml | Dependency management file |
| 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 |
| 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 |
| Function Name | Signature | Defined In | Description |
|---|---|---|---|
| sign_hmac_sha512 | fn sign_hmac_sha512(data: &[u8], key: &SecureBytes) -> Result<Vec |
src/security/signing.rs | HMAC-SHA512 signature over bytes |
| verify_hmac_sha512 | fn verify_hmac_sha512(data: &[u8], sig: &[u8], key: &SecureBytes) -> bool | src/security/signing.rs | Verifies HMAC-SHA512 |
| sign_hmac_sha384 | fn sign_hmac_sha384(data: &[u8], key: &SecureBytes) -> Result<Vec |
src/security/signing.rs | HMAC-SHA384 signature |
| verify_hmac_sha384 | fn verify_hmac_sha384(data: &[u8], sig: &[u8], key: &SecureBytes) -> bool | src/security/signing.rs | Verifies HMAC-SHA384 |
| sign_struct_excluding_field | fn sign_struct_excluding_field<T: Serialize>(value: &T, exclude_field: &str, key: &SecureBytes) -> Result<Vec |
src/security/signing.rs | Sign serializable struct excluding one field |
| verify_struct_excluding_field | fn verify_struct_excluding_field<T: Serialize>(value: &T, exclude_field: &str, sig: &[u8], key: &SecureBytes) -> bool | src/security/signing.rs | Verify serializable struct excluding field |
| Function Name | Signature | Defined In | Description |
|---|---|---|---|
| time_delta_secs | fn time_delta_secs(start: DateTime |
src/utils/precision.rs | Time delta in seconds (with negative guard) |
| time_delta_secs_high_res | fn time_delta_secs_high_res(start: DateTime |
src/utils/precision.rs | High-resolution time delta (secs + nanos) |
| avg_f32 | fn avg_f32(values: &[f32]) -> f32 | src/utils/precision.rs | f32 average using internal f64 accumulation |
| haversine_km | fn haversine_km(a: (f64, f64), b: (f64, f64)) -> f64 | src/utils/precision.rs | Haversine distance in kilometers |
| speed_kmh | fn speed_kmh(distance_km: f64, seconds: f64) -> f64 | src/utils/precision.rs | Speed (km/h) with division-by-zero guard |
| weighted_sum_f64 | fn weighted_sum_f64(values: &[f64], weights: &[f64]) -> Option |
src/utils/precision.rs | Weighted sum (f64), None if lengths mismatch |
| rate_of_change_f64 | fn rate_of_change_f64(value_delta: f64, seconds: f64) -> f64 | src/utils/precision.rs | Rate of change per second with zero-division guard |
| 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 |
| Key Name | Role | Example |
|---|---|---|
| API_KEY | Main authentication key | API_KEY=your_secret_key |
| JWT_SECRET | JWT signing/verification secret | JWT_SECRET=32+_chars_secret |
| DATABASE_URL | DB connection string | DATABASE_URL=mysql://... |
| LOG_LEVEL | Logging verbosity | LOG_LEVEL=debug |
| GEO_PROVIDER | Geolocation provider | GEO_PROVIDER=ipapi |
| 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 |
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.
let allowed_zones = vec!["Riyadh".to_string(), "Jeddah".to_string()];
let allowed_hours = Some((6, 18));
let access_granted = composite_verifier.verify_smart_access(
geo_input, // (Option<IpAddr>, Option<(f64, f64, u8, f64)>)
behavior_input, // BehaviorInput
(os, device, env), // (&str, &str, &str)
&allowed_zones,
allowed_hours,
).await?;
if !access_granted {
// Deny access or log suspicious attempt
}
let geo_location = geo_resolver.resolve(Some(ip), Some(gps), None, None, None, None, None).await?;
if let Some(city) = &geo_location.city {
if allowed_zones.contains(city) {
// Geo verification successful
} else {
// Access denied due to location
}
}
let behavior_result = behavior_engine.process(behavior_input).await?;
if behavior_result.risk_level as u8 < 3 {
// Low risk behavior
} else {
// Medium or high risk behavior
}
let device_fp = device_fp_engine.generate_fingerprint(os, device, env).await?;
if device_fp.security_level >= 5 {
// Device is trusted
} else {
// Device is not trusted
}
let role_row: Option<Row> = mysql_async::prelude::Queryable::exec_first(
&mut conn, "SELECT role FROM user_roles WHERE user_id = ? AND role = ?",
(user_id.to_string(), "admin"),
).await?;
if role_row.is_some() {
// User has required role
} else {
// User lacks required role
}
| 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 | No | Yes | Random number generation (via rand::OsRng) |
| 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 |
Stability Notes (Update):
anyhow to 1.0.99.base64 0.22.1, lru 0.16.0, maxminddb 0.26.0, reqwest 0.12.22, thiserror 2.0.12, uuid 1.18.0.categories and keywords in Cargo.toml.JWT_SECRET for JWT instead of a hardcoded value.Security Notes:
cargo audit and cargo update regularly.running 35 tests
... all tests passed ...
test result: ok. 35 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 1.04s
$env:CARGO_HOME and $env:RUSTUP_HOME configured.cargo check successful.cargo test fully passing (35/35) after making a time-dependent test deterministic using a fixed timestamp, with no logic changes.cargo fmt --check clean.cargo clippy shows only non-critical warnings (unused imports/variables and style suggestions), no behavior changes.cargo audit reports no known vulnerabilities.RateLimiter module exists and is intentionally disabled by default pending later decision.base64 (0.22), getrandom (0.3), lru (0.16), maxminddb (0.26), rand (0.9), reqwest (0.12), rstest (0.26), secrecy (0.10), thiserror (2).audit/clippy/fmt after each stage.zeroize and secret wrappers.check, test, fmt, clippy, audit.Set up environment variables (.env/config):
API_KEY=your_secret_key
DATABASE_URL=mysql://user:pass@host/db
Initialize core engines in your app:
verify_smart_access, process, generate_fingerprintCustomize security logic:
Use API endpoints or direct Rust integration:
let allowed_zones = vec!["Riyadh".to_string(), "Jeddah".to_string()];
let allowed_hours = Some((6, 18)); // 6 AM to 6 PM
let access_granted = composite_verifier.verify_smart_access(
geo_input,
behavior_input,
device_info,
&allowed_zones,
allowed_hours,
).await?;
if !access_granted {
// Deny access or log suspicious attempt
}
Cargo.toml like this:toml
| Feature Name | Description |
|---|---|
adaptive |
Enables AI-driven adaptive behavior analysis. |
ar_integration |
Integrates Augmented Reality (AR) sources for enhanced location validation. |
autonomous_vehicles |
Activates modules designed for autonomous cars and smart fleet systems. |
blockchain |
Supports blockchain-based authentication and data anchoring. |
generative_ai |
Uses generative AI models to dynamically generate and adjust security policies. |
gpu |
Enables GPU acceleration for heavy analysis (e.g. sensor or network data). |
predictive |
Adds predictive modeling and anomaly detection based on behavioral patterns. |
quantum |
Activates modules compatible with post-quantum cryptography. |
quantum_computing |
Enables integrations with quantum computing backends and processors. |
v1_1 |
Enables compatibility with API version 1.1 for legacy support. |
v2_0 |
Enables compatibility with API version 2.0 (default for most modules). |
v3_0 |
Enables next-gen modules for upcoming API version 3.0. |
zkp |
Adds support for Zero-Knowledge Proofs for privacy-preserving validation and access control. |
## π¦ Using as a Rust library
```toml
[dependencies]
MKT_KSA_Geolocation_Security = "1.0.2" # import path in Rust: mkt_ksa_geo_sec
# Or from Git:
# MKT_KSA_Geolocation_Security = { git = "https://github.com/mktmansour/MKT-KSA-Geolocation-Security" }
use mkt_ksa_geo_sec::core::geo_resolver::{
GeoResolver, DefaultAiModel, DefaultBlockchain, GeoReaderEnum, MockGeoReader,
};
use mkt_ksa_geo_sec::security::secret::SecureBytes;
use std::sync::Arc;
let resolver = GeoResolver::new(
SecureBytes::new(vec![1; 32]),
Arc::new(DefaultAiModel),
Arc::new(DefaultBlockchain),
true,
false,
Arc::new(GeoReaderEnum::Mock(MockGeoReader::new())),
);
Note: The Rust import path is mkt_ksa_geo_sec.
cdylib/staticlib and consumable from C/C++/Python/.NET/Java/Go.generate_adaptive_fingerprint(os: *const c_char, device_info: *const c_char, env_data: *const c_char) -> *mut c_charfree_fingerprint_string(ptr: *mut c_char)Generated header filename: mkt_ksa_geo_sec.h.
Minimal C usage:
// header generated via cbindgen
char* fp = generate_adaptive_fingerprint("Windows", "LaptopX", "Office");
printf("%s\n", fp);
free_fingerprint_string(fp);
-D warnings across all targets; zero warnings remain.let-else where suitable.#[allow(...)] only when changing code would risk public API/behavior.# Errors/# Panics documentation in critical Result-returning functions.unused_async/unused_self for internal/experimental functions.rust-ini (yanked) via config; non-functional impact (transitive only); documented for future review.once_cell, lazy_static: replaced by std::sync::LazyLock.serde_derive: redundant since serde enables derive feature.getrandom (direct): removed as a direct dependency; switched to rand::rngs::OsRng::try_fill_bytes for secure randomness.reqwest: 0.12.22 β 0.12.23 (Rustls; minor patches).pqcrypto-mlkem: 0.1.0 β 0.1.1.secrecy: 0.8.x β 0.10.3. Introduced internal wrappers security::secret::{SecureString, SecureBytes} to abstract breaking API changes. All call sites updated with no behavior/security change.async-trait, hyper, thiserror, and others auto-updated within constraints.src/security/signing.rs: Central high-security HMAC signing module (no OpenSSL).src/utils/precision.rs: Precision utilities for time/numeric/geospatial calculations.src/api/*.rs):
HttpRequest to extractors: web::Data<AppState>, web::Json<...>, and BearerToken to ensure Send-safe futures and cleaner handler signatures.src/core/geo_resolver.rs):
resolve now takes a ResolveParams struct instead of many positional args; all call sites updated.src/core/behavior_bio.rs):
get_user_profile_data is now synchronous (removed async as there was no await); updated call in src/api/auth.rs (removed .await).src/core/device_fp.rs):
unsafe extern "C" with # Safety docs, preserving implementation logic.secrecy::Secret/SecretVec usages migrated to security::secret::{SecureString, SecureBytes}.cargo fmt --all to fix minor formatting diffs reported by --check.cargo tree -d shows acceptable transitive duplicates at present: base64 (0.21/0.22), http (0.2/1.x), lru (0.14/0.16), hashbrown (0.14/0.15), socket2 (0.5/0.6), windows-sys (0.52/0.59).pub async fn trigger_alert(
payload: web::Json<AlertTriggerRequest>,
bearer: BearerToken,
) -> impl Responder;
pub async fn analyze_behavior(
app_data: web::Data<AppState>,
payload: web::Json<BehaviorAnalyzeRequest>,
bearer: BearerToken,
) -> impl Responder;
pub async fn dashboard_summary(bearer: BearerToken) -> impl Responder;
pub async fn resolve_device(
app_data: web::Data<AppState>,
payload: web::Json<DeviceResolveRequest>,
bearer: BearerToken,
) -> impl Responder;
pub async fn resolve_geo(
app_data: web::Data<AppState>,
payload: web::Json<GeoResolveRequest>,
bearer: BearerToken,
) -> impl Responder;
pub async fn analyze_network(
app_data: web::Data<AppState>,
payload: web::Json<NetworkAnalyzeRequest>,
bearer: BearerToken,
) -> impl Responder;
pub async fn analyze_sensors(
app_data: web::Data<AppState>,
payload: web::Json<SensorsAnalyzeRequest>,
bearer: BearerToken,
) -> impl Responder;
pub async fn weather_summary(
_payload: web::Json<WeatherSummaryRequest>,
bearer: BearerToken,
) -> impl Responder;
impl GeoResolver {
pub async fn resolve(
&self,
params: ResolveParams,
) -> Result<GeoLocation, GeoResolverError>;
}
impl UserService {
pub fn get_user_profile_data(
&self,
_requester_id: Uuid,
_target_user_id: Uuid,
) -> Result<User, BehaviorError>;
}
pub unsafe extern "C" fn generate_adaptive_fingerprint(
os: *const c_char,
device_info: *const c_char,
env_data: *const c_char,
) -> *mut c_char;
pub unsafe extern "C" fn free_fingerprint_string(ptr: *mut c_char);