Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : QYVORA7// File : security/tests/Sources/FuzzTargets/Support.swift8// Module : Tests9// Repository : https://git.spboucher.ai/qyvora10// Project Website : Not specified11// Created : 2026-12-0412// Last Modified : 2026-12-0413//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import AuditSupport42import Foundation43import QyvoraMath4445// Fuzz-target model. A target is a harness `(Bytes) -> Void` around one parser or verifier that46// takes untrusted input. A harness must return normally for every input: a Swift trap47// (out-of-range index, arithmetic overflow, forced unwrap, precondition) kills the worker process48// and is captured by the driver as a crash. Beyond "no trap", harnesses check invariants and call49// `fuzzFail` when one is broken.5051public struct FuzzTarget: Sendable {52 public let name: String53 public let summary: String54 /// Inputs longer than this are truncated by the engine before execution.55 public let maxLength: Int56 /// The input is text: mutations favour printable characters.57 public let text: Bool58 /// The harness reports acceptance (`FuzzOutcome.accept()`), and only the committed seeds may be59 /// accepted: a mutated input that verifies is an invariant failure (forgery / malleability).60 public let acceptOnlySeeds: Bool61 /// Tokens inserted by the dictionary mutator.62 public let dictionary: [Bytes]63 /// Structure-aware seeds built from valid objects (written to the committed corpus by `qyfuzz seed`).64 public let seeds: @Sendable () -> [Bytes]65 /// Seeds regenerated at each start and never written to the committed corpus (throw-away private keys).66 public let runtimeSeeds: (@Sendable () -> [Bytes])?67 public let run: @Sendable (Bytes) -> Void6869 public init(70 _ name: String, _ summary: String, maxLength: Int = 4096, text: Bool = false, acceptOnlySeeds: Bool = false,71 dictionary: [String] = [], tokens: [Bytes] = [], seeds: @escaping @Sendable () -> [Bytes],72 runtimeSeeds: (@Sendable () -> [Bytes])? = nil, run: @escaping @Sendable (Bytes) -> Void73 ) {74 self.name = name75 self.summary = summary76 self.maxLength = maxLength77 self.text = text78 self.acceptOnlySeeds = acceptOnlySeeds79 self.dictionary = dictionary.map { Bytes($0.utf8) } + tokens80 self.seeds = seeds81 self.runtimeSeeds = runtimeSeeds82 self.run = run83 }84}8586/// Outcome of the current execution, read by the engine after the harness returns. The worker is87/// single-threaded, so plain globals are enough.88public enum FuzzOutcome {89 nonisolated(unsafe) static var hash: UInt64 = 0xcbf2_9ce4_8422_232590 nonisolated(unsafe) static var acceptedFlag = false9192 public static func reset() {93 hash = 0xcbf2_9ce4_8422_232594 acceptedFlag = false95 }9697 /// Folds a short label into the outcome class of this execution (for example the error case).98 public static func note(_ label: String) {99 for b in label.utf8 {100 if b == 0x28 { break } // "(": drop associated values, keep the case name101 hash = (hash ^ UInt64(b)) &* 0x100_0000_01b3102 }103 hash = (hash ^ 0xff) &* 0x100_0000_01b3104 }105106 public static func note(error: any Error) { note(String(describing: error)) }107108 /// The verifier accepted the input.109 public static func accept() {110 acceptedFlag = true111 note("accepted")112 }113114 public static var current: UInt64 { hash }115 public static var accepted: Bool { acceptedFlag }116}117118/// Invariant failure: stops the worker with a recognisable message (captured like any other crash).119public func fuzzFail(_ message: @autoclosure () -> String, file: StaticString = #fileID, line: UInt = #line) -> Never {120 fatalError("FUZZ-INVARIANT: \(message())", file: file, line: line)121}122123@inline(__always)124public func fuzzCheck(_ condition: Bool, _ message: @autoclosure () -> String, file: StaticString = #fileID, line: UInt = #line) {125 if !condition { fuzzFail(message(), file: file, line: line) }126}127128/// Sink for values a harness computes only to exercise the code. In a release build the optimiser deletes a129/// computation whose result is unused — together with the overflow and bounds traps inside it (observed: an130/// `Int` addition that overflows did not trap behind `_ = value`). Every such result goes through `fuzzUse`,131/// which folds its bytes into a global the optimiser cannot prove dead.132nonisolated(unsafe) public var fuzzSink: UInt64 = 0xcbf2_9ce4_8422_2325133134@inline(__always)135public func fuzzUse<T>(_ value: T) {136 withUnsafeBytes(of: value) { raw in137 var h = fuzzSink138 for b in raw.prefix(16) { h = (h ^ UInt64(b)) &* 0x100_0000_01b3 }139 fuzzSink = h140 }141}142143/// Runs a throwing parser, noting "ok" or the error case; returns the value when it parsed.144@discardableResult145public func attempt<T>(_ body: () throws -> T) -> T? { attempt("", body) }146147@discardableResult148public func attempt<T>(_ label: String, _ body: () throws -> T) -> T? {149 do {150 let v = try body()151 FuzzOutcome.note(label + "ok")152 fuzzUse(v)153 return v154 } catch {155 FuzzOutcome.note(label + String(describing: error))156 return nil157 }158}159160/// Cursor over the fuzz input, for harnesses that carve several fields out of one byte string.161/// Reads past the end give zeros: every input is usable.162public struct FuzzInput {163 public let bytes: Bytes164 public private(set) var offset = 0165166 public init(_ bytes: Bytes) { self.bytes = bytes }167168 public var remaining: Int { max(0, bytes.count - offset) }169170 public mutating func byte() -> UInt8 {171 defer { offset += 1 }172 return offset < bytes.count ? bytes[offset] : 0173 }174175 /// Exactly `count` bytes, zero-padded.176 public mutating func take(_ count: Int) -> Bytes {177 var out = Bytes()178 out.reserveCapacity(count)179 let available = max(0, min(count, bytes.count - offset))180 if available > 0 { out.append(contentsOf: bytes[offset..<(offset + available)]) }181 if available < count { out.append(contentsOf: Bytes(repeating: 0, count: count - available)) }182 offset += count183 return out184 }185186 /// At most `count` bytes, not padded.187 public mutating func upTo(_ count: Int) -> Bytes {188 let available = max(0, min(count, bytes.count - offset))189 defer { offset += available }190 return available > 0 ? Bytes(bytes[offset..<(offset + available)]) : []191 }192193 public mutating func rest() -> Bytes { upTo(remaining) }194195 /// A length-prefixed field (u16 big endian, clamped to what is left).196 public mutating func field() -> Bytes {197 let n = Int(byte()) << 8 | Int(byte())198 return upTo(n)199 }200}201202public func fuzzString(_ bytes: Bytes) -> String { String(decoding: bytes, as: UTF8.self) }203204/// Length-prefixed concatenation matching `FuzzInput.field()`.205public func fuzzFields(_ fields: Bytes...) -> Bytes {206 var out = Bytes()207 for f in fields {208 precondition(f.count <= 0xffff)209 out += [UInt8(f.count >> 8), UInt8(f.count & 0xff)] + f210 }211 return out212}213214/// Runs an async body to completion from the synchronous harness.215public func fuzzAwait(_ body: @escaping @Sendable () async -> Void) {216 let done = DispatchSemaphore(value: 0)217 Task.detached {218 await body()219 done.signal()220 }221 done.wait()222}223224/// Deterministic bytes for fixtures (SHAKE-free: the audit generator seeded with a label).225public func fixtureBytes(_ label: String, _ count: Int) -> Bytes {226 var h: UInt64 = 0xcbf2_9ce4_8422_2325227 for b in label.utf8 { h = (h ^ UInt64(b)) &* 0x100_0000_01b3 }228 var rng = AuditRNG(seed: h)229 return rng.bytes(count)230}231232/// Index chosen by a selector byte. The JSON seeds are text and start with a letter: "a" selects 0, "b" 1, …233/// (a letter, not a digit, so that the mutations that rewrite numbers leave the selector alone).234/// Any other byte selects by its value. Always below `count`.235public func fuzzSelector(_ byte: UInt8, _ count: Int) -> Int {236 switch byte {237 case 0x61...0x7a: return Int(byte - 0x61) % count238 default: return Int(byte) % count239 }240}241242/// Replaces the leading selector of a seed text ("0"…"9", then "a", "b" for 10, 11) by its letter form.243func letterSelector(_ text: String) -> String {244 guard let first = text.utf8.first else { return text }245 let value: UInt8246 switch first {247 case 0x30...0x39: value = first - 0x30248 case 0x61...0x7a: value = first - 0x61 + 10249 default: return text250 }251 return String(decoding: [0x61 + value], as: UTF8.self) + text.dropFirst()252}253