1
0

index.php 16 KB

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