Repository Public License
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX OS Automation9// File : Packages/ORIXSecurity/Tests/ORIXSecurityTests/AuditLogTests.swift10// Description : Integration tests of the hash-chained audit log on real11// files: chain verification, tamper detection, reopening,12// redaction, two writers.13// Module : ORIXSecurityTests14// Repository : https://git.spboucher.ai/orix-automation15// Created : 2026-11-2116// Last Modified : 2026-11-2117//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author : Simon-Pierre Boucher23// Position : Professor of Finance24// Institution : Université du Québec en Outaouais (UQO)25// Department : Département des sciences administratives26// Organization : SP Boucher27//28// Website : https://spboucher.ai29// Git : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General : info@spboucher.ai36// Professional : contact@spboucher.ai37// Direct : simon@spboucher.ai38// Research : research@spboucher.ai39// Development : dev@spboucher.ai40// Support : support@spboucher.ai41// Security/Admin : admin@spboucher.ai42// Notifications : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification : Public69// Distribution : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License : Proprietary, all rights reserved (see license file)83// License File : LICENSE84// Maintainer : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import Foundation92import ORIXCore93import ORIXTestingSupport94import Testing95@testable import ORIXSecurity9697@Suite("AuditLog (integration, real files)")98struct AuditLogTests {99 private func entry(_ n: Int, kind: AuditEntry.Kind = .toolExecuted) -> AuditEntry {100 AuditEntry(id: "entry-\(n)", kind: kind, runID: "run-1", toolID: "filesystem.write", tier: .reversibleWrite,101 detail: "Wrote file number \(n)", data: ["n": .int(n), "path": .string("/tmp/file-\(n).txt")])102 }103104 private func lines(_ url: URL) throws -> [String] {105 try String(contentsOf: url, encoding: .utf8).split(separator: "\n").map(String.init)106 }107108 @Test func chainVerifiesAndEntriesRoundTrip() async throws {109 let tmp = try TempDirectory(); defer { tmp.remove() }110 let log = try AuditLog(url: tmp.file("audit/audit.jsonl"))111 #expect(await log.verify() == .ok(entries: 0))112 for i in 1...25 { await log.record(entry(i)) }113 #expect(await log.verify() == .ok(entries: 25))114 #expect(await log.writeFailures == 0)115 let all = await log.entries(limit: 100)116 #expect(all.map(\.id) == (1...25).map { "entry-\($0)" })117 #expect(all[4].data == ["n": 5, "path": "/tmp/file-5.txt"])118 #expect(all[4].tier == .reversibleWrite)119 #expect(await log.entries(limit: 3).map(\.id) == ["entry-23", "entry-24", "entry-25"])120 #expect(await log.entryCount() == 25)121122 // Every line is standalone JSON with the documented fields, and the first links to the genesis hash.123 let text = try lines(tmp.file("audit/audit.jsonl"))124 #expect(text.count == 25)125 let first = try JSONValue.parse(text[0])126 #expect(first["prev"]?.stringValue == AuditLog.genesisHash)127 #expect(first["hash"]?.stringValue?.count == 64)128 #expect(first["entry"]?["id"]?.stringValue == "entry-1")129 let second = try JSONValue.parse(text[1])130 #expect(second["prev"] == first["hash"])131 let mode = try FileManager.default.attributesOfItem(atPath: tmp.file("audit/audit.jsonl").path)[.posixPermissions] as? Int132 #expect(mode == 0o600)133 }134135 @Test func editingAMiddleLineIsDetected() async throws {136 let tmp = try TempDirectory(); defer { tmp.remove() }137 let url = tmp.file("audit.jsonl")138 let log = try AuditLog(url: url)139 for i in 1...10 { await log.record(entry(i)) }140 var text = try lines(url)141 #expect(text[4].contains("Wrote file number 5"))142 text[4] = text[4].replacingOccurrences(of: "Wrote file number 5", with: "Wrote file number 6")143 try (text.joined(separator: "\n") + "\n").write(to: url, atomically: false, encoding: .utf8)144 let result = await log.verify()145 #expect(!result.isValid)146 #expect(result.firstBrokenLine == 5)147 #expect(result.verifiedEntries == 4)148 #expect(result.reason?.contains("edited") == true)149 // A freshly opened log reaches the same verdict.150 #expect(try await AuditLog(url: url).verify().firstBrokenLine == 5)151 }152153 @Test func deletingAMiddleLineIsDetected() async throws {154 let tmp = try TempDirectory(); defer { tmp.remove() }155 let url = tmp.file("audit.jsonl")156 let log = try AuditLog(url: url)157 for i in 1...10 { await log.record(entry(i)) }158 var text = try lines(url)159 text.remove(at: 3)160 try (text.joined(separator: "\n") + "\n").write(to: url, atomically: false, encoding: .utf8)161 let result = try await AuditLog(url: url).verify()162 #expect(result.firstBrokenLine == 4)163 #expect(result.reason?.contains("removed") == true)164 }165166 @Test func swappedAndForgedLinesAreDetected() async throws {167 let tmp = try TempDirectory(); defer { tmp.remove() }168 let url = tmp.file("audit.jsonl")169 let log = try AuditLog(url: url)170 for i in 1...6 { await log.record(entry(i)) }171 let original = try lines(url)172 var swapped = original173 swapped.swapAt(1, 2)174 try (swapped.joined(separator: "\n") + "\n").write(to: url, atomically: false, encoding: .utf8)175 #expect(try await AuditLog(url: url).verify().firstBrokenLine == 2)176 var garbage = original177 garbage.insert("{\"not\":\"an audit line\"}", at: 2)178 try (garbage.joined(separator: "\n") + "\n").write(to: url, atomically: false, encoding: .utf8)179 #expect(try await AuditLog(url: url).verify().firstBrokenLine == 3)180 }181182 @Test func reopeningContinuesTheChain() async throws {183 let tmp = try TempDirectory(); defer { tmp.remove() }184 let url = tmp.file("audit.jsonl")185 do {186 let log = try AuditLog(url: url)187 for i in 1...4 { await log.record(entry(i)) }188 }189 let reopened = try AuditLog(url: url)190 for i in 5...8 { await reopened.record(entry(i)) }191 #expect(await reopened.verify() == .ok(entries: 8))192 let text = try lines(url)193 #expect(try JSONValue.parse(text[4])["prev"] == JSONValue.parse(text[3])["hash"])194 #expect(await reopened.entries(limit: 10).count == 8)195 }196197 @Test func twoWritersShareOneChain() async throws {198 let tmp = try TempDirectory(); defer { tmp.remove() }199 let url = tmp.file("audit.jsonl")200 let a = try AuditLog(url: url)201 let b = try AuditLog(url: url)202 await withTaskGroup(of: Void.self) { group in203 for i in 1...40 {204 group.addTask { await (i % 2 == 0 ? a : b).record(self.entry(i)) }205 }206 }207 #expect(await a.verify() == .ok(entries: 40))208 #expect(Set(await b.entries(limit: 100).map(\.id)).count == 40)209 }210211 @Test func detailsAreRedactedBeforeWriting() async throws {212 let tmp = try TempDirectory(); defer { tmp.remove() }213 let url = tmp.file("audit.jsonl")214 let secret = "orix-test-literal-\(UUID().uuidString)"215 Redactor.shared.register(secret: secret)216 defer { Redactor.shared.unregister(secret: secret) }217 let log = try AuditLog(url: url)218 await log.record(AuditEntry(kind: .secretUsed, detail: "Used \(secret) and sk-ant-REDACTME0123456789abcdefghij",219 data: ["header": .string("Bearer abcdefghijklmnopqrstuvwxyz012345"), "password": "hunter2hunter2", "note": .string(secret)]))220 let raw = try String(contentsOf: url, encoding: .utf8)221 #expect(!raw.contains(secret))222 #expect(!raw.contains("REDACTME"))223 #expect(!raw.contains("abcdefghijklmnopqrstuvwxyz012345"))224 #expect(!raw.contains("hunter2"))225 #expect(raw.contains(Redactor.placeholder))226 #expect(await log.verify().isValid)227 }228229 @Test func tornLastLineIsReportedAndDoesNotCorruptLaterEntries() async throws {230 let tmp = try TempDirectory(); defer { tmp.remove() }231 let url = tmp.file("audit.jsonl")232 do {233 let log = try AuditLog(url: url)234 for i in 1...3 { await log.record(entry(i)) }235 }236 // Simulate a crash in the middle of a write: a partial line with no newline.237 let handle = try FileHandle(forWritingTo: url)238 try handle.seekToEnd()239 try handle.write(contentsOf: Data("{\"hash\":\"abc".utf8))240 try handle.close()241 let log = try AuditLog(url: url)242 await log.record(entry(4))243 let result = await log.verify()244 #expect(result.firstBrokenLine == 4)245 #expect(await log.entries(limit: 10).map(\.id) == ["entry-1", "entry-2", "entry-3", "entry-4"])246 }247}248