Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327<?php
declare(strict_types=1);
namespace Wotnak\Atproto\Lexicon;
use Wotnak\Atproto\Identifier\CidParser;use Wotnak\Atproto\Identifier\NsidParser;
/** * Validates AT Protocol data model values represented as JSON-decoded PHP. * * @api */final class DataModelValidator {
public function __construct( private readonly CidParser $cidParser = new CidParser(), private readonly NsidParser $nsidParser = new NsidParser(), ) {}
/** * Validates a complete AT Protocol JSON document. */ public function validateJsonDocument(mixed $value): ValidationResult { $context = new ValidationContext(); if (!$value instanceof \stdClass && (!\is_array($value) || \array_is_list($value))) { $context->addViolation('ATProto JSON documents must be objects.', 'invalid_lex_document'); } else { $this->validate($value, $context); } return new ValidationResult($context->violations(), $value); }
/** * Adds data model violations to the supplied validation context. */ public function validate(mixed $value, ValidationContext $context): void { /** @var list<\Wotnak\Atproto\Lexicon\DataModelValidationTask> $pending */ $paths = new DataModelValidationPaths($context->path()); $pending = [DataModelValidationTask::value($value, 0)]; while ($pending !== []) { $task = \array_pop($pending); if ($task->message !== NULL && $task->code !== NULL) { $context->addViolationAt($paths->render($task->path), $task->message, $task->code); continue; }
$current = $task->value; if (\is_string($current)) { if (!$this->isValidUtf8($current)) { $context->addViolationAt($paths->render($task->path), 'String must contain valid UTF-8.', 'invalid_utf8'); } continue; } if ($current === NULL || \is_bool($current) || \is_int($current)) { continue; } if (\is_float($current)) { if (self::integerValue($current) === NULL) { $context->addViolationAt( $paths->render($task->path), 'Floats are not valid ATProto data model values.', 'invalid_lex_value', ); } continue; } $isObject = $current instanceof \stdClass; if ($isObject) { $referenceId = 'object:' . \spl_object_id($current); if (isset($task->references[$referenceId])) { $context->addViolationAt( $paths->render($task->path), 'Cyclic objects are not valid ATProto data model values.', 'invalid_lex_cycle', ); continue; } $references = $task->references; $references[$referenceId] = TRUE; $current = \get_object_vars($current); } else { $references = $task->references; } if (!\is_array($current)) { $context->addViolationAt( $paths->render($task->path), 'Value is not a valid ATProto data model value.', 'invalid_lex_value', ); continue; } if (\array_key_exists('$bytes', $current)) { if (!$this->isBytesObject($current)) { $context->addViolationAt( $paths->render($task->path), 'Value is not a valid ATProto bytes object.', 'invalid_bytes', ); } continue; } if (\array_key_exists('$link', $current)) { $valid = $context->options->strict ? $this->isLinkObject($current) : $this->isLinkObjectLoose($current); if (!$valid) { $context->addViolationAt( $paths->render($task->path), 'Value is not a valid ATProto CID link.', 'invalid_cid_link', ); } continue; } if (($current['$type'] ?? NULL) === 'blob') { $valid = $context->options->strict ? $this->isBlobObject($current) : $this->isBlobObjectLoose($current); if (!$valid) { $context->addViolationAt($paths->render($task->path), 'Value is not a valid ATProto blob.', 'invalid_blob'); } continue; }
$isList = !$isObject && \array_is_list($current); if (!$isList && \array_key_exists('$type', $current) && !$this->isValidTypeDiscriminator($current['$type'])) { $context->addViolationAt( $paths->render($task->path), 'Object $type must be a valid Lexicon type reference.', 'invalid_lex_type', ); }
$keys = \array_keys($current); for ($index = \count($keys) - 1; $index >= 0; $index--) { $key = $keys[$index]; if (!$isList && (!\is_string($key) || $key === '' || !$this->isValidUtf8($key))) { $pending[] = DataModelValidationTask::violation( $task->path, 'Object keys must be non-empty UTF-8 strings.', 'invalid_lex_key', ); continue; }
$segment = $isList ? '[' . $key . ']' : $key; $childPath = $paths->child($task->path, $segment); $childReferences = $references; $reference = \ReflectionReference::fromArrayElement($current, $key); if ($reference !== NULL) { $referenceId = $reference->getId(); if (isset($childReferences[$referenceId])) { $pending[] = DataModelValidationTask::violation( $childPath, 'Cyclic arrays are not valid ATProto data model values.', 'invalid_lex_cycle', ); continue; } $childReferences[$referenceId] = TRUE; } $pending[] = DataModelValidationTask::value($current[$key], $childPath, $childReferences); } } }
/** * Returns whether the value is a canonical CID link object. * * @param array<mixed> $value */ public function isLinkObject(array $value): bool { return ( \array_keys($value) === ['$link'] && \is_string($value['$link']) && $this->cidParser->isValid($value['$link']) ); }
/** * Returns whether the value is a structurally valid CID link object. * * @param array<mixed> $value */ public function isLinkObjectLoose(array $value): bool { return ( \array_keys($value) === ['$link'] && \is_string($value['$link']) && $this->cidParser->isValidGeneral($value['$link']) ); }
/** * Returns whether the value is a canonical bytes object. * * @param array<mixed> $value */ public static function isBytesObject(array $value): bool { if (\array_keys($value) !== ['$bytes'] || !\is_string($value['$bytes'])) { return FALSE; }
$encoded = $value['$bytes']; if (\preg_match('/^[A-Za-z0-9+\/]*={0,2}$/D', $encoded) !== 1) { return FALSE; }
$unpadded = \rtrim($encoded, '='); $paddingLength = \strlen($encoded) - \strlen($unpadded); $remainder = \strlen($unpadded) % 4; if ($remainder === 1 || $paddingLength > 0 && (\strlen($encoded) % 4) !== 0) { return FALSE; }
$expectedPadding = (4 - $remainder) % 4; if ($paddingLength > 0 && $paddingLength !== $expectedPadding) { return FALSE; }
$decoded = \base64_decode($unpadded . \str_repeat('=', $expectedPadding), TRUE); return $decoded !== FALSE && $unpadded === \rtrim(\base64_encode($decoded), '='); }
/** * Returns whether the value is a canonical blob object. * * @param array<mixed> $value */ public function isBlobObject(array $value): bool { $cid = $this->blobCid($value); return $cid !== NULL && $this->cidParser->isValidBlobCid($cid); }
/** * Returns whether the value is a structurally valid blob object. * * @param array<mixed> $value */ public function isBlobObjectLoose(array $value): bool { $cid = $this->blobCid($value); return $cid !== NULL && $this->cidParser->isValidGeneral($cid); }
/** * Returns whether the value is a current or legacy blob object. * * @param array<mixed> $value */ public function isBlobObjectOrLegacy(array $value): bool { if (($value['$type'] ?? NULL) === 'blob') { return $this->isBlobObjectLoose($value); } return ( \count($value) === 2 && \is_string($value['cid'] ?? NULL) && $this->cidParser->isValidGeneral($value['cid']) && \is_string($value['mimeType'] ?? NULL) && $value['mimeType'] !== '' && $this->isValidUtf8($value['mimeType']) ); }
private static function isValidUtf8(string $value): bool { return \preg_match('//u', $value) === 1; }
/** * @param array<mixed> $value */ private function blobCid(array $value): ?string { $ref = $value['ref'] ?? NULL; $size = self::integerValue($value['size'] ?? NULL); if ( \count($value) !== 4 || ($value['$type'] ?? NULL) !== 'blob' || !\is_array($ref) || \array_keys($ref) !== ['$link'] || !\is_string($ref['$link']) || !\is_string($value['mimeType'] ?? NULL) || $value['mimeType'] === '' || !$this->isValidUtf8($value['mimeType']) || $size === NULL || $size < 0 ) { return NULL; } return $ref['$link']; }
private function isValidTypeDiscriminator(mixed $value): bool { if (!\is_string($value) || $value === '' || \substr_count($value, '#') > 1) { return FALSE; } $parts = \explode('#', $value, 2); $nsid = $parts[0]; $fragment = $parts[1] ?? NULL; return ( $this->nsidParser->isValid($nsid) && ($fragment === NULL || \preg_match('/^[A-Za-z][A-Za-z0-9]*$/D', $fragment) === 1) ); }
/** * Returns the exact integer represented by the value when possible. */ public static function integerValue(mixed $value): ?int { if (\is_int($value)) { return $value; } if ( !\is_float($value) || !\is_finite($value) || \floor($value) !== $value || $value < -9_223_372_036_854_775_808.0 || $value >= 9_223_372_036_854_775_808.0 ) { return NULL; } return (int) $value; }
}