From e898da17169e4adeb18bb39b31da91ef4ca0be0a Mon Sep 17 00:00:00 2001 From: tkgstrator <29420801+tkgstrator@users.noreply.github.com> Date: Fri, 23 Oct 2026 08:18:32 +0900 Subject: [PATCH 1/7] feat(plugins): support JSON POST and PUT requests --- .../HTTPPluginOutboundDispatcher.swift | 3 +- .../HTTPPluginOutboundTransport.swift | 27 +- Interceptor/Localizable.xcstrings | 4 +- .../PluginPackageApprovalView.swift | 2 +- .../HTTPPluginOutboundDispatcherTests.swift | 68 +++- .../HTTPPluginOutboundTransportTests.swift | 194 +++++++++++- .../AutomationCore/PluginOutbound.swift | 48 ++- .../Sources/CQuickJS/bridge.c | 60 +++- .../PluginOutboundTests.swift | 159 +++++++++- .../OutboundRuntimeTests.swift | 207 +++++++++++- .../Tests/Fixtures/outbound-conformance.json | 295 ++++++++++++++++++ .../plans/2026-10-23-outbound-json-methods.md | 37 +++ 12 files changed, 1068 insertions(+), 36 deletions(-) create mode 100644 Packages/InterceptorAutomation/Tests/Fixtures/outbound-conformance.json create mode 100644 docs/superpowers/plans/2026-10-23-outbound-json-methods.md diff --git a/Interceptor/Automation/HTTPPluginOutboundDispatcher.swift b/Interceptor/Automation/HTTPPluginOutboundDispatcher.swift index d421c32..310e235 100644 --- a/Interceptor/Automation/HTTPPluginOutboundDispatcher.swift +++ b/Interceptor/Automation/HTTPPluginOutboundDispatcher.swift @@ -53,7 +53,8 @@ final class HTTPPluginOutboundDispatcher: @unchecked Sendable { let outcome: HTTPPluginOutboundOutcome if await authorization() { outcome = await transport.perform( - HTTPPluginOutboundRequest(host: intent.endpoint.host, path: intent.endpoint.path, headers: intent.headers), + HTTPPluginOutboundRequest(host: intent.endpoint.host, path: intent.endpoint.path, headers: intent.headers, + method: intent.endpoint.method, jsonBody: intent.jsonBody), isAuthorized: authorization, ) } else { diff --git a/Interceptor/Automation/HTTPPluginOutboundTransport.swift b/Interceptor/Automation/HTTPPluginOutboundTransport.swift index bd8739b..13ea1b9 100644 --- a/Interceptor/Automation/HTTPPluginOutboundTransport.swift +++ b/Interceptor/Automation/HTTPPluginOutboundTransport.swift @@ -12,9 +12,25 @@ struct HTTPPluginOutboundRequest: Sendable { let host: String let path: String let headers: [String: String] + let method: String + /// Exact strict-JSON UTF-8 bytes captured at send time; only POST/PUT may carry one. + let jsonBody: Data? + + init(host: String, path: String, headers: [String: String], method: String = "GET", jsonBody: Data? = nil) { + self.host = host + self.path = path + self.headers = headers + self.method = method + self.jsonBody = jsonBody + } /// Defense in depth after manifest/result validation. All HTTP framing is owned here. var isValid: Bool { + guard ["GET", "POST", "PUT"].contains(method) else { return false } + if let jsonBody { + guard method != "GET", PluginOutboundPolicy.isAllowedJSONBody(jsonBody), + headers["content-type"].map({ $0 == "application/json" }) ?? true else { return false } + } guard !host.contains("/"), path.hasPrefix("/"), PluginOutboundPolicy.isAllowedURL("https://" + host + path), headers.count <= PluginOutboundPolicy.maxDeclaredHeaders else { return false } @@ -299,11 +315,20 @@ private final class HTTPPluginOutboundExchange: @unchecked Sendable { var headers = HTTPHeaders() headers.add(name: "host", value: self.request.host) headers.add(name: "connection", value: "close") + let method: HTTPMethod = self.request.method == "POST" ? .POST : self.request.method == "PUT" ? .PUT : .GET + let body = self.request.jsonBody + // Single framing builder: host owns Host/Content-Length/Content-Type; GET stays byte-identical. + if method != .GET { + headers.add(name: "content-length", value: String(body?.count ?? 0)) + if body != nil { headers.add(name: "content-type", value: "application/json") } + } for (name, value) in self.request.headers.sorted(by: { $0.key < $1.key }) { + if body != nil, name == "content-type" { continue } headers.add(name: name, value: value) } - let head = HTTPRequestHead(version: .http1_1, method: .GET, uri: self.request.path, headers: headers) + let head = HTTPRequestHead(version: .http1_1, method: method, uri: self.request.path, headers: headers) channel.write(HTTPClientRequestPart.head(head), promise: nil) + if let body { channel.write(HTTPClientRequestPart.body(.byteBuffer(ByteBuffer(bytes: body))), promise: nil) } channel.writeAndFlush(HTTPClientRequestPart.end(nil)).whenFailure { _ in self.finish(.failed) } } } diff --git a/Interceptor/Localizable.xcstrings b/Interceptor/Localizable.xcstrings index 20a6493..50c7bea 100644 --- a/Interceptor/Localizable.xcstrings +++ b/Interceptor/Localizable.xcstrings @@ -4672,13 +4672,13 @@ "en" : { "stringUnit" : { "state" : "translated", - "value" : "Any readable data, including sign-in information, may be sent to these APIs." + "value" : "Any readable data, including sign-in information, and captured headers or JSON data may be sent to these fixed servers. POST and PUT requests may update data on the external server." } }, "ja" : { "stringUnit" : { "state" : "translated", - "value" : "読み取りを許可したデータは、認証情報も含めて外部APIへ送信される可能性があります。" + "value" : "読み取りを許可したデータは、認証情報も含め、取得したヘッダーやJSONデータとして固定の外部サーバーへ送信される可能性があります。POSTやPUTでは外部サーバー上のデータが更新される場合があります。" } } } diff --git a/Interceptor/Views/Automation/PluginPackageApprovalView.swift b/Interceptor/Views/Automation/PluginPackageApprovalView.swift index 62dff24..ef2989f 100644 --- a/Interceptor/Views/Automation/PluginPackageApprovalView.swift +++ b/Interceptor/Views/Automation/PluginPackageApprovalView.swift @@ -59,7 +59,7 @@ struct PluginPackageApprovalView: View { if let endpoint = package.manifest.outbound[binding] { VStack(alignment: .leading, spacing: 4) { Text(verbatim: binding).font(.headline) - Text(verbatim: "GET " + endpoint.url).font(.footnote).textSelection(.enabled) + Text(verbatim: endpoint.method + " " + endpoint.url).font(.footnote).textSelection(.enabled) LabeledContent("AUTO_APPROVAL_OUTBOUND_HEADERS") { if endpoint.headers.isEmpty { Text("AUTO_READ_NONE") diff --git a/InterceptorTests/HTTPPluginOutboundDispatcherTests.swift b/InterceptorTests/HTTPPluginOutboundDispatcherTests.swift index 53012fc..5f7cb0c 100644 --- a/InterceptorTests/HTTPPluginOutboundDispatcherTests.swift +++ b/InterceptorTests/HTTPPluginOutboundDispatcherTests.swift @@ -1,9 +1,37 @@ import AutomationCore +import AutomationRuntime import Foundation @testable import Interceptor import XCTest final class HTTPPluginOutboundDispatcherTests: XCTestCase, @unchecked Sendable { + func testRealRuntimeActionsCrossCoreValidationAndDispatcher() async throws { + for method in ["POST", "PUT"] { + let package = try OutboundAppFixtures.package( + callback: "Interceptor.send('profile',{headers:{authorization:'Bearer token'},json:{name:'日本語'}});", + method: method) + let output = try await JavaScriptExecutor().runV2( + packageJSON: package.bytes, hook: .responseLeave, + eventJSON: Data(#"{"request":{"method":"GET","host":"api.example.com","path":"/credentials"},"response":{"status":200,"headers":{},"body":{}}}"#.utf8), + configJSON: Data("{}".utf8)) + let actions = try XCTUnwrap(try JSONValue(parsing: output).objectValue?["actions"]?.arrayValue) + let intents = try actions.map { try PluginOutboundIntent.validating($0, manifest: package.manifest) } + let done = expectation(description: "runtime \(method) delivered") + let transport = OutboundRecordingTransport() + let dispatcher = HTTPPluginOutboundDispatcher(transport: transport) { _, outcome in + XCTAssertEqual(outcome, .response(200)) + done.fulfill() + } + defer { dispatcher.shutdown() } + XCTAssertEqual(dispatcher.submit(intents, isAuthorized: { true }), 1) + await fulfillment(of: [done], timeout: 2) + let request = try XCTUnwrap(transport.requests.first) + XCTAssertEqual(request.method, method) + XCTAssertEqual(request.jsonBody, Data(#"{"name":"日本語"}"#.utf8)) + XCTAssertEqual(request.headers, ["authorization": "Bearer token"]) + } + } + func testCapacityIsReservedSynchronouslyAndOverloadHasNoWaitingQueue() async throws { let started = expectation(description: "four admitted operations") started.expectedFulfillmentCount = 4 @@ -71,6 +99,31 @@ final class HTTPPluginOutboundDispatcherTests: XCTestCase, @unchecked Sendable { } } + func testTransportReceivesDeclaredMethodAndExactJSONBodyBytes() async throws { + let body = #"{"name":"日本語","n":1.50e+2,"s":"a\"b\\A"}"# + let cases: [(String, String?)] = [("GET", nil), ("POST", nil), ("POST", body), ("PUT", "null"), ("PUT", body)] + for (method, jsonBody) in cases { + let done = expectation(description: "\(method) \(jsonBody ?? "nil")") + let transport = OutboundRecordingTransport() + let dispatcher = HTTPPluginOutboundDispatcher(transport: transport) { _, outcome in + XCTAssertEqual(outcome, .response(200)) + done.fulfill() + } + defer { dispatcher.shutdown() } + let intent = try OutboundAppFixtures.intent(method: method, jsonBody: jsonBody) + XCTAssertEqual(intent.jsonBody, jsonBody.map { Data($0.utf8) }) + XCTAssertEqual(dispatcher.submit([intent], isAuthorized: { true }), 1) + await fulfillment(of: [done], timeout: 2) + let request = try XCTUnwrap(transport.requests.first) + XCTAssertEqual(request.method, method) + XCTAssertEqual(request.jsonBody, jsonBody.map { Data($0.utf8) }, "dispatcher must forward the exact validated bytes") + XCTAssertEqual(request.host, "secondary.example.com") + XCTAssertEqual(request.path, "/profile") + XCTAssertEqual(request.headers, ["authorization": "Bearer token"]) + XCTAssertTrue(request.isValid) + } + } + func testShutdownDrainWaitsForObserverCallbacksAndResumesEveryWaiter() async throws { let entered = expectation(description: "observer running") let callback = OutboundBlockingCallback() @@ -172,7 +225,8 @@ final class OutboundRecordingTransport: HTTPPluginOutboundTransport, @unchecked enum OutboundAppFixtures { static func package(id: UUID = UUID(), callback: String = "", phase: String = "onLeave", - headers: [String] = ["authorization", "cookie"], readHeaders: [String] = []) throws -> PluginPackage { + headers: [String] = ["authorization", "cookie"], readHeaders: [String] = [], + method: String = "GET") throws -> PluginPackage { let file = "hooks/api.example.com/credentials/GET.js" let manifest: JSONValue = .object([ "schemaVersion": .integer(2), "id": .string(id.uuidString), "name": .string("Outbound test"), "version": .string("1.0.0"), @@ -187,7 +241,7 @@ enum OutboundAppFixtures { "write": .object(["requestBody": .bool(false), "responseBody": .bool(phase == "onEnter")]), "endpointBindings": .array([]), "settings": .object([:]), "outbound": .object(["profile": .object([ - "url": .string("https://secondary.example.com/profile"), "method": .string("GET"), + "url": .string("https://secondary.example.com/profile"), "method": .string(method), "headers": .array(headers.map(JSONValue.string)), ])]), ]) @@ -197,10 +251,10 @@ enum OutboundAppFixtures { ]).data()) } - static func intent() throws -> PluginOutboundIntent { - try PluginOutboundIntent.validating(.object([ - "type": .string("http"), "binding": .string("profile"), - "headers": .object(["authorization": .string("Bearer token")]), - ]), manifest: package().manifest) + static func intent(method: String = "GET", jsonBody: String? = nil, + headers: [String: JSONValue] = ["authorization": .string("Bearer token")]) throws -> PluginOutboundIntent { + var action: [String: JSONValue] = ["type": .string("http"), "binding": .string("profile"), "headers": .object(headers)] + if let jsonBody { action["jsonBody"] = .string(jsonBody) } + return try PluginOutboundIntent.validating(.object(action), manifest: package(method: method).manifest) } } diff --git a/InterceptorTests/HTTPPluginOutboundTransportTests.swift b/InterceptorTests/HTTPPluginOutboundTransportTests.swift index 7b80dfb..f87dd24 100644 --- a/InterceptorTests/HTTPPluginOutboundTransportTests.swift +++ b/InterceptorTests/HTTPPluginOutboundTransportTests.swift @@ -289,6 +289,9 @@ private struct OutboundObservedRequest: Sendable { let userAgentValues: [String] let headerNames: Set let bodyBytes: Int + let body: Data + let contentLengthValues: [String] + let contentTypeValues: [String] } private final class OutboundLocked: @unchecked Sendable { @@ -379,6 +382,7 @@ private final class OutboundOriginHandler: ChannelInboundHandler, @unchecked Sen private let requests: OutboundLocked<[OutboundObservedRequest]> private var head: HTTPRequestHead? private var bodyBytes = 0 + private var body = Data() init(requests: OutboundLocked<[OutboundObservedRequest]>) { self.requests = requests } @@ -386,14 +390,18 @@ private final class OutboundOriginHandler: ChannelInboundHandler, @unchecked Sen func channelRead(context: ChannelHandlerContext, data: NIOAny) { switch unwrapInboundIn(data) { case let .head(head): self.head = head - case let .body(body): bodyBytes += body.readableBytes + case let .body(buffer): + bodyBytes += buffer.readableBytes + body.append(contentsOf: buffer.readableBytesView) case .end: guard let head else { context.close(promise: nil); return } requests.change { $0.append(.init(method: head.method.rawValue, path: head.uri, host: head.headers.first(name: "host"), authorization: head.headers.first(name: "authorization"), cookie: head.headers.first(name: "cookie"), userAgentValues: head.headers["user-agent"], headerNames: Set(head.headers.map { $0.name.lowercased() }), - bodyBytes: bodyBytes)) + bodyBytes: bodyBytes, body: body, + contentLengthValues: head.headers["content-length"], + contentTypeValues: head.headers["content-type"])) } guard head.uri != "/silent" else { return } let status: HTTPResponseStatus = if head.uri == "/redirect" { @@ -479,3 +487,185 @@ private enum OutboundTestTLS { -----END PRIVATE KEY----- """ } + +// MARK: - Outbound method and JSON body framing (phase 1, written before the transport supports it) + +extension HTTPPluginOutboundTransportTests { + private func request( + _ method: String = "GET", body: String? = nil, headers: [String: String] = [:], path: String = "/echo", + ) -> HTTPPluginOutboundRequest { + .init(host: "api.example.com", path: path, headers: headers, method: method, jsonBody: body.map { Data($0.utf8) }) + } + + func testLegacyInitializerDefaultsToBodylessGET() async throws { + let legacy = HTTPPluginOutboundRequest(host: "api.example.com", path: "/echo", headers: [:]) + XCTAssertEqual(legacy.method, "GET") + XCTAssertNil(legacy.jsonBody) + try await withOrigin { origin in + let result = await origin.transport.perform( + .init(host: "api.example.com", path: "/echo", headers: [:], method: "GET", jsonBody: nil), isAuthorized: { true }, + ) + XCTAssertEqual(result, .response(200)) + let observed = try XCTUnwrap(origin.requests.value.first) + XCTAssertEqual(observed.method, "GET") + XCTAssertEqual(observed.headerNames, ["host", "connection"], "GET wire framing must not gain content headers") + XCTAssertEqual(observed.bodyBytes, 0) + XCTAssertTrue(observed.contentLengthValues.isEmpty) + XCTAssertTrue(observed.contentTypeValues.isEmpty) + } + } + + func testPOSTAndPUTSendExactJSONBytesWithActualContentLengthAndSingleContentType() async throws { + let bodies = [#"{"name":"日本語","escaped":"a\"b\\c\n","n":1.50e+2}"#, #"[1,2,3]"#, #""x""#] + for method in ["POST", "PUT"] { + for body in bodies { + try await withOrigin { origin in + let result = await origin.transport.perform(request(method, body: body), isAuthorized: { true }) + XCTAssertEqual(result, .response(200), method) + let observed = try XCTUnwrap(origin.requests.value.first) + XCTAssertEqual(observed.method, method) + XCTAssertEqual(observed.body, Data(body.utf8), "body must be the exact caller-serialized bytes") + XCTAssertEqual(observed.contentLengthValues, [String(body.utf8.count)]) + XCTAssertEqual(observed.bodyBytes, body.utf8.count) + XCTAssertEqual(observed.contentTypeValues, ["application/json"]) + XCTAssertEqual(observed.headerNames, ["host", "connection", "content-length", "content-type"]) + XCTAssertEqual(observed.host, "api.example.com") + } + } + } + } + + func testDeclaredExactJSONContentTypeIsNotDuplicatedAndHeaderGrantsStillApply() async throws { + try await withOrigin { origin in + let result = await origin.transport.perform( + request("POST", body: "{}", headers: ["content-type": "application/json", "authorization": "Bearer fixture-token"], path: "/auth/bearer"), + isAuthorized: { true }, + ) + XCTAssertEqual(result, .response(200)) + let observed = try XCTUnwrap(origin.requests.value.first) + XCTAssertEqual(observed.contentTypeValues, ["application/json"]) + XCTAssertEqual(observed.contentLengthValues, ["2"]) + XCTAssertEqual(observed.authorization, "Bearer fixture-token") + XCTAssertEqual(observed.headerNames, ["host", "connection", "content-length", "content-type", "authorization"]) + } + } + + func testAbsentBodyIsEmptyWhileExplicitJSONNullIsFourBytes() async throws { + for method in ["POST", "PUT"] { + try await withOrigin { origin in + let empty = await origin.transport.perform(request(method), isAuthorized: { true }) + let null = await origin.transport.perform(request(method, body: "null"), isAuthorized: { true }) + XCTAssertEqual(empty, .response(200)) + XCTAssertEqual(null, .response(200)) + let seen = origin.requests.value + XCTAssertEqual(seen.count, 2) + XCTAssertEqual(seen[0].method, method) + XCTAssertEqual(seen[0].contentLengthValues, ["0"], "bodyless POST/PUT declares an empty body") + XCTAssertEqual(seen[0].bodyBytes, 0) + XCTAssertTrue(seen[0].contentTypeValues.isEmpty, "no JSON content type is invented without a body") + XCTAssertEqual(seen[1].contentLengthValues, ["4"]) + XCTAssertEqual(seen[1].body, Data("null".utf8)) + XCTAssertEqual(seen[1].contentTypeValues, ["application/json"]) + } + } + } + + func testBodylessPOSTForwardsAScriptDeclaredContentTypeUnderExistingGrants() async throws { + try await withOrigin { origin in + let result = await origin.transport.perform( + request("POST", headers: ["content-type": "text/plain"]), isAuthorized: { true }, + ) + XCTAssertEqual(result, .response(200)) + let observed = try XCTUnwrap(origin.requests.value.first) + XCTAssertEqual(observed.contentTypeValues, ["text/plain"]) + XCTAssertEqual(observed.contentLengthValues, ["0"]) + } + } + + func testRequestValidationRejectsMethodAndBodyViolationsWithoutAnyWriteOrNetwork() async throws { + XCTAssertTrue(request("GET").isValid) + XCTAssertTrue(request("POST").isValid) + XCTAssertTrue(request("PUT", body: "{}").isValid) + let invalid: [(String, HTTPPluginOutboundRequest)] = [ + ("GET with body", request("GET", body: "{}")), + ("GET with null body", request("GET", body: "null")), + ("DELETE", request("DELETE")), + ("PATCH", request("PATCH", body: "{}")), + ("lowercase post", request("post", body: "{}")), + ("lowercase put", request("put")), + ("lowercase get", request("get")), + ("empty method", request("")), + ("padded method", request("POST ")), + ("invalid UTF-8", .init(host: "api.example.com", path: "/", headers: [:], method: "POST", jsonBody: Data([0x22, 0xFF, 0x22]))), + ("empty body", .init(host: "api.example.com", path: "/", headers: [:], method: "POST", jsonBody: Data())), + ("invalid JSON", request("POST", body: "{")), + ("trailing JSON", request("POST", body: "{} {}")), + ("bare word", request("POST", body: "undefined")), + ("NaN", request("POST", body: "NaN")), + ("duplicate keys", request("POST", body: #"{"a":1,"a":2}"#)), + ("uppercase header remains denied", request("POST", body: "{}", headers: ["Content-Type": "application/json"])), + ("mismatched content type", request("POST", body: "{}", headers: ["content-type": "text/plain"])), + ("mismatched case content type", request("PUT", body: "{}", headers: ["Content-Type": "Application/JSON"])), + ("content type with charset", request("POST", body: "{}", headers: ["content-type": "application/json; charset=utf-8"])), + ("content-length remains denied", request("POST", body: "{}", headers: ["content-length": "2"])), + ("transfer-encoding remains denied", request("POST", body: "{}", headers: ["transfer-encoding": "chunked"])), + ] + for (name, candidate) in invalid { + XCTAssertFalse(candidate.isValid, name) + } + try await withOrigin { origin in + for (name, candidate) in invalid { + let result = await origin.transport.perform(candidate, isAuthorized: { true }) + XCTAssertEqual(result, .rejected, name) + } + XCTAssertTrue(origin.requests.value.isEmpty, "rejected requests never reach the wire") + } + } + + func testJSONDepthAndSizeBoundaries() async throws { + func nested(_ depth: Int) -> String { + String(repeating: "[", count: depth) + String(repeating: "]", count: depth) + } + func string(bytes: Int) -> String { #"""# + String(repeating: "x", count: bytes - 2) + #"""# } + XCTAssertTrue(request("POST", body: nested(16)).isValid, "depth 16 is allowed") + XCTAssertFalse(request("POST", body: nested(17)).isValid, "depth 17 is rejected") + XCTAssertTrue(request("POST", body: string(bytes: 8192)).isValid, "exactly 8192 bytes is allowed") + XCTAssertFalse(request("POST", body: string(bytes: 8193)).isValid, "8193 bytes is rejected") + // Multi-byte scalars are counted in UTF-8 bytes, not characters. + let multibyte = #"""# + String(repeating: "日", count: 2730) + #"""# // 2 + 8190 = 8192 bytes + XCTAssertEqual(multibyte.utf8.count, 8192) + XCTAssertTrue(request("PUT", body: multibyte).isValid) + XCTAssertFalse(request("PUT", body: #"""# + String(repeating: "日", count: 2731) + #"""#).isValid, "8195 bytes") + + try await withOrigin { origin in + let maximal = string(bytes: 8192) + let accepted = await origin.transport.perform(request("POST", body: maximal), isAuthorized: { true }) + XCTAssertEqual(accepted, .response(200)) + XCTAssertEqual(origin.requests.value.first?.contentLengthValues, ["8192"]) + XCTAssertEqual(origin.requests.value.first?.body, Data(maximal.utf8)) + let rejected = await origin.transport.perform(request("POST", body: string(bytes: 8193)), isAuthorized: { true }) + XCTAssertEqual(rejected, .rejected) + XCTAssertEqual(origin.requests.value.count, 1) + } + } + + func testRevokedAuthorizationNeverWritesABody() async throws { + try await withOrigin { origin in + let checks = OutboundLocked(0) + let result = await origin.transport.perform(request("POST", body: #"{"secret":"value"}"#), isAuthorized: { + checks.change { $0 += 1; return $0 < 3 } + }) + XCTAssertEqual(result, .rejected) + XCTAssertTrue(origin.requests.value.isEmpty, "no head or body is written before post-TLS authorization succeeds") + } + } + + func testPOSTRedirectIsNotFollowedAndBodyIsNotResent() async throws { + try await withOrigin { origin in + let result = await origin.transport.perform(request("POST", body: "{}", path: "/redirect"), isAuthorized: { true }) + XCTAssertEqual(result, .response(307)) + XCTAssertEqual(origin.requests.value.map(\.path), ["/redirect"]) + XCTAssertEqual(origin.requests.value.map(\.method), ["POST"]) + } + } +} diff --git a/Packages/InterceptorAutomation/Sources/AutomationCore/PluginOutbound.swift b/Packages/InterceptorAutomation/Sources/AutomationCore/PluginOutbound.swift index 69517ab..dc44060 100644 --- a/Packages/InterceptorAutomation/Sources/AutomationCore/PluginOutbound.swift +++ b/Packages/InterceptorAutomation/Sources/AutomationCore/PluginOutbound.swift @@ -10,6 +10,25 @@ public enum PluginOutboundPolicy { public static let maxHeaderNameBytes = 128 public static let maxHeaderValueBytes = 4096 public static let maxTotalHeaderValueBytes = 8192 + /// Compact UTF-8 bytes and container depth of an outbound JSON body (mirrors the bridge serializer caps). + public static let maxJSONBodyBytes = 8192 + public static let maxJSONBodyDepth = 16 + + enum JSONBodyCheck { case valid, overLimit, invalid } + + /// Strict JSON, at most `maxJSONBodyBytes` bytes and `maxJSONBodyDepth` nested containers. The bytes are not re-encoded. + static func checkJSONBody(_ data: Data) -> JSONBodyCheck { + guard data.count <= maxJSONBodyBytes else { return .overLimit } + do { + return try StrictJSON.parse(data).nesting <= maxJSONBodyDepth ? .valid : .overLimit + } catch AutomationError.limitExceeded { + return .overLimit + } catch { + return .invalid + } + } + + public static func isAllowedJSONBody(_ data: Data) -> Bool { checkJSONBody(data) == .valid } private static let denied: Set = [ "host", "content-length", "transfer-encoding", "connection", "upgrade", "te", "trailer", "expect", "keep-alive", "set-cookie", @@ -74,7 +93,7 @@ public enum PluginOutboundPolicy { } } -/// A validated fixed GET destination and the header names a hook may supply for it. +/// A validated fixed GET, POST or PUT destination and the header names a hook may supply for it. public struct PluginOutboundEndpoint: Equatable, Sendable { public let url: String public let method: String @@ -93,7 +112,7 @@ public struct PluginOutboundEndpoint: Equatable, Sendable { let bad = AutomationError.invalidManifest let f = try JSONFields(v, required: ["url", "method", "headers"], error: bad) let url = try f.string("url"), method = try f.string("method"), headers = try f.strings("headers") - guard method == "GET", PluginOutboundPolicy.isAllowedURL(url), + guard ["GET", "POST", "PUT"].contains(method), PluginOutboundPolicy.isAllowedURL(url), headers.count <= PluginOutboundPolicy.maxDeclaredHeaders, Set(headers).count == headers.count, headers.allSatisfy(PluginOutboundPolicy.isAllowedHeaderName) else { throw bad } return PluginOutboundEndpoint(url: url, method: method, headers: headers) @@ -110,17 +129,33 @@ public enum PluginOutboundIntentError: Error, Equatable, Sendable { case malformed, unknownBinding, undeclaredHeader, invalidHeaderValue, limitExceeded } -/// An HTTP action `{type, binding, headers}` checked against a manifest. The URL comes only from the manifest. +/// An HTTP action `{type, binding, headers[, jsonBody]}` checked against a manifest. The URL and method come only +/// from the manifest. `jsonBody` is the exact compact JSON string captured by the bridge, forwarded byte for byte. public struct PluginOutboundIntent: Equatable, Sendable { public let binding: String public let endpoint: PluginOutboundEndpoint public let headers: [String: String] + /// Validated strict-JSON UTF-8 bytes; nil means no JSON body; POST/PUT frame that as zero bytes. + public let jsonBody: Data? public static func validating(_ action: JSONValue, manifest: PluginManifest) throws -> PluginOutboundIntent { - guard case .object(let o) = action, Set(o.keys) == ["type", "binding", "headers"], + guard case .object(let o) = action, o.keys.contains("type"), o.keys.contains("binding"), o.keys.contains("headers"), + Set(o.keys).isSubset(of: ["type", "binding", "headers", "jsonBody"]), case .string("http")? = o["type"], case .string(let binding)? = o["binding"], case .object(let raw)? = o["headers"] else { throw PluginOutboundIntentError.malformed } guard let endpoint = manifest.outbound[binding] else { throw PluginOutboundIntentError.unknownBinding } + var body: Data? + if let b = o["jsonBody"] { + guard endpoint.method != "GET", case .string(let s) = b else { throw PluginOutboundIntentError.malformed } + let data = Data(s.utf8) + guard data.count <= PluginOutboundPolicy.maxJSONBodyBytes else { throw PluginOutboundIntentError.limitExceeded } + switch PluginOutboundPolicy.checkJSONBody(data) { + case .valid: break + case .overLimit: throw PluginOutboundIntentError.limitExceeded + case .invalid: throw PluginOutboundIntentError.malformed + } + body = data + } var headers: [String: String] = [:], total = 0 for (name, value) in raw { guard endpoint.headers.contains(name) else { throw PluginOutboundIntentError.undeclaredHeader } @@ -131,6 +166,9 @@ public struct PluginOutboundIntent: Equatable, Sendable { headers[name] = s } guard total <= PluginOutboundPolicy.maxTotalHeaderValueBytes else { throw PluginOutboundIntentError.limitExceeded } - return PluginOutboundIntent(binding: binding, endpoint: endpoint, headers: headers) + if body != nil, let contentType = headers["content-type"], contentType != "application/json" { + throw PluginOutboundIntentError.invalidHeaderValue + } + return PluginOutboundIntent(binding: binding, endpoint: endpoint, headers: headers, jsonBody: body) } } diff --git a/Packages/InterceptorAutomation/Sources/CQuickJS/bridge.c b/Packages/InterceptorAutomation/Sources/CQuickJS/bridge.c index 17f56ae..1de296e 100644 --- a/Packages/InterceptorAutomation/Sources/CQuickJS/bridge.c +++ b/Packages/InterceptorAutomation/Sources/CQuickJS/bridge.c @@ -81,10 +81,13 @@ typedef struct { #define MAX_INTENTS 16 #define OUT_MAX_VALUE 4096u #define OUT_MAX_TOTAL 8192u +#define OUT_MAX_JSON_BYTES 8192u +#define OUT_MAX_JSON_DEPTH 16 -typedef struct { Str name; Str *headers; size_t nheaders; } OutDecl; +typedef struct { Str name; Str *headers; size_t nheaders; int method; /* 0 GET, 1 POST, 2 PUT */ } OutDecl; // Snapshot copy of one validated Interceptor.send call; never references JS memory. -typedef struct { Str binding; Str *names; Str *values; size_t n; } Intent; +// `json` is the exact compact serialization taken at send time; has_json distinguishes absent from present. +typedef struct { Str binding; Str *names; Str *values; size_t n; int has_json; Str json; } Intent; typedef struct RunState { QJSCancelToken *token; @@ -1065,8 +1068,8 @@ static int str_eq(JSContext *ctx, JSValueConst s, const char *lit) { // Reads a plain object whose own property names are a subset of `keys` (all enumerable data), with // the `required` bit mask present. vals[i] is owned, JS_UNDEFINED when absent. All-or-nothing. -static int read_obj(RunState *st, JSContext *ctx, JSValueConst obj, const char *const *keys, int n, - unsigned required, JSValue *vals) { +static int read_obj_fields(RunState *st, JSContext *ctx, JSValueConst obj, const char *const *keys, int n, + unsigned required, JSValue *vals, unsigned *seen_out) { for (int i = 0; i < n; i++) vals[i] = JS_UNDEFINED; if (JS_GetClassID(obj) != st->cls_object) return 0; JSPropertyEnum *tab; @@ -1092,9 +1095,15 @@ static int read_obj(RunState *st, JSContext *ctx, JSValueConst obj, const char * if (!ok) { for (int i = 0; i < n; i++) { JS_FreeValue(ctx, vals[i]); vals[i] = JS_UNDEFINED; } } + if (ok && seen_out) *seen_out = seen; return ok; } +static int read_obj(RunState *st, JSContext *ctx, JSValueConst obj, const char *const *keys, int n, + unsigned required, JSValue *vals) { + return read_obj_fields(st, ctx, obj, keys, n, required, vals, NULL); +} + static int get_str(JSContext *ctx, JSValueConst v, Str *out, size_t max) { if (!JS_IsString(v)) return 0; size_t n; @@ -1271,8 +1280,11 @@ static JSValue js_attach(JSContext *ctx, JSValueConst this_val, int argc, JSValu return JS_ThrowTypeError(ctx, "invalid Interceptor.attach"); } +static int serialize_value(RunState *st, JSContext *ctx, JSValueConst val, int depth, int max_depth, size_t cap, Buf *out); + static void intent_free(Intent *it) { str_free(&it->binding); + str_free(&it->json); strs_free(it->names, it->n); strs_free(it->values, it->n); memset(it, 0, sizeof(*it)); @@ -1285,27 +1297,37 @@ static void intents_free(RunState *st) { st->nintents = 0; } -// Interceptor.send(binding, {headers}): validates immediately and records a snapshot copy. Performs no I/O, +// Interceptor.send(binding, {headers, json?}): validates immediately and records a snapshot copy. Performs no I/O, // returns undefined. Any violation (including a call outside a callback) is a sticky failure. static JSValue js_send(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { - static const char *const ok_keys[] = {"headers"}; + static const char *const ok_keys[] = {"headers", "json"}; (void)this_val; RunState *st = JS_GetContextOpaque(ctx); - JSValue opt[1], hv = JS_UNDEFINED; + JSValue opt[2], hv = JS_UNDEFINED; const OutDecl *decl = NULL; Intent it; JSPropertyEnum *tab = NULL; uint32_t cnt = 0; size_t total = 0; int ok = 0; + unsigned seen = 0; memset(&it, 0, sizeof(it)); - opt[0] = JS_UNDEFINED; + opt[0] = opt[1] = JS_UNDEFINED; if (!st || !st->in_callback || argc != 2 || !st->intents || st->nintents >= st->max_intents) goto done; if (!get_str(ctx, argv[0], &it.binding, 32)) goto done; for (int i = 0; i < st->nout; i++) if (str_cmp(&st->out[i].name, &it.binding) == 0) decl = &st->out[i]; if (!decl) goto done; - if (!read_obj(st, ctx, argv[1], ok_keys, 1, 1u, opt)) goto done; + if (!read_obj_fields(st, ctx, argv[1], ok_keys, 2, 1u, opt, &seen)) goto done; + // Presence is independent of the value: a present `json: undefined` is invalid, not absent. + if (seen & 2u) { + Buf jb; + if (decl->method == 0 || JS_IsUndefined(opt[1])) goto done; + if (!serialize_value(st, ctx, opt[1], 1, OUT_MAX_JSON_DEPTH, OUT_MAX_JSON_BYTES, &jb)) goto done; + it.json.s = (char *)jb.p; + it.json.n = jb.len; + it.has_json = 1; + } hv = opt[0]; if (JS_GetClassID(hv) != st->cls_object) goto done; if (JS_GetOwnPropertyNames(ctx, &tab, &cnt, hv, JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK) < 0) { tab = NULL; goto done; } @@ -1325,6 +1347,8 @@ static JSValue js_send(JSContext *ctx, JSValueConst this_val, int argc, JSValueC if (!(c == '\t' || (c >= 0x20 && c <= 0x7E))) good = 0; } if (total > OUT_MAX_TOTAL) good = 0; + if (good && it.has_json && it.names[i].n == 12 && !memcmp(it.names[i].s, "content-type", 12) && + !(it.values[i].n == 16 && !memcmp(it.values[i].s, "application/json", 16))) good = 0; } JS_FreeValue(ctx, key); JS_FreeValue(ctx, val); @@ -1342,6 +1366,7 @@ static JSValue js_send(JSContext *ctx, JSValueConst this_val, int argc, JSValueC done: if (tab) JS_FreePropertyEnum(ctx, tab, cnt); JS_FreeValue(ctx, opt[0]); + JS_FreeValue(ctx, opt[1]); intent_free(&it); if (ok) return JS_UNDEFINED; if (st) st->attach_failed = 1; @@ -1366,7 +1391,18 @@ static void emit_intent(Buf *b, const Intent *it) { } b_ch(b, '"'); } - b_str(b, "}}"); + b_ch(b, '}'); + if (it->has_json) { + b_str(b, ",\"jsonBody\":\""); + for (size_t k = 0; k < it->json.n; k++) { + unsigned char c = (unsigned char)it->json.s[k]; + if (c == '"' || c == '\\') { b_ch(b, '\\'); b_ch(b, (char)c); } + else if (c < 0x20 || c == 0x7F) { char e[7]; snprintf(e, sizeof(e), "\\u%04x", c); b_str(b, e); } + else b_ch(b, (char)c); + } + b_ch(b, '"'); + } + b_ch(b, '}'); } static int install_interceptor(JSContext *ctx) { @@ -1719,7 +1755,7 @@ static void out_free(OutDecl *d) { memset(d, 0, sizeof(*d)); } -// `v` -> optional strict {binding:{url,method:'GET',headers:[...]}} (<= 4 bindings). Takes copies into st->out. +// `v` -> optional strict {binding:{url,method:GET|POST|PUT,headers:[...]}} (<= 4 bindings). Takes copies into st->out. static int parse_outbound(RunState *st, JSContext *ctx, JSValueConst v) { static const char *const ok_keys[] = {"url", "method", "headers"}; if (JS_GetClassID(v) != st->cls_object) return 0; @@ -1737,7 +1773,7 @@ static int parse_outbound(RunState *st, JSContext *ctx, JSValueConst v) { if (good) { good = read_obj(st, ctx, val, ok_keys, 3, 7u, f); if (good) { - good = str_eq(ctx, f[1], "GET") && get_str(ctx, f[0], &url, 2048) && out_url_ok(&url) && + good = (str_eq(ctx, f[1], "GET") ? (d->method = 0, 1) : str_eq(ctx, f[1], "POST") ? (d->method = 1, 1) : str_eq(ctx, f[1], "PUT") ? (d->method = 2, 1) : 0) && get_str(ctx, f[0], &url, 2048) && out_url_ok(&url) && get_list(st, ctx, f[2], 0, 8, &d->headers, &d->nheaders); for (size_t h = 0; good && h < d->nheaders; h++) good = out_header_ok(&d->headers[h]); for (int k = 0; k < 3; k++) JS_FreeValue(ctx, f[k]); diff --git a/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginOutboundTests.swift b/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginOutboundTests.swift index 6e085bb..0e87d7a 100644 --- a/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginOutboundTests.swift +++ b/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginOutboundTests.swift @@ -52,7 +52,7 @@ final class PluginOutboundTests: XCTestCase { accepts(decl()) accepts(decl(headers: "[]")) rejects(decl(extra: #","body":""#)) - rejects(decl(method: "POST")) + rejects(decl(method: "DELETE")) rejects(decl(method: "get")) rejects(#"{"profile":{"url":"https://api.example.com/","method":"GET"}}"#) rejects(#"{"profile":{"url":"https://api.example.com/","headers":[]}}"#) @@ -190,4 +190,161 @@ final class PluginOutboundTests: XCTestCase { func testOutboundDoesNotChangeEndpointBindings() throws { XCTAssertEqual(try manifest().endpointBindings, ["alert"]) } + + // MARK: POST/PUT methods and optional exact JSON body (PHASE1: RED until implemented) + + private func writeManifest(method: String = "POST") throws -> PluginManifest { + try manifest(decl(headers: #"["authorization","content-type"]"#, method: method)) + } + private func bodyAction(_ body: String?, binding: String = "profile") -> JSONValue { + var extra = "" + if let body { extra = #","jsonBody":\#(try! JSONValue.string(body).jsonString())"# } + return action(binding: binding, headers: "{}", extra: extra) + } + private func intent(_ body: String?, method: String = "POST") throws -> PluginOutboundIntent { + try PluginOutboundIntent.validating(bodyAction(body), manifest: writeManifest(method: method)) + } + private func badIntent(_ body: String?, method: String = "POST", _ e: PluginOutboundIntentError, line: UInt = #line) throws { + let m = try writeManifest(method: method) + XCTAssertThrowsError(try PluginOutboundIntent.validating(bodyAction(body), manifest: m), line: line) { + XCTAssertEqual($0 as? PluginOutboundIntentError, e, line: line) + } + } + + func testPostAndPutDeclarationsAreAcceptedButOtherMethodsAreNot() throws { + accepts(decl(method: "POST")) + accepts(decl(method: "PUT")) + accepts(decl(method: "GET")) + XCTAssertEqual(try writeManifest(method: "PUT").outbound["profile"]?.method, "PUT") + for bad in ["DELETE", "PATCH", "HEAD", "OPTIONS", "post", "put", "Post", "Put", "get", "", " POST", "POST "] { + rejects(decl(method: bad)) + } + } + + func testMethodChangeAltersPackageRevision() throws { + let get = try PluginPackage.validate(package(outbound: decl(method: "GET"))).revision + let post = try PluginPackage.validate(package(outbound: decl(method: "POST"))).revision + let put = try PluginPackage.validate(package(outbound: decl(method: "PUT"))).revision + XCTAssertEqual(Set([get, post, put]).count, 3) + } + + func testLegacyGetIntentHasNoBody() throws { + let i = try PluginOutboundIntent.validating(action(), manifest: manifest()) + XCTAssertNil(i.jsonBody) + } + + func testPostPutWithoutBodyIsValidEmptyBody() throws { + for method in ["POST", "PUT"] { + XCTAssertNil(try intent(nil, method: method).jsonBody) + } + } + + func testJSONBodyIsForwardedAsExactSerializedBytesWithoutReencoding() throws { + // Spellings a parse/re-encode round trip would normalise (number format, escapes, key order, non-ASCII). + let exact = #"{"z":1e+21,"a":[0.1,1.5,4294967296],"s":"a\"b\\c\n\u0001é日本😀"}"# + for method in ["POST", "PUT"] { + let i = try intent(exact, method: method) + XCTAssertEqual(i.jsonBody, Data(exact.utf8)) + XCTAssertEqual(i.endpoint.method, method) + } + XCTAssertEqual(try intent("null").jsonBody, Data("null".utf8)) + XCTAssertEqual(try intent("0").jsonBody, Data("0".utf8)) + XCTAssertEqual(try intent(#""x""#).jsonBody, Data(#""x""#.utf8)) + XCTAssertEqual(try intent("[]").jsonBody, Data("[]".utf8)) + XCTAssertEqual(try intent("{}").jsonBody, Data("{}".utf8)) + } + + func testEmptyStringBodyIsInvalidJSONNotAbsentBody() throws { + try badIntent("", .malformed) + } + + func testGetRejectsAnyJSONBody() throws { + for body in ["null", "{}", #"{"a":1}"#] { try badIntent(body, method: "GET", .malformed) } + } + + func testJSONBodyMustBeStrictJSONString() throws { + for bad in ["{", "{'a':1}", #"{"a":1,}"#, "[1,]", "01", "NaN", "Infinity", "undefined", #"{"a":1}{"b":2}"#, + #"{"a":1,"a":2}"#, "\u{FEFF}{}", #""\ud800""#] { + try badIntent(bad, .malformed) + } + // Non-string jsonBody values. + let m = try writeManifest() + for raw in [#"{"a":1}"#, "null", "1", "[]"] { + let a = action(headers: "{}", extra: #","jsonBody":\#(raw)"#) + XCTAssertThrowsError(try PluginOutboundIntent.validating(a, manifest: m)) { + XCTAssertEqual($0 as? PluginOutboundIntentError, .malformed) + } + } + } + + func testJSONBodyByteCapIsInclusiveAtUTF8Length() throws { + let ascii = #"{"a":""# + String(repeating: "x", count: 8184) + #""}"# + XCTAssertEqual(ascii.utf8.count, 8192) + XCTAssertEqual(try intent(ascii).jsonBody?.count, 8192) + let over = #"{"a":""# + String(repeating: "x", count: 8185) + #""}"# + XCTAssertEqual(over.utf8.count, 8193) + try badIntent(over, .limitExceeded) + // 4092 two-byte characters: 8192 UTF-8 bytes but only 4092 characters. + let wide = #"{"a":""# + String(repeating: "\u{e9}", count: 4092) + #""}"# + XCTAssertEqual(wide.utf8.count, 8192) + XCTAssertEqual(try intent(wide).jsonBody?.count, 8192) + let wider = #"{"a":""# + String(repeating: "\u{e9}", count: 4092) + #"x"}"# + XCTAssertEqual(wider.utf8.count, 8193) + try badIntent(wider, .limitExceeded) + } + + func testJSONBodyDepthCapIs16() throws { + func nested(_ n: Int) -> String { String(repeating: "[", count: n) + String(repeating: "]", count: n) } + XCTAssertEqual(try intent(nested(16)).jsonBody, Data(nested(16).utf8)) + try badIntent(nested(17), .limitExceeded) + let obj16 = String(repeating: #"{"a":"#, count: 16) + "1" + String(repeating: "}", count: 16) + XCTAssertNoThrow(try intent(obj16)) + try badIntent(String(repeating: #"{"a":"#, count: 17) + "1" + String(repeating: "}", count: 17), .limitExceeded) + } + + func testIntentKeysetIsExactWithOptionalJSONBodyOnly() throws { + let m = try writeManifest() + XCTAssertNoThrow(try PluginOutboundIntent.validating(action(headers: "{}"), manifest: m)) + for extra in [#","body":"{}""#, #","json":{}"#, #","method":"POST""#, #","jsonBody":"{}","json":{}"#] { + XCTAssertThrowsError(try PluginOutboundIntent.validating(action(headers: "{}", extra: extra), manifest: m)) { + XCTAssertEqual($0 as? PluginOutboundIntentError, .malformed) + } + } + } + + func testBodyDoesNotChangeHeaderValidation() throws { + let m = try writeManifest() + let a = action(headers: #"{"authorization":"Bearer abc"}"#, extra: #","jsonBody":"{}""#) + let i = try PluginOutboundIntent.validating(a, manifest: m) + XCTAssertEqual(i.headers, ["authorization": "Bearer abc"]) + XCTAssertEqual(i.jsonBody, Data("{}".utf8)) + XCTAssertThrowsError(try PluginOutboundIntent.validating(action(headers: #"{"x-other":"1"}"#, extra: #","jsonBody":"{}""#), manifest: m)) { + XCTAssertEqual($0 as? PluginOutboundIntentError, .undeclaredHeader) + } + } +} + +extension PluginOutboundTests { + func testJSONContentTypeMustAgreeWithNativeFraming() throws { + let m = try manifest(decl(headers: #"["content-type"]"#, method: "POST")) + XCTAssertThrowsError(try PluginOutboundIntent.validating(action(headers: #"{"content-type":"text/plain"}"#, extra: #","jsonBody":"{}""#), manifest: m)) { + XCTAssertEqual($0 as? PluginOutboundIntentError, .invalidHeaderValue) + } + let good = try PluginOutboundIntent.validating(action(headers: #"{"content-type":"application/json"}"#, extra: #","jsonBody":"{}""#), manifest: m) + XCTAssertEqual(good.jsonBody, Data("{}".utf8)) + } +} + +extension PluginOutboundTests { + func testSharedOutboundMethodConformance() throws { + let url = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("Fixtures/outbound-conformance.json") + let root = try JSONValue(parsing: Data(contentsOf: url)) + let rows = try XCTUnwrap(root.objectValue?["cases"]?.arrayValue) + for row in rows { + let fields = try XCTUnwrap(row.objectValue) + let outbound = try XCTUnwrap(fields["outbound"]).jsonString() + guard case .bool(let valid)? = fields["valid"] else { return XCTFail("invalid shared fixture") } + if valid { accepts(outbound) } else { rejects(outbound) } + } + } } diff --git a/Packages/InterceptorAutomation/Tests/AutomationRuntimeTests/OutboundRuntimeTests.swift b/Packages/InterceptorAutomation/Tests/AutomationRuntimeTests/OutboundRuntimeTests.swift index a6d4a1d..94d1f31 100644 --- a/Packages/InterceptorAutomation/Tests/AutomationRuntimeTests/OutboundRuntimeTests.swift +++ b/Packages/InterceptorAutomation/Tests/AutomationRuntimeTests/OutboundRuntimeTests.swift @@ -27,11 +27,11 @@ final class OutboundRuntimeTests: XCTestCase, @unchecked Sendable { return try XCTUnwrap(obj["actions"] as? [[String: Any]]) } - private func expectError(_ expected: JavaScriptExecutionError, _ body: String, top: String = "", manifest: Data? = nil, line: UInt = #line) async { + private func expectError(_ expected: JavaScriptExecutionError, _ body: String, top: String = "", manifest: Data? = nil, context: String = "", line: UInt = #line) async { do { let r = try await run(body, top: top, manifest: manifest) - XCTFail("expected \(expected), got \(r)", line: line) - } catch { XCTAssertEqual(error as? JavaScriptExecutionError, expected, line: line) } + XCTFail("expected \(expected), got \(r) (\(context))", line: line) + } catch { XCTAssertEqual(error as? JavaScriptExecutionError, expected, context, line: line) } } private func webhook(_ n: Int) -> String { "{type:'webhook',endpointId:'\(endpoint)',json:{n:\(n)}}" } @@ -171,7 +171,7 @@ final class OutboundRuntimeTests: XCTestCase, @unchecked Sendable { await accepts(decl(headers: #"["x-api-key","a1","!#$%&'*+-.^_`|~"]"#)) await accepts(decl(headers: #"["a","b","c","d","e","f","g","h"]"#)) await rejects(decl(extra: #","body":""#)) - await rejects(decl(method: "POST")) + await rejects(decl(method: "DELETE")) await rejects(decl(method: "get")) await rejects(#"{"profile":{"url":"https://api.example.com/","method":"GET"}}"#) await rejects(#"{"profile":{"url":"https://api.example.com/","headers":[]}}"#) @@ -216,3 +216,202 @@ final class OutboundRuntimeTests: XCTestCase, @unchecked Sendable { await accepts(decl(url: "https://api.example.com/%41%2f%7E")) } } + +// MARK: POST/PUT + `json` option + +extension OutboundRuntimeTests { + private func writeManifest(_ method: String) -> Data { + manifest(outbound: #"{"profile":{"url":"https://api.example.com/v1/profile","method":"\#(method)","headers":["authorization"]},"get":{"url":"https://api.example.com/v1/get","method":"GET","headers":[]}}"#) + } + + private func body(_ call: String, method: String = "POST", line: UInt = #line) async throws -> String? { + let actions = try await run("\(call);", manifest: writeManifest(method)) + XCTAssertEqual(actions.count, 1, line: line) + return actions[0]["jsonBody"] as? String + } + + func testManifestAcceptsPostAndPutOnly() async { + await accepts(decl(method: "POST")) + await accepts(decl(method: "PUT")) + for bad in ["DELETE", "PATCH", "post", "put", "Post", "HEAD", ""] { await rejects(decl(method: bad)) } + } + + func testGetKeysetIsUnchangedAndWriteWithoutJSONHasNoBodyKey() async throws { + let get = try await run("Interceptor.send('get',{headers:{}});", manifest: writeManifest("POST")) + XCTAssertEqual(Set(get[0].keys), ["type", "binding", "headers"]) + for method in ["POST", "PUT"] { + let a = try await run("Interceptor.send('profile',{headers:{}});", manifest: writeManifest(method)) + XCTAssertEqual(Set(a[0].keys), ["type", "binding", "headers"], "absent json means empty body") + } + } + + func testJSONOptionIsRecordedAsInternalJSONBodyString() async throws { + for method in ["POST", "PUT"] { + let a = try await run("Interceptor.send('profile',{headers:{authorization:'t'},json:{b:1,a:[true,null,'x']}});", manifest: writeManifest(method)) + XCTAssertEqual(Set(a[0].keys), ["type", "binding", "headers", "jsonBody"]) + XCTAssertEqual(a[0]["type"] as? String, "http") + XCTAssertEqual(a[0]["jsonBody"] as? String, #"{"b":1,"a":[true,null,"x"]}"#) + XCTAssertNil(a[0]["json"]) + } + } + + func testExplicitNullAndScalarsAreBodiesNotAbsence() async throws { + let n = try await body("Interceptor.send('profile',{headers:{},json:null})") + XCTAssertEqual(n, "null") + let z = try await body("Interceptor.send('profile',{headers:{},json:0})") + XCTAssertEqual(z, "0") + let s = try await body("Interceptor.send('profile',{headers:{},json:'x'})") + XCTAssertEqual(s, "\"x\"") + let f = try await body("Interceptor.send('profile',{headers:{},json:false})") + XCTAssertEqual(f, "false") + let e = try await body("Interceptor.send('profile',{headers:{},json:[]})", method: "PUT") + XCTAssertEqual(e, "[]") + } + + func testJSONBodyBytesAreExactCSerializationNumbersEscapesAndNonASCII() async throws { + let cases: [(js: String, expected: String)] = [ + ("1.5", "1.5"), ("0.1", "0.1"), ("4294967296", "4294967296"), ("1e21", "1e+21"), + ("123456789012345680000", "1.2345678901234568e+20"), + ("'\\u00e9\\u65e5\\ud83d\\ude00'", "\"\u{e9}\u{65e5}\u{1F600}\""), + ("'a\"b\\\\c\\n\\r\\t\\b\\f\\u0001\\u001f/'", #""a\"b\\c\n\r\t\b\f\u0001\u001f/""#), + ("'\\u2028\\u007f'", "\"\u{2028}\u{7f}\""), + ("{'\\u00e9':1,b:2,a:3}", "{\"\u{e9}\":1,\"b\":2,\"a\":3}"), + ] + for c in cases { + let got = try await body("Interceptor.send('profile',{headers:{},json:\(c.js)})") + XCTAssertEqual(got, c.expected, c.js) + } + } + + func testJSONBodySizeBoundaryIsExactUTF8Bytes() async throws { + // {"a":""} is 8 + n bytes. + let ok = try await body("Interceptor.send('profile',{headers:{},json:{a:'x'.repeat(8184)}})") + XCTAssertEqual(ok?.utf8.count, 8192) + await expectError(.scriptError, "Interceptor.send('profile',{headers:{},json:{a:'x'.repeat(8185)}});", manifest: writeManifest("POST")) + // Two-byte characters: 4092 characters == 8192 bytes; one extra ASCII byte exceeds the cap. + let wide = try await body("Interceptor.send('profile',{headers:{},json:{a:'\\u00e9'.repeat(4092)}})") + XCTAssertEqual(wide?.utf8.count, 8192) + await expectError(.scriptError, "Interceptor.send('profile',{headers:{},json:{a:'\\u00e9'.repeat(4092)+'x'}});", manifest: writeManifest("POST")) + // Escaping counts: 4096 newlines serialise to 8192 bytes of "\n" escapes plus braces and key => over. + await expectError(.scriptError, "Interceptor.send('profile',{headers:{},json:{a:'\\n'.repeat(4096)}});", manifest: writeManifest("POST")) + } + + func testJSONBodyDepthBoundaryIs16() async throws { + let ok = try await body("let v=1; for(let i=0;i<16;i++) v=[v]; Interceptor.send('profile',{headers:{},json:v})") + XCTAssertEqual(ok, String(repeating: "[", count: 16) + "1" + String(repeating: "]", count: 16)) + await expectError(.scriptError, "let v=1; for(let i=0;i<17;i++) v=[v]; Interceptor.send('profile',{headers:{},json:v});", manifest: writeManifest("POST")) + let objs = try await body("let v=1; for(let i=0;i<16;i++) v={a:v}; Interceptor.send('profile',{headers:{},json:v})") + XCTAssertNotNil(objs) + await expectError(.scriptError, "let v=1; for(let i=0;i<17;i++) v={a:v}; Interceptor.send('profile',{headers:{},json:v});", manifest: writeManifest("POST")) + } + + func testGetRejectsJSONOptionIncludingNull() async { + for j in ["null", "{}", "1", "'x'"] { + await expectError(.scriptError, "try { Interceptor.send('get',{headers:{},json:\(j)}); } catch (e) {} return {actions:[]};", manifest: writeManifest("POST")) + await expectError(.scriptError, "Interceptor.send('profile',{headers:{},json:1}); Interceptor.send('get',{headers:{},json:\(j)});", manifest: writeManifest("POST")) + } + await expectError(.scriptError, "Interceptor.send('profile',{headers:{},json:{}});", manifest: manifest()) + } + + func testStickyInvalidJSONValuesDiscardEveryIntent() async { + let invalid = [ + "undefined", "(function(){})", "()=>1", "Symbol('s')", "10n", "NaN", "Infinity", "-Infinity", + "new Date(0)", "new Map()", "new Set()", "new Error('x')", "new Number(1)", "new String('x')", "new Boolean(true)", + "Promise.resolve(1)", "new Proxy({}, {})", "new Proxy([], {})", "/re/", + "{a:undefined}", "{a:()=>1}", "{[Symbol('k')]:1}", "[undefined]", "[1,,2]", "{toJSON(){return 1;}}", + "{get a(){return 1;}}", "{set a(v){}}", "Object.defineProperty({}, 'a', {value:1, enumerable:false})", + "Object.defineProperty([], 'x', {value:1, enumerable:true})", "'\\ud800'", + "(()=>{const o={}; o.self=o; return o;})()", "(()=>{const a=[]; a.push(a); return a;})()", + "(()=>{const o={a:{}}; o.a.b=o; return o;})()", + ] + for j in invalid { + await expectError(.scriptError, "Interceptor.send('profile',{headers:{},json:1}); try { Interceptor.send('profile',{headers:{},json:\(j)}); } catch (e) {} return {actions:[]};", manifest: writeManifest("POST"), context: j) + await expectError(.scriptError, "Interceptor.send('profile',{headers:{},json:\(j)});", manifest: writeManifest("PUT"), context: j) + } + } + + func testPresentUndefinedJSONIsInvalidNotAbsentAndAbsentIsValid() async throws { + await expectError(.scriptError, "Interceptor.send('profile',{headers:{},json:undefined});", manifest: writeManifest("POST")) + let a = try await run("Interceptor.send('profile',{headers:{}});", manifest: writeManifest("POST")) + XCTAssertNil(a[0]["jsonBody"]) + } + + func testJSONGetterAndProxyOptionsAreRejected() async { + for opts in ["{headers:{},get json(){return 1;}}", "new Proxy({headers:{},json:1},{})", + "Object.defineProperty({headers:{}}, 'json', {value:1, enumerable:false})"] { + await expectError(.scriptError, "try { Interceptor.send('profile',\(opts)); } catch (e) {} return {actions:[]};", manifest: writeManifest("POST")) + } + } + + func testRawActionAndOverrideAttemptsRemainInvalid() async { + let m = writeManifest("POST") + await expectError(.invalidResult, "return {actions:[{type:'http',binding:'profile',headers:{},jsonBody:'{}'}]};", manifest: m) + await expectError(.invalidResult, "return {actions:[{type:'http',binding:'profile',headers:{}}]};", manifest: m) + for extra in ["jsonBody:'{}'", "body:{}", "method:'PUT'", "method:'POST'", "url:'https://evil.example/'", "contentType:'text/plain'", "data:{}"] { + await expectError(.scriptError, "try { Interceptor.send('profile',{headers:{},\(extra)}); } catch (e) {} return {actions:[]};", manifest: m) + } + await expectError(.scriptError, "Interceptor.send('profile',{headers:{},json:{},jsonBody:'{}'});", manifest: m) + } + + func testSnapshotIsNotAffectedByLaterMutationOfJSON() async throws { + let a = try await run("const o={a:[1],s:'one'}; Interceptor.send('profile',{headers:{},json:o}); o.a.push(2); o.s='two'; o.z=true; Object.freeze(o);", manifest: writeManifest("POST")) + XCTAssertEqual(a[0]["jsonBody"] as? String, #"{"a":[1],"s":"one"}"#) + } + + func testUserJSONStringifyAndToJSONAreNeverConsulted() async throws { + let src = "JSON.stringify = () => { throw new Error('used'); }; Object.prototype.toJSON = function(){ throw new Error('used'); };" + let a = try await run("Interceptor.send('profile',{headers:{},json:{a:1}});", top: src, manifest: writeManifest("POST")) + XCTAssertEqual(a[0]["jsonBody"] as? String, #"{"a":1}"#) + } + + func testJSONBodyIsEscapedCorrectlyInsideTheActionWireObject() async throws { + let a = try await run("Interceptor.send('profile',{headers:{authorization:'x'},json:{q:'\"\\\\\\n\\u00e9'}});", manifest: writeManifest("PUT")) + XCTAssertEqual(a[0]["jsonBody"] as? String, "{\"q\":\"\\\"\\\\\\n\u{e9}\"}") + XCTAssertEqual(a[0]["headers"] as? [String: String], ["authorization": "x"]) + } + + func testBodiesShareTheCombinedResultAndActionCaps() async throws { + let big = "{a:'x'.repeat(8184)}" + let two = try await run("Interceptor.send('profile',{headers:{},json:\(big)}); Interceptor.send('profile',{headers:{},json:\(big)});", manifest: writeManifest("POST")) + XCTAssertEqual(two.count, 2) + await expectError(.scriptError, "for (let i=0;i<3;i++) Interceptor.send('profile',{headers:{},json:1});", manifest: writeManifest("POST")) + // Two maximal bodies plus a returned webhook share the two-action cap. + await expectError(.invalidResult, "Interceptor.send('profile',{headers:{},json:\(big)}); Interceptor.send('profile',{headers:{},json:\(big)}); return {actions:[\(webhook(1))]};", manifest: writeManifest("POST")) + } + + func testEscapedBodiesShareTheCombinedResultByteCap() async throws { + let body = #"'\\'.repeat(4095)"# + let send = "Interceptor.send('profile',{headers:{},json:\(body)});" + let single = try await run(send, manifest: writeManifest("POST")) + XCTAssertEqual((single[0]["jsonBody"] as? String)?.utf8.count, 8192) + await expectError(.invalidResult, send + send, manifest: writeManifest("POST")) + } +} + +extension OutboundRuntimeTests { + func testJSONContentTypeMismatchIsStickyBeforeTransport() async { + let m = manifest(outbound: #"{"profile":{"url":"https://api.example.com/v1/profile","method":"POST","headers":["content-type"]}}"#) + await expectError(.scriptError, "try { Interceptor.send('profile',{headers:{'content-type':'text/plain'},json:{}}); } catch(e) {}", manifest: m) + } +} + +extension OutboundRuntimeTests { + func testJSONSnapshotContainsOnlyOwnProperties() async throws { + let actions = try await run("const inherited={secret:'not-sent'}; const value=Object.create(inherited); value.visible=true; Interceptor.send('profile',{headers:{},json:value});", manifest: writeManifest("POST")) + XCTAssertEqual(actions[0]["jsonBody"] as? String, #"{"visible":true}"#) + } +} + +extension OutboundRuntimeTests { + func testSharedOutboundMethodConformance() async throws { + let url = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("Fixtures/outbound-conformance.json") + let root = try JSONValue(parsing: Data(contentsOf: url)) + let rows = try XCTUnwrap(root.objectValue?["cases"]?.arrayValue) + for row in rows { + let fields = try XCTUnwrap(row.objectValue) + let outbound = try XCTUnwrap(fields["outbound"]).jsonString() + guard case .bool(let valid)? = fields["valid"] else { return XCTFail("invalid shared fixture") } + if valid { await accepts(outbound) } else { await rejects(outbound) } + } + } +} diff --git a/Packages/InterceptorAutomation/Tests/Fixtures/outbound-conformance.json b/Packages/InterceptorAutomation/Tests/Fixtures/outbound-conformance.json new file mode 100644 index 0000000..509a11d --- /dev/null +++ b/Packages/InterceptorAutomation/Tests/Fixtures/outbound-conformance.json @@ -0,0 +1,295 @@ +{ + "cases": [ + { + "name": "fixed-https-get", + "valid": true, + "outbound": { + "lookup": { + "url": "https://api.example.com/profile", + "method": "GET", + "headers": [ + "authorization", + "cookie" + ] + } + } + }, + { + "name": "ascii-letter-anywhere-in-final-label", + "valid": true, + "outbound": { + "lookup": { + "url": "https://api.example.1a/%E6%97%A5%E6%9C%AC", + "method": "GET", + "headers": [] + } + } + }, + { + "name": "percent-encoded-high-bytes", + "valid": true, + "outbound": { + "lookup": { + "url": "https://example.com/%80%ff", + "method": "GET", + "headers": [] + } + } + }, + { + "name": "rfc-pchar-and-slashes", + "valid": true, + "outbound": { + "lookup": { + "url": "https://example.com/a-._~!$&'()*+,;=:@/b", + "method": "GET", + "headers": [ + "!#$%&'*+-.^_`|~09az" + ] + } + } + }, + { + "name": "empty-outbound", + "valid": true, + "outbound": {} + }, + { + "name": "localhost-suffix", + "valid": false, + "outbound": { + "lookup": { + "url": "https://api.localhost/", + "method": "GET", + "headers": [] + } + } + }, + { + "name": "local-suffix", + "valid": false, + "outbound": { + "lookup": { + "url": "https://api.local/", + "method": "GET", + "headers": [] + } + } + }, + { + "name": "single-label", + "valid": false, + "outbound": { + "lookup": { + "url": "https://api/", + "method": "GET", + "headers": [] + } + } + }, + { + "name": "ip-address", + "valid": false, + "outbound": { + "lookup": { + "url": "https://127.0.0.1/", + "method": "GET", + "headers": [] + } + } + }, + { + "name": "numeric-final-label", + "valid": false, + "outbound": { + "lookup": { + "url": "https://example.123/", + "method": "GET", + "headers": [] + } + } + }, + { + "name": "explicit-default-port", + "valid": false, + "outbound": { + "lookup": { + "url": "https://example.com:443/", + "method": "GET", + "headers": [] + } + } + }, + { + "name": "uppercase-host", + "valid": false, + "outbound": { + "lookup": { + "url": "https://Example.com/", + "method": "GET", + "headers": [] + } + } + }, + { + "name": "query", + "valid": false, + "outbound": { + "lookup": { + "url": "https://example.com/?q=1", + "method": "GET", + "headers": [] + } + } + }, + { + "name": "fragment", + "valid": false, + "outbound": { + "lookup": { + "url": "https://example.com/#x", + "method": "GET", + "headers": [] + } + } + }, + { + "name": "encoded-control", + "valid": false, + "outbound": { + "lookup": { + "url": "https://example.com/%00", + "method": "GET", + "headers": [] + } + } + }, + { + "name": "encoded-del", + "valid": false, + "outbound": { + "lookup": { + "url": "https://example.com/%7f", + "method": "GET", + "headers": [] + } + } + }, + { + "name": "encoded-backslash", + "valid": false, + "outbound": { + "lookup": { + "url": "https://example.com/%5c", + "method": "GET", + "headers": [] + } + } + }, + { + "name": "malformed-escape", + "valid": false, + "outbound": { + "lookup": { + "url": "https://example.com/%G0", + "method": "GET", + "headers": [] + } + } + }, + { + "name": "post-declaration", + "valid": true, + "outbound": { + "lookup": { + "url": "https://api.example.com/profile", + "method": "POST", + "headers": [] + } + } + }, + { + "name": "put-declaration", + "valid": true, + "outbound": { + "lookup": { + "url": "https://api.example.com/profile", + "method": "PUT", + "headers": [] + } + } + }, + { + "name": "delete-unsupported", + "valid": false, + "outbound": { + "lookup": { + "url": "https://api.example.com/profile", + "method": "DELETE", + "headers": [] + } + } + }, + { + "name": "lowercase-post", + "valid": false, + "outbound": { + "lookup": { + "url": "https://api.example.com/profile", + "method": "post", + "headers": [] + } + } + }, + { + "name": "lowercase-put", + "valid": false, + "outbound": { + "lookup": { + "url": "https://api.example.com/profile", + "method": "put", + "headers": [] + } + } + }, + { + "name": "uppercase-header-name", + "valid": false, + "outbound": { + "lookup": { + "url": "https://api.example.com/profile", + "method": "GET", + "headers": [ + "Authorization" + ] + } + } + }, + { + "name": "forbidden-set-cookie", + "valid": false, + "outbound": { + "lookup": { + "url": "https://api.example.com/profile", + "method": "GET", + "headers": [ + "set-cookie" + ] + } + } + }, + { + "name": "forbidden-proxy-header", + "valid": false, + "outbound": { + "lookup": { + "url": "https://api.example.com/profile", + "method": "GET", + "headers": [ + "proxy-authorization" + ] + } + } + } + ] +} diff --git a/docs/superpowers/plans/2026-10-23-outbound-json-methods.md b/docs/superpowers/plans/2026-10-23-outbound-json-methods.md new file mode 100644 index 0000000..435a4b3 --- /dev/null +++ b/docs/superpowers/plans/2026-10-23-outbound-json-methods.md @@ -0,0 +1,37 @@ +# Outbound POST and PUT Implementation Plan + +User authorization: on2026-10-23, explicitly implement POST/PUT support and open PRs. This supersedes the earlier host-read-only limit for this narrow capability, preserving isolation from concurrent package/browser work. + +Goal: a Plugin declares a fixed GET/POST/PUT destination, passes an optional bounded JSON body for POST/PUT, and native transport sends the declared method and correct framing. Preserve legacy GET byte behavior and all destination/authorization/cancellation/redirect policies. + +Execution: separate APP worktree /Users/devonly/Developer/interceptor-outbound-methods/Interceptor at6c46cc9 (base codex/http-hooks); paired read-only Mudmouth65686d2. SDK /Users/devonly/Developer/interceptor-splatnet3-plugin at2c553aa (base codex/http-hooks) contains task-owned SplatNet pure draft logic. No edits to shared package-loading tree. Open stacked PRs against codex/http-hooks in both repositories so concurrent base work is not duplicated. + +## Contract + +- Remain schema2; outbound.{binding}.{url,method,headers} accepts exact uppercaseGET,POST,PUT only. Methods/URLs always come from immutable approved manifest. Old schema1/2 GET behavior unchanged. New packages require a runtime supporting these methods; SDK pin moves only to exact reviewed published APPcommit. +- Interceptor.send(binding,{headers,json?}) remains synchronous and returns void. Recorded action is {type:'http',binding,headers,jsonBody?:string}, where jsonBody is the exact compactJSON serialization captured byC atsendtime. It is an internal validated UTF8bodystring, not a second script option. Caller cannot supply method/URL/framing. This method PR does not introduce a callback/event/workflow/store API. Do not claim POST support alone completes SplatNet acquisition. +- Optional json is permitted only for POST/PUT; absence means empty request body, explicit null meansJSONnull. Present undefined/functions/accessors/symbols/cycles/unsupported values fail sticky and discard all intents. Snapshot body at send time; later JS edits cannot mutate it. +- Strict JSON body <=8192 compactUTF8bytes and depth<=16; retain existing combined result32KiB/actions2/header caps. Use existing safe own-data serializer, not user JSON.stringify/toJSON. C/Swift boundary tests include escaped/nonASCII values and exact8192/8193 bytes. Core exposes PluginOutboundIntent.jsonBody:Data? after validating the exact string bytes withStrictJSON; do not re-encode the parsed JSON. This preserves Cnumber/escape bytecounts at8192 boundary and exactwirebytes; body bytes must not be persisted/logged. +- Header framing owned by native host: content-length is already denied. With json present, reject script content-type other than exactlyapplication/json; accept that exact value if declared and emit exactlyone host-controlledapplication/json header. POST/PUT without json send length0 and may forward a script-declared content-type under existing headergrants; GET rejects any json and retains its previous no-body framing. Native request has explicitinit(host:path:headers:method:jsonBody:) with methodGET/jsonBodynil defaults to preserve oldcallers. +- Native request defense-in-depth validates method/body cap and JSON shape; send a ByteBuffer body beforeend and correct content-length. No response-body collection or automatic retries introduced; current outcome/status behavior unchanged. +- Approval presents actual declared method plus fixed destination and explains JSON body data sharing in existing Section footer. No new screen/flow/layout. UpdateJA/EN copy where existingGET-only wording would mislead. + +## File ownership / tasks + +1. Core/bridge worker owns Packages/InterceptorAutomation/Sources/AutomationCore/PluginOutbound.swift, Sources/CQuickJS/bridge.c, Tests/AutomationCoreTests/PluginOutboundTests.swift, Tests/AutomationRuntimeTests/OutboundRuntimeTests.swift and new APP fixtures/outbound-conformance.json if shared cases are adopted; existing APP tests currently use inline declarations, SDK fixture is fixtures/outbound-conformance.json. Coordinator keeps matching declaration cases synchronized. No Package.swift/APIABI struct changes. Testfirst, legacyparity and snapshot tests. +2. Transport worker owns Interceptor/Automation/HTTPPluginOutboundTransport.swift, HTTPPluginOutboundDispatcher.swift, InterceptorTests/HTTPPluginOutbound{Transport,Dispatcher,Processor}Tests.swift and Interceptor/Views/Automation/PluginPackageApprovalView.swift plus AUTO_APPROVAL_OUTBOUND_FOOTER JA/EN fields in Interceptor/Localizable.xcstrings only. Consume jsonBody:Data? fromTask1. UnitTLSfixture asserts POST/PUT,bodybytes,length0 vsnull, no duplication/contentinjection and unchangedGET; all existing rejection/redirect/revocation/cancellation tests remain. No network to external services. +3. SDK worker owns types/interceptor.d.ts, tools/repository_config.py, tests/test_outbound_metadata.py, test_simulator_outbound.py, test_hook_types.py and one functional plugins/json-request example with fixtures. Compiler existingcallback detection reused. Simulator links unchanged shared Cbridge fromAPPpin, never forkC. Add method/body fixtures and buildgeneratedJS/manifests. SDK upstream pin set bycoordinator after reviewedAPPcommit publiclyfetchable. +4. Codex integration owns tests on nativeMac, immutable source manifests, packagepin, PRs and reviewevidence. Workers have native shared filesystem but their commandenvironment lacksBun/Python/Swift; verify own toolchain and report limits. Codex executes those actual tests. No screenshots planned byworkers. Any later capture must immediately convert to losslessWebP exactRGBA/profile/dimensions+hashes/scale and preserveoriginal only fornamedconsumer. + +## Verification / review + +Independent LocalGPT planreview and Claude feasibility review before implementation. Fresh read-only actualdiffreview after integration; unsafeC/header/body boundaries included. Preserve mandatoryghidentity check/hook before commits/push; no officialsigning/release/deploy. Run focusedSwiftCore/Runtime tests and vendorcheck; nativeTLStransport tests on owned simulator with cleanup. SDK portable/fullrequiredchecks, regeneratedJS/manifests andpackagereferences, no fakeSplatNetmanifest. PRCI exactpushedsource separate fromlocalproof. Record body-sharing approvalvisualgate as unverified if no matchingbaseline evidence; neverclaimUIpassfromunit tests. + +## Plan review resolutions + +- C must store declaration method and inspect ownproperty presence independently of JS_UNDEFINED; preserve oldGET action keyset. Use existing serialize_value(st,ctx,value,1,16,8192,&buf) and escape its snapshot as the internal jsonBody string. Core validates and forwards exactbytes, avoiding Swift/C number-spelling drift. +- Explicit native request initializer preserves old callsites. Body0 framing only forPOST/PUT. Content-type withoutJSON follows existinggrant semantics; withJSON exactapplication/json only, host emits itonce. +- Shared SDK fixture currently labels POSTinvalid; change that case plusPUT/lowercase/DELETE and mirror actualCore/Ctests. Returned rawHTTPactions and send optionmethod/URL overrides remaininvalid. +- ActualGitbase/live refs are verified natively, not reviewerclaims. Currentdate is2026-10-23 in userAsia/Tokyo. Publish APPcommitbefore SDKpin; stackedPRs againstcodex/http-hooks require basePRs first. No merges authorized. + +- IndependentLocalGPT P1presence/framing resolved by explicitIntenthas_json plusownedserializedbytes and single nativeframingbuilder. Core/C/SDKmethod andbodyboundaries receive matchingfixtures; directCoreactionduplicatekeys rejected byStrictJSON. Confirm GET-to-POST/PUT manifestchanges package revision; existing approval remains bound to immutable oldrevision. No reusing oldgrant forchangedpackage. From 03da0f7b182f3c2dc4dd9a885b8c8370722fe720 Mon Sep 17 00:00:00 2001 From: tkgstrator <29420801+tkgstrator@users.noreply.github.com> Date: Fri, 23 Oct 2026 08:34:05 +0900 Subject: [PATCH 2/7] test(plugins): detect partial writes after revocation --- .../HTTPPluginOutboundTransportTests.swift | 35 +++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/InterceptorTests/HTTPPluginOutboundTransportTests.swift b/InterceptorTests/HTTPPluginOutboundTransportTests.swift index f87dd24..3ece803 100644 --- a/InterceptorTests/HTTPPluginOutboundTransportTests.swift +++ b/InterceptorTests/HTTPPluginOutboundTransportTests.swift @@ -313,16 +313,21 @@ private final class OutboundLocked: @unchecked Sendable { private final class OutboundOrigin: @unchecked Sendable { let transport: HTTPPluginDirectTransport let requests: OutboundLocked<[OutboundObservedRequest]> + let decryptedBytes: OutboundLocked + let clientChannels: OutboundLocked<[Channel]> private let channels: OutboundLocked<[Channel]> private let group: MultiThreadedEventLoopGroup private init( transport: HTTPPluginDirectTransport, requests: OutboundLocked<[OutboundObservedRequest]>, + decryptedBytes: OutboundLocked, + clientChannels: OutboundLocked<[Channel]>, channels: OutboundLocked<[Channel]>, group: MultiThreadedEventLoopGroup, ) { self.transport = transport; self.requests = requests; self.channels = channels; self.group = group + self.decryptedBytes = decryptedBytes; self.clientChannels = clientChannels } static func clientContext() throws -> NIOSSLContext { @@ -336,6 +341,8 @@ private final class OutboundOrigin: @unchecked Sendable { let group = MultiThreadedEventLoopGroup(numberOfThreads: 1) let channels = OutboundLocked<[Channel]>([]) let requests = OutboundLocked<[OutboundObservedRequest]>([]) + let decryptedBytes = OutboundLocked(0) + let clientChannels = OutboundLocked<[Channel]>([]) do { let certificates = try NIOSSLCertificate.fromPEMBytes(Array(OutboundTestTLS.certificate.utf8)) let key = try NIOSSLPrivateKey(bytes: Array(OutboundTestTLS.privateKey.utf8), format: .pem) @@ -344,9 +351,11 @@ private final class OutboundOrigin: @unchecked Sendable { let serverTLS = try NIOSSLContext(configuration: configuration) let listener = try await ServerBootstrap(group: group).childChannelInitializer { channel in channels.change { $0.append(channel) } + clientChannels.change { $0.append(channel) } do { let pipeline = channel.pipeline.syncOperations try pipeline.addHandler(NIOSSLServerHandler(context: serverTLS)) + try pipeline.addHandler(OutboundDecryptedByteObserver(bytes: decryptedBytes)) try pipeline.configureHTTPServerPipeline() try pipeline.addHandler(OutboundOriginHandler(requests: requests)) return channel.eventLoop.makeSucceededVoidFuture() @@ -358,7 +367,8 @@ private final class OutboundOrigin: @unchecked Sendable { testingResolver: { _ in try SocketAddress(ipAddress: "127.0.0.1", port: port) }, testingTLSContext: clientContext(), ) - return OutboundOrigin(transport: transport, requests: requests, channels: channels, group: group) + return OutboundOrigin(transport: transport, requests: requests, decryptedBytes: decryptedBytes, + clientChannels: clientChannels, channels: channels, group: group) } catch { for channel in channels.value { try? await channel.close().get() @@ -376,6 +386,19 @@ private final class OutboundOrigin: @unchecked Sendable { } } +/// Observe every decrypted application byte, including incomplete HTTP heads or bodies. +private final class OutboundDecryptedByteObserver: ChannelInboundHandler, @unchecked Sendable { + typealias InboundIn = ByteBuffer + private let bytes: OutboundLocked + + init(bytes: OutboundLocked) { self.bytes = bytes } + + func channelRead(context: ChannelHandlerContext, data: NIOAny) { + bytes.change { $0 += unwrapInboundIn(data).readableBytes } + context.fireChannelRead(data) + } +} + private final class OutboundOriginHandler: ChannelInboundHandler, @unchecked Sendable { typealias InboundIn = HTTPServerRequestPart typealias OutboundOut = HTTPServerResponsePart @@ -527,6 +550,7 @@ extension HTTPPluginOutboundTransportTests { XCTAssertEqual(observed.body, Data(body.utf8), "body must be the exact caller-serialized bytes") XCTAssertEqual(observed.contentLengthValues, [String(body.utf8.count)]) XCTAssertEqual(observed.bodyBytes, body.utf8.count) + XCTAssertGreaterThan(origin.decryptedBytes.value, body.utf8.count, "the pre-decoder probe observes HTTP headers and body") XCTAssertEqual(observed.contentTypeValues, ["application/json"]) XCTAssertEqual(observed.headerNames, ["host", "connection", "content-length", "content-type"]) XCTAssertEqual(observed.host, "api.example.com") @@ -656,7 +680,14 @@ extension HTTPPluginOutboundTransportTests { checks.change { $0 += 1; return $0 < 3 } }) XCTAssertEqual(result, .rejected) - XCTAssertTrue(origin.requests.value.isEmpty, "no head or body is written before post-TLS authorization succeeds") + XCTAssertEqual(checks.value, 3, "authorization must reach the post-TLS check") + let client = try XCTUnwrap(origin.clientChannels.value.first) + XCTAssertEqual(origin.clientChannels.value.count, 1) + let closed = expectation(description: "revoked TLS connection closes") + client.closeFuture.whenComplete { _ in closed.fulfill() } + await fulfillment(of: [closed], timeout: 2) + XCTAssertEqual(origin.decryptedBytes.value, 0, "even partial HTTP headers or body must stay off the wire") + XCTAssertTrue(origin.requests.value.isEmpty) } } From 01bbe4bbaf4af0a6f0850c36fa4a9699bde0715e Mon Sep 17 00:00:00 2001 From: tkgstrator <29420801+tkgstrator@users.noreply.github.com> Date: Fri, 23 Oct 2026 13:31:48 +0900 Subject: [PATCH 3/7] test(plugins): verify outbound approval on iOS and retain UI evidence --- .github/workflows/ios.yml | 71 ++ InterceptorUITests/AutomationUITests.swift | 160 +++++ README.md | 14 + scripts/ci-plugin-repository-fixture.py | 34 +- scripts/export-ui-evidence.py | 607 ++++++++++++++++++ scripts/requirements-visual.txt | 5 + .../tests/test_plugin_repository_fixture.py | 66 +- scripts/tests/test_ui_evidence.py | 532 +++++++++++++++ 8 files changed, 1484 insertions(+), 5 deletions(-) create mode 100644 scripts/export-ui-evidence.py create mode 100644 scripts/requirements-visual.txt create mode 100644 scripts/tests/test_ui_evidence.py diff --git a/.github/workflows/ios.yml b/.github/workflows/ios.yml index 00cba46..80eb570 100644 --- a/.github/workflows/ios.yml +++ b/.github/workflows/ios.yml @@ -89,6 +89,20 @@ jobs: with: bun-version: 1.4.2 + - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 + if: ${{ (needs['ci-change-scope'].result != 'success' || needs['ci-change-scope'].outputs.docs_only != 'true') }} + with: + python-version: '3.13.9' + + - name: Install visual test tools + if: ${{ (needs['ci-change-scope'].result != 'success' || needs['ci-change-scope'].outputs.docs_only != 'true') }} + run: | + # Owned venv: only hash-pinned wheels, no dependency resolution, no system site-packages. + rm -rf "$RUNNER_TEMP/visual-tools" + python -m venv "$RUNNER_TEMP/visual-tools" + "$RUNNER_TEMP/visual-tools/bin/python" -m pip install --require-hashes --only-binary=:all: --no-deps -r scripts/requirements-visual.txt + "$RUNNER_TEMP/visual-tools/bin/python" -c 'import pathlib; p = pathlib.Path("scripts/export-ui-evidence.py"); compile(p.read_text(), str(p), "exec")' + - name: Verify native repository contract if: ${{ (needs['ci-change-scope'].result != 'success' || needs['ci-change-scope'].outputs.docs_only != 'true') }} run: | @@ -153,10 +167,13 @@ jobs: operation: cleanup - name: Build and run unit and UI tests + id: ui_tests if: ${{ (needs['ci-change-scope'].result != 'success' || needs['ci-change-scope'].outputs.docs_only != 'true') }} run: | set -o pipefail python3 -m unittest discover -s scripts/tests -p test_plugin_repository_fixture.py -v + "$RUNNER_TEMP/visual-tools/bin/python" -m unittest discover -s scripts/tests -p test_native_visual_regression.py -v + "$RUNNER_TEMP/visual-tools/bin/python" -m unittest discover -s scripts/tests -p test_ui_evidence.py -v NSUnbufferedIO=YES python3 scripts/ci-simulator-start-worker.py python3 scripts/ci-plugin-repository-fixture.py \ --work-dir "$RUNNER_TEMP/plugin-repository-fixture" -- xcodebuild test \ -project Interceptor.xcodeproj -scheme Interceptor \ @@ -204,6 +221,48 @@ jobs: trap 'exit 143' TERM wait "$build_pid" + - name: Collect UI evidence environment + # Must run before simulator cleanup: the device disappears afterwards. + id: ui_environment + if: ${{ (needs['ci-change-scope'].result != 'success' || needs['ci-change-scope'].outputs.docs_only != 'true') && (always()) }} + env: + TEST_OUTCOME: ${{ steps.ui_tests.outcome }} + run: | + "$RUNNER_TEMP/visual-tools/bin/python" - <<'PY' || echo '{"environment_unavailable": true}' > "$RUNNER_TEMP/ui-evidence-environment.json" + import json, os, subprocess + temp = os.environ["RUNNER_TEMP"] + env = {"test_outcome": os.environ.get("TEST_OUTCOME", "unknown")} + udid = os.environ.get("SIMULATOR_UUID", "") + try: + devices = json.loads(subprocess.run(["xcrun", "simctl", "--set", os.environ["CI_SIMULATOR_DEVICE_SET"], "list", "devices", "--json"], + check=True, capture_output=True, text=True, timeout=60).stdout)["devices"] + for runtime, items in devices.items(): + for item in items: + if item.get("udid") == udid: + env.update(simulator_runtime=runtime, simulator_name=item.get("name", ""), + simulator_state=item.get("state", ""), simulator_device_type=item.get("deviceTypeIdentifier", "")) + except Exception as error: + env["simulator_lookup_error"] = type(error).__name__ + try: + env["xcode"] = subprocess.run(["xcodebuild", "-version"], check=True, capture_output=True, text=True, timeout=60).stdout.replace("\n", " ").strip() + except Exception as error: + env["xcode_error"] = type(error).__name__ + json.dump(env, open(os.path.join(temp, "ui-evidence-environment.json"), "w")) + PY + + - name: Export verified UI evidence + # Immediately after XCTest and before any publishing. A missing or incomplete + # result bundle (build failure, cancellation) yields a failure manifest, never evidence. + id: ui_evidence + if: ${{ (needs['ci-change-scope'].result != 'success' || needs['ci-change-scope'].outputs.docs_only != 'true') && (always()) }} + run: | + rm -rf "$RUNNER_TEMP/ui-evidence" + "$RUNNER_TEMP/visual-tools/bin/python" scripts/export-ui-evidence.py \ + --result-bundle "$RUNNER_TEMP/Interceptor.xcresult" \ + --output "$RUNNER_TEMP/ui-evidence" \ + --source "$GITHUB_SHA" \ + --environment "$RUNNER_TEMP/ui-evidence-environment.json" + - name: Clean up dedicated iPhone simulator if: ${{ (needs['ci-change-scope'].result != 'success' || needs['ci-change-scope'].outputs.docs_only != 'true') && (always()) }} run: | @@ -230,6 +289,18 @@ jobs: if-no-files-found: ignore retention-days: 1 + - name: Save verified UI evidence + # Compact lossless WebP and manifest only; raw diagnostics are never exported here. + # The source originals remain solely in the xcresult. Evidence is valid only with + # manifest.json status "complete"; failure.json means unverified. + if: ${{ (needs['ci-change-scope'].result != 'success' || needs['ci-change-scope'].outputs.docs_only != 'true') && (always()) }} + uses: actions/upload-artifact@v4 + with: + name: ui-evidence + path: ${{ runner.temp }}/ui-evidence/ + if-no-files-found: warn + retention-days: 1 + - name: Docs-only exemption if: ${{ needs['ci-change-scope'].result == 'success' && needs['ci-change-scope'].outputs.docs_only == 'true' }} shell: bash diff --git a/InterceptorUITests/AutomationUITests.swift b/InterceptorUITests/AutomationUITests.swift index 8992726..8c150f2 100644 --- a/InterceptorUITests/AutomationUITests.swift +++ b/InterceptorUITests/AutomationUITests.swift @@ -1294,3 +1294,163 @@ extension AutomationUITests { return String(identifier[identifier.index(identifier.startIndex, offsetBy: Self.searchRowPrefix.count) ..< bar]) } } + +// MARK: - Outbound approval methods and consent + +extension AutomationUITests { + /// Identities and bytes of the derived `outbound/approval.json` served by scripts/ci-plugin-repository-fixture.py + /// (derived from multi-file-hooks.json; `outboundRevision` is the SHA-256 of the exact served package bytes). + private static let outboundID = "3C0B5B0E-6D1F-4E57-9A52-7E1D4B8F2A61" + private static let outboundRevision = "af80907085f19584e78617f982be2e57ec6994e1373541ef2b7fa80b77d5e802" + private static let outboundBindings: [(binding: String, method: String, request: String, headers: String?)] = [ + ("lookup", "GET", "GET https://api.example.com/v1/profile", nil), + ("post", "POST", "POST https://api.example.com/v1/records", "authorization, content-type"), + ("put", "PUT", "PUT https://api.example.com/v1/records/latest", "content-type"), + ] + private static let outboundFooters = [ + "en": "Any readable data, including sign-in information, and captured headers or JSON data may be sent to these fixed servers. POST and PUT requests may update data on the external server.", + "ja": "読み取りを許可したデータは、認証情報も含め、取得したヘッダーやJSONデータとして固定の外部サーバーへ送信される可能性があります。POSTやPUTでは外部サーバー上のデータが更新される場合があります。", + ] + private static let outboundNoHeaders = ["en": "No traffic data", "ja": "通信データなし"] + + @MainActor + func testOutboundApprovalMethodsAndConsentInEnglishAndJapanese() async { + guard let repositoryURL = await requiredRepositoryURL() else { return } + // Same fixed same-origin derivation as the browser catalog; the ownership guard above ran on /repository.json. + let outboundURL = repositoryURL.deletingLastPathComponent().appendingPathComponent("outbound/repository.json") + let device = XCUIDevice.shared + let owned: UIDeviceOrientation = UIDevice.current.userInterfaceIdiom == .pad ? .landscapeLeft : .portrait + let previous = device.orientation + device.orientation = owned + defer { device.orientation = previous.isValidInterfaceOrientation ? previous : .portrait } + for japanese in [false, true] { + let tag = japanese ? "ja" : "en" + let app = launch(japanese: japanese, suite: "Interceptor.UITests.\(UUID().uuidString)") + defer { app.terminate() } + openPlugins(app, japanese: japanese) + addRepository(outboundURL, app: app) + openCategory(app, id: "category:Requests") + openCatalogPackage(Self.outboundID, app: app) + enqueueGet(app) + openQueue(app) + confirmQueue(app) + assertEnabled(false, app: app) + + tapEnabled(app) + let form = scrollContainer(app, "plugins.approval.form") + XCTAssertTrue(form.waitForExistence(timeout: 5)) + for entry in Self.outboundBindings { + let identifier = "plugins.approval.outbound." + entry.binding + let elements = { self.outboundElements(identifier, in: form) } + XCTAssertTrue(revealFully(elements, in: form), "\(entry.binding) must be fully visible") + let texts = outboundTexts(elements()) + XCTAssertTrue(texts.contains(entry.request), "\(entry.binding) shows exactly \(entry.request); saw \(texts)") + XCTAssertTrue(texts.contains(entry.binding)) + for other in ["GET", "POST", "PUT"] where other != entry.method { + XCTAssertFalse(texts.contains { $0.hasPrefix(other + " https://") }, "\(entry.binding) has one method") + } + if let headers = entry.headers { + XCTAssertTrue(texts.contains { $0.contains(headers) }, "\(entry.binding) declares \(headers); saw \(texts)") + XCTAssertFalse(texts.contains { $0.contains(Self.outboundNoHeaders[tag]!) }) + } else { + XCTAssertTrue(texts.contains { $0.contains(Self.outboundNoHeaders[tag]!) }, "\(entry.binding) declares no headers; saw \(texts)") + } + attachScreen("Outbound \(entry.method) \(tag)", japanese: japanese, app: app) + } + let footerText = Self.outboundFooters[tag]! + let footer = form.staticTexts.matching(NSPredicate(format: "label == %@", footerText)).firstMatch + XCTAssertTrue(revealFully({ footer.exists ? [footer] : [] }, in: form), "the complete localized footer must be fully visible") + XCTAssertEqual(footer.label, footerText) + attachScreen("Outbound footer \(tag)", japanese: japanese, app: app) + + let revision = reach(app.textViews["plugins.approval.revision"], in: form, attempts: 30) + XCTAssertEqual(revision.value as? String, Self.outboundRevision, "approval binds the exact served bytes") + + app.buttons.matching(identifier: "plugins.approval.cancel").firstMatch.tap() + XCTAssertTrue(form.waitForNonExistence(timeout: 5)) + assertEnabled(false, app: app) + tapEnabled(app) + XCTAssertTrue(form.waitForExistence(timeout: 5)) + app.buttons.matching(identifier: "plugins.approval.confirm").firstMatch.tap() + XCTAssertTrue(form.waitForNonExistence(timeout: 5)) + assertEnabled(true, app: app) + } + } + + /// The identifier on the binding's VStack may propagate to its leaves, or the VStack may be one element. + @MainActor + func outboundElements(_ identifier: String, in form: XCUIElement) -> [XCUIElement] { + form.descendants(matching: .any).matching(identifier: identifier).allElementsBoundByIndex.filter(\.exists) + } + + /// Every label/value of the elements and their static-text and text-view descendants (selectable text may be a text view). + @MainActor + func outboundTexts(_ elements: [XCUIElement]) -> [String] { + var texts: [String] = [] + for element in elements { + texts += [element.label, element.value as? String ?? ""] + for child in element.staticTexts.allElementsBoundByIndex + element.textViews.allElementsBoundByIndex { + texts += [child.label, child.value as? String ?? ""] + } + } + return texts.filter { !$0.isEmpty } + } + + /// Scrolls the real form until all of the elements are inside the unobscured viewport. + @MainActor + func revealFully(_ elements: () -> [XCUIElement], in form: XCUIElement, attempts: Int = 40) -> Bool { + for _ in 0 ..< attempts { + let visible = viewport(form) + let current = elements() + if !current.isEmpty && current.allSatisfy({ !$0.frame.isEmpty && visible.contains($0.frame) }) { return true } + if let first = current.first, first.frame.midY < visible.minY { + form.swipeDown(velocity: .slow) + } else { + form.swipeUp(velocity: .slow) + } + } + return false + } + + /// One full-screen screenshot plus JSON geometry metadata taken from that same image (no extra capture). + @MainActor + func attachScreen(_ name: String, japanese: Bool, app: XCUIApplication) { + let screenshot = XCUIScreen.main.screenshot() + let image = XCTAttachment(screenshot: screenshot) + image.name = name + image.lifetime = .keepAlways + add(image) + + let screen = UIScreen.main + // UIScreen.bounds belongs to the runner, which may use compatibility sizing. + let appFrame = app.frame + let pixels = screenshot.image.cgImage.map { (width: $0.width, height: $0.height) } ?? (width: 0, height: 0) + let orientation = XCUIDevice.shared.orientation + let metadata: [String: Any] = [ + "schemaVersion": 1, + "kind": "interceptor-ui-screen", + "scale": Double(screen.scale), + "screenPointWidth": Double(appFrame.width), + "screenPointHeight": Double(appFrame.height), + "imagePixelWidth": pixels.width, + "imagePixelHeight": pixels.height, + "osVersion": UIDevice.current.systemVersion, + "deviceModel": ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"] ?? UIDevice.current.model, + "orientation": orientation.isLandscape ? "landscape" : "portrait", + "locale": japanese ? "ja_JP" : "en_US", + ] + XCTAssertGreaterThan(pixels.width, 0, "screenshot must expose a CGImage") + let expected = [Double(appFrame.width * screen.scale), Double(appFrame.height * screen.scale)].sorted() + for (actualEdge, expectedEdge) in zip([Double(pixels.width), Double(pixels.height)].sorted(), expected) { + XCTAssertEqual(actualEdge, expectedEdge, accuracy: 1, "\(name) geometry must match the image") + } + guard let data = try? JSONSerialization.data(withJSONObject: metadata, options: [.sortedKeys]) else { + XCTFail("geometry metadata for \(name) is not serializable") + return + } + let geometry = XCTAttachment(data: data, uniformTypeIdentifier: "public.json") + geometry.name = name + ".geometry" + geometry.lifetime = .keepAlways + add(geometry) + } +} diff --git a/README.md b/README.md index eb765df..56a239b 100644 --- a/README.md +++ b/README.md @@ -108,6 +108,20 @@ fresh iPhone simulator for each run. Test results and logs are uploaded to the `simulator-results` artifact only when the simulator job fails, and are kept for one day. +After the tests, `scripts/export-ui-evidence.py` (run from a hash-pinned Pillow +12.3.0 virtual environment under `RUNNER_TEMP`) exports the XCTest screenshot +attachments from the result bundle and publishes them in the one-day +`ui-evidence` artifact on both success and failure. The artifact holds only +verified lossless WebP files (exact RGBA, ICC profile and dimensions, with +source hashes) and `manifest.json`; no raw diagnostics are included, and the +original PNGs remain only in the `xcresult`. The eight required screenshots +(`Outbound GET/POST/PUT/footer` in `en` and `ja`) must each have a paired +`.geometry` JSON whose display scale is observed from the device, not assumed. +Evidence is valid only when `manifest.json` has `"status": "complete"`; a +`failure.json` (missing or incomplete result bundle, corrupt, unsupported or +out-of-bounds images, build failure or cancellation) means unverified and is +never a pass. + CI requires the repository secret `QUANTUMLEAP_READ_TOKEN`, a GitHub token with read access to `qtmleap/QuantumLeap`. For a dedicated CI credential, prefer a fine-grained token limited to that repository with **Contents: read-only**. diff --git a/scripts/ci-plugin-repository-fixture.py b/scripts/ci-plugin-repository-fixture.py index 1f7df12..221bdb5 100644 --- a/scripts/ci-plugin-repository-fixture.py +++ b/scripts/ci-plugin-repository-fixture.py @@ -33,6 +33,17 @@ REPOSITORY_EXPIRES_AT = '2026-12-30T00:00:00Z' DERIVED_BROWSER_PACKAGE = '/browser/target-hosts.json' DERIVED_BROWSER_REPOSITORY = '/browser/repository.json' +DERIVED_OUTBOUND_PACKAGE = '/outbound/approval.json' +DERIVED_OUTBOUND_REPOSITORY = '/outbound/repository.json' +OUTBOUND_PACKAGE_ID = '3C0B5B0E-6D1F-4E57-9A52-7E1D4B8F2A61' +OUTBOUND_CATALOG_ID = 'A8F2C6D4-19B3-4C7E-8E05-5D2B9C41F7A3' +OUTBOUND_HOST = 'https://api.example.com' +# Deterministic binding order and declarations shown by the approval UI test. +OUTBOUND_BINDINGS = { + 'lookup': {'url': OUTBOUND_HOST + '/v1/profile', 'method': 'GET', 'headers': []}, + 'post': {'url': OUTBOUND_HOST + '/v1/records', 'method': 'POST', 'headers': ['authorization', 'content-type']}, + 'put': {'url': OUTBOUND_HOST + '/v1/records/latest', 'method': 'PUT', 'headers': ['content-type']}, +} def encoded(value): @@ -122,8 +133,21 @@ def repository_files(token, device): derived_payload = payload | {'id': '532AEB4B-8744-44DA-86CB-DC46E3831F23', 'name': 'Browser catalog fixture', 'plugins': [derived_entry]} files[DERIVED_BROWSER_REPOSITORY] = encoded({'schemaVersion': 1, 'payload': base64.b64encode(encoded(derived_payload)).decode()}) - # The readiness nonce binds the exact complete allowlist, including the - # derived catalog, rather than only entries in the original catalog. + # A second explicitly synthetic catalog, derived from multi-file-hooks.json, carries schema-2 + # outbound declarations. The original packages and the browser catalog stay byte-identical. + outbound = json.loads(packages['multi-file-hooks.json'][0]) + outbound['manifest'].update(id=OUTBOUND_PACKAGE_ID, name='Outbound approval example', + author='Outbound fixture author', category='Requests', + summary='Derived fixture for outbound method and consent views.', + outbound=json.loads(json.dumps(OUTBOUND_BINDINGS))) + outbound_raw = encoded(outbound) + files[DERIVED_OUTBOUND_PACKAGE] = outbound_raw + outbound_meta = outbound['manifest'] + outbound_entry = {key: outbound_meta[key] for key in ('id', 'name', 'version', 'author', 'summary', 'category')} | { + 'packagePath': 'approval.json', 'sha256': digest(outbound_raw), 'size': len(outbound_raw)} + outbound_payload = payload | {'id': OUTBOUND_CATALOG_ID, 'name': 'Outbound catalog fixture', 'plugins': [outbound_entry]} + files[DERIVED_OUTBOUND_REPOSITORY] = encoded({'schemaVersion': 1, 'payload': base64.b64encode(encoded(outbound_payload)).decode()}) + # Bind readiness only after every derived catalog and package has been added. package_digest = digest(encoded({path: digest(raw) for path, raw in files.items()})) files['/__interceptor_fixture'] = encoded({'fixture': MARKER, 'version': 1, 'runToken': token, 'device': device, 'packageDigest': package_digest}) @@ -438,10 +462,12 @@ def interrupted(signum, _): server = FixtureServer(files, tls, options.port) record.update({'repositoryURL': server.base_url + '/repository.json', 'runToken': token, 'packageDigest': package_digest, 'publicFiles': {name: digest(raw) for name, raw in files.items()}, - 'derivedPackages': {DERIVED_BROWSER_PACKAGE: 'multi-file-hooks.json'}}) + 'derivedPackages': {DERIVED_BROWSER_PACKAGE: 'multi-file-hooks.json', + DERIVED_OUTBOUND_PACKAGE: 'multi-file-hooks.json'}}) context = check_ready(server, tls, files['/__interceptor_fixture']) if options.self_test: - for path in (DERIVED_BROWSER_REPOSITORY, DERIVED_BROWSER_PACKAGE): + for path in (DERIVED_BROWSER_REPOSITORY, DERIVED_BROWSER_PACKAGE, + DERIVED_OUTBOUND_REPOSITORY, DERIVED_OUTBOUND_PACKAGE): with urllib.request.urlopen(server.base_url + path, context=context, timeout=2) as response: if response.status != 200 or response.read() != files[path]: raise RuntimeError('Derived browser fixture was not served exactly: ' + path) diff --git a/scripts/export-ui-evidence.py b/scripts/export-ui-evidence.py new file mode 100644 index 0000000..c3361a4 --- /dev/null +++ b/scripts/export-ui-evidence.py @@ -0,0 +1,607 @@ +#!/usr/bin/env python3 +"""Export UI screenshots from an xcresult and publish them only as verified lossless WebP. + +Usage: export-ui-evidence.py --result-bundle X.xcresult --output DIR --source SHA [--environment JSON] + +The output directory is created atomically and only after every required image has been +converted and re-verified. On any failure it contains a bounded failure.json and no images. +Exit status: 0 success, 1 evidence failure, 2 usage error. +""" +import argparse, hashlib, json, math, os, re, shutil, stat, struct, subprocess, sys, tempfile, time, zlib + +SCHEMA_VERSION = 1 +PILLOW_VERSION = "12.3.0" +CAPS = { + "manifest_bytes": 4 * 1024 * 1024, + "attachments": 4096, + "images": 64, + "encoded_bytes": 32 * 1024 * 1024, + "image_input_bytes": 128 * 1024 * 1024, + "dimension": 8192, + "pixels": 16 * 1024 * 1024, + "icc_bytes": 1024 * 1024, + "png_chunks": 4096, + "output_bytes": 96 * 1024 * 1024, + "geometry_bytes": 8 * 1024, + "nonimage_file_bytes": 256 * 1024 * 1024, + "nonimage_total_bytes": 1024 * 1024 * 1024, + "hash_chunk": 1024 * 1024, + "environment_bytes": 64 * 1024, + "seconds": 600, + "export_seconds": 300, + "text": 200, +} +REQUIRED_NAMES = [f"Outbound {m} {t}" for t in ("en", "ja") for m in ("GET", "POST", "PUT", "footer")] +GEOMETRY_KIND = "interceptor-ui-screen" +GEOMETRY_FIELDS = ("scale", "screenPointWidth", "screenPointHeight", "imagePixelWidth", "imagePixelHeight", + "osVersion", "deviceModel", "orientation", "locale") +PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n" +SAFE_FILENAME = re.compile(r"^[A-Za-z0-9._ -]{1,200}$") + + +class EvidenceError(Exception): + def __init__(self, code, message): + super().__init__(message) + self.code = code + self.message = message + + +class Deadline: + def __init__(self, seconds): + self.end = time.monotonic() + seconds + + def check(self): + if time.monotonic() > self.end: + raise EvidenceError("time-cap", "evidence export exceeded its time cap") + + def remaining(self): + return max(1.0, self.end - time.monotonic()) + + +def sha256(data): + return hashlib.sha256(data).hexdigest() + + +def clean_text(value, limit=None): + limit = limit or CAPS["text"] + if not isinstance(value, str): + return None + return "".join(c if c.isprintable() else "?" for c in value)[:limit] + + +# ---------------------------------------------------------------- PNG inspection + +def inspect_png(data): + """Validate PNG structure and metadata without decoding pixels. Returns a description dict.""" + if len(data) > CAPS["encoded_bytes"]: + raise EvidenceError("encoded-size", "PNG exceeds the encoded size cap") + if not data.startswith(PNG_SIGNATURE): + raise EvidenceError("not-png", "attachment is not a PNG") + pos, chunks, seen = len(PNG_SIGNATURE), [], {} + ihdr = icc_raw = None + color_chunks = {} + while True: + if len(chunks) >= CAPS["png_chunks"]: + raise EvidenceError("png-chunks", "PNG has too many chunks") + if pos + 12 > len(data): + raise EvidenceError("png-truncated", "PNG is truncated") + length, kind = struct.unpack(">I4s", data[pos:pos + 8]) + end = pos + 8 + length + if length > 0x7FFFFFFF or end + 4 > len(data): + raise EvidenceError("png-truncated", "PNG chunk exceeds the file") + body = data[pos + 8:end] + if struct.unpack(">I", data[end:end + 4])[0] != zlib.crc32(data[pos + 4:end]): + raise EvidenceError("png-crc", "PNG chunk CRC mismatch") + if not chunks and kind != b"IHDR": + raise EvidenceError("png-structure", "PNG does not start with IHDR") + chunks.append(kind) + seen[kind] = seen.get(kind, 0) + 1 + if kind == b"IHDR": + if seen[kind] > 1 or length != 13: + raise EvidenceError("png-structure", "invalid PNG IHDR") + ihdr = struct.unpack(">IIBBBBB", body) + # Bound dimensions before any further interpretation or decode. + if not (0 < ihdr[0] <= CAPS["dimension"] and 0 < ihdr[1] <= CAPS["dimension"]) \ + or ihdr[0] * ihdr[1] > CAPS["pixels"]: + raise EvidenceError("dimension-cap", "PNG dimensions exceed caps") + elif kind == b"iCCP": + icc_raw = body + elif kind in (b"sRGB", b"gAMA", b"cHRM"): + color_chunks[kind] = body + pos = end + 4 + if kind == b"IEND": + break + if pos != len(data): + raise EvidenceError("png-structure", "trailing bytes after PNG IEND") + width, height, depth, color_type, compression, filt, interlace = ihdr + if depth != 8: + raise EvidenceError("unsupported-depth", f"unsupported PNG bit depth {depth}") + if color_type not in (2, 6): + raise EvidenceError("unsupported-color-type", f"unsupported PNG color type {color_type}") + if interlace != 0: + raise EvidenceError("unsupported-interlace", "interlaced PNG is unsupported") + for animated in (b"acTL", b"fcTL", b"fdAT"): + if animated in seen: + raise EvidenceError("unsupported-animation", "animated PNG is unsupported") + for ambiguous in (b"tRNS", b"cICP"): + if ambiguous in seen: + raise EvidenceError("ambiguous-color", f"PNG {ambiguous.decode()} chunk is unsupported") + if any(seen.get(kind, 0) > 1 for kind in (b"iCCP", b"sRGB", b"gAMA", b"cHRM")): + raise EvidenceError("ambiguous-color", "duplicate PNG color profile chunk") + if b"sRGB" in color_chunks and color_chunks[b"sRGB"] not in (b"\x00", b"\x01", b"\x02", b"\x03"): + raise EvidenceError("ambiguous-color", "invalid sRGB rendering intent") + expected_srgb = {b"gAMA": struct.pack(">I", 45455), + b"cHRM": struct.pack(">8I", 31270, 32900, 64000, 33000, 30000, 60000, 15000, 6000)} + for kind, expected in expected_srgb.items(): + if kind in color_chunks and (b"sRGB" not in color_chunks or color_chunks[kind] != expected): + raise EvidenceError("ambiguous-color", "unsupported or inconsistent PNG color fallback") + if icc_raw is not None and b"sRGB" in seen: + raise EvidenceError("ambiguous-color", "PNG has both iCCP and sRGB") + icc = None + if icc_raw is not None: + name_end = icc_raw.find(b"\0") + if name_end < 1 or name_end + 2 > len(icc_raw) or icc_raw[name_end + 1] != 0: + raise EvidenceError("ambiguous-color", "invalid iCCP chunk") + inflater = zlib.decompressobj() + try: + icc = inflater.decompress(icc_raw[name_end + 2:], CAPS["icc_bytes"] + 1) + except zlib.error: + raise EvidenceError("ambiguous-color", "invalid iCCP data") + if not icc or len(icc) > CAPS["icc_bytes"] or inflater.unconsumed_tail: + raise EvidenceError("ambiguous-color", "iCCP profile is empty or too large") + if not inflater.eof or inflater.unused_data: + raise EvidenceError("ambiguous-color", "iCCP data is truncated or has trailing bytes") + policy = "icc" + elif b"sRGB" in seen: + policy = "standard-srgb" + else: + raise EvidenceError("ambiguous-color", "PNG has no explicit color metadata") + return {"width": width, "height": height, "has_alpha": color_type == 6, "policy": policy, "icc": icc} + + +# ---------------------------------------------------------------- WebP conversion + +def load_pillow(): + try: + import PIL + from PIL import Image, features + except ImportError: + raise EvidenceError("pillow-missing", "Pillow is not installed") + if PIL.__version__ != PILLOW_VERSION: + raise EvidenceError("pillow-version", f"Pillow {PILLOW_VERSION} is required") + if not features.check("webp"): + raise EvidenceError("webp-missing", "Pillow lacks WebP support") + Image.MAX_IMAGE_PIXELS = CAPS["pixels"] + return Image, features + + +def webp_chunks(data): + if len(data) < 12 or data[:4] != b"RIFF" or data[8:12] != b"WEBP" \ + or struct.unpack(" CAPS["encoded_bytes"]: + raise EvidenceError("encoded-size", "WebP exceeds the encoded size cap") + kinds = webp_chunks(encoded) + if b"VP8L" not in kinds or b"VP8 " in kinds or b"ANIM" in kinds or b"ANMF" in kinds: + raise EvidenceError("webp-not-lossless", "WebP is not a single lossless frame") + with Image.open(destination) as output: + if output.format != "WEBP" or getattr(output, "n_frames", 1) != 1 or output.size != rgba.size: + raise EvidenceError("webp-mismatch", "WebP dimensions or frames differ") + output.load() + output_icc = output.info.get("icc_profile") + if (output_icc if info["policy"] == "icc" else (output_icc or None)) != (info["icc"] if info["policy"] == "icc" else None): + raise EvidenceError("webp-profile", "WebP ICC profile differs from the PNG") + output_pixels = output.convert("RGBA").tobytes() + if output_pixels != source_pixels: + raise EvidenceError("webp-pixels", "WebP pixels differ from the PNG (including RGB under alpha)") + return {"sha256": sha256(encoded), "bytes": len(encoded)} + + +# ---------------------------------------------------------------- manifest handling + +def read_bounded(path, limit, what): + try: + info = os.lstat(path) + except OSError: + raise EvidenceError("missing-file", f"{what} is missing") + if not stat.S_ISREG(info.st_mode): + raise EvidenceError("unsafe-path", f"{what} is not a regular file") + if info.st_size > limit: + raise EvidenceError("encoded-size", f"{what} exceeds its size cap") + with open(path, "rb") as handle: + return handle.read(limit + 1) + + +def safe_export_path(directory, name): + if not isinstance(name, str) or not SAFE_FILENAME.match(name) or name in (".", "..", "manifest.json") \ + or name.startswith("."): + raise EvidenceError("unsafe-path", "exported file name is not a plain file name") + path = os.path.join(directory, name) + if os.path.dirname(os.path.realpath(path)) != os.path.realpath(directory): + raise EvidenceError("unsafe-path", "exported file escapes the export directory") + return path + + +def collect_attachments(directory): + manifest = json.loads(read_bounded(os.path.join(directory, "manifest.json"), CAPS["manifest_bytes"], "manifest.json")) + if not isinstance(manifest, list): + raise EvidenceError("manifest-schema", "manifest is not a list") + attachments, seen = [], set() + for test in manifest: + if not isinstance(test, dict) or not isinstance(test.get("attachments"), list): + raise EvidenceError("manifest-schema", "manifest test entry is malformed") + for entry in test["attachments"]: + if not isinstance(entry, dict) or not isinstance(entry.get("suggestedHumanReadableName"), str) \ + or not isinstance(entry.get("deviceId"), str): + raise EvidenceError("manifest-schema", "manifest attachment entry is malformed") + exported = entry.get("exportedFileName") + path = safe_export_path(directory, exported) + if exported in seen: + raise EvidenceError("duplicate-file", "duplicate exported file name") + seen.add(exported) + if len(attachments) >= CAPS["attachments"]: + raise EvidenceError("file-count", "too many attachments") + attachments.append({"path": path, "entry": entry, "test": test.get("testIdentifier")}) + return attachments + + +def parse_geometry(data, name): + try: + raw = json.loads(data) + except ValueError: + raise EvidenceError("geometry-schema", f"geometry for {name} is not JSON") + if not isinstance(raw, dict) or raw.get("schemaVersion") != 1 or raw.get("kind") != GEOMETRY_KIND: + raise EvidenceError("geometry-schema", f"geometry for {name} has an unexpected schema") + geometry = {} + for key in GEOMETRY_FIELDS: + value = raw.get(key) + if key in ("scale", "screenPointWidth", "screenPointHeight"): + ok = isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) and 0 < value < 100000 + elif key in ("imagePixelWidth", "imagePixelHeight"): + ok = isinstance(value, int) and not isinstance(value, bool) and 0 < value <= CAPS["dimension"] + else: + ok = isinstance(value, str) and 0 < len(value) <= 64 + if not ok: + raise EvidenceError("geometry-schema", f"geometry for {name} has an invalid {key}") + geometry[key] = value + if geometry["orientation"] not in ("portrait", "landscape"): + raise EvidenceError("geometry-schema", f"geometry for {name} has an invalid orientation") + return geometry + + +def dims_match(width, height, geometry): + pair = sorted((width, height)) + return pair == sorted((geometry["imagePixelWidth"], geometry["imagePixelHeight"])) + + +UUID_PATTERN = r"[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}" + + +def attachment_name_matches(actual, base, extension): + """True for exactly `base` or `base` + Xcode's generated `__` + extension.""" + if actual == base: + return True + return re.fullmatch(re.escape(base) + r"_[0-9]+_" + UUID_PATTERN + re.escape(extension), actual, + re.ASCII) is not None + + +def image_name_matches(actual, name): + return attachment_name_matches(actual, name, ".png") + + +def geometry_name_matches(actual, name): + # Xcode inserts its suffix before the custom extension, independently of the JSON file UTI. + return actual == name + ".geometry" or re.fullmatch( + re.escape(name) + r"_[0-9]+_" + UUID_PATTERN + r"\.geometry", actual, re.ASCII) is not None + + +def stream_hash(path, deadline): + """SHA-256 of a regular file read in bounded chunks; never holds the contents.""" + digest = hashlib.sha256() + with open(path, "rb") as handle: + while True: + deadline.check() + block = handle.read(CAPS["hash_chunk"]) + if not block: + return digest.hexdigest() + digest.update(block) + + +def classify(attachments, deadline): + """Split attachments into PNG images and non-images. + + Images are read whole (strictly capped). Non-images are streamed: only size, sniffed type and hash are + kept, plus the bytes of files small enough to be geometry metadata. Non-images beyond the per-file or + aggregate hashing caps are recorded metadata-only (hash None, explicit skip reason), never failing evidence. + """ + images, others, hashed_total, image_total = [], [], 0, 0 + for item in attachments: + deadline.check() + try: + info = os.lstat(item["path"]) + except OSError: + raise EvidenceError("missing-file", "attachment is missing") + if not stat.S_ISREG(info.st_mode): + raise EvidenceError("unsafe-path", "attachment is not a regular file") + with open(item["path"], "rb") as handle: + head = handle.read(4096) + if head.startswith(PNG_SIGNATURE): + if info.st_size > CAPS["encoded_bytes"]: + raise EvidenceError("encoded-size", "attachment exceeds the encoded size cap") + image_total += info.st_size + if image_total > CAPS["image_input_bytes"]: + raise EvidenceError("input-bytes", "image attachments exceed the aggregate input cap") + item["data"] = read_bounded(item["path"], CAPS["encoded_bytes"], "attachment") + images.append(item) + if len(images) > CAPS["images"]: + raise EvidenceError("file-count", "too many image attachments") + continue + names = (item["entry"]["exportedFileName"], item["entry"]["suggestedHumanReadableName"]) + if any(os.path.splitext(name)[1].lower() in (".png", ".jpg", ".jpeg", ".gif", ".webp", ".heic", ".tif", ".tiff") + for name in names) or head.startswith(b"\xff\xd8\xff"): + raise EvidenceError("unsupported-image", "image attachment is not a supported PNG") + item["size"], item["type"], item["data"] = info.st_size, sniff_type(head), None + if info.st_size <= CAPS["geometry_bytes"]: + item["data"] = read_bounded(item["path"], CAPS["geometry_bytes"], "attachment") + if info.st_size > CAPS["nonimage_file_bytes"]: + item["sha256"], item["skipped"] = None, "file-size-cap" + elif hashed_total + info.st_size > CAPS["nonimage_total_bytes"]: + item["sha256"], item["skipped"] = None, "aggregate-size-cap" + else: + hashed_total += info.st_size + item["sha256"], item["skipped"] = stream_hash(item["path"], deadline), None + others.append(item) + return images, others + + +def sniff_type(data): + head = data[:16].lstrip() + if head[:1] in (b"{", b"["): + return "json" + if data[:3] == b"\xff\xd8\xff": + return "jpeg" + if data[:4] in (b"RIFF", b"%PDF"): + return data[:4].decode("latin1").lower() + try: + data[:4096].decode("utf-8") + return "text" + except UnicodeDecodeError: + return "binary" + + +def check_environment(raw): + if raw is None: + return {} + if len(raw.encode()) > CAPS["environment_bytes"]: + raise EvidenceError("environment", "environment JSON exceeds its size cap") + try: + value = json.loads(raw) + except ValueError: + raise EvidenceError("environment", "environment is not valid JSON") + if not isinstance(value, dict) or len(value) > 64: + raise EvidenceError("environment", "environment must be a small JSON object") + result = {} + for key, item in value.items(): + if not re.match(r"^[A-Za-z0-9_.-]{1,64}$", key) or not isinstance(item, (str, int, float, bool)) \ + or isinstance(item, float) and not math.isfinite(item): + raise EvidenceError("environment", "environment entries must be simple scalars") + result[key] = clean_text(item, 256) if isinstance(item, str) else item + return result + + +def tool_versions(runner): + versions = {"python": sys.version.split()[0]} + try: + Image, features = load_pillow() + import PIL + versions.update(pillow=PIL.__version__, libwebp=features.version("webp")) + except EvidenceError: + raise + try: + out = runner(["xcrun", "xcresulttool", "version"]) + versions["xcresulttool"] = clean_text(out.strip().splitlines()[0]) if out.strip() else None + except Exception: + versions["xcresulttool"] = None + return versions + + +def run_command(args, timeout=30): + return subprocess.run(args, check=True, capture_output=True, text=True, timeout=timeout).stdout + + +def xcresult_export(bundle, destination, deadline): + try: + subprocess.run(["xcrun", "xcresulttool", "export", "attachments", "--path", bundle, + "--output-path", destination], check=True, capture_output=True, + timeout=min(CAPS["export_seconds"], deadline.remaining())) + except subprocess.TimeoutExpired: + raise EvidenceError("export-timeout", "xcresulttool export timed out") + except (subprocess.CalledProcessError, OSError): + raise EvidenceError("export-failed", "xcresulttool export failed") + + +# ---------------------------------------------------------------- orchestration + +def build_evidence(bundle, staging, source, environment, export_fn=xcresult_export, runner=run_command, deadline=None): + """Populate staging with verified WebP files and manifest.json. Raises EvidenceError on any problem.""" + deadline = deadline or Deadline(CAPS["seconds"]) + load_pillow() + exported = tempfile.mkdtemp(prefix=".export-", dir=os.path.dirname(os.path.abspath(staging))) + try: + export_fn(bundle, exported, deadline) + deadline.check() + attachments = collect_attachments(exported) + images, others = classify(attachments, deadline) + + geometries, required_items = {}, {} + for name in REQUIRED_NAMES: + matches = [i for i in images if image_name_matches(i["entry"]["suggestedHumanReadableName"], name)] + geo_matches = [i for i in attachments + if geometry_name_matches(i["entry"]["suggestedHumanReadableName"], name)] + if len(matches) != 1: + raise EvidenceError("required-missing" if not matches else "required-duplicate", + f"required screenshot '{name}' found {len(matches)} times") + if len(geo_matches) != 1: + raise EvidenceError("required-missing" if not geo_matches else "required-duplicate", + f"geometry for '{name}' found {len(geo_matches)} times") + if geo_matches[0] in images: + raise EvidenceError("geometry-schema", f"geometry for {name} is an image") + geo_data = geo_matches[0]["data"] + if geo_data is None: + raise EvidenceError("geometry-schema", f"geometry for {name} is too large") + geometries[name] = parse_geometry(geo_data, name) + if geo_matches[0]["entry"]["deviceId"] != matches[0]["entry"]["deviceId"]: + raise EvidenceError("geometry-device", f"geometry for {name} is from another device") + required_items[id(matches[0])] = name + + # Observed scale per device, only where every observation agrees. + scales = {} + for name, item in ((n, next(i for i in images if id(i) in required_items and required_items[id(i)] == n)) + for n in REQUIRED_NAMES): + scales.setdefault(item["entry"]["deviceId"], set()).add(geometries[name]["scale"]) + + records, total, version_info = [], 0, tool_versions(runner) + for index, item in enumerate(sorted(images, key=lambda i: i["entry"]["suggestedHumanReadableName"] + i["entry"]["exportedFileName"])): + deadline.check() + data, entry = item["data"], item["entry"] + info = inspect_png(data) + name = required_items.get(id(item)) + record = {"index": index, "required_name": name, "source_png_sha256": sha256(data), + "attachment_name": clean_text(entry["suggestedHumanReadableName"]), + "test_identifier": clean_text(item["test"]), + "source_png_bytes": len(data), "pixel_width": info["width"], "pixel_height": info["height"], + "has_alpha": info["has_alpha"], "color_policy": info["policy"], + "icc_sha256": sha256(info["icc"]) if info["icc"] else None, + "device_id": clean_text(entry["deviceId"]), "device_name": clean_text(entry.get("deviceName")), + "configuration": clean_text(entry.get("configurationName")), + "associated_with_failure": bool(entry.get("isAssociatedWithFailure")), + "timestamp": entry.get("timestamp") if isinstance(entry.get("timestamp"), (int, float)) else None, + "original_disposition": "retained-only-in-xcresult"} + if name: + geometry = geometries[name] + if not dims_match(info["width"], info["height"], geometry): + raise EvidenceError("geometry-mismatch", f"geometry for {name} does not match the image") + record.update(display_scale=geometry["scale"], display_scale_source="observed", geometry=geometry) + else: + device_scales = scales.get(entry["deviceId"], set()) + # Element screenshots can be cropped; the observed display scale is still device-wide. + if len(device_scales) == 1: + record.update(display_scale=next(iter(device_scales)), + display_scale_source="inferred-from-same-device-required-geometry") + else: + record.update(display_scale=None, display_scale_source="unknown") + output_name = f"{index:03d}-{record['source_png_sha256'][:16]}.webp" + record["file"] = output_name + destination = os.path.join(staging, output_name) + record.update(webp_sha256=None) + result = convert_to_lossless_webp(data, info, destination) + total += result["bytes"] + if total > CAPS["output_bytes"]: + raise EvidenceError("output-bytes", "verified output exceeds the byte cap") + record.update(webp_sha256=result["sha256"], webp_bytes=result["bytes"], verified_lossless_exact=True) + os.remove(item["path"]) # the verified WebP replaces the exported PNG + item["data"] = None + records.append(record) + + non_images = [{"index": i, "sha256": o["sha256"], "bytes": o["size"], "type": o["type"], "hash_skipped": o["skipped"], + "published": False} for i, o in enumerate(others)] + manifest = {"schemaVersion": SCHEMA_VERSION, "status": "complete", "source": source, + "required_names": REQUIRED_NAMES, "images": records, "non_image_attachments": non_images, + "toolchain": version_info, "environment": environment, + "webp_options": {"lossless": True, "exact": True, "method": 6, "icc": "retained exact bytes"}, + "total_webp_bytes": total} + with open(os.path.join(staging, "manifest.json"), "w") as handle: + json.dump(manifest, handle, indent=2, sort_keys=True) # completion marker, written last + finally: + shutil.rmtree(exported, ignore_errors=True) + + +def publish(output, source, environment_raw, bundle, **kwargs): + """Stage and atomically promote. Returns True on success; failure.json is published on failure.""" + output = os.path.abspath(output) + parent = os.path.dirname(output) + os.makedirs(parent, exist_ok=True) + if os.path.lexists(output): + raise EvidenceError("output-exists", "output path already exists") + staging = tempfile.mkdtemp(prefix=".staging-", dir=parent) + try: + build_evidence(bundle, staging, source, check_environment(environment_raw), **kwargs) + os.rename(staging, output) + return True + except BaseException as error: + shutil.rmtree(staging, ignore_errors=True) + if isinstance(error, EvidenceError): + code, message = error.code, error.message[:CAPS["text"]] + else: + code, message = "internal-error", type(error).__name__ + failure = tempfile.mkdtemp(prefix=".failure-", dir=parent) + with open(os.path.join(failure, "failure.json"), "w") as handle: + json.dump({"schemaVersion": SCHEMA_VERSION, "status": "failed", "source": source, + "code": code, "message": message}, handle, indent=2, sort_keys=True) + os.rename(failure, output) + if isinstance(error, (KeyboardInterrupt, SystemExit)): + raise + return False + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--result-bundle", required=True) + parser.add_argument("--output", required=True) + parser.add_argument("--source", required=True) + parser.add_argument("--environment", help="JSON object (inline or a path to a JSON file)") + args = parser.parse_args(argv) + if not re.fullmatch(r"[0-9a-f]{40}", args.source): + parser.error("--source must be a 40-character lowercase git SHA") + environment = args.environment + if environment is not None and not environment.lstrip().startswith("{"): + try: + environment = read_bounded(environment, CAPS["environment_bytes"], "environment file").decode() + except (EvidenceError, UnicodeDecodeError) as error: + parser.error(f"unreadable --environment: {getattr(error, 'message', 'invalid text')}") + try: + ok = publish(args.output, args.source, environment, args.result_bundle) + except EvidenceError as error: + print(f"error: {error.message}", file=sys.stderr) + return 1 + if not ok: + print("error: UI evidence export failed; see failure.json", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/requirements-visual.txt b/scripts/requirements-visual.txt new file mode 100644 index 0000000..769e363 --- /dev/null +++ b/scripts/requirements-visual.txt @@ -0,0 +1,5 @@ +# Hash-pinned for `pip install --require-hashes --only-binary=:all: --no-deps`. +# Hashes are the official PyPI macOS cp313 wheels (x86_64 and arm64) for 12.3.0. +Pillow==12.3.0 \ + --hash=sha256:7a743ff716f746fc19a9557f60dab1600d4613255f8a7aeb3cdde4db7eb15a66 \ + --hash=sha256:d69141514cc30b774ceea5e3ed3a6635c8d8a96edf664689b890f4089111fb35 diff --git a/scripts/tests/test_plugin_repository_fixture.py b/scripts/tests/test_plugin_repository_fixture.py index d665699..68ab510 100644 --- a/scripts/tests/test_plugin_repository_fixture.py +++ b/scripts/tests/test_plugin_repository_fixture.py @@ -294,6 +294,60 @@ def test_browser_variant_is_explicitly_derived_and_keeps_sdk_catalog_unchanged(s self.assertTrue({file for phases in rule['hooks'].values() for file in phases.values()} <= set(package['sourceFiles'])) + BASE_HASHES = { + '/request-summary.json': 'f7985fe4eb7a5d60bcc69fc682b0f853e0c22a7a2a52bab84b1e1bccebe2ed12', + '/response-details.json': '841f9582b395c81964f1a875980f102aa3c2942079f8e42c32571725e8761210', + '/multi-file-hooks.json': '6f007a8e930949b7e0094b59b17cbfb82128eaf196156edd9901495f543440fa', + '/approval-limits.json': '80b1908a2ddeef087e5b419bc07dae8ac2c61279f10eed40b934e814ae9b50af', + '/repository.json': '8b73cee200453d88937e75252721418d4ce63784a2d2222f61f6564764cb8eae', + '/browser/target-hosts.json': '30fd5c5184f04d685115d3fee7c4c0c330c77fb09ba4eb964d9bb6c859bb59ae', + '/browser/repository.json': '9e262cd56b3ff8e41afd8675d70e156e872fe1c2b471af41c801d4cfbd8a67f4', + } + + def test_original_served_bytes_match_hardcoded_pre_outbound_hashes(self): + files, _ = fixture.repository_files('this-run', DEVICE) + for path, expected in self.BASE_HASHES.items(): + self.assertEqual(fixture.digest(files[path]), expected, path) + + def test_outbound_variant_is_explicitly_derived_with_three_deterministic_bindings(self): + files, _ = fixture.repository_files('this-run', DEVICE) + index = json.loads(base64.b64decode(json.loads(files['/outbound/repository.json'])['payload'], validate=True)) + self.assertEqual(index['name'], 'Outbound catalog fixture') + self.assertEqual(len(index['plugins']), 1) + entry = index['plugins'][0] + self.assertEqual(entry['packagePath'], 'approval.json') + raw = files['/outbound/' + entry['packagePath']] + package = json.loads(raw) + manifest = package['manifest'] + self.assertEqual(manifest['name'], 'Outbound approval example') + self.assertEqual(entry['sha256'], fixture.digest(raw)) + self.assertEqual(entry['size'], len(raw)) + for key in ('id', 'name', 'version', 'author', 'summary', 'category'): + self.assertEqual(entry[key], manifest[key]) + self.assertEqual(manifest['outbound'], { + 'lookup': {'url': 'https://api.example.com/v1/profile', 'method': 'GET', 'headers': []}, + 'post': {'url': 'https://api.example.com/v1/records', 'method': 'POST', 'headers': ['authorization', 'content-type']}, + 'put': {'url': 'https://api.example.com/v1/records/latest', 'method': 'PUT', 'headers': ['content-type']}, + }) + sdk = json.loads(files['/multi-file-hooks.json']) + self.assertNotIn(manifest['id'], {sdk['manifest']['id'], 'E9472B70-2DB2-4F4C-A291-33F5FEF88519'}) + self.assertEqual(package['sourceFiles'], sdk['sourceFiles']) + self.assertNotIn('outbound', sdk['manifest']) + self.assertNotEqual(index['id'], '57414817-0F72-40BA-A27C-535B784BEE00') + self.assertNotEqual(index['id'], '532AEB4B-8744-44DA-86CB-DC46E3831F23') + + def test_native_outbound_expectations_match_served_package(self): + import re + files, _ = fixture.repository_files('this-run', DEVICE) + native = (ROOT / 'InterceptorUITests/AutomationUITests.swift').read_text() + revision = re.search(r'outboundRevision = "([a-f0-9]{64})"', native) + identifier = re.search(r'outboundID = "([0-9A-F-]{36})"', native) + self.assertIsNotNone(revision) + self.assertEqual(revision.group(1), fixture.digest(files['/outbound/approval.json'])) + self.assertEqual(identifier.group(1), json.loads(files['/outbound/approval.json'])['manifest']['id']) + for binding in json.loads(files['/outbound/approval.json'])['manifest']['outbound'].values(): + self.assertIn('"%s %s"' % (binding['method'], binding['url']), native) + def test_readiness_digest_binds_every_allowlisted_catalog_and_package(self): files, bound_digest = fixture.repository_files('this-run', DEVICE) payload_files = {path: fixture.digest(raw) for path, raw in files.items() if path != '/__interceptor_fixture'} @@ -301,6 +355,11 @@ def test_readiness_digest_binds_every_allowlisted_catalog_and_package(self): changed = dict(payload_files) changed['/browser/target-hosts.json'] = '0' * 64 self.assertNotEqual(bound_digest, fixture.digest(fixture.encoded(changed))) + self.assertIn('/outbound/repository.json', payload_files) + self.assertIn('/outbound/approval.json', payload_files) + changed = dict(payload_files) + changed['/outbound/approval.json'] = '0' * 64 + self.assertNotEqual(bound_digest, fixture.digest(fixture.encoded(changed))) def test_browser_derivation_targets_the_exact_file_independent_of_rule_order(self): packages = fixture.load_packages() @@ -327,11 +386,16 @@ def test_browser_variant_is_served_over_https_and_written_under_owned_public_dir record = json.loads((work / 'fixture-run.json').read_text()) self.assertIn('/browser/repository.json', record['publicFiles']) self.assertIn('/browser/target-hosts.json', record['publicFiles']) - self.assertEqual(record['derivedPackages'], {'/browser/target-hosts.json': 'multi-file-hooks.json'}) + self.assertEqual(record['derivedPackages'], {'/browser/target-hosts.json': 'multi-file-hooks.json', + '/outbound/approval.json': 'multi-file-hooks.json'}) + self.assertIn('/outbound/repository.json', record['publicFiles']) + self.assertIn('/outbound/approval.json', record['publicFiles']) self.assertTrue((work / 'public/browser/repository.json').is_file()) served = {(entry['path'], entry['status']) for entry in record['requests']['entries']} self.assertIn(('/browser/repository.json', 200), served) self.assertIn(('/browser/target-hosts.json', 200), served) + self.assertIn(('/outbound/repository.json', 200), served) + self.assertIn(('/outbound/approval.json', 200), served) self.assertTrue(record['serverStopped']) self.assertTrue(record['privateKeysRemoved']) diff --git a/scripts/tests/test_ui_evidence.py b/scripts/tests/test_ui_evidence.py new file mode 100644 index 0000000..ff4b0a5 --- /dev/null +++ b/scripts/tests/test_ui_evidence.py @@ -0,0 +1,532 @@ +import importlib.util +import json +import os +from pathlib import Path +import struct +import tempfile +import unittest +import zlib + +from PIL import Image + +ROOT = Path(__file__).resolve().parents[2] +spec = importlib.util.spec_from_file_location('ui_evidence', ROOT / 'scripts/export-ui-evidence.py') +ev = importlib.util.module_from_spec(spec) +spec.loader.exec_module(ev) + +SOURCE = 'a' * 40 +ICC = b'\x00\x00\x02\x0cappl' + bytes(range(256)) * 2 # opaque bytes: only byte-exact retention is under test +WIDTH, HEIGHT = 4, 3 + + +def chunk(kind, body): + return struct.pack('>I', len(body)) + kind + body + struct.pack('>I', zlib.crc32(kind + body)) + + +def png(pixels=None, width=WIDTH, height=HEIGHT, color_type=6, depth=8, interlace=0, extra=(), icc=ICC, srgb=False): + """Build a PNG by hand so metadata chunks are exactly controlled.""" + channels = 4 if color_type == 6 else 3 + if pixels is None: + pixels = [bytes((x * 40, y * 60, 200, 255 if channels == 4 else 0)[:channels]) + for y in range(height) for x in range(width)] + rows = b''.join(b'\0' + b''.join(pixels[y * width:(y + 1) * width]) for y in range(height)) + out = ev.PNG_SIGNATURE + chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, depth, color_type, 0, 0, interlace)) + if srgb: + out += chunk(b'sRGB', b'\0') + elif icc is not None: + out += chunk(b'iCCP', b'profile\0\0' + zlib.compress(icc)) + for kind, body in extra: + out += chunk(kind, body) + return out + chunk(b'IDAT', zlib.compress(rows)) + chunk(b'IEND', b'') + + +def geometry(scale=2, width=WIDTH, height=HEIGHT): + return json.dumps({'schemaVersion': 1, 'kind': ev.GEOMETRY_KIND, 'scale': scale, + 'screenPointWidth': width / scale, 'screenPointHeight': height / scale, + 'imagePixelWidth': width, 'imagePixelHeight': height, 'osVersion': '26.0', + 'deviceModel': 'iPhone', 'orientation': 'portrait', 'locale': 'en_US'}).encode() + + +class Export: + """Synthetic xcresulttool export: files plus a manifest.json in xcresulttool's schema.""" + + def __init__(self, device='DEVICE-A', scale=2): + self.files, self.entries = {}, [] + self.device, self.scale = device, scale + + def add(self, name, data, exported=None, device=None): + exported = exported or f'att-{len(self.entries)}' + self.files[exported] = data + self.entries.append({'suggestedHumanReadableName': name, 'exportedFileName': exported, + 'deviceId': device or self.device, 'deviceName': 'iPhone', + 'isAssociatedWithFailure': False, 'timestamp': 1.5}) + return exported + + def add_required(self, image=None, skip=(), device=None, scale=None): + for name in ev.REQUIRED_NAMES: + if name in skip: + continue + self.add(name, image if image is not None else png(), device=device) + self.add(name + '.geometry', geometry(scale or self.scale), device=device) + return self + + def __call__(self, bundle, destination, deadline): + for name, data in self.files.items(): + path = os.path.join(destination, name) + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, 'wb') as handle: + handle.write(data) + with open(os.path.join(destination, 'manifest.json'), 'w') as handle: + json.dump([{'testIdentifier': 'T/test', 'attachments': self.entries}], handle) + + +def runner(args, timeout=30): + return 'xcresulttool version 1\n' + + +class EvidenceBase(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + self.output = self.root / 'out' / 'evidence' + + def publish(self, export, env=None): + return ev.publish(str(self.output), SOURCE, env, 'unused.xcresult', export_fn=export, runner=runner) + + def manifest(self): + return json.loads((self.output / 'manifest.json').read_text()) + + def failure(self): + return json.loads((self.output / 'failure.json').read_text()) + + def assertFailed(self, code, export, env=None): + self.assertFalse(self.publish(export, env)) + self.assertEqual(sorted(p.name for p in self.output.iterdir()), ['failure.json']) + self.assertEqual(self.failure()['code'], code) + self.assertEqual(sorted(p.name for p in self.output.parent.iterdir()), ['evidence'], 'staging leaked') + + +class PngInspectionTests(unittest.TestCase): + def test_rgba_with_icc(self): + info = ev.inspect_png(png()) + self.assertEqual((info['width'], info['height'], info['has_alpha'], info['policy']), (WIDTH, HEIGHT, True, 'icc')) + self.assertEqual(info['icc'], ICC) + + def test_rgb_srgb(self): + info = ev.inspect_png(png(color_type=2, srgb=True)) + self.assertFalse(info['has_alpha']) + self.assertEqual((info['policy'], info['icc']), ('standard-srgb', None)) + + def assertRejected(self, code, data): + with self.assertRaises(ev.EvidenceError) as caught: + ev.inspect_png(data) + self.assertEqual(caught.exception.code, code) + + def test_rejects_unsupported_or_ambiguous(self): + self.assertRejected('unsupported-depth', png(depth=16)) + self.assertRejected('unsupported-color-type', png(color_type=3)) + self.assertRejected('unsupported-interlace', png(interlace=1)) + self.assertRejected('unsupported-animation', png(extra=[(b'acTL', b'\0' * 8)])) + self.assertRejected('ambiguous-color', png(extra=[(b'tRNS', b'\0' * 6)])) + self.assertRejected('ambiguous-color', png(icc=None)) + self.assertRejected('ambiguous-color', png(extra=[(b'sRGB', b'\0')])) + self.assertRejected('not-png', b'GIF89a' + b'\0' * 32) + + def test_rejects_corruption(self): + good = png() + corrupt = bytearray(good) + corrupt[-1] ^= 0xFF + self.assertRejected('png-crc', bytes(corrupt)) + self.assertRejected('png-truncated', good[:-7]) + self.assertRejected('png-truncated', good[:20]) + self.assertRejected('png-structure', good + b'junk') + + def test_color_fallback_must_match_explicit_srgb(self): + gamma = (b'gAMA', struct.pack('>I', 45455)) + chroma = (b'cHRM', struct.pack('>8I', 31270, 32900, 64000, 33000, 30000, 60000, 15000, 6000)) + self.assertEqual(ev.inspect_png(png(srgb=True, extra=[gamma, chroma]))['policy'], 'standard-srgb') + for chunks in ([(b'sRGB', b'')], [(b'sRGB', b'\x04')], [gamma], [chroma], + [(b'sRGB', b'\0'), (b'gAMA', struct.pack('>I', 100000))], + [(b'sRGB', b'\0'), (b'cHRM', b'\0' * 32)]): + self.assertRejected('ambiguous-color', png(icc=None, extra=chunks)) + + def test_icc_zlib_must_be_complete_and_exact(self): + def with_icc(body): + return ev.PNG_SIGNATURE + chunk(b'IHDR', struct.pack('>IIBBBBB', WIDTH, HEIGHT, 8, 6, 0, 0, 0)) \ + + chunk(b'iCCP', b'profile\0\0' + body) + chunk(b'IEND', b'') + stream = zlib.compress(ICC) + self.assertEqual(ev.inspect_png(with_icc(stream))['icc'], ICC) + self.assertRejected('ambiguous-color', with_icc(stream + b'trailing')) + self.assertRejected('ambiguous-color', with_icc(stream[:-6])) + self.assertRejected('ambiguous-color', with_icc(stream[:-1])) + + def test_dimension_and_size_caps(self): + header = ev.PNG_SIGNATURE + chunk(b'IHDR', struct.pack('>IIBBBBB', ev.CAPS['dimension'] + 1, 1, 8, 6, 0, 0, 0)) + self.assertRejected('dimension-cap', header) + header = ev.PNG_SIGNATURE + chunk(b'IHDR', struct.pack('>IIBBBBB', 5000, 5000, 8, 6, 0, 0, 0)) + self.assertRejected('dimension-cap', header) + self.assertRejected('encoded-size', b'\0' * (ev.CAPS['encoded_bytes'] + 1)) + + +class ConversionTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + + def convert(self, data): + dest = os.path.join(self.tmp.name, 'out.webp') + result = ev.convert_to_lossless_webp(data, ev.inspect_png(data), dest) + return dest, result + + def test_transparent_rgba_and_icc_roundtrip(self): + pixels = [bytes((10, 20, 30, 0)), bytes((255, 0, 0, 0)), bytes((1, 2, 3, 128)), bytes((9, 8, 7, 255))] * 3 + data = png(pixels=pixels) + dest, result = self.convert(data) + with Image.open(dest) as out: + self.assertEqual(out.format, 'WEBP') + self.assertEqual(out.size, (WIDTH, HEIGHT)) + self.assertEqual(out.info.get('icc_profile'), ICC) + # RGB under fully transparent alpha must survive (exact=True). + self.assertEqual(out.convert('RGBA').tobytes(), b''.join(pixels)) + self.assertEqual(result['bytes'], os.path.getsize(dest)) + self.assertIn(b'VP8L', ev.webp_chunks(Path(dest).read_bytes())) + + def test_rgb_srgb_has_no_profile(self): + dest, _ = self.convert(png(color_type=2, srgb=True)) + with Image.open(dest) as out: + self.assertIsNone(out.info.get('icc_profile')) + self.assertEqual(out.convert('RGBA').getpixel((0, 0))[3], 255) + + def test_webp_chunk_validation(self): + with self.assertRaises(ev.EvidenceError): + ev.webp_chunks(b"RIFF\x10\0\0\0WEBP") + with self.assertRaises(ev.EvidenceError): + ev.webp_chunks(b'not webp at all') + + +class GeometryTests(unittest.TestCase): + def test_parse_valid(self): + self.assertEqual(ev.parse_geometry(geometry(3), 'n')['scale'], 3) + + def test_parse_invalid(self): + good = json.loads(geometry()) + for patch in ({'scale': 0}, {'scale': True}, {'scale': float('nan')}, {'imagePixelWidth': 99999}, + {'imagePixelWidth': 1.5}, {'orientation': 'flat'}, {'kind': 'other'}, {'schemaVersion': 2}, + {'locale': ''}): + with self.assertRaises(ev.EvidenceError, msg=str(patch)): + ev.parse_geometry(json.dumps({**good, **patch}).encode(), 'n') + for data in (b'not json', b'[]'): + with self.assertRaises(ev.EvidenceError): + ev.parse_geometry(data, 'n') + + def test_dims_match_allows_rotation_only(self): + geo = json.loads(geometry()) + self.assertTrue(ev.dims_match(HEIGHT, WIDTH, geo)) + self.assertFalse(ev.dims_match(WIDTH, HEIGHT + 1, geo)) + + +class PublishTests(EvidenceBase): + def test_aggregate_image_input_is_bounded(self): + original = ev.CAPS['image_input_bytes'] + self.addCleanup(ev.CAPS.__setitem__, 'image_input_bytes', original) + ev.CAPS['image_input_bytes'] = len(png()) * 7 + self.assertFailed('input-bytes', Export().add_required()) + + def test_damaged_supplementary_image_cannot_be_a_nonimage(self): + export = Export().add_required() + export.add('Supplementary.png', b'broken PNG', exported='broken.png') + self.assertFailed('unsupported-image', export) + + def test_success_maps_metadata_and_verifies_all_required(self): + export = Export().add_required() + self.assertTrue(self.publish(export, '{"runtime": "iOS 26.0", "build": 7}')) + self.assertEqual(sorted(p.name for p in self.output.parent.iterdir()), ['evidence']) + manifest = self.manifest() + self.assertEqual(manifest['status'], 'complete') + self.assertEqual(manifest['source'], SOURCE) + self.assertEqual(manifest['environment'], {'runtime': 'iOS 26.0', 'build': 7}) + self.assertEqual(manifest['required_names'], ev.REQUIRED_NAMES) + self.assertEqual(len(ev.REQUIRED_NAMES), 8) + images = manifest['images'] + self.assertEqual(sorted(i['required_name'] for i in images), sorted(ev.REQUIRED_NAMES)) + for record in images: + self.assertTrue(record['attachment_name']) + self.assertEqual(record['test_identifier'], 'T/test') + self.assertEqual(record['display_scale'], 2) + self.assertEqual(record['display_scale_source'], 'observed') + self.assertEqual(record['device_id'], 'DEVICE-A') + self.assertTrue(record['verified_lossless_exact']) + self.assertEqual(record['color_policy'], 'icc') + self.assertEqual(record['original_disposition'], 'retained-only-in-xcresult') + self.assertTrue((self.output / record['file']).is_file()) + with Image.open(self.output / record['file']) as out: + self.assertEqual(out.info.get('icc_profile'), ICC) + self.assertEqual(len(manifest['non_image_attachments']), 8) + self.assertTrue(all(not n['published'] for n in manifest['non_image_attachments'])) + published = sorted(p.name for p in self.output.iterdir()) + self.assertEqual(published, sorted([i['file'] for i in images] + ['manifest.json'])) + self.assertFalse(any(n.endswith('.png') for n in published)) + + def test_observed_scale_is_per_device_not_hardcoded(self): + export = Export(device='A', scale=3) + for name in ev.REQUIRED_NAMES[:4]: + export.add(name, png(), device='A') + export.add(name + '.geometry', geometry(3), device='A') + for name in ev.REQUIRED_NAMES[4:]: + export.add(name, png(), device='B') + export.add(name + '.geometry', geometry(2), device='B') + self.assertTrue(self.publish(export)) + got = {i['required_name']: (i['device_id'], i['display_scale']) for i in self.manifest()['images']} + for name in ev.REQUIRED_NAMES[:4]: + self.assertEqual(got[name], ('A', 3)) + for name in ev.REQUIRED_NAMES[4:]: + self.assertEqual(got[name], ('B', 2)) + + def test_extra_images_scale_inferred_or_unknown(self): + export = Export().add_required() + export.add('Extra same device', png(width=2, height=2)) + export.add('Extra other device', png(), device='DEVICE-Z') + export.add('notes.txt', b'hello') + self.assertTrue(self.publish(export)) + manifest = self.manifest() + extras = {i['device_id']: i for i in manifest['images'] if i['required_name'] is None} + self.assertEqual(extras['DEVICE-A']['display_scale'], 2) + self.assertEqual(extras['DEVICE-A']['display_scale_source'], 'inferred-from-same-device-required-geometry') + self.assertIsNone(extras['DEVICE-Z']['display_scale']) + self.assertEqual(extras['DEVICE-Z']['display_scale_source'], 'unknown') + self.assertEqual(len(manifest['images']), 10) + self.assertEqual(len(manifest['non_image_attachments']), 9) + + def test_real_xcode_suffixed_names_accepted(self): + uuid = 'D95B5FA3-05D1-4FB4-9079-47538FDE159A' + export = Export() + for n, name in enumerate(ev.REQUIRED_NAMES): + export.add(f'{name}_{n}_{uuid}.png', png(), exported=f'{uuid[:-2]}{n:02d}.png') + export.add(f'{name}_{n}_{uuid}.geometry', geometry(), exported=f'g{n}.json') + self.assertTrue(self.publish(export)) + self.assertEqual(sorted(i['required_name'] for i in self.manifest()['images']), sorted(ev.REQUIRED_NAMES)) + + def test_malformed_suffixes_rejected(self): + uuid = 'D95B5FA3-05D1-4FB4-9079-47538FDE159A' + base = 'Outbound GET en' + for bad in (f'{base}_x_{uuid}.png', f'{base}__{uuid}.png', f'{base}_0_{uuid[:-1]}.png', f'{base}_0_{uuid}', + f'{base}_0_{uuid}.json', f'{base}_0_{uuid}.png.png', f'{base} _0_{uuid}.png', + f'{base}_0_{uuid}.PNG', f'{base}.png', f'{base}_0_{uuid}\n.png', f'{base}_٣_{uuid}.png'): + self.assertFalse(ev.image_name_matches(bad, base), bad) + self.assertTrue(ev.image_name_matches(f'{base}_12_{uuid}.png', base)) + self.assertTrue(ev.image_name_matches(base, base)) + self.assertTrue(ev.geometry_name_matches(f'{base}_0_{uuid}.geometry', base)) + self.assertFalse(ev.geometry_name_matches(f'{base}.geometry_0_{uuid}.json', base)) + self.assertFalse(ev.geometry_name_matches(f'{base}.geometry_0_{uuid}.png', base)) + self.assertFalse(ev.geometry_name_matches(f'{base}_0_{uuid}.json', base)) + + def test_ambiguous_suffixed_and_plain_duplicate_fails(self): + export = Export().add_required() + export.add('Outbound GET en_0_D95B5FA3-05D1-4FB4-9079-47538FDE159A.png', png()) + self.assertFailed('required-duplicate', export) + + def test_large_nonimage_is_streamed_not_read_or_rejected(self): + export = Export().add_required() + export.add('screen recording', b'\0\0\0\x18ftypmp42' + b'\0' * 64) + original = ev.read_bounded + calls = [] + ev.read_bounded = lambda path, limit, what: (calls.append(limit), original(path, limit, what))[1] + self.addCleanup(setattr, ev, 'read_bounded', original) + small = dict(ev.CAPS) + self.addCleanup(lambda: (ev.CAPS.clear(), ev.CAPS.update(small))) + ev.CAPS['encoded_bytes'] = 1024 * 1024 # recording below exceeds this yet must not fail evidence + ev.CAPS['hash_chunk'] = 4096 + export.files['att-%d' % (len(export.entries) - 1)] = b'v' * (2 * 1024 * 1024) + self.assertTrue(self.publish(export)) + entry = [n for n in self.manifest()['non_image_attachments'] if n['bytes'] == 2 * 1024 * 1024][0] + import hashlib + self.assertEqual(entry['sha256'], hashlib.sha256(b'v' * (2 * 1024 * 1024)).hexdigest()) + self.assertIsNone(entry['hash_skipped']) + self.assertNotIn(2 * 1024 * 1024, calls) + self.assertEqual(sorted(p.name for p in self.output.iterdir() if not p.name.endswith('.webp')), ['manifest.json']) + + def test_nonimage_beyond_caps_is_metadata_only(self): + export = Export().add_required() + export.add('big.mov', b'x' * 5000) + export.add('big2.mov', b'y' * 3000) + small = dict(ev.CAPS) + self.addCleanup(lambda: (ev.CAPS.clear(), ev.CAPS.update(small))) + ev.CAPS['nonimage_file_bytes'] = 4000 + self.assertTrue(self.publish(export)) + skipped = [n for n in self.manifest()['non_image_attachments'] if n['bytes'] in (5000, 3000)] + self.assertEqual({n['bytes']: n['hash_skipped'] for n in skipped}, {5000: 'file-size-cap', 3000: None}) + self.assertIsNone([n for n in skipped if n['bytes'] == 5000][0]['sha256']) + + def test_oversize_png_still_rejected(self): + export = Export().add_required() + export.files[export.entries[0]['exportedFileName']] = ev.PNG_SIGNATURE + b'\0' * ev.CAPS['encoded_bytes'] + self.assertFailed('encoded-size', export) + + def test_attachment_cap_is_realistic(self): + self.assertEqual(ev.CAPS['attachments'], 4096) + + def test_each_missing_required_name_or_geometry_fails(self): + for name in ev.REQUIRED_NAMES: + with self.subTest(missing=name): + self.tearDown_output() + self.assertFailed('required-missing', self.partial(skip_image=name)) + for name in ev.REQUIRED_NAMES: + with self.subTest(missing_geometry=name): + self.tearDown_output() + self.assertFailed('required-missing', self.partial(skip_geometry=name)) + + def tearDown_output(self): + import shutil + shutil.rmtree(self.output.parent, ignore_errors=True) + + def partial(self, skip_image=None, skip_geometry=None): + export = Export() + for name in ev.REQUIRED_NAMES: + if name != skip_image: + export.add(name, png()) + if name != skip_geometry: + export.add(name + '.geometry', geometry()) + return export + + def test_duplicate_required_fails(self): + export = Export().add_required() + export.add('Outbound GET en', png()) + self.assertFailed('required-duplicate', export) + + def test_geometry_mismatch_and_other_device_fail(self): + export = Export().add_required() + export.files[export.entries[1]['exportedFileName']] = geometry(2, WIDTH + 1, HEIGHT) + self.assertFailed('geometry-mismatch', export) + self.tearDown_output() + export = Export().add_required() + export.entries[1]['deviceId'] = 'OTHER' + self.assertFailed('geometry-device', export) + + def test_corrupt_second_image_promotes_nothing(self): + export = Export().add_required() + good = png() + index = [e['suggestedHumanReadableName'] for e in export.entries].index('Outbound footer ja') + export.files[export.entries[index]['exportedFileName']] = good[:-9] + self.assertFailed('png-truncated', export) + + def test_unsupported_depth_fails_closed(self): + export = Export().add_required() + export.files[export.entries[0]['exportedFileName']] = png(depth=16) + self.assertFailed('unsupported-depth', export) + + def test_export_failure_and_missing_manifest(self): + def failing(bundle, destination, deadline): + raise ev.EvidenceError('export-failed', 'xcresulttool export failed') + self.assertFailed('export-failed', failing) + self.tearDown_output() + self.assertFailed('missing-file', lambda bundle, destination, deadline: None) + + def test_traversal_names_rejected(self): + for bad in ('../escape.png', '/etc/passwd', 'sub/dir.png', '.hidden', 'manifest.json', '..', 'a\x00b', ''): + with self.subTest(name=bad): + self.tearDown_output() + export = Export() + export.entries.append({'suggestedHumanReadableName': 'x', 'exportedFileName': bad, 'deviceId': 'D'}) + self.assertFailed('unsafe-path', export) + + def test_symlink_attachment_rejected(self): + outside = self.root / 'secret.png' + outside.write_bytes(png()) + + def export(bundle, destination, deadline): + os.symlink(outside, os.path.join(destination, 'link')) + os.symlink('real', os.path.join(destination, 'inside')) + Path(destination, 'real').write_bytes(png()) + with open(os.path.join(destination, 'manifest.json'), 'w') as handle: + json.dump([{'attachments': [{'suggestedHumanReadableName': 'x', 'exportedFileName': 'link', 'deviceId': 'D'}]}], handle) + self.assertFailed('unsafe-path', export) + self.tearDown_output() + + def inside(bundle, destination, deadline): + export(bundle, destination, deadline) + with open(os.path.join(destination, 'manifest.json'), 'w') as handle: + json.dump([{'attachments': [{'suggestedHumanReadableName': 'x', 'exportedFileName': 'inside', 'deviceId': 'D'}]}], handle) + self.assertFailed('unsafe-path', inside) + + def test_manifest_schema_and_bounds(self): + def manifest_only(content): + def export(bundle, destination, deadline): + with open(os.path.join(destination, 'manifest.json'), 'w') as handle: + json.dump(content, handle) + return export + self.assertFailed('manifest-schema', manifest_only({'not': 'a list'})) + self.tearDown_output() + self.assertFailed('manifest-schema', manifest_only([{'attachments': [{'suggestedHumanReadableName': 1}]}])) + self.tearDown_output() + many = [{'suggestedHumanReadableName': 'n', 'exportedFileName': f'f{i}', 'deviceId': 'D'} + for i in range(ev.CAPS['attachments'] + 1)] + self.assertFailed('file-count', manifest_only([{'attachments': many}])) + self.tearDown_output() + self.assertFailed('manifest-schema', manifest_only([{'attachments': 'x'}])) + + def test_duplicate_exported_file_name_rejected(self): + export = Export().add_required() + export.entries.append(dict(export.entries[0])) + self.assertFailed('duplicate-file', export) + + def test_too_many_images_rejected(self): + export = Export().add_required() + for i in range(ev.CAPS['images']): + export.add(f'extra {i}', png()) + self.assertFailed('file-count', export) + + def test_time_cap(self): + class Expired(ev.Deadline): + def check(self): + raise ev.EvidenceError('time-cap', 'evidence export exceeded its time cap') + export = Export().add_required() + with self.assertRaises(ev.EvidenceError): + ev.build_evidence("b", str(self.root / "stage"), SOURCE, {}, export_fn=export, runner=runner, deadline=Expired(1)) + self.assertEqual([p.name for p in self.root.iterdir() if p.name.startswith('.export-')], []) + + def test_existing_output_is_not_overwritten(self): + self.output.mkdir(parents=True) + (self.output / 'keep').write_text('x') + with self.assertRaises(ev.EvidenceError): + self.publish(Export().add_required()) + self.assertEqual([p.name for p in self.output.iterdir()], ['keep']) + + def test_environment_validation(self): + self.assertFailed('environment', Export().add_required(), '{"bad key": 1}') + self.tearDown_output() + self.assertFailed('environment', Export().add_required(), '{"k": {"nested": 1}}') + self.tearDown_output() + self.assertFailed('environment', Export().add_required(), 'not json') + self.tearDown_output() + self.assertFailed('environment', Export().add_required(), '{"k": "' + 'x' * ev.CAPS['environment_bytes'] + '"}') + + def test_failure_json_is_bounded(self): + def failing(bundle, destination, deadline): + raise ev.EvidenceError('export-failed', 'm' * 5000) + self.assertFalse(self.publish(failing)) + self.assertLessEqual(len(self.failure()['message']), ev.CAPS['text']) + self.assertEqual(self.failure()['status'], 'failed') + + def crash(bundle, destination, deadline): + raise RuntimeError('secret /private/path') + self.tearDown_output() + self.assertFalse(self.publish(crash)) + self.assertEqual(self.failure()['code'], 'internal-error') + self.assertNotIn('secret', json.dumps(self.failure())) + + +class MainTests(unittest.TestCase): + def test_source_must_be_full_sha(self): + with self.assertRaises(SystemExit) as caught: + ev.main(['--result-bundle', 'x', '--output', 'y', '--source', 'abc']) + self.assertEqual(caught.exception.code, 2) + + def test_missing_arguments(self): + with self.assertRaises(SystemExit) as caught: + ev.main(['--output', 'y']) + self.assertEqual(caught.exception.code, 2) + + +if __name__ == '__main__': + unittest.main() From f406571d15da1d48c69681e9c8f4c47ca8767d41 Mon Sep 17 00:00:00 2001 From: tkgstrator <29420801+tkgstrator@users.noreply.github.com> Date: Fri, 23 Oct 2026 13:38:16 +0900 Subject: [PATCH 4/7] test(plugins): capture the initial approval overview --- InterceptorUITests/AutomationUITests.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/InterceptorUITests/AutomationUITests.swift b/InterceptorUITests/AutomationUITests.swift index 8c150f2..a5f0f2f 100644 --- a/InterceptorUITests/AutomationUITests.swift +++ b/InterceptorUITests/AutomationUITests.swift @@ -1339,6 +1339,7 @@ extension AutomationUITests { tapEnabled(app) let form = scrollContainer(app, "plugins.approval.form") XCTAssertTrue(form.waitForExistence(timeout: 5)) + attachScreen("Outbound overview \(tag)", japanese: japanese, app: app) for entry in Self.outboundBindings { let identifier = "plugins.approval.outbound." + entry.binding let elements = { self.outboundElements(identifier, in: form) } From 8ed0981e4310777546ccb16ad448fcb33a326e10 Mon Sep 17 00:00:00 2001 From: tkgstrator <29420801+tkgstrator@users.noreply.github.com> Date: Fri, 23 Oct 2026 13:49:12 +0900 Subject: [PATCH 5/7] fix(ci): preserve screenshot EXIF orientation in WebP evidence --- scripts/export-ui-evidence.py | 26 ++++++++++++++++++++++---- scripts/tests/test_ui_evidence.py | 21 +++++++++++++++++++++ 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/scripts/export-ui-evidence.py b/scripts/export-ui-evidence.py index c3361a4..ffd23c4 100644 --- a/scripts/export-ui-evidence.py +++ b/scripts/export-ui-evidence.py @@ -20,6 +20,7 @@ "dimension": 8192, "pixels": 16 * 1024 * 1024, "icc_bytes": 1024 * 1024, + "exif_bytes": 64 * 1024, "png_chunks": 4096, "output_bytes": 96 * 1024 * 1024, "geometry_bytes": 8 * 1024, @@ -78,7 +79,7 @@ def inspect_png(data): if not data.startswith(PNG_SIGNATURE): raise EvidenceError("not-png", "attachment is not a PNG") pos, chunks, seen = len(PNG_SIGNATURE), [], {} - ihdr = icc_raw = None + ihdr = icc_raw = exif = None color_chunks = {} while True: if len(chunks) >= CAPS["png_chunks"]: @@ -106,6 +107,10 @@ def inspect_png(data): raise EvidenceError("dimension-cap", "PNG dimensions exceed caps") elif kind == b"iCCP": icc_raw = body + elif kind == b"eXIf": + if exif is not None or length > CAPS["exif_bytes"] or body[:4] not in (b"II*\0", b"MM\0*"): + raise EvidenceError("exif-metadata", "unsupported PNG EXIF metadata") + exif = body elif kind in (b"sRGB", b"gAMA", b"cHRM"): color_chunks[kind] = body pos = end + 4 @@ -156,7 +161,7 @@ def inspect_png(data): policy = "standard-srgb" else: raise EvidenceError("ambiguous-color", "PNG has no explicit color metadata") - return {"width": width, "height": height, "has_alpha": color_type == 6, "policy": policy, "icc": icc} + return {"width": width, "height": height, "has_alpha": color_type == 6, "policy": policy, "icc": icc, "exif": exif} # ---------------------------------------------------------------- WebP conversion @@ -204,11 +209,19 @@ def convert_to_lossless_webp(png_bytes, info, destination): raise EvidenceError("ambiguous-color", "decoded ICC profile differs from the PNG chunk") if info["policy"] == "standard-srgb" and source_icc: raise EvidenceError("ambiguous-color", "unexpected ICC profile") + source_exif = source.info.get("exif", b"") + if source_exif.removeprefix(b"Exif\0\0") != (info["exif"] or b""): + raise EvidenceError("exif-metadata", "decoded EXIF differs from PNG metadata") + orientation = source.getexif().get(274, 1) + if type(orientation) is not int or orientation not in range(1, 9): + raise EvidenceError("exif-metadata", "invalid EXIF orientation") rgba = source.convert("RGBA") source_pixels = rgba.tobytes() save_args = {"format": "WEBP", "lossless": True, "exact": True, "quality": 100, "method": 6} if info["policy"] == "icc": save_args["icc_profile"] = info["icc"] + if source_exif: + save_args["exif"] = source_exif rgba.save(destination, **save_args) with open(destination, "rb") as handle: encoded = handle.read(CAPS["encoded_bytes"] + 1) @@ -224,10 +237,14 @@ def convert_to_lossless_webp(png_bytes, info, destination): output_icc = output.info.get("icc_profile") if (output_icc if info["policy"] == "icc" else (output_icc or None)) != (info["icc"] if info["policy"] == "icc" else None): raise EvidenceError("webp-profile", "WebP ICC profile differs from the PNG") + output_exif = output.info.get("exif", b"") + if output_exif.removeprefix(b"Exif\0\0") != (info["exif"] or b"") or output.getexif().get(274, 1) != orientation: + raise EvidenceError("webp-exif", "WebP EXIF metadata or orientation differs from the PNG") output_pixels = output.convert("RGBA").tobytes() if output_pixels != source_pixels: raise EvidenceError("webp-pixels", "WebP pixels differ from the PNG (including RGB under alpha)") - return {"sha256": sha256(encoded), "bytes": len(encoded)} + return {"sha256": sha256(encoded), "bytes": len(encoded), "exif_orientation": orientation, + "exif_sha256": sha256(info["exif"]) if info["exif"] is not None else None} # ---------------------------------------------------------------- manifest handling @@ -531,7 +548,8 @@ def build_evidence(bundle, staging, source, environment, export_fn=xcresult_expo total += result["bytes"] if total > CAPS["output_bytes"]: raise EvidenceError("output-bytes", "verified output exceeds the byte cap") - record.update(webp_sha256=result["sha256"], webp_bytes=result["bytes"], verified_lossless_exact=True) + record.update(webp_sha256=result["sha256"], webp_bytes=result["bytes"], verified_lossless_exact=True, + exif_sha256=result["exif_sha256"], exif_orientation=result["exif_orientation"]) os.remove(item["path"]) # the verified WebP replaces the exported PNG item["data"] = None records.append(record) diff --git a/scripts/tests/test_ui_evidence.py b/scripts/tests/test_ui_evidence.py index ff4b0a5..0d2f841 100644 --- a/scripts/tests/test_ui_evidence.py +++ b/scripts/tests/test_ui_evidence.py @@ -179,6 +179,27 @@ def convert(self, data): result = ev.convert_to_lossless_webp(data, ev.inspect_png(data), dest) return dest, result + def test_exif_orientation_and_pixels_survive_without_rotation(self): + from PIL import ImageOps + for orientation in range(1, 9): + exif = Image.Exif() + exif[274] = orientation + data = png(extra=[(b'eXIf', exif.tobytes()[6:])]) + dest, result = self.convert(data) + with Image.open(dest) as output: + self.assertEqual(output.size, (WIDTH, HEIGHT)) + self.assertEqual(output.getexif()[274], orientation) + self.assertEqual(output.info['exif'].removeprefix(b'Exif\0\0'), exif.tobytes()[6:]) + self.assertEqual(ImageOps.exif_transpose(output).size, + (HEIGHT, WIDTH) if orientation in (5, 6, 7, 8) else (WIDTH, HEIGHT)) + self.assertEqual(result['exif_orientation'], orientation) + + def test_invalid_exif_orientation_rejected(self): + exif = Image.Exif() + exif[274] = 9 + with self.assertRaises(ev.EvidenceError): + self.convert(png(extra=[(b'eXIf', exif.tobytes()[6:])])) + def test_transparent_rgba_and_icc_roundtrip(self): pixels = [bytes((10, 20, 30, 0)), bytes((255, 0, 0, 0)), bytes((1, 2, 3, 128)), bytes((9, 8, 7, 255))] * 3 data = png(pixels=pixels) From 4a18c550e31ec5699c927bc2b6f2459b160529d4 Mon Sep 17 00:00:00 2001 From: tkgstrator <29420801+tkgstrator@users.noreply.github.com> Date: Fri, 23 Oct 2026 13:57:03 +0900 Subject: [PATCH 6/7] revert: remove unrelated outbound approval UI verification --- .github/workflows/ios.yml | 71 -- Interceptor/Localizable.xcstrings | 4 +- .../PluginPackageApprovalView.swift | 2 +- InterceptorUITests/AutomationUITests.swift | 161 ----- README.md | 14 - scripts/ci-plugin-repository-fixture.py | 34 +- scripts/export-ui-evidence.py | 625 ------------------ scripts/requirements-visual.txt | 5 - .../tests/test_plugin_repository_fixture.py | 66 +- scripts/tests/test_ui_evidence.py | 553 ---------------- 10 files changed, 8 insertions(+), 1527 deletions(-) delete mode 100644 scripts/export-ui-evidence.py delete mode 100644 scripts/requirements-visual.txt delete mode 100644 scripts/tests/test_ui_evidence.py diff --git a/.github/workflows/ios.yml b/.github/workflows/ios.yml index 80eb570..00cba46 100644 --- a/.github/workflows/ios.yml +++ b/.github/workflows/ios.yml @@ -89,20 +89,6 @@ jobs: with: bun-version: 1.4.2 - - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6 - if: ${{ (needs['ci-change-scope'].result != 'success' || needs['ci-change-scope'].outputs.docs_only != 'true') }} - with: - python-version: '3.13.9' - - - name: Install visual test tools - if: ${{ (needs['ci-change-scope'].result != 'success' || needs['ci-change-scope'].outputs.docs_only != 'true') }} - run: | - # Owned venv: only hash-pinned wheels, no dependency resolution, no system site-packages. - rm -rf "$RUNNER_TEMP/visual-tools" - python -m venv "$RUNNER_TEMP/visual-tools" - "$RUNNER_TEMP/visual-tools/bin/python" -m pip install --require-hashes --only-binary=:all: --no-deps -r scripts/requirements-visual.txt - "$RUNNER_TEMP/visual-tools/bin/python" -c 'import pathlib; p = pathlib.Path("scripts/export-ui-evidence.py"); compile(p.read_text(), str(p), "exec")' - - name: Verify native repository contract if: ${{ (needs['ci-change-scope'].result != 'success' || needs['ci-change-scope'].outputs.docs_only != 'true') }} run: | @@ -167,13 +153,10 @@ jobs: operation: cleanup - name: Build and run unit and UI tests - id: ui_tests if: ${{ (needs['ci-change-scope'].result != 'success' || needs['ci-change-scope'].outputs.docs_only != 'true') }} run: | set -o pipefail python3 -m unittest discover -s scripts/tests -p test_plugin_repository_fixture.py -v - "$RUNNER_TEMP/visual-tools/bin/python" -m unittest discover -s scripts/tests -p test_native_visual_regression.py -v - "$RUNNER_TEMP/visual-tools/bin/python" -m unittest discover -s scripts/tests -p test_ui_evidence.py -v NSUnbufferedIO=YES python3 scripts/ci-simulator-start-worker.py python3 scripts/ci-plugin-repository-fixture.py \ --work-dir "$RUNNER_TEMP/plugin-repository-fixture" -- xcodebuild test \ -project Interceptor.xcodeproj -scheme Interceptor \ @@ -221,48 +204,6 @@ jobs: trap 'exit 143' TERM wait "$build_pid" - - name: Collect UI evidence environment - # Must run before simulator cleanup: the device disappears afterwards. - id: ui_environment - if: ${{ (needs['ci-change-scope'].result != 'success' || needs['ci-change-scope'].outputs.docs_only != 'true') && (always()) }} - env: - TEST_OUTCOME: ${{ steps.ui_tests.outcome }} - run: | - "$RUNNER_TEMP/visual-tools/bin/python" - <<'PY' || echo '{"environment_unavailable": true}' > "$RUNNER_TEMP/ui-evidence-environment.json" - import json, os, subprocess - temp = os.environ["RUNNER_TEMP"] - env = {"test_outcome": os.environ.get("TEST_OUTCOME", "unknown")} - udid = os.environ.get("SIMULATOR_UUID", "") - try: - devices = json.loads(subprocess.run(["xcrun", "simctl", "--set", os.environ["CI_SIMULATOR_DEVICE_SET"], "list", "devices", "--json"], - check=True, capture_output=True, text=True, timeout=60).stdout)["devices"] - for runtime, items in devices.items(): - for item in items: - if item.get("udid") == udid: - env.update(simulator_runtime=runtime, simulator_name=item.get("name", ""), - simulator_state=item.get("state", ""), simulator_device_type=item.get("deviceTypeIdentifier", "")) - except Exception as error: - env["simulator_lookup_error"] = type(error).__name__ - try: - env["xcode"] = subprocess.run(["xcodebuild", "-version"], check=True, capture_output=True, text=True, timeout=60).stdout.replace("\n", " ").strip() - except Exception as error: - env["xcode_error"] = type(error).__name__ - json.dump(env, open(os.path.join(temp, "ui-evidence-environment.json"), "w")) - PY - - - name: Export verified UI evidence - # Immediately after XCTest and before any publishing. A missing or incomplete - # result bundle (build failure, cancellation) yields a failure manifest, never evidence. - id: ui_evidence - if: ${{ (needs['ci-change-scope'].result != 'success' || needs['ci-change-scope'].outputs.docs_only != 'true') && (always()) }} - run: | - rm -rf "$RUNNER_TEMP/ui-evidence" - "$RUNNER_TEMP/visual-tools/bin/python" scripts/export-ui-evidence.py \ - --result-bundle "$RUNNER_TEMP/Interceptor.xcresult" \ - --output "$RUNNER_TEMP/ui-evidence" \ - --source "$GITHUB_SHA" \ - --environment "$RUNNER_TEMP/ui-evidence-environment.json" - - name: Clean up dedicated iPhone simulator if: ${{ (needs['ci-change-scope'].result != 'success' || needs['ci-change-scope'].outputs.docs_only != 'true') && (always()) }} run: | @@ -289,18 +230,6 @@ jobs: if-no-files-found: ignore retention-days: 1 - - name: Save verified UI evidence - # Compact lossless WebP and manifest only; raw diagnostics are never exported here. - # The source originals remain solely in the xcresult. Evidence is valid only with - # manifest.json status "complete"; failure.json means unverified. - if: ${{ (needs['ci-change-scope'].result != 'success' || needs['ci-change-scope'].outputs.docs_only != 'true') && (always()) }} - uses: actions/upload-artifact@v4 - with: - name: ui-evidence - path: ${{ runner.temp }}/ui-evidence/ - if-no-files-found: warn - retention-days: 1 - - name: Docs-only exemption if: ${{ needs['ci-change-scope'].result == 'success' && needs['ci-change-scope'].outputs.docs_only == 'true' }} shell: bash diff --git a/Interceptor/Localizable.xcstrings b/Interceptor/Localizable.xcstrings index e46038a..2f123d6 100644 --- a/Interceptor/Localizable.xcstrings +++ b/Interceptor/Localizable.xcstrings @@ -4704,13 +4704,13 @@ "en" : { "stringUnit" : { "state" : "translated", - "value" : "Any readable data, including sign-in information, and captured headers or JSON data may be sent to these fixed servers. POST and PUT requests may update data on the external server." + "value" : "Any readable data, including sign-in information, may be sent to these APIs." } }, "ja" : { "stringUnit" : { "state" : "translated", - "value" : "読み取りを許可したデータは、認証情報も含め、取得したヘッダーやJSONデータとして固定の外部サーバーへ送信される可能性があります。POSTやPUTでは外部サーバー上のデータが更新される場合があります。" + "value" : "読み取りを許可したデータは、認証情報も含めて外部APIへ送信される可能性があります。" } } } diff --git a/Interceptor/Views/Automation/PluginPackageApprovalView.swift b/Interceptor/Views/Automation/PluginPackageApprovalView.swift index ef2989f..62dff24 100644 --- a/Interceptor/Views/Automation/PluginPackageApprovalView.swift +++ b/Interceptor/Views/Automation/PluginPackageApprovalView.swift @@ -59,7 +59,7 @@ struct PluginPackageApprovalView: View { if let endpoint = package.manifest.outbound[binding] { VStack(alignment: .leading, spacing: 4) { Text(verbatim: binding).font(.headline) - Text(verbatim: endpoint.method + " " + endpoint.url).font(.footnote).textSelection(.enabled) + Text(verbatim: "GET " + endpoint.url).font(.footnote).textSelection(.enabled) LabeledContent("AUTO_APPROVAL_OUTBOUND_HEADERS") { if endpoint.headers.isEmpty { Text("AUTO_READ_NONE") diff --git a/InterceptorUITests/AutomationUITests.swift b/InterceptorUITests/AutomationUITests.swift index a5f0f2f..8992726 100644 --- a/InterceptorUITests/AutomationUITests.swift +++ b/InterceptorUITests/AutomationUITests.swift @@ -1294,164 +1294,3 @@ extension AutomationUITests { return String(identifier[identifier.index(identifier.startIndex, offsetBy: Self.searchRowPrefix.count) ..< bar]) } } - -// MARK: - Outbound approval methods and consent - -extension AutomationUITests { - /// Identities and bytes of the derived `outbound/approval.json` served by scripts/ci-plugin-repository-fixture.py - /// (derived from multi-file-hooks.json; `outboundRevision` is the SHA-256 of the exact served package bytes). - private static let outboundID = "3C0B5B0E-6D1F-4E57-9A52-7E1D4B8F2A61" - private static let outboundRevision = "af80907085f19584e78617f982be2e57ec6994e1373541ef2b7fa80b77d5e802" - private static let outboundBindings: [(binding: String, method: String, request: String, headers: String?)] = [ - ("lookup", "GET", "GET https://api.example.com/v1/profile", nil), - ("post", "POST", "POST https://api.example.com/v1/records", "authorization, content-type"), - ("put", "PUT", "PUT https://api.example.com/v1/records/latest", "content-type"), - ] - private static let outboundFooters = [ - "en": "Any readable data, including sign-in information, and captured headers or JSON data may be sent to these fixed servers. POST and PUT requests may update data on the external server.", - "ja": "読み取りを許可したデータは、認証情報も含め、取得したヘッダーやJSONデータとして固定の外部サーバーへ送信される可能性があります。POSTやPUTでは外部サーバー上のデータが更新される場合があります。", - ] - private static let outboundNoHeaders = ["en": "No traffic data", "ja": "通信データなし"] - - @MainActor - func testOutboundApprovalMethodsAndConsentInEnglishAndJapanese() async { - guard let repositoryURL = await requiredRepositoryURL() else { return } - // Same fixed same-origin derivation as the browser catalog; the ownership guard above ran on /repository.json. - let outboundURL = repositoryURL.deletingLastPathComponent().appendingPathComponent("outbound/repository.json") - let device = XCUIDevice.shared - let owned: UIDeviceOrientation = UIDevice.current.userInterfaceIdiom == .pad ? .landscapeLeft : .portrait - let previous = device.orientation - device.orientation = owned - defer { device.orientation = previous.isValidInterfaceOrientation ? previous : .portrait } - for japanese in [false, true] { - let tag = japanese ? "ja" : "en" - let app = launch(japanese: japanese, suite: "Interceptor.UITests.\(UUID().uuidString)") - defer { app.terminate() } - openPlugins(app, japanese: japanese) - addRepository(outboundURL, app: app) - openCategory(app, id: "category:Requests") - openCatalogPackage(Self.outboundID, app: app) - enqueueGet(app) - openQueue(app) - confirmQueue(app) - assertEnabled(false, app: app) - - tapEnabled(app) - let form = scrollContainer(app, "plugins.approval.form") - XCTAssertTrue(form.waitForExistence(timeout: 5)) - attachScreen("Outbound overview \(tag)", japanese: japanese, app: app) - for entry in Self.outboundBindings { - let identifier = "plugins.approval.outbound." + entry.binding - let elements = { self.outboundElements(identifier, in: form) } - XCTAssertTrue(revealFully(elements, in: form), "\(entry.binding) must be fully visible") - let texts = outboundTexts(elements()) - XCTAssertTrue(texts.contains(entry.request), "\(entry.binding) shows exactly \(entry.request); saw \(texts)") - XCTAssertTrue(texts.contains(entry.binding)) - for other in ["GET", "POST", "PUT"] where other != entry.method { - XCTAssertFalse(texts.contains { $0.hasPrefix(other + " https://") }, "\(entry.binding) has one method") - } - if let headers = entry.headers { - XCTAssertTrue(texts.contains { $0.contains(headers) }, "\(entry.binding) declares \(headers); saw \(texts)") - XCTAssertFalse(texts.contains { $0.contains(Self.outboundNoHeaders[tag]!) }) - } else { - XCTAssertTrue(texts.contains { $0.contains(Self.outboundNoHeaders[tag]!) }, "\(entry.binding) declares no headers; saw \(texts)") - } - attachScreen("Outbound \(entry.method) \(tag)", japanese: japanese, app: app) - } - let footerText = Self.outboundFooters[tag]! - let footer = form.staticTexts.matching(NSPredicate(format: "label == %@", footerText)).firstMatch - XCTAssertTrue(revealFully({ footer.exists ? [footer] : [] }, in: form), "the complete localized footer must be fully visible") - XCTAssertEqual(footer.label, footerText) - attachScreen("Outbound footer \(tag)", japanese: japanese, app: app) - - let revision = reach(app.textViews["plugins.approval.revision"], in: form, attempts: 30) - XCTAssertEqual(revision.value as? String, Self.outboundRevision, "approval binds the exact served bytes") - - app.buttons.matching(identifier: "plugins.approval.cancel").firstMatch.tap() - XCTAssertTrue(form.waitForNonExistence(timeout: 5)) - assertEnabled(false, app: app) - tapEnabled(app) - XCTAssertTrue(form.waitForExistence(timeout: 5)) - app.buttons.matching(identifier: "plugins.approval.confirm").firstMatch.tap() - XCTAssertTrue(form.waitForNonExistence(timeout: 5)) - assertEnabled(true, app: app) - } - } - - /// The identifier on the binding's VStack may propagate to its leaves, or the VStack may be one element. - @MainActor - func outboundElements(_ identifier: String, in form: XCUIElement) -> [XCUIElement] { - form.descendants(matching: .any).matching(identifier: identifier).allElementsBoundByIndex.filter(\.exists) - } - - /// Every label/value of the elements and their static-text and text-view descendants (selectable text may be a text view). - @MainActor - func outboundTexts(_ elements: [XCUIElement]) -> [String] { - var texts: [String] = [] - for element in elements { - texts += [element.label, element.value as? String ?? ""] - for child in element.staticTexts.allElementsBoundByIndex + element.textViews.allElementsBoundByIndex { - texts += [child.label, child.value as? String ?? ""] - } - } - return texts.filter { !$0.isEmpty } - } - - /// Scrolls the real form until all of the elements are inside the unobscured viewport. - @MainActor - func revealFully(_ elements: () -> [XCUIElement], in form: XCUIElement, attempts: Int = 40) -> Bool { - for _ in 0 ..< attempts { - let visible = viewport(form) - let current = elements() - if !current.isEmpty && current.allSatisfy({ !$0.frame.isEmpty && visible.contains($0.frame) }) { return true } - if let first = current.first, first.frame.midY < visible.minY { - form.swipeDown(velocity: .slow) - } else { - form.swipeUp(velocity: .slow) - } - } - return false - } - - /// One full-screen screenshot plus JSON geometry metadata taken from that same image (no extra capture). - @MainActor - func attachScreen(_ name: String, japanese: Bool, app: XCUIApplication) { - let screenshot = XCUIScreen.main.screenshot() - let image = XCTAttachment(screenshot: screenshot) - image.name = name - image.lifetime = .keepAlways - add(image) - - let screen = UIScreen.main - // UIScreen.bounds belongs to the runner, which may use compatibility sizing. - let appFrame = app.frame - let pixels = screenshot.image.cgImage.map { (width: $0.width, height: $0.height) } ?? (width: 0, height: 0) - let orientation = XCUIDevice.shared.orientation - let metadata: [String: Any] = [ - "schemaVersion": 1, - "kind": "interceptor-ui-screen", - "scale": Double(screen.scale), - "screenPointWidth": Double(appFrame.width), - "screenPointHeight": Double(appFrame.height), - "imagePixelWidth": pixels.width, - "imagePixelHeight": pixels.height, - "osVersion": UIDevice.current.systemVersion, - "deviceModel": ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"] ?? UIDevice.current.model, - "orientation": orientation.isLandscape ? "landscape" : "portrait", - "locale": japanese ? "ja_JP" : "en_US", - ] - XCTAssertGreaterThan(pixels.width, 0, "screenshot must expose a CGImage") - let expected = [Double(appFrame.width * screen.scale), Double(appFrame.height * screen.scale)].sorted() - for (actualEdge, expectedEdge) in zip([Double(pixels.width), Double(pixels.height)].sorted(), expected) { - XCTAssertEqual(actualEdge, expectedEdge, accuracy: 1, "\(name) geometry must match the image") - } - guard let data = try? JSONSerialization.data(withJSONObject: metadata, options: [.sortedKeys]) else { - XCTFail("geometry metadata for \(name) is not serializable") - return - } - let geometry = XCTAttachment(data: data, uniformTypeIdentifier: "public.json") - geometry.name = name + ".geometry" - geometry.lifetime = .keepAlways - add(geometry) - } -} diff --git a/README.md b/README.md index 56a239b..eb765df 100644 --- a/README.md +++ b/README.md @@ -108,20 +108,6 @@ fresh iPhone simulator for each run. Test results and logs are uploaded to the `simulator-results` artifact only when the simulator job fails, and are kept for one day. -After the tests, `scripts/export-ui-evidence.py` (run from a hash-pinned Pillow -12.3.0 virtual environment under `RUNNER_TEMP`) exports the XCTest screenshot -attachments from the result bundle and publishes them in the one-day -`ui-evidence` artifact on both success and failure. The artifact holds only -verified lossless WebP files (exact RGBA, ICC profile and dimensions, with -source hashes) and `manifest.json`; no raw diagnostics are included, and the -original PNGs remain only in the `xcresult`. The eight required screenshots -(`Outbound GET/POST/PUT/footer` in `en` and `ja`) must each have a paired -`.geometry` JSON whose display scale is observed from the device, not assumed. -Evidence is valid only when `manifest.json` has `"status": "complete"`; a -`failure.json` (missing or incomplete result bundle, corrupt, unsupported or -out-of-bounds images, build failure or cancellation) means unverified and is -never a pass. - CI requires the repository secret `QUANTUMLEAP_READ_TOKEN`, a GitHub token with read access to `qtmleap/QuantumLeap`. For a dedicated CI credential, prefer a fine-grained token limited to that repository with **Contents: read-only**. diff --git a/scripts/ci-plugin-repository-fixture.py b/scripts/ci-plugin-repository-fixture.py index 221bdb5..1f7df12 100644 --- a/scripts/ci-plugin-repository-fixture.py +++ b/scripts/ci-plugin-repository-fixture.py @@ -33,17 +33,6 @@ REPOSITORY_EXPIRES_AT = '2026-12-30T00:00:00Z' DERIVED_BROWSER_PACKAGE = '/browser/target-hosts.json' DERIVED_BROWSER_REPOSITORY = '/browser/repository.json' -DERIVED_OUTBOUND_PACKAGE = '/outbound/approval.json' -DERIVED_OUTBOUND_REPOSITORY = '/outbound/repository.json' -OUTBOUND_PACKAGE_ID = '3C0B5B0E-6D1F-4E57-9A52-7E1D4B8F2A61' -OUTBOUND_CATALOG_ID = 'A8F2C6D4-19B3-4C7E-8E05-5D2B9C41F7A3' -OUTBOUND_HOST = 'https://api.example.com' -# Deterministic binding order and declarations shown by the approval UI test. -OUTBOUND_BINDINGS = { - 'lookup': {'url': OUTBOUND_HOST + '/v1/profile', 'method': 'GET', 'headers': []}, - 'post': {'url': OUTBOUND_HOST + '/v1/records', 'method': 'POST', 'headers': ['authorization', 'content-type']}, - 'put': {'url': OUTBOUND_HOST + '/v1/records/latest', 'method': 'PUT', 'headers': ['content-type']}, -} def encoded(value): @@ -133,21 +122,8 @@ def repository_files(token, device): derived_payload = payload | {'id': '532AEB4B-8744-44DA-86CB-DC46E3831F23', 'name': 'Browser catalog fixture', 'plugins': [derived_entry]} files[DERIVED_BROWSER_REPOSITORY] = encoded({'schemaVersion': 1, 'payload': base64.b64encode(encoded(derived_payload)).decode()}) - # A second explicitly synthetic catalog, derived from multi-file-hooks.json, carries schema-2 - # outbound declarations. The original packages and the browser catalog stay byte-identical. - outbound = json.loads(packages['multi-file-hooks.json'][0]) - outbound['manifest'].update(id=OUTBOUND_PACKAGE_ID, name='Outbound approval example', - author='Outbound fixture author', category='Requests', - summary='Derived fixture for outbound method and consent views.', - outbound=json.loads(json.dumps(OUTBOUND_BINDINGS))) - outbound_raw = encoded(outbound) - files[DERIVED_OUTBOUND_PACKAGE] = outbound_raw - outbound_meta = outbound['manifest'] - outbound_entry = {key: outbound_meta[key] for key in ('id', 'name', 'version', 'author', 'summary', 'category')} | { - 'packagePath': 'approval.json', 'sha256': digest(outbound_raw), 'size': len(outbound_raw)} - outbound_payload = payload | {'id': OUTBOUND_CATALOG_ID, 'name': 'Outbound catalog fixture', 'plugins': [outbound_entry]} - files[DERIVED_OUTBOUND_REPOSITORY] = encoded({'schemaVersion': 1, 'payload': base64.b64encode(encoded(outbound_payload)).decode()}) - # Bind readiness only after every derived catalog and package has been added. + # The readiness nonce binds the exact complete allowlist, including the + # derived catalog, rather than only entries in the original catalog. package_digest = digest(encoded({path: digest(raw) for path, raw in files.items()})) files['/__interceptor_fixture'] = encoded({'fixture': MARKER, 'version': 1, 'runToken': token, 'device': device, 'packageDigest': package_digest}) @@ -462,12 +438,10 @@ def interrupted(signum, _): server = FixtureServer(files, tls, options.port) record.update({'repositoryURL': server.base_url + '/repository.json', 'runToken': token, 'packageDigest': package_digest, 'publicFiles': {name: digest(raw) for name, raw in files.items()}, - 'derivedPackages': {DERIVED_BROWSER_PACKAGE: 'multi-file-hooks.json', - DERIVED_OUTBOUND_PACKAGE: 'multi-file-hooks.json'}}) + 'derivedPackages': {DERIVED_BROWSER_PACKAGE: 'multi-file-hooks.json'}}) context = check_ready(server, tls, files['/__interceptor_fixture']) if options.self_test: - for path in (DERIVED_BROWSER_REPOSITORY, DERIVED_BROWSER_PACKAGE, - DERIVED_OUTBOUND_REPOSITORY, DERIVED_OUTBOUND_PACKAGE): + for path in (DERIVED_BROWSER_REPOSITORY, DERIVED_BROWSER_PACKAGE): with urllib.request.urlopen(server.base_url + path, context=context, timeout=2) as response: if response.status != 200 or response.read() != files[path]: raise RuntimeError('Derived browser fixture was not served exactly: ' + path) diff --git a/scripts/export-ui-evidence.py b/scripts/export-ui-evidence.py deleted file mode 100644 index ffd23c4..0000000 --- a/scripts/export-ui-evidence.py +++ /dev/null @@ -1,625 +0,0 @@ -#!/usr/bin/env python3 -"""Export UI screenshots from an xcresult and publish them only as verified lossless WebP. - -Usage: export-ui-evidence.py --result-bundle X.xcresult --output DIR --source SHA [--environment JSON] - -The output directory is created atomically and only after every required image has been -converted and re-verified. On any failure it contains a bounded failure.json and no images. -Exit status: 0 success, 1 evidence failure, 2 usage error. -""" -import argparse, hashlib, json, math, os, re, shutil, stat, struct, subprocess, sys, tempfile, time, zlib - -SCHEMA_VERSION = 1 -PILLOW_VERSION = "12.3.0" -CAPS = { - "manifest_bytes": 4 * 1024 * 1024, - "attachments": 4096, - "images": 64, - "encoded_bytes": 32 * 1024 * 1024, - "image_input_bytes": 128 * 1024 * 1024, - "dimension": 8192, - "pixels": 16 * 1024 * 1024, - "icc_bytes": 1024 * 1024, - "exif_bytes": 64 * 1024, - "png_chunks": 4096, - "output_bytes": 96 * 1024 * 1024, - "geometry_bytes": 8 * 1024, - "nonimage_file_bytes": 256 * 1024 * 1024, - "nonimage_total_bytes": 1024 * 1024 * 1024, - "hash_chunk": 1024 * 1024, - "environment_bytes": 64 * 1024, - "seconds": 600, - "export_seconds": 300, - "text": 200, -} -REQUIRED_NAMES = [f"Outbound {m} {t}" for t in ("en", "ja") for m in ("GET", "POST", "PUT", "footer")] -GEOMETRY_KIND = "interceptor-ui-screen" -GEOMETRY_FIELDS = ("scale", "screenPointWidth", "screenPointHeight", "imagePixelWidth", "imagePixelHeight", - "osVersion", "deviceModel", "orientation", "locale") -PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n" -SAFE_FILENAME = re.compile(r"^[A-Za-z0-9._ -]{1,200}$") - - -class EvidenceError(Exception): - def __init__(self, code, message): - super().__init__(message) - self.code = code - self.message = message - - -class Deadline: - def __init__(self, seconds): - self.end = time.monotonic() + seconds - - def check(self): - if time.monotonic() > self.end: - raise EvidenceError("time-cap", "evidence export exceeded its time cap") - - def remaining(self): - return max(1.0, self.end - time.monotonic()) - - -def sha256(data): - return hashlib.sha256(data).hexdigest() - - -def clean_text(value, limit=None): - limit = limit or CAPS["text"] - if not isinstance(value, str): - return None - return "".join(c if c.isprintable() else "?" for c in value)[:limit] - - -# ---------------------------------------------------------------- PNG inspection - -def inspect_png(data): - """Validate PNG structure and metadata without decoding pixels. Returns a description dict.""" - if len(data) > CAPS["encoded_bytes"]: - raise EvidenceError("encoded-size", "PNG exceeds the encoded size cap") - if not data.startswith(PNG_SIGNATURE): - raise EvidenceError("not-png", "attachment is not a PNG") - pos, chunks, seen = len(PNG_SIGNATURE), [], {} - ihdr = icc_raw = exif = None - color_chunks = {} - while True: - if len(chunks) >= CAPS["png_chunks"]: - raise EvidenceError("png-chunks", "PNG has too many chunks") - if pos + 12 > len(data): - raise EvidenceError("png-truncated", "PNG is truncated") - length, kind = struct.unpack(">I4s", data[pos:pos + 8]) - end = pos + 8 + length - if length > 0x7FFFFFFF or end + 4 > len(data): - raise EvidenceError("png-truncated", "PNG chunk exceeds the file") - body = data[pos + 8:end] - if struct.unpack(">I", data[end:end + 4])[0] != zlib.crc32(data[pos + 4:end]): - raise EvidenceError("png-crc", "PNG chunk CRC mismatch") - if not chunks and kind != b"IHDR": - raise EvidenceError("png-structure", "PNG does not start with IHDR") - chunks.append(kind) - seen[kind] = seen.get(kind, 0) + 1 - if kind == b"IHDR": - if seen[kind] > 1 or length != 13: - raise EvidenceError("png-structure", "invalid PNG IHDR") - ihdr = struct.unpack(">IIBBBBB", body) - # Bound dimensions before any further interpretation or decode. - if not (0 < ihdr[0] <= CAPS["dimension"] and 0 < ihdr[1] <= CAPS["dimension"]) \ - or ihdr[0] * ihdr[1] > CAPS["pixels"]: - raise EvidenceError("dimension-cap", "PNG dimensions exceed caps") - elif kind == b"iCCP": - icc_raw = body - elif kind == b"eXIf": - if exif is not None or length > CAPS["exif_bytes"] or body[:4] not in (b"II*\0", b"MM\0*"): - raise EvidenceError("exif-metadata", "unsupported PNG EXIF metadata") - exif = body - elif kind in (b"sRGB", b"gAMA", b"cHRM"): - color_chunks[kind] = body - pos = end + 4 - if kind == b"IEND": - break - if pos != len(data): - raise EvidenceError("png-structure", "trailing bytes after PNG IEND") - width, height, depth, color_type, compression, filt, interlace = ihdr - if depth != 8: - raise EvidenceError("unsupported-depth", f"unsupported PNG bit depth {depth}") - if color_type not in (2, 6): - raise EvidenceError("unsupported-color-type", f"unsupported PNG color type {color_type}") - if interlace != 0: - raise EvidenceError("unsupported-interlace", "interlaced PNG is unsupported") - for animated in (b"acTL", b"fcTL", b"fdAT"): - if animated in seen: - raise EvidenceError("unsupported-animation", "animated PNG is unsupported") - for ambiguous in (b"tRNS", b"cICP"): - if ambiguous in seen: - raise EvidenceError("ambiguous-color", f"PNG {ambiguous.decode()} chunk is unsupported") - if any(seen.get(kind, 0) > 1 for kind in (b"iCCP", b"sRGB", b"gAMA", b"cHRM")): - raise EvidenceError("ambiguous-color", "duplicate PNG color profile chunk") - if b"sRGB" in color_chunks and color_chunks[b"sRGB"] not in (b"\x00", b"\x01", b"\x02", b"\x03"): - raise EvidenceError("ambiguous-color", "invalid sRGB rendering intent") - expected_srgb = {b"gAMA": struct.pack(">I", 45455), - b"cHRM": struct.pack(">8I", 31270, 32900, 64000, 33000, 30000, 60000, 15000, 6000)} - for kind, expected in expected_srgb.items(): - if kind in color_chunks and (b"sRGB" not in color_chunks or color_chunks[kind] != expected): - raise EvidenceError("ambiguous-color", "unsupported or inconsistent PNG color fallback") - if icc_raw is not None and b"sRGB" in seen: - raise EvidenceError("ambiguous-color", "PNG has both iCCP and sRGB") - icc = None - if icc_raw is not None: - name_end = icc_raw.find(b"\0") - if name_end < 1 or name_end + 2 > len(icc_raw) or icc_raw[name_end + 1] != 0: - raise EvidenceError("ambiguous-color", "invalid iCCP chunk") - inflater = zlib.decompressobj() - try: - icc = inflater.decompress(icc_raw[name_end + 2:], CAPS["icc_bytes"] + 1) - except zlib.error: - raise EvidenceError("ambiguous-color", "invalid iCCP data") - if not icc or len(icc) > CAPS["icc_bytes"] or inflater.unconsumed_tail: - raise EvidenceError("ambiguous-color", "iCCP profile is empty or too large") - if not inflater.eof or inflater.unused_data: - raise EvidenceError("ambiguous-color", "iCCP data is truncated or has trailing bytes") - policy = "icc" - elif b"sRGB" in seen: - policy = "standard-srgb" - else: - raise EvidenceError("ambiguous-color", "PNG has no explicit color metadata") - return {"width": width, "height": height, "has_alpha": color_type == 6, "policy": policy, "icc": icc, "exif": exif} - - -# ---------------------------------------------------------------- WebP conversion - -def load_pillow(): - try: - import PIL - from PIL import Image, features - except ImportError: - raise EvidenceError("pillow-missing", "Pillow is not installed") - if PIL.__version__ != PILLOW_VERSION: - raise EvidenceError("pillow-version", f"Pillow {PILLOW_VERSION} is required") - if not features.check("webp"): - raise EvidenceError("webp-missing", "Pillow lacks WebP support") - Image.MAX_IMAGE_PIXELS = CAPS["pixels"] - return Image, features - - -def webp_chunks(data): - if len(data) < 12 or data[:4] != b"RIFF" or data[8:12] != b"WEBP" \ - or struct.unpack(" CAPS["encoded_bytes"]: - raise EvidenceError("encoded-size", "WebP exceeds the encoded size cap") - kinds = webp_chunks(encoded) - if b"VP8L" not in kinds or b"VP8 " in kinds or b"ANIM" in kinds or b"ANMF" in kinds: - raise EvidenceError("webp-not-lossless", "WebP is not a single lossless frame") - with Image.open(destination) as output: - if output.format != "WEBP" or getattr(output, "n_frames", 1) != 1 or output.size != rgba.size: - raise EvidenceError("webp-mismatch", "WebP dimensions or frames differ") - output.load() - output_icc = output.info.get("icc_profile") - if (output_icc if info["policy"] == "icc" else (output_icc or None)) != (info["icc"] if info["policy"] == "icc" else None): - raise EvidenceError("webp-profile", "WebP ICC profile differs from the PNG") - output_exif = output.info.get("exif", b"") - if output_exif.removeprefix(b"Exif\0\0") != (info["exif"] or b"") or output.getexif().get(274, 1) != orientation: - raise EvidenceError("webp-exif", "WebP EXIF metadata or orientation differs from the PNG") - output_pixels = output.convert("RGBA").tobytes() - if output_pixels != source_pixels: - raise EvidenceError("webp-pixels", "WebP pixels differ from the PNG (including RGB under alpha)") - return {"sha256": sha256(encoded), "bytes": len(encoded), "exif_orientation": orientation, - "exif_sha256": sha256(info["exif"]) if info["exif"] is not None else None} - - -# ---------------------------------------------------------------- manifest handling - -def read_bounded(path, limit, what): - try: - info = os.lstat(path) - except OSError: - raise EvidenceError("missing-file", f"{what} is missing") - if not stat.S_ISREG(info.st_mode): - raise EvidenceError("unsafe-path", f"{what} is not a regular file") - if info.st_size > limit: - raise EvidenceError("encoded-size", f"{what} exceeds its size cap") - with open(path, "rb") as handle: - return handle.read(limit + 1) - - -def safe_export_path(directory, name): - if not isinstance(name, str) or not SAFE_FILENAME.match(name) or name in (".", "..", "manifest.json") \ - or name.startswith("."): - raise EvidenceError("unsafe-path", "exported file name is not a plain file name") - path = os.path.join(directory, name) - if os.path.dirname(os.path.realpath(path)) != os.path.realpath(directory): - raise EvidenceError("unsafe-path", "exported file escapes the export directory") - return path - - -def collect_attachments(directory): - manifest = json.loads(read_bounded(os.path.join(directory, "manifest.json"), CAPS["manifest_bytes"], "manifest.json")) - if not isinstance(manifest, list): - raise EvidenceError("manifest-schema", "manifest is not a list") - attachments, seen = [], set() - for test in manifest: - if not isinstance(test, dict) or not isinstance(test.get("attachments"), list): - raise EvidenceError("manifest-schema", "manifest test entry is malformed") - for entry in test["attachments"]: - if not isinstance(entry, dict) or not isinstance(entry.get("suggestedHumanReadableName"), str) \ - or not isinstance(entry.get("deviceId"), str): - raise EvidenceError("manifest-schema", "manifest attachment entry is malformed") - exported = entry.get("exportedFileName") - path = safe_export_path(directory, exported) - if exported in seen: - raise EvidenceError("duplicate-file", "duplicate exported file name") - seen.add(exported) - if len(attachments) >= CAPS["attachments"]: - raise EvidenceError("file-count", "too many attachments") - attachments.append({"path": path, "entry": entry, "test": test.get("testIdentifier")}) - return attachments - - -def parse_geometry(data, name): - try: - raw = json.loads(data) - except ValueError: - raise EvidenceError("geometry-schema", f"geometry for {name} is not JSON") - if not isinstance(raw, dict) or raw.get("schemaVersion") != 1 or raw.get("kind") != GEOMETRY_KIND: - raise EvidenceError("geometry-schema", f"geometry for {name} has an unexpected schema") - geometry = {} - for key in GEOMETRY_FIELDS: - value = raw.get(key) - if key in ("scale", "screenPointWidth", "screenPointHeight"): - ok = isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value) and 0 < value < 100000 - elif key in ("imagePixelWidth", "imagePixelHeight"): - ok = isinstance(value, int) and not isinstance(value, bool) and 0 < value <= CAPS["dimension"] - else: - ok = isinstance(value, str) and 0 < len(value) <= 64 - if not ok: - raise EvidenceError("geometry-schema", f"geometry for {name} has an invalid {key}") - geometry[key] = value - if geometry["orientation"] not in ("portrait", "landscape"): - raise EvidenceError("geometry-schema", f"geometry for {name} has an invalid orientation") - return geometry - - -def dims_match(width, height, geometry): - pair = sorted((width, height)) - return pair == sorted((geometry["imagePixelWidth"], geometry["imagePixelHeight"])) - - -UUID_PATTERN = r"[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}" - - -def attachment_name_matches(actual, base, extension): - """True for exactly `base` or `base` + Xcode's generated `__` + extension.""" - if actual == base: - return True - return re.fullmatch(re.escape(base) + r"_[0-9]+_" + UUID_PATTERN + re.escape(extension), actual, - re.ASCII) is not None - - -def image_name_matches(actual, name): - return attachment_name_matches(actual, name, ".png") - - -def geometry_name_matches(actual, name): - # Xcode inserts its suffix before the custom extension, independently of the JSON file UTI. - return actual == name + ".geometry" or re.fullmatch( - re.escape(name) + r"_[0-9]+_" + UUID_PATTERN + r"\.geometry", actual, re.ASCII) is not None - - -def stream_hash(path, deadline): - """SHA-256 of a regular file read in bounded chunks; never holds the contents.""" - digest = hashlib.sha256() - with open(path, "rb") as handle: - while True: - deadline.check() - block = handle.read(CAPS["hash_chunk"]) - if not block: - return digest.hexdigest() - digest.update(block) - - -def classify(attachments, deadline): - """Split attachments into PNG images and non-images. - - Images are read whole (strictly capped). Non-images are streamed: only size, sniffed type and hash are - kept, plus the bytes of files small enough to be geometry metadata. Non-images beyond the per-file or - aggregate hashing caps are recorded metadata-only (hash None, explicit skip reason), never failing evidence. - """ - images, others, hashed_total, image_total = [], [], 0, 0 - for item in attachments: - deadline.check() - try: - info = os.lstat(item["path"]) - except OSError: - raise EvidenceError("missing-file", "attachment is missing") - if not stat.S_ISREG(info.st_mode): - raise EvidenceError("unsafe-path", "attachment is not a regular file") - with open(item["path"], "rb") as handle: - head = handle.read(4096) - if head.startswith(PNG_SIGNATURE): - if info.st_size > CAPS["encoded_bytes"]: - raise EvidenceError("encoded-size", "attachment exceeds the encoded size cap") - image_total += info.st_size - if image_total > CAPS["image_input_bytes"]: - raise EvidenceError("input-bytes", "image attachments exceed the aggregate input cap") - item["data"] = read_bounded(item["path"], CAPS["encoded_bytes"], "attachment") - images.append(item) - if len(images) > CAPS["images"]: - raise EvidenceError("file-count", "too many image attachments") - continue - names = (item["entry"]["exportedFileName"], item["entry"]["suggestedHumanReadableName"]) - if any(os.path.splitext(name)[1].lower() in (".png", ".jpg", ".jpeg", ".gif", ".webp", ".heic", ".tif", ".tiff") - for name in names) or head.startswith(b"\xff\xd8\xff"): - raise EvidenceError("unsupported-image", "image attachment is not a supported PNG") - item["size"], item["type"], item["data"] = info.st_size, sniff_type(head), None - if info.st_size <= CAPS["geometry_bytes"]: - item["data"] = read_bounded(item["path"], CAPS["geometry_bytes"], "attachment") - if info.st_size > CAPS["nonimage_file_bytes"]: - item["sha256"], item["skipped"] = None, "file-size-cap" - elif hashed_total + info.st_size > CAPS["nonimage_total_bytes"]: - item["sha256"], item["skipped"] = None, "aggregate-size-cap" - else: - hashed_total += info.st_size - item["sha256"], item["skipped"] = stream_hash(item["path"], deadline), None - others.append(item) - return images, others - - -def sniff_type(data): - head = data[:16].lstrip() - if head[:1] in (b"{", b"["): - return "json" - if data[:3] == b"\xff\xd8\xff": - return "jpeg" - if data[:4] in (b"RIFF", b"%PDF"): - return data[:4].decode("latin1").lower() - try: - data[:4096].decode("utf-8") - return "text" - except UnicodeDecodeError: - return "binary" - - -def check_environment(raw): - if raw is None: - return {} - if len(raw.encode()) > CAPS["environment_bytes"]: - raise EvidenceError("environment", "environment JSON exceeds its size cap") - try: - value = json.loads(raw) - except ValueError: - raise EvidenceError("environment", "environment is not valid JSON") - if not isinstance(value, dict) or len(value) > 64: - raise EvidenceError("environment", "environment must be a small JSON object") - result = {} - for key, item in value.items(): - if not re.match(r"^[A-Za-z0-9_.-]{1,64}$", key) or not isinstance(item, (str, int, float, bool)) \ - or isinstance(item, float) and not math.isfinite(item): - raise EvidenceError("environment", "environment entries must be simple scalars") - result[key] = clean_text(item, 256) if isinstance(item, str) else item - return result - - -def tool_versions(runner): - versions = {"python": sys.version.split()[0]} - try: - Image, features = load_pillow() - import PIL - versions.update(pillow=PIL.__version__, libwebp=features.version("webp")) - except EvidenceError: - raise - try: - out = runner(["xcrun", "xcresulttool", "version"]) - versions["xcresulttool"] = clean_text(out.strip().splitlines()[0]) if out.strip() else None - except Exception: - versions["xcresulttool"] = None - return versions - - -def run_command(args, timeout=30): - return subprocess.run(args, check=True, capture_output=True, text=True, timeout=timeout).stdout - - -def xcresult_export(bundle, destination, deadline): - try: - subprocess.run(["xcrun", "xcresulttool", "export", "attachments", "--path", bundle, - "--output-path", destination], check=True, capture_output=True, - timeout=min(CAPS["export_seconds"], deadline.remaining())) - except subprocess.TimeoutExpired: - raise EvidenceError("export-timeout", "xcresulttool export timed out") - except (subprocess.CalledProcessError, OSError): - raise EvidenceError("export-failed", "xcresulttool export failed") - - -# ---------------------------------------------------------------- orchestration - -def build_evidence(bundle, staging, source, environment, export_fn=xcresult_export, runner=run_command, deadline=None): - """Populate staging with verified WebP files and manifest.json. Raises EvidenceError on any problem.""" - deadline = deadline or Deadline(CAPS["seconds"]) - load_pillow() - exported = tempfile.mkdtemp(prefix=".export-", dir=os.path.dirname(os.path.abspath(staging))) - try: - export_fn(bundle, exported, deadline) - deadline.check() - attachments = collect_attachments(exported) - images, others = classify(attachments, deadline) - - geometries, required_items = {}, {} - for name in REQUIRED_NAMES: - matches = [i for i in images if image_name_matches(i["entry"]["suggestedHumanReadableName"], name)] - geo_matches = [i for i in attachments - if geometry_name_matches(i["entry"]["suggestedHumanReadableName"], name)] - if len(matches) != 1: - raise EvidenceError("required-missing" if not matches else "required-duplicate", - f"required screenshot '{name}' found {len(matches)} times") - if len(geo_matches) != 1: - raise EvidenceError("required-missing" if not geo_matches else "required-duplicate", - f"geometry for '{name}' found {len(geo_matches)} times") - if geo_matches[0] in images: - raise EvidenceError("geometry-schema", f"geometry for {name} is an image") - geo_data = geo_matches[0]["data"] - if geo_data is None: - raise EvidenceError("geometry-schema", f"geometry for {name} is too large") - geometries[name] = parse_geometry(geo_data, name) - if geo_matches[0]["entry"]["deviceId"] != matches[0]["entry"]["deviceId"]: - raise EvidenceError("geometry-device", f"geometry for {name} is from another device") - required_items[id(matches[0])] = name - - # Observed scale per device, only where every observation agrees. - scales = {} - for name, item in ((n, next(i for i in images if id(i) in required_items and required_items[id(i)] == n)) - for n in REQUIRED_NAMES): - scales.setdefault(item["entry"]["deviceId"], set()).add(geometries[name]["scale"]) - - records, total, version_info = [], 0, tool_versions(runner) - for index, item in enumerate(sorted(images, key=lambda i: i["entry"]["suggestedHumanReadableName"] + i["entry"]["exportedFileName"])): - deadline.check() - data, entry = item["data"], item["entry"] - info = inspect_png(data) - name = required_items.get(id(item)) - record = {"index": index, "required_name": name, "source_png_sha256": sha256(data), - "attachment_name": clean_text(entry["suggestedHumanReadableName"]), - "test_identifier": clean_text(item["test"]), - "source_png_bytes": len(data), "pixel_width": info["width"], "pixel_height": info["height"], - "has_alpha": info["has_alpha"], "color_policy": info["policy"], - "icc_sha256": sha256(info["icc"]) if info["icc"] else None, - "device_id": clean_text(entry["deviceId"]), "device_name": clean_text(entry.get("deviceName")), - "configuration": clean_text(entry.get("configurationName")), - "associated_with_failure": bool(entry.get("isAssociatedWithFailure")), - "timestamp": entry.get("timestamp") if isinstance(entry.get("timestamp"), (int, float)) else None, - "original_disposition": "retained-only-in-xcresult"} - if name: - geometry = geometries[name] - if not dims_match(info["width"], info["height"], geometry): - raise EvidenceError("geometry-mismatch", f"geometry for {name} does not match the image") - record.update(display_scale=geometry["scale"], display_scale_source="observed", geometry=geometry) - else: - device_scales = scales.get(entry["deviceId"], set()) - # Element screenshots can be cropped; the observed display scale is still device-wide. - if len(device_scales) == 1: - record.update(display_scale=next(iter(device_scales)), - display_scale_source="inferred-from-same-device-required-geometry") - else: - record.update(display_scale=None, display_scale_source="unknown") - output_name = f"{index:03d}-{record['source_png_sha256'][:16]}.webp" - record["file"] = output_name - destination = os.path.join(staging, output_name) - record.update(webp_sha256=None) - result = convert_to_lossless_webp(data, info, destination) - total += result["bytes"] - if total > CAPS["output_bytes"]: - raise EvidenceError("output-bytes", "verified output exceeds the byte cap") - record.update(webp_sha256=result["sha256"], webp_bytes=result["bytes"], verified_lossless_exact=True, - exif_sha256=result["exif_sha256"], exif_orientation=result["exif_orientation"]) - os.remove(item["path"]) # the verified WebP replaces the exported PNG - item["data"] = None - records.append(record) - - non_images = [{"index": i, "sha256": o["sha256"], "bytes": o["size"], "type": o["type"], "hash_skipped": o["skipped"], - "published": False} for i, o in enumerate(others)] - manifest = {"schemaVersion": SCHEMA_VERSION, "status": "complete", "source": source, - "required_names": REQUIRED_NAMES, "images": records, "non_image_attachments": non_images, - "toolchain": version_info, "environment": environment, - "webp_options": {"lossless": True, "exact": True, "method": 6, "icc": "retained exact bytes"}, - "total_webp_bytes": total} - with open(os.path.join(staging, "manifest.json"), "w") as handle: - json.dump(manifest, handle, indent=2, sort_keys=True) # completion marker, written last - finally: - shutil.rmtree(exported, ignore_errors=True) - - -def publish(output, source, environment_raw, bundle, **kwargs): - """Stage and atomically promote. Returns True on success; failure.json is published on failure.""" - output = os.path.abspath(output) - parent = os.path.dirname(output) - os.makedirs(parent, exist_ok=True) - if os.path.lexists(output): - raise EvidenceError("output-exists", "output path already exists") - staging = tempfile.mkdtemp(prefix=".staging-", dir=parent) - try: - build_evidence(bundle, staging, source, check_environment(environment_raw), **kwargs) - os.rename(staging, output) - return True - except BaseException as error: - shutil.rmtree(staging, ignore_errors=True) - if isinstance(error, EvidenceError): - code, message = error.code, error.message[:CAPS["text"]] - else: - code, message = "internal-error", type(error).__name__ - failure = tempfile.mkdtemp(prefix=".failure-", dir=parent) - with open(os.path.join(failure, "failure.json"), "w") as handle: - json.dump({"schemaVersion": SCHEMA_VERSION, "status": "failed", "source": source, - "code": code, "message": message}, handle, indent=2, sort_keys=True) - os.rename(failure, output) - if isinstance(error, (KeyboardInterrupt, SystemExit)): - raise - return False - - -def main(argv=None): - parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) - parser.add_argument("--result-bundle", required=True) - parser.add_argument("--output", required=True) - parser.add_argument("--source", required=True) - parser.add_argument("--environment", help="JSON object (inline or a path to a JSON file)") - args = parser.parse_args(argv) - if not re.fullmatch(r"[0-9a-f]{40}", args.source): - parser.error("--source must be a 40-character lowercase git SHA") - environment = args.environment - if environment is not None and not environment.lstrip().startswith("{"): - try: - environment = read_bounded(environment, CAPS["environment_bytes"], "environment file").decode() - except (EvidenceError, UnicodeDecodeError) as error: - parser.error(f"unreadable --environment: {getattr(error, 'message', 'invalid text')}") - try: - ok = publish(args.output, args.source, environment, args.result_bundle) - except EvidenceError as error: - print(f"error: {error.message}", file=sys.stderr) - return 1 - if not ok: - print("error: UI evidence export failed; see failure.json", file=sys.stderr) - return 1 - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/scripts/requirements-visual.txt b/scripts/requirements-visual.txt deleted file mode 100644 index 769e363..0000000 --- a/scripts/requirements-visual.txt +++ /dev/null @@ -1,5 +0,0 @@ -# Hash-pinned for `pip install --require-hashes --only-binary=:all: --no-deps`. -# Hashes are the official PyPI macOS cp313 wheels (x86_64 and arm64) for 12.3.0. -Pillow==12.3.0 \ - --hash=sha256:7a743ff716f746fc19a9557f60dab1600d4613255f8a7aeb3cdde4db7eb15a66 \ - --hash=sha256:d69141514cc30b774ceea5e3ed3a6635c8d8a96edf664689b890f4089111fb35 diff --git a/scripts/tests/test_plugin_repository_fixture.py b/scripts/tests/test_plugin_repository_fixture.py index 68ab510..d665699 100644 --- a/scripts/tests/test_plugin_repository_fixture.py +++ b/scripts/tests/test_plugin_repository_fixture.py @@ -294,60 +294,6 @@ def test_browser_variant_is_explicitly_derived_and_keeps_sdk_catalog_unchanged(s self.assertTrue({file for phases in rule['hooks'].values() for file in phases.values()} <= set(package['sourceFiles'])) - BASE_HASHES = { - '/request-summary.json': 'f7985fe4eb7a5d60bcc69fc682b0f853e0c22a7a2a52bab84b1e1bccebe2ed12', - '/response-details.json': '841f9582b395c81964f1a875980f102aa3c2942079f8e42c32571725e8761210', - '/multi-file-hooks.json': '6f007a8e930949b7e0094b59b17cbfb82128eaf196156edd9901495f543440fa', - '/approval-limits.json': '80b1908a2ddeef087e5b419bc07dae8ac2c61279f10eed40b934e814ae9b50af', - '/repository.json': '8b73cee200453d88937e75252721418d4ce63784a2d2222f61f6564764cb8eae', - '/browser/target-hosts.json': '30fd5c5184f04d685115d3fee7c4c0c330c77fb09ba4eb964d9bb6c859bb59ae', - '/browser/repository.json': '9e262cd56b3ff8e41afd8675d70e156e872fe1c2b471af41c801d4cfbd8a67f4', - } - - def test_original_served_bytes_match_hardcoded_pre_outbound_hashes(self): - files, _ = fixture.repository_files('this-run', DEVICE) - for path, expected in self.BASE_HASHES.items(): - self.assertEqual(fixture.digest(files[path]), expected, path) - - def test_outbound_variant_is_explicitly_derived_with_three_deterministic_bindings(self): - files, _ = fixture.repository_files('this-run', DEVICE) - index = json.loads(base64.b64decode(json.loads(files['/outbound/repository.json'])['payload'], validate=True)) - self.assertEqual(index['name'], 'Outbound catalog fixture') - self.assertEqual(len(index['plugins']), 1) - entry = index['plugins'][0] - self.assertEqual(entry['packagePath'], 'approval.json') - raw = files['/outbound/' + entry['packagePath']] - package = json.loads(raw) - manifest = package['manifest'] - self.assertEqual(manifest['name'], 'Outbound approval example') - self.assertEqual(entry['sha256'], fixture.digest(raw)) - self.assertEqual(entry['size'], len(raw)) - for key in ('id', 'name', 'version', 'author', 'summary', 'category'): - self.assertEqual(entry[key], manifest[key]) - self.assertEqual(manifest['outbound'], { - 'lookup': {'url': 'https://api.example.com/v1/profile', 'method': 'GET', 'headers': []}, - 'post': {'url': 'https://api.example.com/v1/records', 'method': 'POST', 'headers': ['authorization', 'content-type']}, - 'put': {'url': 'https://api.example.com/v1/records/latest', 'method': 'PUT', 'headers': ['content-type']}, - }) - sdk = json.loads(files['/multi-file-hooks.json']) - self.assertNotIn(manifest['id'], {sdk['manifest']['id'], 'E9472B70-2DB2-4F4C-A291-33F5FEF88519'}) - self.assertEqual(package['sourceFiles'], sdk['sourceFiles']) - self.assertNotIn('outbound', sdk['manifest']) - self.assertNotEqual(index['id'], '57414817-0F72-40BA-A27C-535B784BEE00') - self.assertNotEqual(index['id'], '532AEB4B-8744-44DA-86CB-DC46E3831F23') - - def test_native_outbound_expectations_match_served_package(self): - import re - files, _ = fixture.repository_files('this-run', DEVICE) - native = (ROOT / 'InterceptorUITests/AutomationUITests.swift').read_text() - revision = re.search(r'outboundRevision = "([a-f0-9]{64})"', native) - identifier = re.search(r'outboundID = "([0-9A-F-]{36})"', native) - self.assertIsNotNone(revision) - self.assertEqual(revision.group(1), fixture.digest(files['/outbound/approval.json'])) - self.assertEqual(identifier.group(1), json.loads(files['/outbound/approval.json'])['manifest']['id']) - for binding in json.loads(files['/outbound/approval.json'])['manifest']['outbound'].values(): - self.assertIn('"%s %s"' % (binding['method'], binding['url']), native) - def test_readiness_digest_binds_every_allowlisted_catalog_and_package(self): files, bound_digest = fixture.repository_files('this-run', DEVICE) payload_files = {path: fixture.digest(raw) for path, raw in files.items() if path != '/__interceptor_fixture'} @@ -355,11 +301,6 @@ def test_readiness_digest_binds_every_allowlisted_catalog_and_package(self): changed = dict(payload_files) changed['/browser/target-hosts.json'] = '0' * 64 self.assertNotEqual(bound_digest, fixture.digest(fixture.encoded(changed))) - self.assertIn('/outbound/repository.json', payload_files) - self.assertIn('/outbound/approval.json', payload_files) - changed = dict(payload_files) - changed['/outbound/approval.json'] = '0' * 64 - self.assertNotEqual(bound_digest, fixture.digest(fixture.encoded(changed))) def test_browser_derivation_targets_the_exact_file_independent_of_rule_order(self): packages = fixture.load_packages() @@ -386,16 +327,11 @@ def test_browser_variant_is_served_over_https_and_written_under_owned_public_dir record = json.loads((work / 'fixture-run.json').read_text()) self.assertIn('/browser/repository.json', record['publicFiles']) self.assertIn('/browser/target-hosts.json', record['publicFiles']) - self.assertEqual(record['derivedPackages'], {'/browser/target-hosts.json': 'multi-file-hooks.json', - '/outbound/approval.json': 'multi-file-hooks.json'}) - self.assertIn('/outbound/repository.json', record['publicFiles']) - self.assertIn('/outbound/approval.json', record['publicFiles']) + self.assertEqual(record['derivedPackages'], {'/browser/target-hosts.json': 'multi-file-hooks.json'}) self.assertTrue((work / 'public/browser/repository.json').is_file()) served = {(entry['path'], entry['status']) for entry in record['requests']['entries']} self.assertIn(('/browser/repository.json', 200), served) self.assertIn(('/browser/target-hosts.json', 200), served) - self.assertIn(('/outbound/repository.json', 200), served) - self.assertIn(('/outbound/approval.json', 200), served) self.assertTrue(record['serverStopped']) self.assertTrue(record['privateKeysRemoved']) diff --git a/scripts/tests/test_ui_evidence.py b/scripts/tests/test_ui_evidence.py deleted file mode 100644 index 0d2f841..0000000 --- a/scripts/tests/test_ui_evidence.py +++ /dev/null @@ -1,553 +0,0 @@ -import importlib.util -import json -import os -from pathlib import Path -import struct -import tempfile -import unittest -import zlib - -from PIL import Image - -ROOT = Path(__file__).resolve().parents[2] -spec = importlib.util.spec_from_file_location('ui_evidence', ROOT / 'scripts/export-ui-evidence.py') -ev = importlib.util.module_from_spec(spec) -spec.loader.exec_module(ev) - -SOURCE = 'a' * 40 -ICC = b'\x00\x00\x02\x0cappl' + bytes(range(256)) * 2 # opaque bytes: only byte-exact retention is under test -WIDTH, HEIGHT = 4, 3 - - -def chunk(kind, body): - return struct.pack('>I', len(body)) + kind + body + struct.pack('>I', zlib.crc32(kind + body)) - - -def png(pixels=None, width=WIDTH, height=HEIGHT, color_type=6, depth=8, interlace=0, extra=(), icc=ICC, srgb=False): - """Build a PNG by hand so metadata chunks are exactly controlled.""" - channels = 4 if color_type == 6 else 3 - if pixels is None: - pixels = [bytes((x * 40, y * 60, 200, 255 if channels == 4 else 0)[:channels]) - for y in range(height) for x in range(width)] - rows = b''.join(b'\0' + b''.join(pixels[y * width:(y + 1) * width]) for y in range(height)) - out = ev.PNG_SIGNATURE + chunk(b'IHDR', struct.pack('>IIBBBBB', width, height, depth, color_type, 0, 0, interlace)) - if srgb: - out += chunk(b'sRGB', b'\0') - elif icc is not None: - out += chunk(b'iCCP', b'profile\0\0' + zlib.compress(icc)) - for kind, body in extra: - out += chunk(kind, body) - return out + chunk(b'IDAT', zlib.compress(rows)) + chunk(b'IEND', b'') - - -def geometry(scale=2, width=WIDTH, height=HEIGHT): - return json.dumps({'schemaVersion': 1, 'kind': ev.GEOMETRY_KIND, 'scale': scale, - 'screenPointWidth': width / scale, 'screenPointHeight': height / scale, - 'imagePixelWidth': width, 'imagePixelHeight': height, 'osVersion': '26.0', - 'deviceModel': 'iPhone', 'orientation': 'portrait', 'locale': 'en_US'}).encode() - - -class Export: - """Synthetic xcresulttool export: files plus a manifest.json in xcresulttool's schema.""" - - def __init__(self, device='DEVICE-A', scale=2): - self.files, self.entries = {}, [] - self.device, self.scale = device, scale - - def add(self, name, data, exported=None, device=None): - exported = exported or f'att-{len(self.entries)}' - self.files[exported] = data - self.entries.append({'suggestedHumanReadableName': name, 'exportedFileName': exported, - 'deviceId': device or self.device, 'deviceName': 'iPhone', - 'isAssociatedWithFailure': False, 'timestamp': 1.5}) - return exported - - def add_required(self, image=None, skip=(), device=None, scale=None): - for name in ev.REQUIRED_NAMES: - if name in skip: - continue - self.add(name, image if image is not None else png(), device=device) - self.add(name + '.geometry', geometry(scale or self.scale), device=device) - return self - - def __call__(self, bundle, destination, deadline): - for name, data in self.files.items(): - path = os.path.join(destination, name) - os.makedirs(os.path.dirname(path), exist_ok=True) - with open(path, 'wb') as handle: - handle.write(data) - with open(os.path.join(destination, 'manifest.json'), 'w') as handle: - json.dump([{'testIdentifier': 'T/test', 'attachments': self.entries}], handle) - - -def runner(args, timeout=30): - return 'xcresulttool version 1\n' - - -class EvidenceBase(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - self.root = Path(self.tmp.name) - self.output = self.root / 'out' / 'evidence' - - def publish(self, export, env=None): - return ev.publish(str(self.output), SOURCE, env, 'unused.xcresult', export_fn=export, runner=runner) - - def manifest(self): - return json.loads((self.output / 'manifest.json').read_text()) - - def failure(self): - return json.loads((self.output / 'failure.json').read_text()) - - def assertFailed(self, code, export, env=None): - self.assertFalse(self.publish(export, env)) - self.assertEqual(sorted(p.name for p in self.output.iterdir()), ['failure.json']) - self.assertEqual(self.failure()['code'], code) - self.assertEqual(sorted(p.name for p in self.output.parent.iterdir()), ['evidence'], 'staging leaked') - - -class PngInspectionTests(unittest.TestCase): - def test_rgba_with_icc(self): - info = ev.inspect_png(png()) - self.assertEqual((info['width'], info['height'], info['has_alpha'], info['policy']), (WIDTH, HEIGHT, True, 'icc')) - self.assertEqual(info['icc'], ICC) - - def test_rgb_srgb(self): - info = ev.inspect_png(png(color_type=2, srgb=True)) - self.assertFalse(info['has_alpha']) - self.assertEqual((info['policy'], info['icc']), ('standard-srgb', None)) - - def assertRejected(self, code, data): - with self.assertRaises(ev.EvidenceError) as caught: - ev.inspect_png(data) - self.assertEqual(caught.exception.code, code) - - def test_rejects_unsupported_or_ambiguous(self): - self.assertRejected('unsupported-depth', png(depth=16)) - self.assertRejected('unsupported-color-type', png(color_type=3)) - self.assertRejected('unsupported-interlace', png(interlace=1)) - self.assertRejected('unsupported-animation', png(extra=[(b'acTL', b'\0' * 8)])) - self.assertRejected('ambiguous-color', png(extra=[(b'tRNS', b'\0' * 6)])) - self.assertRejected('ambiguous-color', png(icc=None)) - self.assertRejected('ambiguous-color', png(extra=[(b'sRGB', b'\0')])) - self.assertRejected('not-png', b'GIF89a' + b'\0' * 32) - - def test_rejects_corruption(self): - good = png() - corrupt = bytearray(good) - corrupt[-1] ^= 0xFF - self.assertRejected('png-crc', bytes(corrupt)) - self.assertRejected('png-truncated', good[:-7]) - self.assertRejected('png-truncated', good[:20]) - self.assertRejected('png-structure', good + b'junk') - - def test_color_fallback_must_match_explicit_srgb(self): - gamma = (b'gAMA', struct.pack('>I', 45455)) - chroma = (b'cHRM', struct.pack('>8I', 31270, 32900, 64000, 33000, 30000, 60000, 15000, 6000)) - self.assertEqual(ev.inspect_png(png(srgb=True, extra=[gamma, chroma]))['policy'], 'standard-srgb') - for chunks in ([(b'sRGB', b'')], [(b'sRGB', b'\x04')], [gamma], [chroma], - [(b'sRGB', b'\0'), (b'gAMA', struct.pack('>I', 100000))], - [(b'sRGB', b'\0'), (b'cHRM', b'\0' * 32)]): - self.assertRejected('ambiguous-color', png(icc=None, extra=chunks)) - - def test_icc_zlib_must_be_complete_and_exact(self): - def with_icc(body): - return ev.PNG_SIGNATURE + chunk(b'IHDR', struct.pack('>IIBBBBB', WIDTH, HEIGHT, 8, 6, 0, 0, 0)) \ - + chunk(b'iCCP', b'profile\0\0' + body) + chunk(b'IEND', b'') - stream = zlib.compress(ICC) - self.assertEqual(ev.inspect_png(with_icc(stream))['icc'], ICC) - self.assertRejected('ambiguous-color', with_icc(stream + b'trailing')) - self.assertRejected('ambiguous-color', with_icc(stream[:-6])) - self.assertRejected('ambiguous-color', with_icc(stream[:-1])) - - def test_dimension_and_size_caps(self): - header = ev.PNG_SIGNATURE + chunk(b'IHDR', struct.pack('>IIBBBBB', ev.CAPS['dimension'] + 1, 1, 8, 6, 0, 0, 0)) - self.assertRejected('dimension-cap', header) - header = ev.PNG_SIGNATURE + chunk(b'IHDR', struct.pack('>IIBBBBB', 5000, 5000, 8, 6, 0, 0, 0)) - self.assertRejected('dimension-cap', header) - self.assertRejected('encoded-size', b'\0' * (ev.CAPS['encoded_bytes'] + 1)) - - -class ConversionTests(unittest.TestCase): - def setUp(self): - self.tmp = tempfile.TemporaryDirectory() - self.addCleanup(self.tmp.cleanup) - - def convert(self, data): - dest = os.path.join(self.tmp.name, 'out.webp') - result = ev.convert_to_lossless_webp(data, ev.inspect_png(data), dest) - return dest, result - - def test_exif_orientation_and_pixels_survive_without_rotation(self): - from PIL import ImageOps - for orientation in range(1, 9): - exif = Image.Exif() - exif[274] = orientation - data = png(extra=[(b'eXIf', exif.tobytes()[6:])]) - dest, result = self.convert(data) - with Image.open(dest) as output: - self.assertEqual(output.size, (WIDTH, HEIGHT)) - self.assertEqual(output.getexif()[274], orientation) - self.assertEqual(output.info['exif'].removeprefix(b'Exif\0\0'), exif.tobytes()[6:]) - self.assertEqual(ImageOps.exif_transpose(output).size, - (HEIGHT, WIDTH) if orientation in (5, 6, 7, 8) else (WIDTH, HEIGHT)) - self.assertEqual(result['exif_orientation'], orientation) - - def test_invalid_exif_orientation_rejected(self): - exif = Image.Exif() - exif[274] = 9 - with self.assertRaises(ev.EvidenceError): - self.convert(png(extra=[(b'eXIf', exif.tobytes()[6:])])) - - def test_transparent_rgba_and_icc_roundtrip(self): - pixels = [bytes((10, 20, 30, 0)), bytes((255, 0, 0, 0)), bytes((1, 2, 3, 128)), bytes((9, 8, 7, 255))] * 3 - data = png(pixels=pixels) - dest, result = self.convert(data) - with Image.open(dest) as out: - self.assertEqual(out.format, 'WEBP') - self.assertEqual(out.size, (WIDTH, HEIGHT)) - self.assertEqual(out.info.get('icc_profile'), ICC) - # RGB under fully transparent alpha must survive (exact=True). - self.assertEqual(out.convert('RGBA').tobytes(), b''.join(pixels)) - self.assertEqual(result['bytes'], os.path.getsize(dest)) - self.assertIn(b'VP8L', ev.webp_chunks(Path(dest).read_bytes())) - - def test_rgb_srgb_has_no_profile(self): - dest, _ = self.convert(png(color_type=2, srgb=True)) - with Image.open(dest) as out: - self.assertIsNone(out.info.get('icc_profile')) - self.assertEqual(out.convert('RGBA').getpixel((0, 0))[3], 255) - - def test_webp_chunk_validation(self): - with self.assertRaises(ev.EvidenceError): - ev.webp_chunks(b"RIFF\x10\0\0\0WEBP") - with self.assertRaises(ev.EvidenceError): - ev.webp_chunks(b'not webp at all') - - -class GeometryTests(unittest.TestCase): - def test_parse_valid(self): - self.assertEqual(ev.parse_geometry(geometry(3), 'n')['scale'], 3) - - def test_parse_invalid(self): - good = json.loads(geometry()) - for patch in ({'scale': 0}, {'scale': True}, {'scale': float('nan')}, {'imagePixelWidth': 99999}, - {'imagePixelWidth': 1.5}, {'orientation': 'flat'}, {'kind': 'other'}, {'schemaVersion': 2}, - {'locale': ''}): - with self.assertRaises(ev.EvidenceError, msg=str(patch)): - ev.parse_geometry(json.dumps({**good, **patch}).encode(), 'n') - for data in (b'not json', b'[]'): - with self.assertRaises(ev.EvidenceError): - ev.parse_geometry(data, 'n') - - def test_dims_match_allows_rotation_only(self): - geo = json.loads(geometry()) - self.assertTrue(ev.dims_match(HEIGHT, WIDTH, geo)) - self.assertFalse(ev.dims_match(WIDTH, HEIGHT + 1, geo)) - - -class PublishTests(EvidenceBase): - def test_aggregate_image_input_is_bounded(self): - original = ev.CAPS['image_input_bytes'] - self.addCleanup(ev.CAPS.__setitem__, 'image_input_bytes', original) - ev.CAPS['image_input_bytes'] = len(png()) * 7 - self.assertFailed('input-bytes', Export().add_required()) - - def test_damaged_supplementary_image_cannot_be_a_nonimage(self): - export = Export().add_required() - export.add('Supplementary.png', b'broken PNG', exported='broken.png') - self.assertFailed('unsupported-image', export) - - def test_success_maps_metadata_and_verifies_all_required(self): - export = Export().add_required() - self.assertTrue(self.publish(export, '{"runtime": "iOS 26.0", "build": 7}')) - self.assertEqual(sorted(p.name for p in self.output.parent.iterdir()), ['evidence']) - manifest = self.manifest() - self.assertEqual(manifest['status'], 'complete') - self.assertEqual(manifest['source'], SOURCE) - self.assertEqual(manifest['environment'], {'runtime': 'iOS 26.0', 'build': 7}) - self.assertEqual(manifest['required_names'], ev.REQUIRED_NAMES) - self.assertEqual(len(ev.REQUIRED_NAMES), 8) - images = manifest['images'] - self.assertEqual(sorted(i['required_name'] for i in images), sorted(ev.REQUIRED_NAMES)) - for record in images: - self.assertTrue(record['attachment_name']) - self.assertEqual(record['test_identifier'], 'T/test') - self.assertEqual(record['display_scale'], 2) - self.assertEqual(record['display_scale_source'], 'observed') - self.assertEqual(record['device_id'], 'DEVICE-A') - self.assertTrue(record['verified_lossless_exact']) - self.assertEqual(record['color_policy'], 'icc') - self.assertEqual(record['original_disposition'], 'retained-only-in-xcresult') - self.assertTrue((self.output / record['file']).is_file()) - with Image.open(self.output / record['file']) as out: - self.assertEqual(out.info.get('icc_profile'), ICC) - self.assertEqual(len(manifest['non_image_attachments']), 8) - self.assertTrue(all(not n['published'] for n in manifest['non_image_attachments'])) - published = sorted(p.name for p in self.output.iterdir()) - self.assertEqual(published, sorted([i['file'] for i in images] + ['manifest.json'])) - self.assertFalse(any(n.endswith('.png') for n in published)) - - def test_observed_scale_is_per_device_not_hardcoded(self): - export = Export(device='A', scale=3) - for name in ev.REQUIRED_NAMES[:4]: - export.add(name, png(), device='A') - export.add(name + '.geometry', geometry(3), device='A') - for name in ev.REQUIRED_NAMES[4:]: - export.add(name, png(), device='B') - export.add(name + '.geometry', geometry(2), device='B') - self.assertTrue(self.publish(export)) - got = {i['required_name']: (i['device_id'], i['display_scale']) for i in self.manifest()['images']} - for name in ev.REQUIRED_NAMES[:4]: - self.assertEqual(got[name], ('A', 3)) - for name in ev.REQUIRED_NAMES[4:]: - self.assertEqual(got[name], ('B', 2)) - - def test_extra_images_scale_inferred_or_unknown(self): - export = Export().add_required() - export.add('Extra same device', png(width=2, height=2)) - export.add('Extra other device', png(), device='DEVICE-Z') - export.add('notes.txt', b'hello') - self.assertTrue(self.publish(export)) - manifest = self.manifest() - extras = {i['device_id']: i for i in manifest['images'] if i['required_name'] is None} - self.assertEqual(extras['DEVICE-A']['display_scale'], 2) - self.assertEqual(extras['DEVICE-A']['display_scale_source'], 'inferred-from-same-device-required-geometry') - self.assertIsNone(extras['DEVICE-Z']['display_scale']) - self.assertEqual(extras['DEVICE-Z']['display_scale_source'], 'unknown') - self.assertEqual(len(manifest['images']), 10) - self.assertEqual(len(manifest['non_image_attachments']), 9) - - def test_real_xcode_suffixed_names_accepted(self): - uuid = 'D95B5FA3-05D1-4FB4-9079-47538FDE159A' - export = Export() - for n, name in enumerate(ev.REQUIRED_NAMES): - export.add(f'{name}_{n}_{uuid}.png', png(), exported=f'{uuid[:-2]}{n:02d}.png') - export.add(f'{name}_{n}_{uuid}.geometry', geometry(), exported=f'g{n}.json') - self.assertTrue(self.publish(export)) - self.assertEqual(sorted(i['required_name'] for i in self.manifest()['images']), sorted(ev.REQUIRED_NAMES)) - - def test_malformed_suffixes_rejected(self): - uuid = 'D95B5FA3-05D1-4FB4-9079-47538FDE159A' - base = 'Outbound GET en' - for bad in (f'{base}_x_{uuid}.png', f'{base}__{uuid}.png', f'{base}_0_{uuid[:-1]}.png', f'{base}_0_{uuid}', - f'{base}_0_{uuid}.json', f'{base}_0_{uuid}.png.png', f'{base} _0_{uuid}.png', - f'{base}_0_{uuid}.PNG', f'{base}.png', f'{base}_0_{uuid}\n.png', f'{base}_٣_{uuid}.png'): - self.assertFalse(ev.image_name_matches(bad, base), bad) - self.assertTrue(ev.image_name_matches(f'{base}_12_{uuid}.png', base)) - self.assertTrue(ev.image_name_matches(base, base)) - self.assertTrue(ev.geometry_name_matches(f'{base}_0_{uuid}.geometry', base)) - self.assertFalse(ev.geometry_name_matches(f'{base}.geometry_0_{uuid}.json', base)) - self.assertFalse(ev.geometry_name_matches(f'{base}.geometry_0_{uuid}.png', base)) - self.assertFalse(ev.geometry_name_matches(f'{base}_0_{uuid}.json', base)) - - def test_ambiguous_suffixed_and_plain_duplicate_fails(self): - export = Export().add_required() - export.add('Outbound GET en_0_D95B5FA3-05D1-4FB4-9079-47538FDE159A.png', png()) - self.assertFailed('required-duplicate', export) - - def test_large_nonimage_is_streamed_not_read_or_rejected(self): - export = Export().add_required() - export.add('screen recording', b'\0\0\0\x18ftypmp42' + b'\0' * 64) - original = ev.read_bounded - calls = [] - ev.read_bounded = lambda path, limit, what: (calls.append(limit), original(path, limit, what))[1] - self.addCleanup(setattr, ev, 'read_bounded', original) - small = dict(ev.CAPS) - self.addCleanup(lambda: (ev.CAPS.clear(), ev.CAPS.update(small))) - ev.CAPS['encoded_bytes'] = 1024 * 1024 # recording below exceeds this yet must not fail evidence - ev.CAPS['hash_chunk'] = 4096 - export.files['att-%d' % (len(export.entries) - 1)] = b'v' * (2 * 1024 * 1024) - self.assertTrue(self.publish(export)) - entry = [n for n in self.manifest()['non_image_attachments'] if n['bytes'] == 2 * 1024 * 1024][0] - import hashlib - self.assertEqual(entry['sha256'], hashlib.sha256(b'v' * (2 * 1024 * 1024)).hexdigest()) - self.assertIsNone(entry['hash_skipped']) - self.assertNotIn(2 * 1024 * 1024, calls) - self.assertEqual(sorted(p.name for p in self.output.iterdir() if not p.name.endswith('.webp')), ['manifest.json']) - - def test_nonimage_beyond_caps_is_metadata_only(self): - export = Export().add_required() - export.add('big.mov', b'x' * 5000) - export.add('big2.mov', b'y' * 3000) - small = dict(ev.CAPS) - self.addCleanup(lambda: (ev.CAPS.clear(), ev.CAPS.update(small))) - ev.CAPS['nonimage_file_bytes'] = 4000 - self.assertTrue(self.publish(export)) - skipped = [n for n in self.manifest()['non_image_attachments'] if n['bytes'] in (5000, 3000)] - self.assertEqual({n['bytes']: n['hash_skipped'] for n in skipped}, {5000: 'file-size-cap', 3000: None}) - self.assertIsNone([n for n in skipped if n['bytes'] == 5000][0]['sha256']) - - def test_oversize_png_still_rejected(self): - export = Export().add_required() - export.files[export.entries[0]['exportedFileName']] = ev.PNG_SIGNATURE + b'\0' * ev.CAPS['encoded_bytes'] - self.assertFailed('encoded-size', export) - - def test_attachment_cap_is_realistic(self): - self.assertEqual(ev.CAPS['attachments'], 4096) - - def test_each_missing_required_name_or_geometry_fails(self): - for name in ev.REQUIRED_NAMES: - with self.subTest(missing=name): - self.tearDown_output() - self.assertFailed('required-missing', self.partial(skip_image=name)) - for name in ev.REQUIRED_NAMES: - with self.subTest(missing_geometry=name): - self.tearDown_output() - self.assertFailed('required-missing', self.partial(skip_geometry=name)) - - def tearDown_output(self): - import shutil - shutil.rmtree(self.output.parent, ignore_errors=True) - - def partial(self, skip_image=None, skip_geometry=None): - export = Export() - for name in ev.REQUIRED_NAMES: - if name != skip_image: - export.add(name, png()) - if name != skip_geometry: - export.add(name + '.geometry', geometry()) - return export - - def test_duplicate_required_fails(self): - export = Export().add_required() - export.add('Outbound GET en', png()) - self.assertFailed('required-duplicate', export) - - def test_geometry_mismatch_and_other_device_fail(self): - export = Export().add_required() - export.files[export.entries[1]['exportedFileName']] = geometry(2, WIDTH + 1, HEIGHT) - self.assertFailed('geometry-mismatch', export) - self.tearDown_output() - export = Export().add_required() - export.entries[1]['deviceId'] = 'OTHER' - self.assertFailed('geometry-device', export) - - def test_corrupt_second_image_promotes_nothing(self): - export = Export().add_required() - good = png() - index = [e['suggestedHumanReadableName'] for e in export.entries].index('Outbound footer ja') - export.files[export.entries[index]['exportedFileName']] = good[:-9] - self.assertFailed('png-truncated', export) - - def test_unsupported_depth_fails_closed(self): - export = Export().add_required() - export.files[export.entries[0]['exportedFileName']] = png(depth=16) - self.assertFailed('unsupported-depth', export) - - def test_export_failure_and_missing_manifest(self): - def failing(bundle, destination, deadline): - raise ev.EvidenceError('export-failed', 'xcresulttool export failed') - self.assertFailed('export-failed', failing) - self.tearDown_output() - self.assertFailed('missing-file', lambda bundle, destination, deadline: None) - - def test_traversal_names_rejected(self): - for bad in ('../escape.png', '/etc/passwd', 'sub/dir.png', '.hidden', 'manifest.json', '..', 'a\x00b', ''): - with self.subTest(name=bad): - self.tearDown_output() - export = Export() - export.entries.append({'suggestedHumanReadableName': 'x', 'exportedFileName': bad, 'deviceId': 'D'}) - self.assertFailed('unsafe-path', export) - - def test_symlink_attachment_rejected(self): - outside = self.root / 'secret.png' - outside.write_bytes(png()) - - def export(bundle, destination, deadline): - os.symlink(outside, os.path.join(destination, 'link')) - os.symlink('real', os.path.join(destination, 'inside')) - Path(destination, 'real').write_bytes(png()) - with open(os.path.join(destination, 'manifest.json'), 'w') as handle: - json.dump([{'attachments': [{'suggestedHumanReadableName': 'x', 'exportedFileName': 'link', 'deviceId': 'D'}]}], handle) - self.assertFailed('unsafe-path', export) - self.tearDown_output() - - def inside(bundle, destination, deadline): - export(bundle, destination, deadline) - with open(os.path.join(destination, 'manifest.json'), 'w') as handle: - json.dump([{'attachments': [{'suggestedHumanReadableName': 'x', 'exportedFileName': 'inside', 'deviceId': 'D'}]}], handle) - self.assertFailed('unsafe-path', inside) - - def test_manifest_schema_and_bounds(self): - def manifest_only(content): - def export(bundle, destination, deadline): - with open(os.path.join(destination, 'manifest.json'), 'w') as handle: - json.dump(content, handle) - return export - self.assertFailed('manifest-schema', manifest_only({'not': 'a list'})) - self.tearDown_output() - self.assertFailed('manifest-schema', manifest_only([{'attachments': [{'suggestedHumanReadableName': 1}]}])) - self.tearDown_output() - many = [{'suggestedHumanReadableName': 'n', 'exportedFileName': f'f{i}', 'deviceId': 'D'} - for i in range(ev.CAPS['attachments'] + 1)] - self.assertFailed('file-count', manifest_only([{'attachments': many}])) - self.tearDown_output() - self.assertFailed('manifest-schema', manifest_only([{'attachments': 'x'}])) - - def test_duplicate_exported_file_name_rejected(self): - export = Export().add_required() - export.entries.append(dict(export.entries[0])) - self.assertFailed('duplicate-file', export) - - def test_too_many_images_rejected(self): - export = Export().add_required() - for i in range(ev.CAPS['images']): - export.add(f'extra {i}', png()) - self.assertFailed('file-count', export) - - def test_time_cap(self): - class Expired(ev.Deadline): - def check(self): - raise ev.EvidenceError('time-cap', 'evidence export exceeded its time cap') - export = Export().add_required() - with self.assertRaises(ev.EvidenceError): - ev.build_evidence("b", str(self.root / "stage"), SOURCE, {}, export_fn=export, runner=runner, deadline=Expired(1)) - self.assertEqual([p.name for p in self.root.iterdir() if p.name.startswith('.export-')], []) - - def test_existing_output_is_not_overwritten(self): - self.output.mkdir(parents=True) - (self.output / 'keep').write_text('x') - with self.assertRaises(ev.EvidenceError): - self.publish(Export().add_required()) - self.assertEqual([p.name for p in self.output.iterdir()], ['keep']) - - def test_environment_validation(self): - self.assertFailed('environment', Export().add_required(), '{"bad key": 1}') - self.tearDown_output() - self.assertFailed('environment', Export().add_required(), '{"k": {"nested": 1}}') - self.tearDown_output() - self.assertFailed('environment', Export().add_required(), 'not json') - self.tearDown_output() - self.assertFailed('environment', Export().add_required(), '{"k": "' + 'x' * ev.CAPS['environment_bytes'] + '"}') - - def test_failure_json_is_bounded(self): - def failing(bundle, destination, deadline): - raise ev.EvidenceError('export-failed', 'm' * 5000) - self.assertFalse(self.publish(failing)) - self.assertLessEqual(len(self.failure()['message']), ev.CAPS['text']) - self.assertEqual(self.failure()['status'], 'failed') - - def crash(bundle, destination, deadline): - raise RuntimeError('secret /private/path') - self.tearDown_output() - self.assertFalse(self.publish(crash)) - self.assertEqual(self.failure()['code'], 'internal-error') - self.assertNotIn('secret', json.dumps(self.failure())) - - -class MainTests(unittest.TestCase): - def test_source_must_be_full_sha(self): - with self.assertRaises(SystemExit) as caught: - ev.main(['--result-bundle', 'x', '--output', 'y', '--source', 'abc']) - self.assertEqual(caught.exception.code, 2) - - def test_missing_arguments(self): - with self.assertRaises(SystemExit) as caught: - ev.main(['--output', 'y']) - self.assertEqual(caught.exception.code, 2) - - -if __name__ == '__main__': - unittest.main() From 30b71641fdc145cc424d44a0976c6eff9c54f407 Mon Sep 17 00:00:00 2001 From: tkgstrator <29420801+tkgstrator@users.noreply.github.com> Date: Fri, 23 Oct 2026 15:25:37 +0900 Subject: [PATCH 7/7] feat(plugins): add QuickJS fetch for response hooks --- Interceptor.xcodeproj/project.pbxproj | 1 + .../HTTPPluginFetchDispatcher.swift | 138 +++++ .../HTTPPluginOutboundDispatcher.swift | 3 +- .../HTTPPluginOutboundTransport.swift | 187 ++++++- .../Automation/HTTPPluginProcessor.swift | 228 +++++--- .../HTTPPluginFetchProcessorTests.swift | 289 ++++++++++ InterceptorTests/HTTPPluginFetchTests.swift | 119 ++++ .../HTTPPluginOutboundDispatcherTests.swift | 68 +-- .../HTTPPluginOutboundTransportTests.swift | 158 +++++- .../AutomationCore/PluginOutbound.swift | 45 +- .../JavaScriptExecutor.swift | 96 ++-- .../JavaScriptFetchExecutor.swift | 297 ++++++++++ .../Sources/CQuickJS/bridge.c | 526 ++++++++++++++++-- .../Sources/CQuickJS/include/CQuickJS.h | 31 +- .../PluginOutboundTests.swift | 159 +----- .../JavaScriptFetchTests.swift | 242 ++++++++ .../OutboundRuntimeTests.swift | 207 +------ .../Tests/Fixtures/outbound-conformance.json | 295 ---------- .../plans/2026-10-23-outbound-json-methods.md | 37 -- .../plans/2026-10-23-quickjs-fetch.md | 33 ++ 20 files changed, 2196 insertions(+), 963 deletions(-) create mode 100644 Interceptor/Automation/HTTPPluginFetchDispatcher.swift create mode 100644 InterceptorTests/HTTPPluginFetchProcessorTests.swift create mode 100644 InterceptorTests/HTTPPluginFetchTests.swift create mode 100644 Packages/InterceptorAutomation/Sources/AutomationRuntime/JavaScriptFetchExecutor.swift create mode 100644 Packages/InterceptorAutomation/Tests/AutomationRuntimeTests/JavaScriptFetchTests.swift delete mode 100644 Packages/InterceptorAutomation/Tests/Fixtures/outbound-conformance.json delete mode 100644 docs/superpowers/plans/2026-10-23-outbound-json-methods.md create mode 100644 docs/superpowers/plans/2026-10-23-quickjs-fetch.md diff --git a/Interceptor.xcodeproj/project.pbxproj b/Interceptor.xcodeproj/project.pbxproj index fc0bf2d..b7f3cae 100644 --- a/Interceptor.xcodeproj/project.pbxproj +++ b/Interceptor.xcodeproj/project.pbxproj @@ -105,6 +105,7 @@ Automation/AutomationSharedConfiguration.swift, Automation/HTTPPluginProcessor.swift, Automation/HTTPPluginOutboundDispatcher.swift, + Automation/HTTPPluginFetchDispatcher.swift, Automation/HTTPPluginOutboundTransport.swift, Automation/HTTPPluginOutboundProbe.swift, Automation/TunnelAuthorizationMonitor.swift, diff --git a/Interceptor/Automation/HTTPPluginFetchDispatcher.swift b/Interceptor/Automation/HTTPPluginFetchDispatcher.swift new file mode 100644 index 0000000..2e7bb13 --- /dev/null +++ b/Interceptor/Automation/HTTPPluginFetchDispatcher.swift @@ -0,0 +1,138 @@ +import Foundation + +/// Tracked background runner for fetch-capable hooks. At most one job is active per processor; +/// extras are rejected without queueing. The slot is reserved before the Task exists, so shutdown +/// and an immediately finishing Task are safe in either order. +final class HTTPPluginFetchDispatcher: @unchecked Sendable { + enum Completion: Sendable, Equatable { + case completed + case failed + case cancelled + case rejected + } + + /// Test-only visibility; never receives bodies, tokens or secret-bearing errors. + typealias Observer = @Sendable (Completion) -> Void + + private let lock = NSLock() + private let observer: Observer? + private var active: UUID? + private var task: Task? + private var invalidated = false + private var drainWaiters: [UUID: CheckedContinuation] = [:] + + init(observer: Observer? = nil) { + self.observer = observer + } + + var isActive: Bool { + lock.withLock { !invalidated } + } + + /// `work` returns normally on success and throws on any failure; `CancellationError` maps to `.cancelled`. + /// It must stop its own non-Task resources (the fetch executor) when its Task is cancelled. + @discardableResult + func submit(_ work: @escaping @Sendable () async throws -> Void) -> Bool { + let id = UUID() + let admitted = lock.withLock { + guard !invalidated, active == nil else { return false } + active = id + return true + } + guard admitted else { + observer?(.rejected) + return false + } + let job = Task { [self] in + let completion: Completion + do { + try await work() + completion = Task.isCancelled || !isLive(id) ? .cancelled : .completed + } catch is CancellationError { + completion = .cancelled + } catch { + completion = Task.isCancelled || !isLive(id) ? .cancelled : .failed + } + finish(id, completion) + } + let retained = lock.withLock { + // The Task can finish, or shutdown can run, before this installation. + guard !invalidated, active == id else { return false } + task = job + return true + } + if !retained { + job.cancel() + } + return true + } + + func shutdown() { + let job = lock.withLock { + invalidated = true + return task + } + job?.cancel() + } + + private func isLive(_ id: UUID) -> Bool { + lock.withLock { !invalidated && active == id } + } + + private func finish(_ id: UUID, _ completion: Completion) { + observer?(completion) + let waiters: [CheckedContinuation] = lock.withLock { + if active == id { + active = nil + task = nil + } + guard invalidated, active == nil else { return [] } + let waiters = Array(drainWaiters.values) + drainWaiters.removeAll() + return waiters + } + for waiter in waiters { + waiter.resume(returning: true) + } + } + + /// Bounded cleanup proof. Call after `shutdown`; a timeout is never evidence of a drain. + func waitUntilStopped(timeoutNanoseconds: UInt64 = 4_000_000_000) async -> Bool { + guard lock.withLock({ invalidated }) else { return false } + return await withTaskGroup(of: Bool.self) { group in + group.addTask { await self.waitForDrain() } + group.addTask { + do { try await Task.sleep(nanoseconds: min(timeoutNanoseconds, 4_000_000_000)) } + catch { return false } + return false + } + let result = await group.next() ?? false + group.cancelAll() + return result + } + } + + private func waitForDrain() async -> Bool { + let id = UUID() + return await withTaskCancellationHandler { + await withCheckedContinuation { continuation in + let immediate: Bool? = lock.withLock { + if Task.isCancelled { + return false + } + if active == nil { + return true + } + drainWaiters[id] = continuation + return nil + } + if let immediate { + continuation.resume(returning: immediate) + } + } + } onCancel: { + let waiter = self.lock.withLock { self.drainWaiters.removeValue(forKey: id) } + waiter?.resume(returning: false) + } + } +} diff --git a/Interceptor/Automation/HTTPPluginOutboundDispatcher.swift b/Interceptor/Automation/HTTPPluginOutboundDispatcher.swift index 310e235..d421c32 100644 --- a/Interceptor/Automation/HTTPPluginOutboundDispatcher.swift +++ b/Interceptor/Automation/HTTPPluginOutboundDispatcher.swift @@ -53,8 +53,7 @@ final class HTTPPluginOutboundDispatcher: @unchecked Sendable { let outcome: HTTPPluginOutboundOutcome if await authorization() { outcome = await transport.perform( - HTTPPluginOutboundRequest(host: intent.endpoint.host, path: intent.endpoint.path, headers: intent.headers, - method: intent.endpoint.method, jsonBody: intent.jsonBody), + HTTPPluginOutboundRequest(host: intent.endpoint.host, path: intent.endpoint.path, headers: intent.headers), isAuthorized: authorization, ) } else { diff --git a/Interceptor/Automation/HTTPPluginOutboundTransport.swift b/Interceptor/Automation/HTTPPluginOutboundTransport.swift index 13ea1b9..e13117a 100644 --- a/Interceptor/Automation/HTTPPluginOutboundTransport.swift +++ b/Interceptor/Automation/HTTPPluginOutboundTransport.swift @@ -53,9 +53,63 @@ enum HTTPPluginOutboundOutcome: Sendable, Equatable { case tooLarge } +/// Standard-fetch result: only status and the strictly framed, identity-encoded, UTF-8 body. +enum HTTPPluginFetchOutcome: Sendable, Equatable { + case response(status: Int, body: Data) + case rejected + case failed + case cancelled + case timedOut + case tooLarge +} + protocol HTTPPluginOutboundTransport: Sendable { func perform(_ request: HTTPPluginOutboundRequest, isAuthorized: @escaping @Sendable () async -> Bool) async -> HTTPPluginOutboundOutcome + /// Retains the response body (<= `maxResponseBytes`) within `min(timeoutMilliseconds, 5000)`. + func fetch(_ request: HTTPPluginOutboundRequest, timeoutMilliseconds: Int, maxResponseBytes: Int, + isAuthorized: @escaping @Sendable () async -> Bool) async -> HTTPPluginFetchOutcome +} + +extension HTTPPluginOutboundTransport { + /// Existing test doubles and transports do not support fetch. + func fetch(_ request: HTTPPluginOutboundRequest, timeoutMilliseconds: Int, maxResponseBytes: Int, + isAuthorized: @escaping @Sendable () async -> Bool) async -> HTTPPluginFetchOutcome + { + .rejected + } +} + +/// Per-exchange response policy. The legacy preset keeps the original 64 KiB wire cap and discards bodies. +struct HTTPPluginExchangeLimits: Sendable { + static let legacy = HTTPPluginExchangeLimits(wireBytes: 65_536, bodyBytes: nil, deadlineNanoseconds: 3_000_000_000) + static let maxFetchDeadlineMilliseconds = 5000 + static let maxFetchResponseBytes = 1_048_576 + + let wireBytes: Int + /// Non-nil collects the body (fetch mode): identity encoding is forced and compressed replies are rejected. + let bodyBytes: Int? + let deadlineNanoseconds: UInt64 + + var isFetch: Bool { + bodyBytes != nil + } + + static func fetch(timeoutMilliseconds: Int, maxResponseBytes: Int) -> HTTPPluginExchangeLimits? { + guard timeoutMilliseconds > 0, maxResponseBytes > 0 else { return nil } + let cap = min(maxResponseBytes, maxFetchResponseBytes) + return HTTPPluginExchangeLimits(wireBytes: cap, bodyBytes: cap, + deadlineNanoseconds: UInt64(min(timeoutMilliseconds, maxFetchDeadlineMilliseconds)) * 1_000_000) + } +} + +private struct HTTPPluginExchangeResult: Sendable { + let outcome: HTTPPluginOutboundOutcome + let body: Data + init(_ outcome: HTTPPluginOutboundOutcome, body: Data = Data()) { + self.outcome = outcome + self.body = body + } } /// Numeric-IP sockets never consult CFNetwork's PAC/cookie/credential/cache machinery. @@ -92,44 +146,67 @@ struct HTTPPluginDirectTransport: HTTPPluginOutboundTransport { func perform(_ request: HTTPPluginOutboundRequest, isAuthorized: @escaping @Sendable () async -> Bool) async -> HTTPPluginOutboundOutcome { - guard request.isValid else { return .rejected } - guard !Task.isCancelled else { return .cancelled } + await execute(request, limits: .legacy, isAuthorized: isAuthorized).outcome + } + + func fetch(_ request: HTTPPluginOutboundRequest, timeoutMilliseconds: Int, maxResponseBytes: Int, + isAuthorized: @escaping @Sendable () async -> Bool) async -> HTTPPluginFetchOutcome + { + guard let limits = HTTPPluginExchangeLimits.fetch(timeoutMilliseconds: timeoutMilliseconds, + maxResponseBytes: maxResponseBytes) else { return .rejected } + let result = await execute(request, limits: limits, isAuthorized: isAuthorized) + switch result.outcome { + case let .response(status): return .response(status: status, body: result.body) + case .rejected: return .rejected + case .failed: return .failed + case .cancelled: return .cancelled + case .timedOut: return .timedOut + case .tooLarge: return .tooLarge + } + } + + private func execute(_ request: HTTPPluginOutboundRequest, limits: HTTPPluginExchangeLimits, + isAuthorized: @escaping @Sendable () async -> Bool) async -> HTTPPluginExchangeResult + { + guard request.isValid else { return .init(.rejected) } + guard !Task.isCancelled else { return .init(.cancelled) } // The deadline includes authorization, DNS, TCP, TLS and the entire response. - return await withTaskGroup(of: HTTPPluginOutboundOutcome.self) { tasks in - tasks.addTask { await run(request, isAuthorized: isAuthorized) } + return await withTaskGroup(of: HTTPPluginExchangeResult.self) { tasks in + tasks.addTask { await run(request, limits: limits, isAuthorized: isAuthorized) } tasks.addTask { do { - try await Task.sleep(nanoseconds: 3_000_000_000) - return .timedOut + try await Task.sleep(nanoseconds: limits.deadlineNanoseconds) + return .init(.timedOut) } catch { - return .cancelled + return .init(.cancelled) } } - let result = await tasks.next() ?? .failed + let result = await tasks.next() ?? .init(.failed) tasks.cancelAll() return result } } - private func run(_ request: HTTPPluginOutboundRequest, - isAuthorized: @escaping @Sendable () async -> Bool) async -> HTTPPluginOutboundOutcome + private func run(_ request: HTTPPluginOutboundRequest, limits: HTTPPluginExchangeLimits, + isAuthorized: @escaping @Sendable () async -> Bool) async -> HTTPPluginExchangeResult { - guard await isAuthorized() else { return .rejected } - guard !Task.isCancelled else { return .cancelled } - guard let tlsContext else { return .failed } + guard await isAuthorized() else { return .init(.rejected) } + guard !Task.isCancelled else { return .init(.cancelled) } + guard let tlsContext else { return .init(.failed) } do { let address = try await resolver(request.host) - guard !Task.isCancelled else { return .cancelled } + guard !Task.isCancelled else { return .init(.cancelled) } guard permitsTestAddress || (address.port == 443 && address.ipAddress.map(HTTPPluginPublicAddress.isAllowed) == true) - else { return .rejected } - guard await isAuthorized() else { return .rejected } - guard !Task.isCancelled else { return .cancelled } - let exchange = HTTPPluginOutboundExchange(loop: Self.group.next(), request: request, isAuthorized: isAuthorized) + else { return .init(.rejected) } + guard await isAuthorized() else { return .init(.rejected) } + guard !Task.isCancelled else { return .init(.cancelled) } + let exchange = HTTPPluginOutboundExchange(loop: Self.group.next(), request: request, limits: limits, + isAuthorized: isAuthorized) return await exchange.perform(address: address, tlsContext: tlsContext) } catch is CancellationError { - return .cancelled + return .init(.cancelled) } catch { - return Task.isCancelled ? .cancelled : .failed + return .init(Task.isCancelled ? .cancelled : .failed) } } } @@ -263,21 +340,27 @@ private final class HTTPPluginDNSLookup: @unchecked Sendable { private final class HTTPPluginOutboundExchange: @unchecked Sendable { let loop: EventLoop private let request: HTTPPluginOutboundRequest + let limits: HTTPPluginExchangeLimits private let isAuthorized: @Sendable () async -> Bool private let promise: EventLoopPromise + /// Mutated on the event loop only; read after the promise (completed from the loop) resolves. + private var collected = Data() private var channel: Channel? private var finished = false private var authorizationTask: Task? - init(loop: EventLoop, request: HTTPPluginOutboundRequest, isAuthorized: @escaping @Sendable () async -> Bool) { + init(loop: EventLoop, request: HTTPPluginOutboundRequest, limits: HTTPPluginExchangeLimits, + isAuthorized: @escaping @Sendable () async -> Bool) + { self.loop = loop self.request = request + self.limits = limits self.isAuthorized = isAuthorized promise = loop.makePromise(of: HTTPPluginOutboundOutcome.self) } - func perform(address: SocketAddress, tlsContext: NIOSSLContext) async -> HTTPPluginOutboundOutcome { - await withTaskCancellationHandler { + func perform(address: SocketAddress, tlsContext: NIOSSLContext) async -> HTTPPluginExchangeResult { + let outcome: HTTPPluginOutboundOutcome = await withTaskCancellationHandler { loop.execute { guard !self.finished else { return } ClientBootstrap(group: self.loop) @@ -289,6 +372,23 @@ private final class HTTPPluginOutboundExchange: @unchecked Sendable { } onCancel: { self.loop.execute { self.finish(.cancelled) } } + // `finish` runs on the loop before the promise succeeds, so `collected` is final here. + if case .response = outcome, limits.isFetch { + return HTTPPluginExchangeResult(outcome, body: collected) + } + return HTTPPluginExchangeResult(outcome) + } + + /// Event-loop only. Returns false once the retained body would exceed the cap. + func append(_ buffer: ByteBuffer) -> Bool { + guard let cap = limits.bodyBytes, buffer.readableBytes <= cap - collected.count else { return false } + collected.append(contentsOf: buffer.readableBytesView) + return true + } + + /// Event-loop only. Fetch bodies must be valid UTF-8 for `Response.text()/json()`. + var collectedIsUTF8: Bool { + String(data: collected, encoding: .utf8) != nil } private func configure(channel: Channel, tlsContext: NIOSSLContext) -> EventLoopFuture { @@ -315,20 +415,32 @@ private final class HTTPPluginOutboundExchange: @unchecked Sendable { var headers = HTTPHeaders() headers.add(name: "host", value: self.request.host) headers.add(name: "connection", value: "close") + if self.limits.isFetch { + headers.add(name: "accept-encoding", value: "identity") + } let method: HTTPMethod = self.request.method == "POST" ? .POST : self.request.method == "PUT" ? .PUT : .GET let body = self.request.jsonBody // Single framing builder: host owns Host/Content-Length/Content-Type; GET stays byte-identical. if method != .GET { headers.add(name: "content-length", value: String(body?.count ?? 0)) - if body != nil { headers.add(name: "content-type", value: "application/json") } + if body != nil { + headers.add(name: "content-type", value: "application/json") + } } for (name, value) in self.request.headers.sorted(by: { $0.key < $1.key }) { - if body != nil, name == "content-type" { continue } + if body != nil, name == "content-type" { + continue + } + if self.limits.isFetch, name == "accept-encoding" { + continue + } headers.add(name: name, value: value) } let head = HTTPRequestHead(version: .http1_1, method: method, uri: self.request.path, headers: headers) channel.write(HTTPClientRequestPart.head(head), promise: nil) - if let body { channel.write(HTTPClientRequestPart.body(.byteBuffer(ByteBuffer(bytes: body))), promise: nil) } + if let body { + channel.write(HTTPClientRequestPart.body(.byteBuffer(ByteBuffer(bytes: body))), promise: nil) + } channel.writeAndFlush(HTTPClientRequestPart.end(nil)).whenFailure { _ in self.finish(.failed) } } } @@ -368,7 +480,7 @@ private final class HTTPPluginOutboundWireLimit: ChannelInboundHandler { func channelRead(context: ChannelHandlerContext, data: NIOAny) { let size = unwrapInboundIn(data).readableBytes - guard size <= 65_536 - received else { exchange.finish(.tooLarge); return } + guard size <= exchange.limits.wireBytes - received else { exchange.finish(.tooLarge); return } received += size context.fireChannelRead(data) } @@ -396,16 +508,35 @@ private final class HTTPPluginOutboundResponse: ChannelInboundHandler { if code == 101 { exchange.finish(.failed) } else if code >= 200 { + if exchange.limits.isFetch, !Self.isAcceptableFetchHead(head) { + exchange.finish(.failed); return + } status = code } - case .body: break // Never retain or return secondary response data. + case let .body(buffer): + // Legacy mode never retains or returns secondary response data. + if exchange.limits.isFetch, status != nil, !exchange.append(buffer) { + exchange.finish(.tooLarge) + } case .end: if let status { + if exchange.limits.isFetch, !exchange.collectedIsUTF8 { + exchange.finish(.failed); return + } exchange.finish(.response(status)) } } } + /// Identity content only; chunked is the sole transfer coding and never combines with Content-Length. + /// NIO's decoder already rejects malformed chunking and conflicting Content-Length values. + private static func isAcceptableFetchHead(_ head: HTTPResponseHead) -> Bool { + guard head.headers[canonicalForm: "content-encoding"].allSatisfy({ $0.lowercased() == "identity" }) else { return false } + let transfer = head.headers[canonicalForm: "transfer-encoding"].map { $0.lowercased() } + guard transfer.isEmpty || transfer == ["chunked"] else { return false } + return transfer.isEmpty || head.headers[canonicalForm: "content-length"].isEmpty + } + func channelInactive(context: ChannelHandlerContext) { exchange.finish(.failed) context.fireChannelInactive() diff --git a/Interceptor/Automation/HTTPPluginProcessor.swift b/Interceptor/Automation/HTTPPluginProcessor.swift index f87a682..012a322 100644 --- a/Interceptor/Automation/HTTPPluginProcessor.swift +++ b/Interceptor/Automation/HTTPPluginProcessor.swift @@ -14,22 +14,38 @@ final class HTTPPluginProcessor: HTTPPluginProcessing, Sendable { private let admission = HTTPPluginPhaseAdmission() private let hasCaptureConsent: @Sendable () -> Bool private let outbound: HTTPPluginOutboundDispatcher + private let outboundTransport: any HTTPPluginOutboundTransport + private let fetchExecutor = JavaScriptFetchExecutor() + private let fetchDispatcher: HTTPPluginFetchDispatcher private static let bodyLimit = 24 * 1024 private struct PhaseResult { var body: Data? var intents: [PluginOutboundIntent] = [] + /// response.leave evaluations: built under the permit, run only after it is released. + var deferred: [DeferredRun] = [] + } + + private struct DeferredRun: Sendable { + let manifest: PluginManifest + let packageBytes: Data + let hook: JavaScriptHook + let event: Data + let config: Data } init(store: PluginActivationStore, snapshot: PluginActivationSnapshot, hasCaptureConsent: @escaping @Sendable () -> Bool = { CaptureAuthorization.isGranted }, outboundTransport: any HTTPPluginOutboundTransport = HTTPPluginDirectTransport(), - outboundObserver: HTTPPluginOutboundDispatcher.Observer? = nil) + outboundObserver: HTTPPluginOutboundDispatcher.Observer? = nil, + fetchObserver: HTTPPluginFetchDispatcher.Observer? = nil) { self.store = store self.snapshot = snapshot self.hasCaptureConsent = hasCaptureConsent + self.outboundTransport = outboundTransport outbound = HTTPPluginOutboundDispatcher(transport: outboundTransport, observer: outboundObserver) + fetchDispatcher = HTTPPluginFetchDispatcher(observer: fetchObserver) } func matches(_ request: HTTPPluginRequest) -> Bool { @@ -47,21 +63,79 @@ final class HTTPPluginProcessor: HTTPPluginProcessing, Sendable { } func isAuthorized() async -> Bool { - guard outbound.isActive, hasCaptureConsent() else { return false } + guard outbound.isActive, fetchDispatcher.isActive, hasCaptureConsent() else { return false } let current = await store.isCurrent(admitted: snapshot) - return current && outbound.isActive + return current && outbound.isActive && fetchDispatcher.isActive } /// Synchronous so tunnel shutdown/revocation cannot leave a window for new outbound admission. func shutdown() { outbound.shutdown() + fetchDispatcher.shutdown() + fetchExecutor.cancel() executor.cancel() } + /// Proves both the legacy outbound sends and the fetch run have drained. func waitUntilStopped() async -> Bool { - await outbound.waitUntilStopped() + let outboundStopped = await outbound.waitUntilStopped() + let fetchStopped = await fetchDispatcher.waitUntilStopped() + return outboundStopped && fetchStopped } + /// Runs after the phase permit is released. One active run per processor; extras are rejected, not queued. + private func submitDeferred(_ runs: [DeferredRun], initialIntents: [PluginOutboundIntent]) { + let executor = fetchExecutor, transport = outboundTransport + fetchDispatcher.submit { [self] in + var intents = initialIntents + for run in runs { + try Task.checkCancellation() + guard await isAuthorized() else { throw Failure.revoked } + let authorization: @Sendable () async -> Bool = { [self] in + guard !Task.isCancelled else { return false } + return await isAuthorized() + } + let output = try await withTaskCancellationHandler { + try await executor.runV2(packageJSON: run.packageBytes, hook: run.hook, eventJSON: run.event, + configJSON: run.config) + { request in + try await Self.fetch(request, via: transport, isAuthorized: authorization) + } + } onCancel: { executor.cancel() } + guard await isAuthorized() else { throw Failure.revoked } + let fields = try Self.validate(output: output, manifest: run.manifest, intents: &intents) + // response.leave cannot mutate: any mutation is an invalid result. + guard fields["mutation"] == nil else { throw Failure.invalidResult } + } + // The complete result is validated before any send; authorization is rechecked first. + try Task.checkCancellation() + guard await isAuthorized() else { throw Failure.revoked } + outbound.submit(intents) { [self] in await isAuthorized() } + } + } + + /// Maps a validated JS fetch onto the direct transport. Policy (public host, 443, headers, JSON body) is + /// enforced by `HTTPPluginOutboundRequest.isValid` and the transport itself. + private static func fetch(_ request: JavaScriptFetchRequest, via transport: any HTTPPluginOutboundTransport, + isAuthorized: @escaping @Sendable () async -> Bool) async throws -> JavaScriptFetchResponse + { + guard PluginOutboundPolicy.isAllowedURL(request.url), + let components = URLComponents(string: request.url), let host = components.host + else { throw JavaScriptExecutionError.invalidInput } + let path = components.percentEncodedPath.isEmpty ? "/" : components.percentEncodedPath + let outbound = HTTPPluginOutboundRequest(host: host, path: path, headers: request.headers, + method: request.method, jsonBody: request.body) + switch await transport.fetch(outbound, timeoutMilliseconds: request.timeoutMilliseconds, + maxResponseBytes: request.maxResponseBytes, isAuthorized: isAuthorized) + { + case let .response(status, body): return JavaScriptFetchResponse(status: status, body: body) + case .cancelled: throw CancellationError() + case .rejected, .failed, .timedOut, .tooLarge: throw FetchFailure.network + } + } + + private enum FetchFailure: Error { case network } + func process(_ phase: HTTPPluginPhase, request: HTTPPluginRequest, response: HTTPPluginResponse?) async throws -> Data? { try await admission.acquire() // No await inside a defer: release explicitly on every path. @@ -81,7 +155,11 @@ final class HTTPPluginProcessor: HTTPPluginProcessing, Sendable { // No networking is awaited while a phase or VM permit is held. guard !Task.isCancelled else { throw JavaScriptExecutionError.cancelled } guard await isAuthorized() else { throw Failure.revoked } - outbound.submit(result.intents) { [self] in await isAuthorized() } + if result.deferred.isEmpty { + outbound.submit(result.intents) { [self] in await isAuthorized() } + } else { + submitDeferred(result.deferred, initialIntents: result.intents) + } return result.body } @@ -99,70 +177,27 @@ final class HTTPPluginProcessor: HTTPPluginProcessing, Sendable { var body = original var receivedMutation = false var intents: [PluginOutboundIntent] = [] + var deferred: [DeferredRun] = [] for approved in snapshot.revisions { guard await isAuthorized() else { throw Failure.revoked } let package = approved.package, manifest = package.manifest guard manifest.matches.contains(where: { $0.matches(method: request.method, host: request.host, path: request.path, status: isResponse ? response?.status : nil) }) else { continue } - var req: [String: JSONValue] = try ["method": .string(request.method), "host": .string(request.host), - "path": .string(request.path), - "headers": Self.headers(request.headers, granted: manifest.read.headers)] - // Bound the event to granted fields before VM admission. C independently enforces the - // same grants; raw request identity remains available only for authoritative matching. - req["query"] = Self.query(request.query, granted: manifest.read.queryKeys) - if manifest.read.body == .json { - if isResponse { - // Transport retains only complete eligible forwarded request JSON. A missing - // or unparseable associated body must not suppress an eligible response hook. - if !request.body.isEmpty, request.body.count <= Self.bodyLimit, - let forwarded = try? JSONValue(parsing: request.body) - { - req["body"] = forwarded - } - } else { - req["body"] = try JSONValue(parsing: body) - } - } - var event: [String: JSONValue] = ["id": .string(request.id.uuidString), "phase": .string(phase.rawValue), - "request": .object(req)] - if let response, isResponse { - var leg: [String: JSONValue] = try ["status": .integer(Int64(response.status)), - "headers": Self.headers(response.headers, granted: manifest.read.headers)] - if manifest.read.body == .json { - leg["body"] = try JSONValue(parsing: body) - } - event["response"] = .object(leg) + let (eventBytes, config) = try Self.encode(manifest: manifest, phase: phase, request: request, response: response, body: body) + let output: Data + do { + // Read-only probe keeps existing sync hooks/errors and phase admission unchanged. + // A fetch attempt commits nothing; only that hook is replayed on the background VM. + output = try await executor.runV2(packageJSON: package.bytes, hook: hook, eventJSON: eventBytes, + configJSON: config, detectAsync: phase == .responseLeave) + } catch is JavaScriptAsyncRequired { + deferred.append(DeferredRun(manifest: manifest, packageBytes: package.bytes, hook: hook, + event: eventBytes, config: config)) + continue } - let eventBytes = try JSONValue.object(event).data() - guard eventBytes.count <= JavaScriptLimits.maxEventBytes else { throw Failure.invalidResult } - let config = try JSONValue.object(["settings": manifest.settings, "endpoints": .object([:])]).data() - guard config.count <= JavaScriptLimits.maxConfigBytes else { throw JavaScriptExecutionError.invalidInput } - let output = try await executor.runV2(packageJSON: package.bytes, hook: hook, eventJSON: eventBytes, - configJSON: config) guard await isAuthorized() else { throw Failure.revoked } - guard output.count <= JavaScriptLimits.maxResultBytes, - let fields = try JSONValue(parsing: output).objectValue, - Set(fields.keys).isSubset(of: ["actions", "mutation"]), let actions = fields["actions"]?.arrayValue, - actions.count <= JavaScriptLimits.maxActions - else { - throw Failure.invalidResult - } - for action in actions { - if action.objectValue?["type"]?.stringValue == "http" { - guard manifest.schemaVersion == 2, - let intent = try? PluginOutboundIntent.validating(action, manifest: manifest) - else { throw Failure.invalidResult } - intents.append(intent) - guard intents.count <= JavaScriptLimits.maxActions else { throw Failure.invalidResult } - } else { - // Legacy webhook actions remain display-only, but must still cross a strict boundary. - guard let fields = action.objectValue, Set(fields.keys) == ["type", "endpointId", "json"], - fields["type"]?.stringValue == "webhook", - fields["endpointId"]?.stringValue.flatMap(UUID.init(uuidString:)) != nil, - fields["json"] != nil else { throw Failure.invalidResult } - } - } + let fields = try Self.validate(output: output, manifest: manifest, intents: &intents) if let mutation = fields["mutation"] { guard isEnter, manifest.read.body == .json, isResponse ? manifest.writeResponseBody : manifest.writeRequestBody, @@ -177,11 +212,80 @@ final class HTTPPluginProcessor: HTTPPluginProcessing, Sendable { } } guard await isAuthorized() else { throw Failure.revoked } - guard isEnter, receivedMutation else { return PhaseResult(intents: intents) } + guard isEnter, receivedMutation else { return PhaseResult(intents: intents, deferred: deferred) } guard try JSONValue(parsing: body) != JSONValue(parsing: original) else { return PhaseResult(intents: intents) } return PhaseResult(body: body, intents: intents) } + /// Bounds the event to granted fields before VM admission. C independently enforces the + /// same grants; raw request identity remains available only for authoritative matching. + private static func encode(manifest: PluginManifest, phase: HTTPPluginPhase, request: HTTPPluginRequest, + response: HTTPPluginResponse?, body: Data) throws -> (event: Data, config: Data) + { + let isResponse = phase == .responseEnter || phase == .responseLeave + var req: [String: JSONValue] = try ["method": .string(request.method), "host": .string(request.host), + "path": .string(request.path), + "headers": headers(request.headers, granted: manifest.read.headers)] + req["query"] = query(request.query, granted: manifest.read.queryKeys) + if manifest.read.body == .json { + if isResponse { + // Transport retains only complete eligible forwarded request JSON. A missing + // or unparseable associated body must not suppress an eligible response hook. + if !request.body.isEmpty, request.body.count <= bodyLimit, + let forwarded = try? JSONValue(parsing: request.body) + { + req["body"] = forwarded + } + } else { + req["body"] = try JSONValue(parsing: body) + } + } + var event: [String: JSONValue] = ["id": .string(request.id.uuidString), "phase": .string(phase.rawValue), + "request": .object(req)] + if let response, isResponse { + var leg: [String: JSONValue] = try ["status": .integer(Int64(response.status)), + "headers": headers(response.headers, granted: manifest.read.headers)] + if manifest.read.body == .json { + leg["body"] = try JSONValue(parsing: body) + } + event["response"] = .object(leg) + } + let eventBytes = try JSONValue.object(event).data() + guard eventBytes.count <= JavaScriptLimits.maxEventBytes else { throw Failure.invalidResult } + let config = try JSONValue.object(["settings": manifest.settings, "endpoints": .object([:])]).data() + guard config.count <= JavaScriptLimits.maxConfigBytes else { throw JavaScriptExecutionError.invalidInput } + return (eventBytes, config) + } + + /// Strict result and action validation shared by sync and fetch runs. Appends only validated legacy HTTP intents. + private static func validate(output: Data, manifest: PluginManifest, + intents: inout [PluginOutboundIntent]) throws -> [String: JSONValue] + { + guard output.count <= JavaScriptLimits.maxResultBytes, + let fields = try JSONValue(parsing: output).objectValue, + Set(fields.keys).isSubset(of: ["actions", "mutation"]), let actions = fields["actions"]?.arrayValue, + actions.count <= JavaScriptLimits.maxActions + else { + throw Failure.invalidResult + } + for action in actions { + if action.objectValue?["type"]?.stringValue == "http" { + guard manifest.schemaVersion == 2, + let intent = try? PluginOutboundIntent.validating(action, manifest: manifest) + else { throw Failure.invalidResult } + intents.append(intent) + guard intents.count <= JavaScriptLimits.maxActions else { throw Failure.invalidResult } + } else { + // Legacy webhook actions remain display-only, but must still cross a strict boundary. + guard let fields = action.objectValue, Set(fields.keys) == ["type", "endpointId", "json"], + fields["type"]?.stringValue == "webhook", + fields["endpointId"]?.stringValue.flatMap(UUID.init(uuidString:)) != nil, + fields["json"] != nil else { throw Failure.invalidResult } + } + } + return fields + } + private static func headers(_ values: [String: String], granted: [String]) throws -> JSONValue { var names = Set() var result: [String: JSONValue] = [:] diff --git a/InterceptorTests/HTTPPluginFetchProcessorTests.swift b/InterceptorTests/HTTPPluginFetchProcessorTests.swift new file mode 100644 index 0000000..7d96113 --- /dev/null +++ b/InterceptorTests/HTTPPluginFetchProcessorTests.swift @@ -0,0 +1,289 @@ +import AutomationCore +import AutomationRuntime +import Foundation +@testable import Interceptor +import MudmouthHTTPHooks +import XCTest + +/// Standard `fetch` from response.onLeave through the real activation store, C runtime and fetch dispatcher, +/// with a recording transport in place of the network (the real TLS exchange is covered in the transport tests). +final class HTTPPluginFetchProcessorTests: XCTestCase, @unchecked Sendable { + private var directory: URL! + private let fetchURL = "https://api.example.com/v1/exchange" + + override func setUpWithError() throws { + directory = FileManager.default.temporaryDirectory.appendingPathComponent("FetchProcessor-" + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + + override func tearDownWithError() throws { + try FileManager.default.removeItem(at: directory) + } + + /// One route with a synchronous request.onEnter (to observe the next sync phase) and the given response.onLeave body. + private func package(leave: String) throws -> PluginPackage { + let file = "hooks/api.example.com/credentials/GET.js" + let manifest: JSONValue = .object([ + "schemaVersion": .integer(2), "id": .string(UUID().uuidString), "name": .string("Fetch test"), "version": .string("1.0.0"), + "matches": .array([.object([ + "hosts": .array([.string("api.example.com")]), "methods": .array([.string("GET")]), + "path": .object(["kind": .string("exact"), "value": .string("/credentials")]), + "hooks": .object(["request": .object(["onEnter": .string(file)]), "response": .object(["onLeave": .string(file)])]), + ])]), + "read": .object(["metadata": .array(["method", "host", "path", "status"].map(JSONValue.string)), + "headers": .array([.string("set-cookie")]), "queryKeys": .array([]), + "body": .object(["mode": .string("json")])]), + "write": .object(["requestBody": .bool(true), "responseBody": .bool(false)]), + "endpointBindings": .array([]), "settings": .object([:]), + "outbound": .object(["profile": .object([ + "url": .string("https://secondary.example.com/profile"), "method": .string("GET"), + "headers": .array([.string("authorization")]), + ])]), + ]) + let source = "Interceptor.attach({request:{onEnter(r){r.body.n=2;}},response:{onLeave(r){\(leave)}}});" + return try PluginPackage.validate(JSONValue.object(["manifest": manifest, "sourceFiles": .object([file: .string(source)])]).data()) + } + + private struct Harness { + let processor: HTTPPluginProcessor + let store: PluginActivationStore + let completions: Completions + } + + private func harness(leave: String, transport: FetchStubTransport) async throws -> Harness { + let package = try package(leave: leave) + let (store, revisions) = try await AutomationFixtures.activationContext(packages: [package], + activationURL: directory.appendingPathComponent("active.json")) + var snapshot = try await store.snapshot() + for revision in revisions { + snapshot = try await store.activate(revision.package, revisionID: revision.id, expectedGeneration: snapshot.generation) + } + let completions = Completions() + let processor = HTTPPluginProcessor(store: store, snapshot: snapshot, hasCaptureConsent: { true }, outboundTransport: transport, + fetchObserver: { completions.append($0) }) + return Harness(processor: processor, store: store, completions: completions) + } + + private var request: HTTPPluginRequest { + HTTPPluginRequest(id: UUID(), method: "GET", host: "api.example.com", path: "/credentials", headers: [:], body: Data(#"{"n":1}"#.utf8)) + } + + private var response: HTTPPluginResponse { + HTTPPluginResponse(status: 200, headers: ["set-cookie": "fixture_session=session-token; Path=/; HttpOnly"], + body: Data(#"{"accessToken":"token"}"#.utf8)) + } + + private func awaitCompletion(_ harness: Harness, _ expected: HTTPPluginFetchDispatcher.Completion, count: Int = 1) async { + for _ in 0 ..< 500 where harness.completions.values.count < count { + try? await Task.sleep(nanoseconds: 10_000_000) + } + XCTAssertEqual(harness.completions.values.last, expected) + } + + private func fetchScript(_ then: String = "") -> String { + "return (async()=>{await fetch('\(fetchURL)');\(then)})();" + } + + func testResponseLeaveReturnsBeforeABlockedFetchFinishesAndTheNextSyncPhaseRuns() async throws { + let gate = AsyncGate() + let transport = FetchStubTransport { _ in await gate.wait(); return .response(status: 200, body: Data("{}".utf8)) } + let harness = try await harness(leave: fetchScript(), transport: transport) + defer { harness.processor.shutdown() } + let leave = try await harness.processor.process(.responseLeave, request: request, response: response) + XCTAssertNil(leave) + await transport.waitUntilEntered(1) + XCTAssertTrue(harness.completions.values.isEmpty, "the fetch is still blocked after the phase returned") + let enter = try await harness.processor.process(.requestEnter, request: request, response: nil) + XCTAssertEqual(try JSONValue(parsing: XCTUnwrap(enter)), .object(["n": .integer(2)])) + await gate.open() + await awaitCompletion(harness, .completed) + } + + func testCapturedTokenBodyAndHeadersReachFetchJavaScript() async throws { + let transport = FetchStubTransport { _ in .response(status: 200, body: Data("{}".utf8)) } + let script = """ + return (async()=>{await fetch('\(fetchURL)',{method:'POST',headers:{authorization:'Bearer '+r.body.accessToken,\ + cookie:r.headers['set-cookie'].split(';')[0]},body:JSON.stringify({token:r.body.accessToken})});})(); + """ + let harness = try await harness(leave: script, transport: transport) + defer { harness.processor.shutdown() } + _ = try await harness.processor.process(.responseLeave, request: request, response: response) + await awaitCompletion(harness, .completed) + let sent = try XCTUnwrap(transport.fetched.first) + XCTAssertEqual(sent.host, "api.example.com") + XCTAssertEqual(sent.path, "/v1/exchange") + XCTAssertEqual(sent.method, "POST") + XCTAssertEqual(sent.headers, ["authorization": "Bearer token", "cookie": "fixture_session=session-token", + "content-type": "application/json"]) + XCTAssertEqual(sent.jsonBody, Data(#"{"token":"token"}"#.utf8)) + } + + func testAnExtraResponseLeaveWhileOneFetchRunIsActiveIsRejectedNotQueued() async throws { + let gate = AsyncGate() + let transport = FetchStubTransport { _ in await gate.wait(); return .response(status: 200, body: Data()) } + let harness = try await harness(leave: fetchScript(), transport: transport) + defer { harness.processor.shutdown() } + _ = try await harness.processor.process(.responseLeave, request: request, response: response) + await transport.waitUntilEntered(1) + _ = try await harness.processor.process(.responseLeave, request: request, response: response) + XCTAssertEqual(harness.completions.values, [.rejected]) + await gate.open() + await awaitCompletion(harness, .completed, count: 2) + XCTAssertEqual(transport.fetched.count, 1, "the rejected run must never reach the transport") + } + + func testShutdownCancelsABlockedFetchAndWaitProvesBothSystemsDrained() async throws { + let transport = FetchStubTransport { _ in + do { try await Task.sleep(nanoseconds: 60_000_000_000) } catch { return .cancelled } + return .response(status: 200, body: Data()) + } + let harness = try await harness(leave: fetchScript(), transport: transport) + _ = try await harness.processor.process(.responseLeave, request: request, response: response) + await transport.waitUntilEntered(1) + harness.processor.shutdown() + let drained = await harness.processor.waitUntilStopped() + XCTAssertTrue(drained) + XCTAssertEqual(transport.fetched.count, 1) + XCTAssertEqual(harness.completions.values.count, 1) + XCTAssertNotEqual(harness.completions.values.first, .completed) + let authorized = await harness.processor.isAuthorized() + XCTAssertFalse(authorized) + } + + func testRevocationPreventsTheNextFetchAndAnyFollowUp() async throws { + let transport = FetchStubTransport() + let script = """ + return (async()=>{ + try{await fetch('\(fetchURL)');}catch(e){} + try{await fetch('\(fetchURL)');}catch(e){} + Interceptor.send('profile',{headers:{authorization:'Bearer x'}}); + })(); + """ + let harness = try await harness(leave: script, transport: transport) + defer { harness.processor.shutdown() } + let store = harness.store + transport.setHandler { _ in + _ = try? await store.revokeAll() + return .response(status: 200, body: Data("{}".utf8)) + } + _ = try await harness.processor.process(.responseLeave, request: request, response: response) + await awaitCompletion(harness, .failed) + XCTAssertEqual(transport.fetched.count, 1, "the second fetch must be refused by the revoked authorization") + XCTAssertTrue(transport.performed.isEmpty, "revocation must also drop the legacy follow-up") + } + + func testInvalidResultAfterFetchDispatchesNoFollowUps() async throws { + let transport = FetchStubTransport { _ in .response(status: 200, body: Data("{}".utf8)) } + // response.onLeave is read-only: the attempted mutation fails the run, so the earlier send must never dispatch. + let script = """ + return (async()=>{await fetch('\(fetchURL)');Interceptor.send('profile',{headers:{authorization:'Bearer x'}});r.body.accessToken='changed';})(); + """ + let harness = try await harness(leave: script, transport: transport) + defer { harness.processor.shutdown() } + _ = try await harness.processor.process(.responseLeave, request: request, response: response) + await awaitCompletion(harness, .failed) + XCTAssertEqual(transport.fetched.count, 1) + try? await Task.sleep(nanoseconds: 200_000_000) + XCTAssertTrue(transport.performed.isEmpty) + } + + func testValidFetchFollowedBySendDispatchesExactlyTheLegacyIntentAfterCompletion() async throws { + let transport = FetchStubTransport { _ in .response(status: 200, body: Data(#"{"t":"fresh"}"#.utf8)) } + let script = """ + return (async()=>{const j=await (await fetch('\(fetchURL)')).json();\ + Interceptor.send('profile',{headers:{authorization:'Bearer '+j.t}});})(); + """ + let harness = try await harness(leave: script, transport: transport) + defer { harness.processor.shutdown() } + _ = try await harness.processor.process(.responseLeave, request: request, response: response) + await awaitCompletion(harness, .completed) + for _ in 0 ..< 200 where transport.performed.isEmpty { + try? await Task.sleep(nanoseconds: 10_000_000) + } + let sent = try XCTUnwrap(transport.performed.first) + XCTAssertEqual(transport.performed.count, 1) + XCTAssertEqual(sent.host, "secondary.example.com") + XCTAssertEqual(sent.path, "/profile") + XCTAssertEqual(sent.headers, ["authorization": "Bearer fresh"]) + } +} + +private actor AsyncGate { + private var opened = false + private var waiters: [CheckedContinuation] = [] + func wait() async { + if opened { + return + } + await withCheckedContinuation { waiters.append($0) } + } + + func open() { + opened = true + waiters.forEach { $0.resume() } + waiters.removeAll() + } +} + +private final class Completions: @unchecked Sendable { + private let lock = NSLock() + private var storage: [HTTPPluginFetchDispatcher.Completion] = [] + var values: [HTTPPluginFetchDispatcher.Completion] { + lock.withLock { storage } + } + + func append(_ value: HTTPPluginFetchDispatcher.Completion) { + lock.withLock { storage.append(value) } + } +} + +/// Like the real transport, a fetch is refused when authorization is already gone and only authorized calls are recorded. +private final class FetchStubTransport: HTTPPluginOutboundTransport, @unchecked Sendable { + typealias Handler = @Sendable (HTTPPluginOutboundRequest) async -> HTTPPluginFetchOutcome + private let lock = NSLock() + private var handler: Handler + private var fetchedStorage: [HTTPPluginOutboundRequest] = [] + private var performedStorage: [HTTPPluginOutboundRequest] = [] + + init(handler: @escaping Handler = { _ in .response(status: 200, body: Data()) }) { + self.handler = handler + } + + var fetched: [HTTPPluginOutboundRequest] { + lock.withLock { fetchedStorage } + } + + var performed: [HTTPPluginOutboundRequest] { + lock.withLock { performedStorage } + } + + func setHandler(_ handler: @escaping Handler) { + lock.withLock { self.handler = handler } + } + + func waitUntilEntered(_ count: Int) async { + for _ in 0 ..< 500 where fetched.count < count { + try? await Task.sleep(nanoseconds: 10_000_000) + } + XCTAssertGreaterThanOrEqual(fetched.count, count) + } + + func perform(_ request: HTTPPluginOutboundRequest, + isAuthorized: @escaping @Sendable () async -> Bool) async -> HTTPPluginOutboundOutcome + { + guard await isAuthorized() else { return .rejected } + lock.withLock { performedStorage.append(request) } + return .response(200) + } + + func fetch(_ request: HTTPPluginOutboundRequest, timeoutMilliseconds: Int, maxResponseBytes: Int, + isAuthorized: @escaping @Sendable () async -> Bool) async -> HTTPPluginFetchOutcome + { + guard await isAuthorized() else { return .rejected } + let current = lock.withLock { () -> Handler in + fetchedStorage.append(request) + return handler + } + return await current(request) + } +} diff --git a/InterceptorTests/HTTPPluginFetchTests.swift b/InterceptorTests/HTTPPluginFetchTests.swift new file mode 100644 index 0000000..9b3c213 --- /dev/null +++ b/InterceptorTests/HTTPPluginFetchTests.swift @@ -0,0 +1,119 @@ +import Foundation +@testable import Interceptor +import XCTest + +final class HTTPPluginFetchDispatcherTests: XCTestCase { + func testSecondSubmissionIsRejectedWithoutQueueing() async { + let release = AsyncGate() + let completions = CompletionLog() + let dispatcher = HTTPPluginFetchDispatcher { completions.append($0) } + XCTAssertTrue(dispatcher.submit { await release.wait() }) + XCTAssertFalse(dispatcher.submit { XCTFail("must not queue") }) + XCTAssertEqual(completions.values, [.rejected]) + await release.open() + dispatcher.shutdown() + let drained = await dispatcher.waitUntilStopped() + XCTAssertTrue(drained) + } + + func testShutdownCancelsAndWaitProvesDrain() async { + let started = expectation(description: "started") + let dispatcher = HTTPPluginFetchDispatcher() + dispatcher.submit { + started.fulfill() + try await Task.sleep(nanoseconds: 60_000_000_000) + } + await fulfillment(of: [started], timeout: 2) + dispatcher.shutdown() + let drained = await dispatcher.waitUntilStopped() + XCTAssertTrue(drained) + XCTAssertFalse(dispatcher.submit {}, "no admission after shutdown") + } + + func testWaitBeforeShutdownIsNotAProof() async { + let dispatcher = HTTPPluginFetchDispatcher() + let drained = await dispatcher.waitUntilStopped(timeoutNanoseconds: 10_000_000) + XCTAssertFalse(drained) + } + + func testShutdownRacingImmediatelyFinishingTask() async { + for _ in 0 ..< 200 { + let dispatcher = HTTPPluginFetchDispatcher() + dispatcher.submit {} + dispatcher.shutdown() + let drained = await dispatcher.waitUntilStopped() + XCTAssertTrue(drained) + } + } + + func testFailureMapsWithoutLeakingErrorDetail() async { + let done = expectation(description: "done") + let completions = CompletionLog() + let dispatcher = HTTPPluginFetchDispatcher { completions.append($0); done.fulfill() } + dispatcher.submit { throw NSError(domain: "secret-token", code: 1) } + await fulfillment(of: [done], timeout: 2) + XCTAssertEqual(completions.values, [.failed]) + dispatcher.shutdown() + } +} + +final class HTTPPluginFetchTransportPolicyTests: XCTestCase { + func testDefaultTransportImplementationRejectsFetch() async { + let transport = OutboundRecordingTransport() + let request = HTTPPluginOutboundRequest(host: "api.example.com", path: "/x", headers: [:]) + let outcome = await transport.fetch(request, timeoutMilliseconds: 5000, maxResponseBytes: 1 << 20, isAuthorized: { true }) + XCTAssertEqual(outcome, .rejected) + XCTAssertTrue(transport.requests.isEmpty) + } + + func testFetchLimitsClampDeadlineAndBody() throws { + let limits = try XCTUnwrap(HTTPPluginExchangeLimits.fetch(timeoutMilliseconds: 120_000, maxResponseBytes: 64 << 20)) + XCTAssertEqual(limits.deadlineNanoseconds, 5_000_000_000) + XCTAssertEqual(limits.bodyBytes, 1_048_576) + XCTAssertTrue(limits.isFetch) + XCTAssertNil(HTTPPluginExchangeLimits.fetch(timeoutMilliseconds: 0, maxResponseBytes: 10)) + XCTAssertNil(HTTPPluginExchangeLimits.fetch(timeoutMilliseconds: 10, maxResponseBytes: 0)) + } + + func testLegacyLimitsUnchanged() { + XCTAssertEqual(HTTPPluginExchangeLimits.legacy.wireBytes, 65_536) + XCTAssertEqual(HTTPPluginExchangeLimits.legacy.deadlineNanoseconds, 3_000_000_000) + XCTAssertFalse(HTTPPluginExchangeLimits.legacy.isFetch) + } + + func testDirectTransportRejectsInvalidRequestBeforeNetwork() async { + let transport = HTTPPluginDirectTransport() + let bad = HTTPPluginOutboundRequest(host: "localhost", path: "/", headers: [:]) + let outcome = await transport.fetch(bad, timeoutMilliseconds: 1000, maxResponseBytes: 1024, isAuthorized: { true }) + XCTAssertEqual(outcome, .rejected) + } +} + +private actor AsyncGate { + private var opened = false + private var waiters: [CheckedContinuation] = [] + func wait() async { + if opened { + return + } + await withCheckedContinuation { waiters.append($0) } + } + + func open() { + opened = true + waiters.forEach { $0.resume() } + waiters.removeAll() + } +} + +private final class CompletionLog: @unchecked Sendable { + private let lock = NSLock() + private var storage: [HTTPPluginFetchDispatcher.Completion] = [] + var values: [HTTPPluginFetchDispatcher.Completion] { + lock.withLock { storage } + } + + func append(_ value: HTTPPluginFetchDispatcher.Completion) { + lock.withLock { storage.append(value) } + } +} diff --git a/InterceptorTests/HTTPPluginOutboundDispatcherTests.swift b/InterceptorTests/HTTPPluginOutboundDispatcherTests.swift index 5f7cb0c..53012fc 100644 --- a/InterceptorTests/HTTPPluginOutboundDispatcherTests.swift +++ b/InterceptorTests/HTTPPluginOutboundDispatcherTests.swift @@ -1,37 +1,9 @@ import AutomationCore -import AutomationRuntime import Foundation @testable import Interceptor import XCTest final class HTTPPluginOutboundDispatcherTests: XCTestCase, @unchecked Sendable { - func testRealRuntimeActionsCrossCoreValidationAndDispatcher() async throws { - for method in ["POST", "PUT"] { - let package = try OutboundAppFixtures.package( - callback: "Interceptor.send('profile',{headers:{authorization:'Bearer token'},json:{name:'日本語'}});", - method: method) - let output = try await JavaScriptExecutor().runV2( - packageJSON: package.bytes, hook: .responseLeave, - eventJSON: Data(#"{"request":{"method":"GET","host":"api.example.com","path":"/credentials"},"response":{"status":200,"headers":{},"body":{}}}"#.utf8), - configJSON: Data("{}".utf8)) - let actions = try XCTUnwrap(try JSONValue(parsing: output).objectValue?["actions"]?.arrayValue) - let intents = try actions.map { try PluginOutboundIntent.validating($0, manifest: package.manifest) } - let done = expectation(description: "runtime \(method) delivered") - let transport = OutboundRecordingTransport() - let dispatcher = HTTPPluginOutboundDispatcher(transport: transport) { _, outcome in - XCTAssertEqual(outcome, .response(200)) - done.fulfill() - } - defer { dispatcher.shutdown() } - XCTAssertEqual(dispatcher.submit(intents, isAuthorized: { true }), 1) - await fulfillment(of: [done], timeout: 2) - let request = try XCTUnwrap(transport.requests.first) - XCTAssertEqual(request.method, method) - XCTAssertEqual(request.jsonBody, Data(#"{"name":"日本語"}"#.utf8)) - XCTAssertEqual(request.headers, ["authorization": "Bearer token"]) - } - } - func testCapacityIsReservedSynchronouslyAndOverloadHasNoWaitingQueue() async throws { let started = expectation(description: "four admitted operations") started.expectedFulfillmentCount = 4 @@ -99,31 +71,6 @@ final class HTTPPluginOutboundDispatcherTests: XCTestCase, @unchecked Sendable { } } - func testTransportReceivesDeclaredMethodAndExactJSONBodyBytes() async throws { - let body = #"{"name":"日本語","n":1.50e+2,"s":"a\"b\\A"}"# - let cases: [(String, String?)] = [("GET", nil), ("POST", nil), ("POST", body), ("PUT", "null"), ("PUT", body)] - for (method, jsonBody) in cases { - let done = expectation(description: "\(method) \(jsonBody ?? "nil")") - let transport = OutboundRecordingTransport() - let dispatcher = HTTPPluginOutboundDispatcher(transport: transport) { _, outcome in - XCTAssertEqual(outcome, .response(200)) - done.fulfill() - } - defer { dispatcher.shutdown() } - let intent = try OutboundAppFixtures.intent(method: method, jsonBody: jsonBody) - XCTAssertEqual(intent.jsonBody, jsonBody.map { Data($0.utf8) }) - XCTAssertEqual(dispatcher.submit([intent], isAuthorized: { true }), 1) - await fulfillment(of: [done], timeout: 2) - let request = try XCTUnwrap(transport.requests.first) - XCTAssertEqual(request.method, method) - XCTAssertEqual(request.jsonBody, jsonBody.map { Data($0.utf8) }, "dispatcher must forward the exact validated bytes") - XCTAssertEqual(request.host, "secondary.example.com") - XCTAssertEqual(request.path, "/profile") - XCTAssertEqual(request.headers, ["authorization": "Bearer token"]) - XCTAssertTrue(request.isValid) - } - } - func testShutdownDrainWaitsForObserverCallbacksAndResumesEveryWaiter() async throws { let entered = expectation(description: "observer running") let callback = OutboundBlockingCallback() @@ -225,8 +172,7 @@ final class OutboundRecordingTransport: HTTPPluginOutboundTransport, @unchecked enum OutboundAppFixtures { static func package(id: UUID = UUID(), callback: String = "", phase: String = "onLeave", - headers: [String] = ["authorization", "cookie"], readHeaders: [String] = [], - method: String = "GET") throws -> PluginPackage { + headers: [String] = ["authorization", "cookie"], readHeaders: [String] = []) throws -> PluginPackage { let file = "hooks/api.example.com/credentials/GET.js" let manifest: JSONValue = .object([ "schemaVersion": .integer(2), "id": .string(id.uuidString), "name": .string("Outbound test"), "version": .string("1.0.0"), @@ -241,7 +187,7 @@ enum OutboundAppFixtures { "write": .object(["requestBody": .bool(false), "responseBody": .bool(phase == "onEnter")]), "endpointBindings": .array([]), "settings": .object([:]), "outbound": .object(["profile": .object([ - "url": .string("https://secondary.example.com/profile"), "method": .string(method), + "url": .string("https://secondary.example.com/profile"), "method": .string("GET"), "headers": .array(headers.map(JSONValue.string)), ])]), ]) @@ -251,10 +197,10 @@ enum OutboundAppFixtures { ]).data()) } - static func intent(method: String = "GET", jsonBody: String? = nil, - headers: [String: JSONValue] = ["authorization": .string("Bearer token")]) throws -> PluginOutboundIntent { - var action: [String: JSONValue] = ["type": .string("http"), "binding": .string("profile"), "headers": .object(headers)] - if let jsonBody { action["jsonBody"] = .string(jsonBody) } - return try PluginOutboundIntent.validating(.object(action), manifest: package(method: method).manifest) + static func intent() throws -> PluginOutboundIntent { + try PluginOutboundIntent.validating(.object([ + "type": .string("http"), "binding": .string("profile"), + "headers": .object(["authorization": .string("Bearer token")]), + ]), manifest: package().manifest) } } diff --git a/InterceptorTests/HTTPPluginOutboundTransportTests.swift b/InterceptorTests/HTTPPluginOutboundTransportTests.swift index 3ece803..9d4a9b5 100644 --- a/InterceptorTests/HTTPPluginOutboundTransportTests.swift +++ b/InterceptorTests/HTTPPluginOutboundTransportTests.swift @@ -292,6 +292,7 @@ private struct OutboundObservedRequest: Sendable { let body: Data let contentLengthValues: [String] let contentTypeValues: [String] + var acceptEncodingValues: [String] = [] } private final class OutboundLocked: @unchecked Sendable { @@ -391,7 +392,9 @@ private final class OutboundDecryptedByteObserver: ChannelInboundHandler, @unche typealias InboundIn = ByteBuffer private let bytes: OutboundLocked - init(bytes: OutboundLocked) { self.bytes = bytes } + init(bytes: OutboundLocked) { + self.bytes = bytes + } func channelRead(context: ChannelHandlerContext, data: NIOAny) { bytes.change { $0 += unwrapInboundIn(data).readableBytes } @@ -424,9 +427,14 @@ private final class OutboundOriginHandler: ChannelInboundHandler, @unchecked Sen headerNames: Set(head.headers.map { $0.name.lowercased() }), bodyBytes: bodyBytes, body: body, contentLengthValues: head.headers["content-length"], - contentTypeValues: head.headers["content-type"])) + contentTypeValues: head.headers["content-type"], + acceptEncodingValues: head.headers["accept-encoding"])) } guard head.uri != "/silent" else { return } + if head.uri.hasPrefix("/fetch/") { + respondToFetch(context: context, uri: head.uri, requestBody: body) + return + } let status: HTTPResponseStatus = if head.uri == "/redirect" { .temporaryRedirect } else if head.uri == "/auth/bearer" { @@ -449,6 +457,47 @@ private final class OutboundOriginHandler: ChannelInboundHandler, @unchecked Sen } } + /// Fixture responses for standard-fetch tests; routed by path so legacy paths stay byte-identical. + private func respondToFetch(context: ChannelHandlerContext, uri: String, requestBody: Data) { + func send(_ status: HTTPResponseStatus, _ headers: [(String, String)], _ chunks: [Data], chunked: Bool = false) { + var fields = HTTPHeaders(headers) + if chunked { + fields.add(name: "transfer-encoding", value: "chunked") + } else { + fields.add(name: "content-length", value: String(chunks.reduce(0) { $0 + $1.count })) + } + context.write(wrapOutboundOut(.head(.init(version: .http1_1, status: status, headers: fields))), promise: nil) + for chunk in chunks { + context.write(wrapOutboundOut(.body(.byteBuffer(context.channel.allocator.buffer(bytes: chunk)))), promise: nil) + } + context.writeAndFlush(wrapOutboundOut(.end(nil)), promise: nil) + } + switch uri { + case "/fetch/echo": send(.ok, [("content-type", "application/json")], [requestBody]) + case "/fetch/text": send(.ok, [("content-type", "text/plain")], [Data("plain text, not JSON".utf8)]) + case "/fetch/invalid-utf8": send(.ok, [("content-type", "text/plain")], [Data([0x61, 0xFF, 0xFE, 0x62])]) + case "/fetch/gzip": send(.ok, [("content-encoding", "gzip")], [Data([0x1F, 0x8B])]) + case "/fetch/redirect": + send(.found, [("location", "https://other.example.com/must-not-be-followed")], [Data("{}".utf8)]) + case "/fetch/chunked": + send(.ok, [("content-type", "application/json")], [Data(#"{"a":"#.utf8), Data("[1,2,".utf8), Data("3]}".utf8)], chunked: true) + case "/fetch/chunked-big": + send(.ok, [], (0 ..< 8).map { _ in Data(repeating: 0x78, count: 512) }, chunked: true) + case "/fetch/slow-chunks": + // The first part is flushed immediately; the fetch must not complete before `.end`. + context.write(wrapOutboundOut(.head(.init(version: .http1_1, status: .ok, + headers: HTTPHeaders([("transfer-encoding", "chunked")])))), promise: nil) + context.writeAndFlush(wrapOutboundOut(.body(.byteBuffer(context.channel.allocator.buffer(string: #"{"late":"#)))), promise: nil) + let bound = NIOLoopBound(context, eventLoop: context.eventLoop) + context.eventLoop.scheduleTask(in: .milliseconds(300)) { + let context = bound.value + context.write(self.wrapOutboundOut(.body(.byteBuffer(context.channel.allocator.buffer(string: "true}")))), promise: nil) + context.writeAndFlush(self.wrapOutboundOut(.end(nil)), promise: nil) + } + default: send(.notFound, [], [Data()]) + } + } + func errorCaught(context: ChannelHandlerContext, error: Error) { context.close(promise: nil) } @@ -650,7 +699,9 @@ extension HTTPPluginOutboundTransportTests { func nested(_ depth: Int) -> String { String(repeating: "[", count: depth) + String(repeating: "]", count: depth) } - func string(bytes: Int) -> String { #"""# + String(repeating: "x", count: bytes - 2) + #"""# } + func string(bytes: Int) -> String { + #"""# + String(repeating: "x", count: bytes - 2) + #"""# + } XCTAssertTrue(request("POST", body: nested(16)).isValid, "depth 16 is allowed") XCTAssertFalse(request("POST", body: nested(17)).isValid, "depth 17 is rejected") XCTAssertTrue(request("POST", body: string(bytes: 8192)).isValid, "exactly 8192 bytes is allowed") @@ -700,3 +751,104 @@ extension HTTPPluginOutboundTransportTests { } } } + +// MARK: - Standard fetch over the real TLS/NIO exchange + +extension HTTPPluginOutboundTransportTests { + private func fetch(_ origin: OutboundOrigin, _ path: String, method: String = "GET", body: String? = nil, + headers: [String: String] = [:], timeout: Int = 5000, cap: Int = 1 << 20) async -> HTTPPluginFetchOutcome + { + await origin.transport.fetch( + .init(host: "api.example.com", path: path, headers: headers, method: method, jsonBody: body.map { Data($0.utf8) }), + timeoutMilliseconds: timeout, maxResponseBytes: cap, isAuthorized: { true }, + ) + } + + func testFetchReturnsEchoedRequestBodyAndForcesIdentityEncoding() async throws { + try await withOrigin { origin in + let outcome = await fetch(origin, "/fetch/echo", method: "POST", body: #"{"k":1}"#, headers: ["accept-encoding": "gzip"]) + XCTAssertEqual(outcome, .response(status: 200, body: Data(#"{"k":1}"#.utf8))) + let seen = try XCTUnwrap(origin.requests.value.first) + XCTAssertEqual(seen.acceptEncodingValues, ["identity"], "script-supplied accept-encoding must not reach the wire") + XCTAssertEqual(seen.body, Data(#"{"k":1}"#.utf8)) + } + } + + func testFetchCompletesOnlyAtEndOfAChunkedResponse() async throws { + try await withOrigin { origin in + let chunked = await fetch(origin, "/fetch/chunked") + XCTAssertEqual(chunked, .response(status: 200, body: Data(#"{"a":[1,2,3]}"#.utf8))) + let start = ContinuousClock.now + let slow = await fetch(origin, "/fetch/slow-chunks") + XCTAssertEqual(slow, .response(status: 200, body: Data(#"{"late":true}"#.utf8))) + XCTAssertGreaterThanOrEqual(start.duration(to: .now), .milliseconds(250), "must wait for .end, not the first body part") + } + } + + func testFetchAcceptsNonJSONTextButRejectsInvalidUTF8() async throws { + try await withOrigin { origin in + let text = await fetch(origin, "/fetch/text") + XCTAssertEqual(text, .response(status: 200, body: Data("plain text, not JSON".utf8))) + let invalid = await fetch(origin, "/fetch/invalid-utf8") + XCTAssertEqual(invalid, .failed) + } + } + + func testFetchRejectsEncodedResponses() async throws { + try await withOrigin { origin in + let outcome = await fetch(origin, "/fetch/gzip") + XCTAssertEqual(outcome, .failed) + } + } + + func testFetchDoesNotFollowRedirectsAndReturnsTheRedirectStatus() async throws { + try await withOrigin { origin in + let outcome = await fetch(origin, "/fetch/redirect", headers: ["authorization": "Bearer fixture-token"]) + XCTAssertEqual(outcome, .response(status: 302, body: Data("{}".utf8))) + XCTAssertEqual(origin.requests.value.map(\.path), ["/fetch/redirect"]) + } + } + + func testFetchResponseCapAppliesToChunkedBodiesAndLegacyPerformStillDiscardsBodies() async throws { + try await withOrigin { origin in + let capped = await fetch(origin, "/fetch/chunked-big", cap: 1500) + XCTAssertEqual(capped, .tooLarge) + let roomy = await fetch(origin, "/fetch/chunked-big") + XCTAssertEqual(roomy, .response(status: 200, body: Data(repeating: 0x78, count: 4096))) + let legacy = await origin.transport.perform(.init(host: "api.example.com", path: "/fetch/text", headers: [:]), isAuthorized: { true }) + XCTAssertEqual(legacy, .response(200)) + XCTAssertEqual(origin.requests.value.last?.acceptEncodingValues, [], "legacy requests keep their exact headers") + } + } + + func testFetchDeadlineIsCappedByTheCallerAndClosesASilentOrigin() async throws { + try await withOrigin { origin in + let start = ContinuousClock.now + let outcome = await fetch(origin, "/silent", timeout: 300) + XCTAssertEqual(outcome, .timedOut) + XCTAssertLessThan(start.duration(to: .now), .seconds(3)) + } + } + + func testFetchCancellationClosesAnOutstandingResponse() async throws { + try await withOrigin { origin in + let task = Task { await fetch(origin, "/silent") } + for _ in 0 ..< 100 where origin.requests.value.isEmpty { + try? await Task.sleep(nanoseconds: 10_000_000) + } + XCTAssertEqual(origin.requests.value.map(\.path), ["/silent"]) + task.cancel() + let outcome = await task.value + XCTAssertEqual(outcome, .cancelled) + } + } + + func testFetchRevokedAuthorizationNeverReachesTheOrigin() async throws { + try await withOrigin { origin in + let outcome = await origin.transport.fetch(.init(host: "api.example.com", path: "/fetch/text", headers: [:]), + timeoutMilliseconds: 1000, maxResponseBytes: 1024, isAuthorized: { false }) + XCTAssertEqual(outcome, .rejected) + XCTAssertTrue(origin.requests.value.isEmpty) + } + } +} diff --git a/Packages/InterceptorAutomation/Sources/AutomationCore/PluginOutbound.swift b/Packages/InterceptorAutomation/Sources/AutomationCore/PluginOutbound.swift index dc44060..5be6ccc 100644 --- a/Packages/InterceptorAutomation/Sources/AutomationCore/PluginOutbound.swift +++ b/Packages/InterceptorAutomation/Sources/AutomationCore/PluginOutbound.swift @@ -28,7 +28,9 @@ public enum PluginOutboundPolicy { } } - public static func isAllowedJSONBody(_ data: Data) -> Bool { checkJSONBody(data) == .valid } + public static func isAllowedJSONBody(_ data: Data) -> Bool { + checkJSONBody(data) == .valid + } private static let denied: Set = [ "host", "content-length", "transfer-encoding", "connection", "upgrade", "te", "trailer", "expect", "keep-alive", "set-cookie", @@ -80,20 +82,26 @@ public enum PluginOutboundPolicy { private static func isSafePath(_ p: String) -> Bool { guard PluginManifest.isEncodedPath(p) else { return false } let u = Array(p.utf8) - func hex(_ c: UInt8) -> UInt8 { c <= 0x39 ? c - 0x30 : (c | 0x20) - 0x61 + 10 } + func hex(_ c: UInt8) -> UInt8 { + c <= 0x39 ? c - 0x30 : (c | 0x20) - 0x61 + 10 + } var i = 0 while i < u.count { if u[i] == 0x25 { let v = hex(u[i + 1]) << 4 | hex(u[i + 2]) - if v < 0x20 || v == 0x7F || v == 0x5C { return false } + if v < 0x20 || v == 0x7F || v == 0x5C { + return false + } i += 3 - } else { i += 1 } + } else { + i += 1 + } } return true } } -/// A validated fixed GET, POST or PUT destination and the header names a hook may supply for it. +/// A validated fixed GET destination and the header names a hook may supply for it. public struct PluginOutboundEndpoint: Equatable, Sendable { public let url: String public let method: String @@ -112,7 +120,7 @@ public struct PluginOutboundEndpoint: Equatable, Sendable { let bad = AutomationError.invalidManifest let f = try JSONFields(v, required: ["url", "method", "headers"], error: bad) let url = try f.string("url"), method = try f.string("method"), headers = try f.strings("headers") - guard ["GET", "POST", "PUT"].contains(method), PluginOutboundPolicy.isAllowedURL(url), + guard method == "GET", PluginOutboundPolicy.isAllowedURL(url), headers.count <= PluginOutboundPolicy.maxDeclaredHeaders, Set(headers).count == headers.count, headers.allSatisfy(PluginOutboundPolicy.isAllowedHeaderName) else { throw bad } return PluginOutboundEndpoint(url: url, method: method, headers: headers) @@ -129,33 +137,17 @@ public enum PluginOutboundIntentError: Error, Equatable, Sendable { case malformed, unknownBinding, undeclaredHeader, invalidHeaderValue, limitExceeded } -/// An HTTP action `{type, binding, headers[, jsonBody]}` checked against a manifest. The URL and method come only -/// from the manifest. `jsonBody` is the exact compact JSON string captured by the bridge, forwarded byte for byte. +/// An HTTP action `{type, binding, headers}` checked against a manifest. The URL comes only from the manifest. public struct PluginOutboundIntent: Equatable, Sendable { public let binding: String public let endpoint: PluginOutboundEndpoint public let headers: [String: String] - /// Validated strict-JSON UTF-8 bytes; nil means no JSON body; POST/PUT frame that as zero bytes. - public let jsonBody: Data? public static func validating(_ action: JSONValue, manifest: PluginManifest) throws -> PluginOutboundIntent { - guard case .object(let o) = action, o.keys.contains("type"), o.keys.contains("binding"), o.keys.contains("headers"), - Set(o.keys).isSubset(of: ["type", "binding", "headers", "jsonBody"]), + guard case .object(let o) = action, Set(o.keys) == ["type", "binding", "headers"], case .string("http")? = o["type"], case .string(let binding)? = o["binding"], case .object(let raw)? = o["headers"] else { throw PluginOutboundIntentError.malformed } guard let endpoint = manifest.outbound[binding] else { throw PluginOutboundIntentError.unknownBinding } - var body: Data? - if let b = o["jsonBody"] { - guard endpoint.method != "GET", case .string(let s) = b else { throw PluginOutboundIntentError.malformed } - let data = Data(s.utf8) - guard data.count <= PluginOutboundPolicy.maxJSONBodyBytes else { throw PluginOutboundIntentError.limitExceeded } - switch PluginOutboundPolicy.checkJSONBody(data) { - case .valid: break - case .overLimit: throw PluginOutboundIntentError.limitExceeded - case .invalid: throw PluginOutboundIntentError.malformed - } - body = data - } var headers: [String: String] = [:], total = 0 for (name, value) in raw { guard endpoint.headers.contains(name) else { throw PluginOutboundIntentError.undeclaredHeader } @@ -166,9 +158,6 @@ public struct PluginOutboundIntent: Equatable, Sendable { headers[name] = s } guard total <= PluginOutboundPolicy.maxTotalHeaderValueBytes else { throw PluginOutboundIntentError.limitExceeded } - if body != nil, let contentType = headers["content-type"], contentType != "application/json" { - throw PluginOutboundIntentError.invalidHeaderValue - } - return PluginOutboundIntent(binding: binding, endpoint: endpoint, headers: headers, jsonBody: body) + return PluginOutboundIntent(binding: binding, endpoint: endpoint, headers: headers) } } diff --git a/Packages/InterceptorAutomation/Sources/AutomationRuntime/JavaScriptExecutor.swift b/Packages/InterceptorAutomation/Sources/AutomationRuntime/JavaScriptExecutor.swift index 4a05736..df2f782 100644 --- a/Packages/InterceptorAutomation/Sources/AutomationRuntime/JavaScriptExecutor.swift +++ b/Packages/InterceptorAutomation/Sources/AutomationRuntime/JavaScriptExecutor.swift @@ -1,5 +1,5 @@ -import CQuickJS import AutomationCore +import CQuickJS import Foundation /// Which declarative hook of a plugin source is invoked. @@ -14,17 +14,17 @@ public enum JavaScriptHook: String, Sendable, CaseIterable { /// Global function name the script must define for this hook (legacy v1 hooks only). public var functionName: String { switch self { - case .request: return "onRequest" - case .response: return "onResponse" - case .requestEnter, .requestLeave, .responseEnter, .responseLeave: return rawValue + case .request: "onRequest" + case .response: "onResponse" + case .requestEnter, .requestLeave, .responseEnter, .responseLeave: rawValue } } /// The four dotted lifecycle phases run through `JavaScriptExecutor.runV2` only. public var isLifecyclePhase: Bool { switch self { - case .request, .response: return false - case .requestEnter, .requestLeave, .responseEnter, .responseLeave: return true + case .request, .response: false + case .requestEnter, .requestLeave, .responseEnter, .responseLeave: true } } } @@ -43,6 +43,9 @@ public enum JavaScriptExecutionError: Error, Equatable, Sendable { case internalFailure } +/// Internal scheduling signal for a read-only hook; never a script-visible API. +public struct JavaScriptAsyncRequired: Error, Sendable {} + public enum JavaScriptLimits { public static let deadlineMilliseconds = 50 public static let heapBytes = 8 * 1024 * 1024 @@ -76,14 +79,18 @@ private final class Job: @unchecked Sendable { func cancel() { lock.lock() - if let token { qjs_cancel_token_cancel(token) } + if let token { + qjs_cancel_token_cancel(token) + } lock.unlock() } /// Must be called after `qjs_run` has returned. func finish() { lock.lock() - if let token { qjs_cancel_token_free(token) } + if let token { + qjs_cancel_token_free(token) + } token = nil lock.unlock() } @@ -103,14 +110,17 @@ public final class JavaScriptExecutor: @unchecked Sendable { guard !hook.isLifecyclePhase, source.utf8.count <= JavaScriptLimits.maxSourceBytes, eventJSON.count <= JavaScriptLimits.maxEventBytes, - configJSON.count <= JavaScriptLimits.maxConfigBytes else { + configJSON.count <= JavaScriptLimits.maxConfigBytes + else { throw JavaScriptExecutionError.invalidInput } return try await admitAndRun(input: Data(source.utf8), hookName: hook.functionName, event: eventJSON, config: configJSON, isV2: false) } - private func admitAndRun(input: Data, hookName: String, event: Data, config: Data, isV2: Bool) async throws -> Data { - if Task.isCancelled { throw JavaScriptExecutionError.cancelled } + private func admitAndRun(input: Data, hookName: String, event: Data, config: Data, isV2: Bool, detectAsync: Bool = false) async throws -> Data { + if Task.isCancelled { + throw JavaScriptExecutionError.cancelled + } guard let job = Job() else { throw JavaScriptExecutionError.internalFailure } guard admit(job) else { job.finish() @@ -121,7 +131,7 @@ public final class JavaScriptExecutor: @unchecked Sendable { try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in queue.async { let outcome = Result { try Self.execute(job: job, source: sourceBytes, hook: hookName, - event: event, config: config, isV2: isV2) } + event: event, config: config, isV2: isV2, detectAsync: detectAsync) } // Release admission before resuming so the caller can immediately run again. self.release(job) continuation.resume(with: outcome) @@ -132,17 +142,21 @@ public final class JavaScriptExecutor: @unchecked Sendable { } } - /// Evaluates only the source selected by the full strict schema 2 package and raw event. /// The native C boundary independently validates every file, route, reference and grant. public func runV2(packageJSON: Data, hook: JavaScriptHook, eventJSON: Data, configJSON: Data) async throws -> Data { - guard hook.isLifecyclePhase, !packageJSON.isEmpty, + try await runV2(packageJSON: packageJSON, hook: hook, eventJSON: eventJSON, configJSON: configJSON, detectAsync: false) + } + + public func runV2(packageJSON: Data, hook: JavaScriptHook, eventJSON: Data, configJSON: Data, detectAsync: Bool) async throws -> Data { + guard !detectAsync || hook == .responseLeave, hook.isLifecyclePhase, !packageJSON.isEmpty, packageJSON.count <= JavaScriptLimits.maxPackageBytes, eventJSON.count <= JavaScriptLimits.maxEventBytes, - configJSON.count <= JavaScriptLimits.maxConfigBytes else { + configJSON.count <= JavaScriptLimits.maxConfigBytes + else { throw JavaScriptExecutionError.invalidInput } - return try await admitAndRun(input: packageJSON, hookName: hook.functionName, event: eventJSON, config: configJSON, isV2: true) + return try await admitAndRun(input: packageJSON, hookName: hook.functionName, event: eventJSON, config: configJSON, isV2: true, detectAsync: detectAsync) } /// Cancels the currently admitted invocation, if any. Idle calls must not affect later runs. @@ -156,7 +170,9 @@ public final class JavaScriptExecutor: @unchecked Sendable { private func admit(_ job: Job) -> Bool { lock.lock() defer { lock.unlock() } - if current != nil { return false } + if current != nil { + return false + } current = job return true } @@ -164,15 +180,18 @@ public final class JavaScriptExecutor: @unchecked Sendable { private func release(_ job: Job) { job.finish() lock.lock() - if current === job { current = nil } + if current === job { + current = nil + } lock.unlock() } - private static func execute(job: Job, source: [UInt8], hook: String, event: Data, config: Data, isV2: Bool) throws -> Data { + private static func execute(job: Job, source: [UInt8], hook: String, event: Data, config: Data, isV2: Bool, detectAsync: Bool) throws -> Data { // Run strict parsing on the worker queue, before JS can discard duplicate keys. do { guard case .object = try JSONValue(parsing: event), - case .object = try JSONValue(parsing: config) else { + case .object = try JSONValue(parsing: config) + else { throw JavaScriptExecutionError.invalidInput } } catch { throw JavaScriptExecutionError.invalidInput } @@ -185,13 +204,17 @@ public final class JavaScriptExecutor: @unchecked Sendable { max_config_bytes: JavaScriptLimits.maxConfigBytes, max_result_bytes: JavaScriptLimits.maxResultBytes, max_result_depth: JavaScriptLimits.maxResultDepth, - max_actions: JavaScriptLimits.maxActions) + max_actions: JavaScriptLimits.maxActions, + ) let token = job.nativeToken var result = source.withUnsafeBufferPointer { src in event.withUnsafeBytes { ev in config.withUnsafeBytes { cfg in let evp = ev.baseAddress?.assumingMemoryBound(to: UInt8.self) let cfgp = cfg.baseAddress?.assumingMemoryBound(to: UInt8.self) + if isV2 && detectAsync { + return qjs_run_v2_probe(token, &limits, src.baseAddress, src.count, hook, evp, ev.count, cfgp, cfg.count) + } if isV2 { return qjs_run_v2(token, &limits, src.baseAddress, src.count, hook, evp, ev.count, cfgp, cfg.count) } @@ -201,21 +224,22 @@ public final class JavaScriptExecutor: @unchecked Sendable { } defer { qjs_result_free(&result) } switch result.status { - case Int32(QJS_OK): - guard let bytes = result.data, result.length <= JavaScriptLimits.maxResultBytes else { - throw JavaScriptExecutionError.invalidResult - } - let data = Data(bytes: bytes, count: result.length) - do { _ = try JSONValue(parsing: data) } - catch { throw JavaScriptExecutionError.invalidResult } - return data - case Int32(QJS_TIMEOUT): throw JavaScriptExecutionError.timeout - case Int32(QJS_CANCELLED): throw JavaScriptExecutionError.cancelled - case Int32(QJS_MEMORY_OR_STACK): throw JavaScriptExecutionError.memoryOrStack - case Int32(QJS_INVALID_INPUT): throw JavaScriptExecutionError.invalidInput - case Int32(QJS_INVALID_RESULT): throw JavaScriptExecutionError.invalidResult - case Int32(QJS_SCRIPT_ERROR): throw JavaScriptExecutionError.scriptError - default: throw JavaScriptExecutionError.internalFailure + case Int32(QJS_OK): + guard let bytes = result.data, result.length <= JavaScriptLimits.maxResultBytes else { + throw JavaScriptExecutionError.invalidResult + } + let data = Data(bytes: bytes, count: result.length) + do { _ = try JSONValue(parsing: data) } + catch { throw JavaScriptExecutionError.invalidResult } + return data + case Int32(QJS_ASYNC_REQUIRED): throw JavaScriptAsyncRequired() + case Int32(QJS_TIMEOUT): throw JavaScriptExecutionError.timeout + case Int32(QJS_CANCELLED): throw JavaScriptExecutionError.cancelled + case Int32(QJS_MEMORY_OR_STACK): throw JavaScriptExecutionError.memoryOrStack + case Int32(QJS_INVALID_INPUT): throw JavaScriptExecutionError.invalidInput + case Int32(QJS_INVALID_RESULT): throw JavaScriptExecutionError.invalidResult + case Int32(QJS_SCRIPT_ERROR): throw JavaScriptExecutionError.scriptError + default: throw JavaScriptExecutionError.internalFailure } } } diff --git a/Packages/InterceptorAutomation/Sources/AutomationRuntime/JavaScriptFetchExecutor.swift b/Packages/InterceptorAutomation/Sources/AutomationRuntime/JavaScriptFetchExecutor.swift new file mode 100644 index 0000000..56de93e --- /dev/null +++ b/Packages/InterceptorAutomation/Sources/AutomationRuntime/JavaScriptFetchExecutor.swift @@ -0,0 +1,297 @@ +import AutomationCore +import CQuickJS +import Foundation + +public struct JavaScriptFetchRequest: Sendable { + public let url: String + public let method: String + public let headers: [String: String] + public let body: Data? + public let timeoutMilliseconds: Int + public let maxResponseBytes: Int +} + +public struct JavaScriptFetchResponse: Sendable { + public let status: Int + public let body: Data + public init(status: Int, body: Data) { + self.status = status + self.body = body + } +} + +/// One fetch-enabled invocation: native cancel token plus the in-flight transport task. +/// Both are guarded by one lock so a late `cancel()` can neither touch a freed token nor miss a +/// task installed after cancellation was requested. +private final class FetchJob: @unchecked Sendable { + private let lock = NSLock() + private var token: OpaquePointer? + private var task: Task? + private var cancelled = false + + init?() { + guard let token = qjs_cancel_token_new() else { return nil } + self.token = token + } + + var nativeToken: OpaquePointer? { + lock.lock() + defer { lock.unlock() } + return token + } + + var isCancelled: Bool { + lock.lock() + defer { lock.unlock() } + return cancelled + } + + func cancel() { + lock.lock() + cancelled = true + if let token { + qjs_cancel_token_cancel(token) + } + let task = task + lock.unlock() + task?.cancel() + } + + /// Installs the task; if cancellation already happened the task is cancelled immediately. + func install(_ task: Task) { + lock.lock() + self.task = task + let already = cancelled + lock.unlock() + if already { + task.cancel() + } + } + + func clearTask() { + lock.lock() + task = nil + lock.unlock() + } + + /// Call only after `qjs_run_v2_fetch` has returned. + func finish() { + lock.lock() + if let token { + qjs_cancel_token_free(token) + } + token = nil + lock.unlock() + } +} + +private final class FetchContext: @unchecked Sendable { + let job: FetchJob + let transport: JavaScriptFetchExecutor.Transport + init(job: FetchJob, transport: @escaping JavaScriptFetchExecutor.Transport) { + self.job = job + self.transport = transport + } +} + +private let fetchMaxResponseBytes = 1024 * 1024 + +/// C callback: decodes the validated request, drives the async transport to completion on this +/// owned thread and always awaits/stops the transport task before returning. +private let fetchCallback: QJSFetchCallback = { opaque, json, length, timeoutMs, reply in + guard let opaque, let json, let reply else { return 2 } + let context = Unmanaged.fromOpaque(opaque).takeUnretainedValue() + let job = context.job + if job.isCancelled { + return 2 + } + guard let object = try? JSONSerialization.jsonObject(with: Data(bytes: json, count: length)) as? [String: Any], + let url = object["url"] as? String, let method = object["method"] as? String, + let headers = object["headers"] as? [String: String] else { return 1 } + let request = JavaScriptFetchRequest( + url: url, method: method, headers: headers, + body: (object["body"] as? String).map { Data($0.utf8) }, + timeoutMilliseconds: Int(timeoutMs), maxResponseBytes: fetchMaxResponseBytes, + ) + + let done = DispatchSemaphore(value: 0) + let transport = context.transport + let box = ResultBox() + let task = Task { + do { box.value = try await .success(transport(request)) } catch { box.value = .failure(error) } + done.signal() + } + job.install(task) + var timedOut = false + if done.wait(timeout: .now() + .milliseconds(Int(timeoutMs) + 250)) == .timedOut { + timedOut = true + task.cancel() + done.wait() + } + let outcome = box.value ?? .failure(CancellationError()) + job.clearTask() + if job.isCancelled { + return 2 + } + switch outcome { + case let .success(response): + guard (100 ... 599).contains(response.status), response.body.count <= fetchMaxResponseBytes else { return 1 } + let ok = response.body.withUnsafeBytes { raw in + qjs_fetch_reply_set(reply, Int32(response.status), raw.baseAddress?.assumingMemoryBound(to: UInt8.self), raw.count) + } + return ok == 0 ? 0 : 1 + case let .failure(error): + return error is CancellationError && !timedOut ? 2 : 1 + } +} + +private final class ResultBox: @unchecked Sendable { + var value: Result? // written before the semaphore signal +} + +/// Runs `response.onLeave` with the standard global `fetch`, one VM per call on an owned thread. +/// At most two instances run at once process-wide; one per executor. Extras fail with `.busy`. +public final class JavaScriptFetchExecutor: @unchecked Sendable { + /// Trusted host transport: honor the request deadline and Task cancellation, and finish owned + /// I/O before returning. The callback waits for completion so no socket outlives the invocation. + public typealias Transport = @Sendable (JavaScriptFetchRequest) async throws -> JavaScriptFetchResponse + + private static let globalLock = NSLock() + private nonisolated(unsafe) static var globalActive = 0 + private static let globalSlots = 2 + private static let stackBytes = 2 * 1024 * 1024 + static let cpuDeadlineMilliseconds = 250 + + private let lock = NSLock() + private var current: FetchJob? + + public init() {} + + public func runV2(packageJSON: Data, hook: JavaScriptHook, eventJSON: Data, configJSON: Data, + transport: @escaping Transport) async throws -> Data + { + guard hook == .responseLeave, !packageJSON.isEmpty, + packageJSON.count <= JavaScriptLimits.maxPackageBytes, + eventJSON.count <= JavaScriptLimits.maxEventBytes, + configJSON.count <= JavaScriptLimits.maxConfigBytes + else { + throw JavaScriptExecutionError.invalidInput + } + if Task.isCancelled { + throw JavaScriptExecutionError.cancelled + } + guard let job = FetchJob() else { throw JavaScriptExecutionError.internalFailure } + guard admit(job) else { + job.finish() + throw JavaScriptExecutionError.busy + } + let hookName = hook.functionName + return try await withTaskCancellationHandler { + try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in + let thread = Thread { + let outcome = Result { + try Self.execute(job: job, package: packageJSON, hook: hookName, event: eventJSON, + config: configJSON, transport: transport) + } + // Release admission (instance and global) before resuming the caller. + self.release(job) + continuation.resume(with: outcome) + } + thread.name = "app.interceptor.automation.fetch" + thread.stackSize = Self.stackBytes + thread.qualityOfService = .userInitiated + thread.start() + } + } onCancel: { + job.cancel() + } + } + + /// Cancels the currently admitted invocation, if any. Idle calls must not affect later runs. + public func cancel() { + lock.lock() + let job = current + lock.unlock() + job?.cancel() + } + + private func admit(_ job: FetchJob) -> Bool { + lock.lock() + defer { lock.unlock() } + if current != nil { + return false + } + Self.globalLock.lock() + defer { Self.globalLock.unlock() } + if Self.globalActive >= Self.globalSlots { + return false + } + Self.globalActive += 1 + current = job + return true + } + + private func release(_ job: FetchJob) { + job.finish() + lock.lock() + if current === job { + current = nil + Self.globalLock.lock() + Self.globalActive -= 1 + Self.globalLock.unlock() + } + lock.unlock() + } + + private static func execute(job: FetchJob, package: Data, hook: String, event: Data, config: Data, + transport: @escaping Transport) throws -> Data + { + do { + guard case .object = try JSONValue(parsing: event), + case .object = try JSONValue(parsing: config) else { throw JavaScriptExecutionError.invalidInput } + } catch { throw JavaScriptExecutionError.invalidInput } + var limits = QJSLimits( + deadline_ms: cpuDeadlineMilliseconds, + heap_bytes: JavaScriptLimits.heapBytes, + stack_bytes: JavaScriptLimits.stackBytes, + max_source_bytes: JavaScriptLimits.maxSourceBytes, + max_event_bytes: JavaScriptLimits.maxEventBytes, + max_config_bytes: JavaScriptLimits.maxConfigBytes, + max_result_bytes: JavaScriptLimits.maxResultBytes, + max_result_depth: JavaScriptLimits.maxResultDepth, + max_actions: JavaScriptLimits.maxActions, + ) + let context = FetchContext(job: job, transport: transport) + let token = job.nativeToken + var result = withExtendedLifetime(context) { + let opaque = Unmanaged.passUnretained(context).toOpaque() + return package.withUnsafeBytes { pkg in + event.withUnsafeBytes { ev in + config.withUnsafeBytes { cfg in + qjs_run_v2_fetch(token, &limits, fetchCallback, opaque, + pkg.baseAddress?.assumingMemoryBound(to: UInt8.self), pkg.count, hook, + ev.baseAddress?.assumingMemoryBound(to: UInt8.self), ev.count, + cfg.baseAddress?.assumingMemoryBound(to: UInt8.self), cfg.count) + } + } + } + } + defer { qjs_result_free(&result) } + switch result.status { + case Int32(QJS_OK): + guard let bytes = result.data, result.length <= JavaScriptLimits.maxResultBytes else { + throw JavaScriptExecutionError.invalidResult + } + let data = Data(bytes: bytes, count: result.length) + do { _ = try JSONValue(parsing: data) } catch { throw JavaScriptExecutionError.invalidResult } + return data + case Int32(QJS_TIMEOUT): throw JavaScriptExecutionError.timeout + case Int32(QJS_CANCELLED): throw JavaScriptExecutionError.cancelled + case Int32(QJS_MEMORY_OR_STACK): throw JavaScriptExecutionError.memoryOrStack + case Int32(QJS_INVALID_INPUT): throw JavaScriptExecutionError.invalidInput + case Int32(QJS_INVALID_RESULT): throw JavaScriptExecutionError.invalidResult + case Int32(QJS_SCRIPT_ERROR): throw JavaScriptExecutionError.scriptError + default: throw JavaScriptExecutionError.internalFailure + } + } +} diff --git a/Packages/InterceptorAutomation/Sources/CQuickJS/bridge.c b/Packages/InterceptorAutomation/Sources/CQuickJS/bridge.c index 1de296e..6f88f8e 100644 --- a/Packages/InterceptorAutomation/Sources/CQuickJS/bridge.c +++ b/Packages/InterceptorAutomation/Sources/CQuickJS/bridge.c @@ -81,13 +81,10 @@ typedef struct { #define MAX_INTENTS 16 #define OUT_MAX_VALUE 4096u #define OUT_MAX_TOTAL 8192u -#define OUT_MAX_JSON_BYTES 8192u -#define OUT_MAX_JSON_DEPTH 16 -typedef struct { Str name; Str *headers; size_t nheaders; int method; /* 0 GET, 1 POST, 2 PUT */ } OutDecl; +typedef struct { Str name; Str *headers; size_t nheaders; } OutDecl; // Snapshot copy of one validated Interceptor.send call; never references JS memory. -// `json` is the exact compact serialization taken at send time; has_json distinguishes absent from present. -typedef struct { Str binding; Str *names; Str *values; size_t n; int has_json; Str json; } Intent; +typedef struct { Str binding; Str *names; Str *values; size_t n; } Intent; typedef struct RunState { QJSCancelToken *token; @@ -118,7 +115,14 @@ typedef struct RunState { int read_body_json; int body_writable; // enter phase with the manifest write grant for the invoked leg // v2 only: declared outbound bindings and the HTTP intents recorded by Interceptor.send. - int in_callback; // set only while the host invokes a registered callback + int in_callback; // set only while the host invokes a registered callback (and drains its promise jobs) + int requires_async; // read-only probe attempted a fetch; no network has occurred + // fetch mode only (qjs_run_v2_fetch): trusted blocking host callback plus aggregate caps. + QJSFetchCallback fetch_cb; + void *fetch_opaque; + uint64_t wall_deadline_ns; // 0 when not in fetch mode + unsigned nrequests; + size_t response_total; int nout; OutDecl out[MAX_OUT]; Intent *intents; @@ -137,7 +141,8 @@ static int budget_exceeded(RunState *st) { st->stop = QJS_CANCELLED; return 1; } - if (now_ns() >= st->deadline_ns) { + uint64_t now = now_ns(); + if (now >= st->deadline_ns || (st->wall_deadline_ns && now >= st->wall_deadline_ns)) { st->stop = QJS_TIMEOUT; return 1; } @@ -1280,11 +1285,8 @@ static JSValue js_attach(JSContext *ctx, JSValueConst this_val, int argc, JSValu return JS_ThrowTypeError(ctx, "invalid Interceptor.attach"); } -static int serialize_value(RunState *st, JSContext *ctx, JSValueConst val, int depth, int max_depth, size_t cap, Buf *out); - static void intent_free(Intent *it) { str_free(&it->binding); - str_free(&it->json); strs_free(it->names, it->n); strs_free(it->values, it->n); memset(it, 0, sizeof(*it)); @@ -1297,37 +1299,27 @@ static void intents_free(RunState *st) { st->nintents = 0; } -// Interceptor.send(binding, {headers, json?}): validates immediately and records a snapshot copy. Performs no I/O, +// Interceptor.send(binding, {headers}): validates immediately and records a snapshot copy. Performs no I/O, // returns undefined. Any violation (including a call outside a callback) is a sticky failure. static JSValue js_send(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { - static const char *const ok_keys[] = {"headers", "json"}; + static const char *const ok_keys[] = {"headers"}; (void)this_val; RunState *st = JS_GetContextOpaque(ctx); - JSValue opt[2], hv = JS_UNDEFINED; + JSValue opt[1], hv = JS_UNDEFINED; const OutDecl *decl = NULL; Intent it; JSPropertyEnum *tab = NULL; uint32_t cnt = 0; size_t total = 0; int ok = 0; - unsigned seen = 0; memset(&it, 0, sizeof(it)); - opt[0] = opt[1] = JS_UNDEFINED; + opt[0] = JS_UNDEFINED; if (!st || !st->in_callback || argc != 2 || !st->intents || st->nintents >= st->max_intents) goto done; if (!get_str(ctx, argv[0], &it.binding, 32)) goto done; for (int i = 0; i < st->nout; i++) if (str_cmp(&st->out[i].name, &it.binding) == 0) decl = &st->out[i]; if (!decl) goto done; - if (!read_obj_fields(st, ctx, argv[1], ok_keys, 2, 1u, opt, &seen)) goto done; - // Presence is independent of the value: a present `json: undefined` is invalid, not absent. - if (seen & 2u) { - Buf jb; - if (decl->method == 0 || JS_IsUndefined(opt[1])) goto done; - if (!serialize_value(st, ctx, opt[1], 1, OUT_MAX_JSON_DEPTH, OUT_MAX_JSON_BYTES, &jb)) goto done; - it.json.s = (char *)jb.p; - it.json.n = jb.len; - it.has_json = 1; - } + if (!read_obj(st, ctx, argv[1], ok_keys, 1, 1u, opt)) goto done; hv = opt[0]; if (JS_GetClassID(hv) != st->cls_object) goto done; if (JS_GetOwnPropertyNames(ctx, &tab, &cnt, hv, JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK) < 0) { tab = NULL; goto done; } @@ -1347,8 +1339,6 @@ static JSValue js_send(JSContext *ctx, JSValueConst this_val, int argc, JSValueC if (!(c == '\t' || (c >= 0x20 && c <= 0x7E))) good = 0; } if (total > OUT_MAX_TOTAL) good = 0; - if (good && it.has_json && it.names[i].n == 12 && !memcmp(it.names[i].s, "content-type", 12) && - !(it.values[i].n == 16 && !memcmp(it.values[i].s, "application/json", 16))) good = 0; } JS_FreeValue(ctx, key); JS_FreeValue(ctx, val); @@ -1366,7 +1356,6 @@ static JSValue js_send(JSContext *ctx, JSValueConst this_val, int argc, JSValueC done: if (tab) JS_FreePropertyEnum(ctx, tab, cnt); JS_FreeValue(ctx, opt[0]); - JS_FreeValue(ctx, opt[1]); intent_free(&it); if (ok) return JS_UNDEFINED; if (st) st->attach_failed = 1; @@ -1391,18 +1380,7 @@ static void emit_intent(Buf *b, const Intent *it) { } b_ch(b, '"'); } - b_ch(b, '}'); - if (it->has_json) { - b_str(b, ",\"jsonBody\":\""); - for (size_t k = 0; k < it->json.n; k++) { - unsigned char c = (unsigned char)it->json.s[k]; - if (c == '"' || c == '\\') { b_ch(b, '\\'); b_ch(b, (char)c); } - else if (c < 0x20 || c == 0x7F) { char e[7]; snprintf(e, sizeof(e), "\\u%04x", c); b_str(b, e); } - else b_ch(b, (char)c); - } - b_ch(b, '"'); - } - b_ch(b, '}'); + b_str(b, "}}"); } static int install_interceptor(JSContext *ctx) { @@ -1755,7 +1733,7 @@ static void out_free(OutDecl *d) { memset(d, 0, sizeof(*d)); } -// `v` -> optional strict {binding:{url,method:GET|POST|PUT,headers:[...]}} (<= 4 bindings). Takes copies into st->out. +// `v` -> optional strict {binding:{url,method:'GET',headers:[...]}} (<= 4 bindings). Takes copies into st->out. static int parse_outbound(RunState *st, JSContext *ctx, JSValueConst v) { static const char *const ok_keys[] = {"url", "method", "headers"}; if (JS_GetClassID(v) != st->cls_object) return 0; @@ -1773,7 +1751,7 @@ static int parse_outbound(RunState *st, JSContext *ctx, JSValueConst v) { if (good) { good = read_obj(st, ctx, val, ok_keys, 3, 7u, f); if (good) { - good = (str_eq(ctx, f[1], "GET") ? (d->method = 0, 1) : str_eq(ctx, f[1], "POST") ? (d->method = 1, 1) : str_eq(ctx, f[1], "PUT") ? (d->method = 2, 1) : 0) && get_str(ctx, f[0], &url, 2048) && out_url_ok(&url) && + good = str_eq(ctx, f[1], "GET") && get_str(ctx, f[0], &url, 2048) && out_url_ok(&url) && get_list(st, ctx, f[2], 0, 8, &d->headers, &d->nheaders); for (size_t h = 0; good && h < d->nheaders; h++) good = out_header_ok(&d->headers[h]); for (int k = 0; k < 3; k++) JS_FreeValue(ctx, f[k]); @@ -2187,15 +2165,407 @@ static int v2_safe_integer_tokens(const uint8_t *text, size_t len) { return 1; } +// MARK: standard global fetch (fetch mode only) +// +// One synchronous trusted host callback per request. fetch() validates natively, blocks in the callback +// (the wait extends the CPU deadline but never the wall deadline) and returns an already-settled +// Promise. Promise jobs are drained only while a registered callback is active. + +#define FETCH_CPU_MS 250u +#define FETCH_WALL_MS 120000ull +#define FETCH_MAX_REQUESTS 64u +#define FETCH_MAX_JSON_BYTES 8192u +#define FETCH_MAX_JSON_DEPTH 16 +#define FETCH_REQUEST_MS 5000u +#define FETCH_MAX_BODY (1024u * 1024u) +#define FETCH_MAX_TOTAL (16u * 1024u * 1024u) +#define FETCH_REQ_BODY_MAX 8192u +#define FETCH_REQ_JSON_CAP (128u * 1024u) + +struct QJSFetchReply { + int32_t status; + uint8_t *body; + size_t len; + int has; + int overflow; +}; + +int32_t qjs_fetch_reply_set(QJSFetchReply *reply, int32_t status, const uint8_t *body, size_t len) { + if (!reply) return 1; + if (status < 100 || status > 599 || len > FETCH_MAX_BODY || (len && !body)) { + reply->overflow = 1; + return 1; + } + uint8_t *copy = copy_z(body, len); + if (!copy) { reply->overflow = 1; return 1; } + free(reply->body); + reply->body = copy; + reply->len = len; + reply->status = status; + reply->has = 1; + return 0; +} + +// Consumes `v`. Returns a Promise already fulfilled (reject == 0) or rejected (reject == 1) with it. +static JSValue settled_promise(JSContext *ctx, JSValue v, int reject) { + JSValue f[2]; + JSValue p = JS_NewPromiseCapability(ctx, f); + if (JS_IsException(p)) { JS_FreeValue(ctx, v); return p; } + JSValue r = JS_Call(ctx, f[reject], JS_UNDEFINED, 1, (JSValueConst *)&v); + int failed = JS_IsException(r); + JS_FreeValue(ctx, r); + JS_FreeValue(ctx, v); + JS_FreeValue(ctx, f[0]); + JS_FreeValue(ctx, f[1]); + if (failed) { JS_FreeValue(ctx, p); return JS_EXCEPTION; } + return p; +} + +static JSValue reject_error(JSContext *ctx, int syntax, const char *msg) { + if (syntax) JS_ThrowSyntaxError(ctx, "%s", msg); + else JS_ThrowTypeError(ctx, "%s", msg); + return settled_promise(ctx, JS_GetException(ctx), 1); +} + +// Private shared state for the two body readers; neither JS nor the Response exposes this object. +static int consume_response_body(JSContext *ctx, JSValueConst state) { + JSValue used = JS_GetPropertyStr(ctx, state, "used"); + if (JS_IsException(used)) return -1; + int consumed = JS_ToBool(ctx, used); + JS_FreeValue(ctx, used); + if (consumed < 0) return -1; + if (consumed) return 0; + return JS_SetPropertyStr(ctx, state, "used", JS_TRUE) < 0 ? -1 : 1; +} + +static JSValue js_resp_used(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic, JSValue *data) { + (void)this_val; (void)argc; (void)argv; (void)magic; + return JS_GetPropertyStr(ctx, data[0], "used"); +} + +static JSValue js_resp_text(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic, JSValue *data) { + (void)this_val; (void)argc; (void)argv; (void)magic; + int consumed = consume_response_body(ctx, data[1]); + if (consumed < 0) return JS_EXCEPTION; + if (!consumed) return reject_error(ctx, 0, "response body already consumed"); + return settled_promise(ctx, JS_DupValue(ctx, data[0]), 0); +} + +static JSValue js_resp_json(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv, int magic, JSValue *data) { + (void)this_val; (void)argc; (void)argv; (void)magic; + int consumed = consume_response_body(ctx, data[1]); + if (consumed < 0) return JS_EXCEPTION; + if (!consumed) return reject_error(ctx, 0, "response body already consumed"); + RunState *st = JS_GetContextOpaque(ctx); + size_t n; + const char *c = JS_ToCStringLen2(ctx, &n, data[0], 0); + if (!c) return JS_EXCEPTION; + int ok = json_check((const uint8_t *)c, n, 64) && v2_safe_integer_tokens((const uint8_t *)c, n); + JSValue parsed = JS_UNDEFINED; + if (ok) parsed = JS_ParseJSON(ctx, c, n, ""); + JS_FreeCString(ctx, c); + if (!ok) return reject_error(ctx, 1, "invalid JSON"); + if (JS_IsException(parsed)) { + if (!st || st->stop || st->oom) return JS_EXCEPTION; + return settled_promise(ctx, JS_GetException(ctx), 1); + } + return settled_promise(ctx, parsed, 0); +} + +static JSValue make_response(JSContext *ctx, int32_t status, const uint8_t *body, size_t len) { + JSValue obj = JS_NewObject(ctx); + JSValue bodyv = JS_NewStringLen(ctx, (const char *)body, len); + JSValue state = JS_NewObjectProto(ctx, JS_NULL); + JSValue text = JS_UNDEFINED, json = JS_UNDEFINED, used = JS_UNDEFINED; + if (JS_IsException(obj) || JS_IsException(bodyv) || JS_IsException(state)) goto fail; + if (JS_SetPropertyStr(ctx, state, "used", JS_FALSE) < 0) goto fail; + JSValueConst data[2] = {bodyv, state}; + text = JS_NewCFunctionData(ctx, js_resp_text, 0, 0, 2, data); + json = JS_NewCFunctionData(ctx, js_resp_json, 0, 0, 2, data); + used = JS_NewCFunctionData(ctx, js_resp_used, 0, 0, 1, (JSValueConst *)&state); + if (JS_IsException(text) || JS_IsException(json) || JS_IsException(used)) goto fail; + if (JS_DefinePropertyValueStr(ctx, obj, "status", JS_NewInt32(ctx, status), JS_PROP_ENUMERABLE) < 0) goto fail; + if (JS_DefinePropertyValueStr(ctx, obj, "ok", JS_NewBool(ctx, status >= 200 && status <= 299), JS_PROP_ENUMERABLE) < 0) goto fail; + JSAtom atom = JS_NewAtom(ctx, "bodyUsed"); + if (atom == JS_ATOM_NULL) goto fail; + int ok = JS_DefinePropertyGetSet(ctx, obj, atom, used, JS_UNDEFINED, JS_PROP_ENUMERABLE); + used = JS_UNDEFINED; + JS_FreeAtom(ctx, atom); + if (ok < 0) goto fail; + if (JS_SetPropertyStr(ctx, obj, "text", text) < 0) { text = JS_UNDEFINED; goto fail; } + text = JS_UNDEFINED; + if (JS_SetPropertyStr(ctx, obj, "json", json) < 0) { json = JS_UNDEFINED; goto fail; } + JS_FreeValue(ctx, bodyv); + JS_FreeValue(ctx, state); + return obj; +fail: + JS_FreeValue(ctx, obj); + JS_FreeValue(ctx, bodyv); + JS_FreeValue(ctx, text); + JS_FreeValue(ctx, json); + JS_FreeValue(ctx, state); + JS_FreeValue(ctx, used); + return JS_EXCEPTION; +} + +typedef struct { + Str url, method; + Str *names, *values; + size_t n; + Str body; + int has_body; +} FetchReq; + +static void fetch_req_free(FetchReq *r) { + str_free(&r->url); + str_free(&r->method); + strs_free(r->names, r->n); + strs_free(r->values, r->n); + str_free(&r->body); + memset(r, 0, sizeof(*r)); +} + +static int fetch_header_value_ok(const Str *v) { + for (size_t k = 0; k < v->n; k++) { + unsigned char c = (unsigned char)v->s[k]; + if (!(c == '\t' || (c >= 0x20 && c <= 0x7E))) return 0; + } + return 1; +} + +// Fills `r` from fetch(url[, init]). 1 = valid, 0 = invalid, -1 = allocation failure. +static int parse_fetch_args(RunState *st, JSContext *ctx, int argc, JSValueConst *argv, FetchReq *r) { + static const char *const keys[] = {"method", "headers", "body"}; + JSValue f[3] = {JS_UNDEFINED, JS_UNDEFINED, JS_UNDEFINED}; + JSPropertyEnum *tab = NULL; + uint32_t cnt = 0; + unsigned seen = 0; + size_t total = 0; + int ok = 0, is_write = 0; + memset(r, 0, sizeof(*r)); + if (argc < 1 || argc > 2 || !get_str(ctx, argv[0], &r->url, 2048) || !out_url_ok(&r->url)) goto done; + if (argc == 2 && !JS_IsUndefined(argv[1]) && !read_obj_fields(st, ctx, argv[1], keys, 3, 0u, f, &seen)) goto done; + + if (!JS_IsUndefined(f[0])) { + if (!get_str(ctx, f[0], &r->method, 16)) goto done; + for (size_t i = 0; i < r->method.n; i++) if (r->method.s[i] >= 'a' && r->method.s[i] <= 'z') r->method.s[i] -= 32; + } else { + r->method.s = strdup("GET"); + if (!r->method.s) { st->oom = 1; goto done; } + r->method.n = 3; + } + if (!((r->method.n == 3 && (!memcmp(r->method.s, "GET", 3) || !memcmp(r->method.s, "PUT", 3))) || + (r->method.n == 4 && !memcmp(r->method.s, "POST", 4)))) goto done; + is_write = r->method.s[0] != 'G'; + + if (!JS_IsUndefined(f[2])) { + if (!is_write || !get_str(ctx, f[2], &r->body, FETCH_REQ_BODY_MAX) || + !json_check((const uint8_t *)r->body.s, r->body.n, FETCH_MAX_JSON_DEPTH)) goto done; + r->has_body = 1; + } + if (!JS_IsUndefined(f[1])) { + if (JS_GetClassID(f[1]) != st->cls_object) goto done; + if (JS_GetOwnPropertyNames(ctx, &tab, &cnt, f[1], JS_GPN_STRING_MASK | JS_GPN_SYMBOL_MASK) < 0) { tab = NULL; goto done; } + if (cnt > 8) goto done; + } + r->names = calloc(cnt + 1, sizeof(Str)); + r->values = calloc(cnt + 1, sizeof(Str)); + if (!r->names || !r->values) { st->oom = 1; goto done; } + for (uint32_t i = 0; i < cnt; i++) { + JSValue key = JS_AtomToValue(ctx, tab[i].atom), val = JS_UNDEFINED; + int good = JS_IsString(key) && get_str(ctx, key, &r->names[i], 128); + r->n = i + 1; + if (good) { + for (size_t k = 0; k < r->names[i].n; k++) { + char *c = &r->names[i].s[k]; + if (*c >= 'A' && *c <= 'Z') *c += 32; + } + good = out_header_ok(&r->names[i]) && !(r->names[i].n == 15 && !memcmp(r->names[i].s, "accept-encoding", 15)) && + own_data(ctx, f[1], tab[i].atom, &val) && get_str(ctx, val, &r->values[i], OUT_MAX_VALUE) && + fetch_header_value_ok(&r->values[i]); + } + if (good) { + total += r->values[i].n; + if (total > OUT_MAX_TOTAL) good = 0; + for (uint32_t j = 0; good && j < i; j++) if (str_cmp(&r->names[j], &r->names[i]) == 0) good = 0; + if (good && r->has_body && r->names[i].n == 12 && !memcmp(r->names[i].s, "content-type", 12) && + !(r->values[i].n == 16 && !memcmp(r->values[i].s, "application/json", 16))) good = 0; + } + JS_FreeValue(ctx, key); + JS_FreeValue(ctx, val); + if (!good) goto done; + } + for (size_t i = 1; i < r->n; i++) + for (size_t j = i; j > 0 && str_cmp(&r->names[j - 1], &r->names[j]) > 0; j--) { + Str t = r->names[j]; r->names[j] = r->names[j - 1]; r->names[j - 1] = t; + t = r->values[j]; r->values[j] = r->values[j - 1]; r->values[j - 1] = t; + } + ok = 1; +done: + if (tab) JS_FreePropertyEnum(ctx, tab, cnt); + for (int i = 0; i < 3; i++) JS_FreeValue(ctx, f[i]); + if (!ok) { int oom = st->oom; fetch_req_free(r); return oom ? -1 : 0; } + return 1; +} + +static void put_json_string(Buf *b, const Str *s) { + b_ch(b, '"'); + for (size_t k = 0; k < s->n; k++) { + unsigned char c = (unsigned char)s->s[k]; + if (c == '"' || c == '\\') { b_ch(b, '\\'); b_ch(b, (char)c); } + else if (c < 0x20 || c == 0x7F) { char e[7]; snprintf(e, sizeof(e), "\\u%04x", c); b_str(b, e); } + else b_ch(b, (char)c); + } + b_ch(b, '"'); +} + +// {"url","method","headers":{lowercase,sorted},"body"?:""}. A body without content-type gets application/json. +static int build_fetch_json(const FetchReq *r, Buf *b) { + int has_ct = 0; + for (size_t i = 0; i < r->n; i++) if (r->names[i].n == 12 && !memcmp(r->names[i].s, "content-type", 12)) has_ct = 1; + b->p = malloc(FETCH_REQ_JSON_CAP + 1); + b->len = 0; + b->cap = FETCH_REQ_JSON_CAP; + b->overflow = 0; + if (!b->p) return 0; + b_str(b, "{\"url\":"); + put_json_string(b, &r->url); + b_str(b, ",\"method\":"); + put_json_string(b, &r->method); + b_str(b, ",\"headers\":{"); + int first = 1, ct_done = !(r->has_body && !has_ct); + for (size_t i = 0; i <= r->n; i++) { + if (!ct_done && (i == r->n || str_cmp(&(Str){"content-type", 12}, &r->names[i]) < 0)) { + if (!first) b_ch(b, ','); + b_str(b, "\"content-type\":\"application/json\""); + first = 0; + ct_done = 1; + } + if (i == r->n) break; + if (!first) b_ch(b, ','); + first = 0; + put_json_string(b, &r->names[i]); + b_ch(b, ':'); + put_json_string(b, &r->values[i]); + } + b_ch(b, '}'); + if (r->has_body) { + b_str(b, ",\"body\":"); + put_json_string(b, &r->body); + } + b_ch(b, '}'); + if (b->overflow) { free(b->p); b->p = NULL; return 0; } + b->p[b->len] = 0; + return 1; +} + +static JSValue js_fetch(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { + (void)this_val; + RunState *st = JS_GetContextOpaque(ctx); + FetchReq req; + Buf json = {NULL, 0, 0, 0}; + // Outside an active registered callback (including its promise-job drain) the whole run is invalid. + if (!st || !st->fetch_cb || !st->in_callback) { + if (st) st->attach_failed = 1; + return JS_ThrowTypeError(ctx, "invalid fetch"); + } + if (budget_exceeded(st)) return JS_ThrowTypeError(ctx, "fetch stopped"); + int parsed = parse_fetch_args(st, ctx, argc, argv, &req); + if (parsed < 0) return JS_ThrowTypeError(ctx, "out of memory"); + if (!parsed) return reject_error(ctx, 0, "invalid fetch request"); + if (st->nrequests >= FETCH_MAX_REQUESTS) { fetch_req_free(&req); return reject_error(ctx, 0, "fetch request limit"); } + int built = build_fetch_json(&req, &json); + fetch_req_free(&req); + if (!built) return reject_error(ctx, 0, "invalid fetch request"); + st->nrequests++; + + uint64_t t0 = now_ns(); + uint64_t left_ms = st->wall_deadline_ns > t0 ? (st->wall_deadline_ns - t0) / 1000000ull : 0; + if (left_ms == 0) { + free(json.p); + st->stop = QJS_TIMEOUT; + return JS_ThrowTypeError(ctx, "fetch stopped"); + } + uint32_t timeout_ms = left_ms < FETCH_REQUEST_MS ? (uint32_t)left_ms : FETCH_REQUEST_MS; + QJSFetchReply reply; + memset(&reply, 0, sizeof(reply)); + int32_t rc = st->fetch_cb(st->fetch_opaque, json.p, json.len, timeout_ms, &reply); + free(json.p); + // Host wait is excluded from the cumulative CPU budget only; the wall deadline keeps running. + st->deadline_ns += now_ns() - t0; + JSValue out; + if (rc == 2) { + st->stop = QJS_CANCELLED; + out = JS_ThrowTypeError(ctx, "fetch aborted"); + } else if (budget_exceeded(st)) { + out = JS_ThrowTypeError(ctx, "fetch stopped"); + } else if (reply.overflow || (rc == 0 && reply.has && st->response_total + reply.len > FETCH_MAX_TOTAL)) { + st->stop = QJS_MEMORY_OR_STACK; + out = JS_ThrowTypeError(ctx, "fetch response too large"); + } else if (rc != 0 || !reply.has || !utf8_valid(reply.body, reply.len)) { + out = reject_error(ctx, 0, "network error"); + } else { + st->response_total += reply.len; + JSValue resp = make_response(ctx, reply.status, reply.body, reply.len); + out = JS_IsException(resp) ? resp : settled_promise(ctx, resp, 0); + } + free(reply.body); + return out; +} + +// Read-only scheduling probe: no transport, no committed intents, and a fresh VM for the later run. +static JSValue js_probe_fetch(JSContext *ctx, JSValueConst this_val, int argc, JSValueConst *argv) { + (void)this_val; (void)argc; (void)argv; + RunState *st = JS_GetContextOpaque(ctx); + if (!st || !st->in_callback) { + if (st) st->attach_failed = 1; + return JS_ThrowTypeError(ctx, "fetch outside callback"); + } + st->requires_async = 1; + return JS_ThrowTypeError(ctx, "asynchronous hook required"); +} + +static int install_fetch(JSContext *ctx, int probe) { + JSValue global = JS_GetGlobalObject(ctx); + JSValue fn = JS_NewCFunction(ctx, probe ? js_probe_fetch : js_fetch, "fetch", 1); + int ok = !JS_IsException(fn) && JS_DefinePropertyValueStr(ctx, global, "fetch", fn, 0) > 0; + if (JS_IsException(fn)) JS_FreeValue(ctx, fn); + JS_FreeValue(ctx, global); + return ok; +} + +// Drains promise jobs until none remain, then resolves a returned Promise in place (*ret is replaced by its +// fulfilment value). Pending after the drain means no job can ever settle it: a script error. +static int settle_callback(RunState *st, JSContext *ctx, JSRuntime *rt, JSValue *ret) { + for (;;) { + if (budget_exceeded(st)) return st->stop; + JSContext *jctx = NULL; + int r = JS_ExecutePendingJob(rt, &jctx); + if (r == 0) break; + if (r < 0) return classify_exception(ctx, st, QJS_SCRIPT_ERROR); + } + if (budget_exceeded(st)) return st->stop; + int state = (int)JS_PromiseState(ctx, *ret); + if (state < 0) return 0; // not a Promise + if (state == JS_PROMISE_FULFILLED) { + JSValue v = JS_PromiseResult(ctx, *ret); + JS_FreeValue(ctx, *ret); + *ret = v; + return 0; + } + return st->oom ? QJS_MEMORY_OR_STACK : QJS_SCRIPT_ERROR; +} + static int v2_setup_failure(const RunState *st) { return st->stop ? st->stop : st->oom ? QJS_MEMORY_OR_STACK : QJS_INVALID_INPUT; } -QJSResult qjs_run_v2(QJSCancelToken *token, const QJSLimits *limits, - const uint8_t *package_json, size_t package_len, - const char *hook, - const uint8_t *event_json, size_t event_len, - const uint8_t *config_json, size_t config_len) { +static QJSResult run_v2_impl(QJSCancelToken *token, const QJSLimits *limits, + QJSFetchCallback fetch_cb, void *fetch_opaque, int probe_fetch, + const uint8_t *package_json, size_t package_len, + const char *hook, + const uint8_t *event_json, size_t event_len, + const uint8_t *config_json, size_t config_len) { QJSResult res = {QJS_INTERNAL, NULL, 0}; uint8_t *src = NULL, *ev = NULL, *cfg = NULL, *package = NULL; size_t source_len = 0; @@ -2212,13 +2582,24 @@ QJSResult qjs_run_v2(QJSCancelToken *token, const QJSLimits *limits, memset(&id, 0, sizeof(id)); for (int i = 0; i < MAX_REGS; i++) st.regs[i].cb = JS_UNDEFINED; st.token = token; - st.deadline_ns = now_ns() + (uint64_t)(limits ? limits->deadline_ms : 0) * 1000000ull; + { + size_t cpu_ms = limits ? limits->deadline_ms : 0; + if (fetch_cb && cpu_ms > FETCH_CPU_MS) cpu_ms = FETCH_CPU_MS; + st.deadline_ns = now_ns() + (uint64_t)cpu_ms * 1000000ull; + } + if (fetch_cb) { + st.fetch_cb = fetch_cb; + st.fetch_opaque = fetch_opaque; + st.wall_deadline_ns = now_ns() + FETCH_WALL_MS * 1000000ull; + } if (!limits || limits->deadline_ms == 0 || limits->heap_bytes == 0 || limits->stack_bytes == 0 || limits->max_result_bytes == 0 || limits->max_result_depth == 0) { return res; } if (!parse_phase(hook, &leg, &kind)) { res.status = QJS_INVALID_INPUT; return res; } + // Fetch mode exists only for response.onLeave; every other phase keeps the synchronous contract. + if ((fetch_cb || probe_fetch) && !(leg == 1 && kind == 1)) { res.status = QJS_INVALID_INPUT; return res; } st.phase_leg = leg; st.phase_kind = kind; @@ -2321,7 +2702,7 @@ QJSResult qjs_run_v2(QJSCancelToken *token, const QJSLimits *limits, } } - if (!install_interceptor(ctx)) { status = st.oom ? QJS_MEMORY_OR_STACK : QJS_INTERNAL; goto cleanup; } + if (!install_interceptor(ctx) || ((fetch_cb || probe_fetch) && !install_fetch(ctx, probe_fetch))) { status = st.oom ? QJS_MEMORY_OR_STACK : QJS_INTERNAL; goto cleanup; } { JSValue completion = JS_Eval(ctx, (const char *)src, source_len, "", JS_EVAL_TYPE_GLOBAL | JS_EVAL_FLAG_STRICT); @@ -2354,6 +2735,18 @@ QJSResult qjs_run_v2(QJSCancelToken *token, const QJSLimits *limits, size_t first_intent = st.nintents; st.in_callback = 1; JSValue ret = JS_Call(ctx, st.regs[i].cb, JS_UNDEFINED, 2, argv); + if (probe_fetch && !budget_exceeded(&st) && + (st.requires_async || (!JS_IsException(ret) && (int)JS_PromiseState(ctx, ret) >= 0))) { + st.in_callback = 0; + JS_FreeValue(ctx, ret); + free(v.out.p); + status = QJS_ASYNC_REQUIRED; + goto cleanup; + } + if (fetch_cb && !JS_IsException(ret)) { + int fs = settle_callback(&st, ctx, rt, &ret); + if (fs) { st.in_callback = 0; JS_FreeValue(ctx, ret); free(v.out.p); status = fs; goto cleanup; } + } st.in_callback = 0; if (JS_IsException(ret)) { status = classify_exception(ctx, &st, QJS_SCRIPT_ERROR); @@ -2448,3 +2841,38 @@ QJSResult qjs_run_v2(QJSCancelToken *token, const QJSLimits *limits, res.status = status; return res; } + +QJSResult qjs_run_v2(QJSCancelToken *token, const QJSLimits *limits, + const uint8_t *package_json, size_t package_len, + const char *hook, + const uint8_t *event_json, size_t event_len, + const uint8_t *config_json, size_t config_len) { + return run_v2_impl(token, limits, NULL, NULL, 0, package_json, package_len, hook, event_json, event_len, + config_json, config_len); +} + +QJSResult qjs_run_v2_fetch(QJSCancelToken *token, const QJSLimits *limits, + QJSFetchCallback callback, void *opaque, + const uint8_t *package_json, size_t package_len, + const char *hook, + const uint8_t *event_json, size_t event_len, + const uint8_t *config_json, size_t config_len) { + if (!callback) { + QJSResult res = {QJS_INVALID_INPUT, NULL, 0}; + return res; + } + return run_v2_impl(token, limits, callback, opaque, 0, package_json, package_len, hook, event_json, event_len, + config_json, config_len); +} + +QJSResult qjs_run_v2_probe(QJSCancelToken *token, const QJSLimits *limits, + const uint8_t *package_json, size_t package_len, const char *hook, + const uint8_t *event_json, size_t event_len, + const uint8_t *config_json, size_t config_len) { + if (!hook || strcmp(hook, "response.onLeave")) { + QJSResult res = {QJS_INVALID_INPUT, NULL, 0}; + return res; + } + return run_v2_impl(token, limits, NULL, NULL, 1, package_json, package_len, hook, + event_json, event_len, config_json, config_len); +} diff --git a/Packages/InterceptorAutomation/Sources/CQuickJS/include/CQuickJS.h b/Packages/InterceptorAutomation/Sources/CQuickJS/include/CQuickJS.h index b63000c..06a3529 100644 --- a/Packages/InterceptorAutomation/Sources/CQuickJS/include/CQuickJS.h +++ b/Packages/InterceptorAutomation/Sources/CQuickJS/include/CQuickJS.h @@ -24,7 +24,8 @@ enum { QJS_INVALID_INPUT = 4, QJS_INVALID_RESULT = 5, QJS_SCRIPT_ERROR = 6, - QJS_INTERNAL = 7 + QJS_INTERNAL = 7, + QJS_ASYNC_REQUIRED = 8 }; typedef struct QJSLimits { @@ -74,6 +75,34 @@ QJSResult qjs_run_v2(QJSCancelToken *token, const QJSLimits *limits, const uint8_t *event_json, size_t event_len, const uint8_t *config_json, size_t config_len); +/// Standard global `fetch` host contract (response.onLeave only). The callback is trusted, runs on the +/// calling thread and may block; it must honor `timeout_ms` and the cancel token. `request_json` is a +/// validated {url,method,headers,body?} (lowercase header names; body is a JSON text <= 8192 bytes). +typedef struct QJSFetchReply QJSFetchReply; + +/// Copies a bounded response (status 100...599, body <= 1 MiB UTF-8). Returns 0 on success. +int32_t qjs_fetch_reply_set(QJSFetchReply *reply, int32_t status, const uint8_t *body, size_t len); + +/// Callback result: 0 success (reply set), 1 network error, 2 abort/cancel/revoked. +typedef int32_t (*QJSFetchCallback)(void *opaque, const uint8_t *request_json, size_t len, + uint32_t timeout_ms, QJSFetchReply *reply); + +/// Same as `qjs_run_v2` plus a global `fetch` (64 requests, 120 s wall, 250 ms CPU excluding callback wait, +/// 1 MiB per / 16 MiB total response). Only valid for `response.onLeave`; NULL callback is invalid input. +QJSResult qjs_run_v2_fetch(QJSCancelToken *token, const QJSLimits *limits, + QJSFetchCallback callback, void *opaque, + const uint8_t *package_json, size_t package_len, + const char *hook, + const uint8_t *event_json, size_t event_len, + const uint8_t *config_json, size_t config_len); + +/// Read-only response.onLeave scheduling probe. Runs sync hooks unchanged, but performs no network. +/// A fetch attempt or returned Promise gives QJS_ASYNC_REQUIRED, discarding all recorded intents. +QJSResult qjs_run_v2_probe(QJSCancelToken *token, const QJSLimits *limits, + const uint8_t *package_json, size_t package_len, const char *hook, + const uint8_t *event_json, size_t event_len, + const uint8_t *config_json, size_t config_len); + void qjs_result_free(QJSResult *result); #ifdef __cplusplus diff --git a/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginOutboundTests.swift b/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginOutboundTests.swift index 0e87d7a..6e085bb 100644 --- a/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginOutboundTests.swift +++ b/Packages/InterceptorAutomation/Tests/AutomationCoreTests/PluginOutboundTests.swift @@ -52,7 +52,7 @@ final class PluginOutboundTests: XCTestCase { accepts(decl()) accepts(decl(headers: "[]")) rejects(decl(extra: #","body":""#)) - rejects(decl(method: "DELETE")) + rejects(decl(method: "POST")) rejects(decl(method: "get")) rejects(#"{"profile":{"url":"https://api.example.com/","method":"GET"}}"#) rejects(#"{"profile":{"url":"https://api.example.com/","headers":[]}}"#) @@ -190,161 +190,4 @@ final class PluginOutboundTests: XCTestCase { func testOutboundDoesNotChangeEndpointBindings() throws { XCTAssertEqual(try manifest().endpointBindings, ["alert"]) } - - // MARK: POST/PUT methods and optional exact JSON body (PHASE1: RED until implemented) - - private func writeManifest(method: String = "POST") throws -> PluginManifest { - try manifest(decl(headers: #"["authorization","content-type"]"#, method: method)) - } - private func bodyAction(_ body: String?, binding: String = "profile") -> JSONValue { - var extra = "" - if let body { extra = #","jsonBody":\#(try! JSONValue.string(body).jsonString())"# } - return action(binding: binding, headers: "{}", extra: extra) - } - private func intent(_ body: String?, method: String = "POST") throws -> PluginOutboundIntent { - try PluginOutboundIntent.validating(bodyAction(body), manifest: writeManifest(method: method)) - } - private func badIntent(_ body: String?, method: String = "POST", _ e: PluginOutboundIntentError, line: UInt = #line) throws { - let m = try writeManifest(method: method) - XCTAssertThrowsError(try PluginOutboundIntent.validating(bodyAction(body), manifest: m), line: line) { - XCTAssertEqual($0 as? PluginOutboundIntentError, e, line: line) - } - } - - func testPostAndPutDeclarationsAreAcceptedButOtherMethodsAreNot() throws { - accepts(decl(method: "POST")) - accepts(decl(method: "PUT")) - accepts(decl(method: "GET")) - XCTAssertEqual(try writeManifest(method: "PUT").outbound["profile"]?.method, "PUT") - for bad in ["DELETE", "PATCH", "HEAD", "OPTIONS", "post", "put", "Post", "Put", "get", "", " POST", "POST "] { - rejects(decl(method: bad)) - } - } - - func testMethodChangeAltersPackageRevision() throws { - let get = try PluginPackage.validate(package(outbound: decl(method: "GET"))).revision - let post = try PluginPackage.validate(package(outbound: decl(method: "POST"))).revision - let put = try PluginPackage.validate(package(outbound: decl(method: "PUT"))).revision - XCTAssertEqual(Set([get, post, put]).count, 3) - } - - func testLegacyGetIntentHasNoBody() throws { - let i = try PluginOutboundIntent.validating(action(), manifest: manifest()) - XCTAssertNil(i.jsonBody) - } - - func testPostPutWithoutBodyIsValidEmptyBody() throws { - for method in ["POST", "PUT"] { - XCTAssertNil(try intent(nil, method: method).jsonBody) - } - } - - func testJSONBodyIsForwardedAsExactSerializedBytesWithoutReencoding() throws { - // Spellings a parse/re-encode round trip would normalise (number format, escapes, key order, non-ASCII). - let exact = #"{"z":1e+21,"a":[0.1,1.5,4294967296],"s":"a\"b\\c\n\u0001é日本😀"}"# - for method in ["POST", "PUT"] { - let i = try intent(exact, method: method) - XCTAssertEqual(i.jsonBody, Data(exact.utf8)) - XCTAssertEqual(i.endpoint.method, method) - } - XCTAssertEqual(try intent("null").jsonBody, Data("null".utf8)) - XCTAssertEqual(try intent("0").jsonBody, Data("0".utf8)) - XCTAssertEqual(try intent(#""x""#).jsonBody, Data(#""x""#.utf8)) - XCTAssertEqual(try intent("[]").jsonBody, Data("[]".utf8)) - XCTAssertEqual(try intent("{}").jsonBody, Data("{}".utf8)) - } - - func testEmptyStringBodyIsInvalidJSONNotAbsentBody() throws { - try badIntent("", .malformed) - } - - func testGetRejectsAnyJSONBody() throws { - for body in ["null", "{}", #"{"a":1}"#] { try badIntent(body, method: "GET", .malformed) } - } - - func testJSONBodyMustBeStrictJSONString() throws { - for bad in ["{", "{'a':1}", #"{"a":1,}"#, "[1,]", "01", "NaN", "Infinity", "undefined", #"{"a":1}{"b":2}"#, - #"{"a":1,"a":2}"#, "\u{FEFF}{}", #""\ud800""#] { - try badIntent(bad, .malformed) - } - // Non-string jsonBody values. - let m = try writeManifest() - for raw in [#"{"a":1}"#, "null", "1", "[]"] { - let a = action(headers: "{}", extra: #","jsonBody":\#(raw)"#) - XCTAssertThrowsError(try PluginOutboundIntent.validating(a, manifest: m)) { - XCTAssertEqual($0 as? PluginOutboundIntentError, .malformed) - } - } - } - - func testJSONBodyByteCapIsInclusiveAtUTF8Length() throws { - let ascii = #"{"a":""# + String(repeating: "x", count: 8184) + #""}"# - XCTAssertEqual(ascii.utf8.count, 8192) - XCTAssertEqual(try intent(ascii).jsonBody?.count, 8192) - let over = #"{"a":""# + String(repeating: "x", count: 8185) + #""}"# - XCTAssertEqual(over.utf8.count, 8193) - try badIntent(over, .limitExceeded) - // 4092 two-byte characters: 8192 UTF-8 bytes but only 4092 characters. - let wide = #"{"a":""# + String(repeating: "\u{e9}", count: 4092) + #""}"# - XCTAssertEqual(wide.utf8.count, 8192) - XCTAssertEqual(try intent(wide).jsonBody?.count, 8192) - let wider = #"{"a":""# + String(repeating: "\u{e9}", count: 4092) + #"x"}"# - XCTAssertEqual(wider.utf8.count, 8193) - try badIntent(wider, .limitExceeded) - } - - func testJSONBodyDepthCapIs16() throws { - func nested(_ n: Int) -> String { String(repeating: "[", count: n) + String(repeating: "]", count: n) } - XCTAssertEqual(try intent(nested(16)).jsonBody, Data(nested(16).utf8)) - try badIntent(nested(17), .limitExceeded) - let obj16 = String(repeating: #"{"a":"#, count: 16) + "1" + String(repeating: "}", count: 16) - XCTAssertNoThrow(try intent(obj16)) - try badIntent(String(repeating: #"{"a":"#, count: 17) + "1" + String(repeating: "}", count: 17), .limitExceeded) - } - - func testIntentKeysetIsExactWithOptionalJSONBodyOnly() throws { - let m = try writeManifest() - XCTAssertNoThrow(try PluginOutboundIntent.validating(action(headers: "{}"), manifest: m)) - for extra in [#","body":"{}""#, #","json":{}"#, #","method":"POST""#, #","jsonBody":"{}","json":{}"#] { - XCTAssertThrowsError(try PluginOutboundIntent.validating(action(headers: "{}", extra: extra), manifest: m)) { - XCTAssertEqual($0 as? PluginOutboundIntentError, .malformed) - } - } - } - - func testBodyDoesNotChangeHeaderValidation() throws { - let m = try writeManifest() - let a = action(headers: #"{"authorization":"Bearer abc"}"#, extra: #","jsonBody":"{}""#) - let i = try PluginOutboundIntent.validating(a, manifest: m) - XCTAssertEqual(i.headers, ["authorization": "Bearer abc"]) - XCTAssertEqual(i.jsonBody, Data("{}".utf8)) - XCTAssertThrowsError(try PluginOutboundIntent.validating(action(headers: #"{"x-other":"1"}"#, extra: #","jsonBody":"{}""#), manifest: m)) { - XCTAssertEqual($0 as? PluginOutboundIntentError, .undeclaredHeader) - } - } -} - -extension PluginOutboundTests { - func testJSONContentTypeMustAgreeWithNativeFraming() throws { - let m = try manifest(decl(headers: #"["content-type"]"#, method: "POST")) - XCTAssertThrowsError(try PluginOutboundIntent.validating(action(headers: #"{"content-type":"text/plain"}"#, extra: #","jsonBody":"{}""#), manifest: m)) { - XCTAssertEqual($0 as? PluginOutboundIntentError, .invalidHeaderValue) - } - let good = try PluginOutboundIntent.validating(action(headers: #"{"content-type":"application/json"}"#, extra: #","jsonBody":"{}""#), manifest: m) - XCTAssertEqual(good.jsonBody, Data("{}".utf8)) - } -} - -extension PluginOutboundTests { - func testSharedOutboundMethodConformance() throws { - let url = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("Fixtures/outbound-conformance.json") - let root = try JSONValue(parsing: Data(contentsOf: url)) - let rows = try XCTUnwrap(root.objectValue?["cases"]?.arrayValue) - for row in rows { - let fields = try XCTUnwrap(row.objectValue) - let outbound = try XCTUnwrap(fields["outbound"]).jsonString() - guard case .bool(let valid)? = fields["valid"] else { return XCTFail("invalid shared fixture") } - if valid { accepts(outbound) } else { rejects(outbound) } - } - } } diff --git a/Packages/InterceptorAutomation/Tests/AutomationRuntimeTests/JavaScriptFetchTests.swift b/Packages/InterceptorAutomation/Tests/AutomationRuntimeTests/JavaScriptFetchTests.swift new file mode 100644 index 0000000..1d15fbb --- /dev/null +++ b/Packages/InterceptorAutomation/Tests/AutomationRuntimeTests/JavaScriptFetchTests.swift @@ -0,0 +1,242 @@ +import AutomationCore +@testable import AutomationRuntime +import XCTest + +/// Standard global `fetch` through the real shared C runtime (`qjs_run_v2_fetch`), response.onLeave only. +final class JavaScriptFetchTests: XCTestCase, @unchecked Sendable { + private let file = "hooks/api.example.com/credentials/GET.js" + private let route = #"{"hosts":["api.example.com"],"methods":["GET"],"path":{"kind":"exact","value":"/credentials"},"hooks":{"response":{"onLeave":"hooks/api.example.com/credentials/GET.js"}}}"# + private let event = Data(#"{"request":{"method":"GET","host":"api.example.com","path":"/credentials"},"response":{"status":200,"headers":{},"body":{"accessToken":"t"}}}"#.utf8) + private let config = Data("{}".utf8) + private let url = "https://api.example.com/v1/profile" + + private func package(_ source: String) throws -> Data { + let code = try JSONValue.string(source).jsonString() + let m = #"{"schemaVersion":2,"id":"22222222-2222-4222-8222-222222222222","name":"Sample","version":"1.0.0","matches":[\#(route)],"read":{"metadata":["host"],"headers":[],"queryKeys":[],"body":{"mode":"json"}},"write":{"requestBody":false,"responseBody":false},"endpointBindings":[],"settings":{},"outbound":{}}"# + return Data(#"{"manifest":\#(m),"sourceFiles":{"\#(file)":\#(code)}}"#.utf8) + } + + private func run(_ body: String, top: String = "", executor: JavaScriptFetchExecutor = JavaScriptFetchExecutor(), + transport: @escaping JavaScriptFetchExecutor.Transport = { _ in JavaScriptFetchResponse(status: 200, body: Data("{\"a\":1}".utf8)) }) async throws -> [[String: Any]] + { + let pkg = try package("\(top)Interceptor.attach({response:{onLeave:\(body)}});") + let data = try await executor.runV2(packageJSON: pkg, hook: .responseLeave, eventJSON: event, configJSON: config, transport: transport) + let obj = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any]) + return try XCTUnwrap(obj["actions"] as? [[String: Any]]) + } + + private func expectError(_ expected: JavaScriptExecutionError, _ body: String, top: String = "", executor: JavaScriptFetchExecutor = JavaScriptFetchExecutor(), line: UInt = #line, + transport: @escaping JavaScriptFetchExecutor.Transport = { _ in JavaScriptFetchResponse(status: 200, body: Data("{}".utf8)) }) async + { + do { + let r = try await run(body, top: top, executor: executor, transport: transport) + XCTFail("expected \(expected), got \(r)", line: line) + } catch { XCTAssertEqual(error as? JavaScriptExecutionError, expected, line: line) } + } + + private actor Recorder { + var requests: [JavaScriptFetchRequest] = [] + func add(_ r: JavaScriptFetchRequest) { + requests.append(r) + } + } + + func testAsyncAwaitFetchJsonAndStatus() async throws { + let rec = Recorder() + let actions = try await run("async (res) => { const r = await fetch('\(url)'); const j = await r.json(); if (r.status !== 200 || !r.ok || j.a !== 1) throw new Error('x'); }") { req in + await rec.add(req) + return JavaScriptFetchResponse(status: 200, body: Data("{\"a\":1}".utf8)) + } + XCTAssertEqual(actions.count, 0) + let seen = await rec.requests + XCTAssertEqual(seen.count, 1) + XCTAssertEqual(seen[0].url, url) + XCTAssertEqual(seen[0].method, "GET") + XCTAssertEqual(seen[0].maxResponseBytes, 1024 * 1024) + XCTAssertLessThanOrEqual(seen[0].timeoutMilliseconds, 5000) + } + + func testPostBodyHeadersAndDefaultContentType() async throws { + let rec = Recorder() + _ = try await run("async () => { await fetch('\(url)', {method:'post', headers:{Authorization:'Bearer x'}, body:'{\"k\":1}'}); }") { req in + await rec.add(req) + return JavaScriptFetchResponse(status: 204, body: Data()) + } + let all = await rec.requests + let r = try XCTUnwrap(all.first) + XCTAssertEqual(r.method, "POST") + XCTAssertEqual(r.headers, ["authorization": "Bearer x", "content-type": "application/json"]) + XCTAssertEqual(r.body, Data("{\"k\":1}".utf8)) + } + + func testResponseTextAndNonOkStatus() async throws { + _ = try await run("async () => { const r = await fetch('\(url)'); if (r.ok || r.status !== 404 || (await r.text()) !== 'nope') throw new Error('x'); }") { _ in + JavaScriptFetchResponse(status: 404, body: Data("nope".utf8)) + } + } + + func testNetworkErrorIsCatchable() async throws { + struct Boom: Error {} + _ = try await run("async () => { try { await fetch('\(url)'); } catch (e) { return; } throw new Error('not rejected'); }") { _ in throw Boom() } + } + + func testInvalidJSONRejectsCatchably() async throws { + _ = try await run("async () => { const r = await fetch('\(url)'); try { await r.json(); } catch (e) { return; } throw new Error('x'); }") { _ in + JavaScriptFetchResponse(status: 200, body: Data("{bad".utf8)) + } + } + + func testResponseBodyCanOnlyBeConsumedOnce() async throws { + _ = try await run("async () => { const r = await fetch('\(url)'); if (r.bodyUsed) throw new Error('used early'); await r.json(); if (!r.bodyUsed) throw new Error('not consumed'); try { await r.text(); } catch (e) { return; } throw new Error('read twice'); }") + } + + func testInvalidRequestsRejectCatchably() async throws { + let bad = ["'http://api.example.com/x'", "'https://127.0.0.1/x'", "'https://api.example.com:8443/x'", "'https://api.example.com/x?q=1'", + "'\(url)', {method:'DELETE'}", "'\(url)', {headers:{host:'x'}}", "'\(url)', {headers:{'accept-encoding':'gzip'}}", + "'\(url)', {body:'{}'}", "'\(url)', {method:'POST', body:'not json'}", "'\(url)', {redirect:'follow'}", "42"] + for args in bad { + _ = try await run("async () => { try { await fetch(\(args)); } catch (e) { return; } throw new Error('accepted'); }") { _ in + XCTFail("transport must not be called for \(args)") + return JavaScriptFetchResponse(status: 200, body: Data()) + } + } + } + + func testRequestCapIs64() async throws { + let counter = Recorder() + _ = try await run("async () => { let rejected = 0; for (let i = 0; i < 65; i++) { try { await fetch('\(url)'); } catch (e) { rejected++; } } if (rejected !== 1) throw new Error('r' + rejected); }") { req in + await counter.add(req) + return JavaScriptFetchResponse(status: 200, body: Data()) + } + let n = await counter.requests.count + XCTAssertEqual(n, 64) + } + + func testAggregateResponseCapFailsClosed() async { + let big = Data(repeating: 0x61, count: 1024 * 1024) + await expectError(.memoryOrStack, "async () => { for (let i = 0; i < 17; i++) { const r = await fetch('\(url)'); void r; } }", + transport: { _ in JavaScriptFetchResponse(status: 200, body: big) }) + } + + func testOversizedResponseIsNetworkError() async throws { + _ = try await run("async () => { try { await fetch('\(url)'); } catch (e) { return; } throw new Error('x'); }") { _ in + JavaScriptFetchResponse(status: 200, body: Data(repeating: 0x61, count: 1024 * 1024 + 1)) + } + } + + func testTopLevelFetchIsStickyInvalid() async { + await expectError(.scriptError, "() => {}", top: "try { fetch('\(url)'); } catch (e) {}\n") + } + + func testNeverSettlingPromiseIsScriptError() async { + await expectError(.scriptError, "() => new Promise(() => {})") + } + + func testRejectedReturnedPromiseIsScriptError() async { + await expectError(.scriptError, "async () => { throw new Error('x'); }") + } + + func testCpuBudgetExcludesTransportWaitOnly() async throws { + _ = try await run("async () => { await fetch('\(url)'); }") { _ in + try await Task.sleep(nanoseconds: 600_000_000) + return JavaScriptFetchResponse(status: 200, body: Data()) + } + await expectError(.timeout, "async () => { await fetch('\(url)'); for (;;) {} }") + } + + func testCancelDuringTransportCancelsTaskAndThrows() async throws { + let executor = JavaScriptFetchExecutor() + let started = expectation(description: "started") + let cancelled = Recorder() + let task = Task { () -> Error? in + do { + _ = try await self.run("async () => { await fetch('\(self.url)'); }", executor: executor) { _ in + started.fulfill() + do { try await Task.sleep(nanoseconds: 30_000_000_000) } catch { await cancelled.add(JavaScriptFetchRequest(url: "c", method: "", headers: [:], body: nil, timeoutMilliseconds: 0, maxResponseBytes: 0)); throw error } + return JavaScriptFetchResponse(status: 200, body: Data()) + } + return nil + } catch { return error } + } + await fulfillment(of: [started], timeout: 5) + executor.cancel() + let error = await task.value + XCTAssertEqual(error as? JavaScriptExecutionError, .cancelled) + let c = await cancelled.requests.count + XCTAssertEqual(c, 1) + executor.cancel() // idle cancel is harmless + _ = try await run("() => {}", executor: executor) + } + + func testCancelBeforeRunDoesNotPoisonNextRun() async throws { + let executor = JavaScriptFetchExecutor() + executor.cancel() + _ = try await run("async () => { await fetch('\(url)'); }", executor: executor) + } + + func testSameExecutorIsSingleFlight() async throws { + let executor = JavaScriptFetchExecutor() + let started = expectation(description: "started") + let first = Task { _ = try await self.run("async () => { await fetch('\(self.url)'); }", executor: executor) { _ in + started.fulfill() + try await Task.sleep(nanoseconds: 400_000_000) + return JavaScriptFetchResponse(status: 200, body: Data()) + } } + await fulfillment(of: [started], timeout: 5) + await expectError(.busy, "() => {}", executor: executor) + _ = try await first.value + _ = try await run("() => {}", executor: executor) + } + + func testGlobalAdmissionAllowsTwoInstances() async throws { + let started = expectation(description: "two started"); started.expectedFulfillmentCount = 2 + let slow: JavaScriptFetchExecutor.Transport = { _ in + started.fulfill() + try await Task.sleep(nanoseconds: 500_000_000) + return JavaScriptFetchResponse(status: 200, body: Data()) + } + let body = "async () => { await fetch('\(url)'); }" + let a = Task { _ = try await self.run(body, transport: slow) } + let b = Task { _ = try await self.run(body, transport: slow) } + await fulfillment(of: [started], timeout: 5) + await expectError(.busy, "() => {}") // third fresh executor + _ = try await a.value + _ = try await b.value + } + + func testNonLeavePhasesAndLegacyHooksRejectFetchMode() async throws { + let pkg = try package("Interceptor.attach({response:{onLeave(){}}});") + for hook in [JavaScriptHook.requestEnter, .requestLeave, .responseEnter, .request, .response] { + do { + _ = try await JavaScriptFetchExecutor().runV2(packageJSON: pkg, hook: hook, eventJSON: event, configJSON: config) { _ in + JavaScriptFetchResponse(status: 200, body: Data()) + } + XCTFail("accepted \(hook)") + } catch { XCTAssertEqual(error as? JavaScriptExecutionError, .invalidInput) } + } + } + + func testSchedulingProbePreservesSyncAndDefersAsyncWithoutNetwork() async throws { + let executor = JavaScriptExecutor() + let sync = try package("Interceptor.attach({response:{onLeave(){return {actions:[]};}}});") + let output = try await executor.runV2(packageJSON: sync, hook: .responseLeave, eventJSON: event, configJSON: config, detectAsync: true) + XCTAssertEqual(try JSONValue(parsing: output), .object(["actions": .array([])])) + for callback in ["async () => {}", "() => { fetch('https://api.example.com/x'); }", "() => { try { fetch('https://api.example.com/x'); } catch(e) {} }"] { + let pkg = try package("Interceptor.attach({response:{onLeave:" + callback + "}});") + do { + _ = try await executor.runV2(packageJSON: pkg, hook: .responseLeave, eventJSON: event, configJSON: config, detectAsync: true) + XCTFail("expected a scheduling signal") + } catch { XCTAssertTrue(error is JavaScriptAsyncRequired, "\(error)") } + } + let bad = try package("Interceptor.attach({response:{onLeave(){throw new Error('legacy failure');}}});") + do { + _ = try await executor.runV2(packageJSON: bad, hook: .responseLeave, eventJSON: event, configJSON: config, detectAsync: true) + XCTFail("legacy sync error must remain immediate") + } catch { XCTAssertEqual(error as? JavaScriptExecutionError, .scriptError) } + } + + func testLegacyRuntimeHasNoGlobalFetch() async throws { + let pkg = try package("Interceptor.attach({response:{onLeave(){ if (typeof fetch !== 'undefined') throw new Error('x'); }}});") + _ = try await JavaScriptExecutor().runV2(packageJSON: pkg, hook: .responseLeave, eventJSON: event, configJSON: config) + } +} diff --git a/Packages/InterceptorAutomation/Tests/AutomationRuntimeTests/OutboundRuntimeTests.swift b/Packages/InterceptorAutomation/Tests/AutomationRuntimeTests/OutboundRuntimeTests.swift index 94d1f31..a6d4a1d 100644 --- a/Packages/InterceptorAutomation/Tests/AutomationRuntimeTests/OutboundRuntimeTests.swift +++ b/Packages/InterceptorAutomation/Tests/AutomationRuntimeTests/OutboundRuntimeTests.swift @@ -27,11 +27,11 @@ final class OutboundRuntimeTests: XCTestCase, @unchecked Sendable { return try XCTUnwrap(obj["actions"] as? [[String: Any]]) } - private func expectError(_ expected: JavaScriptExecutionError, _ body: String, top: String = "", manifest: Data? = nil, context: String = "", line: UInt = #line) async { + private func expectError(_ expected: JavaScriptExecutionError, _ body: String, top: String = "", manifest: Data? = nil, line: UInt = #line) async { do { let r = try await run(body, top: top, manifest: manifest) - XCTFail("expected \(expected), got \(r) (\(context))", line: line) - } catch { XCTAssertEqual(error as? JavaScriptExecutionError, expected, context, line: line) } + XCTFail("expected \(expected), got \(r)", line: line) + } catch { XCTAssertEqual(error as? JavaScriptExecutionError, expected, line: line) } } private func webhook(_ n: Int) -> String { "{type:'webhook',endpointId:'\(endpoint)',json:{n:\(n)}}" } @@ -171,7 +171,7 @@ final class OutboundRuntimeTests: XCTestCase, @unchecked Sendable { await accepts(decl(headers: #"["x-api-key","a1","!#$%&'*+-.^_`|~"]"#)) await accepts(decl(headers: #"["a","b","c","d","e","f","g","h"]"#)) await rejects(decl(extra: #","body":""#)) - await rejects(decl(method: "DELETE")) + await rejects(decl(method: "POST")) await rejects(decl(method: "get")) await rejects(#"{"profile":{"url":"https://api.example.com/","method":"GET"}}"#) await rejects(#"{"profile":{"url":"https://api.example.com/","headers":[]}}"#) @@ -216,202 +216,3 @@ final class OutboundRuntimeTests: XCTestCase, @unchecked Sendable { await accepts(decl(url: "https://api.example.com/%41%2f%7E")) } } - -// MARK: POST/PUT + `json` option - -extension OutboundRuntimeTests { - private func writeManifest(_ method: String) -> Data { - manifest(outbound: #"{"profile":{"url":"https://api.example.com/v1/profile","method":"\#(method)","headers":["authorization"]},"get":{"url":"https://api.example.com/v1/get","method":"GET","headers":[]}}"#) - } - - private func body(_ call: String, method: String = "POST", line: UInt = #line) async throws -> String? { - let actions = try await run("\(call);", manifest: writeManifest(method)) - XCTAssertEqual(actions.count, 1, line: line) - return actions[0]["jsonBody"] as? String - } - - func testManifestAcceptsPostAndPutOnly() async { - await accepts(decl(method: "POST")) - await accepts(decl(method: "PUT")) - for bad in ["DELETE", "PATCH", "post", "put", "Post", "HEAD", ""] { await rejects(decl(method: bad)) } - } - - func testGetKeysetIsUnchangedAndWriteWithoutJSONHasNoBodyKey() async throws { - let get = try await run("Interceptor.send('get',{headers:{}});", manifest: writeManifest("POST")) - XCTAssertEqual(Set(get[0].keys), ["type", "binding", "headers"]) - for method in ["POST", "PUT"] { - let a = try await run("Interceptor.send('profile',{headers:{}});", manifest: writeManifest(method)) - XCTAssertEqual(Set(a[0].keys), ["type", "binding", "headers"], "absent json means empty body") - } - } - - func testJSONOptionIsRecordedAsInternalJSONBodyString() async throws { - for method in ["POST", "PUT"] { - let a = try await run("Interceptor.send('profile',{headers:{authorization:'t'},json:{b:1,a:[true,null,'x']}});", manifest: writeManifest(method)) - XCTAssertEqual(Set(a[0].keys), ["type", "binding", "headers", "jsonBody"]) - XCTAssertEqual(a[0]["type"] as? String, "http") - XCTAssertEqual(a[0]["jsonBody"] as? String, #"{"b":1,"a":[true,null,"x"]}"#) - XCTAssertNil(a[0]["json"]) - } - } - - func testExplicitNullAndScalarsAreBodiesNotAbsence() async throws { - let n = try await body("Interceptor.send('profile',{headers:{},json:null})") - XCTAssertEqual(n, "null") - let z = try await body("Interceptor.send('profile',{headers:{},json:0})") - XCTAssertEqual(z, "0") - let s = try await body("Interceptor.send('profile',{headers:{},json:'x'})") - XCTAssertEqual(s, "\"x\"") - let f = try await body("Interceptor.send('profile',{headers:{},json:false})") - XCTAssertEqual(f, "false") - let e = try await body("Interceptor.send('profile',{headers:{},json:[]})", method: "PUT") - XCTAssertEqual(e, "[]") - } - - func testJSONBodyBytesAreExactCSerializationNumbersEscapesAndNonASCII() async throws { - let cases: [(js: String, expected: String)] = [ - ("1.5", "1.5"), ("0.1", "0.1"), ("4294967296", "4294967296"), ("1e21", "1e+21"), - ("123456789012345680000", "1.2345678901234568e+20"), - ("'\\u00e9\\u65e5\\ud83d\\ude00'", "\"\u{e9}\u{65e5}\u{1F600}\""), - ("'a\"b\\\\c\\n\\r\\t\\b\\f\\u0001\\u001f/'", #""a\"b\\c\n\r\t\b\f\u0001\u001f/""#), - ("'\\u2028\\u007f'", "\"\u{2028}\u{7f}\""), - ("{'\\u00e9':1,b:2,a:3}", "{\"\u{e9}\":1,\"b\":2,\"a\":3}"), - ] - for c in cases { - let got = try await body("Interceptor.send('profile',{headers:{},json:\(c.js)})") - XCTAssertEqual(got, c.expected, c.js) - } - } - - func testJSONBodySizeBoundaryIsExactUTF8Bytes() async throws { - // {"a":""} is 8 + n bytes. - let ok = try await body("Interceptor.send('profile',{headers:{},json:{a:'x'.repeat(8184)}})") - XCTAssertEqual(ok?.utf8.count, 8192) - await expectError(.scriptError, "Interceptor.send('profile',{headers:{},json:{a:'x'.repeat(8185)}});", manifest: writeManifest("POST")) - // Two-byte characters: 4092 characters == 8192 bytes; one extra ASCII byte exceeds the cap. - let wide = try await body("Interceptor.send('profile',{headers:{},json:{a:'\\u00e9'.repeat(4092)}})") - XCTAssertEqual(wide?.utf8.count, 8192) - await expectError(.scriptError, "Interceptor.send('profile',{headers:{},json:{a:'\\u00e9'.repeat(4092)+'x'}});", manifest: writeManifest("POST")) - // Escaping counts: 4096 newlines serialise to 8192 bytes of "\n" escapes plus braces and key => over. - await expectError(.scriptError, "Interceptor.send('profile',{headers:{},json:{a:'\\n'.repeat(4096)}});", manifest: writeManifest("POST")) - } - - func testJSONBodyDepthBoundaryIs16() async throws { - let ok = try await body("let v=1; for(let i=0;i<16;i++) v=[v]; Interceptor.send('profile',{headers:{},json:v})") - XCTAssertEqual(ok, String(repeating: "[", count: 16) + "1" + String(repeating: "]", count: 16)) - await expectError(.scriptError, "let v=1; for(let i=0;i<17;i++) v=[v]; Interceptor.send('profile',{headers:{},json:v});", manifest: writeManifest("POST")) - let objs = try await body("let v=1; for(let i=0;i<16;i++) v={a:v}; Interceptor.send('profile',{headers:{},json:v})") - XCTAssertNotNil(objs) - await expectError(.scriptError, "let v=1; for(let i=0;i<17;i++) v={a:v}; Interceptor.send('profile',{headers:{},json:v});", manifest: writeManifest("POST")) - } - - func testGetRejectsJSONOptionIncludingNull() async { - for j in ["null", "{}", "1", "'x'"] { - await expectError(.scriptError, "try { Interceptor.send('get',{headers:{},json:\(j)}); } catch (e) {} return {actions:[]};", manifest: writeManifest("POST")) - await expectError(.scriptError, "Interceptor.send('profile',{headers:{},json:1}); Interceptor.send('get',{headers:{},json:\(j)});", manifest: writeManifest("POST")) - } - await expectError(.scriptError, "Interceptor.send('profile',{headers:{},json:{}});", manifest: manifest()) - } - - func testStickyInvalidJSONValuesDiscardEveryIntent() async { - let invalid = [ - "undefined", "(function(){})", "()=>1", "Symbol('s')", "10n", "NaN", "Infinity", "-Infinity", - "new Date(0)", "new Map()", "new Set()", "new Error('x')", "new Number(1)", "new String('x')", "new Boolean(true)", - "Promise.resolve(1)", "new Proxy({}, {})", "new Proxy([], {})", "/re/", - "{a:undefined}", "{a:()=>1}", "{[Symbol('k')]:1}", "[undefined]", "[1,,2]", "{toJSON(){return 1;}}", - "{get a(){return 1;}}", "{set a(v){}}", "Object.defineProperty({}, 'a', {value:1, enumerable:false})", - "Object.defineProperty([], 'x', {value:1, enumerable:true})", "'\\ud800'", - "(()=>{const o={}; o.self=o; return o;})()", "(()=>{const a=[]; a.push(a); return a;})()", - "(()=>{const o={a:{}}; o.a.b=o; return o;})()", - ] - for j in invalid { - await expectError(.scriptError, "Interceptor.send('profile',{headers:{},json:1}); try { Interceptor.send('profile',{headers:{},json:\(j)}); } catch (e) {} return {actions:[]};", manifest: writeManifest("POST"), context: j) - await expectError(.scriptError, "Interceptor.send('profile',{headers:{},json:\(j)});", manifest: writeManifest("PUT"), context: j) - } - } - - func testPresentUndefinedJSONIsInvalidNotAbsentAndAbsentIsValid() async throws { - await expectError(.scriptError, "Interceptor.send('profile',{headers:{},json:undefined});", manifest: writeManifest("POST")) - let a = try await run("Interceptor.send('profile',{headers:{}});", manifest: writeManifest("POST")) - XCTAssertNil(a[0]["jsonBody"]) - } - - func testJSONGetterAndProxyOptionsAreRejected() async { - for opts in ["{headers:{},get json(){return 1;}}", "new Proxy({headers:{},json:1},{})", - "Object.defineProperty({headers:{}}, 'json', {value:1, enumerable:false})"] { - await expectError(.scriptError, "try { Interceptor.send('profile',\(opts)); } catch (e) {} return {actions:[]};", manifest: writeManifest("POST")) - } - } - - func testRawActionAndOverrideAttemptsRemainInvalid() async { - let m = writeManifest("POST") - await expectError(.invalidResult, "return {actions:[{type:'http',binding:'profile',headers:{},jsonBody:'{}'}]};", manifest: m) - await expectError(.invalidResult, "return {actions:[{type:'http',binding:'profile',headers:{}}]};", manifest: m) - for extra in ["jsonBody:'{}'", "body:{}", "method:'PUT'", "method:'POST'", "url:'https://evil.example/'", "contentType:'text/plain'", "data:{}"] { - await expectError(.scriptError, "try { Interceptor.send('profile',{headers:{},\(extra)}); } catch (e) {} return {actions:[]};", manifest: m) - } - await expectError(.scriptError, "Interceptor.send('profile',{headers:{},json:{},jsonBody:'{}'});", manifest: m) - } - - func testSnapshotIsNotAffectedByLaterMutationOfJSON() async throws { - let a = try await run("const o={a:[1],s:'one'}; Interceptor.send('profile',{headers:{},json:o}); o.a.push(2); o.s='two'; o.z=true; Object.freeze(o);", manifest: writeManifest("POST")) - XCTAssertEqual(a[0]["jsonBody"] as? String, #"{"a":[1],"s":"one"}"#) - } - - func testUserJSONStringifyAndToJSONAreNeverConsulted() async throws { - let src = "JSON.stringify = () => { throw new Error('used'); }; Object.prototype.toJSON = function(){ throw new Error('used'); };" - let a = try await run("Interceptor.send('profile',{headers:{},json:{a:1}});", top: src, manifest: writeManifest("POST")) - XCTAssertEqual(a[0]["jsonBody"] as? String, #"{"a":1}"#) - } - - func testJSONBodyIsEscapedCorrectlyInsideTheActionWireObject() async throws { - let a = try await run("Interceptor.send('profile',{headers:{authorization:'x'},json:{q:'\"\\\\\\n\\u00e9'}});", manifest: writeManifest("PUT")) - XCTAssertEqual(a[0]["jsonBody"] as? String, "{\"q\":\"\\\"\\\\\\n\u{e9}\"}") - XCTAssertEqual(a[0]["headers"] as? [String: String], ["authorization": "x"]) - } - - func testBodiesShareTheCombinedResultAndActionCaps() async throws { - let big = "{a:'x'.repeat(8184)}" - let two = try await run("Interceptor.send('profile',{headers:{},json:\(big)}); Interceptor.send('profile',{headers:{},json:\(big)});", manifest: writeManifest("POST")) - XCTAssertEqual(two.count, 2) - await expectError(.scriptError, "for (let i=0;i<3;i++) Interceptor.send('profile',{headers:{},json:1});", manifest: writeManifest("POST")) - // Two maximal bodies plus a returned webhook share the two-action cap. - await expectError(.invalidResult, "Interceptor.send('profile',{headers:{},json:\(big)}); Interceptor.send('profile',{headers:{},json:\(big)}); return {actions:[\(webhook(1))]};", manifest: writeManifest("POST")) - } - - func testEscapedBodiesShareTheCombinedResultByteCap() async throws { - let body = #"'\\'.repeat(4095)"# - let send = "Interceptor.send('profile',{headers:{},json:\(body)});" - let single = try await run(send, manifest: writeManifest("POST")) - XCTAssertEqual((single[0]["jsonBody"] as? String)?.utf8.count, 8192) - await expectError(.invalidResult, send + send, manifest: writeManifest("POST")) - } -} - -extension OutboundRuntimeTests { - func testJSONContentTypeMismatchIsStickyBeforeTransport() async { - let m = manifest(outbound: #"{"profile":{"url":"https://api.example.com/v1/profile","method":"POST","headers":["content-type"]}}"#) - await expectError(.scriptError, "try { Interceptor.send('profile',{headers:{'content-type':'text/plain'},json:{}}); } catch(e) {}", manifest: m) - } -} - -extension OutboundRuntimeTests { - func testJSONSnapshotContainsOnlyOwnProperties() async throws { - let actions = try await run("const inherited={secret:'not-sent'}; const value=Object.create(inherited); value.visible=true; Interceptor.send('profile',{headers:{},json:value});", manifest: writeManifest("POST")) - XCTAssertEqual(actions[0]["jsonBody"] as? String, #"{"visible":true}"#) - } -} - -extension OutboundRuntimeTests { - func testSharedOutboundMethodConformance() async throws { - let url = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().appendingPathComponent("Fixtures/outbound-conformance.json") - let root = try JSONValue(parsing: Data(contentsOf: url)) - let rows = try XCTUnwrap(root.objectValue?["cases"]?.arrayValue) - for row in rows { - let fields = try XCTUnwrap(row.objectValue) - let outbound = try XCTUnwrap(fields["outbound"]).jsonString() - guard case .bool(let valid)? = fields["valid"] else { return XCTFail("invalid shared fixture") } - if valid { await accepts(outbound) } else { await rejects(outbound) } - } - } -} diff --git a/Packages/InterceptorAutomation/Tests/Fixtures/outbound-conformance.json b/Packages/InterceptorAutomation/Tests/Fixtures/outbound-conformance.json deleted file mode 100644 index 509a11d..0000000 --- a/Packages/InterceptorAutomation/Tests/Fixtures/outbound-conformance.json +++ /dev/null @@ -1,295 +0,0 @@ -{ - "cases": [ - { - "name": "fixed-https-get", - "valid": true, - "outbound": { - "lookup": { - "url": "https://api.example.com/profile", - "method": "GET", - "headers": [ - "authorization", - "cookie" - ] - } - } - }, - { - "name": "ascii-letter-anywhere-in-final-label", - "valid": true, - "outbound": { - "lookup": { - "url": "https://api.example.1a/%E6%97%A5%E6%9C%AC", - "method": "GET", - "headers": [] - } - } - }, - { - "name": "percent-encoded-high-bytes", - "valid": true, - "outbound": { - "lookup": { - "url": "https://example.com/%80%ff", - "method": "GET", - "headers": [] - } - } - }, - { - "name": "rfc-pchar-and-slashes", - "valid": true, - "outbound": { - "lookup": { - "url": "https://example.com/a-._~!$&'()*+,;=:@/b", - "method": "GET", - "headers": [ - "!#$%&'*+-.^_`|~09az" - ] - } - } - }, - { - "name": "empty-outbound", - "valid": true, - "outbound": {} - }, - { - "name": "localhost-suffix", - "valid": false, - "outbound": { - "lookup": { - "url": "https://api.localhost/", - "method": "GET", - "headers": [] - } - } - }, - { - "name": "local-suffix", - "valid": false, - "outbound": { - "lookup": { - "url": "https://api.local/", - "method": "GET", - "headers": [] - } - } - }, - { - "name": "single-label", - "valid": false, - "outbound": { - "lookup": { - "url": "https://api/", - "method": "GET", - "headers": [] - } - } - }, - { - "name": "ip-address", - "valid": false, - "outbound": { - "lookup": { - "url": "https://127.0.0.1/", - "method": "GET", - "headers": [] - } - } - }, - { - "name": "numeric-final-label", - "valid": false, - "outbound": { - "lookup": { - "url": "https://example.123/", - "method": "GET", - "headers": [] - } - } - }, - { - "name": "explicit-default-port", - "valid": false, - "outbound": { - "lookup": { - "url": "https://example.com:443/", - "method": "GET", - "headers": [] - } - } - }, - { - "name": "uppercase-host", - "valid": false, - "outbound": { - "lookup": { - "url": "https://Example.com/", - "method": "GET", - "headers": [] - } - } - }, - { - "name": "query", - "valid": false, - "outbound": { - "lookup": { - "url": "https://example.com/?q=1", - "method": "GET", - "headers": [] - } - } - }, - { - "name": "fragment", - "valid": false, - "outbound": { - "lookup": { - "url": "https://example.com/#x", - "method": "GET", - "headers": [] - } - } - }, - { - "name": "encoded-control", - "valid": false, - "outbound": { - "lookup": { - "url": "https://example.com/%00", - "method": "GET", - "headers": [] - } - } - }, - { - "name": "encoded-del", - "valid": false, - "outbound": { - "lookup": { - "url": "https://example.com/%7f", - "method": "GET", - "headers": [] - } - } - }, - { - "name": "encoded-backslash", - "valid": false, - "outbound": { - "lookup": { - "url": "https://example.com/%5c", - "method": "GET", - "headers": [] - } - } - }, - { - "name": "malformed-escape", - "valid": false, - "outbound": { - "lookup": { - "url": "https://example.com/%G0", - "method": "GET", - "headers": [] - } - } - }, - { - "name": "post-declaration", - "valid": true, - "outbound": { - "lookup": { - "url": "https://api.example.com/profile", - "method": "POST", - "headers": [] - } - } - }, - { - "name": "put-declaration", - "valid": true, - "outbound": { - "lookup": { - "url": "https://api.example.com/profile", - "method": "PUT", - "headers": [] - } - } - }, - { - "name": "delete-unsupported", - "valid": false, - "outbound": { - "lookup": { - "url": "https://api.example.com/profile", - "method": "DELETE", - "headers": [] - } - } - }, - { - "name": "lowercase-post", - "valid": false, - "outbound": { - "lookup": { - "url": "https://api.example.com/profile", - "method": "post", - "headers": [] - } - } - }, - { - "name": "lowercase-put", - "valid": false, - "outbound": { - "lookup": { - "url": "https://api.example.com/profile", - "method": "put", - "headers": [] - } - } - }, - { - "name": "uppercase-header-name", - "valid": false, - "outbound": { - "lookup": { - "url": "https://api.example.com/profile", - "method": "GET", - "headers": [ - "Authorization" - ] - } - } - }, - { - "name": "forbidden-set-cookie", - "valid": false, - "outbound": { - "lookup": { - "url": "https://api.example.com/profile", - "method": "GET", - "headers": [ - "set-cookie" - ] - } - } - }, - { - "name": "forbidden-proxy-header", - "valid": false, - "outbound": { - "lookup": { - "url": "https://api.example.com/profile", - "method": "GET", - "headers": [ - "proxy-authorization" - ] - } - } - } - ] -} diff --git a/docs/superpowers/plans/2026-10-23-outbound-json-methods.md b/docs/superpowers/plans/2026-10-23-outbound-json-methods.md deleted file mode 100644 index 435a4b3..0000000 --- a/docs/superpowers/plans/2026-10-23-outbound-json-methods.md +++ /dev/null @@ -1,37 +0,0 @@ -# Outbound POST and PUT Implementation Plan - -User authorization: on2026-10-23, explicitly implement POST/PUT support and open PRs. This supersedes the earlier host-read-only limit for this narrow capability, preserving isolation from concurrent package/browser work. - -Goal: a Plugin declares a fixed GET/POST/PUT destination, passes an optional bounded JSON body for POST/PUT, and native transport sends the declared method and correct framing. Preserve legacy GET byte behavior and all destination/authorization/cancellation/redirect policies. - -Execution: separate APP worktree /Users/devonly/Developer/interceptor-outbound-methods/Interceptor at6c46cc9 (base codex/http-hooks); paired read-only Mudmouth65686d2. SDK /Users/devonly/Developer/interceptor-splatnet3-plugin at2c553aa (base codex/http-hooks) contains task-owned SplatNet pure draft logic. No edits to shared package-loading tree. Open stacked PRs against codex/http-hooks in both repositories so concurrent base work is not duplicated. - -## Contract - -- Remain schema2; outbound.{binding}.{url,method,headers} accepts exact uppercaseGET,POST,PUT only. Methods/URLs always come from immutable approved manifest. Old schema1/2 GET behavior unchanged. New packages require a runtime supporting these methods; SDK pin moves only to exact reviewed published APPcommit. -- Interceptor.send(binding,{headers,json?}) remains synchronous and returns void. Recorded action is {type:'http',binding,headers,jsonBody?:string}, where jsonBody is the exact compactJSON serialization captured byC atsendtime. It is an internal validated UTF8bodystring, not a second script option. Caller cannot supply method/URL/framing. This method PR does not introduce a callback/event/workflow/store API. Do not claim POST support alone completes SplatNet acquisition. -- Optional json is permitted only for POST/PUT; absence means empty request body, explicit null meansJSONnull. Present undefined/functions/accessors/symbols/cycles/unsupported values fail sticky and discard all intents. Snapshot body at send time; later JS edits cannot mutate it. -- Strict JSON body <=8192 compactUTF8bytes and depth<=16; retain existing combined result32KiB/actions2/header caps. Use existing safe own-data serializer, not user JSON.stringify/toJSON. C/Swift boundary tests include escaped/nonASCII values and exact8192/8193 bytes. Core exposes PluginOutboundIntent.jsonBody:Data? after validating the exact string bytes withStrictJSON; do not re-encode the parsed JSON. This preserves Cnumber/escape bytecounts at8192 boundary and exactwirebytes; body bytes must not be persisted/logged. -- Header framing owned by native host: content-length is already denied. With json present, reject script content-type other than exactlyapplication/json; accept that exact value if declared and emit exactlyone host-controlledapplication/json header. POST/PUT without json send length0 and may forward a script-declared content-type under existing headergrants; GET rejects any json and retains its previous no-body framing. Native request has explicitinit(host:path:headers:method:jsonBody:) with methodGET/jsonBodynil defaults to preserve oldcallers. -- Native request defense-in-depth validates method/body cap and JSON shape; send a ByteBuffer body beforeend and correct content-length. No response-body collection or automatic retries introduced; current outcome/status behavior unchanged. -- Approval presents actual declared method plus fixed destination and explains JSON body data sharing in existing Section footer. No new screen/flow/layout. UpdateJA/EN copy where existingGET-only wording would mislead. - -## File ownership / tasks - -1. Core/bridge worker owns Packages/InterceptorAutomation/Sources/AutomationCore/PluginOutbound.swift, Sources/CQuickJS/bridge.c, Tests/AutomationCoreTests/PluginOutboundTests.swift, Tests/AutomationRuntimeTests/OutboundRuntimeTests.swift and new APP fixtures/outbound-conformance.json if shared cases are adopted; existing APP tests currently use inline declarations, SDK fixture is fixtures/outbound-conformance.json. Coordinator keeps matching declaration cases synchronized. No Package.swift/APIABI struct changes. Testfirst, legacyparity and snapshot tests. -2. Transport worker owns Interceptor/Automation/HTTPPluginOutboundTransport.swift, HTTPPluginOutboundDispatcher.swift, InterceptorTests/HTTPPluginOutbound{Transport,Dispatcher,Processor}Tests.swift and Interceptor/Views/Automation/PluginPackageApprovalView.swift plus AUTO_APPROVAL_OUTBOUND_FOOTER JA/EN fields in Interceptor/Localizable.xcstrings only. Consume jsonBody:Data? fromTask1. UnitTLSfixture asserts POST/PUT,bodybytes,length0 vsnull, no duplication/contentinjection and unchangedGET; all existing rejection/redirect/revocation/cancellation tests remain. No network to external services. -3. SDK worker owns types/interceptor.d.ts, tools/repository_config.py, tests/test_outbound_metadata.py, test_simulator_outbound.py, test_hook_types.py and one functional plugins/json-request example with fixtures. Compiler existingcallback detection reused. Simulator links unchanged shared Cbridge fromAPPpin, never forkC. Add method/body fixtures and buildgeneratedJS/manifests. SDK upstream pin set bycoordinator after reviewedAPPcommit publiclyfetchable. -4. Codex integration owns tests on nativeMac, immutable source manifests, packagepin, PRs and reviewevidence. Workers have native shared filesystem but their commandenvironment lacksBun/Python/Swift; verify own toolchain and report limits. Codex executes those actual tests. No screenshots planned byworkers. Any later capture must immediately convert to losslessWebP exactRGBA/profile/dimensions+hashes/scale and preserveoriginal only fornamedconsumer. - -## Verification / review - -Independent LocalGPT planreview and Claude feasibility review before implementation. Fresh read-only actualdiffreview after integration; unsafeC/header/body boundaries included. Preserve mandatoryghidentity check/hook before commits/push; no officialsigning/release/deploy. Run focusedSwiftCore/Runtime tests and vendorcheck; nativeTLStransport tests on owned simulator with cleanup. SDK portable/fullrequiredchecks, regeneratedJS/manifests andpackagereferences, no fakeSplatNetmanifest. PRCI exactpushedsource separate fromlocalproof. Record body-sharing approvalvisualgate as unverified if no matchingbaseline evidence; neverclaimUIpassfromunit tests. - -## Plan review resolutions - -- C must store declaration method and inspect ownproperty presence independently of JS_UNDEFINED; preserve oldGET action keyset. Use existing serialize_value(st,ctx,value,1,16,8192,&buf) and escape its snapshot as the internal jsonBody string. Core validates and forwards exactbytes, avoiding Swift/C number-spelling drift. -- Explicit native request initializer preserves old callsites. Body0 framing only forPOST/PUT. Content-type withoutJSON follows existinggrant semantics; withJSON exactapplication/json only, host emits itonce. -- Shared SDK fixture currently labels POSTinvalid; change that case plusPUT/lowercase/DELETE and mirror actualCore/Ctests. Returned rawHTTPactions and send optionmethod/URL overrides remaininvalid. -- ActualGitbase/live refs are verified natively, not reviewerclaims. Currentdate is2026-10-23 in userAsia/Tokyo. Publish APPcommitbefore SDKpin; stackedPRs againstcodex/http-hooks require basePRs first. No merges authorized. - -- IndependentLocalGPT P1presence/framing resolved by explicitIntenthas_json plusownedserializedbytes and single nativeframingbuilder. Core/C/SDKmethod andbodyboundaries receive matchingfixtures; directCoreactionduplicatekeys rejected byStrictJSON. Confirm GET-to-POST/PUT manifestchanges package revision; existing approval remains bound to immutable oldrevision. No reusing oldgrant forchangedpackage. diff --git a/docs/superpowers/plans/2026-10-23-quickjs-fetch.md b/docs/superpowers/plans/2026-10-23-quickjs-fetch.md new file mode 100644 index 0000000..becd53e --- /dev/null +++ b/docs/superpowers/plans/2026-10-23-quickjs-fetch.md @@ -0,0 +1,33 @@ +# QuickJS fetch implementation + +The Salmon Run Plugin needs to POST GraphQL queries and read the responses in +ordinary JavaScript. The existing response.onLeave hook already supplies the +captured BulletToken response; no new capture API is needed. + +- Provide global fetch in response.onLeave with GET/POST/PUT and JSON bodies. +- Reuse the existing strict schema2 package/grants boundary and direct public + HTTPS443/TLS transport. The outgoing request is defined solely in JS. +- Use a dedicated bounded VM thread for the trusted transport callback and drain + Promise jobs for await. Keep legacy synchronous execution unchanged elsewhere. +- HTTPResponse.status/ok/bodyUsed/text()/json() are available; body is consumed + once. No redirects, streaming, compressed replies or automatic credentials. +- Body<=8KiB, response<=1MiB,64requests,16MiB aggregate,8MiB JS heap,250ms CPU + excluding callbackwait,120sec wall. Two VMs perprocess; one perprocessor. +- Probe responseLeave without networking. Synchronous hooks keep their existing + results/errors; a returned Promise or attempted fetch schedules a fresh VM + after the phase permit is released. The read-only hook may run again up to its + first fetch; no probe output or send intent is committed. +- The processor has one active background run and no waiting queue. Additional + runs are rejected through the existing observer; it does not hold original + traffic or synchronous hooks while external requests finish. +- A phase mixing synchronous send intents and deferred hooks commits all intents + after the deferred results validate. Overload, cancellation or failure drops + that phase's intents together, preserving the phase's all-or-nothing behavior. +- Check authorization before transport and subsequent requests; cancel and drain + the VM and socket on shutdown. Keep callbacks and token ownership race-safe. +- No new UI, proprietary JS send API, credential storage or result persistence. + +Verification: real shared-C Swift runtime tests; real NIO/TLS fixture origin; +iOS app/extension build and affected native tests; generated Salmon Plugin +through the exact shared C bridge with offline HTTP fixtures. Real Nintendo +acceptance is a separate hardware/service check.