diff --git a/CHANGELOG.md b/CHANGELOG.md index f49d90e..669d2ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,14 @@ default; `JSONTextSequenceOptions.MalformedTexts.skip` skips them and counts them on the iterator, but never skips resource failures. `JSONTextSequenceWriter` writes RS, strict JSON and LF per value, as one sequence or in awaited chunks. +- Add `JSONEnvelope`, a versioned record of one payload in RFC 8785 canonical + bytes. Format version 1 is a canonical object with `digest`, `format` + (`swift-json-envelope`), `formatVersion` (1), `payload`, `type` and `version`. + The digest is the SHA-256 of the payload's canonical bytes; decoding checks the + marker, fields and digest and reports `JSONEnvelopeFailure` for invalid or + damaged envelopes. Equal envelopes encode to equal bytes, and equal payloads + have equal digests for content addressing. Tests pin bytes and digests computed + independently. ## Unreleased — 1.9.1 hygiene diff --git a/Documentation/Qualification/TestDiscovery.json b/Documentation/Qualification/TestDiscovery.json index 36b3a4a..cef7159 100644 --- a/Documentation/Qualification/TestDiscovery.json +++ b/Documentation/Qualification/TestDiscovery.json @@ -1,7 +1,7 @@ { "schema_version": 2, "root_functions": { - "JSONTests": 198, + "JSONTests": 203, "JSONSchemaTests": 79, "JSONRegexRuntimeTests": 16, "JSONStreamingTests": 42, @@ -73,7 +73,7 @@ "JSONSchemaDSL" ], "portable_root_functions": { - "JSONTests": 198, + "JSONTests": 203, "JSONSchemaTests": 79, "JSONRegexRuntimeTests": 16, "JSONStreamingTests": 42, @@ -89,7 +89,7 @@ "JSONDSLTests": 47 }, "wasi_root_functions": { - "JSONTests": 198, + "JSONTests": 203, "JSONSchemaTests": 79, "JSONRegexRuntimeTests": 16, "JSONStreamingTests": 42, diff --git a/Sources/JSON/Codec/JSONEnvelope.swift b/Sources/JSON/Codec/JSONEnvelope.swift new file mode 100644 index 0000000..1c7b59b --- /dev/null +++ b/Sources/JSON/Codec/JSONEnvelope.swift @@ -0,0 +1,211 @@ +// SPDX-License-Identifier: Apache-2.0 +// Original versioned, digest-checked envelope over RFC 8785 canonical JSON. +import Foundation + +/// A versioned, self-checking record of one JSON payload, written as RFC 8785 canonical JSON. +/// +/// An envelope names what its payload is (``type``) and which schema version of +/// that type it follows (``version``), so a store can migrate old records. Its +/// wire form is one canonical object with six members: +/// +/// ```json +/// {"digest":"sha256:…","format":"swift-json-envelope","formatVersion":1,"payload":{…},"type":"mcp.task","version":3} +/// ``` +/// +/// `digest` is the SHA-256 of the payload's canonical bytes. Decoding recomputes +/// it, so a damaged payload is detected, and equal payloads always have equal +/// digests, so the digest can serve as a content address. Because the whole +/// envelope is canonical, equal envelopes encode to equal bytes. +/// +/// Format version 1 is fixed: the member names, the marker and the digest +/// algorithm do not change. A later format would use a new `formatVersion`. +public struct JSONEnvelope: Sendable, Equatable { + /// The format marker, `swift-json-envelope`. + public static let format = "swift-json-envelope" + /// The format version this type reads and writes, `1`. + public static let formatVersion = 1 + /// The largest accepted ``type`` length in UTF-8 bytes. + public static let maximumTypeBytes = 256 + /// The accepted ``version`` range: the positive integers that binary64 represents exactly. + public static let versions: ClosedRange = 1...9_007_199_254_740_991 + + /// The caller's name for the kind of payload, such as `mcp.task`. + public let type: String + /// The schema version of ``type`` that the payload follows. + public let version: Int + /// The enveloped value. + public let payload: JSON + + /// Creates an envelope after checking its type and version. + /// + /// - Throws: ``JSONEnvelopeFailure/invalidType`` for an empty type or one longer + /// than ``maximumTypeBytes``; ``JSONEnvelopeFailure/invalidVersion`` for a version + /// outside ``versions``. + /// + /// - Parameters: + /// - type: A non-empty name for the kind of payload, at most 256 UTF-8 bytes. + /// - version: The payload's schema version, from 1 through 2^53 − 1. + /// - payload: The value to envelope. + public init(type: String, version: Int, payload: JSON) throws { + guard !type.isEmpty, type.utf8.count <= Self.maximumTypeBytes else { throw JSONEnvelopeFailure.invalidType } + guard Self.versions.contains(version) else { throw JSONEnvelopeFailure.invalidVersion } + self.type = type; self.version = version; self.payload = payload + } + + /// Writes the envelope's canonical bytes and returns them with the payload digest. + /// + /// - Returns: The canonical envelope bytes and the `sha256:` digest of the payload. + /// - Throws: Inexact conversion for a number the policy refuses, resource failure or cancellation. + /// + /// - Parameters: + /// - options: Limits and the canonical number policy. + public func encode(options: JSONEnvelopeOptions = .init()) throws -> JSONEnvelopeEncoding { + try encodeWithReport(options: options).result + } + /// Writes the envelope with one cumulative work ledger. + /// + /// - Returns: The encoding and the ledger's charged counts. + /// - Throws: Inexact conversion for a number the policy refuses, resource failure or cancellation. + /// + /// - Parameters: + /// - options: Limits and the canonical number policy. + public func encodeWithReport(options: JSONEnvelopeOptions = .init()) throws -> JSONOperationReport { + var meter = try JSONWorkMeter(limits: options.limits, domain: .writing) + let writer = JSONCanonicalWriter(limits: options.limits, numberPolicy: options.numberPolicy) + let payloadBytes = try writer.write(payload, meter: &meter) + let digest = try Self.digest(of: payloadBytes, meter: &meter) + try meter.resetValueBounds(); let typeBytes = try writer.write(.string(type), meter: &meter) + try meter.resetValueBounds(); let versionBytes = try writer.write(.number(JSONNumber(integer: version)), meter: &meter) + // Members in RFC 8785 order; every name is ASCII, so UTF-16 order is byte order. + var bytes: [UInt8] = [] + func append(_ part: C, meter: inout JSONWorkMeter) throws where C.Element == UInt8 { + for byte in part { try meter.work(); try meter.retain(1); bytes.append(byte) } + } + func literal(_ text: String, meter: inout JSONWorkMeter) throws { + try meter.charge(.outputBytes, UInt64(text.utf8.count)); try append(text.utf8, meter: &meter) + } + try literal("{\"digest\":\"\(digest)\",\"format\":\"\(Self.format)\",\"formatVersion\":\(Self.formatVersion),\"payload\":", meter: &meter) + try append(payloadBytes, meter: &meter) + try literal(",\"type\":", meter: &meter); try append(typeBytes, meter: &meter) + try literal(",\"version\":", meter: &meter); try append(versionBytes, meter: &meter) + try literal("}", meter: &meter) + try meter.checkpoint() + return .init(result: .init(data: Data(bytes), digest: digest), statistics: meter.statistics()) + } + + /// Reads an envelope and verifies its format, fields and payload digest. + /// + /// The input may be any strict JSON spelling of the envelope object; canonical + /// bytes are not required. Use the same number policy that encoded it. + /// + /// - Returns: The checked envelope. + /// - Throws: ``JSONEnvelopeFailure`` for a well-formed JSON value that is not a + /// valid version 1 envelope or whose digest does not match; `JSONFailure` for + /// syntax, a refused number, resource failure; or cancellation. + /// + /// - Parameters: + /// - data: The envelope bytes. + /// - options: Limits and the canonical number policy used for the digest. + public static func decode(_ data: Data, options: JSONEnvelopeOptions = .init()) throws -> JSONEnvelope { + try decodeWithReport(data, options: options).result + } + /// Reads and verifies an envelope with one cumulative work ledger. + /// + /// See ``decode(_:options:)``. + /// + /// - Returns: The checked envelope and the ledger's charged counts. + /// - Throws: ``JSONEnvelopeFailure``, `JSONFailure` or cancellation, as for ``decode(_:options:)``. + /// + /// - Parameters: + /// - data: The envelope bytes. + /// - options: Limits and the canonical number policy used for the digest. + public static func decodeWithReport(_ data: Data, options: JSONEnvelopeOptions = .init()) throws -> JSONOperationReport { + var meter = try JSONWorkMeter(limits: options.limits, domain: .core) + try meter.require(.inputBytes, UInt64(data.count)) + var input: [UInt8] = [] + for byte in data { try meter.work(); try meter.retain(1); input.append(byte) } + let root = try JSONParser().parse(input, meter: &meter) + try meter.release(UInt64(input.count)); input = [] + + guard case .object(let object) = root, object.count == 6 else { throw JSONEnvelopeFailure.invalidFormat } + func member(_ name: String, meter: inout JSONWorkMeter) throws -> JSON { + guard let value = try object.lookup(name, meter: &meter) else { throw JSONEnvelopeFailure.invalidFormat } + return value + } + guard case .string(format) = try member("format", meter: &meter) else { throw JSONEnvelopeFailure.invalidFormat } + guard case .number(let formatVersion) = try member("formatVersion", meter: &meter) else { throw JSONEnvelopeFailure.invalidFormat } + guard try integer(formatVersion, meter: &meter) == Self.formatVersion else { + throw JSONEnvelopeFailure.unsupportedFormatVersion + } + guard case .string(let type) = try member("type", meter: &meter) else { throw JSONEnvelopeFailure.invalidType } + guard case .number(let versionNumber) = try member("version", meter: &meter), + let version = try integer(versionNumber, meter: &meter) else { throw JSONEnvelopeFailure.invalidVersion } + guard case .string(let digest) = try member("digest", meter: &meter), isDigest(digest) else { throw JSONEnvelopeFailure.invalidDigest } + let payload = try member("payload", meter: &meter) + let envelope = try JSONEnvelope(type: type, version: version, payload: payload) + + try meter.resetValueBounds() + let writer = JSONCanonicalWriter(limits: options.limits, numberPolicy: options.numberPolicy) + let payloadBytes = try writer.write(payload, meter: &meter) + guard try Self.digest(of: payloadBytes, meter: &meter) == digest else { throw JSONEnvelopeFailure.digestMismatch } + try meter.checkpoint() + return .init(result: envelope, statistics: meter.statistics()) + } + + /// The integer value, or nil when the number is not an integer that fits `Int`. + private static func integer(_ number: JSONNumber, meter: inout JSONWorkMeter) throws -> Int? { + do { return try number.integer(as: Int.self, meter: &meter) } + catch let failure as JSONFailure where failure.category == .conversion { return nil } + } + private static func digest(of bytes: [UInt8], meter: inout JSONWorkMeter) throws -> String { + "sha256:" + (try JSONSHA256Core.hexadecimal(bytes, accounting: &meter)) + } + private static func isDigest(_ text: String) -> Bool { + let bytes = Array(text.utf8) + guard bytes.count == 71, bytes.starts(with: Array("sha256:".utf8)) else { return false } + return bytes.dropFirst(7).allSatisfy { (0x30...0x39).contains($0) || (0x61...0x66).contains($0) } + } +} + +/// Limits and the number policy for encoding and decoding a ``JSONEnvelope``. +public struct JSONEnvelopeOptions: Sendable { + /// Finite capacities and work quotas applied to each call. + public var limits: JSONLimits + /// The canonical number policy for the payload; decoding must use the policy that encoded it. + public var numberPolicy: JSONCanonicalWriter.NumberPolicy + /// Creates the configuration; finite limits are checked when an operation begins. + /// + /// - Parameters: + /// - limits: Finite inclusive capacities and work quotas for each call. + /// - numberPolicy: Refuse (the default) or round numbers that binary64 cannot represent exactly. + public init(limits: JSONLimits = .balanced, numberPolicy: JSONCanonicalWriter.NumberPolicy = .preserving) { + self.limits = limits; self.numberPolicy = numberPolicy + } +} + +/// The canonical bytes of a ``JSONEnvelope`` and the digest of its payload. +public struct JSONEnvelopeEncoding: Sendable, Equatable { + /// The canonical envelope bytes. + public let data: Data + /// The payload digest, `sha256:` followed by 64 lowercase hexadecimal digits. + public let digest: String +} + +/// Why a well-formed JSON value is not a valid version 1 ``JSONEnvelope``. +/// +/// Syntax, resource and number-conversion failures are reported as `JSONFailure`. +/// No case carries input text. +public enum JSONEnvelopeFailure: Error, Sendable, Equatable { + /// The root is not an object with exactly the six envelope members, or the format marker is wrong. + case invalidFormat + /// The format version is not 1. + case unsupportedFormatVersion + /// The type is not a non-empty string of at most 256 UTF-8 bytes. + case invalidType + /// The version is not an integer from 1 through 2^53 − 1. + case invalidVersion + /// The digest is not `sha256:` followed by 64 lowercase hexadecimal digits. + case invalidDigest + /// The payload's canonical digest differs from the recorded digest. + case digestMismatch +} diff --git a/Sources/JSON/Documentation.docc/JSON.md b/Sources/JSON/Documentation.docc/JSON.md index f11b993..ff6fa8c 100644 --- a/Sources/JSON/Documentation.docc/JSON.md +++ b/Sources/JSON/Documentation.docc/JSON.md @@ -15,7 +15,9 @@ preserved/normalized decimal spelling. Scalar sorting is deterministic JSON output, not a cryptographic canonicalization standard. For that, use ``JSONCanonicalWriter``, which writes RFC 8785 (JCS) canonical bytes: UTF-16 key order, short string escapes and ECMAScript binary64 numbers. By default it refuses -a number whose binary64 spelling would change its exact value. +a number whose binary64 spelling would change its exact value. ``JSONEnvelope`` +builds on it: a typed, versioned payload in canonical bytes with a SHA-256 +digest that decoding verifies. See . ``JSONValueEncoder`` and ``JSONValueDecoder`` implement native value-based Codable. Direct JSON/JSONObject round-trips preserve raw scalar keys and numbers. @@ -60,6 +62,7 @@ belongs exclusively to each invocation. - - - +- - ### Exact model @@ -75,6 +78,10 @@ belongs exclusively to each invocation. - ``JSONWriter`` - ``JSONWritingOptions`` - ``JSONCanonicalWriter`` +- ``JSONEnvelope`` +- ``JSONEnvelopeOptions`` +- ``JSONEnvelopeEncoding`` +- ``JSONEnvelopeFailure`` - ``JSONIndentationUnit`` - ``JSONValueEncoder`` - ``JSONValueDecoder`` diff --git a/Sources/JSON/Documentation.docc/VersionedEnvelopes.md b/Sources/JSON/Documentation.docc/VersionedEnvelopes.md new file mode 100644 index 0000000..194f4a3 --- /dev/null +++ b/Sources/JSON/Documentation.docc/VersionedEnvelopes.md @@ -0,0 +1,61 @@ +# Versioned envelopes + +Store a typed, versioned payload as canonical bytes with a content digest. + +## Overview + +A ``JSONEnvelope`` wraps one payload with the caller's name for its kind +(``JSONEnvelope/type``) and the schema version of that kind +(``JSONEnvelope/version``). It is meant for records that a store keeps for a +long time, where later code must recognize what a record is, migrate older +versions and notice damage. + +```swift +let envelope = try JSONEnvelope(type: "mcp.task", version: 3, payload: task) +let encoding = try envelope.encode() +store.save(encoding.data, key: encoding.digest) + +let restored = try JSONEnvelope.decode(store.load(key)) +``` + +### Wire format + +Format version 1 is one RFC 8785 canonical object with exactly six members: + +```json +{"digest":"sha256:87245ae1c062ec8fd5e2ab1ac60fbc44f6822d6176fe850381db1fd6e97c7810","format":"swift-json-envelope","formatVersion":1,"payload":{"id":7,"state":"done"},"type":"mcp.task","version":3} +``` + +- `format` is always `swift-json-envelope`; `formatVersion` is always `1`. +- `type` is a non-empty string of at most 256 UTF-8 bytes; `version` is an + integer from 1 through 2^53 − 1. +- `digest` is `sha256:` followed by the lowercase hexadecimal SHA-256 of the + payload's canonical bytes. + +Because the whole envelope is canonical, equal envelopes encode to equal bytes. +Equal payloads, compared with the exact model's equality, have equal digests, so +the digest works as a content address independent of the type and version. + +### Decoding + +``JSONEnvelope/decode(_:options:)`` accepts any strict JSON spelling of the +object, recomputes the payload digest and compares it with the recorded one. A +well-formed value that is not a valid envelope throws a ``JSONEnvelopeFailure``: +a wrong marker or member set, an unsupported format version, an invalid type, +version or digest field, or a digest mismatch. Syntax, resource and number +failures stay `JSONFailure`. + +### Numbers + +The payload is canonicalized with ``JSONCanonicalWriter``. By default +(``JSONCanonicalWriter/NumberPolicy/preserving``) a number that binary64 cannot +spell exactly, such as `0.10000000000000001`, is refused rather than changed. +With ``JSONCanonicalWriter/NumberPolicy/rounding`` such numbers are rounded +before hashing, and decoding must use the same policy. + +## Topics + +- ``JSONEnvelope`` +- ``JSONEnvelopeOptions`` +- ``JSONEnvelopeEncoding`` +- ``JSONEnvelopeFailure`` diff --git a/Sources/JSONCLIEngine/CLIBuildIdentity.swift b/Sources/JSONCLIEngine/CLIBuildIdentity.swift index 86a1953..ea9f983 100644 --- a/Sources/JSONCLIEngine/CLIBuildIdentity.swift +++ b/Sources/JSONCLIEngine/CLIBuildIdentity.swift @@ -2,6 +2,6 @@ // Generated by Scripts/generate_cli_identity.py; excludes this file. // SHA-256 of the ordered Package.swift + Sources content manifest (DocC catalogs excluded), not a Git commit. package enum CLIBuildIdentity { - package static let revision = "sha256:c0c4442af4a6e52b5e232fc41405acbf92616b366832ae0df0bfb843e18a3773" + package static let revision = "sha256:fd026d72a5ef7b9f545d4ab4b08edd1460af5d0630551034a16f066824e1fa39" package static let kind = "source-sha256" } diff --git a/Tests/JSONTests/EnvelopeTests.swift b/Tests/JSONTests/EnvelopeTests.swift new file mode 100644 index 0000000..815b87f --- /dev/null +++ b/Tests/JSONTests/EnvelopeTests.swift @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: Apache-2.0 +import Foundation +import Testing +import JSON + +private func parse(_ text: String) throws -> JSON { try JSONParser().parse(text) } +private func decode(_ text: String, options: JSONEnvelopeOptions = .init()) throws -> JSONEnvelope { + try JSONEnvelope.decode(Data(text.utf8), options: options) +} +/// Digests computed independently with Python's hashlib over the RFC 8785 payload bytes. +private let taskDigest = "sha256:87245ae1c062ec8fd5e2ab1ac60fbc44f6822d6176fe850381db1fd6e97c7810" +private let taskEnvelope = #"{"digest":"sha256:87245ae1c062ec8fd5e2ab1ac60fbc44f6822d6176fe850381db1fd6e97c7810","format":"swift-json-envelope","formatVersion":1,"payload":{"id":7,"state":"done"},"type":"mcp.task","version":3}"# + +@Test func envelopeEncodesPinnedCanonicalBytesAndDigest() throws { + let envelope = try JSONEnvelope(type: "mcp.task", version: 3, payload: parse(#"{"state":"done","id":7.0}"#)) + let encoding = try envelope.encode() + #expect(String(decoding: encoding.data, as: UTF8.self) == taskEnvelope) + #expect(encoding.digest == taskDigest) + // The assembled bytes equal the canonical writer's output for the same object. + #expect(encoding.data == (try JSONCanonicalWriter().write(parse(taskEnvelope)))) + #expect(try JSONEnvelope(type: "t", version: 1, payload: .null).encode().digest == + "sha256:74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b") + let unicode = try JSONEnvelope(type: "café/ü", version: 9_007_199_254_740_991, payload: parse(#"{"€":"é","a":[1,0.1,1e21]}"#)) + let unicodeEncoding = try unicode.encode() + #expect(unicodeEncoding.digest == "sha256:c03fa255bcdb45e82dc0a02f2c19c989fc723c823c1103f597e047f411e2ab78") + #expect(String(decoding: unicodeEncoding.data, as: UTF8.self).hasSuffix(#""type":"café/ü","version":9007199254740991}"#)) +} + +@Test func equalEnvelopesHaveEqualBytesAndRoundTrip() throws { + let a = try JSONEnvelope(type: "doc", version: 2, payload: parse(#"{"b":[1.50,{"y":null,"x":true}],"a":"s"}"#)) + let b = try JSONEnvelope(type: "doc", version: 2, payload: parse(#"{"a":"s","b":[1.5,{"x":true,"y":null}]}"#)) + #expect(a == b) + #expect(try a.encode() == b.encode()) + #expect(try JSONEnvelope.decode(a.encode().data) == a) + // Any strict spelling decodes: reordered members and whitespace are allowed. + let spaced = "{\n \"version\": 3, \"type\": \"mcp.task\",\n \"payload\": { \"state\": \"done\", \"id\": 7 },\n" + + " \"formatVersion\": 1, \"format\": \"swift-json-envelope\", \"digest\": \"\(taskDigest)\"\n}" + let decoded = try decode(spaced) + let expectedPayload = try parse(#"{"id":7,"state":"done"}"#) + #expect(decoded.type == "mcp.task" && decoded.version == 3 && decoded.payload == expectedPayload) + #expect(try decoded.encode().data == Data(taskEnvelope.utf8)) + let report = try JSONEnvelope.decodeWithReport(Data(taskEnvelope.utf8)) + #expect(report.result == decoded && report.statistics[.workUnits] > 0) + #expect(try a.encodeWithReport().statistics[.outputBytes] == UInt64(try a.encode().data.count)) +} + +@Test func envelopeDecodingDetectsCorruptionAndInvalidFields() throws { + func replacing(_ old: String, _ new: String) -> String { taskEnvelope.replacingOccurrences(of: old, with: new) } + let cases: [(String, JSONEnvelopeFailure)] = [ + (replacing(#""state":"done""#, #""state":"dona""#), .digestMismatch), + (replacing(#""id":7"#, #""id":8"#), .digestMismatch), + (replacing("swift-json-envelope", "swift-json-value"), .invalidFormat), + (replacing(#","version":3}"#, #","version":3,"extra":0}"#), .invalidFormat), + (replacing(#""type":"mcp.task","#, ""), .invalidFormat), + ("[1]", .invalidFormat), ("{}", .invalidFormat), + (replacing(#""formatVersion":1"#, #""formatVersion":2"#), .unsupportedFormatVersion), + (replacing(#""formatVersion":1"#, #""formatVersion":1.5"#), .unsupportedFormatVersion), + (replacing(#""formatVersion":1"#, #""formatVersion":"1""#), .invalidFormat), + (replacing(#""mcp.task""#, #""""#), .invalidType), + (replacing(#""mcp.task""#, "7"), .invalidType), + (replacing(#""version":3"#, #""version":0"#), .invalidVersion), + (replacing(#""version":3"#, #""version":3.5"#), .invalidVersion), + (replacing(#""version":3"#, #""version":9007199254740992"#), .invalidVersion), + (replacing(#""version":3"#, #""version":99999999999999999999"#), .invalidVersion), + (replacing(#""version":3"#, #""version":"3""#), .invalidVersion), + (replacing("87245ae1", "87245AE1"), .invalidDigest), + (replacing("sha256:", "sha512:"), .invalidDigest), + (replacing(#""sha256:87245ae1"#, #""sha256:7245ae1"#), .invalidDigest), + ] + for (text, expected) in cases { + #expect(throws: expected, "\(text)") { try decode(text) } + } + // Syntax and duplicate members stay JSON failures. + #expect { try decode(String(taskEnvelope.dropLast())) } throws: { ($0 as? JSONFailure)?.category == .syntax } + #expect { try decode(replacing(#","version":3}"#, #","version":3,"version":3}"#)) } throws: { ($0 as? JSONFailure)?.code == .duplicateKey } +} + +@Test func envelopeValidatesTypeVersionAndNumberPolicy() throws { + #expect(throws: JSONEnvelopeFailure.invalidType) { try JSONEnvelope(type: "", version: 1, payload: .null) } + #expect(throws: JSONEnvelopeFailure.invalidType) { try JSONEnvelope(type: String(repeating: "é", count: 129), version: 1, payload: .null) } + _ = try JSONEnvelope(type: String(repeating: "é", count: 128), version: 1, payload: .null) + for version in [0, -1, 9_007_199_254_740_992, .max] { + #expect(throws: JSONEnvelopeFailure.invalidVersion) { try JSONEnvelope(type: "t", version: version, payload: .null) } + } + // A number binary64 cannot spell exactly is refused unless rounding is chosen on both sides. + let inexact = try JSONEnvelope(type: "t", version: 1, payload: parse("[0.10000000000000001]")) + #expect { try inexact.encode() } throws: { ($0 as? JSONFailure)?.code == .inexactConversion } + let rounding = JSONEnvelopeOptions(numberPolicy: .rounding) + let rounded = try inexact.encode(options: rounding) + #expect(String(decoding: rounded.data, as: UTF8.self).contains(#""payload":[0.1]"#)) + #expect(try JSONEnvelope.decode(rounded.data, options: rounding).payload == (try parse("[0.1]"))) + let stored = String(decoding: rounded.data, as: UTF8.self).replacingOccurrences(of: "[0.1]", with: "[0.10000000000000001]") + #expect { try decode(stored) } throws: { ($0 as? JSONFailure)?.code == .inexactConversion } + #expect(try decode(stored, options: rounding).payload == (try parse("[0.10000000000000001]"))) +} + +@Test func envelopeOperationsAreBounded() throws { + var limits = JSONLimits.balanced; limits[.inputBytes] = 64 + #expect { try decode(taskEnvelope, options: .init(limits: limits)) } throws: { ($0 as? JSONFailure)?.resource?.metric == .inputBytes } + limits = .balanced; limits[.outputBytes] = 100 + let envelope = try JSONEnvelope(type: "mcp.task", version: 3, payload: parse(#"{"id":7,"state":"done"}"#)) + #expect { try envelope.encode(options: .init(limits: limits)) } throws: { ($0 as? JSONFailure)?.resource?.metric == .outputBytes } + limits[.outputBytes] = UInt64(taskEnvelope.utf8.count) + #expect(try envelope.encode(options: .init(limits: limits)).data.count == taskEnvelope.utf8.count) +}