MKT_KSA_Geolocation_Security 2.0.1

Smart geolocation & behavioral security library for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
# MKT_KSA_Geolocation_Security

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

<p align="center">
  <a href="https://github.com/mktmansour/MKT-KSA-Geolocation-Security/actions/workflows/rust.yml">
    <img alt="Rust" src="https://img.shields.io/github/actions/workflow/status/mktmansour/MKT-KSA-Geolocation-Security/rust.yml?branch=main&event=push&style=for-the-badge&label=Rust" />
  </a>
  <a href="https://github.com/mktmansour/MKT-KSA-Geolocation-Security/actions/workflows/clippy.yml">
    <img alt="Clippy" src="https://img.shields.io/github/actions/workflow/status/mktmansour/MKT-KSA-Geolocation-Security/clippy.yml?branch=main&event=push&style=for-the-badge&label=Clippy" />
  </a>
  <a href="https://github.com/mktmansour/MKT-KSA-Geolocation-Security/actions/workflows/codeql.yml">
    <img alt="CodeQL" src="https://img.shields.io/github/actions/workflow/status/mktmansour/MKT-KSA-Geolocation-Security/codeql.yml?branch=main&event=push&style=for-the-badge&label=CodeQL" />
  </a>
  <a href="https://github.com/mktmansour/MKT-KSA-Geolocation-Security/actions/workflows/security-gates.yml">
    <img alt="Security Gates" src="https://img.shields.io/github/actions/workflow/status/mktmansour/MKT-KSA-Geolocation-Security/security-gates.yml?branch=main&event=push&style=for-the-badge&label=Security%20Gates" />
  </a>
</p>

<p align="center">
  <a href="https://crates.io/crates/MKT_KSA_Geolocation_Security">
    <img alt="Crates.io" src="https://img.shields.io/crates/v/MKT_KSA_Geolocation_Security.svg?style=for-the-badge" />
  </a>
  <a href="https://docs.rs/MKT_KSA_Geolocation_Security">
    <img alt="Docs.rs" src="https://img.shields.io/docsrs/MKT_KSA_Geolocation_Security?style=for-the-badge" />
  </a>
  <a href="https://crates.io/crates/MKT_KSA_Geolocation_Security">
    <img alt="Downloads" src="https://img.shields.io/crates/d/MKT_KSA_Geolocation_Security.svg?style=for-the-badge" />
  </a>
  <img alt="License" src="https://img.shields.io/badge/license-Apache--2.0-0A66C2?style=for-the-badge" />
  <img alt="Edition" src="https://img.shields.io/badge/edition-2021-0A66C2?style=for-the-badge" />
  <img alt="Made in Saudi Arabia" src="https://img.shields.io/badge/Made%20in-Saudi%20Arabia-006C35?style=for-the-badge" />
</p>

![MKT KSA Geolocation Security Cover](docs/images/mkt_ksa.png)

<table align="center">
  <tr>
    <td align="center">
      <img alt="Documentation Style" src="https://img.shields.io/badge/Documentation-Engineering%20Grade-0A66C2?style=for-the-badge" />
    </td>
    <td align="center">
      <img alt="Release Baseline" src="https://img.shields.io/badge/Stable_Baseline-v2.0.1-0077B6?style=for-the-badge" />
    </td>
  </tr>
  <tr>
    <td align="center" colspan="2">
      <img alt="Security Mode" src="https://img.shields.io/badge/Security-Maintenance%20Mode-005A8D?style=for-the-badge" />
    </td>
  </tr>
</table>

> [!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](docs/images/banners/section-08.svg)

### 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](docs/images/2026mkt.png)

## Community Note

![Community Signal](https://img.shields.io/badge/Community-Feedback%20Loop-0A66C2?style=for-the-badge)

[![Crates Downloads](https://img.shields.io/crates/d/MKT_KSA_Geolocation_Security.svg?style=for-the-badge)](https://crates.io/crates/MKT_KSA_Geolocation_Security)
[![GitHub Stars](https://img.shields.io/github/stars/mktmansour/MKT-KSA-Geolocation-Security?style=for-the-badge)](https://github.com/mktmansour/MKT-KSA-Geolocation-Security/stargazers)

- 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]https://github.com/mktmansour/MKT-KSA-Geolocation-Security/issues/50
- Write comments and integration feedback: [Issue #50]https://github.com/mktmansour/MKT-KSA-Geolocation-Security/issues/50

## Contents

- 🛡️ [0. Release Safety Advisory]#0-release-safety-advisory
- 🎯 [1. What This Project Does]#1-what-this-project-does
- 🧭 [1.1 Project Goal]#11-project-goal
-[1.2 Key Features]#12-key-features
- 🏛️ [1.3 Target Audiences]#13-target-audiences
- 🔐 [2. Runtime and Security Posture]#2-runtime-and-security-posture
- 🗂️ [3. Complete Repository Role Map]#3-complete-repository-role-map
- 🔄 [4. Module Interactions and Control Flow]#4-module-interactions-and-control-flow
- 🧱 [4.1 Project Architecture Diagram]#41-project-architecture-diagram
- 🌐 [5. API Reference and Invocation]#5-api-reference-and-invocation
- ⚙️ [6. Environment Variables]#6-environment-variables
- 🧪 [7. Build, Run, and Validate]#7-build-run-and-validate
- 🛠️ [8. Current Hardening and Fix History]#8-current-hardening-and-fix-history
- 🔌 [9. Library Integration and C-ABI]#9-library-integration-and-c-abi
- 📚 [10. Detailed Folder and File Responsibilities]#10-detailed-folder-and-file-responsibilities
- 🧠 [11. Deep SRC Engineering Review]#11-deep-src-engineering-review
- 👨‍💻 [12. Developer Guide]#12-developer-guide
- 🤖 [13. AI and Intelligence Role]#13-ai-and-intelligence-role

## Project Wiki (Bilingual)

- English Wiki Home: [docs/wiki/en/Home.md]docs/wiki/en/Home.md
- Arabic Wiki Home: [docs/wiki/ar/Home.md]docs/wiki/ar/Home.md
- Wiki Source Index: [docs/wiki/README.md]docs/wiki/README.md

## 1. What This Project Does

![Section 01 Banner](docs/images/banners/section-01.svg)

`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](docs/images/banners/section-02.svg)

- 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](docs/images/banners/section-03.svg)

### 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](docs/images/banners/section-04.svg)

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
5. Handler calls the relevant core engine or DB layer.
6. Response is returned as JSON (or HTTP error with strict status semantics).

### 4.1 Project Architecture Diagram

![Project Architecture Diagram](docs/images/project-architecture.svg)

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

```mermaid
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](docs/images/banners/section-05.svg)

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:

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

Geo resolve:

```bash
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:

```bash
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:

```bash
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:

```bash
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:

```bash
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:

```bash
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:

```bash
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:

```bash
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](docs/images/banners/section-06.svg)

| 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](docs/images/banners/section-07.svg)

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

Run:

```bash
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](docs/images/banners/section-08.svg)

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](docs/images/banners/section-09.svg)

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:

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

Build shared library:

```bash
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](docs/images/banners/section-10.svg)

### `.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](docs/images/banners/section-11.svg)

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

### 11.1 SRC responsibility map

<div align="center">

| 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 |

</div>

### 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.

```mermaid
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](docs/images/banners/section-11-request.svg)

- 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.

```mermaid
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](docs/images/banners/section-11-trust.svg)

- 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.

```mermaid
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](docs/images/banners/section-11-storage.svg)

- Owns schema evolution through migrations.
- Implements async CRUD for runtime endpoints.
- Isolated boundary for alert/user persistence behavior.

```mermaid
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](docs/images/banners/section-11-security.svg)

- JWT generation/validation and claims checks.
- Per-IP rate-limiting and abuse throttling.
- Input validation/sanitization and policy guards.
- Secret wrapping and signature verification.

```mermaid
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.

```mermaid
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](docs/images/banners/section-12.svg)

### 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

```bash
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](docs/images/banners/section-13.svg)

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

```mermaid
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`.