<?php

namespace Tests\Feature;

use PHPUnit\Framework\Attributes\DataProvider;
use Tests\TestCase;

/**
 * A deploy can prove the web server hands PHP the query string.
 *
 * Prod's vhost served requests without it twice, most recently for five weeks:
 * `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 and pagination, and made ?new=1 open the user's most
 * recent conversation on the publish approval it was parked on.
 *
 * Every signal said healthy: the right commit was deployed, the files on disk were
 * correct, the application booted, /up returned 200, and the chat works because it
 * sends over POST. So deploy.sh asks the one question that was not being asked.
 */
class AQueryStringMustReachTheApplicationTest extends TestCase
{
    public function test_the_route_echoes_the_parameter_it_was_given(): void
    {
        $this->getJson('/up/query?ping=abc123')->assertOk()->assertJson(['ping' => 'abc123']);
    }

    /** Null rather than an invented value, so a dropped parameter reads as one. */
    public function test_it_reports_null_when_no_parameter_arrived(): void
    {
        $this->getJson('/up/query')->assertOk()->assertJson(['ping' => null]);
    }

    /** The sha deploy.sh actually sends, which is the case that has to work. */
    public function test_a_commit_sha_comes_back(): void
    {
        $this->getJson('/up/query?ping=f33edf89')->assertOk()->assertJson(['ping' => 'f33edf89']);
    }

    /**
     * Nothing but a plain token is reflected.
     *
     * response()->json() does not escape what it is handed, so this endpoint used
     * to return `?ping=<script>` byte for byte. Not reachable as script behind an
     * application/json content type, and now not present either, because an
     * unauthenticated route that reflects arbitrary input is a thing to have to
     * re-reason about on every audit and nothing needs it.
     */
    #[DataProvider('rejected')]
    public function test_anything_that_is_not_a_token_reads_back_as_null(string $query): void
    {
        $this->getJson('/up/query?'.$query)
            ->assertOk()
            ->assertJson(['ping' => null])
            ->assertDontSee('script', false);
    }

    /** @return array<string, list<string>> */
    public static function rejected(): array
    {
        return [
            'a script tag' => ['ping='.urlencode('<script>alert(1)</script>')],
            'quotes and ampersands' => ['ping='.urlencode('"\'&')],
            'an array' => ['ping[]=a'],
            'longer than a sha' => ['ping='.str_repeat('a', 65)],
            'empty' => ['ping='],
        ];
    }

    /**
     * The deploy script is deliberately not asserted on.
     *
     * There was a test here reading deploy.sh as text, checking it called this
     * route and compared the answer. Both of those changes were reverted on
     * instruction: deploy.sh is not to be touched for this release, and neither
     * change was needed by it. Step 12 becoming fatal is only worth having if prod
     * runs opcache.validate_timestamps=0, which is unconfirmed, and the
     * query-string check guards a vhost mistake that deploying cannot cause and
     * deploy.sh cannot prevent - it would only notice on the next deploy after
     * someone had already broken nginx.
     *
     * So the check lives in the release doc as a one-line curl instead, and this
     * route is what makes that one line possible. The route is worth having either
     * way: the fault it detects ran undetected for five weeks and was misdiagnosed
     * twice, and nothing else on the site answers the question.
     *
     * Deliberately not replaced with an assertion that the doc contains the curl.
     * Grepping prose for a command tells you the sentence exists, not that anyone
     * runs it, and the tests above already cover the only part that can regress in
     * code.
     */
    public function test_the_route_is_reachable_without_signing_in(): void
    {
        // The property that makes it usable from a deploy, a cron or a shell on a
        // box with no session: no redirect to /login, no token to configure first.
        $this->getJson('/up/query?ping=f33edf89')
            ->assertOk()
            ->assertJson(['ping' => 'f33edf89']);
    }
}
