# Alrahma Sunday School API: End-to-End Use Case, Negative Test, and Penetration Test Plan

## 1. Goal

The goal is to cover every major end-to-end workflow in the Alrahma Sunday School API from public access through authenticated school operations, including administration, registration, attendance, grading, finance, reporting, communications, inventory, security, and system health.

This plan should validate that the API works as a complete school management system, not as a loose collection of endpoints pretending to be architecture.

## 2. Scope

The project is a Laravel 12 API with role-based access, authentication, school-year controls, finance workflows, grading, attendance, parent/student/staff/teacher modules, reporting, notifications, and operational tools.

The plan covers:

- Authentication and authorization
- Public website and frontend APIs
- User, role, permission, and navigation management
- Student, parent, family, staff, and teacher management
- Enrollment and withdrawal
- Class sections and teacher assignments
- Attendance, lateness, absence, early dismissal, and attendance consequences
- Assignments and class progress
- Scores, exams, quizzes, homework, participation, projects, midterms, finals, and grading locks
- Strong grading feature gates
- Report cards, certificates, slips, stickers, badges, and printable outputs
- Finance, invoices, payments, PayPal, manual payments, refunds, reimbursements, discounts, event charges, installment plans, carryforwards, and notifications
- Inventory, supplies, suppliers, purchase orders, and class preparation
- Messaging, broadcast email, WhatsApp groups, notifications, and support
- Incidents, flags, and emergency contacts
- Configuration, school year, calendar, settings, UI, policies, and system health
- Background commands and scheduled jobs
- Security, auditability, validation, and failure handling

## 3. User Roles to Cover

The minimum role set should include:

- Guest/Public User
- Parent
- Student
- Teacher
- Staff
- Administrator
- Finance/Admin user
- Super Admin or system-level user

Each use case must prove three things:

1. The correct role can perform the workflow.
2. The wrong role is blocked.
3. The system leaves correct data behind after the workflow completes.

Testing only the happy path is decorative QA. It makes dashboards green and production angry.

---

# Part I: End-to-End Workflow Coverage

## 4. Public and Guest Workflows

### Use Cases

- View public school information
- View landing page content
- View facility, team, testimonial, call-to-action, help, privacy, and terms pages
- Submit contact/support form
- Register a new account
- Login with valid credentials
- Fail login with invalid credentials
- Access public certificate verification by token
- Access public time-off notification link by token
- Use public badge scan/scanner routes where allowed

### Acceptance Criteria

- Public routes return correct status codes and payloads.
- Contact form creates a valid record or notification.
- Registration validates required fields, captcha rules, duplicate emails, phone formatting, and role defaults.
- Login returns token/session data.
- Invalid login attempts are tracked.
- Protected routes reject unauthenticated users.

## 5. Authentication, Session, and Security Workflows

### Use Cases

- Register user
- Login
- Refresh token/session
- Logout
- Fetch current user profile
- Switch active role
- Retrieve allowed permissions
- Attempt unauthorized route access
- Trigger IP attempt tracking
- Ban and unban IP addresses
- Handle inactive users
- Delete unverified users
- Reset password
- Clean up expired password resets

### Acceptance Criteria

- Tokens are issued, refreshed, and revoked correctly.
- Role switching does not grant permissions the user does not own.
- Permission middleware blocks forbidden access.
- Security logs are created for suspicious behavior.
- Unverified or inactive cleanup does not remove valid active users.
- Password reset tokens expire and cannot be reused.

## 6. User, Role, Permission, and Navigation Workflows

### Use Cases

- Admin lists users
- Admin creates user
- Admin updates user
- Admin deletes or deactivates user
- Admin assigns roles
- Admin removes roles
- Admin creates roles
- Admin updates role permissions
- Admin builds navigation/menu by role
- User receives correct navigation items after login
- Forbidden roles cannot access admin-only menus

### Acceptance Criteria

- Role-permission mappings are enforced at route and UI-navigation levels.
- Users with multiple roles only receive permitted actions for their active role.
- Deleted/deactivated users cannot authenticate.
- Navigation output matches actual backend permissions.

## 7. Parent, Family, Guardian, and Student Lifecycle

### Use Cases

- Create family
- Add guardians
- Add students to family
- Assign emergency contacts
- Add allergies and medical conditions
- Update student profile
- Assign student school ID
- Assign student to class section
- View parent dashboard
- Parent views student data
- Parent cannot view unrelated student data
- Admin searches families/students
- Withdraw student
- Re-enroll student
- Transfer or update family relationships

### Acceptance Criteria

- Family, guardian, student, and emergency contact links persist correctly.
- Sensitive student medical data is protected.
- Parents only access their own children.
- Enrollment status changes cascade to finance, class assignment, and reporting where appropriate.
- School ID generation is unique and stable.

## 8. Administrator Enrollment and School Operations

### Use Cases

- View admin dashboard metrics
- Search users/students/families
- Manage enrollment withdrawal queue
- List new students
- Update enrollment statuses
- Assign teachers to classes
- Manage emergency contacts
- View teacher submissions
- Notify teachers of missing submissions
- Manage promotions and placement
- Finalize promotion batches
- Audit promotion changes

### Acceptance Criteria

- Admin dashboards reflect current database state.
- Enrollment updates are transactional.
- Teacher-class assignments are visible to both admin and teacher workflows.
- Promotion workflows record audit logs.
- Placement finalization cannot corrupt current class assignments.

## 9. Staff and Teacher Workflows

### Use Cases

- Teacher logs in
- Teacher views assigned classes
- Teacher views class roster
- Teacher submits attendance
- Teacher submits class progress
- Teacher submits assignments
- Teacher submits scores
- Teacher requests print materials
- Staff logs attendance
- Staff manages absence/vacation/time-off where applicable
- Admin views staff/teacher activity

### Acceptance Criteria

- Teachers only see assigned classes.
- Teachers cannot submit scores or attendance for unrelated classes.
- Teacher submissions are timestamped.
- Admin notification logic catches missing teacher submissions.
- Print request workflow moves through teacher request and admin processing states.

## 10. Attendance Workflows

### Use Cases

- Teacher submits student attendance
- Staff submits attendance
- Admin manages attendance
- Attendance auto-publish runs
- Attendance records sync
- Parent views attendance report
- Absence is recorded
- Late arrival is recorded
- Early dismissal is recorded with signature
- Attendance comment templates are used
- Attendance consequences are calculated
- Absentee and late summaries are sent
- Attendance is recalculated by command

### Acceptance Criteria

- Attendance status is stored correctly per student, class, and date.
- Late slips and early dismissals generate correct logs.
- Parents see only their own child’s attendance.
- Attendance summary calculations match source records.
- Scheduled attendance commands are idempotent.
- Attendance consequence rules trigger only when thresholds are met.

## 11. Attendance Tracking and Violation Workflow

### Use Cases

- System identifies pending attendance violations
- Admin/staff reviews attendance tracking cases
- System composes attendance communication
- Notification logs are created
- Parent contact is recorded
- Violation status is resolved or escalated

### Acceptance Criteria

- Violation rules are deterministic and testable.
- No duplicate notifications are created for the same unresolved case.
- Parent communication history is preserved.
- Resolved cases are excluded from active violation queues.

## 12. Assignments and Class Progress

### Use Cases

- Teacher creates assignment
- Teacher updates assignment
- Teacher lists assignments by class
- Teacher submits class progress report
- Teacher attaches progress files
- Admin reviews class progress
- Parent/student views relevant class progress where allowed

### Acceptance Criteria

- Assignments are scoped to the correct class/section.
- Class progress supports attachments safely.
- Unauthorized users cannot access class progress for unrelated students/classes.
- Progress reports can be audited by date, teacher, class, and school year.

## 13. Scores, Exams, and Grading

### Use Cases

- Teacher enters quiz score
- Teacher enters homework score
- Teacher enters project score
- Teacher enters participation score
- Teacher enters midterm score
- Teacher enters final score
- Teacher enters exam draft
- Admin reviews score dashboard
- System calculates semester score
- System predicts score risk
- Teacher/admin adds score comments
- Admin locks grading period
- Admin unlocks or prevents changes depending on policy
- Strong grading is disabled by default
- Strong grading enabled for selected sections
- Strong grading blocks invalid or pending scores
- Legacy scores remain unchanged

### Acceptance Criteria

- Score values are validated against max points.
- Invalid scores are rejected.
- Pending, excused, missing, and scored statuses behave correctly.
- Legacy semester scores are displayed without recalculation.
- Strong grading only applies when configured.
- Grading locks prevent mutation after finalization.
- Score snapshots preserve calculation inputs and outputs.

## 14. Report Cards, Certificates, Slips, Stickers, and Badges

### Use Cases

- Generate report card
- Parent acknowledges report card
- Generate certificate
- Verify certificate publicly by token
- Generate slips
- Generate stickers
- Generate badge PDF
- Print badge
- Scan badge
- Log badge print
- Admin views print logs

### Acceptance Criteria

- Generated files match student/class/school-year data.
- Private files require authorization.
- Public verification tokens do not expose unrelated private data.
- Badge scan creates valid logs.
- PDF generation works under expected production dependencies.

## 15. Finance: Core Billing and Invoices

### Use Cases

- Configure fees
- Calculate tuition
- Create invoice
- Attach students to invoice
- View invoice list
- View invoice details
- Generate invoice PDF
- Apply charges
- Apply additional charges
- Apply event charges
- Apply discounts
- Void charge
- Approve charge
- Attach approved charge to invoice

### Acceptance Criteria

- Invoice totals match charges, discounts, refunds, and payments.
- Fee calculations are repeatable and explainable.
- Event charges do not mutate invoice totals until approved/attached.
- Discount vouchers track usage and eligibility.
- Invoice PDFs match database totals.

## 16. Finance: Payments, Manual Payments, PayPal, and Transactions

### Use Cases

- Record manual payment
- Record PayPal payment
- Sync PayPal payments
- View payment transactions
- Handle payment error
- Allocate payment to invoice
- Allocate payment to installment
- Send receipt notification log
- View parent payment history
- Admin views unpaid parents

### Acceptance Criteria

- Payments update balances correctly.
- Duplicate PayPal transactions are not double-counted.
- Manual payments require admin/finance permission.
- Payment allocation rules are consistent.
- Receipts are logged even if external sending is disabled.
- Payment errors are visible and actionable.

## 17. Finance: Refunds, Reimbursements, Carryforwards, and Installments

### Use Cases

- Request refund
- Approve refund
- Reject refund
- Process refund payout
- Request reimbursement
- Assign reimbursement batch
- Upload reimbursement files
- Export reimbursement data
- Create installment plan
- Activate installment plan
- Cancel installment plan
- Detect overdue installments
- Preview prior-year balance carryforward
- Draft carryforward
- Approve carryforward
- Post carryforward to new-year invoice
- Waive or adjust carryforward
- Export carryforward report
- Add finance follow-up note
- Mark parent contacted
- Record promise-to-pay
- Resolve follow-up

### Acceptance Criteria

- Refunds do not create negative or inconsistent balances.
- Reimbursements preserve attachment access rules.
- Installment plan totals reconcile with invoice balances.
- Carryforwards create separate new-year invoices and do not mutate prior-year invoices.
- Follow-up notes do not change balances.
- Finance lifecycle actions are auditable.

## 18. Communication and Notification Workflows

### Use Cases

- Send direct message
- List message inbox
- Mark message read
- Send notification
- Read notification
- Delete notification
- Broadcast email
- Attach broadcast email image/file
- Send communication to family/student groups
- Log communication
- Send WhatsApp invite
- Manage WhatsApp group links
- Track WhatsApp membership
- Send payment notification logs
- Send teacher-submission reminders
- Send attendance summaries

### Acceptance Criteria

- Messages are scoped to sender and recipient.
- Broadcast recipients are correctly selected.
- Notification logs exist even when external channels are mocked/log-only.
- WhatsApp invite links are valid and not duplicated unnecessarily.
- Attachments are validated and protected.

## 19. Inventory, Supplies, Purchase Orders, and Class Preparation

### Use Cases

- Create inventory category
- Create inventory item
- Record inventory movement
- Assign supply category
- Create supplier
- Create purchase order
- Receive purchase order
- Update purchase order status
- Teacher requests class preparation materials
- Class preparation adjusts inventory
- Generate class preparation print output

### Acceptance Criteria

- Inventory quantities update correctly after movements and receiving.
- Class preparation cannot consume unavailable stock unless explicitly allowed.
- Purchase order receiving is idempotent.
- Supplier and item references remain consistent.
- Inventory summary matches raw movements.

## 20. Incidents, Flags, and Emergency Management

### Use Cases

- Create incident
- Update incident
- List incident history
- Create current flag
- Resolve current flag
- Analyze incidents
- View emergency contact directory
- Update emergency contact
- Delete emergency contact

### Acceptance Criteria

- Incident data is visible only to authorized roles.
- Current flags reflect active operational issues.
- Emergency contacts remain linked to correct students/families.
- Incident history is not silently lost when active state changes.

## 21. Settings, School Year, Calendar, UI, and Configuration

### Use Cases

- View settings
- Update settings
- View school calendar
- Create calendar event
- Update event
- Delete event
- Switch school year context
- Close school year
- Block edits to locked school year
- Update configuration
- Update UI style
- View frontend page configuration
- Manage policies

### Acceptance Criteria

- School-year edit guards block unsafe historical edits.
- Calendar events are visible to intended audiences.
- Configuration changes are validated.
- Closed school years are immutable unless a privileged override exists.
- UI and frontend settings do not expose admin-only configuration.

## 22. System, Health, Documentation, and Maintenance

### Use Cases

- Call health endpoint
- Call database health endpoint
- Call system dashboard endpoint
- Export API documentation
- Run cleanup expired notifications
- Run cleanup password resets
- Run delete unverified users
- Run delete inactive users
- Run attendance publish command
- Run payment notification command
- Run PayPal sync command
- Run config update command

### Acceptance Criteria

- Health endpoints return useful operational status.
- Scheduled commands can run repeatedly without corrupting data.
- Cleanup commands remove only eligible records.
- Documentation route reflects active API routes.
- CI/CD pipelines run tests and static checks before deployment.

---

# Part II: Required End-to-End Scenario Set

## Scenario A: New Family Registration to Active Enrollment

1. Guest registers.
2. Admin approves or manages account.
3. Family is created.
4. Parent/guardian is linked.
5. Student is added.
6. Emergency contacts and medical data are added.
7. Student is assigned school ID.
8. Student is assigned class section.
9. Teacher sees student in roster.
10. Parent sees student profile.

## Scenario B: Normal Sunday School Day

1. Teacher logs in.
2. Teacher opens assigned class.
3. Teacher takes attendance.
4. Late student is logged.
5. Early dismissal is recorded.
6. Attendance auto-publish runs.
7. Parent views attendance report.
8. Admin views attendance summary.
9. Late/absentee summary command runs.

## Scenario C: Academic Term Completion

1. Teacher enters homework, quiz, project, participation, midterm, and final scores.
2. Invalid score is rejected.
3. Teacher adds score comments.
4. Admin reviews grading dashboard.
5. Admin locks grading.
6. Semester score is calculated.
7. Report card is generated.
8. Parent acknowledges report card.
9. Certificate is generated where eligible.

## Scenario D: Family Billing Lifecycle

1. Admin configures tuition/fees.
2. Invoice is generated for family.
3. Discount is applied.
4. Event charge is created and approved.
5. Manual payment is recorded.
6. PayPal sync is run.
7. Receipt notification is logged.
8. Balance is recalculated.
9. Parent payment history is viewed.
10. Unpaid parent report is generated.

## Scenario E: Finance Edge Lifecycle

1. Parent has unpaid prior-year balance.
2. Admin previews carryforward.
3. Admin drafts carryforward.
4. Admin approves carryforward.
5. System posts new-year invoice.
6. Admin creates installment plan.
7. Payment is allocated to installment.
8. Overdue installment report runs.
9. Follow-up note is created.
10. Promise-to-pay is recorded.
11. Case is resolved.

## Scenario F: Teacher Submission Follow-Up

1. Teacher misses required submission.
2. Admin dashboard detects missing submission.
3. Admin sends reminder.
4. Notification history is created.
5. Teacher submits missing item.
6. Admin report updates.
7. Duplicate reminder behavior is controlled.

## Scenario G: Print and Badge Workflow

1. Teacher requests print materials.
2. Admin reviews print request.
3. Admin generates slips/stickers.
4. Badge PDF is generated.
5. Badge is printed.
6. Badge print log is created.
7. Badge is scanned.
8. Scan log is created.

## Scenario H: Security and Unauthorized Access

1. Parent attempts to access unrelated student.
2. Teacher attempts to access unrelated class.
3. Staff attempts admin finance action.
4. Inactive user attempts login.
5. Banned IP attempts login.
6. Expired token accesses route.
7. All are rejected with correct status codes and no data leakage.

---

# Part III: Data Setup Strategy

Create reusable seed fixtures for:

- One administrator
- One finance administrator
- One staff member
- Two teachers
- Two parents
- Two families
- At least four students
- Two school years, one current and one closed
- Two class sections
- One active event
- One invoice with charges
- One invoice with payments
- One student with medical/allergy records
- One student with full academic scores
- One student with attendance violations
- One inventory item with supplier and purchase order

Avoid brittle tests that depend on random seed data. Randomness belongs in chaos engineering, not basic confidence.

---

# Part IV: Test Layers

## Unit Tests

Use for:

- Services
- Calculators
- Validators
- Permission helpers
- Score formulas
- Finance math
- Notification recipient selection
- Attendance rule engine

## Feature/API Tests

Use for:

- Routes
- Auth
- Validation
- Role access
- CRUD flows
- State transitions
- File generation
- Command behavior

## End-to-End Scenario Tests

Use for:

- Multi-module workflows
- Parent/student/admin/teacher handoffs
- Finance reconciliation
- Academic lifecycle
- Attendance lifecycle
- Deployment smoke checks

## Contract Tests

Use for:

- Response shape
- Status codes
- Pagination
- Error format
- Required fields
- Backward compatibility

---

# Part V: Negative Test Coverage Plan

## 1. Negative Testing Principle

Every end-to-end use case must include failure-path testing. A workflow is not covered unless the system proves that it rejects invalid users, invalid input, invalid ownership, invalid state transitions, duplicate actions, expired data, and unsafe edge cases.

For each workflow, test:

- Unauthenticated access
- Wrong-role access
- Wrong-owner access
- Missing required fields
- Invalid field format
- Invalid enum/status value
- Boundary values
- Duplicate request
- Out-of-order workflow step
- Closed school year mutation
- Deleted/inactive record usage
- External provider failure
- File upload failure
- Race condition or repeated command execution

A passing happy-path test proves the system works when everyone behaves. That is adorable and useless by itself.

## 2. Authentication and Authorization Negative Tests

### Test Cases

- Unauthenticated user calls protected endpoint
- Expired token calls protected endpoint
- Malformed token calls protected endpoint
- Logged-out token is reused
- Inactive user attempts login
- Deleted user attempts login
- Unverified user attempts restricted access
- Banned IP attempts login
- User switches to role they do not own
- User accesses route outside active role permissions
- Parent accesses admin endpoint
- Teacher accesses finance endpoint
- Staff accesses super-admin endpoint
- Student accesses another student’s data
- Parent accesses unrelated child
- Teacher accesses unassigned class
- Finance user modifies grading data
- Admin route called without required permission

### Expected Result

- Return 401 for unauthenticated requests.
- Return 403 for authenticated but unauthorized requests.
- Do not leak protected records in the response.
- Do not mutate database state.
- Log security-relevant failures where appropriate.

## 3. Registration and Login Negative Tests

### Test Cases

- Register with missing name
- Register with missing email
- Register with invalid email format
- Register with duplicate email
- Register with weak password
- Register with password confirmation mismatch
- Register with invalid phone format
- Register with missing required guardian/student fields
- Submit invalid captcha if captcha is enabled
- Login with wrong password
- Login with unknown email
- Login with inactive account
- Login repeatedly from same IP until rate-limit/attempt tracking triggers
- Password reset with invalid email
- Password reset with expired token
- Password reset with reused token
- Password reset with mismatched password confirmation

### Expected Result

- Validation errors are specific and consistent.
- No duplicate users are created.
- No token is issued on failed login.
- Login attempt tracking works.
- Expired or reused reset tokens fail safely.

## 4. User, Role, Permission, and Navigation Negative Tests

### Test Cases

- Create user with duplicate email
- Create user with invalid role
- Assign nonexistent role to user
- Remove last required admin role from only admin user
- Assign permission that does not exist
- Create role with duplicate name
- Delete role still assigned to users
- Update role without permission
- Fetch navigation as user with no active role
- Fetch navigation for role with no menu permissions
- Force menu item access through direct API route

### Expected Result

- Invalid role and permission operations fail.
- Navigation never exposes unauthorized menu items.
- Direct API calls remain protected even if a user guesses the route.

## 5. Student, Parent, Family, and Guardian Negative Tests

### Test Cases

- Create student without required family
- Create student with invalid date of birth
- Create student with future date of birth
- Create duplicate student school ID
- Assign student to nonexistent family
- Assign student to deleted family
- Parent attempts to update unrelated student
- Parent attempts to view unrelated emergency contact
- Remove last guardian from active student
- Create emergency contact with invalid phone/email
- Create allergy/medical record for unrelated student
- Withdraw student twice
- Re-enroll withdrawn student into invalid class
- Assign student to closed school year
- Delete student with active invoice, scores, or attendance records

### Expected Result

- Invalid family/student relationships are rejected.
- Ownership boundaries are enforced.
- Critical linked records are protected from destructive deletion.
- Withdraw/re-enroll transitions are controlled.

## 6. Class Section and Teacher Assignment Negative Tests

### Test Cases

- Create class section with duplicate name for same school year
- Create class section with invalid grade level
- Assign teacher to nonexistent section
- Assign inactive teacher to section
- Assign student to nonexistent section
- Assign student to section from wrong school year
- Assign duplicate teacher-section relationship
- Teacher fetches roster for unassigned section
- Teacher submits data for unassigned section
- Delete class section with active students
- Delete section with scores, attendance, or assignments

### Expected Result

- Class assignments remain consistent.
- Teachers cannot operate outside assigned classes.
- Historical academic records are not orphaned.

## 7. Attendance Negative Tests

### Test Cases

- Submit attendance without class section
- Submit attendance for unrelated class
- Submit attendance for nonexistent student
- Submit attendance for student not in class
- Submit invalid attendance status
- Submit future attendance date if not allowed
- Submit attendance for closed school year
- Submit duplicate attendance for same student/date/class
- Submit early dismissal without signature or required reason
- Submit late slip with invalid timestamp
- Submit absence without required fields
- Teacher changes attendance after lock/publish
- Attendance publish command runs twice
- Attendance recalculation command runs twice
- Parent fetches unrelated attendance report

### Expected Result

- Invalid attendance records are rejected.
- Duplicate records are not created.
- Locked or published attendance cannot be mutated unless allowed by privileged override.
- Commands are idempotent.
- Parent access is scoped correctly.

## 8. Assignment and Class Progress Negative Tests

### Test Cases

- Teacher creates assignment for unassigned class
- Create assignment without title
- Create assignment with due date before assigned date
- Create assignment with invalid attachment type
- Upload oversized attachment
- Update another teacher’s assignment
- Delete assignment after scores depend on it
- Submit class progress for wrong class
- Submit class progress for closed school year
- Parent/student views unrelated class progress
- Admin reviews nonexistent progress report

### Expected Result

- Assignments stay scoped to valid classes.
- Files are validated and protected.
- Academic records are not broken by unsafe deletes.

## 9. Scores, Exams, and Grading Negative Tests

### Test Cases

- Submit score for unrelated class
- Submit score for nonexistent student
- Submit score for student not in class
- Submit score below zero
- Submit score above max points
- Submit score with invalid decimal precision
- Submit score with invalid status
- Submit score without required assessment type
- Submit final score before required prerequisite scores
- Submit score into locked grading period
- Modify score after report card finalization
- Submit score for closed school year
- Submit duplicate exam draft
- Approve invalid exam draft
- Enable strong grading with incomplete config
- Strong grading rejects missing required categories
- Strong grading rejects invalid score composition
- Legacy score is recalculated unexpectedly
- Finance/admin role attempts grading endpoint
- Parent attempts to mutate score
- Student attempts to mutate score

### Expected Result

- Invalid scores are rejected.
- Locked/finalized grading records remain immutable.
- Strong grading gates only apply when enabled and configured.
- Legacy records remain stable.
- Unauthorized users cannot mutate academic records.

## 10. Report Card, Certificate, Badge, and PDF Negative Tests

### Test Cases

- Generate report card for nonexistent student
- Generate report card for unrelated student
- Generate report card before required scores exist
- Generate report card for unlocked/unfinalized grading period
- Parent acknowledges unrelated report card
- Acknowledge report card twice
- Generate certificate for ineligible student
- Verify certificate with invalid token
- Verify certificate with expired/revoked token
- Download private PDF without auth
- Download PDF for unrelated student
- Generate badge for nonexistent student
- Scan invalid badge token
- Scan revoked badge
- Print badge without permission
- Generate sticker/slip for closed or invalid data

### Expected Result

- Private files are protected.
- Public token routes expose only intentionally public data.
- Duplicate acknowledgements/scans are handled safely.
- Eligibility rules are enforced.

## 11. Finance Negative Tests

### 11.1 Invoice and Charge Negative Tests

#### Test Cases

- Create invoice for nonexistent family
- Create invoice for inactive/withdrawn student if not allowed
- Create duplicate invoice for same period/student
- Create charge with negative amount
- Create charge with zero amount if not allowed
- Create charge with invalid category
- Approve nonexistent charge
- Approve same charge twice
- Attach unapproved charge to invoice
- Attach charge to unrelated invoice
- Void charge after payment allocation if not allowed
- Apply discount exceeding invoice total
- Apply expired discount voucher
- Apply voucher beyond usage limit
- Apply voucher to ineligible family/student
- Generate invoice PDF for unrelated family

#### Expected Result

- Invoice totals remain correct.
- Charges and discounts obey lifecycle rules.
- No negative balance is created unless explicitly modeled as credit.
- Unauthorized access is blocked.

### 11.2 Payment Negative Tests

#### Test Cases

- Record payment for nonexistent invoice
- Record payment for unrelated family
- Record payment with negative amount
- Record payment with zero amount
- Record overpayment if not allowed
- Record duplicate manual payment reference
- Record duplicate PayPal transaction ID
- PayPal webhook/sync sends same transaction twice
- PayPal payment has invalid status
- PayPal payment belongs to wrong account/config
- Payment allocation exceeds invoice balance
- Payment allocation to cancelled installment
- Parent attempts manual payment admin route
- Receipt notification fails externally
- Payment recorded but notification fails

#### Expected Result

- No duplicate payments.
- Balances reconcile after every payment attempt.
- External notification failure does not corrupt payment records.
- Manual payment remains admin/finance-only.

### 11.3 Refund, Reimbursement, Installment, and Carryforward Negative Tests

#### Test Cases

- Request refund above paid amount
- Approve refund twice
- Process refund before approval
- Reject already processed refund
- Create reimbursement without required attachment
- Upload invalid reimbursement file type
- Assign reimbursement to invalid batch
- Create installment plan where total does not equal invoice balance
- Activate installment plan twice
- Cancel installment plan after completed payments if not allowed
- Pay cancelled installment
- Carryforward already carried balance
- Carryforward negative or zero balance
- Approve carryforward twice
- Post carryforward to closed school year
- Waive carryforward without permission
- Promise-to-pay date in past if not allowed
- Resolve finance follow-up without required resolution note

#### Expected Result

- Financial state transitions are strict.
- Refunds, installments, reimbursements, and carryforwards do not corrupt ledger totals.
- Repeated actions are idempotent or rejected clearly.

## 12. Communication and Notification Negative Tests

### Test Cases

- Send message without recipient
- Send message to nonexistent user
- Send message to unauthorized recipient group
- Parent messages unrelated teacher/class group
- Upload invalid broadcast attachment
- Upload oversized broadcast attachment
- Send broadcast without permission
- Send duplicate broadcast by retry
- Read notification belonging to another user
- Delete notification belonging to another user
- Send WhatsApp invite to invalid group
- Create duplicate WhatsApp group link
- Send notification when channel config is missing
- External email/SMS provider fails
- Notification command runs twice

### Expected Result

- Recipient targeting is correct.
- Private messages and notifications remain private.
- External provider failures are logged and recoverable.
- Duplicate command runs do not spam recipients.

## 13. Inventory and Purchase Order Negative Tests

### Test Cases

- Create inventory item without category
- Create duplicate SKU/item code
- Record negative inventory movement without permission
- Consume more stock than available
- Receive purchase order twice
- Receive more quantity than ordered
- Create purchase order for nonexistent supplier
- Delete supplier with active purchase orders
- Teacher requests unavailable supplies
- Class preparation consumes stock twice
- Upload invalid attachment to purchase order
- Update purchase order after final/received status

### Expected Result

- Inventory quantities never become accidentally inconsistent.
- Purchase order lifecycle is enforced.
- Stock consumption is idempotent and traceable.

## 14. Incidents, Flags, and Emergency Negative Tests

### Test Cases

- Create incident for nonexistent student
- Create incident for unrelated student
- Create incident without required severity/type
- Use invalid incident severity
- Resolve nonexistent incident
- Resolve already resolved incident
- Create duplicate active flag
- Resolve flag without permission
- Parent views unrelated incident
- Teacher views incident outside assigned class if restricted
- Delete emergency contact used by active student
- Create emergency contact with invalid details

### Expected Result

- Incidents and flags remain scoped and auditable.
- Sensitive disciplinary or safety data is protected.
- Duplicate active flags are prevented where appropriate.

## 15. Settings, Calendar, School Year, and Configuration Negative Tests

### Test Cases

- Update settings without admin permission
- Update config with invalid value/type
- Set school year date range where end is before start
- Create overlapping active school years
- Close school year with pending required tasks if blocked
- Modify closed school year records
- Create calendar event with invalid date range
- Delete calendar event without permission
- Create frontend setting with unsafe HTML/script if applicable
- Update policy with missing content
- Switch to nonexistent school year context

### Expected Result

- Configuration remains valid.
- Closed school years are protected.
- Unsafe content is rejected or sanitized.
- Only authorized users can change system behavior.

## 16. File Upload and Storage Negative Tests

### Test Cases

- Upload unsupported file type
- Upload oversized file
- Upload empty file
- Upload file with misleading extension
- Upload executable/script file
- Download file without permission
- Download file for unrelated student/family
- Delete file owned by another user
- Generate PDF when storage path is unavailable
- Generate PDF when template data is missing
- External storage failure
- Repeated PDF generation request

### Expected Result

- Unsafe files are rejected.
- Private files are protected.
- Storage failures fail cleanly.
- Generated files are deterministic or versioned intentionally.

## 17. Scheduled Command and Job Negative Tests

### Test Cases

- Run attendance auto-publish twice
- Run attendance sync twice
- Run late summary command twice
- Run absentee summary command twice
- Run payment notification command twice
- Run PayPal sync twice
- Run cleanup expired notifications twice
- Run cleanup expired password resets twice
- Run delete inactive users with no eligible users
- Run delete unverified users with recently registered users
- Run config update command with invalid config
- Job fails halfway through database mutation
- Notification job fails after log creation
- External API unavailable during sync

### Expected Result

- Commands are idempotent.
- No duplicate records or duplicate notifications are created.
- Partial failures roll back or leave recoverable state.
- Cleanup commands do not delete ineligible records.

## 18. API Contract and Validation Negative Tests

### Test Cases

- Send malformed JSON
- Send wrong content type
- Send invalid pagination parameters
- Send invalid sort field
- Send invalid filter field
- Send SQL-like input in search fields
- Send script tags in text fields
- Send extremely long strings
- Send null where object expected
- Send array where scalar expected
- Send unknown fields if strict validation is expected
- Call invalid route
- Call valid route with unsupported HTTP method

### Expected Result

- Return consistent validation errors.
- No SQL errors leak.
- No stack traces leak in production mode.
- Unknown or malformed requests fail safely.
- Error response format remains consistent.

## 19. Concurrency and Race Condition Negative Tests

### Test Cases

- Two admins approve same charge simultaneously
- Two payments submit for same invoice simultaneously
- Two teachers submit attendance for same student/date simultaneously
- Two report card generations run simultaneously
- Two carryforward approvals run simultaneously
- Two PayPal sync jobs process same transaction
- Two inventory consumption actions reduce same item below zero
- Two users update same student profile simultaneously
- Retry same request after timeout
- Client double-clicks submit button

### Expected Result

- Database constraints and transactions protect state.
- Duplicate writes are prevented.
- Final balances, scores, attendance, and inventory quantities remain correct.
- The API returns predictable results under retries.

## 20. Required Negative Test Matrix Per Use Case

Each end-to-end scenario must include at least these negative tests:

- Unauthenticated request returns 401
- Wrong role returns 403
- Wrong owner returns 403 or 404 according to API policy
- Missing required field returns 422
- Invalid field type returns 422
- Invalid state transition returns 409 or 422
- Duplicate action is rejected or idempotently accepted
- Closed school year mutation is blocked
- Deleted/inactive related record is rejected
- Database state remains unchanged after failed request
- Audit/security/notification log is created where expected

## 21. Negative Test Naming Convention

Use this pattern:

```text
test_[role]_[action]_fails_when_[invalid_condition]
```

Examples:

```text
test_parent_cannot_view_unrelated_student_attendance
test_teacher_cannot_submit_scores_for_unassigned_class
test_invoice_balance_does_not_change_when_invalid_payment_fails
test_paypal_sync_does_not_duplicate_existing_transaction
test_attendance_publish_command_is_idempotent
test_report_card_cannot_be_generated_before_grading_is_finalized
```

Vague names like `testFinanceValidation` should be treated as little bug incubators wearing a trench coat.

## 22. Definition of Done for Negative Testing

A module is not complete unless:

- Every protected route has auth and role negative tests.
- Every ownership-sensitive route has wrong-owner tests.
- Every create/update endpoint has validation failure tests.
- Every stateful workflow has invalid transition tests.
- Every finance mutation has reconciliation tests after failure.
- Every grading mutation has locked/finalized-period tests.
- Every scheduled command has idempotency tests.
- Every file route has unauthorized and invalid-file tests.
- Every public token route has invalid-token tests.
- Every failed request proves the database did not change incorrectly.

Negative tests are not extra. They are where the real system is tested.

---

# Part VI: Penetration Testing Coverage Plan

## 1. Objective

The objective of penetration testing is to verify that the Alrahma Sunday School API resists real-world attack patterns across authentication, authorization, student privacy, finance workflows, file handling, public token routes, admin functions, and infrastructure exposure.

This testing must focus on the API as a complete school management system containing sensitive student, parent, finance, medical, attendance, and academic data.

Penetration testing should validate:

- Unauthorized data access is blocked.
- Role boundaries cannot be bypassed.
- Family/student ownership rules cannot be bypassed.
- Financial records cannot be manipulated.
- Grades and attendance cannot be tampered with.
- Files and PDFs cannot be accessed without permission.
- Public token routes do not leak private data.
- Inputs cannot be abused for injection or stored attacks.
- Authentication tokens cannot be reused, forged, or escalated.
- Infrastructure and deployment settings do not expose secrets.

## 2. Testing Rules and Constraints

Penetration tests must be performed only against approved environments.

Use:

- Local development environment
- Dedicated staging environment
- Seeded test database
- Mocked payment providers
- Mocked email/SMS/WhatsApp providers
- Non-production file storage
- Non-production secrets
- Synthetic student, parent, and finance data

Do not:

- Use production data
- Test against production without written approval
- Run destructive tests against shared environments
- Use real parent, student, staff, or financial information
- Trigger real payment transactions or real communications

Apparently this needs saying, because “testing security” has historically been a popular way to accidentally become the incident.

## 3. Penetration Testing Phases

## Phase 1: Reconnaissance and Attack Surface Mapping

### Test Areas

- Enumerate all public routes
- Enumerate all protected API routes
- Identify admin-only endpoints
- Identify finance endpoints
- Identify grading endpoints
- Identify attendance endpoints
- Identify public token routes
- Identify upload/download routes
- Identify PDF generation routes
- Identify scheduled-command-triggerable endpoints if any
- Identify debug, docs, health, and system endpoints
- Check exposed response headers
- Check CORS behavior
- Check error responses
- Check route naming leaks
- Check API documentation exposure

### Expected Findings to Validate

- No private route is accidentally public.
- No sensitive route appears in public documentation without auth.
- Health endpoints expose only safe operational data.
- Error responses do not reveal stack traces, SQL, file paths, secrets, or internal class names in production mode.
- CORS does not allow unsafe origins with credentials.

## Phase 2: Authentication Penetration Tests

### Test Cases

- Attempt login with valid email and wrong password
- Attempt brute-force login with repeated password guesses
- Attempt credential stuffing pattern with many emails
- Attempt login from same IP repeatedly
- Attempt login from rotating IP headers such as `X-Forwarded-For`
- Attempt login with inactive user
- Attempt login with deleted user
- Attempt login with unverified user
- Attempt login after logout using old token
- Attempt token replay
- Attempt malformed JWT/token
- Attempt unsigned or tampered token
- Attempt token with modified role/user ID claims
- Attempt expired token
- Attempt refresh token reuse
- Attempt password reset token reuse
- Attempt password reset token guessing
- Attempt password reset for unknown email
- Check whether user enumeration is possible through login/reset responses
- Check session fixation behavior if sessions are used

### Expected Result

- Brute-force attempts are rate-limited or tracked.
- Tokens cannot be forged, replayed after logout, or reused after expiration.
- Password reset tokens are single-use and expire correctly.
- Responses do not disclose whether an email exists unless intentionally designed.
- Inactive, deleted, and unverified users cannot access protected workflows.

## Phase 3: Authorization and Role Escalation Penetration Tests

### Test Cases

- Parent calls admin endpoints
- Parent calls finance endpoints
- Parent calls teacher endpoints
- Teacher calls finance endpoints
- Teacher calls admin user-management endpoints
- Staff calls super-admin endpoints
- Student calls parent-only endpoints
- Finance user calls grading mutation endpoints
- Authenticated user changes request role ID manually
- Authenticated user changes active role to unauthorized role
- Authenticated user edits role/permission payload in request
- Authenticated user accesses hidden menu endpoint directly
- Authenticated user guesses privileged route URL
- User with multiple roles attempts privilege escalation during role switch
- User modifies `user_id`, `role_id`, `parent_id`, `student_id`, `teacher_id`, or `family_id` in payload

### Expected Result

- Every forbidden action returns 403 or safe 404.
- Direct route access is blocked even when the UI hides the route.
- Role switching cannot grant permissions the user does not own.
- Changing IDs in the request does not bypass server-side authorization.

## Phase 4: Object-Level Authorization / IDOR Tests

This is one of the highest-risk areas. Parent/student systems are basically IDOR playgrounds if backend checks are lazy.

### Test Cases

- Parent accesses unrelated student profile by changing student ID
- Parent accesses unrelated attendance report
- Parent accesses unrelated report card
- Parent accesses unrelated invoice
- Parent accesses unrelated payment history
- Parent downloads unrelated student PDF
- Parent acknowledges unrelated report card
- Teacher accesses roster for unassigned class
- Teacher submits attendance for unassigned class
- Teacher submits scores for unassigned student
- Teacher views incident for student outside assigned class
- Student views another student’s record
- Staff accesses records outside allowed scope
- Finance user accesses family not in permitted scope if scoping exists
- User changes ID in URL path
- User changes ID in query string
- User changes ID in JSON body
- User changes nested relationship IDs
- User uses deleted or historical IDs
- User enumerates sequential IDs

### Expected Result

- Ownership is checked server-side for every object.
- Unauthorized object access returns 403 or safe 404.
- No response contains partial private data.
- Sequential ID enumeration does not expose records.

## Phase 5: Input Validation and Injection Tests

### Test Cases

- Submit SQL injection strings in search fields
- Submit SQL injection strings in filters
- Submit SQL injection strings in login fields
- Submit SQL injection strings in finance note fields
- Submit SQL injection strings in student/family names
- Submit NoSQL-style operators if any JSON filtering exists
- Submit command injection strings to file/PDF/export endpoints
- Submit path traversal strings such as `../` in file paths
- Submit null bytes in filenames
- Submit extremely long strings
- Submit deeply nested JSON
- Submit oversized request bodies
- Submit invalid UTF-8
- Submit arrays where scalars are expected
- Submit objects where strings are expected
- Submit script tags in comments, messages, notes, incident descriptions, frontend page content, policy content, broadcast email content, and support forms
- Submit HTML event handlers such as image error handlers
- Submit markdown/HTML injection in rich text fields
- Submit formula injection strings in CSV/exportable fields, such as values starting with `=`, `+`, `-`, or `@`

### Expected Result

- Inputs are validated, rejected, escaped, or sanitized according to field purpose.
- No SQL errors leak.
- No command execution occurs.
- Exports protect against spreadsheet formula injection.
- Stored text does not execute script when rendered by frontend/admin tools.

## Phase 6: File Upload, Download, and PDF Security Tests

### Test Cases

- Upload executable file with allowed extension
- Upload script file disguised as image
- Upload oversized file
- Upload empty file
- Upload file with double extension
- Upload file with path traversal filename
- Upload file with MIME mismatch
- Upload SVG containing script
- Upload HTML file if not allowed
- Upload malicious PDF if PDF upload exists
- Upload image with metadata payload
- Attempt unauthorized download of private file
- Attempt download by guessing file ID
- Attempt download using path traversal
- Attempt access to storage path directly
- Attempt access to generated report card PDF without auth
- Attempt access to unrelated invoice PDF
- Attempt access to unrelated badge PDF
- Attempt public certificate token enumeration
- Attempt public badge token enumeration
- Attempt repeated PDF generation to exhaust resources

### Expected Result

- File type validation checks both extension and MIME/content where practical.
- Private files require authorization.
- Generated PDFs are not exposed by predictable public paths.
- Public token routes are unguessable and scoped.
- PDF generation is rate-limited or protected from abuse.

## Phase 7: Finance Penetration Tests

Finance needs special treatment because attackers love money almost as much as developers love forgetting server-side validation.

### Test Cases

- Parent modifies invoice amount in payment request
- Parent pays another family’s invoice
- Parent submits negative payment amount
- Parent submits zero payment amount
- Parent submits overpayment if not allowed
- Parent replays PayPal callback/webhook payload
- Parent modifies PayPal transaction ID
- Parent reuses existing PayPal transaction ID
- Parent changes invoice ID during payment allocation
- Parent applies expired discount voucher
- Parent applies someone else’s voucher
- Parent applies voucher beyond usage limit
- Parent applies discount exceeding balance
- Parent manipulates installment plan ID
- Parent pays cancelled installment
- User creates refund request above paid amount
- User requests refund for unrelated payment
- Finance user approves same refund twice
- Finance user posts carryforward twice
- User modifies prior-year carryforward amount
- User creates event charge for unrelated student
- User attaches unapproved charge to invoice
- User voids paid charge without permission
- Race two payments against same invoice
- Race two approvals against same charge/refund/carryforward

### Expected Result

- All financial calculations happen server-side.
- Client-provided totals are ignored or verified.
- Duplicate payment references are rejected.
- PayPal/webhook data is verified.
- Balances cannot be corrupted by replay, race, or tampering.
- Every finance mutation is auditable.

## Phase 8: Grading and Academic Integrity Penetration Tests

### Test Cases

- Teacher changes score for unassigned student
- Teacher changes score in locked grading period
- Teacher changes finalized report card data
- Teacher submits score above max value
- Teacher bypasses strong grading by changing payload flags
- Teacher submits legacy score into strong grading flow
- Parent attempts score mutation
- Student attempts score mutation
- Finance/admin role attempts score mutation
- User modifies semester score directly if endpoint exists
- User changes assessment category ID to manipulate weighting
- User submits duplicate score records
- Race two score updates against same student/category
- Generate report card before grading finalization
- Acknowledge another student’s report card

### Expected Result

- Academic records are protected by role, ownership, class assignment, school year, and grading lock.
- Server-side calculation cannot be bypassed by client payloads.
- Historical and finalized records remain stable.

## Phase 9: Attendance and Student Safety Penetration Tests

### Test Cases

- Teacher submits attendance for unassigned class
- Teacher changes attendance after publish/lock
- Parent submits attendance if not allowed
- User submits early dismissal for unrelated student
- User omits required dismissal signature/reason
- User modifies dismissal timestamp
- User downloads unrelated late slip
- User accesses attendance violation records for unrelated student
- User manipulates attendance consequence status
- Run attendance publish command repeatedly
- Race duplicate attendance submissions
- Submit attendance for closed school year
- Submit attendance for withdrawn student

### Expected Result

- Attendance and dismissal workflows are protected from unauthorized mutation.
- Published/locked attendance cannot be changed without privileged workflow.
- Safety-sensitive records are private and auditable.

## Phase 10: Public Token Route Penetration Tests

### Test Cases

- Guess certificate verification token
- Guess badge scan token
- Guess time-off notification token
- Use expired token
- Use revoked token
- Use token for wrong resource type
- Use token with modified characters
- Use token repeatedly
- Use token to infer private student data
- Use valid token and inspect whether excessive data is returned
- Check token length and entropy
- Check whether tokens are sequential or predictable

### Expected Result

- Tokens are long, random, unguessable, scoped, and revocable where needed.
- Public routes return only minimum required data.
- Invalid tokens return safe errors without revealing whether nearby tokens exist.

## Phase 11: Messaging, Notifications, and Broadcast Abuse Tests

### Test Cases

- Parent messages unrelated family/student group
- Student messages restricted admin group
- User sends message as another sender by modifying sender ID
- User reads another user’s notification
- User deletes another user’s notification
- User sends broadcast without permission
- User injects script into broadcast email content
- User uploads malicious broadcast attachment
- User triggers duplicate broadcast by retry
- User abuses notification endpoint for spam
- External provider failure leaks secrets or stack trace
- User manipulates recipient group filters

### Expected Result

- Sender and recipient are enforced server-side.
- Broadcast routes are privileged.
- Stored content is sanitized or safely rendered.
- Duplicate sends are controlled.
- Notification data remains private.

## Phase 12: Admin, Settings, and School-Year Abuse Tests

### Test Cases

- Non-admin updates settings
- Non-admin changes school year
- Admin creates overlapping school years
- User mutates closed school year records
- User reopens closed school year without permission
- User changes system config through mass assignment
- User injects unsafe HTML into frontend settings
- User changes policy content without permission
- User changes fee config without finance/admin permission
- User accesses system dashboard without admin role
- User accesses API docs if they expose private routes

### Expected Result

- System configuration is admin-only and validated.
- Closed school-year protections work.
- Mass assignment cannot modify sensitive fields.
- Administrative dashboards do not leak data.

## Phase 13: Mass Assignment and Parameter Tampering Tests

### Test Cases

- Add `is_admin: true` to profile update
- Add `role_id` to profile update
- Add `permissions` array to user update
- Add `balance` to invoice update
- Add `paid: true` to invoice update
- Add `finalized: true` to grading payload
- Add `school_year_locked: false` to school year payload
- Add `created_by` or `updated_by` fields
- Add `deleted_at` field
- Add nested unauthorized objects
- Modify server-calculated fields
- Modify audit fields
- Modify status fields outside allowed transition endpoint

### Expected Result

- Sensitive attributes cannot be mass-assigned.
- Server-calculated and audit fields are ignored or rejected.
- State changes happen only through explicit authorized workflows.

## Phase 14: Rate Limiting and Abuse Tests

### Test Cases

- Rapid login attempts
- Rapid registration attempts
- Rapid password reset requests
- Rapid contact form submissions
- Rapid support ticket submissions
- Rapid PDF generation requests
- Rapid public token verification attempts
- Rapid badge scan attempts
- Rapid search requests
- Large pagination limits
- Expensive report-generation loops
- Repeated file uploads
- Repeated notification sends

### Expected Result

- High-risk and expensive endpoints are rate-limited.
- Abuse does not exhaust server resources.
- Rate-limit responses do not leak sensitive state.

## Phase 15: API Error Handling and Information Disclosure Tests

### Test Cases

- Trigger validation error
- Trigger 401
- Trigger 403
- Trigger 404
- Trigger 405
- Trigger 409
- Trigger 422
- Trigger 500 in staging
- Trigger database constraint violation
- Trigger missing file error
- Trigger external provider error
- Trigger PDF generation error
- Check production debug mode
- Check stack trace exposure
- Check SQL query exposure
- Check environment variable exposure
- Check Laravel version/header exposure if avoidable

### Expected Result

- Errors are consistent and safe.
- Production does not expose debug traces.
- Sensitive internals are not returned to clients.

## Phase 16: Infrastructure and Deployment Penetration Tests

### Test Areas

- TLS configuration
- HTTP to HTTPS redirect
- Security headers
- CORS configuration
- Cookie flags if cookies are used
- Environment file exposure
- Git directory exposure
- Storage directory exposure
- Public upload directory exposure
- Debug routes
- Telescope/Horizon/admin tooling exposure if installed
- Queue dashboard exposure
- API documentation exposure
- Database port exposure
- Redis/cache exposure
- Default credentials
- Container image secrets
- CI/CD secret leakage
- Backup file exposure
- Old build artifacts
- Directory listing
- Server banner disclosure

### Expected Result

- No secrets are exposed.
- Admin tooling is protected.
- Only required ports are reachable.
- Deployment artifacts are not publicly accessible.
- Security headers and TLS are correctly configured.

## 4. Recommended Tooling

Use a mix of automated and manual testing.

Recommended automated tools:

- OWASP ZAP for dynamic API scanning
- Burp Suite Community or Professional for manual API testing
- Postman or Insomnia for authenticated request collections
- k6 for abuse and rate-limit testing
- Nuclei for infrastructure template checks
- Nikto for basic web server checks where applicable
- SQLMap only against approved test environments
- Trivy or Grype for container and dependency scanning
- Composer audit for PHP dependency vulnerabilities
- npm audit or equivalent if frontend assets exist
- GitLeaks for secret scanning
- Semgrep for static code security rules
- PHPStan or Larastan for static correctness
- OWASP Dependency-Check if dependency reporting is needed

Do not blindly trust scanner output. Automated scanners produce false positives with the confidence of a mediocre consultant.

## 5. OWASP API Security Coverage

Map testing to OWASP API Security Top 10:

- API1 Broken Object Level Authorization
- API2 Broken Authentication
- API3 Broken Object Property Level Authorization
- API4 Unrestricted Resource Consumption
- API5 Broken Function Level Authorization
- API6 Unrestricted Access to Sensitive Business Flows
- API7 Server-Side Request Forgery, if URL fetching exists
- API8 Security Misconfiguration
- API9 Improper Inventory Management
- API10 Unsafe Consumption of APIs

For this project, the highest-priority OWASP risks are:

- Broken object-level authorization
- Broken function-level authorization
- Broken authentication
- Unrestricted access to sensitive finance and grading workflows
- Security misconfiguration
- Unrestricted resource consumption through PDFs, reports, uploads, and public token endpoints

## 6. Required Penetration Test Scenarios

### Scenario A: Parent Attempts Data Theft

1. Login as Parent A.
2. Attempt to access Parent B’s student profile, attendance, report card, invoice, payment history, PDFs, emergency contacts, and messages by changing IDs.

Expected result: all access blocked.

### Scenario B: Teacher Attempts Class Escalation

1. Login as Teacher A.
2. Attempt to view Teacher B’s roster, submit attendance, submit scores, create assignments, view incidents, and generate class reports for Teacher B’s class.

Expected result: all access blocked.

### Scenario C: Finance Tampering

1. Login as parent or low-privilege user.
2. Attempt to modify invoice totals, apply invalid discounts, replay payment transactions, access another family’s invoices, and manipulate installment/carryforward IDs.

Expected result: all financial tampering blocked and balances unchanged.

### Scenario D: Grading Tampering

1. Login as teacher, parent, and student.
2. Attempt to alter locked scores, finalized report cards, unrelated student scores, grading weights, and strong grading flags.

Expected result: academic records remain unchanged.

### Scenario E: Public Token Enumeration

1. Attempt to guess certificate, badge, and notification tokens.
2. Try expired, revoked, malformed, short, sequential, and random tokens.

Expected result: invalid tokens fail safely and reveal no private data.

### Scenario F: Malicious Upload

1. Attempt to upload executable, script, oversized, double-extension, SVG-script, MIME-mismatched, and path-traversal filenames across all upload endpoints.

Expected result: unsafe uploads rejected and no public execution path exists.

### Scenario G: Stored XSS Attempt

1. Inject scripts into messages, notes, incidents, broadcast emails, frontend page content, policies, student names, family names, and finance notes.

Expected result: content is rejected, sanitized, or safely escaped when rendered.

### Scenario H: Command and Job Idempotency Abuse

1. Run attendance publish, PayPal sync, payment notification, cleanup, absentee summary, late summary, and carryforward-related commands repeatedly.

Expected result: no duplicate records, duplicate notifications, duplicate payments, or corrupted state.

## 7. Penetration Testing Deliverables

Each penetration test cycle should produce:

- Executive summary
- Scope and environment
- Test accounts used
- Tools used
- Attack surface map
- Findings by severity
- Reproduction steps
- Affected endpoints
- Evidence screenshots or request/response samples
- Business impact
- Technical impact
- Recommended fix
- Retest result
- Residual risk
- Final sign-off

Severity levels:

- Critical: unauthorized access to student/finance/medical data, account takeover, payment tampering, remote code execution
- High: privilege escalation, IDOR, stored XSS, unauthorized grading/finance mutation
- Medium: sensitive metadata leakage, weak rate limiting, unsafe file handling without direct exploit
- Low: minor headers, verbose non-sensitive errors, low-impact misconfiguration
- Informational: hardening suggestions

## 8. Release Gate

A release should not proceed if any of these remain open:

- Critical finding
- High-risk IDOR
- Authentication bypass
- Role escalation
- Finance balance manipulation
- Unauthorized score mutation
- Unauthorized report card/certificate/PDF access
- Public token predictability
- Stored XSS in admin/parent/teacher views
- Production debug exposure
- Exposed secrets
- Duplicate payment processing vulnerability

Medium findings may be accepted only with documented risk acceptance and a remediation deadline.

Low and informational findings should be tracked, not ignored. That is how small cracks become incident reports with meetings.

## 9. Definition of Done for Penetration Testing

Penetration testing is complete only when:

- The full route inventory has been reviewed.
- All critical workflows have role and ownership attack tests.
- All public token routes have enumeration tests.
- All upload and download routes have abuse tests.
- Finance mutation routes have tampering and replay tests.
- Grading mutation routes have lock-bypass tests.
- Attendance and dismissal routes have safety-boundary tests.
- Scanner findings have been manually verified.
- False positives have been documented.
- Valid findings have fixes or approved risk acceptance.
- Retesting confirms fixes.
- No critical or high-severity finding remains unresolved before release.

---

# Part VII: Overall Release Quality Gates

Before release, require:

- All migrations pass from empty database.
- All seeders pass.
- All feature tests pass.
- All unit tests pass.
- Route contract tests pass.
- No public route exposes protected data.
- No role can access unrelated records.
- Finance totals reconcile.
- Grading calculations are snapshot/audit-safe.
- PDF/file routes enforce authorization.
- Commands are idempotent.
- Docker build succeeds.
- CI pipeline succeeds.
- Production environment variables are documented.
- No critical or high penetration-test finding remains open.

---

# Part VIII: High-Risk Areas

## Finance

Finance is the highest-risk area because invoices, payments, PayPal sync, refunds, carryforwards, discounts, installments, and event charges all touch balances. Treat every finance workflow as a reconciliation problem, not a CRUD problem.

## Grading

Grading is high-risk because legacy and strong grading modes coexist. The system must never silently recalculate historical scores.

## Authorization

Authorization is high-risk because the app has many roles and many ownership boundaries. Parent/student/teacher data leakage would be a serious failure.

## Attendance

Attendance is high-risk because it drives reports, parent communications, consequences, and administrative summaries.

## File Generation

File generation is high-risk because PDFs, badges, certificates, receipts, and reports can expose private student or family data.

## Scheduled Commands

Scheduled commands are high-risk because repeated execution can create duplicate records if not designed idempotently.

---

# Part IX: Final Definition of Done

A use case is done only when:

- The happy path passes.
- The wrong-role path fails.
- The unauthenticated path fails.
- The wrong-owner path fails.
- Invalid input fails cleanly.
- Duplicate submission is handled safely.
- Invalid state transition is blocked.
- Database records are correct.
- Related modules see the updated state.
- Audit/log/notification records are created where expected.
- The workflow works across current school year rules.
- Closed school year mutation is blocked.
- Security and penetration-test risks are accounted for.
- The test is automated or has a documented manual test script.

Anything less is not done. It is merely optimistic.

---

# Part VI: Executable Coverage Gates Added

## 26. API Route to Use-Case Matrix

The test suite now includes `tests/Feature/Api/ApiUseCaseCoverageMatrixTest.php`.

Purpose:

- Every API route must be assigned to a business use-case domain.
- Every required domain must have at least one route.
- Every protected API route must reject anonymous traffic before business logic is reached.

This is not a substitute for feature tests. It is a guardrail that prevents undocumented endpoints from quietly entering the system. Silent endpoint creep is how applications become archaeology projects.

The current executable domains are:

- Public content and support
- Legacy compatibility
- Preferences, navigation, and UI
- Administration, enrollment, and school years
- Students, parents, and families
- Teachers, staff, and class operations
- Attendance and safety
- Grading, scores, and reporting
- Finance, billing, and inventory
- Communications and messaging
- Competition and public results

When a new route is added, update the matrix and add or extend the corresponding workflow test. A route without a use case is not an API, it is a liability with a URL.

## 27. New Workflow Scenarios

The suite now includes two cross-cutting workflow files:

- `ScenarioIPublicAuthAndSystemUseCaseTest.php`
- `ScenarioJCrossModuleApiUseCaseSmokeTest.php`

Scenario I covers the public front door: public content, policies, pages, captcha, contact form, login, current-user lookup, logout, invalid login, and suspended-account handling.

Scenario J covers broad authenticated module reachability and validation safety across admin, teacher, and parent workflows. It deliberately checks that major modules reject bad input cleanly instead of turning malformed requests into 500 errors, because production users are excellent chaos generators.

## 28. Expansion Rule for “All APIs and Features”

For every feature area, keep three layers:

1. Route coverage matrix: the endpoint belongs to an explicit use-case domain.
2. Cross-module smoke test: authenticated users can reach the module and malformed requests do not crash it.
3. Dedicated end-to-end workflow: the correct role performs the real business action, the wrong role is blocked, and the expected database state is left behind.

The suite already has Scenarios A through J. Future expansion should add one scenario file per real business journey, not one random test per controller method. Controller-method testing is a map of plumbing. Use-case testing is a map of the school actually running.

## 29. Expanded Executable Workflow Scenarios

The suite now adds two deeper workflow files beyond broad smoke coverage:

- `ScenarioKParentSelfServiceAndPrivacyTest.php`
- `ScenarioLTeacherAcademicOperationsTest.php`

Scenario K covers the parent portal as a complete use case: the parent reviews profile, attendance, invoices, enrollments, updates contact information, adds emergency contacts, and is blocked from mutating another family’s student or emergency contact records.

Scenario L covers a teacher’s classroom loop: the teacher loads the roster, retrieves class progress metadata, submits weekly progress, updates progress status, adds homework scoring columns, records homework scores, and checks report-card completeness. It also verifies an unassigned teacher cannot view or update another teacher’s progress report.

These are intentionally not controller-method checklists. They assert business behavior across controllers, services, middleware, and database state. That is the point. If a test cannot explain what real-world workflow it protects, it is probably test-shaped furniture.

### Added executable workflow coverage: Scenarios M through O

The expanded workflow suite adds three more explicit use-case tests. These are intentionally written as end-to-end API flows rather than isolated controller pokes, because endpoint confetti is not test strategy.

- **Scenario M: Administrator enrollment and classroom operations** verifies that an administrator can create a parent, create a student, create a class section, assign the student to that class, assign a teacher, confirm roster visibility, and reverse assignments without deleting the underlying student/family records.
- **Scenario N: Communications and support lifecycle** verifies parent-to-teacher messaging, inbox visibility, read-state persistence, archival state changes, public contact submission, and authenticated support queue behavior.
- **Scenario O: Inventory, finance, and audit controls** verifies inventory category/item creation, quantity adjustment, audit fields, movement logging, inventory summary visibility, and finance follow-up actions for unpaid balances.

These tests should continue to grow by scenario. The rule is simple: when a feature exists because a real person performs a job, the test should describe that job from beginning to end. Testing individual URLs is useful, but only after the business workflow is nailed down.

### Added broad-batch executable workflow coverage: Scenarios P through Z

The latest expansion adds a broad pass instead of incremental drip-feed coverage. The new tests are organized by real operational workflows, not by whichever controller happened to annoy the developer that day.

- **Scenario P: Settings, configuration, and calendar governance** covers settings review/update, school calendar CRUD, notifications, and configuration-admin CRUD.
- **Scenario Q: School-year promotion and closure lifecycle** covers admin promotion review/evaluation, parent promotion steps, year close validation, preview, close, and reopen guardrails.
- **Scenario R: Attendance operations and exception handling** covers teacher attendance grids/submission, admin manual attendance edits, staff attendance, early dismissal, late slip surfaces, violation tracking, and attendance comment template lifecycle including legacy aliases.
- **Scenario S: Scoring, grading, and report-card lifecycle** covers teacher entry for homework, quizzes, projects, midterm, final, participation, score comments, grading overview/decisions, locks, below-sixty intervention, and report-card completeness.
- **Scenario T: Documents, print, badges, stickers, slips, and certificates** covers teacher print requests, admin print processing, file access, badge generation/logging, sticker/slip surfaces, and certificate generation/audit.
- **Scenario U: Finance billing, payments, refunds, and installments** covers invoice visibility, payment creation, transaction logging, receipts, fee calculations, installment plans, refund approval/payment, and balance carryforward drafts.
- **Scenario V: Procurement, suppliers, purchase orders, and reimbursements** covers supply categories, suppliers, purchase orders, receiving, reimbursement submission, reimbursement processing, batches, locks, exports, and donation marking.
- **Scenario W: Access control, roles, navigation, and preferences** covers role-permission management, permission assignment, nav-builder lifecycle, role switching, preferences, and non-admin denial.
- **Scenario X: Public, kiosk, scanner, and verification surfaces** covers public content/documentation, health checks, badge scan processing, scanner processing, badge scan logs, and invalid public token handling.
- **Scenario Y: Family, guardians, authorized users, and WhatsApp** covers family bootstrap, second guardian attachment, guardian flags, family lookup/card surfaces, authorized-user invite/update, parent-contact exports, WhatsApp link lifecycle, and membership updates.
- **Scenario Z: Legacy aliases, validation contracts, and compatibility** covers legacy teacher GET/POST aliases, structured validation errors for representative public/authenticated forms, redirects, and non-versioned auth aliases.

This creates a stronger testing spine for “all APIs and features.” It still does not mean the entire product is done. That claim would be a clown car with a CI badge. The next hardening layer should add wrong-owner and wrong-role negative tests inside each scenario where the feature has ownership semantics, then tighten flexible assertions once production controllers have stable response contracts.

## Full-Surface Batch Expansion

The suite now includes a full-surface E2E contract layer under `tests/Feature/Api/V1/FullSurface`.

These files are intentionally broad rather than drip-fed by individual feature:

- `ApiFullSurfaceEndToEndContractTest.php` walks the registered Laravel API route table and probes every route with seeded administrator, teacher, parent, and student context. It verifies controlled response status, no 5xx crashes, malformed-payload safety, and wrong-role portal boundaries.
- `ApiRouteUseCaseCatalogCompletenessTest.php` forces every registered API route to map to a named user journey, not merely a controller namespace.
- `ApiPublicAndAuthFullSurfaceContractTest.php` covers public, documentation, page, policy, health, kiosk, registration, login, me, logout, and frontend identity contracts.
- `ApiAdminOperationsFullSurfaceContractTest.php` covers administrator enrollment, promotion, staff, emergency contacts, school years, permissions, finance dashboards, certificates, reimbursements, flags, and printables.
- `ApiAcademicAttendanceFullSurfaceContractTest.php` covers teacher classroom operations, attendance, tracking, templates, grading, score entry, report cards, print requests, and legacy teacher routes.
- `ApiFinanceInventoryCommunicationsFullSurfaceContractTest.php` covers finance, billing, refunds, carryforwards, event charges, installments, notifications, inventory, suppliers, support, messages, email, communications, and WhatsApp.
- `ApiFamilyPortalFullSurfaceContractTest.php` covers parent profile, student privacy, attendance, invoices, enrollments, promotions, emergency contacts, family guardians, and authorized users.

Expansion rule: new APIs must now satisfy two layers. First, the route must be owned by an explicit user journey in the catalog. Second, it must either be covered by the full-surface contract probe or by a named scenario with stronger business assertions. Endpoint existence alone is not coverage. It is merely a URL with opinions.

### Full-surface deep contract expansion

The next expansion adds a deeper executable contract layer under `tests/Feature/Api/V1/FullSurface`.

New support base:

- `Support/FullSurfaceE2EContractCase.php` centralizes deterministic users, class/student/parent fixtures, route materialization, actor selection, payload generation, and controlled-response assertions.

New deep contract suites:

- `ApiDeepResponseShapeAndEnvelopeContractTest` verifies that successful API responses are parseable JSON and that collection endpoints expose a stable list/envelope shape.
- `ApiDeepValidationFailureContractTest` sends empty, wrong-type, oversized, and hostile nested payloads to mutating routes and requires clean validation/authorization responses instead of 5xx crashes.
- `ApiDeepAuthorizationIsolationMatrixTest` expands role isolation checks across parent, teacher, student, and administrator boundaries, including wrong-family access attempts.
- `ApiDeepPaginationSearchAndFilterContractTest` probes list endpoints with pagination, search, sort, status, school-year, and semester filters, plus invalid date ranges.
- `ApiDeepIdempotencyAndDuplicateSubmissionContractTest` checks duplicate-sensitive POST routes and retryable destructive/archive routes for controlled behavior.
- `ApiDeepFileImportExportAndPrintableContractTest` probes download/export/printable endpoints and upload/import-style endpoints with fake files.
- `ApiDeepStateTransitionInvariantContractTest` targets school-year transitions, promotion previews, attendance transitions, and finance transitions with invalid and repeated states.
- `ApiDeepDocumentationAndRouteParityContractTest` keeps documentation/catalog endpoints reachable and checks the route table remains documentable and grouped by deeper contract domains.

These tests are intentionally broader than named workflow stories. The workflow tests prove business journeys. The full-surface tests prove API discipline: response shape, validation, authorization, idempotency, list/filter safety, file boundary safety, and state transition control. That is the layer that catches boring production failures before users discover them with the enthusiasm of unpaid QA.

### Full-surface expansion v6: security, privacy, hygiene, and boundary contracts

This pass adds another broad layer under `tests/Feature/Api/V1/FullSurface/`. It is intentionally not a new sequence of tiny scenario drips; it expands the contract net across the whole API surface.

New test classes:

- `ApiSecurityAndTransportContractTest` verifies unauthenticated transport behavior, wrong-method handling, and CORS/preflight-style control responses across major domains.
- `ApiErrorEnvelopeConsistencyContractTest` verifies missing routes, validation envelopes, and authorization denials do not leak stack traces, framework internals, or SQL errors.
- `ApiOwnerBoundaryAndPrivacyExpansionTest` verifies family isolation, unassigned-teacher isolation, and sensitive user serialization boundaries.
- `ApiDestructiveActionSafeguardContractTest` verifies delete, archive, remove, cancel, void, close, reopen, and bulk destructive routes handle missing/empty/duplicate attempts without uncontrolled failures.
- `ApiWriteAuditAndTimestampContractTest` verifies successful writes expose usable identifiers or status envelopes, timestamp fields are not serialized as broken values, and audit/log mutation routes are not public.
- `ApiRouteNamingVersioningAndHygieneTest` verifies routes do not drift into debug/temp naming, duplicate URI/method pairs, vague placeholders, or undocumented unversioned API surfaces.
- `ApiBulkImportExportAndPartialFailureExpansionTest` verifies bulk routes handle mixed valid/invalid targets, import routes reject wrong file types cleanly, and export/download/print routes remain controlled.
- `ApiLegacyCurrentAliasParityExpansionTest` verifies auth aliases, legacy teacher aliases, and unversioned compatibility routes do not drift into incompatible or crashing behavior.
- `ApiPermissionMatrixExhaustiveContractTest` adds explicit role-matrix probes for admin, teacher, parent, and student access boundaries.
- `ApiEmptyDatasetAndNullStateContractTest` verifies empty result sets, missing current school-year state, and empty class rosters remain controlled.
- `ApiQueryParameterFuzzingContractTest` probes hostile search, pagination, sort, filter, date, and include parameters to catch SQL leakage and uncontrolled crashes.
- `ApiContractSnapshotSeedTest` adds lightweight contract-key snapshots for core successful payloads so API responses cannot silently lose identity/resource keys without tests noticing.

The intent is to force the backend to answer five hard questions for every feature area:

1. Does the endpoint fail safely?
2. Does it expose the right role and owner boundary?
3. Does it keep response shape stable enough for clients?
4. Does it handle empty, duplicate, malformed, and hostile inputs?
5. Does compatibility stay deliberate rather than accidental?

Future additions should be made in one of two places: workflow scenarios for business journeys, or full-surface contracts for systemic guarantees. Do not add isolated one-off tests unless the bug is too specific to generalize.

## Full-surface v7 expansion: hardening, privacy, and invariants

This pass adds another broad contract layer rather than isolated scenario trickles. The new tests are deliberately written as cross-cutting quality gates over the route table and seeded E2E actors.

New coverage areas:

- Token/session hardening: repeated bad login attempts, garbage bearer tokens, repeat logout safety.
- Sensitive serialization redaction: passwords, remember tokens, provider secrets, payment secrets, and credentials must not leak in success or error responses.
- Mass-assignment and overposting: write endpoints must ignore or reject privilege, ownership, audit, and finance tampering fields.
- Referential integrity: impossible foreign keys must fail with controlled validation/authorization/not-found responses, not raw database errors.
- Read-after-write consistency: successful creates must return an identifier, envelope, or location that supports follow-up reads; successful updates must not null out identity.
- Date, money, and timezone boundaries: impossible dates, ambiguous dates, negative amounts, overflow amounts, NaN/Infinity-style values, and invalid timezones must fail cleanly.
- Attachment/file safety: upload-like endpoints must reject executable files and download-like endpoints must resist path traversal probes.
- Observability: correlation/request IDs must be accepted safely without becoming response-header injection or error-handling hazards.
- Cache correctness: authenticated private resources must not be publicly cacheable, and conditional headers must not bypass authorization.
- Concurrency/stale writes: duplicate submissions and stale version headers must stay controlled and must not leak deadlock/duplicate-key internals.
- Localization fallback: supported and unsupported locales must not cause missing-translation or timezone runtime failures.
- External provider callbacks: webhook/callback/payment-provider routes must reject unsigned malformed payloads without exposing provider secrets.
- Report/export privacy: downloadable and aggregate reporting routes must stay scoped to the actor's family, class, or role.

These tests are not replacements for scenario-level assertions. They are guardrails around the failure classes that normally escape happy-path E2E suites: identity leaks, unsafe error envelopes, overposting, stale writes, bad money math, attachment abuse, and report/export privacy leaks.

## Full-surface v8 expansion: lifecycle depth, edge cases, and operational resilience

This pass adds another broad batch of contract tests under `tests/Feature/Api/V1/FullSurface/`. It is designed to widen the test net without slipping back into route-by-route drip testing.

New coverage areas:

- Authentication lifecycle depth: valid login contract parity, invalid login behavior, identity endpoints, logout idempotency, password reset, registration, and verification safety.
- Role workflow negative matrix: non-admin mutation denial, actor-specific read boundaries, and blocked/suspended/unverified user access probes.
- Schema key stability: successful resource payloads must retain identity/display keys, and error envelopes must remain actionable for clients.
- Business rule edge cases: mismatched school year/semester/class payloads, financial amount boundary rules, and attendance status/time abuse.
- Notification and messaging delivery: recipient validation, bad channels, oversized messages, invalid email/phone values, read/archive/star/delete idempotency.
- Data export least privilege: parent, teacher, and student export/download/report access must remain scoped and must not leak sensitive bulk data.
- Audit and administrative traceability: admin mutations must remain controlled and audit/log routes must not be public or low-privilege mutable.
- Calendar and schedule conflicts: invalid date ranges, reversed times, impossible recurrence, broad private-event queries, and actor-scoped calendar reads.
- Search and autocomplete resilience: empty, tiny, hostile, huge, wildcard, and script-like search inputs must not leak SQL or reflect raw scripts.
- Feature flag/configuration drift: missing core configuration rows must fail closed, and low-privilege users must not mutate privileged settings.
- Transaction rollback backstops: failed multi-step mutations must not spray obvious partial users/students, and failed destructive actions must not remove seeded fixtures.
- Client compatibility/versioning: API routes must be versioned or explicitly legacy, route names must stay unique enough for client generation, and legacy/current auth failures must remain compatible.
- School operations regression backstop: administrator probes across core domains must stay controlled, and each user-facing portal must retain at least one reachable read contract.
- Operational payload resilience: huge bodies, deep arrays, huge ID lists, abusive include/fields/expand query strings must fail safely without memory or framework leaks.

The point of v8 is not to worship the number of test files. The point is to make failure categories explicit: lifecycle, permissions, schema, business rules, delivery, exports, auditability, scheduling, search, config drift, transaction safety, versioning, portal reachability, and payload resilience. That is how the suite becomes a quality system rather than a decorative pile of assertions.

## v9 broad expansion: documentation, media, cache, lifecycle, and abuse contracts

This pass adds another full-surface contract layer rather than another drip of isolated scenarios. The v9 tests focus on API behavior that often slips between business workflows and endpoint smoke tests:

- OpenAPI/documentation route drift and machine-readable route inventory expectations.
- Content negotiation and malformed media-type behavior.
- Soft-delete, restore, archive, cancel, void, and repeated destructive-action safeguards.
- Model lifecycle invariants across create/update/show/index-style resources.
- Notification preference, opt-out, recipient, and broadcast authorization boundaries.
- Report aggregation filters, date windows, grouping, and scoped report access.
- Deeply nested payloads, sparse arrays, oversized ID lists, and array abuse.
- Public/private cache separation and conditional request authorization.
- File upload/download metadata safety, misleading MIME types, and path traversal probes.
- Sorting, field selection, include/expand controls, and sensitive-field redaction.
- Calendar, schedule, timezone, recurrence, and DST boundary inputs.
- Webhook replay, missing signature, bad signature, and provider-secret redaction.
- Impersonation/delegation/acting-as route controls.
- Policy/authorization discovery for protected mutations and wildcard permissions.
- Cross-module referential misuse, where valid IDs from one domain are submitted as IDs for another domain.

The intent remains the same: every new API surface should either be owned by a named user journey or covered by a full-surface contract probe that catches drift, unsafe errors, privacy leaks, role leaks, and malformed-input failures. Endpoint quantity is not quality; it is just a larger blast radius unless these contracts stay strict.

## v10 broad contract expansion

The v10 batch adds another full-surface test layer without executing the suite locally. The goal is to widen contractual pressure across the API surface instead of adding a few isolated scenario crumbs.

New coverage areas:

- Route-family heatmap coverage and mutating-route ownership checks.
- HTTP method semantics, wrong-method behavior, bodyless deletes, and GET routes receiving mutation-looking query input.
- Null and string relationship failure modes for write endpoints.
- Frontend/backend identity and login alias parity.
- Route-parameter abuse: path traversal, script payloads, overflow IDs, and malformed placeholders.
- Privacy, retention, archive, erasure, and sensitive-field redaction boundaries.
- Async/queue/job-style trigger authorization and duplicate client request IDs.
- Financial/report math invariants, invalid money formats, and impossible aggregation windows.
- Migration-safe defaults when optional configuration rows or school-year context are absent.
- Polymorphic ownership overposting and cross-actor owner query isolation.
- Enum/state-machine boundaries for unknown statuses and terminal-state transitions.
- Unicode, bidi, zero-width, email, and phone normalization probes.
- Backward-compatible response envelope shape for collection and detail endpoints.
- Academic calendar boundary dates and hostile semester/term values.
- Mobile-client headers and offline retry/idempotency tolerance.
- Import/template/CSV malformed input and template download access boundaries.
- Cross-version auth route compatibility and containment of unversioned legacy routes.

Rule added by v10: every future API expansion must be visible in the route-family heatmap, must have controlled failure behavior under malformed relationship IDs, and must not rely on frontend assumptions that are absent from API response contracts. Otherwise the frontend gets to discover the contract in production, which is one way to run QA if you hate everyone.


## Batch 11 full-surface hardening expansion

Batch 11 adds another broad contract layer rather than another drip of isolated scenarios. It targets high-risk API failure modes that are easy to miss when teams worship happy-path workflows like tiny golden idols.

New coverage includes:

- Tenant, school-year, and semester isolation across academic, attendance, finance, and reporting routes.
- Open redirect and hostile return-url handling for login, auth, navigation, dashboard, and frontend bootstrap routes.
- SSRF-style URL payloads for callback, webhook, import/export, media, notification, and settings routes.
- HTML/script reflection safety for user-controlled text fields.
- CSV and Excel formula injection payloads in import/export-facing text fields.
- Conditional request and stale ETag behavior on mutating routes.
- Idempotency-key replay and malformed idempotency header behavior.
- Authorization-cache and role-escalation probes after permission-like mutations.
- Null/boolean/string type coercion across broad mutation routes.
- Data minimization checks for parent and student responses.
- Suspended/disabled/pending account lifecycle access probes.
- Header spoofing checks for forwarded, override, impersonation, and fake admin headers.
- Relationship cardinality abuse where single IDs receive arrays or objects.
- Cursor, offset, page, and per-page abuse across list endpoints.
- Operational endpoint exposure checks for debug, logs, metrics, cache, queue, and maintenance-style routes.
- A batch-level regression net proving the major API families remain represented by high-risk negative probes.

Rule going forward: future additions should be added as broad risk families first, then only split into scenario files when a real business workflow needs deeper assertions. More files are not automatically more quality. Sometimes they are just paperwork wearing a lab coat.

## Batch 12 full-surface risk and abuse expansion

Batch 12 adds another broad contract layer over the API surface rather than another tiny scenario drip. It targets production-grade failure modes that sit between normal workflow tests and security regression tests, where most teams conveniently lose interest because the bugs are ugly and the screenshots are boring.

New Batch 12 classes:

- `ApiBatch12MaintenanceModeAndOperationalControlContractTest` checks that maintenance, cache, queue, metrics, logs, debug, and operational control routes are admin-only and return controlled responses.
- `ApiBatch12SensitiveConfigurationExposureContractTest` checks that configuration, bootstrap, frontend, health, debug, and settings responses do not expose secrets or environment internals.
- `ApiBatch12BulkMutationBoundaryContractTest` checks empty bulk targets, cross-domain IDs, and unbounded ID lists across assign/import/delete/archive-style endpoints.
- `ApiBatch12WebhookProviderMatrixContractTest` expands provider callback coverage for missing, bad, and replay-like signature headers across webhook/payment/provider routes.
- `ApiBatch12CrossActorDataLeakageContractTest` probes parent, teacher, and student reads for sensitive-field leakage and owner-scope override attempts.
- `ApiBatch12AttachmentLifecycleContractTest` expands upload/download/file lifecycle checks for MIME spoofing, executable uploads, path traversal, and storage-driver probing.
- `ApiBatch12FinancialLedgerIntegrityContractTest` stresses finance routes with ledger-breaking amounts, wrong module IDs, and parent attempts to force all-family scope.
- `ApiBatch12AttendanceCorrectionAuditContractTest` checks attendance correction boundaries around status, dates, reasons, wrong IDs, and low-privilege mutation attempts.
- `ApiBatch12AcademicGradeBoundaryContractTest` checks score boundaries, wrong student/class contexts, and low-privilege grade finalization overrides.
- `ApiBatch12GuardianDelegationExpirationContractTest` checks guardian and authorized-user expiration, relationship, pickup/messaging flags, and student mutation denial.
- `ApiBatch12SearchEnumerationResistanceContractTest` probes search, lookup, autocomplete, user, parent, and student endpoints for enumeration and injection-style inputs.
- `ApiBatch12LongRunningExportJobContractTest` checks export/report/print/generation routes for async parameters, sensitive field requests, and low-privilege full-school export attempts.
- `ApiBatch12ConsistencyUnderPartialPayloadContractTest` checks sparse POST/PATCH/PUT payloads so validation failures stay controlled and successful partial updates do not null identity or ownership.
- `ApiBatch12RouteMetadataRiskRegisterTest` creates an executable risk register for identity, authorization, privacy, attendance, academics, finance, files, integrations, and operations.
- `ApiBatch12CombinedRegressionSweepTest` applies a combined hostile payload across high-risk route families to catch SQL leaks, environment leaks, auth-internal leaks, and uncontrolled crashes.

Batch 12 is not meant to replace the earlier scenario tests. It is a pressure layer: broad, risk-family based, and intentionally hostile. Future batches should either close a named risk family not covered here or deepen a concrete workflow with stronger business assertions. Otherwise the test suite becomes a decorative haystack, which is less useful than it sounds.


## Batch 13 full-surface integrity and abuse expansion

Batch 13 adds another broad contract layer on top of Batch 12. It focuses less on simply finding more endpoints and more on catching cross-domain integrity failures, forged business actions, and dangerous client assumptions. In plain terms: the API should not trust a request just because it contains an integer and a hopeful field name.

New Batch 13 classes:

- `ApiBatch13PaymentProviderLedgerReconciliationContractTest` stresses payment-provider references, transaction replay, ledger reconciliation payloads, and duplicate provider IDs.
- `ApiBatch13StudentEnrollmentLifecycleIntegrityContractTest` checks enrollment, withdrawal, registration, class assignment, and cross-family/class payload abuse.
- `ApiBatch13TeacherRosterAndAssignmentBoundaryContractTest` checks teacher roster scoping, forced teacher/class overrides, and unassigned-teacher academic mutations.
- `ApiBatch13ParentPortalInvoicePrivacyContractTest` checks parent invoice/payment privacy, all-family override attempts, and parent attempts to mark invoices paid/refunded.
- `ApiBatch13StaffHrPayrollBoundaryContractTest` checks staff/HR/payroll redaction and low-privilege mutation denial for personnel data.
- `ApiBatch13DiscountVoucherScholarshipAbuseContractTest` checks voucher, discount, scholarship, waiver, and fee-abuse payloads.
- `ApiBatch13InventoryProcurementReceivingIntegrityContractTest` checks procurement, receiving, supplier, inventory movement, and negative-stock abuse.
- `ApiBatch13ReportCardTranscriptCertificateForgeryContractTest` checks report-card, transcript, certificate, badge, and print generation forgery payloads.
- `ApiBatch13ContactMessagingAbuseModerationContractTest` checks message/contact/support/broadcast abuse, header injection, spam payloads, and HTML reflection.
- `ApiBatch13ApiPaginationPerformanceGuardContractTest` checks unbounded list parameters, deep includes, search abuse, and memory/time-error disclosure.
- `ApiBatch13LocaleCalendarReligiousDateContractTest` checks locale-specific calendar payloads, Hijri-style dates, reversed ranges, recurrence abuse, and academic date spoofing.
- `ApiBatch13MobileOfflineSyncConflictContractTest` checks mobile/offline sync headers, stale client versions, duplicate offline UUIDs, and conflict-resolution override attempts.
- `ApiBatch13AccountRecoveryCredentialChangeContractTest` checks password reset, verification, credential-change, token leakage, and cross-user credential mutation attempts.
- `ApiBatch13RolePermissionMutationRaceContractTest` checks wildcard permissions, recursive role inheritance, replayed role payloads, and non-admin escalation attempts.
- `ApiBatch13ObservableErrorCorrelationContractTest` checks request/correlation ID safety, header injection, and stack/controller/model disclosure.
- `ApiBatch13FullSurfaceRegressionSuperSweepTest` adds a combined cross-family hostile-payload sweep plus a mutation-family representation check.

Batch 13 keeps the same rule: write broad, risk-family tests first; only split into deeper workflow scenarios when a real business flow needs stronger state assertions. Otherwise the suite becomes a decorative maze where bugs go to retire.

## Batch 14 full-surface session, integrity, and tamper-resistance expansion

Batch 14 adds another broad contract layer on top of Batch 13. It focuses on API boundaries that often break after the functional workflow looks “done”: session/cookie confusion, identity enumeration, tampered export scopes, forged approvals, device/kiosk trust, signed URL abuse, and cross-module ownership overrides. In other words, the boring stuff that becomes very exciting when it leaks data.

New Batch 14 classes:

- `ApiBatch14SessionCookieCsrfBoundaryContractTest` checks that API authentication does not silently depend on browser session cookies or fake CSRF headers, and that browser-only headers do not grant API privilege.
- `ApiBatch14AccountEnumerationAndIdentityPrivacyContractTest` checks recovery/verification routes for user-existence leakage and identity payloads for auth internals.
- `ApiBatch14BulkAssignmentCollisionContractTest` checks duplicate and conflicting bulk assignment payloads across class, teacher, student, enroll, and batch-style routes.
- `ApiBatch14PrintExportTamperingContractTest` checks print/export/certificate/report generation routes for forged scope, signature, deleted/private data, and low-privilege full-school export abuse.
- `ApiBatch14AuditTrailTamperResistanceContractTest` checks audit/log/history routes for forged actor, timestamp, and purge/rewrite attempts.
- `ApiBatch14FinanceReconciliationAndRefundAbuseContractTest` checks finance ledger, payment, refund, transaction, and reconciliation routes for mismatched ownership, negative amounts, fake provider IDs, and parent self-refund abuse.
- `ApiBatch14AcademicPromotionRollbackIntegrityContractTest` checks promotion, school-year, semester, close/reopen, and rollback routes for unsafe rollback/delete payloads and low-privilege promotion attempts.
- `ApiBatch14AttendanceDeviceAndKioskAbuseContractTest` checks scanner, kiosk, badge, dismissal, late, and attendance routes for forged device headers and self-marking abuse.
- `ApiBatch14NotificationTemplateInjectionContractTest` checks notification, template, broadcast, email, WhatsApp, and message routes for template injection, header injection, and non-admin broadcast abuse.
- `ApiBatch14ApiConsumerContractCompatibilityTest` checks core auth/frontend/profile contracts across web, mobile, and API consumer headers, including the token/user login contract.
- `ApiBatch14RelationshipOwnershipMatrixExpansionTest` checks parent, family, guardian, invoice, attendance, score, and student routes for owner override fields and cross-relationship graph access.
- `ApiBatch14StoragePathAndSignedUrlContractTest` checks file/media/upload/download/import/export/signed routes for path traversal, forged signatures, disk override, and secret exposure.
- `ApiBatch14AdminDelegationApprovalWorkflowContractTest` checks approval, delegation, impersonation, role, permission, and authorization routes for forged approval metadata and self-delegation abuse.
- `ApiBatch14DataLifecycleArchivePurgeContractTest` checks archive, restore, purge, erase, retention, delete, and destroy routes for unsafe hard-delete/cascade payloads and non-admin purge attempts.
- `ApiBatch14CrossModuleInvariantRiskRegisterTest` adds an executable Batch 14 risk register so these route families remain visible as the API evolves.
- `ApiBatch14RegressionMegaSweepTest` adds a combined hostile-payload sweep across auth, users, school, academic, attendance, finance, inventory, messaging, file, audit, and settings surfaces.

Batch 14 keeps the same expansion rule: add risk-family tests when the API surface is broad, and only add narrower scenario tests when a workflow has stateful business rules worth proving. Endpoint confetti is still not a strategy, even if it makes the directory look busy.


## Batch 15: Identity, Privacy, Operations, and Abuse-Resistance Contract Expansion

Batch 15 adds another full-surface contract layer focused on long-lived operational and security risks that are easy to miss when tests only chase happy-path workflows.

New coverage areas:

- Token rotation, revocation, refresh replay, logout replay, and identity/session route parity.
- Privacy, consent, erasure, retention, data-subject export, and student/family scope boundaries.
- Repeated abuse patterns across login, password recovery, contact, support, badge, and scanner endpoints.
- Route parameter poisoning with encoded traversal, null bytes, script payloads, SQL-ish values, overflowing IDs, and non-ASCII numeric forms.
- Feature flag, experiment, rollout, settings, and configuration override attempts by low-privilege actors.
- Command, scheduler, queue, sync, cleanup, recalculation, and background trigger authorization.
- Backup, restore, snapshot, database dump, archive, tenant, and residency exposure controls.
- Cross-school duplicate identity, external ID collision, student-number collision, and tenant alias abuse.
- Form-request authorization bypass attempts using `_method`, wildcard permissions, and fake roles.
- Domain event, outbox, notification, webhook, broadcast, email, and WhatsApp forged metadata.
- Impersonation, delegation, acting-as, switch-user, and behalf-of boundary assertions.
- Report drilldown, analytics, dashboard, summary, and export aggregate privacy.
- RTL, Unicode, bidi override, combining characters, emoji, and malformed encoding text payloads.
- Student safety, incident escalation, attendance alerts, flags, and parent/student mutation denial.
- Sparse fieldsets, metadata expansion, debug includes, global search, directory, lookup, and autocomplete enumeration resistance.
- A Batch 15 ultra sweep combining tenant override, owner override, secret includes, hard-delete flags, forged signatures, hostile redirects, and path traversal probes.

This batch continues the rule used by the full-surface suite: broad risk-family tests first, then deeper scenario-specific tests only when a business workflow needs dedicated assertions. Otherwise the test suite becomes a very expensive scrapbook.
