================================================================================
COMPLIANCE, SECURITY, AND LEGAL LOGIC
Auth API — identity, access, privacy, and operational controls
================================================================================

This document describes the compliance, security, and legal rules enforced or
supported by the application. It is the human-readable companion to:
  includes/security.php · includes/auth.php · config/roles.json
  config/blocked_usernames.txt · config/blocked_passwords.txt

Operators should align deployment policies (retention, DPAs, incident response)
with their organization and applicable law. This text is operational guidance
for the software controls; it is not a substitute for legal advice.

--------------------------------------------------------------------------------
1. IDENTITY SNAPSHOT (profile_json)
--------------------------------------------------------------------------------
• Every user has a canonical JSON snapshot of identity fields:
  username, email, first_name, last_name, dept, role
  plus metadata: snapshot_at, snapshot_by.

• On create, admin update, integrity resolve, and migration backfill, a NEW
  snapshot is written to the database.

• On every full profile read, live columns are compared to the stored snapshot
  (identity fields only). If they differ:
  - integrity_mismatch is set to 1
  - the account is disabled (is_active = 0)
  - token_version is bumped (sessions invalidated)
  - an audit entry is written
  - mismatched data is still shown to admins for review

• Direct database edits that bypass the app will surface as a mismatch.
• Admins resolve mismatches via "Resolve integrity" which writes a fresh
  snapshot and may re-enable the account.

--------------------------------------------------------------------------------
2. BLOCKED USERNAMES AND PASSWORDS
--------------------------------------------------------------------------------
• config/blocked_usernames.txt — usernames that cannot be registered or assigned.
• config/blocked_passwords.txt — passwords that cannot be set anywhere.

• Matching is case-insensitive. Comments (#) and blank lines are ignored.
• Enforced on: register, admin create, username change, bulk import, admin
  set-password, password-reset completion, and self-service password change.

• Rejection message (compliance):
  "Not able to create due to compliance and security reasons"

--------------------------------------------------------------------------------
3. PASSWORD CHANGE REASONS
--------------------------------------------------------------------------------
• Every password change REQUIRES a non-empty reason/note.
• The reason is stored in password_change_notes and in the audit log.
• Applies to: admin set_password, admin password-reset resolve, self change.

• If the reason is missing, or the account is disabled / integrity-mismatched:
  "Unable to update password due to account issues."

• Password strength rules (min length, letter, number, optional special) still
  apply after the blocklist and reason checks.

--------------------------------------------------------------------------------
4. ROLES AND ACCESS LEVELS
--------------------------------------------------------------------------------
• Source of truth: config/roles.json
• Rights vocabulary: read, write, delete, manage_users, admin_panel
• Roles (default):
  - admin          — full rights including admin_panel
  - system_admin   — full rights including admin_panel
  - dev            — read, write
  - testing        — read, write
  - weather_team   — read, write
  - viewer         — read only

• Only roles with admin_panel may use the admin UI/API.
• JWT and /me responses expose role, label, and rights from the same JSON.
• Least privilege: assign the minimum role required for the job function.

--------------------------------------------------------------------------------
5. ACCOUNT LOCKOUT AND APPROVAL
--------------------------------------------------------------------------------
• Failed logins increment a counter; after threshold the account is temporarily
  locked (locked_until).
• Self-registered accounts may require admin approval (approval_status) before
  login is allowed.
• Disabled accounts (is_active = 0) cannot authenticate.
• Integrity-mismatched accounts are disabled until an admin resolves them.
• Approval and disable actions are audited.

--------------------------------------------------------------------------------
6. ENCRYPTION, SECRETS, AND AUDIT
--------------------------------------------------------------------------------
• PII fields (email, names, dept, IPs, user agents, URLs, audit details) are
  encrypted at rest (field-bound ciphertext).
• Email lookups use a blind index (HMAC), not plaintext equality on encrypted
  values.
• Passwords: Argon2id over peppered HMAC; never stored or logged in clear text.
• Security-sensitive actions write to audit_log (actor, action, target, details).
• Secrets (DATA_ENCRYPTION_KEY, JWT_SECRET, PASSWORD_PEPPER, BLIND_INDEX_KEY)
  must not appear in source control, tickets, or client-side code.
• API traffic logs exclude passwords, tokens, and request bodies.

--------------------------------------------------------------------------------
7. AUTHORIZED USE ONLY
--------------------------------------------------------------------------------
• Access to this system is limited to authorized personnel and integrated
  applications explicitly granted system/environment access.
• Credentials are individual; sharing accounts is prohibited.
• Attempts to bypass authentication, authorization, encryption, integrity
  checks, rate limits, or audit logging are security incidents.
• Admin actions (create, disable, password set, role change, delete) must be
  performed only for legitimate operational or support purposes.

--------------------------------------------------------------------------------
8. PRIVACY AND PERSONAL DATA
--------------------------------------------------------------------------------
• Categories of personal data may include: name, email, username, department,
  role, login timestamps, IP addresses, user agents, and URL context of login.
• Processing purposes: authentication, authorization, security monitoring,
  abuse prevention, support, and audit.
• Lawful basis depends on deployment context (e.g. contract, legitimate
  interest, legal obligation, or consent where required). Configure notices
  and DPAs outside this application as required by your jurisdiction.
• Data minimization: only fields required for identity and security are stored;
  passwords are stored solely as irreversible hashes.
• Access to personal data in the admin panel is restricted to roles with
  admin_panel / manage_users rights.

--------------------------------------------------------------------------------
9. DATA SUBJECT AND USER REQUESTS (OPERATIONAL)
--------------------------------------------------------------------------------
• Access / export: admins may use user profile and PDF export to fulfill
  legitimate access requests according to organizational procedure.
• Correction: admins may update identity fields via the admin panel; each
  update refreshes the identity snapshot.
• Restriction / disable: accounts can be disabled (is_active = 0) without
  immediate deletion.
• Deletion: permanent delete is available to admins with confirmation; related
  history may be removed by cascade rules. Follow legal hold policy before
  deleting accounts under investigation.
• This software does not automate external privacy-portal workflows; operators
  must follow their organization's privacy process.

--------------------------------------------------------------------------------
10. RETENTION AND LOGGING
--------------------------------------------------------------------------------
• Login history, audit log, traffic log, and password-change notes are retained
  according to server configuration and organizational retention schedules.
• Operators should define and enforce retention (and purge) for:
  - login_history
  - audit_log
  - traffic_log
  - password_change_notes
  - password_reset_requests
• Do not retain personal data longer than needed for security, operations,
  or legal obligation.
• Backups inherit the sensitivity of the live database; protect and retire them
  on a defined schedule.

--------------------------------------------------------------------------------
11. ACCEPTABLE USE AND PROHIBITED CONTENT
--------------------------------------------------------------------------------
• Usernames and displayable identity fields must not contain unlawful,
  harassing, or abusive content. Blocklists may include prohibited terms;
  operators should extend blocklists to match policy.
• The system must not be used to facilitate fraud, unauthorized access,
  malware distribution, or violation of export or sanctions rules.
• Bulk import and API automation must respect rate limits and approval gates.

--------------------------------------------------------------------------------
12. SESSION, TOKEN, AND CLIENT SECURITY
--------------------------------------------------------------------------------
• JWTs are bearer tokens: protect them in transit (HTTPS) and at rest on clients.
• Short-lived tokens and token_version revocation limit exposure after
  password change, admin revoke, or integrity lock.
• Clients must not put tokens in URLs or non-secure storage when avoidable.
• CORS is allow-list based; admin API may be further restricted by IP allow lists.
• FORCE_HTTPS and related deploy settings should remain enabled in production.

--------------------------------------------------------------------------------
13. THIRD-PARTY AND INTEGRATED APPLICATIONS
--------------------------------------------------------------------------------
• Applications consume roles and rights from config/roles.json (via Setup copy
  or GET /admin/roles.php). Downstream apps must enforce the same or stricter
  access levels.
• Testing and Sandbox environment APIs require explicit user grants; absence
  of a grant means no login.
• Service-to-service callers should use approved channels (and mutual TLS where
  configured). Do not embed long-lived user passwords in automation.

--------------------------------------------------------------------------------
14. INCIDENT RESPONSE (SOFTWARE HOOKS)
--------------------------------------------------------------------------------
• Indicators: repeated failed logins, integrity_mismatch flags, unexpected role
  changes, mass password resets, traffic anomalies (admin traffic viewer).
• Immediate controls available to admins:
  - Disable account
  - Unlock / clear lockout after verification
  - Revoke sessions (token_version)
  - Reset password with required reason
  - Resolve or investigate integrity mismatch
• Preserve audit_log and traffic_log when investigating; avoid deleting evidence
  under active incident or legal hold.
• Escalate according to organizational incident-response plan (not automated
  by this application).

--------------------------------------------------------------------------------
15. ADMINISTRATOR DUTIES
--------------------------------------------------------------------------------
• Protect admin credentials with unique strong passwords; prefer separate
  admin accounts (not shared).
• Review pending registrations and password-reset requests promptly.
• Record meaningful reasons for password changes and privileged actions.
• Do not export or share user PDFs, personal data, or audit extracts outside
  approved channels.
• After staffing changes, disable or delete accounts and revoke sessions.

--------------------------------------------------------------------------------
16. LEGAL NOTICES (DEPLOYMENT)
--------------------------------------------------------------------------------
• Unauthorized access to this computer system may be a violation of criminal
  and civil law. Activity may be monitored and logged.
• The organization operating this instance is the data controller (or
  equivalent) for personal data processed here, unless a written agreement
  states otherwise.
• Warranty disclaimer: the software is provided as an operational control
  plane; fitness for a particular legal regime (GDPR, CCPA/CPRA, HIPAA, etc.)
  depends on configuration, process, and legal review outside the codebase.
• By using the admin panel or APIs, operators acknowledge these compliance and
  security rules and their duty to follow organizational policy.

--------------------------------------------------------------------------------
17. ADMIN PORTAL SETUP
--------------------------------------------------------------------------------
• The Setup panel lists API URLs, role/access JSON, and copy helpers so other
  applications can integrate with the same access levels and endpoints.
• The Compliance panel displays this document and structured rules loaded from
  GET /admin/compliance.php.

--------------------------------------------------------------------------------
18. ADA AND ACCESSIBILITY (WCAG-ORIENTED)
--------------------------------------------------------------------------------
• Goal: the Admin Panel and user-facing auth flows should be usable by people
  with disabilities, consistent with the Americans with Disabilities Act (ADA)
  and aligned with WCAG 2.1 Level AA practices where the software controls UI.

• Perceivable
  - Text and controls are not conveyed by color alone (badges include text;
    chips include labels).
  - Form fields have associated labels or aria-label attributes.
  - Status messages use role="alert" where appropriate so assistive tech is notified.
  - Meaningful page language is set (html lang="en").

• Operable
  - Primary actions are available via keyboard (buttons and links are focusable).
  - Focus visibility: focused controls show a visible outline.
  - Modal dialogs expose role="dialog", aria-modal, and labeled close controls.
  - A skip link allows moving past repeated chrome to main content.
  - Avoid relying on hover-only actions for essential functions.

• Understandable
  - Errors are presented in text (not only color or icons).
  - Compliance and security messages use plain language.
  - Consistent navigation: Setup, Compliance, Traffic, Logout remain in the header.

• Robust
  - Semantic HTML for headings, tables, buttons, and forms.
  - ARIA used to supplement native semantics (alerts, dialogs, icon-only buttons),
    not to replace them when a native control exists.

• Operator responsibilities
  - When embedding this auth UI in another product, verify contrast, zoom (200%),
    screen-reader flows, and keyboard-only paths for that product’s theme.
  - PDFs exported for users should not be the sole channel for required notices
    when an accessible HTML alternative can be provided.
  - Custom themes must keep a visible focus indicator and readable contrast.

• Limitations
  - Full ADA conformance of a deployment depends on hosting, content, and any
    downstream applications. This section documents in-app controls and targets;
    formal legal determination requires organizational review.


--------------------------------------------------------------------------------
19. INPUT VALIDATION AND SANITIZATION
--------------------------------------------------------------------------------
• All request input is treated as untrusted.
• JSON bodies are size-capped, reject null bytes, decoded as arrays only, then
  recursively sanitized (filter_var-based string cleaning, type-safe handling).
• Query and form parameters should be read with filter_input() wrappers:
  inputGet(), inputPost(), inputGetInt(), inputGetString(), inputGetBool().
• Values already in memory (JSON fields) use filter_var() via sanitizeString(),
  sanitizeEmail(), sanitizeInt(), sanitizeBool(), sanitizeUrl().
• Emails are sanitized and validated with FILTER_SANITIZE_EMAIL /
  FILTER_VALIDATE_EMAIL before storage or lookup.
• Integers from clients are bounded (min/max) to prevent overflow abuse.
• Application logic still applies domain validation (roles, blocklists, password
  policy) after generic sanitization.


--------------------------------------------------------------------------------
20. FILESYSTEM PERMISSIONS (DEPLOYMENT)
--------------------------------------------------------------------------------
• Standard directories: 755 (rwxr-xr-x). The system (and web server user) may
  read and traverse; only the owner may write.
• Standard files: 644 (rw-r--r--). Source and static assets are readable but
  not modifiable by other local users or the web group by default.
• Sensitive configuration files: 600 (rw-------) or 400 (r--------) for files
  that contain database passwords, encryption keys, or secrets — for example:
  .env, config/database.php, includes/crypto.php (and any local secret files).
  Mode 600 blocks other local server users from reading credentials.
• Apply after deploy:
    bash bin/set-permissions.sh
  or from another path:
    bash bin/set-permissions.sh /var/www/auth-api
• Web document root should not serve .env or private config; keep secrets
  outside the public URL space when possible. Prefer environment variables
  injected by the process manager over world-readable files.
• Owner should be the deploy user; the PHP-FPM/Apache user needs read access
  to application code (644/755) and read access only to secrets it must load
  (run the app as a user that can read 600 files, or inject secrets via env).


--------------------------------------------------------------------------------
21. API AND WEBSITE REQUEST LOCKOUT
--------------------------------------------------------------------------------
• Policy: maximum 5 attempts; then automatic lockout for 1 minute.
• Lockout state is stored in the database table rate_limits:
    rate_key (hashed), attempts, window_start, locked_until
• While locked_until is in the future, further requests from that key are denied
  (HTTP 429, code RATE_LOCKED).
• Unlock methods:
  1. Wait until locked_until has passed (then the next request resets attempts).
  2. Clear the row in the database (only operational unlock without waiting):
       DELETE FROM rate_limits WHERE rate_key = ...;
     or set attempts = 0 and locked_until = NULL for that rate_key.
• Login account lockout uses users.failed_logins and users.locked_until with the
  same 5 attempts / 1 minute defaults (LOGIN_MAX_ATTEMPTS, LOGIN_LOCKOUT_MINUTES).
• Tunable env: API_LOCKOUT_ATTEMPTS (default 5), API_LOCKOUT_SECONDS (default 60).


--------------------------------------------------------------------------------
22. WORKFLOWS (FLOWCHART: START → DECISION → PROCESS → FINISH)
--------------------------------------------------------------------------------
• Declarative automation in config/workflows.json (flowchart style).
• Node types:
    start     — entry (START)
    decision  — branch on conditions (Decision 1 / Decision 2)
    process   — one or more actions in sequence (Process → Process → Process)
    finish    — exit (FINISH)
• Decisions pick the first matching branch.when; otherwise default_next.
• Branches can loop back to earlier process nodes (guarded max steps).
• Trigger events include: login_failed, integrity_mismatch, user_registered,
  registration_approved, password_changed, rate_locked, compliance_block.
• Actions: audit, disable_account, enable_account, lock_account,
  revoke_sessions, clear_rate_limits_for_user, set_role.
• Legacy flat if/then rules still supported under legacy_workflows.
• Migrations run through workflow events: migration_started, migration_applied,
  migration_batch_finished, migration_failed (bin/migrate.php → migration_flow).
• Other system events (user update/toggle/delete, integrity resolve, snapshots)
  also enter the flowchart (auth_security_flow).
• Runs logged to workflow_runs (migration 010). List: GET /admin/workflows.php


--------------------------------------------------------------------------------
23. API KEYS AND SECRETS (WORKFLOW-TRACKED)
--------------------------------------------------------------------------------
• API keys are created, rotated, and revoked only through application APIs that
  fire workflow events (api_keys_flow + auth_security_flow).
• Plain keys are shown once; only HMAC hashes are stored (api_keys.key_hash).
• Auth: X-API-Key: ak_… or Authorization: ApiKey ak_…
• Related file/secret changes emit file_or_secret_changed for monitor visibility.
• Admin UI: API Keys panel; monitor stuck/failed runs under Workflows.


--------------------------------------------------------------------------------
24. MIGRATION PROCESS RULES (MAY NOT PROCESS)
--------------------------------------------------------------------------------
Migrations do not process when any of these rules trigger:
  • Password Blocked — password blocklist missing/unreadable
  • Username Blocked — username blocklist missing/unreadable
  • Auth Issues — users with integrity_mismatch
  • Account Locked — users with active locked_until
  • API Issues — active rate_limits lockouts
  • Member Not Active — inactive approved members
  • Account Pending — pending registrations
  • Account Not Found — target user id missing (when specified)

CLI: php bin/migrate.php
Override (ops only): php bin/migrate.php --force
Status API: GET /admin/migration-rules.php

================================================================================
END OF COMPLIANCE, SECURITY, AND LEGAL LOGIC
================================================================================


--------------------------------------------------------------------------------
CODE GUARDRAILS
--------------------------------------------------------------------------------
Central module: includes/guardrails.php
- Admin required for destructive operations
- JSON body size limits
- Path traversal and protected file overwrite blocked
- Confirmation phrases for bulk password change
- Bulk ID and bulk password caps
- Update packages restricted to updates/pending
- Admin script rate limits
- Last-admin lock/delete protection
- Classification FYI on sensitive responses
