# INVEETAIRE
## SPRINT 2 EXECUTION GUIDE

| Field | Value |
|-------|-------|
| Document Type | Execution Guide |
| Sprint | Sprint 2 — Authentication & Authorization |
| Version | 1.0 (Final) |
| Status | Active |
| Framework Baseline | commit `6616264` · tags `sprint1-baseline`, `framework-v1.1` |
| Based On | AI.md v1.1 · AI_DEVELOPMENT_SYSTEM.md v1.0 · WORKFLOW.md · DBP v1.1 · SPRINT2_PLANNING.md |
| Applies To | All AI Implementation Agents and Human Approvers contributing to Sprint 2 |

> This document is the operational handbook for Sprint 2 execution. It complements — and does not replace — the governance and planning documents. Any AI Implementation Agent must follow this guide from a cold start with no prior session context.

---

## 1. Purpose

This guide defines **how** Sprint 2 is executed. It translates the approved architecture, governance rules, and sprint plan into a concrete, step-by-step operational workflow that any AI Implementation Agent can follow immediately.

Sprint 2 focuses on establishing the secure boundary of the Inveetaire application:
1. **Unified Authentication** — enabling secure authentication for couples, event crew, and platform operators.
2. **Access Control Middleware** — enforcing route guards and role permissions so that each authenticated user can only view their designated resources.
3. **Session Timeout Policy** — protecting workspaces against hijacking via universal inactivity timeouts and role-specific absolute timeout limits.

---

## 2. Sprint 2 Scope & Deliverables

### 2.1 Objectives
Sprint 2 delivers the Identity & Access Control layer:
1. A compiled CSS/JS asset configuration (`tailwind.config.js` and build configurations) to style the new security interfaces.
2. A unified secure login portal at `/login` processing multi-role credentials using standard `password_verify` checks and applying brute-force lockouts.
3. Secure POST `/logout` to cleanly terminate user sessions, delete session files from the server, and invalidate cookies.
4. Robust middleware guards (`AuthMiddleware`, `RoleMiddleware`) to protect routing endpoints.
5. Inactivity (2h) and absolute (8h/12h/24h) session timeout checks run on every request.
6. A password reset workflow for couples and admin users, utilizing temporary tokens saved as secure JSON payloads inside `storage/cache/` (database schema freeze preservation).

### 2.2 Deliverable Task Map

| Task ID | Deliverable | Target Files |
|---------|-------------|--------------|
| *Pre-Check* | Build Configuration | `tailwind.config.js` (Created), `build/README.md` (Created), `README.md` (Modified) |
| **AUTH-001** | Unified Login Portal | `app/modules/Auth/AuthController.php`, `AuthService.php`, `AuthModel.php`, `views/login.php`, `routes.php` (Created); `routes/public.php` (Modified) |
| **AUTH-002** | Session Destruction | `app/modules/Auth/AuthController.php`, `AuthService.php` (Modified) |
| **AUTH-004** | Route Guards & Timeouts | `app/middleware/AuthMiddleware.php`, `app/middleware/RoleMiddleware.php` (Created); `app/core/Session.php`, `app/modules/Auth/AuthService.php` (Modified) |
| **AUTH-003** | Password Reset Flow | `app/modules/Auth/views/forgot_password.php`, `app/modules/Auth/views/reset_password.php` (Created); `app/modules/Auth/AuthController.php`, `AuthService.php`, `AuthModel.php` (Modified) |

---

## 3. Task Execution Lifecycle

Every task in Sprint 2 must follow this sequential lifecycle. Parallel task execution or skipping steps is strictly forbidden:

```
[1] Planning (Task Read & Check Prerequisites)
       │
       ▼
[2] Prompt (Human Approver issues execution prompt)
       │
       ▼
[3] Implementation (AI writes clean code, verifies syntax)
       │
       ▼
[4] Self-Review & Verification (Apply Security & Testing Checklists)
       │
       ▼
[5] Implementation Report (AI submits report for human review)
       │
       ▼
[6] Human Approval (Approver reviews report, diffs, and tests)
       │
       ▼
[7] Git Commit (User stages and commits changes)
       │
       ▼
[8] Memory Creation (Write task memory to .ai/memory/)
       │
       ▼
[9] Proceed (Human Approver authorizes the next task in queue)
```

No developer or AI agent may begin work on a task until the preceding task is fully approved, committed, and pushed to the repository branch.

---

## 4. Dependency and Queue Rules

Sprint 2 tasks must be executed in topological dependency order rather than numerical sequence:

1. **Pre-checklist Build Setup:** Must be executed first so that styles for forms can be built locally.
2. **AUTH-001 (Login Logic):** Prerequisite for all other `AUTH` tasks.
3. **AUTH-002 (Logout) & AUTH-004 (Guards/Timeouts):** Can proceed concurrently once `AUTH-001` is completed, though sequential execution is preferred.
4. **AUTH-003 (Password Reset Flow):** Must be executed last, as it relies on both the user persistence model of `AUTH-001` and the security settings verified in `AUTH-004`.

---

## 5. Working Tree and Verification Rules

### 5.1 Before Writing Code
* **Verify Git Status:** The working tree must be clean (`git status` reports no modified files) except for approved documentation updates.
* **Inspect Prerequisites:** Ensure all parent task files exist, compile, and their tests pass.
* **Isolate Scope:** Do not touch or modify any file outside the explicitly listed "Files Expected" or "Files Modified" in the task description.

### 5.2 Before Submitting for Commit
Before presenting the task report to the Human Approver, the implementing agent must perform the following:
* **Run Syntax Validation:** Run `php -l` on every new and modified PHP file. Syntax errors are an automatic failure.
* **Check Scope Alignment:** Verify that no unrelated code changes or debug files remain in the working directory.
* **Run Regression Tests:** Execute any existing kernel tests to verify that no core functionalities were damaged.
* **Check Output Escaping:** Every dynamic string rendered in a view must be wrapped in `escape_html()`. No exceptions.

---

## 6. Sprint 2 Security Rules

Any implementation of the `AUTH` tasks must strictly adhere to the following security rules (derived from SAD v1.1 Ch.6 and ADR-005):

### 6.1 Authentication
* Credentials must be validated against the `users` table where `is_active = 1` and `deactivated_at IS NULL`.
* Failed logins must trigger warnings in the audit logs.
* Lock out accounts/IPs temporarily after 5 failed attempts from the same source.

### 6.2 Authorization & Role Validation
* `RoleMiddleware` must inspect the session's `role_snapshot` value and compare it against the route's role constraints.
* Any mismatch must immediately yield a 403 response using `ErrorHandler::renderForbidden()`.

### 6.3 Password Hashing
* All password hashing must use the PHP native `password_hash()` function with the `PASSWORD_BCRYPT` algorithm.
* Plain text passwords must never be logged, printed, or stored.

### 6.4 Session Regeneration
* Call `session_regenerate_id(true)` (via `Session::regenerate(true)`) upon successful login and upon entering/exiting Support Mode. This deletes the old session file on the server and mitigates session fixation.

### 6.5 Session Timeout Checks
* Run timeout checks on every request.
* **Absolute Timeout:** Destroy session if time since session creation exceeds the limit (8h for `super_admin`, 12h for `crew`, 24h for `couple`).
* **Inactivity Timeout:** Destroy session if time since last activity exceeds 2 hours (`7200` seconds).

### 6.6 CSRF Protection
* Every state-changing request (POST) must register `CsrfMiddleware` as its leading middleware.
* Compare tokens using timing-safe `hash_equals()`.

### 6.7 Logging and Error Handling
* Use `Logger::warning()` for auth failures, missing CSRF tokens, or invalid access attempts.
* Use `Logger::info()` for successful logins, logouts, or token generations.
* Never print database connection logs, stack traces, or exception details to the user.

### 6.8 Secure Cookie Flags
* Ensure the session cookie parameters are configured with:
  * `HttpOnly` (prevent JS reading cookie).
  * `SameSite=Strict` (prevent cross-site request cookie sending).
  * `Secure` (production only, enforce HTTPS).

---

## 7. Middleware Routing & Ordering Rules

Middleware execution follows a strict pipeline wrapped by the Router. To prevent bypasses, the middleware stack must execute in this exact sequence:

```
                  HTTP Request
                       │
                       ▼
            [ 1. CsrfMiddleware ] (Protects POST inputs)
                       │
                       ▼
            [ 2. AuthMiddleware ] (Asserts authentication presence)
                       │
                       ▼
            [ 3. RoleMiddleware ] (Asserts role authorization)
                       │
                       ▼
            [ 4. Controller Action ] (Executes page logic)
```

No controller action or role evaluation may take place before the CSRF validation and authentication presence checks have successfully completed.

---

## 8. Database Schema Enforcement

* **Immutable Schema:** The MariaDB schema defined in PDD v1.0 is frozen. Adding tables, columns, indexes, or modifying column properties is strictly prohibited.
* **Token Storage:** To respect the schema freeze and avoid introducing unauthorized tables for password resets, temporary reset tokens must be written as encrypted JSON files inside `storage/cache/` (e.g. `storage/cache/reset_token_{token}.json`). These files must be deleted immediately after consumption or expiration.

---

## 9. Testing & Quality Assurance

Each task must specify and pass the following tests before submission:
1. **Static Analysis & Linting:** Confirm syntax checks pass for all PHP files.
2. **Access Prevention Test:** Request portal urls anonymously and confirm redirection to `/login`.
3. **Boundary Test:** Tamper with session timestamp markers and confirm that requests are automatically expired and redirected to `/login` with an expiration flash message.
4. **CSRF Bypass Test:** Submit post requests with missing or empty CSRF token values and confirm that a 403 Forbidden is returned.

---

## 10. Sprint Exit Criteria

Sprint 2 is considered complete and ready for Sprint 3 planning only when the following conditions are fully satisfied:
* All four implementation tasks (`AUTH-001` through `AUTH-004`) are completed, tested, and approved.
* The application is fully styled using local assets compiled via the revised Tailwind configuration.
* All portal roots (`/app/couple/*`, `/app/crew/*`, `/app/admin/*`) are successfully secured by the middleware pipeline.
* No changes have been made to the database schema or the frozen kernel modules in `app/core/` (except the approved timeout check additions in `Session.php`).
* The Sprint 2 Architecture Review has been written, reviewed, and accepted by the Human Approver.
