# TANRAIL ONE — PHASE 5.5
# PRE-IMPLEMENTATION SECURITY AUDIT

## 1. Current Architecture
The system consists of the Production Management and Event Management modules, integrated with the Inventory and Financial/GL core (Phases 1-4).
- Production Management handles Bill of Materials (BOM) and Production Orders.
- Event Management handles Event Bookings, Packages, Attendees, and Invoicing.
- Tenant isolation is primarily enforced globally via `OrganizationScope` and `BusinessUnitScope` injected by `ContextManager`.
- Authorization is handled by Policies (`BillOfMaterialsPolicy`, `ProductionOrderPolicy`, `EventBookingPolicy`) mapping to domain capabilities via `$user->hasAccessToScope()`.

## 2. Existing Security Controls
- **Global Scopes:** Database queries automatically append `organization_id` or `business_unit_id` conditions via booted global scopes.
- **Pessimistic Locking:** `ProductionService` and `EventBookingService` use `lockForUpdate()` during critical state transitions (e.g., `completeProduction`, `confirmBooking`) to prevent race conditions.
- **Idempotent Invoicing:** `EventBookingService` uses `ProcessedEvent::process()` to ensure deposit and final invoices are not duplicated.
- **Tenant Authorization:** Policies check `$user->hasAccessToScope()` before permitting actions on specific records.

## 3. Phase 5.1–5.4 Security Surface
The exposed surface includes:
- **Models:** `BillOfMaterials`, `BillOfMaterialsItem`, `ProductionOrder`, `ProductionOrderItem`, `EventBooking`, `EventBookingPackage`, `EventBookingAttendee`.
- **Services:** `BillOfMaterialsService`, `ProductionService`, `EventBookingService`.
- **Policies:** `BillOfMaterialsPolicy`, `ProductionOrderPolicy`, `EventBookingPolicy`.

## 4. Identified Vulnerabilities/Weaknesses
1. **Cross-Tenant / Cross-BU Reference Attack in Production:**
   - `ProductionService::createProductionOrder` does NOT validate that `$sourceLocation` and `$destinationLocation` belong to the same Organization/Business Unit as the Production Order.
2. **Cross-Tenant Reference Attack in Event Bookings:**
   - `EventBookingService::addPackage` validates `$itemBu->organization_id` but does NOT validate Business Unit isolation if required, and may fail open if `$itemBu` is null or if TaxCategory org validation allows different BUs.
3. **Privilege Escalation (Roleless / Any Role):**
   - Policies (`BillOfMaterialsPolicy`, `ProductionOrderPolicy`, `EventBookingPolicy`) authorize actions (like `create`, `confirm`, `complete`) simply by verifying if the user has *any* access to the tenant (`hasAccessToScope`). They do NOT verify specific granular permissions/capabilities (e.g., `manage-production` or `manage-events`). Thus, a read-only user in a BU can complete production orders.
4. **Immutability Bypass in Production:**
   - `ProductionOrderPolicy::update` does not check the status of the order. Unlike `EventBookingPolicy::update`, which blocks updates to `COMPLETED` or `CANCELLED` bookings, an attacker can push an update to a `COMPLETED` `ProductionOrder`.
5. **Cross-Tenant Item Association:**
   - `BillOfMaterialsService::addItem` checks `$ingredientBu->organization_id !== $bom->organization_id`, but ignores BU-level isolation for items.

## 5. Attack Vectors
- **Inventory Theft (Cross-Tenant):** An attacker in Org A creates a `ProductionOrder` passing a `source_location_id` belonging to Org B. When they complete the order, `ProductionService` deducts stock from Org B's location and adds finished goods to Org A's location.
- **State Mutation (Immutability):** An attacker modifies the target quantity of a `COMPLETED` `ProductionOrder` because `ProductionOrderPolicy::update` lacks state-checks.
- **Privilege Escalation:** An unprivileged user (e.g., a basic clerk) calls `confirmBooking` or `completeProduction` because policies only check tenant membership, not specific role capabilities.

## 6. Required Changes
1. **Services:**
   - Add explicit tenant and BU checks for `InventoryLocation` in `ProductionService`.
   - Add explicit tenant and BU checks for `Item` and `TaxCategory` in `EventBookingService`.
   - Add explicit tenant and BU checks for `Item` in `BillOfMaterialsService`.
2. **Policies:**
   - Inject granular capability/permission checks (e.g., `hasPermission('manage-production')`) rather than just `hasAccessToScope`.
   - Update `ProductionOrderPolicy::update` to reject updates on `COMPLETED` and `CANCELLED` orders.
3. **Tests:**
   - Create `Phase55SecurityHardeningTest.php` to maliciously test cross-tenant location injection, privilege escalation, and immutability bypasses.

## 7. Files that will be modified
- `app/Domains/Modules/Production/Services/ProductionService.php`
- `app/Domains/Modules/Production/Services/BillOfMaterialsService.php`
- `app/Domains/Modules/EventManagement/Services/EventBookingService.php`
- `app/Domains/Modules/Production/Policies/ProductionOrderPolicy.php`
- `app/Domains/Modules/Production/Policies/BillOfMaterialsPolicy.php`
- `app/Domains/Modules/EventManagement/Policies/EventBookingPolicy.php`
- `tests/Feature/Modules/Phase55SecurityHardeningTest.php` (New)

## 8. Files that must NOT be modified
- Accounting Core Services (`InvoiceService`, `GLService`)
- Inventory Core Services (`InventoryService`)
- Base models and global scopes (`OrganizationScope`, `BusinessUnitScope`)

## 9. Database Impact
- None. The audit proves the schema is sound. Security deficiencies reside purely in the Service validation and Policy authorization layers.

## 10. GL/Accounting Impact
- Unchanged. Financial posting relies on `InventoryService` and `InvoiceService` which remain properly encapsulated. Idempotency is verified.

## 11. Inventory Impact
- Unchanged structurally, but security will be hardened by preventing cross-tenant location access in the Production Service.

## 12. Tenant-Isolation Strategy
- Validate all incoming Eloquent models (Locations, Items, TaxCategories, Customers) in Services against the parent record's `organization_id` and `business_unit_id` BEFORE executing any business logic.

## 13. Authorization Strategy
- Fail closed. 
- Restrict `update` and `delete` operations on finalized entities (`COMPLETED`, `CANCELLED`).
- Verify if the domain exposes explicit permissions to replace `hasAccessToScope()` for privileged actions (to be analyzed during implementation).

## 14. Test Strategy
- **Adversarial Testing:** Attempt cross-tenant ID injection for every relationship in `ProductionService` and `EventBookingService`.
- **Immutability Testing:** Attempt updates and deletions on completed records.
- **Privilege Testing:** Attempt state transitions with roleless or cross-BU users.

## 15. Risk Assessment
- **High:** The current lack of location-validation in Production could allow cross-tenant inventory destruction if an attacker enumerates location IDs.
- **High:** Immutability bypass in Production Orders allows historical tampering.
- **Mitigation:** The proposed changes comprehensively seal these vectors without breaking existing Phase 1-4 contracts.

## 16. Exact Implementation Sequence
1. Implement Adversarial Test Suite (`Phase55SecurityHardeningTest.php`) - watch it fail.
2. Harden `ProductionService` (Location validations).
3. Harden `EventBookingService` (Item/Tax validations).
4. Harden `BillOfMaterialsService` (Item validations).
5. Harden `ProductionOrderPolicy` (Immutability checks).
6. Run baseline tests to verify fixes.

## 17. Final Authorization Gate
Ready for implementation pending human authorization.
