s = $s; $this->len = strlen( $s ); } /** * Section 9.2. `args_hash` is over the bytes as transmitted, so it is defined * for any byte string at all and is computed before anything is parsed. */ public static function argumentsHash( string $bytes ): string { return 'sha256:' . hash( 'sha256', $bytes ); } /** * @return Result Result */ public static function check( string $bytes ): Result { if ( strlen( $bytes ) > self::MAX_TOTAL_BYTES ) { return Result::err( 'arg_bytes_exceeded', strlen( $bytes ) . ' bytes exceeds the argument limit' ); } // D4 — well-formed UTF-8. A replacement character would let bad bytes // through in a different shape, so this rejects instead of repairing. if ( ! Utf::isWellFormed( $bytes ) ) { return Result::err( 'arg_invalid_utf8', 'argument bytes are not well-formed UTF-8' ); } // D7 — a leading byte-order mark is not stripped. Both runtimes used to // drop it, which is a rewrite: two byte strings parsed to one value while // hashing differently, and only one of them is what the canonicaliser // emits. It now falls through to the reader and is refused the ordinary // way, as an unexpected character before the object. $reader = new self( $bytes ); $value = $reader->readValue( 0 ); if ( ! $value->isOk() ) { return $value; } $reader->skipWhitespace(); if ( $reader->pos < $reader->len ) { return Result::err( 'arg_invalid_json', 'trailing content at offset ' . $reader->pos ); } // D1 — the top-level value is a JSON object. if ( ! $value->value() instanceof JsonObject ) { return Result::err( 'arg_not_object', 'the top-level argument value must be a JSON object' ); } // D5 — the total-bytes limit binds the canonical form, not only the input. // The per-string limit bounds each string, but NFC expansion accumulates // across an object, so an admissible input can still canonicalise past the // total and the recheck would refuse bytes the gateway legitimately sent. $canonical = strlen( Canonical::encode( $value->value() ) ); if ( $canonical > self::MAX_TOTAL_BYTES ) { return Result::err( 'arg_bytes_exceeded', 'the canonical form is ' . $canonical . ' bytes, which exceeds the argument limit' ); } return $value; } private function skipWhitespace(): void { while ( $this->pos < $this->len ) { $c = $this->s[ $this->pos ]; if ( ' ' === $c || "\t" === $c || "\n" === $c || "\r" === $c ) { ++$this->pos; continue; } break; } } private function readValue( int $depth ): Result { // D5 — nesting depth. if ( $depth > self::MAX_DEPTH ) { return Result::err( 'arg_depth_exceeded', 'nesting deeper than ' . self::MAX_DEPTH ); } $this->skipWhitespace(); if ( $this->pos >= $this->len ) { return Result::err( 'arg_invalid_json', 'unexpected end of input' ); } $c = $this->s[ $this->pos ]; if ( '{' === $c ) { return $this->readObject( $depth ); } if ( '[' === $c ) { return $this->readArray( $depth ); } if ( '"' === $c ) { return $this->readString(); } if ( '-' === $c || ( $c >= '0' && $c <= '9' ) ) { return $this->readNumber(); } if ( $this->startsWith( 'true' ) ) { $this->pos += 4; return Result::ok( true ); } if ( $this->startsWith( 'false' ) ) { $this->pos += 5; return Result::ok( false ); } if ( $this->startsWith( 'null' ) ) { $this->pos += 4; // D6 — null is preserved and is distinct from an absent key. return Result::ok( null ); } return Result::err( 'arg_invalid_json', 'unexpected "' . $c . '" at offset ' . $this->pos ); } private function startsWith( string $literal ): bool { return substr( $this->s, $this->pos, strlen( $literal ) ) === $literal; } private function readObject( int $depth ): Result { ++$this->pos; $out = new JsonObject(); $seen = array(); $this->skipWhitespace(); if ( $this->pos < $this->len && '}' === $this->s[ $this->pos ] ) { ++$this->pos; return Result::ok( $out ); } for ( ; ; ) { $this->skipWhitespace(); if ( $this->pos >= $this->len || '"' !== $this->s[ $this->pos ] ) { return Result::err( 'arg_invalid_json', 'expected a key at ' . $this->pos ); } $key = $this->readString(); if ( ! $key->isOk() ) { return $key; } // D3 — duplicate keys are rejected. The comparison is on the decoded // key, so "a" and "a" collide, and on its NFC form, because // canonicalisation normalises keys: two keys differing only in // composition are one key in the output, and accepting both would emit // an object this same reader refuses. $name = $key->value(); $seen_as = Utf::nfc( $name ); if ( isset( $seen[ $seen_as ] ) ) { return Result::err( 'arg_duplicate_key', 'duplicate key "' . $name . '"' ); } $seen[ $seen_as ] = true; // D5 — keys per object. if ( count( $seen ) > self::MAX_KEYS ) { return Result::err( 'arg_keys_exceeded', 'more than ' . self::MAX_KEYS . ' keys in one object' ); } $this->skipWhitespace(); if ( $this->pos >= $this->len || ':' !== $this->s[ $this->pos ] ) { return Result::err( 'arg_invalid_json', 'expected ":" at ' . $this->pos ); } ++$this->pos; $value = $this->readValue( $depth + 1 ); if ( ! $value->isOk() ) { return $value; } $out->set( $name, $value->value() ); $this->skipWhitespace(); $c = $this->pos < $this->len ? $this->s[ $this->pos ] : ''; if ( ',' === $c ) { ++$this->pos; continue; } if ( '}' === $c ) { ++$this->pos; return Result::ok( $out ); } return Result::err( 'arg_invalid_json', 'expected "," or "}" at ' . $this->pos ); } } private function readArray( int $depth ): Result { ++$this->pos; $out = array(); $this->skipWhitespace(); if ( $this->pos < $this->len && ']' === $this->s[ $this->pos ] ) { ++$this->pos; return Result::ok( $out ); } for ( ; ; ) { $value = $this->readValue( $depth + 1 ); if ( ! $value->isOk() ) { return $value; } $out[] = $value->value(); $this->skipWhitespace(); $c = $this->pos < $this->len ? $this->s[ $this->pos ] : ''; if ( ',' === $c ) { ++$this->pos; continue; } if ( ']' === $c ) { ++$this->pos; return Result::ok( $out ); } return Result::err( 'arg_invalid_json', 'expected "," or "]" at ' . $this->pos ); } } /** * Strings are accumulated in UTF-16 terms and only then encoded, because that * is the unit `\uXXXX` addresses and the unit a lone surrogate is counted in. * Doing it any other way makes the surrogate rule mean something subtly * different in PHP than it does in TypeScript. */ private function readString(): Result { ++$this->pos; $out = ''; $pendingHi = -1; $closed = false; while ( $this->pos < $this->len ) { $c = $this->s[ $this->pos ]; if ( '"' === $c ) { ++$this->pos; $closed = true; break; } if ( '\\' === $c ) { $esc = $this->readEscape(); if ( ! $esc->isOk() ) { return $esc; } $unit = $esc->value(); if ( $pendingHi >= 0 ) { if ( $unit >= 0xDC00 && $unit <= 0xDFFF ) { $cp = 0x10000 + ( ( $pendingHi - 0xD800 ) << 10 ) + ( $unit - 0xDC00 ); $out .= Utf::encodeCodePoint( $cp ); $pendingHi = -1; continue; } return Result::err( 'arg_lone_surrogate', 'unpaired high surrogate' ); } if ( $unit >= 0xD800 && $unit <= 0xDBFF ) { $pendingHi = $unit; continue; } if ( $unit >= 0xDC00 && $unit <= 0xDFFF ) { return Result::err( 'arg_lone_surrogate', 'unpaired low surrogate' ); } $out .= Utf::encodeCodePoint( $unit ); continue; } if ( $pendingHi >= 0 ) { // A raw character is never a low surrogate: the source is // well-formed UTF-8, in which surrogates are not encodable. return Result::err( 'arg_lone_surrogate', 'unpaired high surrogate' ); } $byte = ord( $c ); if ( $byte < 0x20 ) { return Result::err( 'arg_invalid_json', 'raw control character in a string' ); } if ( $byte < 0x80 ) { $out .= $c; ++$this->pos; continue; } $width = $byte >= 0xF0 ? 4 : ( $byte >= 0xE0 ? 3 : 2 ); $out .= substr( $this->s, $this->pos, $width ); $this->pos += $width; } if ( ! $closed ) { return Result::err( 'arg_invalid_json', 'unterminated string' ); } if ( $pendingHi >= 0 ) { return Result::err( 'arg_lone_surrogate', 'unpaired high surrogate' ); } // D5 — string length, in bytes, after the escapes are resolved, measured on // both the string as written and its NFC form and bounded by the larger. // // NFC can expand: U+0344 is two bytes and normalises to U+0308 U+0301, // which is four. Measuring only the input form admits a string whose // canonical serialisation exceeds the limit, and the recheck then refuses // bytes the gateway legitimately produced — the same defect as sorting // before normalising, reached by a different route. $len = max( strlen( $out ), strlen( Utf::nfc( $out ) ) ); if ( $len > self::MAX_STRING_BYTES ) { return Result::err( 'arg_string_too_long', 'string of ' . $len . ' bytes exceeds the limit' ); } return Result::ok( $out ); } /** @return Result Result — one UTF-16 code unit. */ private function readEscape(): Result { ++$this->pos; if ( $this->pos >= $this->len ) { return Result::err( 'arg_invalid_json', 'unterminated escape' ); } $c = $this->s[ $this->pos ]; ++$this->pos; switch ( $c ) { case '"': return Result::ok( 0x22 ); case '\\': return Result::ok( 0x5C ); case '/': return Result::ok( 0x2F ); case 'b': return Result::ok( 0x08 ); case 'f': return Result::ok( 0x0C ); case 'n': return Result::ok( 0x0A ); case 'r': return Result::ok( 0x0D ); case 't': return Result::ok( 0x09 ); case 'u': $hex = substr( $this->s, $this->pos, 4 ); if ( strlen( $hex ) < 4 ) { return Result::err( 'arg_invalid_json', 'truncated \\u escape' ); } if ( 1 !== preg_match( '/\A[0-9a-fA-F]{4}\z/', $hex ) ) { return Result::err( 'arg_invalid_json', 'malformed \\u escape' ); } $this->pos += 4; return Result::ok( (int) hexdec( $hex ) ); default: return Result::err( 'arg_invalid_json', 'unknown escape "\\' . $c . '"' ); } } /** * D2 — integers in [-(2^53 - 1), 2^53 - 1]. Any non-integer number is * rejected, including an integral-valued float such as `1.0`: it is the * literal shape that removes the float-formatting divergence class, not the * value. Decimal quantities travel as strings. */ private function readNumber(): Result { $start = $this->pos; if ( '-' === $this->s[ $this->pos ] ) { ++$this->pos; } while ( $this->pos < $this->len ) { $c = $this->s[ $this->pos ]; if ( $c >= '0' && $c <= '9' ) { ++$this->pos; continue; } break; } $int_part = substr( $this->s, $start, $this->pos - $start ); if ( '' === $int_part || '-' === $int_part ) { return Result::err( 'arg_invalid_json', 'malformed number at offset ' . $start ); } $next = $this->pos < $this->len ? $this->s[ $this->pos ] : ''; if ( '.' === $next || 'e' === $next || 'E' === $next ) { return Result::err( 'arg_non_integer_number', '"' . $int_part . '" is not an integer' ); } $digits = '-' === $int_part[0] ? substr( $int_part, 1 ) : $int_part; if ( strlen( $digits ) > 1 && '0' === $digits[0] ) { return Result::err( 'arg_invalid_json', '"' . $int_part . '" has a leading zero' ); } // Compared as decimal text: the literal may not fit a PHP int on a 32-bit // host, and must not be allowed to silently become a float on any host. if ( self::outsideSafeRange( $int_part, $digits ) ) { return Result::err( 'arg_number_out_of_range', '"' . $int_part . '" is outside the safe-integer range' ); } return Result::ok( (int) $int_part ); } private static function outsideSafeRange( string $literal, string $digits ): bool { $bound = '-' === $literal[0] ? (string) -self::MIN_SAFE_INTEGER : (string) self::MAX_SAFE_INTEGER; $digits = ltrim( $digits, '0' ); if ( '' === $digits ) { return false; } if ( strlen( $digits ) !== strlen( $bound ) ) { return strlen( $digits ) > strlen( $bound ); } return strcmp( $digits, $bound ) > 0; } }