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
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ a lighthouse is loaded.

- No external dependencies — `Package.swift` stays dependency-free
- Atomic writes (`options: .atomic`) for all state persistence
- User input sanitized at `SynapseCore.init` boundary (strips `/`, `\`, `:`, `.` from folder names)
- Explicit user input validated at the throwing `SynapseCore.init(folderName:user:baseOverride:)` boundary; safe names are preserved exactly. Separators/control characters are rejected, and ambiguous legacy aliases require an explicit owner decision. The built-in default initializer remains nonthrowing.
- Errors → stderr (`StandardErrorStream`); stdout is machine-readable output only
- Tests use unique UUID folder names for isolation — never break this pattern, never share state between test cases
- All bedrock output types must be `Sendable` — they cross actor isolation boundaries
Expand Down
1 change: 1 addition & 0 deletions Sources/SynapseCore/Circuit/SynapticCircuit.swift
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,7 @@ public actor SynapticCircuit {
}
}
}
guard !next.isEmpty else { break }
frontier = next
depth += 1
}
Expand Down
34 changes: 18 additions & 16 deletions Sources/SynapseCore/SynapseCore.swift
Original file line number Diff line number Diff line change
Expand Up @@ -312,36 +312,38 @@ public class SynapseCore {

/// - Parameters:
/// - folderName: top-level app-support folder name.
/// - user: per-user namespace (sanitized for path traversal).
/// - user: explicit per-user namespace (validated without rewriting).
/// - baseOverride: dependency-injection seam for the storage root that
/// normally resolves to `~/Library/Application Support`. Injecting a
/// temp (or deliberately read-only) directory lets tests exercise real
/// disk-I/O failure paths — e.g. verifying `saveWeights` returns
/// `false` when the destination is unwritable (ADR-005). `nil` keeps
/// the production location; no behaviour change for normal callers.
public init(folderName: String = "ContextSynapse", user: String = "default", baseOverride: URL? = nil) {
// Validate and sanitize user input to prevent directory traversal
// Remove path separators and dots to prevent traversal attacks
let sanitizedUser = user
.components(separatedBy: CharacterSet(charactersIn: "/\\:."))
.joined()
// The built-in default namespace remains source-compatible for GUI callers.
public convenience init(folderName: String = "ContextSynapse", baseOverride: URL? = nil) {
self.init(folderName: folderName, storageUser: "default", baseOverride: baseOverride)
}

// Ensure the sanitized user is not empty and is alphanumeric with limited special chars
guard !sanitizedUser.isEmpty,
sanitizedUser.rangeOfCharacter(from: CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-_"))) != nil else {
fatalError("Invalid user identifier: must contain alphanumeric characters")
}
/// Explicit identifiers are validated, never rewritten. Failures happen
/// before any directory creation, profile update, or default-state seeding.
public convenience init(folderName: String = "ContextSynapse", user: String, baseOverride: URL? = nil) throws {
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
let root = baseOverride ?? FileManager.default.homeDirectoryForCurrentUser
.appendingPathComponent("Library").appendingPathComponent("Application Support")
try UserStorage.validate(user, usersDir: root.appendingPathComponent(folderName).appendingPathComponent("users"))
self.init(folderName: folderName, storageUser: user, baseOverride: baseOverride)
}

private init(folderName: String, storageUser: String, baseOverride: URL?) {
let home = fm.homeDirectoryForCurrentUser
let storageRoot = baseOverride
?? home.appendingPathComponent("Library").appendingPathComponent("Application Support")
let baseDir = storageRoot.appendingPathComponent(folderName)
self.appSupport = baseDir
self.usersDir = baseDir.appendingPathComponent("users")
self.currentUser = sanitizedUser
self.currentUser = storageUser

// Create user-specific directories
let userDir = usersDir.appendingPathComponent(sanitizedUser)
let userDir = usersDir.appendingPathComponent(storageUser)
self.configURL = userDir.appendingPathComponent("config.json")
self.regionsURL = userDir.appendingPathComponent("regions.json")
self.logDir = userDir.appendingPathComponent("logs")
Expand Down Expand Up @@ -827,7 +829,7 @@ public class SynapseCore {
}

/// Switch to a different user (requires reinitializing SynapseCore)
public static func switchUser(to user: String, folderName: String = "ContextSynapse") -> SynapseCore {
return SynapseCore(folderName: folderName, user: user)
public static func switchUser(to user: String, folderName: String = "ContextSynapse") throws -> SynapseCore {
return try SynapseCore(folderName: folderName, user: user)
}
}
67 changes: 67 additions & 0 deletions Sources/SynapseCore/UserStorage.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import Foundation

/// Path safety without lossy identity normalization. Existing space-named
/// directories remain in place; ambiguous historical aliases need an explicit
/// choice by the owner, not an automatic migration that could claim another user.
enum UserStorage {
enum ValidationError: LocalizedError {
case invalidIdentifier
case ambiguousLegacy(String)
case conflictingOwner

var errorDescription: String? {
switch self {
case .invalidIdentifier:
return "Use a single name containing a letter or digit, without path separators, colon, or control characters (at most 200 UTF-8 bytes)."
case .ambiguousLegacy(let key):
return "Existing state uses the legacy name '\(key)'. Select that stored name explicitly or back up and rename its directory; ownership cannot be inferred safely."
case .conflictingOwner:
return "This directory belongs to a different identifier. Use its exact stored name."
}
}
}

static func validate(_ user: String, usersDir: URL) throws {
let forbidden = CharacterSet.controlCharacters.union(CharacterSet(charactersIn: "/\\:"))
guard !user.isEmpty, user.utf8.count <= 200,
user.rangeOfCharacter(from: forbidden) == nil,
user.rangeOfCharacter(from: .alphanumerics) != nil else {
throw ValidationError.invalidIdentifier
}
let fm = FileManager.default
let directory = usersDir.appendingPathComponent(user)
if fm.fileExists(atPath: directory.path) {
// Refuse case/normalization aliases on case-insensitive volumes even
// if the old directory has no profile. Never overwrite its identity.
let names = try fm.contentsOfDirectory(atPath: usersDir.path)
guard names.contains(user) else { throw ValidationError.conflictingOwner }
let profileURL = directory.appendingPathComponent("profile.json")
if fm.fileExists(atPath: profileURL.path) {
let profile = try JSONDecoder().decode(UserProfile.self, from: Data(contentsOf: profileURL))
guard profile.id == user else { throw ValidationError.conflictingOwner }
}
} else {
// Preserve exact existing owners (including Default/DEFAULT), but
// reserve new case variants of the built-in namespace.
guard user.lowercased() != "default" || user == "default" else {
throw ValidationError.invalidIdentifier
}
let legacy = user.components(separatedBy: CharacterSet(charactersIn: "/\\:.")).joined()
if legacy != user, !legacy.isEmpty,
fm.fileExists(atPath: usersDir.appendingPathComponent(legacy).path) {
// Report the name as stored on disk: on a case-insensitive volume
// `legacy` may match a directory spelled differently, and only the
// stored spelling passes the exact-name check above.
throw ValidationError.ambiguousLegacy(storedName(matching: legacy, in: usersDir) ?? legacy)
}
}
}

/// The directory entry that `name` resolves to on this volume: an exact
/// match first, then a case- or normalization-insensitive one.
static func storedName(matching name: String, in usersDir: URL) -> String? {
guard let names = try? FileManager.default.contentsOfDirectory(atPath: usersDir.path) else { return nil }
if names.contains(name) { return name }
return names.first { $0.compare(name, options: [.caseInsensitive]) == .orderedSame }
}
}
14 changes: 12 additions & 2 deletions Sources/contextsynapse/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,24 @@ if instrumentFlags.contains(where: args.contains) && stateFlags.contains(where:
var selectedUser = "default"
var scanIndex = 1
while scanIndex < args.count {
if args[scanIndex] == "--user", scanIndex + 1 < args.count {
if args[scanIndex] == "--user" {
guard scanIndex + 1 < args.count, !args[scanIndex + 1].hasPrefix("--") else {
fputs("--user requires an identifier\n", stderr)
exit(2)
}
selectedUser = args[scanIndex + 1]
break
}
scanIndex += 1
}

let core = SynapseCore(user: selectedUser)
let core: SynapseCore
do {
core = try SynapseCore(user: selectedUser)
} catch {
fputs("Invalid --user: \(error.localizedDescription)\n", stderr)
exit(2)
}

// MARK: - Instrument verbs (record / export-events / events-summary)
// Terminal commands that append to or read the observation ledger, then exit.
Expand Down
31 changes: 31 additions & 0 deletions Tests/PR40CircuitTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import XCTest
@testable import SynapseCore

final class PR40CircuitTests: XCTestCase {
func testUpdatingEdgeWeightPreservesEdgeIdentity() async throws {
let circuit = SynapticCircuit()
let source = SynapticNode(synapseID: "source")
let target = SynapticNode(synapseID: "target")
let edge = CircuitEdge(source: source.id, target: target.id, weight: 0.2)
await circuit.register(source)
await circuit.register(target)
await circuit.connect(edge)
await circuit.updateEdgeWeight(id: edge.id, weight: 0.8)
await circuit.updateEdgeWeight(id: edge.id, weight: 0.5)
let snapshot = await circuit.snapshot()
XCTAssertEqual(snapshot.edges.count, 1)
XCTAssertEqual(snapshot.edges.first?.id, edge.id)
XCTAssertEqual(snapshot.edges.first?.weight, 0.5)
}

func testFaultInjectionReportsIsolatedNodeAsTooIsolated() async throws {
let circuit = SynapticCircuit()
await circuit.register(SynapticNode(synapseID: "isolated"))
_ = await circuit.forwardPass()
let report = await circuit.injectFault(intoSynapse: "isolated", severity: 1.0)
XCTAssertEqual(report.propagationDepth, 0)
XCTAssertEqual(report.affectedNodeCount, 0)
XCTAssertTrue(report.isTooIsolated)
XCTAssertFalse(report.isHealthy)
}
}
6 changes: 3 additions & 3 deletions Tests/PersistenceFailureTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ final class PersistenceFailureTests: XCTestCase {
let root = try makeReadOnlyRoot()
defer { makeWritableAgain(root) }

let core = SynapseCore(folderName: "CS_\(UUID().uuidString)",
let core = try SynapseCore(folderName: "CS_\(UUID().uuidString)",
user: "u",
baseOverride: root)

Expand All @@ -46,7 +46,7 @@ final class PersistenceFailureTests: XCTestCase {
let root = try makeReadOnlyRoot()
defer { makeWritableAgain(root) }

let core = SynapseCore(folderName: "CS_\(UUID().uuidString)",
let core = try SynapseCore(folderName: "CS_\(UUID().uuidString)",
user: "u",
baseOverride: root)

Expand All @@ -70,7 +70,7 @@ final class PersistenceFailureTests: XCTestCase {
try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: root) }

let core = SynapseCore(folderName: "CS_\(UUID().uuidString)",
let core = try SynapseCore(folderName: "CS_\(UUID().uuidString)",
user: "u",
baseOverride: root)

Expand Down
35 changes: 35 additions & 0 deletions Tests/UserIdentifierCLITests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import XCTest
import Foundation

final class UserIdentifierCLITests: XCTestCase {
func testInvalidUserExitsNormallyWithoutCreatingState() throws {
let repository = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
let executable = repository.appendingPathComponent(".build/debug/contextsynapse")
// Fail rather than skip: build the CLI before running integration tests.
XCTAssertTrue(FileManager.default.isExecutableFile(atPath: executable.path))
for arguments in [["--user", "🔥"], ["--user", "***"], ["--user", "../Ada"], ["--user", ""], ["--user"], ["--user", "--export"]] {
let home = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)
try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true)
defer { try? FileManager.default.removeItem(at: home) }
let process = Process()
process.executableURL = executable
process.arguments = arguments
process.currentDirectoryURL = repository
var environment = ProcessInfo.processInfo.environment
environment["HOME"] = home.path
environment["CFFIXED_USER_HOME"] = home.path
process.environment = environment
let errorPipe = Pipe()
process.standardError = errorPipe
process.standardOutput = FileHandle.nullDevice
process.standardInput = FileHandle.nullDevice
try process.run()
process.waitUntilExit()
let error = String(decoding: errorPipe.fileHandleForReading.readDataToEndOfFile(), as: UTF8.self)
XCTAssertEqual(process.terminationReason, .exit, arguments.description)
XCTAssertEqual(process.terminationStatus, 2, arguments.description)
XCTAssertTrue(error.contains("--user"), error)
XCTAssertFalse(FileManager.default.fileExists(atPath: home.appendingPathComponent("Library/Application Support/ContextSynapse").path))
}
}
}
Loading
Loading