SPB Git

Repository Public MIT

CLISecurityTests.swift 21.5 KB 351 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Tests/GlassCLICoreTests/CLISecurityTests.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 Testing43import SPGlassRegistry44@testable import GlassCLICore4546@Suite("spglass security and failure handling")47struct CLISecurityTests {48    /// Rewrites the manifest of an item and re-links it from the index, as a hostile registry would.49    static func tamperManifest(_ fixture: Fixture, id: String, _ edit: (inout ComponentManifest) -> Void, fixDigest: Bool = true) throws {50        let indexURL = fixture.registry.appendingPathComponent("registry.json")51        var index = try JSONDecoder().decode(RegistryIndex.self, from: Data(contentsOf: indexURL))52        let position = try #require(index.items.firstIndex { $0.id == id })53        let path = index.items[position].versions[0].path54        var manifest = try JSONDecoder().decode(ComponentManifest.self, from: Data(contentsOf: fixture.registry.appendingPathComponent(path)))55        edit(&manifest)56        if fixDigest { manifest.sha256 = RegistryHash.contentDigest(of: manifest.files) }57        let data = try RegistryJSON.encode(manifest)58        try data.write(to: fixture.registry.appendingPathComponent(path))59        index.items[position].versions[0].sha256 = RegistryHash.sha256(data)60        try RegistryJSON.encode(index).write(to: indexURL)61    }6263    @Test func aCorruptedFileIsDetectedAndNothingIsWritten() async throws {64        let fixture = try Fixture(); defer { fixture.cleanUp() }65        await fixture.initialize()66        try "struct Button { /* altered in transit */ }\n".write(to: fixture.registry.appendingPathComponent("components/glass-button/1.0.0/files/Buttons/Button.swift"), atomically: true, encoding: .utf8)67        let before = fixture.snapshot()68        let outcome = await fixture.run("add", "glass-card")69        #expect(outcome.exitCode == ExitCode.integrity.rawValue)70        #expect(outcome.standardError.contains("mismatch"))71        #expect(fixture.snapshot() == before, "not even the valid dependency was installed")72        #expect(!fixture.exists(".spglass-staging"))73    }7475    @Test func aManifestThatDoesNotMatchTheIndexIsRefused() async throws {76        let fixture = try Fixture(); defer { fixture.cleanUp() }77        await fixture.initialize()78        let url = fixture.registry.appendingPathComponent("components/glass-button/1.0.0/manifest.json")79        try Data(contentsOf: url).dropLast(2).write(to: url)80        let outcome = await fixture.run("add", "glass-button")81        #expect(outcome.exitCode == ExitCode.integrity.rawValue && !fixture.exists("Sources/App/GlassKit"))82    }8384    @Test("Hostile manifest paths are refused before any write", arguments: [85        "../../../escape.swift", "/tmp/spglass-escape.swift", "Buttons/../../../escape.swift", "~/escape.swift", ".git/hooks/pre-commit", "a\\..\\b.swift",86    ])87    func traversal(path: String) async throws {88        let fixture = try Fixture(); defer { fixture.cleanUp() }89        await fixture.initialize()90        try Self.tamperManifest(fixture, id: "glass-button") { $0.files[0].path = path }91        let before = fixture.snapshot()92        let outcome = await fixture.run("add", "glass-button")93        #expect(outcome.exitCode == ExitCode.invalidData.rawValue, "\(outcome.standardError)")94        #expect(fixture.snapshot() == before)95        #expect(!FileManager.default.fileExists(atPath: fixture.root.appendingPathComponent("escape.swift").path))96        #expect(!FileManager.default.fileExists(atPath: "/tmp/spglass-escape.swift"))97    }9899    @Test func malformedAndInconsistentManifestsAreRefused() async throws {100        let edits: [(inout ComponentManifest) -> Void] = [101            { $0.id = "glass-card" },102            { $0.version = "2.0.0" },103            { $0.kind = "script" },104            { $0.license = "GPL-3.0" },105            { $0.files[0].sha256 = "nope" },106            { $0.files.append($0.files[0]) },107            { $0.dependencies.append(ManifestDependency(id: "glass-button", version: "1.0.0")) },108            { $0.schemaVersion = 99 },109        ]110        for edit in edits {111            let fixture = try Fixture(); defer { fixture.cleanUp() }112            await fixture.initialize()113            try Self.tamperManifest(fixture, id: "glass-button", edit)114            let outcome = await fixture.run("add", "glass-button")115            #expect(outcome.exitCode != 0 && !fixture.exists("Sources/App/GlassKit"), "\(outcome.standardError)")116        }117        let fixture = try Fixture(); defer { fixture.cleanUp() }118        await fixture.initialize()119        try Self.tamperManifest(fixture, id: "glass-button", { $0.files[0].bytes += 1 }, fixDigest: false)120        #expect(await fixture.run("add", "glass-button").exitCode == ExitCode.integrity.rawValue)121    }122123    @Test func aDependencyCycleIsReported() async throws {124        let fixture = try Fixture(); defer { fixture.cleanUp() }125        await fixture.initialize()126        try Self.tamperManifest(fixture, id: "glass-foundation") { $0.dependencies = [ManifestDependency(id: "glass-card", version: "1.0.0")] }127        let outcome = await fixture.run("add", "glass-card")128        #expect(outcome.exitCode == ExitCode.invalidData.rawValue && outcome.standardError.contains("Dependency cycle"))129        #expect(!fixture.exists("Sources/App/GlassKit"))130    }131132    @Test func oversizedAndDeeplyNestedDocumentsAreRefused() async throws {133        let fixture = try Fixture(); defer { fixture.cleanUp() }134        await fixture.initialize()135        let local = LocalDirectorySource(root: fixture.registry)136        let huge = Data("{\"pad\":\"".utf8) + Data(repeating: 0x61, count: RegistryJSON.maximumDocumentBytes) + Data("\"}".utf8)137        let big = await fixture.run("add", "glass-button", source: StubSource(base: local, replacements: ["registry.json": huge]))138        #expect(big.exitCode == ExitCode.invalidData.rawValue && big.standardError.contains("limit"))139        let nested = Data((String(repeating: "[", count: 100_000) + String(repeating: "]", count: 100_000)).utf8)140        let deep = await fixture.run("add", "glass-button", source: StubSource(base: local, replacements: ["registry.json": nested]))141        #expect(deep.exitCode == ExitCode.invalidData.rawValue)142        let garbage = await fixture.run("list", source: StubSource(base: local, replacements: ["registry.json": Data("<html>502</html>".utf8)]))143        #expect(garbage.exitCode == ExitCode.invalidData.rawValue)144        #expect(!fixture.exists("Sources/App/GlassKit"))145    }146147    @Test func aSymbolicLinkInTheDestinationIsNotFollowed() async throws {148        let fixture = try Fixture(); defer { fixture.cleanUp() }149        await fixture.initialize()150        let outside = fixture.root.appendingPathComponent("outside")151        try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true)152        try FileManager.default.createDirectory(at: fixture.project.appendingPathComponent("Sources/App/GlassKit"), withIntermediateDirectories: true)153        try FileManager.default.createSymbolicLink(at: fixture.project.appendingPathComponent("Sources/App/GlassKit/Buttons"), withDestinationURL: outside)154        let outcome = await fixture.run("add", "glass-button")155        #expect(outcome.exitCode == ExitCode.invalidData.rawValue && outcome.standardError.contains("symbolic link"))156        #expect(try FileManager.default.contentsOfDirectory(atPath: outside.path).isEmpty, "nothing was written through the link")157        #expect(!fixture.exists("Sources/App/GlassKit/Core"), "the operation is all or nothing")158    }159160    @Test func aRegistryLinkThatLeavesTheRegistryIsRefused() async throws {161        let fixture = try Fixture(); defer { fixture.cleanUp() }162        await fixture.initialize()163        let secret = fixture.root.appendingPathComponent("secret.txt")164        try "top secret".write(to: secret, atomically: true, encoding: .utf8)165        let target = fixture.registry.appendingPathComponent("components/glass-button/1.0.0/files/Buttons/Button.swift")166        try FileManager.default.removeItem(at: target)167        try FileManager.default.createSymbolicLink(at: target, withDestinationURL: secret)168        let outcome = await fixture.run("add", "glass-button")169        #expect(outcome.exitCode != 0 && outcome.standardError.contains("symbolic link"))170        #expect(!fixture.exists("Sources/App/GlassKit"))171        await #expect(throws: RegistryError.self) { try await LocalDirectorySource(root: fixture.registry).fetch("../secret.txt", limit: 100) }172    }173174    @Test func anUntrackedFileInTheWayIsAConflictNotAnOverwrite() async throws {175        let fixture = try Fixture(); defer { fixture.cleanUp() }176        await fixture.initialize()177        try fixture.write("Sources/App/GlassKit/Buttons/Button.swift", "// my own file with the same name\n")178        let outcome = await fixture.run("add", "glass-button")179        #expect(outcome.exitCode == ExitCode.conflict.rawValue)180        #expect(fixture.read("Sources/App/GlassKit/Buttons/Button.swift") == "// my own file with the same name\n")181        #expect(!fixture.exists("spglass.lock.json"))182    }183184    @Test func twoItemsCannotClaimTheSameFile() async throws {185        let fixture = try Fixture(); defer { fixture.cleanUp() }186        await fixture.initialize()187        #expect(await fixture.run("add", "glass-button").exitCode == 0)188        try Self.tamperManifest(fixture, id: "glass-card") { $0.files[0].path = "buttons/button.swift" }189        let before = fixture.snapshot()190        let outcome = await fixture.run("add", "glass-card")191        #expect(outcome.exitCode == ExitCode.invalidData.rawValue && outcome.standardError.contains("collide"))192        #expect(fixture.snapshot() == before)193    }194195    @Test("A failure in the middle of the writes restores the previous state", arguments: [0, 1, 2, 3])196    func rollback(failAfter: Int) async throws {197        let fixture = try Fixture(); defer { fixture.cleanUp() }198        await fixture.initialize()199        #expect(await fixture.run("add", "glass-button").exitCode == 0)200        try fixture.publish(version: "1.1.0")201        let before = fixture.snapshot()202        let outcome = await fixture.run("update", "glass-button", failAfterChanges: failAfter)203        #expect(outcome.exitCode == ExitCode.failure.rawValue)204        #expect(fixture.snapshot() == before, "files, deleted files and the lock are all back")205        #expect(!fixture.exists(".spglass-staging"))206        #expect(await fixture.run("update", "glass-button").exitCode == 0, "the project is usable afterwards")207        #expect(try fixture.lock().item("glass-button")?.version == "1.1.0")208    }209210    @Test("A killed process is recovered by the next command", arguments: [1, 2, 3])211    func crashRecovery(abandonAfter: Int) async throws {212        let fixture = try Fixture(); defer { fixture.cleanUp() }213        await fixture.initialize()214        #expect(await fixture.run("add", "glass-button").exitCode == 0)215        let before = fixture.snapshot()216        let project = Project(root: fixture.project)217        var transaction = FileTransaction(project: project)218        transaction.abandonAfterChanges = abandonAfter219        try await transaction.apply([220            .write("Sources/App/GlassKit/Buttons/Button.swift", Data("half written update\n".utf8)),221            .delete("Sources/App/GlassKit/Buttons/Button+Style.swift"),222            .write("Sources/App/GlassKit/Buttons/New.swift", Data("new\n".utf8)),223            .write("spglass.lock.json", Data("{}".utf8)),224        ])225        #expect(fixture.exists(".spglass-staging"), "the interrupted transaction left its journal")226        #expect(fixture.read("Sources/App/GlassKit/Buttons/Button.swift") == "half written update\n")227        #expect(await fixture.run("doctor").standardOutput.contains("! interrupted operations"))228        let next = await fixture.run("add", "glass-button")229        #expect(next.exitCode == 0 && next.standardOutput.contains("Recovered 1 interrupted operation"))230        #expect(fixture.snapshot() == before)231    }232233    @Test func cancellationRollsBack() async throws {234        let fixture = try Fixture(); defer { fixture.cleanUp() }235        await fixture.initialize()236        let before = fixture.snapshot()237        let task = Task { await fixture.run("add", "glass-card") }238        task.cancel()239        let outcome = await task.value240        // Cancellation is cooperative: the command either finished before noticing or was interrupted cleanly.241        if outcome.exitCode == ExitCode.interrupted.rawValue {242            #expect(fixture.snapshot() == before && !fixture.exists(".spglass-staging"))243        } else {244            #expect(outcome.exitCode == 0)245        }246        let transaction = FileTransaction(project: Project(root: fixture.project))247        let cancelled = Task {248            withUnsafeCurrentTask { $0?.cancel() }249            try await transaction.apply([.write("Sources/App/x.swift", Data("x".utf8))])250        }251        await #expect(throws: CancellationError.self) { try await cancelled.value }252        #expect(!fixture.exists("Sources/App/x.swift") && !fixture.exists(".spglass-staging"))253    }254255    @Test func anUnreachableRegistryIsANetworkErrorAndChangesNothing() async throws {256        let fixture = try Fixture(); defer { fixture.cleanUp() }257        await fixture.initialize()258        let before = fixture.snapshot()259        let outcome = await fixture.run("add", "glass-button", source: StubSource(unreachable: true))260        #expect(outcome.exitCode == ExitCode.network.rawValue && fixture.snapshot() == before)261        let doctor = await fixture.run("doctor", source: StubSource(unreachable: true))262        #expect(doctor.exitCode == 0 && doctor.standardOutput.contains("! registry"), "an unreachable registry is a warning for doctor")263        #expect(await fixture.run("verify", source: StubSource(unreachable: true)).exitCode == 0, "verify works without the registry")264    }265266    @Test func theCacheServesInstallsOfflineAndDetectsItsOwnCorruption() async throws {267        let fixture = try Fixture(); defer { fixture.cleanUp() }268        await fixture.initialize()269        let cache = fixture.root.appendingPathComponent("cache")270        let online = CachingRegistrySource(upstream: StubSource(base: LocalDirectorySource(root: fixture.registry)), cacheRoot: cache, offline: false)271        #expect(await fixture.run("add", "glass-button", "--dry-run", source: online).exitCode == 0)272273        let offline = CachingRegistrySource(upstream: StubSource(unreachable: true), cacheRoot: cache, offline: true)274        #expect(await fixture.run("add", "glass-button", source: offline).exitCode == 0, "everything needed is in the cache")275        #expect(fixture.exists("Sources/App/GlassKit/Buttons/Button.swift"))276        let miss = await fixture.run("add", "glass-card", source: offline)277        #expect(miss.exitCode == ExitCode.network.rawValue && miss.standardError.contains("not in the local cache"))278279        // The registry going down after a first contact falls back to the cached index.280        let down = CachingRegistrySource(upstream: StubSource(unreachable: true), cacheRoot: cache, offline: false)281        #expect(await fixture.run("list", source: down).exitCode == 0)282283        // A damaged cache entry is caught by the checksum, dropped and fetched again when online.284        let cached = online.directory.appendingPathComponent("components/glass-button/1.0.0/files/Buttons/Button.swift")285        try "tampered".write(to: cached, atomically: true, encoding: .utf8)286        try FileManager.default.removeItem(at: fixture.project.appendingPathComponent("Sources/App/GlassKit/Buttons/Button.swift"))287        let offlineBad = await fixture.run("add", "glass-button", source: offline)288        #expect(offlineBad.exitCode == ExitCode.integrity.rawValue && !fixture.exists("Sources/App/GlassKit/Buttons/Button.swift"))289        try "tampered".write(to: cached, atomically: true, encoding: .utf8)290        #expect(await fixture.run("add", "glass-button", source: online).exitCode == 0)291        #expect(fixture.read("Sources/App/GlassKit/Buttons/Button.swift")?.hasPrefix("struct Button") == true)292    }293294    @Test func aConfiguredPublicKeyRequiresAValidSignature() async throws {295        let fixture = try Fixture(); defer { fixture.cleanUp() }296        await fixture.initialize()297        let key = RegistrySignature.generatePrivateKey()298        let publicKey = try RegistrySignature.publicKey(forPrivateKey: key)299300        let unsigned = await fixture.run("add", "glass-button", "--public-key", publicKey)301        #expect(unsigned.exitCode == ExitCode.integrity.rawValue && unsigned.standardError.contains("not signed"))302303        try fixture.publish(version: "1.1.0", signingKey: key)304        #expect(await fixture.run("add", "glass-button", "--public-key", publicKey, "--dry-run").exitCode == 0)305        let other = try RegistrySignature.publicKey(forPrivateKey: RegistrySignature.generatePrivateKey())306        #expect(await fixture.run("add", "glass-button", "--public-key", other).exitCode == ExitCode.integrity.rawValue)307308        // Any change to the signed index, even with consistent checksums, is caught.309        try Self.tamperManifest(fixture, id: "glass-button") { $0.description = "Altered." }310        let tampered = await fixture.run("add", "glass-button", "--public-key", publicKey)311        #expect(tampered.exitCode == ExitCode.integrity.rawValue && !fixture.exists("Sources/App/GlassKit"))312        let trusting = await fixture.run("add", "glass-button", "--dry-run")313        #expect(trusting.exitCode == 0, "without a key the same registry passes: checksums alone do not prove authenticity")314    }315316    @Test func insecureRegistriesAreRefused() throws {317        for address in ["http://example.com/registry", "ftp://example.com/r", "https://user:pw@example.com/r", "https:///nohost"] {318            let url = try #require(URL(string: address))319            #expect(throws: CLIError.self, "\(address)") { try HTTPRegistrySource(baseURL: url) }320        }321        #expect(try HTTPRegistrySource(baseURL: #require(URL(string: "https://glass.spboucher.ai/registry/"))).identity == "https://glass.spboucher.ai/registry")322    }323324    @Test func corruptProjectFilesAreReportedNotOverwritten() async throws {325        let fixture = try Fixture(); defer { fixture.cleanUp() }326        await fixture.initialize()327        #expect(await fixture.run("add", "glass-button").exitCode == 0)328        try fixture.write("spglass.lock.json", "{ not json")329        let outcome = await fixture.run("add", "glass-card")330        #expect(outcome.exitCode == ExitCode.invalidData.rawValue)331        #expect(fixture.read("spglass.lock.json") == "{ not json" && !fixture.exists("Sources/App/GlassKit/Containers"))332        try fixture.write("spglass.lock.json", #"{"schemaVersion":1,"registry":"x","themes":[],"items":[{"id":"a","version":"1.0.0","kind":"primitive","requested":true,"dependencies":[],"digest":"","files":[{"path":"../../outside.txt","sha256":"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855","bytes":0}]}]}"#)333        try "keep".write(to: fixture.root.appendingPathComponent("outside.txt"), atomically: true, encoding: .utf8)334        #expect(await fixture.run("remove", "a", "--force").exitCode == ExitCode.invalidData.rawValue, "a hostile lock file cannot make remove delete outside the project")335        #expect(FileManager.default.fileExists(atPath: fixture.root.appendingPathComponent("outside.txt").path))336        try fixture.write("spglass.json", #"{"schemaVersion":1,"registry":"x","sourcesPath":"/etc","themesPath":"t"}"#)337        #expect(await fixture.run("verify").exitCode == ExitCode.invalidData.rawValue)338    }339340    @Test func downloadedContentIsNeverExecuted() async throws {341        let fixture = try Fixture(); defer { fixture.cleanUp() }342        let marker = fixture.root.appendingPathComponent("executed")343        try fixture.publish(version: "1.1.0", extra: [Fixture.item("glass-script", files: ["Scripts/postinstall.sh": "#!/bin/sh\ntouch '\(marker.path)'\n"])])344        await fixture.initialize()345        #expect(await fixture.run("add", "glass-script").exitCode == 0)346        #expect(!FileManager.default.fileExists(atPath: marker.path))347        let attributes = try FileManager.default.attributesOfItem(atPath: fixture.project.appendingPathComponent("Sources/App/GlassKit/Scripts/postinstall.sh").path)348        #expect(((attributes[.posixPermissions] as? Int) ?? 0o777) & 0o111 == 0, "installed files are not executable")349    }350}351
Files main
Menu

Theme