Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 10 additions & 2 deletions Sources/BSVAuth/BRC103/AuthModels.swift
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,14 @@ public struct AuthMessage: Equatable, Sendable, CustomStringConvertible,
}
}

/// Bounds on what a peer accepts.
///
/// `maximumPayloadBytes` bounds a general message's payload, which over HTTP is the whole BRC-104
/// request or response: its body plus a few hundred bytes of framing. The default is 16 MiB, the
/// TypeScript SDK's `MAX_AUTH_MESSAGE_BYTES` and `AuthFetch`'s request frame limit
/// (`MAX_AUTH_HTTP_REQUEST_FRAME_BYTES`), so a reply a TypeScript client reads is one this one
/// reads too. At 1 MiB, a wallet storage reply carrying a photo inscription's transaction was
/// refused before it was read.
public struct AuthLimits: Equatable, Sendable {
public static let maximumAllowedJSONBytes = 64 << 20
public static let maximumAllowedPayloadBytes = 16 << 20
Expand Down Expand Up @@ -227,7 +235,7 @@ public struct AuthLimits: Equatable, Sendable {
public let certificateLimits: CertificateLimits
public let handshakeTimeout: Duration
public init(
maximumJSONBytes: Int = 8 << 20, maximumPayloadBytes: Int = 1 << 20,
maximumJSONBytes: Int = 8 << 20, maximumPayloadBytes: Int = 16 << 20,
maximumSessions: Int = 1024, maximumSessionsPerIdentity: Int = 8,
maximumPendingSessions: Int = 128, maximumMessages: Int = 4096,
maximumCertificateCount: Int = 64, maximumCertificateCertifierCount: Int = 64,
Expand Down Expand Up @@ -271,7 +279,7 @@ public struct AuthLimits: Equatable, Sendable {
}
private init(standard: Void) {
maximumJSONBytes = 8 << 20
maximumPayloadBytes = 1 << 20
maximumPayloadBytes = 16 << 20
maximumSessions = 1024
maximumSessionsPerIdentity = 8
maximumPendingSessions = 128
Expand Down
9 changes: 7 additions & 2 deletions Sources/BSVAuth/BRC104/BRC104Payload.swift
Original file line number Diff line number Diff line change
Expand Up @@ -86,14 +86,19 @@ public struct BRC104Header: Equatable, Sendable, CustomStringConvertible,
}
}

/// Bounds on a BRC-104 request or response payload.
///
/// `maximumPayloadBytes` defaults to 16 MiB, matching `AuthLimits` and the TypeScript SDK's
/// `AuthFetch` (`MAX_AUTH_HTTP_REQUEST_FRAME_BYTES`, and `DEFAULT_SIMPLIFIED_FETCH_MAX_RESPONSE_BYTES`
/// for a response body).
public struct BRC104Limits: Equatable, Sendable {
public let maximumPayloadBytes: Int
public let maximumHeaders: Int
public let maximumHeaderNameBytes: Int
public let maximumHeaderValueBytes: Int
public let maximumHeaderBytes: Int
public init(
maximumPayloadBytes: Int = 1 << 20, maximumHeaders: Int = 64,
maximumPayloadBytes: Int = 16 << 20, maximumHeaders: Int = 64,
maximumHeaderNameBytes: Int = 256,
maximumHeaderValueBytes: Int = 8 << 10, maximumHeaderBytes: Int = 64 << 10
) throws {
Expand All @@ -116,7 +121,7 @@ public struct BRC104Limits: Equatable, Sendable {
maximumHeaderBytes = headerBytes
}
public static let standard = BRC104Limits(
validatedPayload: 1 << 20, headers: 64, headerName: 256, headerValue: 8 << 10,
validatedPayload: 16 << 20, headers: 64, headerName: 256, headerValue: 8 << 10,
headerBytes: 64 << 10)
}

Expand Down
12 changes: 9 additions & 3 deletions Sources/BSVWallet/Values/WalletCryptoLimits.swift
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
/// Bounds on what the wallet's own cryptography reads.
///
/// `maximumPayloadByteCount` bounds the data signed, verified, HMACed or encrypted. The default is
/// 16 MiB: the TypeScript `ProtoWallet` sets no bound of its own, and BRC-103 signs each general
/// message's whole payload, which the TypeScript `AuthFetch` allows up to 16 MiB. At 1 MiB, an
/// authenticated request or response over 1 MiB could not be signed or verified.
public struct WalletCryptoLimits: Hashable, Sendable {
public static let standard = WalletCryptoLimits(
validatedPayload: 1_048_576,
ciphertext: 1_048_624,
validatedPayload: 16_777_216,
ciphertext: 16_777_264,
json: 8_388_608
)

Expand All @@ -10,7 +16,7 @@ public struct WalletCryptoLimits: Hashable, Sendable {
public let maximumJSONByteCount: Int

public init(
maximumPayloadByteCount: Int = 1_048_576,
maximumPayloadByteCount: Int = 16_777_216,
maximumJSONByteCount: Int = 8_388_608
) throws {
guard maximumPayloadByteCount >= 0 else {
Expand Down
80 changes: 77 additions & 3 deletions Tests/BSVAuthTests/BRC104/BRC104HTTPFramingTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,77 @@ struct BRC104HTTPFramingTests {
}
}

/// The TypeScript `AuthFetch` sends a request frame of up to 16 MiB
/// (`MAX_AUTH_HTTP_REQUEST_FRAME_BYTES`) and reads a response body of up to 16 MiB
/// (`DEFAULT_SIMPLIFIED_FETCH_MAX_RESPONSE_BYTES`). A wallet storage reply carrying a 180 KB
/// image inscription as JSON numbers was 1,330,479 bytes, and at the old 1 MiB default it was
/// refused with `resourceLimit` before it was read.
@Test("payloads over 1 MiB and under 16 MiB are signed, framed and read")
func payloadsOverOneMebibyte() async throws {
#expect(AuthLimits.standard.maximumPayloadBytes == 16 << 20)
#expect(try AuthLimits().maximumPayloadBytes == 16 << 20)
#expect(BRC104Limits.standard.maximumPayloadBytes == 16 << 20)
#expect(try BRC104Limits().maximumPayloadBytes == 16 << 20)
#expect(BRC104HTTPFramingLimits.standard.payloadLimits.maximumPayloadBytes == 16 << 20)

let requestBody = [UInt8](repeating: 0x5b, count: (1 << 20) + 1)
let responseBody = [UInt8](repeating: 0x31, count: 1_330_479)
let fixture = try await makeHTTPFixture(
requestBody: requestBody, responseBody: responseBody
)

let requestFrame = try BRC104HTTPFrameCodec.encodeRequest(fixture.requestMessage)
#expect(requestFrame.body == requestBody)
#expect(try BRC104HTTPFrameCodec.decodeRequest(requestFrame) == fixture.requestMessage)

let responseFrame = try BRC104HTTPFrameCodec.encodeResponse(fixture.responseMessage)
#expect(responseFrame.body == responseBody)
let decoded = try BRC104HTTPFrameCodec.decodeResponse(
try BRC104HTTPResponseFrame(
status: responseFrame.status, headers: responseFrame.headers,
body: responseFrame.body
),
expectedRequestID: fixture.requestID
)
#expect(decoded == fixture.responseMessage)
let inner = try BRC104Codec.decodeResponse(try #require(decoded.payload))
#expect(inner.body == responseBody)
}

@Test("a response payload of exactly 16 MiB is read and one byte more is refused")
func sixteenMebibyteBoundary() throws {
let requestID = [UInt8](repeating: 9, count: 32)
let empty = try BRC104Codec.encode(
BRC104Response(requestID: requestID, status: 200, body: [])
)
// The empty body's one-byte length prefix is five bytes for a body this large.
let overhead = empty.count - 1 + 5
let largest = try BRC104Response(
requestID: requestID, status: 200,
body: [UInt8](repeating: 1, count: (16 << 20) - overhead)
)
let encoded = try BRC104Codec.encode(largest)
#expect(encoded.count == 16 << 20)
#expect(try BRC104Codec.decodeResponse(encoded) == largest)

#expect(throws: BRC104Error.resourceLimit) {
try BRC104Codec.encode(
BRC104Response(
requestID: requestID, status: 200,
body: [UInt8](repeating: 1, count: (16 << 20) - overhead + 1)
)
)
}
#expect(throws: BRC104Error.resourceLimit) {
try BRC104Codec.decodeResponse(encoded + [0])
}
#expect(throws: BRC104HTTPFramingError.resourceLimit) {
try BRC104HTTPResponseFrame(
status: 200, body: [UInt8](repeating: 1, count: (16 << 20) + 1)
)
}
}

@Test("frames and messages do not disclose HTTP or authentication data")
func redaction() async throws {
let fixture = try await makeHTTPFixture()
Expand Down Expand Up @@ -214,7 +285,10 @@ private struct HTTPAuthFixture {
let responseMessage: AuthMessage
}

private func makeHTTPFixture() async throws -> HTTPAuthFixture {
private func makeHTTPFixture(
requestBody: [UInt8] = Array(#"{"secret":true}"#.utf8),
responseBody: [UInt8] = Array("accepted".utf8)
) async throws -> HTTPAuthFixture {
let client = PeerAuthenticator(wallet: ProtoWallet(rootKey: try httpPrivateKey(3)))
let server = PeerAuthenticator(wallet: ProtoWallet(rootKey: try httpPrivateKey(7)))
let start = try await client.beginAuthentication(with: try httpPrivateKey(7).publicKey)
Expand All @@ -232,7 +306,7 @@ private func makeHTTPFixture() async throws -> HTTPAuthFixture {
.init(name: "content-type", value: "application/json"),
.init(name: "x-bsv-trace", value: "1"),
],
body: Array(#"{"secret":true}"#.utf8)
body: requestBody
)
let requestMessage = try sentHTTPMessage([
try await client.makeGeneralMessage(
Expand All @@ -249,7 +323,7 @@ private func makeHTTPFixture() async throws -> HTTPAuthFixture {
requestID: requestID,
status: 201,
headers: [.init(name: "x-bsv-result", value: "ok")],
body: Array("accepted".utf8)
body: responseBody
)
let responseMessage = try sentHTTPMessage([
try await server.makeGeneralMessage(
Expand Down
14 changes: 7 additions & 7 deletions Tests/BSVStorageTests/UHRPAdvertisementTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@ import XCTest
/// `[2, "uhrp advertisement"]`, key ID "1", counterparty anyone (lines 89-98).
final class UHRPAdvertisementTests: XCTestCase {
private let hostScalar: [UInt8] = Array(repeating: 0, count: 31) + [0x2a]
private let hash = [UInt8](repeating: 0xab, count: 32)
private let contentHash = [UInt8](repeating: 0xab, count: 32)
private let url = "https://cdn.example/abc"

func testDecodesHandBuiltTypeScriptAdvertisement() throws {
let host = try PrivateKey(hostScalar)
let expiry = CompactSize.encode(1_700_000_000)
let size = CompactSize.encode(1_024)
let fields = [host.publicKey.compressedBytes, hash, Array(url.utf8), expiry, size]
let fields = [host.publicKey.compressedBytes, contentHash, Array(url.utf8), expiry, size]
let lockingKey = try linkedPrivateKey(host)
let signature = try lockingKey.sign(digest: BSVHashing.sha256(Array(fields.joined())))

Expand All @@ -40,7 +40,7 @@ final class UHRPAdvertisementTests: XCTestCase {

let advertisement = try UHRPAdvertisement.decode(script)
XCTAssertEqual(advertisement.hostIdentityKey, host.publicKey)
XCTAssertEqual(advertisement.hash.bytes, hash)
XCTAssertEqual(advertisement.hash.bytes, contentHash)
XCTAssertEqual(advertisement.hostedFileLocation.absoluteString, url)
XCTAssertEqual(advertisement.expiryTime, 1_700_000_000)
XCTAssertEqual(advertisement.fileSize, 1_024)
Expand Down Expand Up @@ -69,7 +69,7 @@ final class UHRPAdvertisementTests: XCTestCase {
// requires six fields, so this shape is refused.
let host = try PrivateKey(hostScalar)
let fields = [
hash,
contentHash,
Array("XUT6PqWb3GP3LR7dmBMCJwZ3oo5g1iGCF3CrpzyuJCemkGu1WGoq".utf8),
Array(url.utf8),
CompactSize.encode(1_700_000_000),
Expand All @@ -88,7 +88,7 @@ final class UHRPAdvertisementTests: XCTestCase {
let host = try PrivateKey(hostScalar)
let lockingKey = try linkedPrivateKey(host)
let fields = [
host.publicKey.compressedBytes, hash, Array(url.utf8),
host.publicKey.compressedBytes, contentHash, Array(url.utf8),
CompactSize.encode(1_700_000_000), CompactSize.encode(1_024),
]
let signature = try lockingKey.sign(digest: BSVHashing.sha256(Array(fields.joined())))
Expand All @@ -108,7 +108,7 @@ final class UHRPAdvertisementTests: XCTestCase {
let host = try PrivateKey(hostScalar)
let lockingKey = try linkedPrivateKey(host)
let fields = [
host.publicKey.compressedBytes, hash, Array(url.utf8),
host.publicKey.compressedBytes, contentHash, Array(url.utf8),
CompactSize.encode(1_700_000_000), CompactSize.encode(1_024),
]
let digest = BSVHashing.sha256(Array(fields.joined()))
Expand Down Expand Up @@ -225,7 +225,7 @@ final class UHRPAdvertisementTests: XCTestCase {
) throws -> Script {
let fields = [
hostKeyField ?? host.publicKey.compressedBytes,
hash ?? self.hash,
hash ?? contentHash,
Array((url ?? self.url).utf8),
expiry,
size,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -402,9 +402,11 @@ final class BRC52CertificateBinaryTests: XCTestCase {
limits: custom
)
let unsigned = try certificate.binary(includingSignature: false, limits: custom)
XCTAssertGreaterThan(unsigned.count, WalletCryptoLimits.standard.maximumPayloadByteCount)
// A wallet bounded at 1 MiB, below the expanded preimage.
let walletLimits = try WalletCryptoLimits(maximumPayloadByteCount: 1_048_576)
XCTAssertGreaterThan(unsigned.count, walletLimits.maximumPayloadByteCount)
let signed = try await certificate.signed(
using: ProtoWallet(rootKey: try key(9)),
using: ProtoWallet(rootKey: try key(9), limits: walletLimits),
limits: custom
)
let signatureValid = try await signed.verifySignature(limits: custom)
Expand All @@ -416,7 +418,7 @@ final class BRC52CertificateBinaryTests: XCTestCase {
)
await XCTAssertThrowsErrorAsync {
_ = try await certificate.signed(
using: ProtoWallet(rootKey: try self.key(9)),
using: ProtoWallet(rootKey: try self.key(9), limits: walletLimits),
limits: exactUnsignedOnly
)
}
Expand Down
4 changes: 3 additions & 1 deletion Tests/BSVWalletTests/WalletIdentifierTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,9 @@ final class WalletIdentifierTests: XCTestCase {
}

func testCryptoLimitsValidation() throws {
XCTAssertEqual(WalletCryptoLimits.standard.maximumCiphertextByteCount, 1_048_624)
XCTAssertEqual(WalletCryptoLimits.standard.maximumPayloadByteCount, 16_777_216)
XCTAssertEqual(WalletCryptoLimits.standard.maximumCiphertextByteCount, 16_777_264)
XCTAssertEqual(try WalletCryptoLimits(), WalletCryptoLimits.standard)
XCTAssertEqual(try WalletCryptoLimits(maximumPayloadByteCount: 0).maximumCiphertextByteCount, 48)
XCTAssertThrowsError(try WalletCryptoLimits(maximumPayloadByteCount: -1))
XCTAssertThrowsError(try WalletCryptoLimits(maximumJSONByteCount: -1))
Expand Down
Loading