59 lines
2.2 KiB
PHP
59 lines
2.2 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Scribase\Mcp\Tests;
|
|
|
|
use PHPUnit\Framework\TestCase;
|
|
use Scribase\Mcp\SqlLiteral;
|
|
|
|
final class SqlLiteralTest extends TestCase
|
|
{
|
|
public function testEncodesPlainAsciiAsHexDecodeExpression(): void
|
|
{
|
|
$encoded = SqlLiteral::encode('hello');
|
|
self::assertSame("convert_from(decode('68656c6c6f', 'hex'), 'UTF8')", $encoded);
|
|
}
|
|
|
|
public function testNeverEmitsAQuoteCharacterForAnAdversarialPayload(): void
|
|
{
|
|
$adversarial = [
|
|
"x'); drop table hermes_agent_memories; --",
|
|
"' OR '1'='1",
|
|
"'; select pg_sleep(5); --",
|
|
"\\'; drop table x; --", // backslash + quote combo
|
|
"a\x00b", // embedded NUL, stripped by the encoder
|
|
];
|
|
|
|
foreach ($adversarial as $payload) {
|
|
$encoded = SqlLiteral::encode($payload);
|
|
self::assertStringStartsWith("convert_from(decode('", $encoded);
|
|
self::assertMatchesRegularExpression(
|
|
"/^convert_from\\(decode\\('[0-9a-f]*', 'hex'\\), 'UTF8'\\)\$/",
|
|
$encoded,
|
|
"payload {$payload} produced a literal containing something other than hex digits",
|
|
);
|
|
}
|
|
}
|
|
|
|
public function testNeverEmitsABackslashForNonAsciiContent(): void
|
|
{
|
|
// The exact class of bug the hex encoding fixes, per the Python
|
|
// sibling's real re-verification: json_encode()'s default escaping
|
|
// turns non-ASCII characters into `\uXXXX` sequences, which would
|
|
// trip the control plane's backslash guard if interpolated as a
|
|
// classic quoted-and-escaped literal.
|
|
$metadataJson = json_encode(['note' => 'café, Türkçe, 日本語'], \JSON_THROW_ON_ERROR);
|
|
$encoded = SqlLiteral::encode($metadataJson);
|
|
self::assertStringNotContainsString('\\', $encoded);
|
|
}
|
|
|
|
public function testRoundTripsThroughHexDecoding(): void
|
|
{
|
|
$original = "a mixed payload: café \" with a 'quote' and a \\backslash\\";
|
|
$encoded = SqlLiteral::encode($original);
|
|
preg_match("/decode\\('([0-9a-f]+)', 'hex'\\)/", $encoded, $matches);
|
|
self::assertSame($original, hex2bin($matches[1]));
|
|
}
|
|
}
|