Repository Public MIT
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP GlassKit7// File : Tests/SPGlassRegistryTests/RegistryCoreTests.swift8// Module : Tests9// Repository : https://git.spboucher.ai/sp-glasskit10// Project Website : https://glass.spboucher.ai11// Created : 2026-12-0212// Last Modified : 2026-12-0213//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 : MIT33//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 Foundation42import Testing43@testable import SPGlassRegistry4445@Suite("Registry paths")46struct RegistryPathTests {47 @Test("Safe relative paths are accepted", arguments: [48 "GlassButton.swift", "Buttons/GlassButton.swift", "Buttons/GlassButton+Style.swift", "Resources/en.lproj/GlassKit.strings",49 "a/b/c/d/e/f.swift", "LICENSE-SPGlassKit.txt", "components/glass-button/1.0.0/manifest.json",50 ])51 func accepts(path: String) throws {52 try RegistryPath.validate(path)53 }5455 @Test("Unsafe paths are refused", arguments: [56 "", "/etc/passwd", "~/x.swift", "../x.swift", "a/../../x.swift", "a/./x.swift", "a//x.swift", "a/", "/", "..",57 "a\\..\\x.swift", "C:/x.swift", "a/x.swift\u{0}", "a/\nx.swift", ".git/config", "a/.hidden", "a/x.swift.", "a/ x.swift",58 "a/x.swift ", "a/é.swift", "a/x\u{202E}fdp.swift", "a/x*.swift", "a/x?.swift", "a/$(id).swift", "a/x;y.swift", "a/x|y",59 String(repeating: "a/", count: 20) + "x.swift", String(repeating: "a", count: 300),60 ])61 func refuses(path: String) {62 #expect(throws: RegistryError.self) { try RegistryPath.validate(path) }63 }6465 @Test func collisionsAreDetectedCaseInsensitively() {66 #expect(throws: RegistryError.pathCollision("A/Button.swift", "a/button.swift")) {67 try RegistryPath.validateSet(["A/Button.swift", "a/button.swift"])68 }69 #expect(throws: RegistryError.self) { try RegistryPath.validateSet(["x.swift", "x.swift"]) }70 }7172 @Test func aFileCannotAlsoBeADirectory() {73 #expect(throws: RegistryError.self) { try RegistryPath.validateSet(["a/b", "a/b/c.swift"]) }74 #expect(throws: RegistryError.self) { try RegistryPath.validateSet(["A/B/c.swift", "a/b"]) }75 }7677 @Test("Identifiers", arguments: [("glass-button", true), ("a", true), ("glass-otp-field-2", true), ("", false), ("Glass", false), ("glass_button", false), ("-a", false), ("a-", false), ("a--b", false), ("a/b", false), ("..", false), ("a b", false), ("é", false)])78 func identifiers(id: String, valid: Bool) {79 #expect(RegistryPath.isValidIdentifier(id) == valid)80 }81}8283@Suite("Semantic versions")84struct SemanticVersionTests {85 @Test func ordering() throws {86 let ordered = try ["0.9.0", "1.0.0-alpha", "1.0.0-alpha.1", "1.0.0-beta", "1.0.0-rc.2", "1.0.0-rc.10", "1.0.0", "1.0.1", "1.2.0", "2.0.0", "10.0.0"].map { try SemanticVersion($0) }87 #expect(ordered == ordered.sorted())88 #expect(try SemanticVersion("1.2.3").description == "1.2.3")89 #expect(try SemanticVersion("1.2.3-rc.1").description == "1.2.3-rc.1")90 }9192 @Test("Invalid versions are refused", arguments: ["", "1", "1.0", "1.0.0.0", "v1.0.0", "01.0.0", "1.0.-1", "1.0.x", "1.0.0-", "1.0.0-a..b", "1.0.0+build", "1.0.0-β", "١.٠.٠", "1.0.99999999999", " 1.0.0"])93 func refuses(text: String) {94 #expect(throws: RegistryError.invalidVersion(text)) { try SemanticVersion(text) }95 }96}9798@Suite("Checksums and signatures")99struct RegistryHashTests {100 @Test func sha256MatchesKnownVectors() {101 #expect(RegistryHash.sha256(Data()) == "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")102 #expect(RegistryHash.sha256(Data("abc".utf8)) == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")103 #expect(RegistryHash.isSHA256(RegistryHash.sha256(Data())))104 #expect(!RegistryHash.isSHA256("E3B0C44298FC1C149AFBF4C8996FB92427AE41E4649B934CA495991B7852B855"))105 #expect(!RegistryHash.isSHA256("abc"))106 }107108 @Test func verifyChecksSizeThenChecksum() {109 let data = Data("hello".utf8)110 let good = ManifestFile(path: "a.swift", sha256: RegistryHash.sha256(data), bytes: 5)111 #expect(throws: Never.self) { try RegistryHash.verify(data, against: good) }112 #expect(throws: RegistryError.sizeMismatch(path: "a.swift", expected: 6, actual: 5)) {113 try RegistryHash.verify(data, against: ManifestFile(path: "a.swift", sha256: good.sha256, bytes: 6))114 }115 #expect(throws: RegistryError.self) {116 try RegistryHash.verify(Data("hellp".utf8), against: good)117 }118 }119120 @Test func contentDigestDependsOnPathsAndChecksumsNotOnOrder() {121 let a = ManifestFile(path: "a.swift", sha256: RegistryHash.sha256(Data("a".utf8)), bytes: 1)122 let b = ManifestFile(path: "b.swift", sha256: RegistryHash.sha256(Data("b".utf8)), bytes: 1)123 #expect(RegistryHash.contentDigest(of: [a, b]) == RegistryHash.contentDigest(of: [b, a]))124 #expect(RegistryHash.contentDigest(of: [a, b]) != RegistryHash.contentDigest(of: [a]))125 let renamed = ManifestFile(path: "c.swift", sha256: a.sha256, bytes: 1)126 #expect(RegistryHash.contentDigest(of: [a]) != RegistryHash.contentDigest(of: [renamed]))127 }128129 @Test func signatureRoundTripAndTamperDetection() throws {130 let privateKey = RegistrySignature.generatePrivateKey()131 let publicKey = try RegistrySignature.publicKey(forPrivateKey: privateKey)132 let data = Data("{\"items\":[]}".utf8)133 let signature = try RegistrySignature.sign(data, privateKey: privateKey)134 try RegistrySignature.verify(data, signature: signature, publicKey: publicKey)135 #expect(throws: RegistryError.signatureInvalid) {136 try RegistrySignature.verify(Data("{\"items\":[1]}".utf8), signature: signature, publicKey: publicKey)137 }138 let other = try RegistrySignature.publicKey(forPrivateKey: RegistrySignature.generatePrivateKey())139 #expect(throws: RegistryError.signatureInvalid) { try RegistrySignature.verify(data, signature: signature, publicKey: other) }140 #expect(throws: RegistryError.signatureInvalid) { try RegistrySignature.verify(data, signature: "not base64!", publicKey: publicKey) }141 #expect(throws: RegistryError.self) { try RegistrySignature.verify(data, signature: signature, publicKey: "short") }142 #expect(throws: RegistryError.self) { try RegistrySignature.sign(data, privateKey: "nope") }143 }144}145146@Suite("Dependency graph")147struct DependencyGraphTests {148 let graph: [String: [String]] = ["card": ["button", "base"], "button": ["base", "icons"], "icons": ["base"], "base": [], "lonely": []]149150 @Test func dependenciesComeFirstAndOrderIsDeterministic() throws {151 let order = try DependencyGraph.installationOrder(roots: ["card"]) { graph[$0] ?? [] }152 #expect(order == ["base", "icons", "button", "card"])153 #expect(try DependencyGraph.installationOrder(roots: ["lonely", "button", "card"]) { graph[$0] ?? [] } == ["lonely", "base", "icons", "button", "card"])154 #expect(try DependencyGraph.installationOrder(roots: ["base", "base"]) { graph[$0] ?? [] } == ["base"])155 }156157 @Test func cyclesAreReportedWithTheirPath() {158 let cyclic = ["a": ["b"], "b": ["c"], "c": ["a"], "self": ["self"]]159 #expect(throws: RegistryError.dependencyCycle(["a", "b", "c", "a"])) {160 try DependencyGraph.installationOrder(roots: ["a"]) { cyclic[$0] ?? [] }161 }162 #expect(throws: RegistryError.dependencyCycle(["self", "self"])) {163 try DependencyGraph.installationOrder(roots: ["self"]) { cyclic[$0] ?? [] }164 }165 }166167 @Test func errorsOfTheLookupArePropagated() {168 #expect(throws: RegistryError.unknownItem("ghost")) {169 try DependencyGraph.installationOrder(roots: ["a"]) { id throws(RegistryError) -> [String] in170 if id == "ghost" { throw .unknownItem(id) }171 return ["ghost"]172 }173 }174 }175176 @Test func dependentsAreTransitive() {177 #expect(DependencyGraph.dependents(of: "base", in: graph) == ["button", "card", "icons"])178 #expect(DependencyGraph.dependents(of: "icons", in: graph) == ["button", "card"])179 #expect(DependencyGraph.dependents(of: "card", in: graph).isEmpty)180 }181182 @Test func deepChainsDoNotOverflowReasonableDepth() throws {183 let chain = Dictionary(uniqueKeysWithValues: (0..<500).map { ("n\($0)", $0 == 499 ? [] : ["n\($0 + 1)"]) })184 let order = try DependencyGraph.installationOrder(roots: ["n0"]) { chain[$0] ?? [] }185 #expect(order.count == 500 && order.first == "n499" && order.last == "n0")186 }187}188189@Suite("Bounded JSON")190struct RegistryJSONTests {191 @Test func oversizedDocumentsAreRefusedBeforeParsing() {192 let data = Data(repeating: 0x20, count: RegistryJSON.maximumDocumentBytes + 1)193 #expect(throws: RegistryError.tooLarge(what: "doc", bytes: data.count, limit: RegistryJSON.maximumDocumentBytes)) {194 try RegistryJSON.decode(RegistryIndex.self, from: data, what: "doc")195 }196 }197198 @Test func deeplyNestedDocumentsAreRefused() {199 let nested = Data((String(repeating: "[", count: 5000) + String(repeating: "]", count: 5000)).utf8)200 #expect(throws: RegistryError.tooDeep(what: "doc", limit: RegistryJSON.maximumDepth)) {201 try RegistryJSON.decode(RegistryIndex.self, from: nested, what: "doc")202 }203 #expect(RegistryJSON.depth(of: Data(#"{"a":"[[[[[[[[[[[[[[[[[[","b":["\"[",{}]}"#.utf8)) == 3)204 }205206 @Test("Malformed documents produce a structured error", arguments: ["", "{", "[]", "nope", #"{"schemaVersion":"1"}"#, #"{"schemaVersion":1}"#, "\u{FEFF}{}"])207 func malformed(json: String) {208 #expect {209 try RegistryJSON.decode(RegistryIndex.self, from: Data(json.utf8), what: "doc")210 } throws: { error in211 if case RegistryError.malformed = error { true } else { false }212 }213 }214215 @Test func encodingIsStableAndEndsWithANewline() throws {216 let file = ManifestFile(path: "a.swift", sha256: String(repeating: "0", count: 64), bytes: 3)217 let first = try RegistryJSON.encode(file), second = try RegistryJSON.encode(file)218 #expect(first == second && first.last == 0x0A)219 #expect(String(decoding: first, as: UTF8.self).contains("\"path\" : \"a.swift\""))220 }221}222223@Suite("Manifest validation")224struct RegistryValidatorTests {225 static func manifest(id: String = "glass-button", version: String = "1.0.0", kind: String = "native-wrapper", license: String = "MIT", files: [ManifestFile]? = nil, dependencies: [ManifestDependency] = []) -> ComponentManifest {226 let files = files ?? [ManifestFile(path: "Buttons/GlassButton.swift", sha256: RegistryHash.sha256(Data("x".utf8)), bytes: 1)]227 return ComponentManifest(id: id, name: "GlassButton", version: version, description: "A button.", kind: kind, category: "buttons", platforms: ["iOS", "macOS"], minimumOS: ["iOS": "26.0", "macOS": "26.0"], dependencies: dependencies, frameworks: [], files: files, license: license, symbols: ["GlassButton"], examples: [], accessibility: [], changelog: [])228 }229230 @Test func aWellFormedManifestPasses() throws {231 try RegistryValidator.validate(Self.manifest())232 let data = try RegistryJSON.encode(Self.manifest())233 #expect(try RegistryJSON.decode(ComponentManifest.self, from: data, what: "m") == Self.manifest())234 }235236 @Test func everyRequiredFieldOfTheSchemaIsPresentInTheEncoding() throws {237 let object = try #require(JSONSerialization.jsonObject(with: RegistryJSON.encode(Self.manifest())) as? [String: Any])238 for field in ["schemaVersion", "id", "name", "version", "description", "kind", "platforms", "minimumOS", "dependencies", "files", "sha256", "license", "symbols", "examples", "accessibility", "changelog"] {239 #expect(object[field] != nil, "\(field)")240 }241 }242243 @Test func invalidManifestsAreRefused() {244 let hash = RegistryHash.sha256(Data("x".utf8))245 let cases: [ComponentManifest] = [246 Self.manifest(id: "Glass Button"),247 Self.manifest(version: "1.0"),248 Self.manifest(kind: "fake-glass"),249 Self.manifest(license: "Proprietary"),250 Self.manifest(files: []),251 Self.manifest(files: [ManifestFile(path: "../../etc/passwd", sha256: hash, bytes: 1)]),252 Self.manifest(files: [ManifestFile(path: "/tmp/x.swift", sha256: hash, bytes: 1)]),253 Self.manifest(files: [ManifestFile(path: "a.swift", sha256: "zz", bytes: 1)]),254 Self.manifest(files: [ManifestFile(path: "a.swift", sha256: hash, bytes: -1)]),255 Self.manifest(files: [ManifestFile(path: "a.swift", sha256: hash, bytes: RegistryJSON.maximumFileBytes + 1)]),256 Self.manifest(files: [ManifestFile(path: "A.swift", sha256: hash, bytes: 1), ManifestFile(path: "a.swift", sha256: hash, bytes: 1)]),257 Self.manifest(files: (0...RegistryValidator.maximumFilesPerItem).map { ManifestFile(path: "f\($0).swift", sha256: hash, bytes: 1) }),258 Self.manifest(dependencies: [ManifestDependency(id: "glass-button", version: "1.0.0")]),259 Self.manifest(dependencies: [ManifestDependency(id: "base", version: "1.0.0"), ManifestDependency(id: "base", version: "1.0.0")]),260 Self.manifest(dependencies: [ManifestDependency(id: "../x", version: "1.0.0")]),261 Self.manifest(dependencies: [ManifestDependency(id: "base", version: "latest")]),262 ]263 for manifest in cases {264 #expect(throws: RegistryError.self, "\(manifest.id) \(manifest.version) \(manifest.files.map(\.path).prefix(2))") { try RegistryValidator.validate(manifest) }265 }266 }267268 @Test func aTamperedFileListInvalidatesTheDigest() {269 var manifest = Self.manifest()270 manifest.files.append(ManifestFile(path: "Extra.swift", sha256: RegistryHash.sha256(Data("y".utf8)), bytes: 1))271 #expect(throws: RegistryError.self) { try RegistryValidator.validate(manifest) }272 }273274 @Test func aNewerSchemaIsRefused() {275 var manifest = Self.manifest()276 manifest.schemaVersion = 2277 #expect(throws: RegistryError.unsupportedSchema(what: "Manifest \"glass-button\"", version: 2)) { try RegistryValidator.validate(manifest) }278 }279280 @Test func indexValidation() throws {281 let version = RegistryIndexVersion(version: "1.0.0", path: "components/a/1.0.0/manifest.json", sha256: RegistryHash.sha256(Data()))282 let entry = RegistryIndexEntry(id: "a", name: "A", kind: "primitive", category: nil, summary: "", latest: "1.0.0", versions: [version])283 try RegistryValidator.validate(RegistryIndex(name: "r", homepage: "h", license: "MIT", items: [entry], themes: []))284 var missingLatest = entry; missingLatest.latest = "2.0.0"285 var traversal = entry; traversal.versions = [RegistryIndexVersion(version: "1.0.0", path: "../../secret", sha256: version.sha256)]286 for bad in [[entry, entry], [missingLatest], [traversal]] {287 #expect(throws: RegistryError.self) { try RegistryValidator.validate(RegistryIndex(name: "r", homepage: "h", license: "MIT", items: bad, themes: [])) }288 }289 }290}291292@Suite("Line diff")293struct LineDiffTests {294 @Test func identicalTextsProduceNoDiff() {295 #expect(LineDiff.unified(old: "a\nb\n", new: "a\nb\n", oldLabel: "x", newLabel: "y").isEmpty)296 #expect(LineDiff.unified(old: "a\r\nb\r\n", new: "a\nb\n", oldLabel: "x", newLabel: "y").isEmpty)297 }298299 @Test func aChangedLineIsShownWithContext() {300 let old = (1...10).map { "line \($0)" }.joined(separator: "\n") + "\n"301 let new = old.replacingOccurrences(of: "line 5", with: "line five")302 let diff = LineDiff.unified(old: old, new: new, oldLabel: "registry", newLabel: "local")303 #expect(diff == """304 --- registry305 +++ local306 @@ -2,7 +2,7 @@307 line 2308 line 3309 line 4310 -line 5311 +line five312 line 6313 line 7314 line 8315316 """)317 }318319 @Test func additionsDeletionsAndSeparateHunks() {320 let old = (1...30).map { "l\($0)" }.joined(separator: "\n")321 var lines = (1...30).map { "l\($0)" }322 lines.remove(at: 1)323 lines.insert("new", at: 25)324 let diff = LineDiff.unified(old: old, new: lines.joined(separator: "\n"), oldLabel: "a", newLabel: "b")325 #expect(diff.components(separatedBy: "\n@@").count == 3, "two hunks expected")326 #expect(diff.contains("-l2\n") && diff.contains("+new\n"))327 #expect(LineDiff.unified(old: "", new: "a\nb\n", oldLabel: "a", newLabel: "b").contains("@@ -0,0 +1,2 @@"))328 }329}330331@Suite("Swift source scanning")332struct SwiftSourceScannerTests {333 let source = """334 // GlassCommented should not count: struct GlassFake {}335 import SwiftUI336 import SPGlassCore337 @_exported import SPGlassThemes338339 /// Uses ``GlassDocOnly`` in documentation.340 public struct GlassThing<Content: View>: View {341 let text = "GlassInString and \\(GlassInterpolated.self)"342 var body: some View { GlassOther(title: "x").glassSurface() }343 }344 /* block345 GlassBlock */346 enum GlassInternal { case a }347 private struct GlassPrivate {}348 @MainActor public final class GlassModel {}349 extension View {350 public func glassThing() -> some View { self }351 }352 let multi = \"\"\"353 GlassMultiline354 \"\"\"355 """356357 @Test func declaredSymbolsSkipPrivateTypesCommentsAndStrings() {358 #expect(SwiftSourceScanner.declaredSymbols(in: source) == ["GlassThing", "GlassInternal", "GlassModel", "glassThing"])359 #expect(SwiftSourceScanner.publicTypes(in: source) == ["GlassThing", "GlassModel"])360 }361362 @Test func referencesIgnoreCommentsAndStringLiterals() {363 let references = SwiftSourceScanner.referencedIdentifiers(in: source)364 #expect(references.contains("GlassOther") && references.contains("glassSurface") && references.contains("View"))365 for absent in ["GlassCommented", "GlassFake", "GlassDocOnly", "GlassInString", "GlassBlock", "GlassMultiline"] {366 #expect(!references.contains(absent), "\(absent)")367 }368 }369370 @Test func importsAreListed() {371 #expect(SwiftSourceScanner.imports(in: source) == ["SwiftUI", "SPGlassCore", "SPGlassThemes"])372 }373374 @Test func sourceModeRemovesOnlyGlassKitImports() {375 let transformed = SourceTransform.forSourceMode(source, moduleNames: ["SPGlassCore", "SPGlassThemes"])376 #expect(SwiftSourceScanner.imports(in: transformed) == ["SwiftUI"])377 #expect(transformed.contains("// GlassCommented should not count"))378 #expect(transformed.components(separatedBy: "\n").count == source.components(separatedBy: "\n").count - 2)379 #expect(SourceTransform.forSourceMode("let x = \"import SPGlassCore\"\n", moduleNames: ["SPGlassCore"]) == "let x = \"import SPGlassCore\"\n")380 }381}382