🔒 API Security, Multi-Tenant Isolation & Abuse Prevention
The RBOS (Raj Astrology Operating System) implements defense-in-depth security architectures to guarantee tenant isolation, prevent API key abuse, protect proprietary astrological algorithms, and ensure data integrity.
1. User Roles & Permission Matrix
RBOS enforces a strict role-based access control (RBAC) and subscription tier model:
| Role / Tier | Identifier | Daily UI Calculations | API Call Limit | 20-Section Life Report | Developer Tools Access |
|---|---|---|---|---|---|
| Guest / Public | guest |
0 (Must register) | 0 (Must register) | No Access | Blocked |
| Free Registered Tier | normal |
5 Free Calls / Day | Included with key | Masked Preview (Locks sensitive chapters) | Blocked (403 Forbidden) |
| 1-Year Premium | normal_yearly |
Unlimited | Unlimited | Full Unmasked Access | Blocked (403 Forbidden) |
| Astrologer Pack | astrologer_pack |
1,000 Credits | 1,000 Credits | Full Unmasked Access | Blocked (403 Forbidden) |
| Pay-As-You-Go | single_* |
Per-Report Purchase | Per-Report Purchase | Full Access for Purchased Types | Blocked (403 Forbidden) |
| Developer / Admin | developer |
Unlimited | Unlimited | Full Unmasked Access | Full Access (engine-analysis.php, knowledge_curator.php) |
2. API Key Architecture & Anti-Theft Whitelisting
Team Key Provisioning
Every registered user can generate multiple API keys (e.g. for development, staging, production, or mobile applications):
- Keys are prefixed with
sk_live_followed by cryptographically secure random bytes:sk_live_a164bed146752093d977e564b30bce022 - Raw keys are displayed only once upon generation. The database stores only the irreversible SHA-256 hash: $$\text{StoredHash} = \text{SHA-256}(\text{RawKey})$$
- Key previews in dashboard tables are masked (e.g.
sk_live_a164...e022).
Anti-Theft Domain Whitelisting
To prevent client-side API key theft from web browser applications, each API key can be restricted to specific domain origins:
- Exact Domain Matching:
app.clientdomain.com - Subdomain Wildcards:
*.clientdomain.com(allowsapi.clientdomain.com,admin.clientdomain.com) - Multi-Domain Lists:
app.clientdomain.com, staging.clientdomain.com, localhost - Open Wildcard:
*(Recommended only for server-side / backend daemon integration)
When a request arrives, ApiMiddleware::validateDomain() inspects the HTTP_ORIGIN and HTTP_REFERER headers. If the origin is not whitelisted, the request is terminated with:
{
"status": "error",
"code": 403,
"error": "Domain Unauthorized: Origin 'https://unauthorized-origin.com' is not in the allowed domains list for this API Key. Update allowed domains in your dashboard."
}
3. Threat Vector Analysis & Backend Defenses
[ Incoming Request ]
│
┌───────────────┴───────────────┐
▼ ▼
[ Web UI Request ] [ REST API Request ]
│ │
CSRF Token Validation API Key Hash Verification
│ │
Session Authenticated? Domain Whitelist Verification
│ │
Role / Privilege Check Sliding Window Rate Limiter
│ │
Daily Usage / Mask Check Tier Endpoint Permission Check
│ │
└───────────────┬───────────────┘
▼
[ Core Engine Execution ]
1. Denial of Service & Rate Limiting (APCu Sliding Window)
- Threat: Malicious scripts bursting 1,000 requests per second to exhaust ephemeris computation threads.
- Defense: An in-memory APCu sliding window tracks per-second request density. Requests exceeding 20 requests per second are rejected with HTTP 429 Too Many Requests:
{ "status": "error", "code": 429, "error": "Rate Limit Exceeded: Maximum 20 requests per second." }
2. Insecure Direct Object References (IDOR)
- Threat: User
Aattempts to revoke or tamper with domain whitelists of an API key belonging to UserBby sending modifiedkey_idvalues in POST requests. - Defense: All database update and revocation queries enforce tenant ownership at the SQL layer:
UPDATE api_keys SET is_active = 0 WHERE id = :key_id AND user_id = :authenticated_user_id; UPDATE api_keys SET allowed_domains = :domains WHERE id = :key_id AND user_id = :authenticated_user_id;If the key does not belong to the active session user, zero rows are affected and the action fails cleanly.
3. Cross-Site Request Forgery (CSRF)
- Threat: A malicious third-party site forces an authenticated user's browser to submit key generation or revocation forms.
- Defense: All state-modifying requests in
dashboard.phprequire a cryptographically secure random token:if (empty($_SESSION['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) { $_SESSION['error'] = 'CSRF validation failed. Please refresh and try again.'; header('Location: dashboard.php'); exit; }
4. Cross-Site Scripting (XSS)
- Threat: Injecting
<script>window.pwned=true;</script>into the Key Name or Domain fields to trigger stored XSS when the dashboard loads. - Defense: All rendered strings are strictly filtered with context-aware entity escaping:
htmlspecialchars($k['key_name'], ENT_QUOTES, 'UTF-8')
5. SQL Injection (SQLi)
- Threat: Supplying
' OR '1'='1or'; DROP TABLE users; --in input forms. - Defense: 100% of database interactions use PDO prepared statements with bound parameters (
?or:named). Unsanitized raw string concatenation into SQL statements is prohibited.
6. Privilege Escalation & Developer Tool Barriers
- Threat: Non-developer accounts navigating directly to internal technical audit tools (
engine-analysis.php,knowledge_curator.php). - Defense: Server-side verification immediately terminates unprivileged access with HTTP 403 Forbidden:
if (($_SESSION['user_role'] ?? '') !== 'developer') { http_response_code(403); echo "403 Forbidden: Access restricted to Developer / Admin role."; exit; }
7. Proprietary Report Content Protection (Masking)
- Threat: Free users attempting to view unmasked 20-Section consultative predictions without paying.
- Defense:
Subscription::checkAccess($userId, '20_section')verifies whether an active yearly subscription or single-report purchase exists in the database. If not,is_masked: trueis enforced, substituting sensitive astrological interpretations with locked preview tokens (🔒) and an upgrade call-to-action.
8. Immediate Revocation Enforcement
- Threat: Using an API key after clicking "Revoke" in the dashboard.
- Defense: Revocation instantly writes
is_active = 0.ApiKey::validate()performs an active check (!$row['is_active']) on every request, eliminating any grace period window.
9. Client-Side Account History Isolation
- Threat: Multiple users sharing a single workstation seeing each other's generated consultation reports.
- Defense: The client-side history storage key is scoped strictly to the authenticated user ID:
const storageKey = 'rbos_saved_reports_' + window.RBOS_USER_ID;A new user starts with an empty array
[]and cannot access reports generated by previous users on the same machine.
4. Automated Security Test Coverage
The RBOS test architecture includes dedicated automated test suites validating security controls:
PHPUnit Security Test Suite
Path: engine/tests/Security/Santhoshr96SecurityAndAbuseTest.php
./engine/vendor/bin/phpunit engine/tests/Security/Santhoshr96SecurityAndAbuseTest.php
- Test 01: Profile & Role Isolation (
role === 'normal'). - Test 02: Free Registered Plan fallback verification.
- Test 03: Report Masking Enforcement (
is_masked: true,access_type: 'free_tier'). - Test 04: Valid API Key Resolution.
- Test 05: Attack — Revoked Key Immediate Lockout.
- Test 06: Attack — IDOR: Attempting to Revoke Another User's API Key.
- Test 07: Attack — IDOR: Attempting to Hijack Domains of Another User's Key.
- Test 08: Anti-Theft Domain Whitelist Enforcement.
- Test 09: Subdomain Wildcard Acceptance (
*.domain.inmatchesapi.domain.in). - Test 10: Attack — SQL Injection in Key Name Creation.
- Test 11: Attack — Stored XSS Payload in Key Name.
- Test 12: Sliding Window Rate Limiting Protection (Max 20 req/s).
Playwright UI & Browser Attack Suite
Path: testing/e2e/santhoshr96_attacks.spec.js
npx playwright test testing/e2e/santhoshr96_attacks.spec.js --reporter=list
- Test 01: Authentic Login & Baseline Free Tier Verification.
- Test 02: Permanent Report Generator Launch Palette Always Visible.
- Test 03: Attack — Privilege Escalation to Developer Tools via Direct URL (
403 Forbidden). - Test 04: Attack — Stored XSS Injection in Key Name (
<script>not executed). - Test 05: Attack — SQL Injection in Domain Whitelist Form.
- Test 06: Attack — CSRF Request Tampering on API Key Operations.
- Test 07: Attack — IDOR Cross-Tenant Key Revocation Attempt.
- Test 08: Attack — Anti-Theft Domain Bypass via REST API.
- Test 09: Attack — Unmasked Premium Report Masking Enforcement (
🔒lock CTA). - Test 10: Attack — Prashna Seed Out-of-Bounds Validation (
min="1",max="249"). - Test 11: Attack — Rectification Search Window Constraints.
- Test 12: Scoped LocalStorage Isolation for User Account.
5. Security Best Practices for API Consumers
- Keep Secret Keys Private: Never commit raw API keys to public source code repositories or client-side bundles without domain whitelists.
- Restrict Allowed Domains: For browser-based applications, always configure specific origin domains in your dashboard rather than using the open wildcard (
*). - Use Dedicated Keys per Environment: Generate separate API keys for Development, Staging, and Production so compromised staging credentials can be revoked without disrupting production systems.
- Implement Client-Side Backoff: Handle HTTP 429 status codes with exponential backoff if executing burst calculations.