index.php 17 KB

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