ManualBlocksController.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Application\Admin;
  4. use App\Domain\Audit\AuditAction;
  5. use App\Domain\Audit\AuditEmitter;
  6. use App\Domain\Ip\Cidr;
  7. use App\Domain\Ip\InvalidCidrException;
  8. use App\Domain\Ip\InvalidIpException;
  9. use App\Domain\Ip\IpAddress;
  10. use App\Domain\ManualBlock\ManualBlock;
  11. use App\Infrastructure\ManualBlock\ManualBlockRepository;
  12. use App\Infrastructure\Reputation\BlocklistCache;
  13. use App\Infrastructure\Reputation\CidrEvaluatorFactory;
  14. use DateTimeImmutable;
  15. use DateTimeZone;
  16. use Doctrine\DBAL\Connection;
  17. use Psr\Http\Message\ResponseInterface;
  18. use Psr\Http\Message\ServerRequestInterface;
  19. /**
  20. * Admin CRUD over `manual_blocks`. SPEC §6 RBAC:
  21. * - Operator: create + delete
  22. * - Viewer: list + get
  23. *
  24. * Per-route role enforcement happens in `AppFactory` via `RbacMiddleware::require`;
  25. * this controller only sees authorized requests.
  26. *
  27. * CIDR canonicalization (recommendation (c) in M06.md): non-canonical input
  28. * such as `203.0.113.55/24` is silently normalized to `203.0.113.0/24` and
  29. * the response body echoes both `cidr` and `normalized_from`. Canonical
  30. * input omits the field. This is the behaviour the M06 acceptance script
  31. * tests for.
  32. */
  33. final class ManualBlocksController
  34. {
  35. use AdminControllerSupport;
  36. public function __construct(
  37. private readonly ManualBlockRepository $manualBlocks,
  38. private readonly CidrEvaluatorFactory $evaluator,
  39. private readonly BlocklistCache $blocklistCache,
  40. private readonly AuditEmitter $audit,
  41. private readonly Connection $connection,
  42. ) {
  43. }
  44. public function list(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
  45. {
  46. $page = self::pagination($request);
  47. $params = $request->getQueryParams();
  48. $kind = null;
  49. if (isset($params['kind']) && is_string($params['kind']) && in_array($params['kind'], [ManualBlock::KIND_IP, ManualBlock::KIND_SUBNET], true)) {
  50. $kind = $params['kind'];
  51. }
  52. $rows = $this->manualBlocks->list($page['limit'], $page['offset'], ['kind' => $kind]);
  53. $total = $this->manualBlocks->count($kind);
  54. return self::json($response, 200, [
  55. 'items' => array_map(static fn (ManualBlock $b) => $b->toArray(), $rows),
  56. 'page' => $page['page'],
  57. 'limit' => $page['limit'],
  58. 'total' => $total,
  59. ]);
  60. }
  61. /**
  62. * @param array{id: string} $args
  63. */
  64. public function show(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
  65. {
  66. $id = self::parseId($args['id']);
  67. if ($id === null) {
  68. return self::error($response, 404, 'not_found');
  69. }
  70. $entry = $this->manualBlocks->findById($id);
  71. if ($entry === null) {
  72. return self::error($response, 404, 'not_found');
  73. }
  74. return self::json($response, 200, $entry->toArray());
  75. }
  76. public function create(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
  77. {
  78. $body = self::jsonBody($request);
  79. $errors = [];
  80. $kind = $body['kind'] ?? null;
  81. if (!in_array($kind, [ManualBlock::KIND_IP, ManualBlock::KIND_SUBNET], true)) {
  82. return self::validationFailed($response, ['kind' => 'required, "ip" or "subnet"']);
  83. }
  84. $reason = null;
  85. if (array_key_exists('reason', $body)) {
  86. if ($body['reason'] !== null && !is_string($body['reason'])) {
  87. $errors['reason'] = 'must be string or null';
  88. } else {
  89. // SEC_REVIEW F52: strip C0/C1 control characters before
  90. // the reason lands in `audit_log.target_label` /
  91. // `details_json` to defeat log-injection and terminal-
  92. // escape attacks on log viewers.
  93. $reason = is_string($body['reason'])
  94. ? self::stripControlChars($body['reason'])
  95. : null;
  96. }
  97. }
  98. $expiresAt = null;
  99. if (array_key_exists('expires_at', $body) && $body['expires_at'] !== null) {
  100. if (!is_string($body['expires_at'])) {
  101. $errors['expires_at'] = 'must be ISO-8601 string or null';
  102. } else {
  103. $parsed = self::parseTimestamp($body['expires_at']);
  104. if ($parsed === null) {
  105. $errors['expires_at'] = 'must be ISO-8601 (e.g. 2026-12-31T23:59:59Z)';
  106. } else {
  107. $expiresAt = $parsed;
  108. }
  109. }
  110. }
  111. if ($kind === ManualBlock::KIND_IP) {
  112. if (!isset($body['ip']) || !is_string($body['ip']) || $body['ip'] === '') {
  113. $errors['ip'] = 'required for kind=ip';
  114. }
  115. if (isset($body['cidr'])) {
  116. $errors['cidr'] = 'forbidden for kind=ip';
  117. }
  118. if ($errors !== []) {
  119. return self::validationFailed($response, $errors);
  120. }
  121. try {
  122. /** @var string $ipText */
  123. $ipText = $body['ip'];
  124. $ip = IpAddress::fromString($ipText);
  125. } catch (InvalidIpException $e) {
  126. return self::validationFailed($response, ['ip' => $e->getMessage()]);
  127. }
  128. $userId = self::actingUserId($request);
  129. $auditCtx = self::auditContext($request);
  130. $id = $this->connection->transactional(function () use ($ip, $reason, $expiresAt, $userId, $auditCtx): int {
  131. $id = $this->manualBlocks->createIp($ip, $reason, $expiresAt, $userId);
  132. $this->audit->emitOrThrow(
  133. AuditAction::MANUAL_BLOCK_CREATED,
  134. 'manual_block',
  135. $id,
  136. ['kind' => 'ip', 'ip' => $ip->text(), 'reason' => $reason, 'expires_at' => $expiresAt?->format('c')],
  137. $auditCtx,
  138. $ip->text(),
  139. );
  140. return $id;
  141. });
  142. $this->evaluator->invalidate();
  143. $this->blocklistCache->invalidateAll();
  144. // Eagerly rebuild so any overlap with the allowlist surfaces as
  145. // a WARNING log entry while we're still in this request — gives
  146. // admins immediate feedback on a suspicious configuration.
  147. $this->evaluator->get();
  148. $created = $this->manualBlocks->findById($id);
  149. if ($created === null) {
  150. return self::error($response, 500, 'create_failed');
  151. }
  152. return self::json($response, 201, $created->toArray());
  153. }
  154. // kind=subnet
  155. if (!isset($body['cidr']) || !is_string($body['cidr']) || $body['cidr'] === '') {
  156. $errors['cidr'] = 'required for kind=subnet';
  157. }
  158. if (isset($body['ip'])) {
  159. $errors['ip'] = 'forbidden for kind=subnet';
  160. }
  161. if ($errors !== []) {
  162. return self::validationFailed($response, $errors);
  163. }
  164. try {
  165. /** @var string $cidrInput */
  166. $cidrInput = $body['cidr'];
  167. $cidr = Cidr::fromString($cidrInput);
  168. } catch (InvalidCidrException $e) {
  169. return self::validationFailed($response, ['cidr' => $e->getMessage()]);
  170. }
  171. $userId = self::actingUserId($request);
  172. $auditCtx = self::auditContext($request);
  173. $id = $this->connection->transactional(function () use ($cidr, $reason, $expiresAt, $userId, $auditCtx): int {
  174. $id = $this->manualBlocks->createSubnet($cidr, $reason, $expiresAt, $userId);
  175. $this->audit->emitOrThrow(
  176. AuditAction::MANUAL_BLOCK_CREATED,
  177. 'manual_block',
  178. $id,
  179. ['kind' => 'subnet', 'cidr' => $cidr->text(), 'reason' => $reason, 'expires_at' => $expiresAt?->format('c')],
  180. $auditCtx,
  181. $cidr->text(),
  182. );
  183. return $id;
  184. });
  185. $this->evaluator->invalidate();
  186. $this->blocklistCache->invalidateAll();
  187. $this->evaluator->get();
  188. $created = $this->manualBlocks->findById($id);
  189. if ($created === null) {
  190. return self::error($response, 500, 'create_failed');
  191. }
  192. $payload = $created->toArray();
  193. if ($cidrInput !== $cidr->text()) {
  194. $payload['normalized_from'] = $cidrInput;
  195. }
  196. return self::json($response, 201, $payload);
  197. }
  198. /**
  199. * @param array{id: string} $args
  200. */
  201. public function delete(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
  202. {
  203. $id = self::parseId($args['id']);
  204. if ($id === null) {
  205. return self::error($response, 404, 'not_found');
  206. }
  207. $existing = $this->manualBlocks->findById($id);
  208. if ($existing === null) {
  209. return self::error($response, 404, 'not_found');
  210. }
  211. $label = $existing->kind === ManualBlock::KIND_IP
  212. ? $existing->ip?->text()
  213. : $existing->cidr?->text();
  214. $auditCtx = self::auditContext($request);
  215. $this->connection->transactional(function () use ($id, $existing, $label, $auditCtx): void {
  216. $this->manualBlocks->delete($id);
  217. $this->audit->emitOrThrow(
  218. AuditAction::MANUAL_BLOCK_DELETED,
  219. 'manual_block',
  220. $id,
  221. ['kind' => $existing->kind, 'ip' => $existing->ip?->text(), 'cidr' => $existing->cidr?->text(), 'reason' => $existing->reason],
  222. $auditCtx,
  223. $label,
  224. );
  225. });
  226. $this->evaluator->invalidate();
  227. $this->blocklistCache->invalidateAll();
  228. return $response->withStatus(204);
  229. }
  230. private static function parseId(string $raw): ?int
  231. {
  232. return preg_match('/^[1-9][0-9]*$/', $raw) === 1 ? (int) $raw : null;
  233. }
  234. private static function parseTimestamp(string $iso): ?DateTimeImmutable
  235. {
  236. try {
  237. return new DateTimeImmutable($iso, new DateTimeZone('UTC'));
  238. } catch (\Exception) {
  239. return null;
  240. }
  241. }
  242. }