1
0

index.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. <?php
  2. /*
  3. * Copyright 2026 Alessandro Chiapparini <sprint_planer_web@chiapparini.org>
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * See the LICENSE file in the project root for the full license text.
  9. */
  10. declare(strict_types=1);
  11. use App\Auth\LocalAdmin;
  12. use App\Auth\OidcClient;
  13. use App\Auth\SessionGuard;
  14. use App\Controllers\AuditController;
  15. use App\Controllers\AuthController;
  16. use App\Controllers\CspReportController;
  17. use App\Controllers\ImportController;
  18. use App\Controllers\SettingsController;
  19. use App\Controllers\SprintController;
  20. use App\Controllers\TaskController;
  21. use App\Controllers\UserController;
  22. use App\Controllers\WorkerController;
  23. use App\Db\Connection;
  24. use App\Db\Migrator;
  25. use App\Http\FatalErrorHandler;
  26. use App\Http\Request;
  27. use App\Http\Response;
  28. use App\Http\Router;
  29. use App\Http\TrustedProxies;
  30. use App\Http\View;
  31. use App\Repositories\AppSettingsRepository;
  32. use App\Repositories\AuditRepository;
  33. use App\Repositories\AuthThrottleRepository;
  34. use App\Repositories\SprintRepository;
  35. use App\Repositories\SprintWeekRepository;
  36. use App\Repositories\SprintWorkerDayRepository;
  37. use App\Repositories\SprintWorkerRepository;
  38. use App\Repositories\TaskAssignmentRepository;
  39. use App\Repositories\TaskRepository;
  40. use App\Repositories\UserRepository;
  41. use App\Repositories\WorkerRepository;
  42. use App\Services\AuditLogger;
  43. use App\Services\Import\SprintImporter;
  44. use App\Services\Import\XlsxSprintImporter;
  45. // Buffer output so a stray warning/notice can't send headers before
  46. // Response::send() gets a chance to set them. send() will flush.
  47. ob_start();
  48. define('APP_ROOT', dirname(__DIR__));
  49. // ---------------------------------------------------------------------------
  50. // Autoload
  51. // ---------------------------------------------------------------------------
  52. $autoload = APP_ROOT . '/vendor/autoload.php';
  53. if (!is_file($autoload)) {
  54. http_response_code(500);
  55. header('Content-Type: text/plain; charset=utf-8');
  56. echo "Composer dependencies are not installed.\n";
  57. echo "Run: composer install (or rebuild the container).\n";
  58. exit;
  59. }
  60. require $autoload;
  61. // ---------------------------------------------------------------------------
  62. // Environment
  63. // ---------------------------------------------------------------------------
  64. if (is_file(APP_ROOT . '/.env')) {
  65. $dotenv = Dotenv\Dotenv::createImmutable(APP_ROOT);
  66. $dotenv->safeLoad();
  67. }
  68. $appEnv = getenv('APP_ENV') ?: 'production';
  69. if ($appEnv !== 'production') {
  70. ini_set('display_errors', '1');
  71. error_reporting(E_ALL);
  72. } else {
  73. ini_set('display_errors', '0');
  74. }
  75. // ---------------------------------------------------------------------------
  76. // R01-N13: install the fatal-error safety net AS EARLY AS POSSIBLE — before
  77. // migrations, before service wiring. An uncaught throwable from anywhere
  78. // below now produces a minimal 500 page with full security headers instead
  79. // of leaking whatever was buffered. We re-register later (with the resolved
  80. // $isHttps) to flip the HSTS bit, but having the handler installed up-front
  81. // covers fatals during bootstrap (e.g. broken migration, missing class).
  82. FatalErrorHandler::register($appEnv, false);
  83. // ---------------------------------------------------------------------------
  84. // R01-N22: schema sanity check (NOT migration).
  85. //
  86. // The request path never applies SQL — `bin/migrate.php` (run by the Docker
  87. // entrypoint or by the operator at deploy time) is the only path that can
  88. // move the schema forward. Here we only OPEN the connection and verify there
  89. // are no pending migration files. If there are, refuse to serve with 503 so
  90. // stale-schema serving cannot happen silently after a forgotten deploy step.
  91. // ---------------------------------------------------------------------------
  92. try {
  93. $pdo = Connection::pdo();
  94. $pending = (new Migrator($pdo))->pendingFiles();
  95. } catch (\Throwable $e) {
  96. error_log('database bootstrap failed: ' . $e->getMessage());
  97. http_response_code(500);
  98. header('Content-Type: text/plain; charset=utf-8');
  99. echo "Database bootstrap failed.\n";
  100. if ($appEnv !== 'production') {
  101. echo $e->getMessage() . "\n";
  102. }
  103. exit;
  104. }
  105. if ($pending !== []) {
  106. error_log(
  107. 'schema out of date — pending migrations: '
  108. . implode(', ', $pending)
  109. . '. Run `php bin/migrate.php` to apply.'
  110. );
  111. http_response_code(503);
  112. header('Content-Type: text/plain; charset=utf-8');
  113. header('Retry-After: 30');
  114. echo "Service Unavailable: database schema is out of date.\n";
  115. if ($appEnv !== 'production') {
  116. echo "Pending migrations: " . implode(', ', $pending) . "\n";
  117. echo "Run: php bin/migrate.php\n";
  118. }
  119. exit;
  120. }
  121. // ---------------------------------------------------------------------------
  122. // Shared services
  123. // ---------------------------------------------------------------------------
  124. $twigCacheDir = APP_ROOT . '/data/twig-cache';
  125. if (!is_dir($twigCacheDir)) {
  126. @mkdir($twigCacheDir, 0775, true);
  127. }
  128. $view = new View(APP_ROOT . '/views', $twigCacheDir);
  129. $users = new UserRepository($pdo);
  130. $workers = new WorkerRepository($pdo);
  131. $sprints = new SprintRepository($pdo);
  132. $sprintWeeks = new SprintWeekRepository($pdo);
  133. $sprintWorkers = new SprintWorkerRepository($pdo);
  134. $swDays = new SprintWorkerDayRepository($pdo);
  135. $tasks = new TaskRepository($pdo);
  136. $taskAssign = new TaskAssignmentRepository($pdo);
  137. $auditRepo = new AuditRepository($pdo);
  138. $appSettings = new AppSettingsRepository($pdo);
  139. $authThrottle = new AuthThrottleRepository($pdo);
  140. $audit = new AuditLogger($pdo);
  141. $auth = new AuthController($pdo, $users, $audit, $view, $authThrottle);
  142. $workerCtrl = new WorkerController($pdo, $users, $workers, $audit, $view);
  143. $sprintCtrl = new SprintController(
  144. $pdo, $users, $sprints, $sprintWeeks, $sprintWorkers, $swDays,
  145. $tasks, $taskAssign, $workers, $audit, $view, $appSettings,
  146. );
  147. $taskCtrl = new TaskController(
  148. $pdo, $users, $sprints, $sprintWorkers, $swDays,
  149. $tasks, $taskAssign, $workers, $audit, $appSettings,
  150. );
  151. $auditCtrl = new AuditController($users, $auditRepo, $view);
  152. $userCtrl = new UserController($pdo, $users, $audit, $view);
  153. $settingsCtrl = new SettingsController($pdo, $users, $appSettings, $audit, $view);
  154. $xlsxParser = new XlsxSprintImporter();
  155. $importCommit = new SprintImporter(
  156. $pdo, $sprints, $sprintWeeks, $sprintWorkers, $swDays,
  157. $tasks, $taskAssign, $workers, $audit,
  158. );
  159. $importCtrl = new ImportController(
  160. $pdo, $users, $sprints, $xlsxParser, $importCommit, $view, $audit,
  161. );
  162. $cspReportCtrl = new CspReportController($audit);
  163. // ---------------------------------------------------------------------------
  164. // Routing
  165. // ---------------------------------------------------------------------------
  166. $router = new Router();
  167. $router->get('/', function (Request $req) use ($view, $pdo, $users, $sprints, $appEnv): Response {
  168. $currentUser = SessionGuard::currentUser($users);
  169. $schemaVersion = (int) $pdo->query(
  170. 'SELECT COALESCE(MAX(version), 0) FROM schema_version'
  171. )->fetchColumn();
  172. $sprintRows = $currentUser === null ? [] : $sprints->allWithCounts();
  173. // R01-N26: one-shot session flash for the post-delete chip. Set by
  174. // `SprintController::delete`; consumed (and cleared) here so a manual
  175. // refresh of `/` cannot re-show the green banner. `currentUser` already
  176. // forced `SessionGuard::start()`, so $_SESSION is live by this point.
  177. $deletedSprintName = '';
  178. if (isset($_SESSION['flash_deleted_sprint_name'])
  179. && is_string($_SESSION['flash_deleted_sprint_name'])
  180. ) {
  181. $deletedSprintName = $_SESSION['flash_deleted_sprint_name'];
  182. unset($_SESSION['flash_deleted_sprint_name']);
  183. }
  184. return Response::html($view->render('home', [
  185. 'title' => 'Sprint Planner',
  186. 'currentUser' => $currentUser,
  187. 'schemaVersion' => $schemaVersion,
  188. 'dbPath' => Connection::path(),
  189. 'appEnv' => $appEnv,
  190. 'oidcConfigured' => OidcClient::isConfigured(),
  191. 'localAdminEnabled' => LocalAdmin::isEnabled(),
  192. 'authError' => isset($req->query['auth_error']),
  193. 'deletedSprintName' => $deletedSprintName,
  194. 'csrfToken' => SessionGuard::csrfToken(),
  195. 'sprintRows' => $sprintRows,
  196. ]));
  197. });
  198. $router->get('/healthz', fn() => Response::text('ok'));
  199. // R01-N19: browser-fired CSP violation reports. Public POST (no auth, no
  200. // CSRF — see CspReportController). Body capped at 16 KiB; one audit row
  201. // per accepted report.
  202. $router->post('/csp-report', $cspReportCtrl->report(...));
  203. $router->get('/auth/login', $auth->login(...));
  204. $router->get('/auth/callback', $auth->callback(...));
  205. $router->post('/auth/logout', $auth->logout(...));
  206. $router->get('/auth/local', $auth->loginLocalForm(...));
  207. $router->post('/auth/local', $auth->loginLocal(...));
  208. $router->get('/workers', $workerCtrl->index(...));
  209. $router->post('/workers', $workerCtrl->create(...));
  210. $router->post('/workers/{id}', $workerCtrl->update(...));
  211. $router->get('/users', $userCtrl->index(...));
  212. $router->post('/users/{id}', $userCtrl->update(...));
  213. $router->post('/users/{id}/tombstone', $userCtrl->tombstone(...));
  214. $router->get('/sprints/import', $importCtrl->newForm(...));
  215. $router->post('/sprints/import', $importCtrl->upload(...));
  216. $router->get('/sprints/import/{token}', $importCtrl->preview(...));
  217. $router->post('/sprints/import/{token}', $importCtrl->commit(...));
  218. $router->get('/sprints/new', $sprintCtrl->newForm(...));
  219. $router->post('/sprints', $sprintCtrl->create(...));
  220. $router->get('/sprints/{id}', $sprintCtrl->show(...));
  221. $router->get('/sprints/{id}/present', $sprintCtrl->present(...));
  222. $router->get('/sprints/{id}/settings', $sprintCtrl->settings(...));
  223. $router->post('/sprints/{id}/delete', $sprintCtrl->delete(...));
  224. // JSON mutation endpoints (admin, CSRF via X-CSRF-Token header):
  225. $router->patch('/sprints/{id}', $sprintCtrl->updateMeta(...));
  226. $router->post('/sprints/{id}/weeks', $sprintCtrl->replaceWeeks(...));
  227. $router->post('/sprints/{id}/workers', $sprintCtrl->addWorker(...));
  228. $router->delete('/sprints/{id}/workers/{sw_id}', $sprintCtrl->removeWorker(...));
  229. $router->post('/sprints/{id}/workers/reorder', $sprintCtrl->reorderWorkers(...));
  230. $router->patch('/sprints/{id}/workers/{sw_id}', $sprintCtrl->updateWorker(...));
  231. // Phase 5 — Arbeitstage grid:
  232. $router->patch('/sprints/{id}/week-cells', $sprintCtrl->updateWeekCells(...));
  233. $router->patch('/sprints/{id}/week/{week_id}', $sprintCtrl->updateWeekDays(...));
  234. // Phase 6 — Task list:
  235. $router->get('/audit', $auditCtrl->index(...));
  236. $router->post('/sprints/{id}/tasks', $taskCtrl->create(...));
  237. $router->post('/sprints/{id}/tasks/reorder', $taskCtrl->reorder(...));
  238. $router->patch('/tasks/{id}', $taskCtrl->update(...));
  239. $router->delete('/tasks/{id}', $taskCtrl->delete(...));
  240. $router->patch('/tasks/{id}/assignments', $taskCtrl->updateAssignments(...));
  241. // Phase 18 — task-cell status (any signed-in user, gated by global flag):
  242. $router->patch('/tasks/{id}/assignments/status', $taskCtrl->updateAssignmentsStatus(...));
  243. // Phase 22 — task move/copy across sprints (admin):
  244. $router->post('/tasks/{id}/move', $taskCtrl->moveToSprint(...));
  245. $router->post('/tasks/{id}/copy', $taskCtrl->copyToSprint(...));
  246. // Phase 18 — global app settings (admin):
  247. $router->get('/settings', $settingsCtrl->show(...));
  248. $router->post('/settings', $settingsCtrl->update(...));
  249. // ---------------------------------------------------------------------------
  250. // Dispatch
  251. // ---------------------------------------------------------------------------
  252. $request = Request::fromGlobals();
  253. // R01-N24: refuse to dispatch oversized request bodies. The cap (1 MiB,
  254. // `Request::MAX_BODY_BYTES`) is well above any legitimate JSON payload the
  255. // app expects — the largest batch endpoint
  256. // (`PATCH /sprints/{id}/week-cells`) is bounded at 5000 cells in the
  257. // controller, comfortably under that. Bodies are short-circuited inside
  258. // `Request::fromGlobals()` so the buffer is never held in PHP memory.
  259. // `Response::err` is the canonical JSON envelope; HTML form clients will
  260. // see the JSON in the browser, which is acceptable for a degenerate
  261. // >1 MiB form POST.
  262. if ($request->bodyTooLarge) {
  263. Response::err(
  264. 'request_too_large',
  265. 'Request body exceeds the ' . (Request::MAX_BODY_BYTES >> 10) . ' KiB cap',
  266. 413,
  267. )->send();
  268. if (ob_get_level() > 0) {
  269. @ob_end_flush();
  270. }
  271. exit;
  272. }
  273. // R01-N05: when `APP_BASE_URL` declares HTTPS, refuse to serve sensitive
  274. // flows over plain HTTP — redirect the user to the canonical scheme before
  275. // any controller, session, or auth logic runs. `/healthz` is exempt so
  276. // liveness probes continue to work over either scheme. The decision uses
  277. // the trusted-proxy helper so a TLS-terminating reverse proxy can pass
  278. // `X-Forwarded-Proto: https` and the app will treat the request as secure.
  279. $baseUrl = (string) (getenv('APP_BASE_URL') ?: '');
  280. $baseIsHttps = str_starts_with($baseUrl, 'https://');
  281. $proxies = TrustedProxies::fromEnv();
  282. $requestIsHttps = $proxies->isHttps($_SERVER);
  283. // Only redirect when we can be SURE the live request is genuinely HTTP —
  284. // otherwise a TLS proxy that forgot to set `X-Forwarded-Proto` would loop
  285. // forever (proxy talks HTTPS to user, talks HTTP to us, we redirect, …).
  286. // Sure cases:
  287. // * no `TRUSTED_PROXIES` configured → REMOTE_ADDR is the user, so the
  288. // server-side scheme is authoritative;
  289. // * `TRUSTED_PROXIES` configured AND REMOTE_ADDR is a trusted proxy AND
  290. // it explicitly told us `X-Forwarded-Proto: http`.
  291. $xfpRaw = (string) ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? '');
  292. $xfp = strtolower(trim(strtok($xfpRaw, ',') ?: ''));
  293. $remote = (string) ($_SERVER['REMOTE_ADDR'] ?? '');
  294. $noProxy = getenv('TRUSTED_PROXIES') === false || trim((string) getenv('TRUSTED_PROXIES')) === '';
  295. $knownHttp = !$requestIsHttps && (
  296. $noProxy
  297. || ($remote !== '' && $proxies->isTrusted($remote) && $xfp === 'http')
  298. );
  299. if ($baseIsHttps && $knownHttp && $request->path !== '/healthz') {
  300. // Cross-origin (scheme-changing) redirect — must go through
  301. // Response::external() because Response::redirect() only accepts
  302. // path-only locations now (R01-N20).
  303. $target = rtrim($baseUrl, '/') . ($_SERVER['REQUEST_URI'] ?? '/');
  304. Response::external($target, 308)->send();
  305. if (ob_get_level() > 0) {
  306. @ob_end_flush();
  307. }
  308. exit;
  309. }
  310. // R01-N13: now that we know the resolved HTTPS posture, re-register the
  311. // fatal handler so a fatal mid-dispatch lands HSTS too. Cheap; just a
  312. // closure replacement.
  313. FatalErrorHandler::register($appEnv, $baseIsHttps);
  314. $response = $router->dispatch($request);
  315. // Apply security headers to every response (spec §9). Sourced from the
  316. // FatalErrorHandler so the happy path and the 500-fallback share a single
  317. // CSP + header set — there's no way for a future edit to drift between
  318. // the two paths.
  319. foreach (FatalErrorHandler::securityHeaders($baseIsHttps) as $name => $value) {
  320. $response->withHeader($name, $value);
  321. }
  322. $response->send();
  323. // Flush the output buffer opened at the top.
  324. if (ob_get_level() > 0) {
  325. @ob_end_flush();
  326. }