<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * Echoes one query parameter back, so a deploy can prove GET parameters arrive.
 *
 * Twice now, prod has served requests to PHP without the query string: the vhost's
 * fallback was `try_files $uri $uri/ /index.php;` with the `?$query_string`
 * missing. Every GET parameter on the site was discarded, which breaks signed
 * URLs, verification links, OAuth redirects, pagination, and `?new=1`, so a new
 * chat resolved to the user's most recent conversation and opened on the publish
 * approval it was parked on.
 *
 * Nothing noticed, either time. The right commit was deployed, the files on disk
 * were correct, the application booted, /up returned 200, and the chat itself
 * works because it sends over POST. The first occurrence was read as a stale build
 * and papered over in the browser, which hid the second for five weeks.
 *
 * Unauthenticated on purpose: it returns only what the caller just sent, so it
 * discloses nothing, and a secret here would be one more thing to configure
 * before the check works. An invokable class rather than a route closure because
 * deploy.sh runs `artisan optimize`, and route caching refuses to serialise a
 * closure.
 *
 * It is a probe, not an echo service, which is why only a plain token comes back.
 * `response()->json()` does not escape its payload - Laravel leaves the encoding
 * options at 0, so `?ping=<script>` was returned verbatim. The content type is
 * application/json and no current browser renders that as HTML, so this was not
 * reachable as script, but an unauthenticated endpoint that reflects arbitrary
 * input is still a thing to have to think about on every future audit, and
 * nothing needs it: deploy.sh sends the short commit sha.
 *
 * Anything that is not a short token reads back as null, which is the same answer
 * as a dropped query string. That is correct for a probe - it says "the value did
 * not come back", which is all the caller is asking - and it cannot be mistaken
 * for success, because the caller compares against what it sent.
 */
class QueryStringCheckController extends Controller
{
    /** A commit sha, or anything else a deploy might reasonably stamp a probe with. */
    private const PING = '/^[A-Za-z0-9._-]{1,64}$/D';

    public function __invoke(Request $request): JsonResponse
    {
        $ping = $request->query('ping');

        return response()->json([
            // is_string first: ?ping[]=a arrives as an array, and casting that to
            // string is a warning and the word "Array", which would then match.
            'ping' => is_string($ping) && preg_match(self::PING, $ping) === 1 ? $ping : null,
        ]);
    }
}
