diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index acb630d..e38029d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,13 +16,13 @@ on: jobs: docs: - runs-on: ubuntu-latest + runs-on: ubuntu-26.04 steps: - uses: actions/checkout@v7 - - uses: pnpm/action-setup@v4 - - uses: actions/setup-node@v4 + - uses: pnpm/action-setup@v6.1.0 + - uses: actions/setup-node@v7 with: - node-version: '22' + node-version: '24' cache: pnpm - run: pnpm install --frozen-lockfile - run: pnpm docs:build @@ -30,12 +30,13 @@ jobs: DOCS_BASE: /LocalShare server: - runs-on: ubuntu-latest + runs-on: ubuntu-26.04 steps: - uses: actions/checkout@v7 - uses: actions/setup-go@v7 with: go-version: '1.23' + cache-dependency-path: server/go.mod - name: 测试 LocalShare Server working-directory: server run: | @@ -49,6 +50,7 @@ jobs: - uses: actions/setup-go@v7 with: go-version: '1.23' + cache-dependency-path: server/go.mod - name: 编译 debug(首次会拉取 Swifter / Sparkle) run: swift build diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 6c20ef7..38f856e 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -17,11 +17,11 @@ concurrency: jobs: build: - runs-on: ubuntu-latest + runs-on: ubuntu-26.04 steps: - uses: actions/checkout@v7 - - uses: pnpm/action-setup@v6 + - uses: pnpm/action-setup@v6.1.0 - uses: actions/setup-node@v7 with: @@ -50,7 +50,7 @@ jobs: name: github-pages url: ${{ steps.deployment.outputs.page_url }} needs: build - runs-on: ubuntu-latest + runs-on: ubuntu-26.04 steps: - name: Deploy to GitHub Pages id: deployment diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8060378..510774f 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -39,6 +39,7 @@ jobs: if: ${{ hashFiles('server/go.mod') != '' }} with: go-version-file: server/go.mod + cache-dependency-path: server/go.mod - name: 编译 LocalShare Server(Linux amd64 / arm64) if: ${{ hashFiles('server/go.mod') != '' }} diff --git a/Sources/LocalShare/FileServer.swift b/Sources/LocalShare/FileServer.swift index 6c6b49d..f44b30c 100644 --- a/Sources/LocalShare/FileServer.swift +++ b/Sources/LocalShare/FileServer.swift @@ -327,7 +327,7 @@ final class FileServer { // MARK: - 请求处理 - private func handle(_ req: HttpRequest) -> HttpResponse { + func handle(_ req: HttpRequest, afterAuthentication: () -> Void = {}) -> HttpResponse { // Tailscale 开关是网络边界,必须先于访问码和 token 鉴权;即使拿着有效链接,关闭后也立即拒绝。 guard Self.allowsClient(address: req.address, tailscaleAccessEnabled: tailscaleAccessEnabled) else { return htmlResponse(403, "Forbidden", Self.forbiddenPage( @@ -381,6 +381,8 @@ final class FileServer { // 鉴权通过的每个请求都刷新该 IP 的活跃时间(含心跳与下载中的请求)。 touchPresence(clientAddress, lookupName: !remoteMode) + // Allow tests to rotate the share at the authenticated request boundary. + afterAuthentication() // 已经有有效 Cookie 却打开 /ls/join 时直接回当前分享入口,不再重复要求输入短码。 if req.method == "GET", req.path == "/ls/join" { diff --git a/Tests/LocalShareTests/RemoteSharingTests.swift b/Tests/LocalShareTests/RemoteSharingTests.swift index e648d4a..ef6f48b 100644 --- a/Tests/LocalShareTests/RemoteSharingTests.swift +++ b/Tests/LocalShareTests/RemoteSharingTests.swift @@ -117,7 +117,8 @@ final class RemoteSharingTests: XCTestCase { XCTAssertEqual(String(data: frame.dropFirst(4).dropFirst(5), encoding: .utf8), "hello") } - @MainActor func testRemotePairStatusUsesUserDefaultsMarker() { + // Keep MainActor-owned objects inside XCTest's async task context during teardown. + @MainActor func testRemotePairStatusUsesUserDefaultsMarker() async { let key = "remotePairedServerAddresses" let previous = UserDefaults.standard.object(forKey: key) defer { diff --git a/Tests/LocalShareTests/ShareRotationTests.swift b/Tests/LocalShareTests/ShareRotationTests.swift index 35433fe..a1d7787 100644 --- a/Tests/LocalShareTests/ShareRotationTests.swift +++ b/Tests/LocalShareTests/ShareRotationTests.swift @@ -1,10 +1,9 @@ import XCTest -import Darwin import Swifter @testable import LocalShare final class ShareRotationTests: XCTestCase { - func testInFlightRequestsStayWithinAuthenticatedShare() async throws { + func testInFlightRequestsStayWithinAuthenticatedShare() throws { let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) defer { try? FileManager.default.removeItem(at: root) } @@ -17,64 +16,63 @@ final class ShareRotationTests: XCTestCase { for upload in [false, true] { let server = FileServer(share: upload ? .directory(oldRoot) : .file(oldFile), token: "old-token") server.uploadEnabled = upload - let port = try server.start(preferredPorts: [in_port_t.random(in: 30000...50000)]) - defer { server.stop() } - let fd = Darwin.socket(AF_INET, SOCK_STREAM, 0) - XCTAssertGreaterThanOrEqual(fd, 0) - var noSignal: Int32 = 1 - _ = setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &noSignal, socklen_t(MemoryLayout.size)) - var timeout = timeval(tv_sec: 5, tv_usec: 0) - _ = setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, socklen_t(MemoryLayout.size)) - var address = sockaddr_in() - address.sin_len = UInt8(MemoryLayout.size) - address.sin_family = sa_family_t(AF_INET) - address.sin_port = port.bigEndian - _ = "127.0.0.1".withCString { inet_pton(AF_INET, $0, &address.sin_addr) } - let connected = withUnsafePointer(to: &address) { - $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { Darwin.connect(fd, $0, socklen_t(MemoryLayout.size)) } - } - XCTAssertEqual(connected, 0) - let socket = Swifter.Socket(socketFileDescriptor: fd) - defer { socket.close() } - // Presence is recorded after auth, before this long path is decoded and routed. - // Single-file reads ignore the filename; repeated encoded slashes upload at the folder root. - let path = "/" + String(repeating: upload ? "%2f" : "%61", count: 500_000) - let body = upload ? "--rotation\r\nContent-Disposition: form-data; name=\"file\"; filename=\"upload.txt\"\r\nContent-Type: text/plain\r\n\r\nupload\r\n--rotation--\r\n" : "" - let headers = upload ? "Content-Type: multipart/form-data; boundary=rotation\r\nContent-Length: \(body.utf8.count)\r\n" : "" - try socket.writeUTF8("\(upload ? "POST" : "GET") \(path)?t=old-token HTTP/1.1\r\nHost: localhost\r\n\(headers)\r\n\(body)") - // The intentionally large request line must finish parsing before the rotation. - let deadline = Date().addingTimeInterval(15) - while server.activeViewers() == 0 && Date() < deadline { - try await Task.sleep(nanoseconds: 100_000) + let request = HttpRequest() + request.method = upload ? "POST" : "GET" + request.path = upload ? "/" : "/old.txt" + request.queryParams = [("t", "old-token")] + request.address = "127.0.0.1" + if upload { + request.headers["content-type"] = "multipart/form-data; boundary=rotation" + request.body = Array("--rotation\r\nContent-Disposition: form-data; name=\"file\"; filename=\"upload.txt\"\r\nContent-Type: text/plain\r\n\r\nupload\r\n--rotation--\r\n".utf8) } - guard server.activeViewers() == 1 else { - XCTFail("request did not reach authenticated routing") - return + var rotated = false + // Rotate after authentication and before content routing, independent of socket timing. + let response = server.handle(request) { + XCTAssertEqual(server.activeViewers(), 1) + server.token = "new-token" + server.share = upload ? .directory(newRoot) : .file(newFile) + rotated = true } - server.token = "new-token" - server.share = upload ? .directory(newRoot) : .file(newFile) - let status = try socket.readLine() - XCTAssertTrue(status.contains("200")) - while !(try socket.readLine()).isEmpty {} + XCTAssertTrue(rotated) + XCTAssertEqual(response.statusCode, 200) + XCTAssertTrue(response.headers()["Set-Cookie"]?.contains("old-token") == true) if upload { XCTAssertEqual(try String(contentsOf: oldRoot.appendingPathComponent("upload.txt")), "upload") XCTAssertFalse(FileManager.default.fileExists(atPath: newRoot.appendingPathComponent("upload.txt").path)) } else { - XCTAssertEqual(String(decoding: try socket.read(length: 3), as: UTF8.self), "old") + XCTAssertEqual(try responseText(response), "old") } - let base = "http://127.0.0.1:\(port)" - let configuration = URLSessionConfiguration.ephemeral - configuration.httpCookieStorage = nil - let session = URLSession(configuration: configuration) - defer { session.invalidateAndCancel() } - let (_, rejected) = try await session.data(from: URL(string: base + "/?t=old-token")!) - XCTAssertEqual((rejected as? HTTPURLResponse)?.statusCode, 403) - let (newContent, accepted) = try await session.data(from: URL(string: base + "/new.txt?t=new-token")!) - XCTAssertEqual((accepted as? HTTPURLResponse)?.statusCode, 200) - XCTAssertEqual(String(decoding: newContent, as: UTF8.self), "new") + request.method = "GET" + request.path = "/new.txt" + request.body = [] + request.headers = [:] + XCTAssertEqual(server.handle(request).statusCode, 403) + request.queryParams = [("t", "new-token")] + let accepted = server.handle(request) + XCTAssertEqual(accepted.statusCode, 200) + XCTAssertEqual(try responseText(accepted), "new") } } + private func responseText(_ response: HttpResponse) throws -> String { + guard case .raw(_, _, _, let write) = response else { + XCTFail("expected a raw file response") + return "" + } + let writer = BodyWriter() + try write?(writer) + return String(decoding: writer.data, as: UTF8.self) + } + + private final class BodyWriter: HttpResponseBodyWriter { + var data = Data() + func write(_ file: String.File) throws { XCTFail("unexpected file writer") } + func write(_ bytes: [UInt8]) throws { data.append(contentsOf: bytes) } + func write(_ bytes: ArraySlice) throws { data.append(contentsOf: bytes) } + func write(_ bytes: NSData) throws { data.append(bytes as Data) } + func write(_ bytes: Data) throws { data.append(bytes) } + } + func testTextBreadcrumbReturnsToMountedShareRoot() { let crumbs = DirectoryListing.breadcrumb(requestPath: "/文本", rootName: "Folder", navigationPath: "/ls/text") XCTAssertTrue(crumbs.contains("href=\"../\""))