<?php

namespace Tests\Feature\Api\V1\FullSurface;

use Tests\Feature\Api\V1\FullSurface\Support\FullSurfaceE2EContractCase;

class ApiUrlFetchSsrfAndCallbackSafetyContractTest extends FullSurfaceE2EContractCase
{
    public function test_url_accepting_routes_reject_internal_network_targets_cleanly(): void
    {
        $routes = array_slice($this->apiRoutesContainingAny(['webhook', 'callback', 'import', 'export', 'avatar', 'logo', 'settings', 'notification', 'whatsapp']), 0, 100);
        $dangerousUrls = [
            'http://127.0.0.1:80/admin',
            'http://localhost:3306/',
            'http://169.254.169.254/latest/meta-data/',
            'file:///etc/passwd',
            'gopher://127.0.0.1:6379/_INFO',
        ];

        foreach ($routes as $route) {
            $method = $this->primaryMethod($route);
            if (! in_array($method, ['POST', 'PUT', 'PATCH'], true)) {
                continue;
            }

            foreach ($dangerousUrls as $url) {
                $uri = $route->uri();
                $payload = $this->payloadFor($method, $uri) + [
                    'url' => $url,
                    'callback_url' => $url,
                    'webhook_url' => $url,
                    'image_url' => $url,
                    'remote_file_url' => $url,
                ];

                $response = $this->requestAs($this->actorFor($uri), $method, $uri, $payload);

                $this->assertControlled($response, $method, $uri);
                $this->assertNoServerError($response, 'SSRF URL probe at ' . $method . ' ' . $uri);
            }
        }
    }
}
