Repository navigation
Preserve user state and validate identifiers without lossy aliases #40
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
7e4e62d
Fix circuit edge updates and isolation reports
mazze93 cbdc015
Reconcile PR 40 with main and validate user storage without lossy ali…
mazze93 74727d3
Merge branch 'main' into codex/fix-bug-in-important-code-section
mazze93 2c25e37
fix(tests): mark throwing SynapseCore init with try in PersistenceFai…
mazze93 1153ae0
fix(storage): preserve existing case-variant default owners
mazze93 875cedc
Merge branch 'main' into codex/fix-bug-in-important-code-section
mazze93 373ed21
Merge remote-tracking branch 'origin/main' into fix40
claude 341d716
Merge main into codex/fix-bug-in-important-code-section
mazze93 358e7a0
fix(storage): report a legacy alias by its stored spelling
mazze93 e371696
Merge main into codex/fix-bug-in-important-code-section
mazze93 b18a16f
test(storage): check the stored-spelling alias outside the error handler
mazze93 45664a8
Merge main into codex/fix-bug-in-important-code-section
mazze93 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)) | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.