From 0a3fadf4c7ade4a6932115efefa78a6b9d28545b Mon Sep 17 00:00:00 2001 From: Youngmin Yoo Date: Fri, 9 Oct 2026 09:48:50 +0900 Subject: [PATCH] fix: discover Tailscale apps and recover stale executable paths --- .../TailscaleMacInstallation.swift | 32 +----- .../ConfiguredRenewalRunner.swift | 13 ++- .../TailscaleExecutableLocator.swift | 45 ++++++++- ...nfiguredRenewalRunnerExecutableTests.swift | 99 +++++++++++++++++++ .../TailscaleExecutableLocatorTests.swift | 37 ++++++- 5 files changed, 189 insertions(+), 37 deletions(-) create mode 100644 SwiftTests/SideRefreshCoreTests/ConfiguredRenewalRunnerExecutableTests.swift diff --git a/Sources/SideRefreshApp/TailscaleMacInstallation.swift b/Sources/SideRefreshApp/TailscaleMacInstallation.swift index 55fedd3..ebd47c7 100644 --- a/Sources/SideRefreshApp/TailscaleMacInstallation.swift +++ b/Sources/SideRefreshApp/TailscaleMacInstallation.swift @@ -7,24 +7,15 @@ enum TailscaleMacInstallation { string: "https://tailscale.com/download/mac" )! - private static let bundleIdentifiers = [ - "io.tailscale.ipn.macsys", - "io.tailscale.ipn.macos", - ] - static var applicationURLs: [URL] { - bundleIdentifiers.flatMap { - NSWorkspace.shared.urlsForApplications( - withBundleIdentifier: $0 - ) - } + TailscaleExecutableLocator.installedApplicationURLs } static var isApplicationInstalled: Bool { !applicationURLs.isEmpty } - static func executableCandidates( + static func availableExecutableURLs( preferredPath: String? ) -> [URL] { let preferred = preferredPath.flatMap { path -> URL? in @@ -36,21 +27,8 @@ enum TailscaleMacInstallation { } return URL(fileURLWithPath: trimmed) } - let candidates = [preferred].compactMap { $0 } - + TailscaleExecutableLocator.standardCandidateURLs - var seenPaths = Set() - return candidates.filter { - seenPaths.insert($0.standardizedFileURL.path).inserted - } - } - - static func availableExecutableURLs( - preferredPath: String? - ) -> [URL] { - TailscaleExecutableLocator( - candidateURLs: executableCandidates( - preferredPath: preferredPath - ) - ).availableExecutableURLs() + return TailscaleExecutableLocator().availableExecutableURLs( + preferredExecutableURL: preferred + ) } } diff --git a/Sources/SideRefreshCore/ConfiguredRenewalRunner.swift b/Sources/SideRefreshCore/ConfiguredRenewalRunner.swift index 2b8efc9..47faf73 100644 --- a/Sources/SideRefreshCore/ConfiguredRenewalRunner.swift +++ b/Sources/SideRefreshCore/ConfiguredRenewalRunner.swift @@ -1,19 +1,22 @@ import Foundation public struct ConfiguredRenewalRunner: Sendable { + private let executableLocator: TailscaleExecutableLocator? private let readTailnetStatus: @Sendable (URL) throws -> TailnetSnapshot public init() { - readTailnetStatus = { + self.init { try TailscaleStatusReader().read(executableURL: $0) } } init( + executableLocator: TailscaleExecutableLocator? = nil, readTailnetStatus: @escaping @Sendable (URL) throws -> TailnetSnapshot ) { + self.executableLocator = executableLocator self.readTailnetStatus = readTailnetStatus } @@ -97,9 +100,11 @@ public struct ConfiguredRenewalRunner: Sendable { ) ) do { - let snapshot = try readTailnetStatus( - URL(fileURLWithPath: target.tailscaleExecutable) - ) + let savedExecutableURL = URL(fileURLWithPath: target.tailscaleExecutable) + let executableURL = (executableLocator ?? TailscaleExecutableLocator()) + .firstAvailableExecutableURL(preferredExecutableURL: savedExecutableURL) + ?? savedExecutableURL + let snapshot = try readTailnetStatus(executableURL) _ = try target.resolve(in: snapshot) progress?( .progress( diff --git a/Sources/SideRefreshCore/TailscaleExecutableLocator.swift b/Sources/SideRefreshCore/TailscaleExecutableLocator.swift index 75509a3..6ab2911 100644 --- a/Sources/SideRefreshCore/TailscaleExecutableLocator.swift +++ b/Sources/SideRefreshCore/TailscaleExecutableLocator.swift @@ -1,4 +1,7 @@ import Foundation +#if canImport(AppKit) +import AppKit +#endif /// Locates a Tailscale command that SideRefresh can execute safely. public struct TailscaleExecutableLocator: Sendable { @@ -10,21 +13,49 @@ public struct TailscaleExecutableLocator: Sendable { "/usr/local/bin/tailscale", ].map { URL(fileURLWithPath: $0) } + private static let bundleIdentifiers = [ + "io.tailscale.ipn.macsys", + "io.tailscale.ipn.macos", + ] + + /// Installed Tailscale apps registered with macOS, including custom locations. + public static var installedApplicationURLs: [URL] { + #if canImport(AppKit) + bundleIdentifiers.flatMap { + NSWorkspace.shared.urlsForApplications(withBundleIdentifier: $0) + }.filter { FileManager.default.fileExists(atPath: $0.path) } + #else + [] + #endif + } + private let candidateURLs: [URL] - /// Creates a locator with candidates ordered by preference. + /// Searches installed app bundles before common CLI locations. public init( - candidateURLs: [URL] = Self.standardCandidateURLs + candidateURLs: [URL] = Self.standardCandidateURLs, + applicationURLs: [URL] = Self.installedApplicationURLs ) { - self.candidateURLs = candidateURLs + let applicationExecutables = applicationURLs.compactMap { url -> URL? in + guard let bundle = Bundle(url: url), + let identifier = bundle.bundleIdentifier, + Self.bundleIdentifiers.contains(identifier) + else { + return nil + } + return bundle.executableURL + } + self.candidateURLs = applicationExecutables + candidateURLs } /// Returns executable candidates without duplicate standardized paths. public func availableExecutableURLs( + preferredExecutableURL: URL? = nil, fileManager: FileManager = .default ) -> [URL] { var seenPaths = Set() - return candidateURLs.compactMap { candidate in + let candidates = [preferredExecutableURL].compactMap { $0 } + candidateURLs + return candidates.compactMap { candidate in let url = candidate.standardizedFileURL guard url.isFileURL, url.path.hasPrefix("/"), @@ -39,8 +70,12 @@ public struct TailscaleExecutableLocator: Sendable { /// Returns the first executable candidate, or `nil` when none is usable. public func firstAvailableExecutableURL( + preferredExecutableURL: URL? = nil, fileManager: FileManager = .default ) -> URL? { - availableExecutableURLs(fileManager: fileManager).first + availableExecutableURLs( + preferredExecutableURL: preferredExecutableURL, + fileManager: fileManager + ).first } } diff --git a/SwiftTests/SideRefreshCoreTests/ConfiguredRenewalRunnerExecutableTests.swift b/SwiftTests/SideRefreshCoreTests/ConfiguredRenewalRunnerExecutableTests.swift new file mode 100644 index 0000000..b70edf0 --- /dev/null +++ b/SwiftTests/SideRefreshCoreTests/ConfiguredRenewalRunnerExecutableTests.swift @@ -0,0 +1,99 @@ +import Foundation +import XCTest +@testable import SideRefreshCore + +final class ConfiguredRenewalRunnerExecutableTests: XCTestCase { + func testImmediateAndDueRenewalsRecoverMissingSavedExecutable() throws { + for immediately in [true, false] { + let fixture = try Fixture() + defer { try? FileManager.default.removeItem(at: fixture.directory) } + let runner = fixture.runner(candidates: [fixture.executable]) + + let result = immediately + ? try runner.runImmediately(fixture.configuration()) + : try runner.runIfDue(fixture.configuration()) + + XCTAssertTrue(result.commandWasExecuted) + XCTAssertTrue(result.succeeded) + } + } + + func testExecutableSavedPathIsPreferredOverFallback() throws { + let fixture = try Fixture() + defer { try? FileManager.default.removeItem(at: fixture.directory) } + let fallback = fixture.directory.appendingPathComponent("wrong-tailscale") + try Data("#!/bin/sh\nexit 42\n".utf8).write(to: fallback) + try FileManager.default.setAttributes( + [.posixPermissions: 0o700], ofItemAtPath: fallback.path + ) + + let result = try fixture.runner(candidates: [fallback]).runImmediately( + fixture.configuration(savedExecutable: fixture.executable) + ) + + XCTAssertTrue(result.succeeded) + } + + func testMissingTailscaleStopsRenewalWithSavedPathError() throws { + let fixture = try Fixture() + defer { try? FileManager.default.removeItem(at: fixture.directory) } + let configuration = fixture.configuration() + + XCTAssertThrowsError( + try fixture.runner(candidates: []).runImmediately(configuration) + ) { error in + guard case let .invalidExecutable(path) = + error as? TailscaleStatusReaderError else { + return XCTFail("Expected missing executable error, got \(error)") + } + XCTAssertEqual(path, configuration.tailnetTarget?.tailscaleExecutable) + } + XCTAssertTrue(try RenewalEngine( + stateFileURL: configuration.stateFileURL + ).status(for: configuration.command).isDue) + } + + private struct Fixture { + let directory: URL + let executable: URL + + init() throws { + directory = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory( + at: directory, withIntermediateDirectories: true + ) + executable = directory.appendingPathComponent("tailscale") + let script = """ + #!/bin/sh + [ "$1" = status ] && [ "$2" = --json ] || exit 41 + [ "$TAILSCALE_BE_CLI" = 1 ] || exit 43 + printf '%s' '{"Peer":{"phone":{"ID":"phone-node","HostName":"phone","DNSName":"phone.example.ts.net.","OS":"iOS","TailscaleIPs":["100.64.0.9"],"Online":true}}}' + """ + try Data(script.utf8).write(to: executable) + try FileManager.default.setAttributes( + [.posixPermissions: 0o700], ofItemAtPath: executable.path + ) + } + + func runner(candidates: [URL]) -> ConfiguredRenewalRunner { + ConfiguredRenewalRunner( + executableLocator: TailscaleExecutableLocator( + candidateURLs: candidates, applicationURLs: [] + ) + ) { try TailscaleStatusReader().read(executableURL: $0) } + } + + func configuration(savedExecutable: URL? = nil) -> AgentConfiguration { + AgentConfiguration( + stateFileURL: directory.appendingPathComponent("state.json"), + tailnetTarget: TailnetTarget( + tailscaleExecutable: (savedExecutable + ?? directory.appendingPathComponent("old/tailscale")).path, + nodeID: "phone-node", dnsName: "phone.example.ts.net." + ), + command: RenewalCommand(executableURL: URL(fileURLWithPath: "/usr/bin/true")) + ) + } + } +} diff --git a/SwiftTests/SideRefreshCoreTests/TailscaleExecutableLocatorTests.swift b/SwiftTests/SideRefreshCoreTests/TailscaleExecutableLocatorTests.swift index 656ad2d..f391018 100644 --- a/SwiftTests/SideRefreshCoreTests/TailscaleExecutableLocatorTests.swift +++ b/SwiftTests/SideRefreshCoreTests/TailscaleExecutableLocatorTests.swift @@ -3,6 +3,40 @@ import SideRefreshCore import XCTest final class TailscaleExecutableLocatorTests: XCTestCase { + func testLocatorFindsBundleExecutableInCustomApplicationLocation() throws { + let directory = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString, isDirectory: true) + defer { try? FileManager.default.removeItem(at: directory) } + + for identifier in ["io.tailscale.ipn.macsys", "io.tailscale.ipn.macos"] { + let app = directory.appendingPathComponent("\(identifier)/VPN Client.app") + let contents = app.appendingPathComponent("Contents") + let executable = contents.appendingPathComponent("MacOS/TailnetCommand") + try FileManager.default.createDirectory( + at: executable.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + let info = try PropertyListSerialization.data( + fromPropertyList: [ + "CFBundleIdentifier": identifier, + "CFBundleExecutable": "TailnetCommand", + "CFBundlePackageType": "APPL", + ], format: .xml, options: 0 + ) + try info.write(to: contents.appendingPathComponent("Info.plist")) + try Data("#!/bin/sh\n".utf8).write(to: executable) + try FileManager.default.setAttributes( + [.posixPermissions: 0o700], ofItemAtPath: executable.path + ) + + let locator = TailscaleExecutableLocator( + candidateURLs: [], applicationURLs: [app] + ) + + XCTAssertEqual(locator.firstAvailableExecutableURL(), executable) + } + } + func testLocatorUsesTheFirstExecutableCandidate() throws { let directory = FileManager.default.temporaryDirectory .appendingPathComponent(UUID().uuidString, isDirectory: true) @@ -22,7 +56,8 @@ final class TailscaleExecutableLocatorTests: XCTestCase { ) let result = TailscaleExecutableLocator( - candidateURLs: [unavailable, executable] + candidateURLs: [unavailable, executable], + applicationURLs: [] ).firstAvailableExecutableURL() XCTAssertEqual(result, executable)