Post-Deployment Website Security Checks in Native PHP 8.3+ Using an AI Analyzer
A deployment can pass its smoke tests while quietly weakening the browser’s security posture. A proxy change drops a header. A certificate replacement leaves an unexpected TLS configuration. The application still serves pages, so the release looks healthy.
This project adds a public website security check to the end of every production deployment. Native PHP 8.3 calls the Website Security Analyzer, validates its response, stores a private report, and returns an exit status that the deployment runner can enforce.
The analyzer performs bounded, non-invasive analysis of public HTTPS and browser security posture. Treat its findings as useful deployment evidence, not as a penetration test or proof that an application is secure.
Get access and activate a service token
- Register an account, or sign in.
- Open the Website Security Analyzer service and plan page.
- Choose an available Free, Plus, or Pro plan and complete activation. Select capacity for your deployment frequency, including occasional repeated checks.
- Open the official documentation, find the Service token panel, and copy the service-scoped token.
This service requires authentication. It accepts a Bearer token, an X-API-Token header, or a token query parameter. We use Bearer authentication to keep credentials out of URLs. Regenerating the token revokes the previous active token: update the deployment runner’s configuration immediately after rotation.
The exact request is POST https://ai.mihajlo.mk/api/website-security-analyzer-api/v1/analyze-website, with a JSON body containing url. First, run this minimal request against your own public HTTPS website. Replace the placeholders locally; keep shell tracing disabled.
umask 077
mkdir -p .private
curl --silent --show-error --fail-with-body \
--connect-timeout 3 --max-time 15 --config - <<'EOF'
url = "https://ai.mihajlo.mk/api/website-security-analyzer-api/v1/analyze-website"
request = "POST"
header = "Authorization: Bearer YOUR_SERVICE_TOKEN"
header = "Content-Type: application/json"
data = "{\"url\":\"https://YOUR_PUBLIC_HOST/\"}"
output = ".private/sample.json"
EOF
Inspect the HTTP outcome and saved response privately. Do not commit this capture. The supplied contract identifies the information returned, but does not specify its exact JSON paths. Consequently, this implementation uses configured JSON pointers rather than guessing response field names.
Before building the integration, create $HOME/.config/deploy-security/production.env on the deployment runner, outside the web root, with permissions 0600:
SECURITY_API_TOKEN='YOUR_SERVICE_TOKEN'
SECURITY_SITE_URL='https://YOUR_PUBLIC_HOST/'
SECURITY_SCORE_POINTER='/REPLACE_WITH_VERIFIED_PATH'
SECURITY_FINDINGS_POINTER='/REPLACE_WITH_VERIFIED_PATH'
SECURITY_TLS_POINTER='/REPLACE_WITH_VERIFIED_PATH'
SECURITY_RECOMMENDATIONS_POINTER='/REPLACE_WITH_VERIFIED_PATH'
SECURITY_BLOCK_GROUPS='REPLACE_WITH_VERIFIED_GROUP_NAME'
Set each pointer from the successful response and documentation. JSON pointers use slash-separated paths; encode a literal slash as ~1 and a literal tilde as ~0. Set the comma-separated blocking groups to the exact severity labels your policy rejects. These are local configuration names, not additional API parameters.
Build a small deployment companion
Use PHP 8.3 or later with cURL, Composer, and a trusted deployment runner. Install phpunit/phpunit:^11.5 for tests. The runtime needs no Composer dependencies.
mkdir -p src bin tests deploy
composer init --name=example/deploy-security --no-interaction
composer require --dev 'phpunit/phpunit:^11.5'
printf '%s\n' '.private/' '/vendor/' >> .gitignore
The project has four implementation files: src/Security.php, bin/check-security.php, tests/SecurityTest.php, and deploy/after-production.sh. Keep this checkout on the runner, outside the public document root.
A synchronous command fits a small team’s deployment workflow: the result belongs to one release and is immediately visible. Each request has a three-second connection timeout and a fifteen-second total timeout. Only an explicit rate-limit response receives one bounded retry. Network errors and server failures remain unresolved because replaying a POST could duplicate work or consume more quota.
Isolate transport and response mapping
Create src/Security.php. The transport fixes the API destination, disables redirects, verifies TLS, and caps the response body. The mapper preserves findings, TLS details, and recommendations without assuming their individual entry fields.
<?php
declare(strict_types=1);
namespace DeploySecurity;
final class Failure extends \RuntimeException
{
public function __construct(
public readonly string $kind,
public readonly ?int $status = null,
public readonly ?int $retryAfter = null,
) { parent::__construct($kind); }
}
interface Transport
{
// Returns [HTTP status, response body, Retry-After header].
public function send(string $token, string $body): array;
}
final class CurlTransport implements Transport
{
public function send(string $token, string $body): array
{
$c = curl_init(
'https://ai.mihajlo.mk/api/website-security-analyzer-api/v1/analyze-website'
);
if ($c === false) { throw new Failure('transport_unknown'); }
$response = '';
$retry = '';
curl_setopt_array($c, [
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $body,
CURLOPT_HTTPHEADER => [
'Authorization: Bearer ' . $token,
'Content-Type: application/json',
'Accept: application/json',
],
CURLOPT_CONNECTTIMEOUT => 3,
CURLOPT_TIMEOUT => 15,
CURLOPT_FOLLOWLOCATION => false,
CURLOPT_PROTOCOLS => CURLPROTO_HTTPS,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_WRITEFUNCTION => static function ($c, string $chunk)
use (&$response): int {
if (strlen($response) + strlen($chunk) > 1048576) { return 0; }
$response .= $chunk;
return strlen($chunk);
},
CURLOPT_HEADERFUNCTION => static function ($c, string $line)
use (&$retry): int {
if (strncasecmp($line, 'Retry-After:', 12) === 0) {
$retry = trim(substr($line, 12));
}
return strlen($line);
},
]);
$ok = curl_exec($c);
$status = (int) curl_getinfo($c, CURLINFO_RESPONSE_CODE);
curl_close($c);
if ($ok === false) { throw new Failure('transport_unknown'); }
return [$status, $response, $retry];
}
}
final readonly class Report
{
public function __construct(
public int|float $score,
public array $findings,
public object $tls,
public array $recommendations,
public bool $blocked,
) {}
}
final class Analyzer
{
public function __construct(
private Transport $transport,
private \Closure $pause,
) {}
private static function pointer(mixed $value, string $path): mixed
{
if ($path === '') { return $value; }
if (!str_starts_with($path, '/')) { throw new Failure('configuration'); }
foreach (explode('/', substr($path, 1)) as $part) {
if (preg_match('/~(?![01])/', $part)) {
throw new Failure('configuration');
}
$key = str_replace(['~1', '~0'], ['/', '~'], $part);
if (is_object($value) && property_exists($value, $key)) {
$value = $value->{$key};
} elseif (is_array($value) && array_key_exists($key, $value)) {
$value = $value[$key];
} else { throw new Failure('contract'); }
}
return $value;
}
public function analyze(string $url, string $token, array $paths, array $block): Report
{
$body = json_encode(['url' => $url], JSON_THROW_ON_ERROR);
for ($attempt = 0; ; $attempt++) {
[$status, $json, $retry] = $this->transport->send($token, $body);
if ($status !== 429) { break; }
$date = strtotime($retry);
$delay = ctype_digit($retry) ? min(86400, (int) $retry)
: ($date === false ? 2 : max(0, $date - time()));
if ($attempt === 1 || $delay > 10) {
throw new Failure('rate_limited', 429, $delay);
}
($this->pause)(max(1, $delay) * 1000 + random_int(0, 250));
}
if ($status < 200 || $status >= 300) {
throw new Failure('http', $status);
}
try { $data = json_decode($json, false, 64, JSON_THROW_ON_ERROR); }
catch (\JsonException) { throw new Failure('contract'); }
$score = self::pointer($data, $paths['score']);
$groups = self::pointer($data, $paths['findings']);
$tls = self::pointer($data, $paths['tls']);
$recommendations = self::pointer($data, $paths['recommendations']);
if ((!is_int($score) && !is_float($score))
|| !is_finite((float) $score) || !$groups instanceof \stdClass
|| !$tls instanceof \stdClass || !is_array($recommendations)) {
throw new Failure('contract');
}
$findings = get_object_vars($groups);
foreach ($findings as $items) {
if (!is_array($items)) { throw new Failure('contract'); }
}
$blocked = false;
foreach ($block as $group) {
if (!array_key_exists($group, $findings)) {
throw new Failure('contract');
}
$blocked = $blocked || count($findings[$group]) > 0;
}
return new Report($score, $findings, $tls, $recommendations, $blocked);
}
}
The boundary deliberately requires a numeric score, an object containing severity arrays, a TLS object, and a recommendations array. Verify those shapes during setup. If the documented response differs, adjust this mapper and its tests explicitly. Missing configured blocking groups fail validation; an unfamiliar response must never become a clean bill of health.
No score range or direction is assumed. The release policy uses severity groups, while preserving the score for review. A 429 honors numeric or date-based Retry-After; longer waits are reported to the runner instead of holding the deployment open.
Make the command enforce the policy
Create bin/check-security.php. Native PHP does not automatically load environment files; the shell hook below exports configuration before execution.
<?php
declare(strict_types=1);
require __DIR__ . '/../src/Security.php';
use DeploySecurity\{Analyzer, CurlTransport, Failure};
umask(0077);
$id = 'unknown';
function required(string $name): string {
$value = getenv($name);
if ($value === false || $value === '') { throw new Failure('configuration'); }
return $value;
}
try {
$id = substr(required('DEPLOYMENT_ID'), 0, 128);
$url = required('SECURITY_SITE_URL');
$parts = parse_url($url);
$token = required('SECURITY_API_TOKEN');
if (!filter_var($url, FILTER_VALIDATE_URL)
|| ($parts['scheme'] ?? '') !== 'https'
|| isset($parts['user']) || isset($parts['pass'])
|| isset($parts['query']) || isset($parts['fragment'])
|| preg_match('/[\r\n]/', $token)) {
throw new Failure('configuration');
}
$paths = [];
foreach (['score', 'findings', 'tls', 'recommendations'] as $name) {
$paths[$name] = required('SECURITY_' . strtoupper($name) . '_POINTER');
}
$block = array_map('trim', explode(',', required('SECURITY_BLOCK_GROUPS')));
if (in_array('', $block, true)) { throw new Failure('configuration'); }
$analyzer = new Analyzer(new CurlTransport(), static fn(int $ms) => usleep($ms * 1000));
$report = $analyzer->analyze($url, $token, $paths, $block);
$dir = __DIR__ . '/../.private';
if (!is_dir($dir) && !mkdir($dir, 0700, true)) {
throw new Failure('artifact');
}
$json = json_encode(['deployment' => $id, 'report' => $report], JSON_THROW_ON_ERROR);
$file = $dir . '/' . hash('sha256', $id) . '.json';
if (file_put_contents($file, $json, LOCK_EX) !== strlen($json)) {
throw new Failure('artifact');
}
$event = ['state' => $report->blocked ? 'findings' : 'passed', 'score' => $report->score];
$exit = $report->blocked ? 1 : 0;
} catch (\Throwable $e) {
$event = $e instanceof Failure
? ['state' => $e->kind, 'http_status' => $e->status, 'retry_after' => $e->retryAfter]
: ['state' => 'internal'];
$exit = ($e instanceof Failure && $e->kind === 'configuration') ? 2 : 75;
}
fwrite(STDERR, json_encode([
'time' => gmdate(DATE_ATOM), 'deployment' => $id,
] + $event, JSON_THROW_ON_ERROR) . PHP_EOL);
exit($exit);
Exit 0 means the configured check passed; 1 means blocking findings; 2 means configuration failure; 75 means an unresolved operational or contract failure. Logs contain release identity and structured outcomes, never credentials or response bodies. Private artifacts retain the mapped evidence.
Test without spending service quota
Create tests/SecurityTest.php. These payloads are deliberately synthetic application fixtures, not examples of the provider’s response schema. Injecting the pause function keeps retry tests immediate.
<?php
declare(strict_types=1);
require_once __DIR__ . '/../src/Security.php';
use DeploySecurity\{Analyzer, Failure, Transport};
use PHPUnit\Framework\TestCase;
final class FakeTransport implements Transport {
public int $calls = 0;
public function __construct(private array $responses) {}
public function send(string $token, string $body): array {
$this->calls++;
return array_shift($this->responses);
}
}
final class SecurityTest extends TestCase {
private const PATHS = [
'score' => '/metric', 'findings' => '/levels',
'tls' => '/connection', 'recommendations' => '/tips',
];
private const GOOD = '{"metric":72,"levels":{"block":[]},"connection":{},"tips":[]}';
private function analyze(FakeTransport $fake): DeploySecurity\Report {
return (new Analyzer($fake, static function (int $ms): void {}))
->analyze('https://example.com/', 'TEST_ONLY', self::PATHS, ['block']);
}
public function testMappingAndBlocking(): void {
$data = json_decode(self::GOOD, true);
$data['levels']['block'] = [['synthetic' => 'finding']];
$data['connection'] = (object) ['synthetic' => 'TLS detail'];
$report = $this->analyze(new FakeTransport([[200, json_encode($data), '']]));
self::assertSame(72, $report->score);
self::assertTrue($report->blocked);
self::assertSame('TLS detail', $report->tls->synthetic);
self::assertSame([], $report->recommendations);
}
public function testRateLimitRetriesOnce(): void {
$fake = new FakeTransport([[429, '', '0'], [200, self::GOOD, '']]);
self::assertFalse($this->analyze($fake)->blocked);
self::assertSame(2, $fake->calls);
}
public function testAuthenticationFailureIsNotRetried(): void {
$fake = new FakeTransport([[401, '', '']]);
try { $this->analyze($fake); self::fail('Expected failure'); }
catch (Failure $e) { self::assertSame(401, $e->status); }
self::assertSame(1, $fake->calls);
}
public function testMissingGroupCannotPass(): void {
$json = str_replace('"block":[]', '"unrecognized":[]', self::GOOD);
$this->expectException(Failure::class);
$this->analyze(new FakeTransport([[200, $json, '']]));
}
}
Attach it to every production release
Create deploy/after-production.sh:
#!/bin/sh
set -eu
set +x
cd "$(dirname "$0")/.."
: "${DEPLOYMENT_ID:?Production runner must supply a unique release identifier}"
set -a
. "$HOME/.config/deploy-security/production.env"
set +a
exec php bin/check-security.php
Configure your existing production pipeline to invoke sh deploy/after-production.sh after deployment and successful public readiness checks. Supply its immutable release identifier as DEPLOYMENT_ID. Serialize production releases through this stage so the public URL still represents the release being checked. Include rollback deployments in the same path.
Give this stage a sixty-second budget, preserve its exit status, and disable blanket job retries. A failed post-deployment check means the release is already live; your runbook must assign investigation and any rollback decision. If your hosting supports traffic promotion, check the public candidate before promotion as well.
Keep the target URL in trusted configuration, never in request input. Protect report access and set artifact retention deliberately: findings can reveal useful reconnaissance details. Do not render their contents as trusted HTML.
Verify the deployment evidence
Common failures have different remedies. Authentication errors require checking activation and token rotation. Rate limits require reviewing plan capacity and scheduling a later check. Transport failures require checking runner connectivity and CA certificates without disabling verification. Contract failures require comparing the private response with the configured pointers and mapper.
Run vendor/bin/phpunit tests, then perform a controlled production deployment and confirm:
- The hook runs after public readiness, including for rollback releases.
- The configured paths and severity names match the actual response.
- A private artifact and structured log identify the same deployment.
- Blocking findings and operational failures both fail the stage.
- Tokens and report bodies stay out of repository history and pipeline logs.
The valuable outcome is a repeatable question attached to every release: what changed in the security posture visitors can actually observe? Answer it consistently, preserve the evidence, and make unresolved results someone’s responsibility.