diff --git a/changelog.d/cluster-owner-approval-request.md b/changelog.d/cluster-owner-approval-request.md new file mode 100644 index 0000000000..2ccd66ca7b --- /dev/null +++ b/changelog.d/cluster-owner-approval-request.md @@ -0,0 +1,3 @@ +### The guided cluster setup asks the DevNet coordinator for its own approval + +After the Test stage passes, `darkbloom cluster` asks the coordinator to register a model approval for the pair (model, its artifact, prefill schedule and the installed app's version, with the account's credential). The pair then reads the coordinator's public approvals together with the account's own approvals, at setup and at every later check, and saves the match as before. On DevNet no operator adds an approval row for a new pair. Production and staging do not take the request: the setup says so on one line ("Cluster approval request: …"), and the pair serves as before. The cluster service asks the same way while the pair holds no approval (at its start and after an update) and renews the approval a week before it ends. A failed request never stops serving, and running the setup again is safe. diff --git a/docs/architecture/inference.md b/docs/architecture/inference.md index 45c07ff127..69dbb69d19 100644 --- a/docs/architecture/inference.md +++ b/docs/architecture/inference.md @@ -225,9 +225,14 @@ and `libs/darkbloom-cluster/Sources/DarkbloomClusterPlacement/ClusterPlacementBa `ClusterOnboardingDriver` presents connection, pairing, model choice, startup and a test response as five stages. Completion requires the test response to succeed; a failed response retains the saved setup for a later retry. After -the test response succeeds, the control leader registers the pair with the -coordinator when the coordinator serves a cluster approval for this pair -(`ClusterOnboardingDriver.register`, control operation `register`). Both parts +the test response succeeds, the control leader first asks the coordinator to +register a model approval for this pair (`ClusterApprovalRequest`, +`POST /v1/cluster/owner-approvals`; only DevNet takes it, and every other +answer is one line that stops nothing). It then registers the pair with the +coordinator when the coordinator serves a cluster approval for this pair, +in its public list or in the account's own approvals +(`ClusterApprovalFetch.fetchOwned`; `ClusterOnboardingDriver.register`, +control operation `register`). Both parts then run as coordinator-paired members (`ClusterService.Settings.memberArguments`), which have no local API, and the ready screen shows the registered line (`ClusterOnboardingReady.offered`, diff --git a/docs/developer/test.md b/docs/developer/test.md index 51b2b1d9c4..e3771b84de 100644 --- a/docs/developer/test.md +++ b/docs/developer/test.md @@ -1081,6 +1081,12 @@ frame (member nonce, epoch, generation, renewal payloads and a refused payload). check the provider against them; the platform's own tests must agree. Refresh them only together with the coordinator change, after review. +`owner_cluster_approval_vector.json` in the same folder is byte for byte the vector of the same name in the +platform repository's coordinator API tests: the `POST /v1/cluster/owner-approvals` body +the provider sends, the coordinator's 201 answer and the approval's canonical policy bytes. +`ClusterApprovalRequestTests` checks that the provider sends exactly that body and verifies the answer's +`policy_sha256`. Replace it only with the platform's file. + The `cluster-member-fixture-child` executable target (`provider-swift/Tests/ClusterMemberFixtureChild/`) is a CPU-only stand-in for an installed owner and its native child, run by the native-pair member control tests over the real owner pipe and key prelude. It is diff --git a/docs/provider/two-mac-cluster.md b/docs/provider/two-mac-cluster.md index 57473bd6cf..37a991e9e5 100644 --- a/docs/provider/two-mac-cluster.md +++ b/docs/provider/two-mac-cluster.md @@ -111,8 +111,9 @@ start fails and says why. To serve without any coordinator, use ## Registered with the coordinator as a cluster member (DevNet) -When the coordinator's operator approval file holds a cluster approval for this -pair's model (DevNet only), the pair registers with the coordinator by itself. +On DevNet the guided setup asks the coordinator for a cluster approval for +this pair's model, and the pair registers with the coordinator by itself. An +approval the coordinator's operator added for the model is taken the same way. Nothing is typed and no file is copied. Production and staging serve no approvals, and the pair serves as described above. The pair serves its owner's own requests, and public requests too once the coordinator's @@ -121,8 +122,14 @@ split ([serving a pair](../reference/cluster-control-protocol.md#serving-a-pair) A tensor-parallel pair registers like a pipeline one; its plan names no cut. 1. Run `darkbloom cluster` and choose a model, as in [the steps](#the-steps-once). - After the Test stage passes, the leader reads the approvals the coordinator - serves (`GET /v1/cluster/approvals`) and takes the one whose model and + After the Test stage passes, the leader asks the coordinator to register a + model approval for this pair (`POST /v1/cluster/owner-approvals`, with the + account's credential; only DevNet takes it, and any other answer is one + line that changes nothing). The cluster service asks the same way later + while the pair holds no approval, for example after an update, and renews + the approval a week before it ends. Then it reads the approvals the coordinator + serves (`GET /v1/cluster/approvals`, and the account's own approvals from + `GET /v1/cluster/owner-approvals`) and takes the one whose model and prefill schedule match this pair's setup. A build-pinned approval must also match the installed app's digests. A model approval names no build and must match only the model's artifact, so it stays valid after an update diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index 0c836383e8..3e2b5bff86 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -1030,7 +1030,8 @@ pair's placement; [serving a pair](cluster-control-protocol.md#serving-a-pair)). | Step | Rule | Source | |---|---|---| -| Fetch | `GET /v1/cluster/approvals`, no query, no credential; HTTPS only (plain HTTP only to this Mac's loopback); no redirect; at most `maximumBytes = 512 * 1024` bytes and `maximumApprovals = 128` entries; `timeoutSeconds = 10`. The body is `darkbloom_cluster_catalog_v2` with `cluster_approvals`. Each entry has the fields of one of the two shapes (build-pinned or model approval); one list can hold both. One unknown, missing or malformed field refuses the whole answer. 404 (pair control off: production, staging) and every failure mean no approval. A read error after an HTTP answer is an answer that cannot be used, not "no answer" | `provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalFetch.swift` (`ClusterApprovalFetch`) | +| Request | Before the Fetch, the control leader asks its coordinator to register the pair's model approval under the account: after the guided setup's Test stage, and at each cluster service check while the saved setup holds no approval, or holds an owner approval (id `owner/…`) within `renewWithinSeconds = 7 * 86_400` of its `not_after`, which it first deletes (`DELETE /v1/cluster/owner-approvals/{id}`; 204 or 404 go on, any other answer stops the renewal). The request is `POST /v1/cluster/owner-approvals` with the account credential (`Authorization: Bearer`, the saved `auth_token`) and the body `{"provider_version","model","artifact_sha256","schedule"}` in that order: the installed app's `CFBundleShortVersionString` (the `Contents/Info.plist` beside the setup's helpers), the setup's `publicModelID`, its `capability.artifactSHA256` and its prefill schedule (`1` or `2`). The coordinator's tests pin the same bytes (`provider-swift/Tests/ProviderCoreTests/Fixtures/coordinator-wire/owner_cluster_approval_vector.json`). Same URL rules as the Fetch. A 200 or 201 holds `{"approval":{…},"policy_sha256":"…"}`, read like an owner entry of the Fetch; the coordinator answers the live approval it already holds for the model and schedule, so asking again is safe. Every outcome is one line ("Cluster approval request: …") that stops nothing: 403 or 404 (production, staging, a build without `-dev.`), another 4xx (400, 409 when the account or the owner catalog is full), nothing sent (no credential, no version), or a failure (no answer, 5xx, an unreadable answer). The service asks again at its next check only after a failure (no answer, 5xx, an unreadable answer); any other outcome settles that need (asking for one, or renewing one approval) until the next service run or update, so a registered approval that this Mac then cannot save is not asked for, nor stopped for, every minute. A check that a running cluster command kept from saving asks again at the next check. A renewal is a new need. Not sent by a local-only cluster or for a setup with a pair approval saved by hand or an operator's approval | `provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalRequest.swift` (`need`, `ensure`); `ClusterService.checkApproval` | +| Fetch | `GET /v1/cluster/approvals`, no query, no credential; with the account credential also `GET /v1/cluster/owner-approvals` (`{"approvals":[{"approval":{…},"policy_sha256":"…"}]}`: the account's own approvals, which the public list does not hold; each `approval` is read like a public entry and its `policy_sha256` must be the SHA-256 of the canonical policy bytes this Mac derives). Its entries join the public list; 401, 403 or 404 there means the account holds none and leaves the public answer as it is; any other failure of either request is the answer; HTTPS only (plain HTTP only to this Mac's loopback); no redirect; at most `maximumBytes = 512 * 1024` bytes and `maximumApprovals = 128` entries; `timeoutSeconds = 10`. The body is `darkbloom_cluster_catalog_v2` with `cluster_approvals`. Each entry has the fields of one of the two shapes (build-pinned or model approval); one list can hold both. One unknown, missing or malformed field refuses the whole answer. 404 (pair control off: production, staging) and every failure mean no approval. A read error after an HTTP answer is an answer that cannot be used, not "no answer" | `provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalFetch.swift` (`ClusterApprovalFetch`) | | Match | The entry whose `model` is the setup's `publicModelID`, whose `schedule` is its prefill schedule (`1` serial, `2` one-chunk lookahead), and that is still current. A model approval matches when its `artifact_sha256` is the saved setup's `capability.artifactSHA256`; no runtime facts are computed for it. A build-pinned entry matches when its eight digests all equal this Mac's own cluster runtime facts (computed at most once per check from the helpers beside the setup's worker and the setup's model folder). Latest `not_after` first, across both shapes. An entry for another build or another copy of the model does not match | `provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalLifetime.swift` (`select`) | | Check | On each Mac, against its own files: every digest of a build-pinned entry (`ClusterApprovalAttachment.mismatches`), or the artifact of a model approval (refusal: "the approval's artifact_sha256 differs from this Mac's setup"); the member's own start refusals (`requireLocalRankGranted`); the roster of this Mac's pairing (S17); `validate` below | `provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalAttachment.swift` (`attachment`) | | Save | Both parts stop. The leader checks the entry, sends it to the other Mac over the cable (service command `approval`), and saves it only after the other Mac checked and saved it. A refusal on either Mac saves it on neither. Both parts then start as cluster members | `provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalSync.swift` (`run`, `receive`) | diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalFetch.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalFetch.swift index 70ee91294a..989c15e406 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalFetch.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalFetch.swift @@ -5,9 +5,13 @@ import Foundation /// approves nothing by itself: the leader takes only an entry whose digests are this Mac's own cluster runtime facts /// (or a model approval for its saved setup's model, schedule and artifact), and each Mac checks it against its own /// installed files before it saves it (`ClusterApprovalAttachment`). A coordinator without pair control answers 404, -/// and every failure means "no approval": nothing here can stop a Mac from serving. +/// and every failure means "no approval": nothing here can stop a Mac from serving. With the account credential the +/// leader also reads the approvals its own account registered (`GET /v1/cluster/owner-approvals`, +/// `ClusterApprovalRequest`), which the public list does not hold, and takes them as listed entries too. public enum ClusterApprovalFetch { public static let path = "/v1/cluster/approvals" + /// The caller's own unexpired approvals (DevNet): `{"approvals":[{"approval":{…},"policy_sha256":"…"}]}`. + public static let ownerPath = "/v1/cluster/owner-approvals" public static let schemaName = "darkbloom_cluster_catalog_v2" /// More entries than any operator file holds are never read. static let maximumApprovals = 128 @@ -27,7 +31,7 @@ public enum ClusterApprovalFetch { /// The request URL for the provider's coordinator: HTTPS, or plain HTTP to this Mac's own loopback (a local test /// coordinator). Nil for any other URL, so a plain request never leaves the Mac. - static func url(coordinatorURL: String) -> URL? { + static func url(coordinatorURL: String, path: String = ClusterApprovalFetch.path) -> URL? { guard var components = URLComponents(string: coordinatorHTTPBase(coordinatorURL)), let scheme = components.scheme?.lowercased(), let host = components.host?.lowercased(), scheme == "https" || (scheme == "http" && ["127.0.0.1", "localhost", "::1"].contains(host)), @@ -37,51 +41,110 @@ public enum ClusterApprovalFetch { } public static func fetch(coordinatorURL: String) async -> Outcome { - guard let url = url(coordinatorURL: coordinatorURL) else { + await get(coordinatorURL: coordinatorURL, path: path, token: nil, notOffered: [404], decode: decode) + } + + /// The approvals the credential's account registered. 404 (owner approvals off), 403 (not development, no + /// account) and 401 (a credential the coordinator does not take) mean it holds none. + static func fetchOwned(coordinatorURL: String, token: String) async -> Outcome { + await get(coordinatorURL: coordinatorURL, path: ownerPath, token: token, notOffered: [401, 403, 404], decode: decodeOwned) + } + + /// The public list and the account's own approvals as one answer. An account that holds none leaves the public + /// answer as it is (production and staging byte for byte). When either request fails, the answer is that failure, + /// so a partial answer never withdraws a saved approval that the other list holds. + static func combined(_ listed: Outcome, owned: Outcome) -> Outcome { + switch (listed, owned) { + case (_, .notOffered): return listed + case (.approvals(let listedEntries), .approvals(let own)): return .approvals(listedEntries + own) + case (.notOffered, .approvals(let own)): return .approvals(own) + case (.approvals, _), (.notOffered, _): return owned + default: return listed + } + } + + private static func get(coordinatorURL: String, path: String, token: String?, notOffered: Set, + decode: (Data) throws -> [ClusterRuntimeApproval]) async -> Outcome { + guard let url = url(coordinatorURL: coordinatorURL, path: path) else { return .unavailable("the coordinator URL is not HTTPS") } + switch await send(url, token: token, reads: { $0 == 200 }) { + case .unreachable(let reason): return .unreachable(reason) + case .unusable(let reason): return .unavailable(reason) + case .answered(let status, _) where notOffered.contains(status): return .notOffered + case .answered(let status, .none): return .unavailable("HTTP \(status)") + case .answered(_, .some(let body)): + do { return .approvals(try decode(body)) } catch let error as ClusterConfigurationError { + return .unavailable("\(error)") + } catch { + return .unavailable(error.localizedDescription) + } + } + } + + /// The coordinator's answer to one request (`send`). + enum Answer { + /// Its HTTP status, and its body when the caller reads that status. + case answered(status: Int, body: Data?) + /// An answer that cannot be used: not this URL's, over `maximumBytes`, or unreadable. The reason. + case unusable(String) + /// No HTTP answer at all (no route, refused, timed out): the reason. + case unreachable(String) + } + + /// One request to the coordinator under the rules every cluster approval exchange keeps: an ephemeral session with + /// no cache, cookie or credential store, no redirect followed (a credential never leaves for another URL), + /// `timeoutSeconds`, and at most `maximumBytes` of a body read, only for a status `reads` takes. + static func send(_ url: URL, method: String = "GET", token: String?, body: Data? = nil, + reads: (Int) -> Bool) async -> Answer { let configuration = URLSessionConfiguration.ephemeral configuration.timeoutIntervalForRequest = timeoutSeconds; configuration.timeoutIntervalForResource = timeoutSeconds configuration.urlCache = nil; configuration.httpCookieStorage = nil; configuration.urlCredentialStorage = nil let session = URLSession(configuration: configuration, delegate: ClusterNoRedirect(), delegateQueue: nil) defer { session.invalidateAndCancel() } var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: timeoutSeconds) + request.httpMethod = method + if let body { + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + request.httpBody = body + } request.setValue("application/json", forHTTPHeaderField: "Accept") + if let token { request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") } do { let (stream, response) = try await session.bytes(for: request) - guard let http = response as? HTTPURLResponse, http.url == url else { return .unavailable("no HTTP answer") } - if http.statusCode == 404 { return .notOffered } - guard http.statusCode == 200 else { return .unavailable("HTTP \(http.statusCode)") } - guard response.expectedContentLength <= Int64(maximumBytes) else { return .unavailable("the answer exceeds its bound") } + guard let http = response as? HTTPURLResponse, http.url == url else { return .unusable("no HTTP answer") } + guard reads(http.statusCode) else { return .answered(status: http.statusCode, body: nil) } + guard response.expectedContentLength <= Int64(maximumBytes) else { return .unusable("the answer exceeds its bound") } // An answer came: a failure from here on is an unusable answer, never "unreachable". var bytes = Data() do { for try await byte in stream { - guard bytes.count < maximumBytes else { return .unavailable("the answer exceeds its bound") } + guard bytes.count < maximumBytes else { return .unusable("the answer exceeds its bound") } bytes.append(byte) } } catch { - return .unavailable("the answer could not be read: \(error.localizedDescription)") + return .unusable("the answer could not be read: \(error.localizedDescription)") } - return .approvals(try decode(bytes)) - } catch let error as ClusterConfigurationError { - return .unavailable("\(error)") + return .answered(status: http.statusCode, body: bytes) } catch let error as URLError { return .unreachable(error.localizedDescription) } catch { - return .unavailable(error.localizedDescription) + return .unusable(error.localizedDescription) } } - /// What the provider configuration's coordinator serves; nil when the provider configuration names no coordinator. - static func fetch(providerConfiguration: URL) async -> Outcome? { + /// What the provider configuration's coordinator serves, with the account's own approvals when this Mac holds + /// the account credential (`combined`); nil when the provider configuration names no coordinator. + static func fetch(providerConfiguration: URL, token: String? = AuthTokenStore.load()) async -> Outcome? { guard let coordinator = try? ConfigManager.loadOrDefaults(from: providerConfiguration).coordinator.url else { return nil } - return await fetch(coordinatorURL: coordinator) + let listed = await fetch(coordinatorURL: coordinator) + guard let token, !token.isEmpty else { return listed } + return combined(listed, owned: await fetchOwned(coordinatorURL: coordinator, token: token)) } /// The same, from a thread outside the cooperative pool (the cluster service's and the onboarding's threads). - static func fetchBlocking(providerConfiguration: URL) -> Outcome? { - blockingWizard { await fetch(providerConfiguration: providerConfiguration) } + static func fetchBlocking(providerConfiguration: URL, token: String? = AuthTokenStore.load()) -> Outcome? { + blockingWizard { await fetch(providerConfiguration: providerConfiguration, token: token) } } /// `{"schema":"darkbloom_cluster_catalog_v2","cluster_approvals":[…]}`, read as strictly as a saved setup reads @@ -101,4 +164,44 @@ public enum ClusterApprovalFetch { for approval in approvals { _ = try approval.canonicalPolicy() } return approvals } + + /// `{"approvals":[{"approval":{…},"policy_sha256":"…"}]}`: each entry read as `decodeOwnedEntry` reads one. One + /// bad entry refuses the whole answer. + static func decodeOwned(_ data: Data) throws -> [ClusterRuntimeApproval] { + guard let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any], Set(object.keys) == ["approvals"], + let entries = object["approvals"] as? [[String: Any]], entries.count <= maximumApprovals, + entries.allSatisfy(isOwnedEntry) else { + throw ClusterConfigurationError.invalid("The owner approvals answer is not an approvals list") + } + struct List: Decodable { let approvals: [OwnedEntry] } + return try JSONDecoder().decode(List.self, from: data).approvals.map { try $0.verified() } + } + + /// `{"approval":{…},"policy_sha256":"…"}`, the answer of a registration: the `approval` read as strictly as a + /// public entry (`decode`), and its `policy_sha256` must be the SHA-256 of the canonical policy bytes this Mac + /// derives from it. + static func decodeOwnedEntry(_ data: Data) throws -> ClusterRuntimeApproval { + guard let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any], isOwnedEntry(object) else { + throw ClusterConfigurationError.invalid("The answer is not an owner approval") + } + return try JSONDecoder().decode(OwnedEntry.self, from: data).verified() + } + + private static func isOwnedEntry(_ entry: [String: Any]) -> Bool { + Set(entry.keys) == ["approval", "policy_sha256"] + && (entry["approval"] as? [String: Any]).map { ClusterRuntimeApproval.isEntry($0.keys) } == true + } + + private struct OwnedEntry: Decodable { + let approval: ClusterRuntimeApproval + let policySHA256: String + enum CodingKeys: String, CodingKey { case approval; case policySHA256 = "policy_sha256" } + + func verified() throws -> ClusterRuntimeApproval { + guard ClusterConfigurationCodec.sha256(try approval.canonicalPolicy()) == policySHA256 else { + throw ClusterConfigurationError.invalid("Owner approval \(approval.id) does not hash to its policy_sha256") + } + return approval + } + } } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalRequest.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalRequest.swift new file mode 100644 index 0000000000..e1376042e4 --- /dev/null +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Membership/ClusterApproval/ClusterApprovalRequest.swift @@ -0,0 +1,182 @@ +import Foundation +import DarkbloomClusterProtocol + +/// The control leader's request that the provider's coordinator register this pair's model approval under the +/// account (`POST /v1/cluster/owner-approvals`), and its renewal (`DELETE /v1/cluster/owner-approvals/{id}`, then the +/// request again). The leader asks before it reads the approvals (`ClusterApprovalFetch`): after the guided setup's +/// Test stage, and at the cluster service's checks while the setup holds no approval or holds an owner approval +/// within `renewWithinSeconds` of its end (`need`). The request carries the provider's coordinator credential, the +/// installed app's version, the setup's model, its artifact and its prefill schedule; the coordinator answers with the +/// approval it holds for them (a new one, or the live one it already has, so asking again is safe). The answer +/// approves nothing by itself: the fetch reads the account's own approvals (`ClusterApprovalFetch.fetchOwned`), and +/// the existing match and save on both Macs (`ClusterApprovalSync`) take the entry as they take an operator's. Only a +/// DevNet coordinator takes the request; production and staging answer 403 or 404. Every outcome is one line, and +/// none stops a Mac from serving. +enum ClusterApprovalRequest { + static let path = ClusterApprovalFetch.ownerPath + /// An owner approval this close to its `not_after` is renewed. + static let renewWithinSeconds: Double = 7 * 86_400 + /// How the coordinator names an approval its owner registered: `owner///s/`. + static let ownerIDPrefix = "owner/" + + enum Outcome: Equatable, Sendable { + /// 200 or 201: the coordinator holds this approval for the pair. + case registered(String) + /// 403 or 404: this coordinator does not register approvals for this pair (production, staging, a build + /// without `-dev.`, the setting off). + case notTaken(Int) + /// Another 4xx: the coordinator refused this request (400 a body it does not read, 409 the account or the + /// catalog is full). + case refused(Int) + /// Nothing was sent: this Mac lacks what the request needs (a credential, the installed version, an HTTPS + /// coordinator). + case notSent(String) + /// No answer, a 5xx or a redirect, an answer that is not an owner approval, or a renewal whose delete failed. + case failed(String) + + /// The one line for the screen and the service log (`ClusterOnboardingReady.approvalRequestNotice`). + var line: String { + let text: String + switch self { + case .registered(let id): text = "the coordinator holds approval \(id) for this pair" + case .notTaken(let status): text = "not taken by this coordinator (HTTP \(status))" + case .refused(let status): text = "refused by the coordinator (HTTP \(status))" + case .notSent(let reason): text = "not sent (\(reason))" + case .failed(let reason): text = "failed (\(reason))" + } + return ClusterOnboardingReady.approvalRequestNotice + ": " + text + "." + } + + /// Whether the cluster service asks again for the same need at its next check: only after a failure that may + /// pass (no answer, a server error). Any answer settles that need for this run of the service: a registered + /// approval is read and saved by the same check (asking again would answer the same approval, and a save + /// refused once would be stopped for and refused again every minute), and a refusal, or a Mac that cannot + /// send, waits for the next service run or update. A later need (a renewal) is asked when it comes, and a check + /// that a busy command lock kept from saving asks again at the next one. + var retries: Bool { + switch self { + case .failed: return true + case .registered, .notTaken, .refused, .notSent: return false + } + } + } + + /// What the leader asks for its saved setup before it reads the approvals. + enum Need: Equatable, Sendable { + /// Nothing: the setup holds a pair approval saved by hand, an operator's cluster approval, or an owner approval + /// with more than `renewWithinSeconds` left. + case nothing + /// The setup holds no approval: ask for one. + case request + /// The setup holds this owner approval, which ends within `renewWithinSeconds`: delete it, then ask again. + case renew(String) + } + + static func need(_ saved: ClusterConfigurationStore.Saved, now: Double) -> Need { + let member = saved.configuration.nativeMember + guard member?.approval == nil else { return .nothing } + guard let held = member?.clusterApproval else { return .request } + guard held.id.hasPrefix(ownerIDPrefix), let end = ClusterApprovalLifetime.expiry(held), end - now <= renewWithinSeconds else { + return .nothing + } + return .renew(held.id) + } + + /// The request body: exactly the fields the coordinator's endpoint reads, in the order of the shared vector + /// (`Fixtures/coordinator-wire/owner_cluster_approval_vector.json`, the same bytes the coordinator's tests pin). + static func body(providerVersion: String, model: String, artifact: String, schedule: UInt8) throws -> Data { + func string(_ value: String) throws -> String { + String(decoding: try JSONSerialization.data(withJSONObject: value, options: [.fragmentsAllowed, .withoutEscapingSlashes]), + as: UTF8.self) + } + return Data(("{\"provider_version\":" + (try string(providerVersion)) + ",\"model\":" + (try string(model)) + + ",\"artifact_sha256\":" + (try string(artifact)) + ",\"schedule\":\(schedule)}").utf8) + } + + /// The version of the app whose helpers the setup runs (`Contents/Info.plist` beside `Contents/Helpers`): what + /// this Mac has installed, which an update may have changed since this process started. + static func installedVersion(_ configuration: ClusterConfiguration) -> String? { + let contents = ClusterApprovalAttachment.installation(configuration).worker.deletingLastPathComponent().deletingLastPathComponent() + guard let data = try? Data(contentsOf: contents.appendingPathComponent("Info.plist")), + let info = (try? PropertyListSerialization.propertyList(from: data, format: nil)) as? [String: Any], + let version = info["CFBundleShortVersionString"] as? String, !version.isEmpty else { return nil } + return version + } + + /// One exchange with the coordinator under the fetch's rules (`ClusterApprovalFetch.send`: HTTPS or this Mac's + /// loopback, no redirect, so the credential never leaves the Mac in plain text or for another URL): the status and, + /// for a 200 or 201, the body; or the outcome that ends the request first. + private static func exchange(coordinatorURL: String, path: String, method: String, token: String?, + body: Data?) async -> Result<(status: Int, data: Data), Stop> { + guard let url = ClusterApprovalFetch.url(coordinatorURL: coordinatorURL, path: path) else { + return .failure(.init(.notSent("the coordinator URL is not HTTPS"))) + } + guard let token, !token.isEmpty else { return .failure(.init(.notSent("this Mac is not linked to an account"))) } + switch await ClusterApprovalFetch.send(url, method: method, token: token, body: body, reads: { $0 == 200 || $0 == 201 }) { + case .answered(let status, let data): return .success((status: status, data: data ?? Data())) + case .unusable(let reason): return .failure(.init(.failed(reason))) + case .unreachable(let reason): return .failure(.init(.failed("no answer: " + reason))) + } + } + + /// An outcome that ends an exchange before an answer to read. + private struct Stop: Error { let outcome: Outcome; init(_ outcome: Outcome) { self.outcome = outcome } } + + /// `POST /v1/cluster/owner-approvals` to `coordinatorURL` (the provider configuration's WebSocket URL). A 200 or + /// 201 must hold one owner approval whose `policy_sha256` this Mac derives (`ClusterApprovalFetch.decodeOwnedEntry`). + static func request(coordinatorURL: String, token: String?, providerVersion: String, model: String, artifact: String, + schedule: UInt8) async -> Outcome { + let body: Data + do { body = try self.body(providerVersion: providerVersion, model: model, artifact: artifact, schedule: schedule) } catch { + return .notSent(error.localizedDescription) + } + switch await exchange(coordinatorURL: coordinatorURL, path: path, method: "POST", token: token, body: body) { + case .failure(let stop): + return stop.outcome + case .success(let answer): + switch answer.status { + case 200, 201: + guard let approval = try? ClusterApprovalFetch.decodeOwnedEntry(answer.data) else { + return .failed("the answer is not an owner approval") + } + return .registered(approval.id) + case 403, 404: return .notTaken(answer.status) + case 400..<500: return .refused(answer.status) + default: return .failed("HTTP \(answer.status)") + } + } + } + + /// `DELETE /v1/cluster/owner-approvals/{id}`: nil when the coordinator no longer holds it (204, or 404: not, or no + /// longer, this account's), else why the renewal stopped. + static func delete(id: String, coordinatorURL: String, token: String?) async -> Outcome? { + switch await exchange(coordinatorURL: coordinatorURL, path: path + "/" + id, method: "DELETE", token: token, body: nil) { + case .failure(let stop): return stop.outcome + case .success(let answer) where answer.status == 204 || answer.status == 404: return nil + case .success(let answer): return .failed("the renewal could not delete approval \(id): HTTP \(answer.status)") + } + } + + /// What the saved setup needs (`need`), asked of the provider configuration's coordinator with the saved account + /// credential: nil when it needs nothing, so nothing is sent and nothing is said. + static func ensure(_ saved: ClusterConfigurationStore.Saved, providerConfiguration: URL, now: Double, + token: String? = AuthTokenStore.load()) async -> Outcome? { + let needed = need(saved, now: now) + if needed == .nothing { return nil } + guard let coordinator = try? ConfigManager.loadOrDefaults(from: providerConfiguration).coordinator.url else { + return .notSent("the provider configuration names no coordinator") + } + let configuration = saved.configuration + guard let version = installedVersion(configuration) else { return .notSent("the installed app's version could not be read") } + if case .renew(let id) = needed, let stopped = await delete(id: id, coordinatorURL: coordinator, token: token) { return stopped } + return await request(coordinatorURL: coordinator, token: token, providerVersion: version, model: configuration.publicModelID, + artifact: saved.capability.artifactSHA256, + schedule: ClusterApprovalLifetime.schedule(configuration.selectedPrefillSchedule)) + } + + /// The same, from a thread outside the cooperative pool (the cluster service's and the onboarding's threads). + static func ensureBlocking(_ saved: ClusterConfigurationStore.Saved, providerConfiguration: URL, now: Double, + token: String? = AuthTokenStore.load()) -> Outcome? { + blockingWizard { await ensure(saved, providerConfiguration: providerConfiguration, now: now, token: token) } + } +} diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift index 043da369a4..7cdfe574fd 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingFlow.swift @@ -518,6 +518,10 @@ public struct ClusterOnboardingReady: Codable, Sendable, Equatable { /// How the line of a pair registered with the coordinator as a cluster member starts (`ClusterLocalServing`). public static let registeredNotice = "Registered with the coordinator as a cluster member" + /// How the line of the leader's request that the coordinator register the pair's approval starts + /// (`ClusterApprovalRequest`). The request stops nothing, so its line alone is no reason to wait for the parts. + public static let approvalRequestNotice = "Cluster approval request" + /// Said instead of the test request when the pair is offered for pairing (and the answer of `t` then). public static let offeredTestLine = "This pair has no local API while it is offered for pairing: requests from your own account reach it through Darkbloom." @@ -1228,17 +1232,19 @@ public enum ClusterOnboardingDriver { } /// After the Test stage: registers the pair with the coordinator when it serves a cluster approval for this pair, - /// then waits until both Macs serve again. Nothing is said, and nothing stopped, when the coordinator serves none. - /// A registration that stopped the parts and was then refused also waits: both parts start again as before. + /// then waits until both Macs serve again. Only the approval request's line is said, and nothing stopped, when the + /// coordinator serves none. A registration that stopped the parts and was then refused also waits: both parts + /// start again as before. static func register(title: String, _ operations: ClusterOnboardingOperations, _ console: ClusterOnboardingConsole) { let lines: [String] switch operations.register() { case .success(let said): lines = said case .failure(let failure): lines = failure.lines } - guard !lines.isEmpty else { return } for line in lines { console.say(" " + line) } - console.say(lines.first?.hasPrefix(ClusterOnboardingReady.registeredNotice) == true + let stopped = lines.filter { !$0.hasPrefix(ClusterOnboardingReady.approvalRequestNotice) } + guard !stopped.isEmpty else { return } + console.say(stopped.first?.hasPrefix(ClusterOnboardingReady.registeredNotice) == true ? "Starting both Macs' parts again as cluster members…" : "Starting both Macs' parts again…") _ = awaitReady(title: title, operations, console) } diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift index b38f593264..341694980e 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterOnboardingLive.swift @@ -1109,30 +1109,36 @@ final class OnboardingLive: @unchecked Sendable { return .success(lines + result.lines) } - /// After the Test stage passed: registers the pair with the coordinator as a cluster member when the coordinator - /// serves a cluster approval whose digests are this Mac's own facts (`ClusterApprovalSync`), on the control leader. + /// After the Test stage passed: asks the coordinator to register the pair's model approval, then registers the + /// pair with the coordinator as a cluster member when the coordinator serves a cluster approval for this pair + /// (`ClusterApprovalSync`), on the control leader. func register() -> Result<[String], ClusterOnboardingFailure> { routed(.init(op: .register), seconds: 900, acting: true, local: { localRegister() }) { $0.lines } } - /// The leader's half of `register`. A local-only cluster never asks; a coordinator that serves no matching entry - /// (404, none listed, any failure) changes nothing and stops nothing. Otherwise both parts stop (each save needs - /// its device journal empty), each Mac checks the entry against its own files and saves it, the other Mac first, - /// and both parts start again as cluster members. + /// The leader's half of `register`. A local-only cluster never asks. First the leader asks its coordinator to + /// register the pair's model approval when the setup holds none, or to renew an owner approval near its end + /// (`ClusterApprovalRequest.ensure`; one line, whatever the answer, and it stops nothing). Then a coordinator that serves no matching + /// entry (404, none listed, any failure) changes nothing and stops nothing. Otherwise both parts stop (each save + /// needs its device journal empty), each Mac checks the entry against its own files and saves it, the other Mac + /// first, and both parts start again as cluster members. func localRegister() -> Result<[String], ClusterOnboardingFailure> { guard leadership?.scope.isLocalOnly != true else { return .success([]) } let providerConfiguration = settings.service.wizard.providerConfiguration - guard let saved = try? ClusterApprovalAttachment.savedSetup(paths: context.paths, providerConfiguration: providerConfiguration), - let fetched = ClusterApprovalFetch.fetchBlocking(providerConfiguration: providerConfiguration), + guard let saved = try? ClusterApprovalAttachment.savedSetup(paths: context.paths, providerConfiguration: providerConfiguration) + else { return .success([]) } + let asked = ClusterApprovalRequest.ensureBlocking(saved, providerConfiguration: providerConfiguration, + now: Date().timeIntervalSince1970).map { [$0.line] } ?? [] + guard let fetched = ClusterApprovalFetch.fetchBlocking(providerConfiguration: providerConfiguration), case .save(let approval) = ClusterApprovalSync.decision(saved: saved, fetched: fetched, now: Date().timeIntervalSince1970, facts: ClusterApprovalAttachment.installedFacts) else { - return .success([]) + return .success(asked) } - if case .failure(let failure) = localStop() { return .failure(failure) } + if case .failure(let failure) = localStop() { return .failure(.init(asked + failure.lines)) } guard drained(seconds: 300) else { // The services start the parts again by themselves, with the setups as they were. try? store.updateRecord { $0.leadership?.serving = true } - return .failure(.init("A part did not stop within 5 minutes, so the cluster was not registered with the coordinator.")) + return .failure(.init(asked + ["A part did not stop within 5 minutes, so the cluster was not registered with the coordinator."])) } let result = ClusterApprovalSync.run(fetched: .approvals([approval]), paths: context.paths, providerConfiguration: providerConfiguration, pairingStore: .default(home: context.paths.homeDirectory), @@ -1140,8 +1146,9 @@ final class OnboardingLive: @unchecked Sendable { _ = try command(request, seconds: 180) } if let note = result.note { try? store.updateRecord { $0.approvalNote = note } } - if case .failure(let failure) = localServe() { return .failure(.init((result.line.map { [$0 + "."] } ?? []) + failure.lines)) } - return .success(result.line.map { [$0 + "."] } ?? []) + let said = asked + (result.line.map { [$0 + "."] } ?? []) + if case .failure(let failure) = localServe() { return .failure(.init(said + failure.lines)) } + return .success(said) } /// After `localStop`: waits until both Macs say nothing is left running (at most diff --git a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift index f589880104..17d47875ac 100644 --- a/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift +++ b/provider-swift/Sources/ProviderCore/Inference/Distributed/Onboarding/ClusterService.swift @@ -108,6 +108,10 @@ public final class ClusterService: @unchecked Sendable { private var approvalInFlight = false private var nextApprovalCheck = Date.distantPast private var approvalWatch = ClusterApprovalCheck.Watch() + // The owner approval need (`ClusterApprovalRequest.need`) the coordinator answered in this run of the service, or + // this Mac could not send (`ClusterApprovalRequest.Outcome.retries`): not asked again until the need changes (a + // renewal), the next run of this service or an update. + private var ownerRequestSettled: ClusterApprovalRequest.Need? // This Mac's coordinator-paired parts that ended in a row right after starting (`ClusterApprovalCheck.memberQuickEnds`), // and whether the running part is one. private var memberQuickEnds = 0 @@ -1006,13 +1010,17 @@ public final class ClusterService: @unchecked Sendable { + choices[index].lines.joined(separator: " ") + ")") // The re-adopted setups carry no cluster approval: the next check finds the same model approval again, or the // build-pinned entry of the updated app. - self.lock.withLock { self.approvalChecked = false; self.nextApprovalCheck = .distantPast } + self.lock.withLock { + self.approvalChecked = false; self.nextApprovalCheck = .distantPast; self.ownerRequestSettled = nil + } } } /// On the control leader: asks the coordinator for its cluster approvals once per run of this service, and every /// `ClusterOnboardingUpdate.checkEverySeconds` while the pair is registered or serves locally with its approval set - /// aside (`ClusterApprovalCheck.asks`). Only when a setup must change (`ClusterApprovalCheck.step`: an approval to + /// aside (`ClusterApprovalCheck.asks`), or while the setup needs an owner approval (`ClusterApprovalRequest.need`: + /// none held, or an owner approval near its end) that the coordinator has not answered in this run. Such a check + /// first asks the coordinator to register (or renew) it, says the outcome in one line, and then reads the list. Only when a setup must change (`ClusterApprovalCheck.step`: an approval to /// save, or one to serve without because the coordinator gave no answer for the grace, no longer lists it, or the /// parts keep failing with it) it stops both parts, changes both Macs' setups and serves again. A coordinator that /// serves nothing new changes nothing and stops nothing. An approval that ended is removed by each Mac itself @@ -1030,6 +1038,8 @@ public final class ClusterService: @unchecked Sendable { guard let self else { return } defer { self.lock.withLock { self.approvalInFlight = false } } let first = self.lock.withLock { !self.approvalChecked } + // Read once, so the decision taken again under the command lock asks as the first one did. + let settled = self.lock.withLock { self.ownerRequestSettled } func checked() { self.lock.withLock { self.approvalChecked = true @@ -1046,7 +1056,7 @@ public final class ClusterService: @unchecked Sendable { /// The saved setup's worker digest, recorded with an approval set aside. let worker: String } - func decide(_ answer: () -> ClusterApprovalFetch.Outcome?) -> Decided? { + func decide(_ answer: (ClusterConfigurationStore.Saved, ClusterApprovalRequest.Need) -> ClusterApprovalFetch.Outcome?) -> Decided? { let record = try? self.store.readRecord() let scope = record?.leadership?.scope ?? .publicServing var setAside = record?.approvalSetAside @@ -1060,11 +1070,13 @@ public final class ClusterService: @unchecked Sendable { let peer = try? JSONDecoder().decode(ClusterServiceStatus.self, from: live.command(.init(op: .status), seconds: 10)) let peerApprovalID = ClusterApprovalCheck.peerApprovalID(peer) let macsDiffer = ClusterApprovalCheck.macsDiffer(saved, peerApprovalID: peerApprovalID) - let asks = ClusterApprovalCheck.asks(first: first, serving: record?.leadership?.serving == true, scope: scope, - offered: offered, setAside: setAside != nil, macsDiffer: macsDiffer) + let need: ClusterApprovalRequest.Need = scope.isLocalOnly ? .nothing : ClusterApprovalRequest.need(saved, now: now) + let ownerNeed: ClusterApprovalRequest.Need = need == settled ? .nothing : need + let asks = ownerNeed != .nothing || ClusterApprovalCheck.asks(first: first, serving: record?.leadership?.serving == true, + scope: scope, offered: offered, setAside: setAside != nil, macsDiffer: macsDiffer) guard asks || macsDiffer else { return nil } // A local-only cluster settles a difference between the Macs without asking the coordinator. - guard let fetched = asks ? answer() : .unavailable("not asked") else { return nil } + guard let fetched = asks ? answer(saved, ownerNeed) : .unavailable("not asked") else { return nil } if let ended = setAside, !ClusterApprovalLifetime.current(ended.approval, now: now) { try? self.store.updateRecord { $0.approvalSetAside = nil } setAside = nil @@ -1078,8 +1090,21 @@ public final class ClusterService: @unchecked Sendable { worker: saved.capability.runtimeBinarySHA256) } var fetched: ClusterApprovalFetch.Outcome? - func answer() -> ClusterApprovalFetch.Outcome? { + // The owner need this check's request got an answer for (`retries` false). It is settled when the check + // ends, unless a busy command lock kept the check from saving what the answer registered. + var answeredNeed: ClusterApprovalRequest.Need?, saveDeferred = false + defer { + if let answeredNeed, !saveDeferred { self.lock.withLock { self.ownerRequestSettled = answeredNeed } } + } + func answer(_ saved: ClusterConfigurationStore.Saved, _ ownerNeed: ClusterApprovalRequest.Need) -> ClusterApprovalFetch.Outcome? { if fetched == nil { + // The owner approval request (DevNet) comes first, so the list read next holds what it registered. + if ownerNeed != .nothing, + let asked = ClusterApprovalRequest.ensureBlocking(saved, providerConfiguration: configuration, + now: Date().timeIntervalSince1970) { + say(asked.line) + if !asked.retries { answeredNeed = ownerNeed } + } fetched = ClusterApprovalFetch.fetchBlocking(providerConfiguration: configuration) ?? .unavailable("no coordinator is configured") } return fetched @@ -1091,6 +1116,7 @@ public final class ClusterService: @unchecked Sendable { // not at every tick. guard let held = ClusterControlCommandLock.acquire(seconds: 5) else { say("another cluster command is running: the cluster approval is checked again in a minute") + saveDeferred = true return checked() } defer { held.release() } diff --git a/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift b/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift index dbb5cc080c..a106489c18 100644 --- a/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift +++ b/provider-swift/Tests/ClusterOnboardingChecks/OnboardingChecks.swift @@ -28,6 +28,7 @@ import Darwin pairingStateMachine() leaderFromScratch() leaderWaitsForThePartsAfterTheRegistration() + leaderSaysTheApprovalRequestAndWaitsForNothingElse() forcedModeNoticeOnTheSetupScreen() memberFromScratch() bothWaitingAtOnce() @@ -662,6 +663,10 @@ import Darwin "Starting both Macs' parts again…"), ("registered", .success([ClusterOnboardingReady.registeredNotice + ": approval devnet/0.10.4-dev.1/Qwen3.5-9B/s1, until 2026-11-12T00:00:00Z."]), "Starting both Macs' parts again as cluster members…"), + ("asked, then registered", .success([ + ClusterOnboardingReady.approvalRequestNotice + ": the coordinator holds approval owner/a/Qwen3.5-9B/s1/0123456789ab for this pair.", + ClusterOnboardingReady.registeredNotice + ": approval owner/a/Qwen3.5-9B/s1/0123456789ab, until 2026-11-12T00:00:00Z."]), + "Starting both Macs' parts again as cluster members…"), ] for (label, result, restart) in cases { let recorder = Recorder() @@ -682,6 +687,27 @@ import Darwin } } + /// After the Test stage: the approval request's line is said, and when the coordinator then serves no approval + /// (the request was not taken, failed, or its row does not match) nothing stopped, so the setup ends at once. + static func leaderSaysTheApprovalRequestAndWaitsForNothingElse() { + let line = ClusterOnboardingReady.approvalRequestNotice + ": not taken by this coordinator (HTTP 404)." + let recorder = Recorder() + let run = TerminalRun(operations(recorder, pairEvents: [.searching, .waitingAsLeader, .connected, + .code("123456", peer: ["Apple M3 Ultra, 256 GB"]), .peerDecided(true)], + pairResult: .paired(role: .leader, peerName: "Apple M3 Ultra, 256 GB"), registerResult: .success([line]))) + expect(run.waitFor("Does the other Mac show 123 456? Press y if it does, n if it does not."), "request only: the code question") + run.type("y") + expect(run.waitFor("Choose a model [1-2, enter = 1]: "), "request only: the model choice") + run.type("\r") + _ = run.finish() + let text = run.text + expect(text.contains(" " + line), "request only: the request line: \(text)") + expect(!text.contains("Starting both Macs' parts again"), "request only: no restart line") + expect(recorder.all.last == "register", "request only: nothing is awaited after the request: \(recorder.all)") + let said = text.range(of: line)?.lowerBound, done = text.range(of: "Done.")?.lowerBound + expect(said != nil && done != nil && said! < done!, "request only: Done comes after the request line") + } + /// DEVELOPER ONLY (`DARKBLOOM_CLUSTER_FORCE_MODE` in a debug build): a forced mode is said loudly, in one line, on /// the setup screen right under the planning line; without the setting the screen has no such line. static func forcedModeNoticeOnTheSetupScreen() { diff --git a/provider-swift/Tests/ProviderCoreTests/Fixtures/coordinator-wire/owner_cluster_approval_vector.json b/provider-swift/Tests/ProviderCoreTests/Fixtures/coordinator-wire/owner_cluster_approval_vector.json new file mode 100644 index 0000000000..73618971c7 --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Fixtures/coordinator-wire/owner_cluster_approval_vector.json @@ -0,0 +1,9 @@ +{ + "method": "POST", + "path": "/v1/cluster/owner-approvals", + "authorization": "Bearer ", + "request": "{\"provider_version\":\"0.10.5-dev.branch.16\",\"model\":\"glm-5.3-flash\",\"artifact_sha256\":\"3aae613ff188bb0f72e880774a84e4d8e9943ab20c929d8a302af9c57b97d5ac\",\"schedule\":1}", + "status": 201, + "response": "{\"approval\":{\"id\":\"owner/account-one/glm-5.3-flash/s1/0123456789ab\",\"model\":\"glm-5.3-flash\",\"generation\":1,\"artifact_sha256\":\"3aae613ff188bb0f72e880774a84e4d8e9943ab20c929d8a302af9c57b97d5ac\",\"schedule\":1,\"maximum_transport_frame\":1048616,\"maximum_plaintext\":1048576,\"maximum_records\":1048576,\"maximum_cumulative_plaintext\":4294967296,\"allowed_numerics_classes\":[],\"minimum_members\":2,\"maximum_members\":2,\"minimum_member_usable_bytes\":1,\"not_after\":\"2027-01-29T00:00:00Z\"},\"policy_sha256\":\"1683c2acd7e89589957a99707e85801a903e328b566cdc1e8185761599d0b148\"}\n", + "canonical_hex": "6461726b626c6f6f6d2f636f6f7264696e61746f722d636c75737465722d6d6f64656c2d617070726f76616c2f7631000000002f6f776e65722f6163636f756e742d6f6e652f676c6d2d352e332d666c6173682f73312f3031323334353637383961620000000d676c6d2d352e332d666c61736800000000000000013aae613ff188bb0f72e880774a84e4d8e9943ab20c929d8a302af9c57b97d5ac01010100100028001000000000000000100000000000010000000018ff1465004100000202000000000000000100000009502f90000000001bf08eb00000000014f46b040000000000" +} diff --git a/provider-swift/Tests/ProviderCoreTests/Helpers/MockCoordinator.swift b/provider-swift/Tests/ProviderCoreTests/Helpers/MockCoordinator.swift index 559cdbaa0e..9599102b31 100644 --- a/provider-swift/Tests/ProviderCoreTests/Helpers/MockCoordinator.swift +++ b/provider-swift/Tests/ProviderCoreTests/Helpers/MockCoordinator.swift @@ -64,6 +64,13 @@ public struct CapturedMessages: Sendable { public var enrollmentAuthorizations: [String] = [] /// The query of each `GET /v1/cluster/approvals`, in arrival order. public var clusterApprovalQueries: [String] = [] + /// The body and `Authorization` header of each `POST /v1/cluster/owner-approvals`, in arrival order. + public var clusterApprovalPosts: [Data] = [] + public var clusterApprovalAuthorizations: [String] = [] + /// The `Authorization` header of each `GET /v1/cluster/owner-approvals`, in arrival order. + public var ownerApprovalAuthorizations: [String] = [] + /// The id of each `DELETE /v1/cluster/owner-approvals/{id}`, in arrival order. + public var ownerApprovalDeletes: [String] = [] public init() {} } @@ -195,6 +202,12 @@ public final class MockCoordinator: @unchecked Sendable { private var acknowledgedReadiness = Set() /// `GET /v1/cluster/approvals`: the status and exact body bytes answered; nil answers 404 (pair control off). private var clusterApprovals: (status: Int, body: Data, location: String?)? + /// `POST /v1/cluster/owner-approvals` and `GET /v1/cluster/owner-approvals`: the same; nil answers 404 (owner + /// approvals off). + private var clusterApprovalRequests: (status: Int, body: Data, location: String?)? + private var ownerApprovals: (status: Int, body: Data, location: String?)? + /// `DELETE /v1/cluster/owner-approvals/{id}`: the status answered. + private var ownerApprovalDeleteStatus = 204 private var activeOutbound: WebSocketOutboundWriter? private var bound: BoundServer? @@ -258,6 +271,43 @@ public final class MockCoordinator: @unchecked Sendable { lock.withLock { clusterApprovals = body.map { (status, $0, location) } } } + /// What `POST /v1/cluster/owner-approvals` answers from now on; nil answers 404, as a coordinator without owner + /// approvals does. `location` adds a `Location` header (a redirect the provider must not follow). + public func setClusterApprovalRequests(status: Int = 201, body: Data?, location: String? = nil) { + lock.withLock { clusterApprovalRequests = body.map { (status, $0, location) } } + } + + /// What `GET /v1/cluster/owner-approvals` answers from now on; nil answers 404. + public func setOwnerApprovals(status: Int = 200, body: Data?, location: String? = nil) { + lock.withLock { ownerApprovals = body.map { (status, $0, location) } } + } + + /// What `DELETE /v1/cluster/owner-approvals/{id}` answers from now on (204 by default). + public func setOwnerApprovalDeleteStatus(_ status: Int) { + lock.withLock { ownerApprovalDeleteStatus = status } + } + + /// The coordinator's strict reading of a `POST /v1/cluster/owner-approvals` body: exactly `provider_version`, + /// `model`, `artifact_sha256` (64 lowercase hex) and `schedule` (1 or 2), each once; anything else is its 400. + static func isOwnerApprovalRequest(_ body: Data) -> Bool { + guard let fields = try? JSONSerialization.jsonObject(with: body) as? [String: Any], + Set(fields.keys) == ["provider_version", "model", "artifact_sha256", "schedule"], + let version = fields["provider_version"] as? String, !version.isEmpty, + let model = fields["model"] as? String, !model.isEmpty, + let artifact = fields["artifact_sha256"] as? String, artifact.count == 64, + artifact.allSatisfy({ "0123456789abcdef".contains($0) }), + let schedule = fields["schedule"] as? Int, [1, 2].contains(schedule) else { return false } + return true + } + + /// The answer set for a cluster approval route: its status, exact body bytes and `Location`; nil is a 404. + private static func answer(_ answer: (status: Int, body: Data, location: String?)?) -> Response { + guard let answer else { return makeJSONResponse(body: ["error": "not found"], status: .notFound) } + var headers: HTTPFields = [.contentType: "application/json"] + if let location = answer.location { headers[.location] = location } + return Response(status: .init(code: answer.status), headers: headers, body: .init(byteBuffer: ByteBuffer(bytes: answer.body))) + } + /// Return a snapshot of all messages captured so far. Each call clones the /// underlying state, so the returned value is safe to inspect without /// holding any locks. @@ -556,11 +606,45 @@ public final class MockCoordinator: @unchecked Sendable { self.captured.clusterApprovalQueries.append(query) return self.clusterApprovals } - guard let answer else { return MockCoordinator.makeJSONResponse(body: ["error": "not found"], status: .notFound) } - var headers: HTTPFields = [.contentType: "application/json"] - if let location = answer.location { headers[.location] = location } - return Response(status: .init(code: answer.status), headers: headers, - body: .init(byteBuffer: ByteBuffer(bytes: answer.body))) + return MockCoordinator.answer(answer) + } + + // ----- HTTP: /v1/cluster/owner-approvals ----- + router.post("/v1/cluster/owner-approvals") { [weak self] request, _ -> Response in + guard let self else { + return MockCoordinator.makeJSONResponse(body: ["error": "mock dead"], status: .internalServerError) + } + let body = Data(try await request.body.collect(upTo: 64 * 1024).readableBytesView) + let answer = self.lock.withLock { () -> (status: Int, body: Data, location: String?)? in + self.captured.clusterApprovalPosts.append(body) + self.captured.clusterApprovalAuthorizations.append(request.headers[.authorization] ?? "") + return self.clusterApprovalRequests + } + guard answer == nil || MockCoordinator.isOwnerApprovalRequest(body) else { + return MockCoordinator.makeJSONResponse(body: ["error": "invalid request"], status: .badRequest) + } + return MockCoordinator.answer(answer) + } + router.delete("/v1/cluster/owner-approvals/**") { [weak self] request, _ -> Response in + guard let self else { + return MockCoordinator.makeJSONResponse(body: ["error": "mock dead"], status: .internalServerError) + } + let prefix = "/v1/cluster/owner-approvals/" + let path = request.uri.path.removingPercentEncoding ?? request.uri.path + let status = self.lock.withLock { () -> Int in + self.captured.ownerApprovalDeletes.append(String(path.dropFirst(prefix.count))) + return self.ownerApprovalDeleteStatus + } + return Response(status: .init(code: status)) + } + router.get("/v1/cluster/owner-approvals") { [weak self] request, _ -> Response in + guard let self else { + return MockCoordinator.makeJSONResponse(body: ["error": "mock dead"], status: .internalServerError) + } + return MockCoordinator.answer(self.lock.withLock { () -> (status: Int, body: Data, location: String?)? in + self.captured.ownerApprovalAuthorizations.append(request.headers[.authorization] ?? "") + return self.ownerApprovals + }) } // ----- HTTP: /v1/releases/latest ----- diff --git a/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalRequestTests.swift b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalRequestTests.swift new file mode 100644 index 0000000000..b93fe6079e --- /dev/null +++ b/provider-swift/Tests/ProviderCoreTests/Inference/Distributed/ClusterApproval/ClusterApprovalRequestTests.swift @@ -0,0 +1,282 @@ +import Foundation +import Testing +@testable import ProviderCore + +/// The owner approvals (`/v1/cluster/owner-approvals`) against a real local HTTP server that answers as the +/// coordinator does, and against the vector the coordinator's tests pin with the same bytes: what the leader sends, +/// with which credential, when it asks or renews, that every answer but a verified 200 or 201 is one line that stops +/// nothing, and that the account's own approvals join the public list only as a whole answer. +@Suite("Cluster approval request", .serialized) +struct ClusterApprovalRequestTests { + static let ownID = "owner/acct/fixture/qwen/s1/0123456789ab" + + private func coordinator() async throws -> (MockCoordinator, String) { + let mock = MockCoordinator() + let base = try await mock.start() + return (mock, base.mockProviderWebSocketURL()) + } + + /// The shared vector: `Fixtures/coordinator-wire/owner_cluster_approval_vector.json`, byte for byte the coordinator's + /// `coordinator/tests/api/testdata/owner_cluster_approval_vector.json`. + private func vector() throws -> [String: Any] { + let url = try #require(Bundle.module.url(forResource: "owner_cluster_approval_vector", withExtension: "json", + subdirectory: "Fixtures/coordinator-wire")) + return try #require(try JSONSerialization.jsonObject(with: Data(contentsOf: url)) as? [String: Any]) + } + + private func entry(_ approval: ClusterRuntimeApproval, policy: String? = nil) throws -> [String: Any] { + let derived = ClusterConfigurationCodec.sha256(try approval.canonicalPolicy()) + return ["approval": try JSONSerialization.jsonObject(with: JSONEncoder().encode(approval)), "policy_sha256": policy ?? derived] + } + + private func owned(_ approvals: [ClusterRuntimeApproval]) throws -> Data { + try JSONSerialization.data(withJSONObject: ["approvals": try approvals.map { try entry($0) }]) + } + + private func reply(_ approval: ClusterRuntimeApproval) throws -> Data { + try JSONSerialization.data(withJSONObject: try entry(approval)) + } + + private func installApp(_ mac: ClusterApprovalMacs.Mac, version: String) throws { + let plist = try PropertyListSerialization.data(fromPropertyList: ["CFBundleShortVersionString": version], + format: .xml, options: 0) + try plist.write(to: mac.home.appendingPathComponent("app/Contents/Info.plist")) + } + + private func ask(_ url: String, token: String? = "t") async -> ClusterApprovalRequest.Outcome { + await ClusterApprovalRequest.request(coordinatorURL: url, token: token, providerVersion: "0.10.5-dev.branch.16", + model: "glm-5.3-flash", artifact: String(repeating: "3a", count: 32), schedule: 1) + } + + // MARK: - The shared vector + + @Test func theProviderSendsAndReadsTheSharedVectorByteForByte() async throws { + let vector = try vector() + #expect(vector["method"] as? String == "POST") + #expect(vector["path"] as? String == ClusterApprovalRequest.path) + let request = try #require(vector["request"] as? String), response = try #require(vector["response"] as? String) + let fields = try #require(try JSONSerialization.jsonObject(with: Data(request.utf8)) as? [String: Any]) + let version = try #require(fields["provider_version"] as? String), model = try #require(fields["model"] as? String) + let artifact = try #require(fields["artifact_sha256"] as? String), schedule = try #require(fields["schedule"] as? Int) + #expect(try ClusterApprovalRequest.body(providerVersion: version, model: model, artifact: artifact, schedule: UInt8(schedule)) + == Data(request.utf8)) + // The reply: one owner approval whose canonical bytes and policy_sha256 are the vector's. + let approval = try ClusterApprovalFetch.decodeOwnedEntry(Data(response.utf8)) + #expect(approval.id == "owner/account-one/glm-5.3-flash/s1/0123456789ab") + #expect(approval.isModelApproval && approval.minimumMembers == 2 && approval.maximumMembers == 2) + let canonical = try approval.canonicalPolicy() + #expect(canonical.map { String(format: "%02x", $0) }.joined() == vector["canonical_hex"] as? String) + #expect(ClusterConfigurationCodec.sha256(canonical) == "1683c2acd7e89589957a99707e85801a903e328b566cdc1e8185761599d0b148") + + // Over HTTP: the same bytes leave the provider, with its credential, and the vector's reply registers. + let (mock, url) = try await coordinator() + mock.setClusterApprovalRequests(status: try #require(vector["status"] as? Int), body: Data(response.utf8)) + #expect(await ClusterApprovalRequest.request(coordinatorURL: url, token: "provider-token", providerVersion: version, + model: model, artifact: artifact, schedule: UInt8(schedule)) + == .registered(approval.id)) + let sent = mock.snapshot() + #expect(sent.clusterApprovalPosts == [Data(request.utf8)]) + #expect(sent.clusterApprovalAuthorizations == ["Bearer provider-token"]) + await mock.shutdown() + } + + // MARK: - The request + + @Test func aSetupWithoutAnApprovalAsksWithItsInstalledVersionModelArtifactAndSchedule() async throws { + let (mock, url) = try await coordinator() + let macs = try ClusterApprovalMacs(coordinatorURL: url) + try installApp(macs.leader, version: "0.10.5-dev.branch.42") + mock.setClusterApprovalRequests(status: 201, body: try reply(macs.modelApproval(id: Self.ownID))) + let saved = try macs.saved(macs.leader) + #expect(ClusterApprovalRequest.need(saved, now: Date().timeIntervalSince1970) == .request) + let outcome = await ClusterApprovalRequest.ensure(saved, providerConfiguration: macs.leader.provider, + now: Date().timeIntervalSince1970, token: "account-token") + #expect(outcome == .registered(Self.ownID)) + #expect(outcome?.line == "Cluster approval request: the coordinator holds approval \(Self.ownID) for this pair.") + // An answer settles the need: the service does not ask for it again in this run. + #expect(outcome?.retries == false) + let sent = mock.snapshot() + #expect(sent.clusterApprovalAuthorizations == ["Bearer account-token"]) + #expect(sent.clusterApprovalPosts.map { String(decoding: $0, as: UTF8.self) } == [#"{"provider_version":"0.10.5-dev.branch.42","model":"fixture/qwen","artifact_sha256":""# + + ClusterApprovalMacs.hash("b") + #"","schedule":1}"#]) + await mock.shutdown() + } + + @Test func anOwnerApprovalNearItsEndIsDeletedThenAskedForAgain() async throws { + let (mock, url) = try await coordinator() + let macs = try ClusterApprovalMacs(coordinatorURL: url) + try installApp(macs.leader, version: "0.10.5-dev.branch.42") + let facts = try macs.facts() + #expect(macs.sync(.approvals([macs.modelApproval(endsIn: 3 * 86_400, id: Self.ownID)]), leaderFacts: facts, followerFacts: facts).changed) + let saved = try macs.saved(macs.leader), now = Date().timeIntervalSince1970 + #expect(ClusterApprovalRequest.need(saved, now: now) == .renew(Self.ownID)) + // More than a week left, or an operator's approval: nothing to ask, nothing sent. + #expect(ClusterApprovalRequest.need(saved, now: now - 5 * 86_400) == .nothing) + let renewed = macs.modelApproval(endsIn: 90 * 86_400, id: "owner/acct/fixture/qwen/s1/ba9876543210") + mock.setClusterApprovalRequests(status: 201, body: try reply(renewed)) + #expect(await ClusterApprovalRequest.ensure(saved, providerConfiguration: macs.leader.provider, now: now, token: "t") + == .registered(renewed.id)) + #expect(mock.snapshot().ownerApprovalDeletes == [Self.ownID]) + #expect(mock.snapshot().clusterApprovalPosts.count == 1) + // A delete the coordinator refuses stops the renewal before the request; one it no longer holds does not. + mock.setOwnerApprovalDeleteStatus(500) + #expect(await ClusterApprovalRequest.ensure(saved, providerConfiguration: macs.leader.provider, now: now, token: "t") + == .failed("the renewal could not delete approval \(Self.ownID): HTTP 500")) + #expect(mock.snapshot().clusterApprovalPosts.count == 1) + mock.setOwnerApprovalDeleteStatus(404) + #expect(await ClusterApprovalRequest.ensure(saved, providerConfiguration: macs.leader.provider, now: now, token: "t") + == .registered(renewed.id)) + await mock.shutdown() + } + + @Test func anOperatorsApprovalIsNeverRenewedHere() throws { + let macs = try ClusterApprovalMacs(coordinatorURL: "ws://127.0.0.1:9/ws/provider") + let facts = try macs.facts() + #expect(macs.sync(.approvals([macs.modelApproval(endsIn: 3 * 86_400)]), leaderFacts: facts, followerFacts: facts).changed) + #expect(ClusterApprovalRequest.need(try macs.saved(macs.leader), now: Date().timeIntervalSince1970) == .nothing) + } + + @Test func productionStagingAndASettingOffAreNotTaken() async throws { + let (mock, url) = try await coordinator() + // No route at all (a coordinator without owner approvals) is a 404. + #expect(await ask(url) == .notTaken(404)) + mock.setClusterApprovalRequests(status: 403, body: Data(#"{"error":"forbidden"}"#.utf8)) + let refused = await ask(url) + #expect(refused == .notTaken(403)) + #expect(refused.line == "Cluster approval request: not taken by this coordinator (HTTP 403).") + #expect(!refused.retries) + await mock.shutdown() + } + + @Test func everyOtherAnswerIsOneLine() async throws { + let (mock, url) = try await coordinator() + let cases: [(Int, String?, Data, ClusterApprovalRequest.Outcome, Bool)] = [ + (409, nil, Data("{}".utf8), .refused(409), false), + (500, nil, Data("{}".utf8), .failed("HTTP 500"), true), + (302, "https://elsewhere.invalid/v1/cluster/owner-approvals", Data(), .failed("HTTP 302"), true), + (201, nil, Data("created".utf8), .failed("the answer is not an owner approval"), true), + ] + for (status, location, body, expected, retries) in cases { + mock.setClusterApprovalRequests(status: status, body: body, location: location) + let outcome = await ask(url) + #expect(outcome == expected, "HTTP \(status)") + #expect(outcome.retries == retries, "HTTP \(status)") + } + // The redirect was not followed: only this server's route saw requests. + #expect(mock.snapshot().clusterApprovalPosts.count == cases.count) + // A body the coordinator does not read is its 400. + mock.setClusterApprovalRequests(status: 201, body: Data("{}".utf8)) + let invalid = await ClusterApprovalRequest.request(coordinatorURL: url, token: "t", providerVersion: "0.10.5-dev.branch.1", + model: "glm-5.3-flash", artifact: "ABC", schedule: 1) + #expect(invalid == .refused(400)) + #expect(invalid.line == "Cluster approval request: refused by the coordinator (HTTP 400).") + await mock.shutdown() + } + + @Test func nothingIsSentWithoutACredentialAVersionOrAnHTTPSCoordinator() async throws { + let (mock, url) = try await coordinator() + mock.setClusterApprovalRequests(status: 201, body: Data("{}".utf8)) + for token in [nil, ""] as [String?] { + let outcome = await ask(url, token: token) + #expect(outcome == .notSent("this Mac is not linked to an account")) + #expect(outcome.line == "Cluster approval request: not sent (this Mac is not linked to an account).") + } + #expect(await ask("ws://coordinator.example/ws/provider") == .notSent("the coordinator URL is not HTTPS")) + // No Info.plist beside the setup's helpers: no version, so no request. + let macs = try ClusterApprovalMacs(coordinatorURL: url) + let saved = try macs.saved(macs.leader), now = Date().timeIntervalSince1970 + #expect(await ClusterApprovalRequest.ensure(saved, providerConfiguration: macs.leader.provider, now: now, token: "t") + == .notSent("the installed app's version could not be read")) + // A provider configuration that cannot be read (here a folder) names no coordinator. + #expect(await ClusterApprovalRequest.ensure(saved, providerConfiguration: macs.root, now: now, token: "t") + == .notSent("the provider configuration names no coordinator")) + #expect(mock.snapshot().clusterApprovalPosts.isEmpty) + await mock.shutdown() + } + + @Test func noAnswerFailsInOneLine() async throws { + // Nothing listens on port 9 of this Mac. + guard case .failed(let reason) = await ask("ws://127.0.0.1:9/ws/provider") else { + Issue.record("no answer was not a failure"); return + } + #expect(reason.hasPrefix("no answer: "), "\(reason)") + } + + // MARK: - The account's own approvals + + @Test func theAccountsOwnApprovalsJoinThePublicList() async throws { + let (mock, url) = try await coordinator() + let macs = try ClusterApprovalMacs(coordinatorURL: url) + let operatorRow = macs.approval(), own = macs.modelApproval(id: Self.ownID) + mock.setClusterApprovals(body: try ClusterApprovalMacs.body([operatorRow])) + mock.setOwnerApprovals(body: try owned([own])) + #expect(await ClusterApprovalFetch.fetch(providerConfiguration: macs.leader.provider, token: "account-token") + == .approvals([operatorRow, own])) + #expect(mock.snapshot().ownerApprovalAuthorizations == ["Bearer account-token"]) + // Without a credential only the public list is asked. + #expect(await ClusterApprovalFetch.fetch(providerConfiguration: macs.leader.provider, token: nil) == .approvals([operatorRow])) + #expect(mock.snapshot().ownerApprovalAuthorizations.count == 1) + // A public 404 with own approvals: the own approvals. + mock.setClusterApprovals(body: nil) + #expect(await ClusterApprovalFetch.fetch(providerConfiguration: macs.leader.provider, token: "t") == .approvals([own])) + await mock.shutdown() + } + + @Test func anAccountWithoutOwnApprovalsLeavesThePublicAnswerAsItIs() async throws { + let (mock, url) = try await coordinator() + let macs = try ClusterApprovalMacs(coordinatorURL: url) + let operatorRow = macs.approval() + for status in [401, 403, 404] { + mock.setOwnerApprovals(status: status, body: Data("{}".utf8)) + mock.setClusterApprovals(body: try ClusterApprovalMacs.body([operatorRow])) + #expect(await ClusterApprovalFetch.fetch(providerConfiguration: macs.leader.provider, token: "t") == .approvals([operatorRow])) + mock.setClusterApprovals(body: nil) + #expect(await ClusterApprovalFetch.fetch(providerConfiguration: macs.leader.provider, token: "t") == .notOffered) + } + await mock.shutdown() + } + + @Test func aFailedHalfIsTheAnswer() async throws { + let (mock, url) = try await coordinator() + let macs = try ClusterApprovalMacs(coordinatorURL: url) + mock.setClusterApprovals(body: try ClusterApprovalMacs.body([macs.approval()])) + mock.setOwnerApprovals(status: 500, body: Data("{}".utf8)) + #expect(await ClusterApprovalFetch.fetch(providerConfiguration: macs.leader.provider, token: "t") == .unavailable("HTTP 500")) + mock.setOwnerApprovals(body: try owned([macs.modelApproval()])) + mock.setClusterApprovals(status: 502, body: Data("{}".utf8)) + #expect(await ClusterApprovalFetch.fetch(providerConfiguration: macs.leader.provider, token: "t") == .unavailable("HTTP 502")) + // The combination itself, for the outcomes no server is needed for. + #expect(ClusterApprovalFetch.combined(.notOffered, owned: .unreachable("down")) == .unreachable("down")) + #expect(ClusterApprovalFetch.combined(.unreachable("down"), owned: .approvals([])) == .unreachable("down")) + await mock.shutdown() + } + + @Test func anOwnApprovalsAnswerIsReadStrictly() throws { + let macs = try ClusterApprovalMacs(coordinatorURL: "ws://127.0.0.1:9/ws/provider") + let own = macs.modelApproval(id: Self.ownID) + #expect(try ClusterApprovalFetch.decodeOwned(try owned([own])) == [own]) + var extra = try entry(own); extra["generation"] = 1 + var unknown = try entry(own) + var approval = unknown["approval"] as! [String: Any]; approval["granted"] = true; unknown["approval"] = approval + let refused: [(String, Any)] = [ + ("another top-level field", ["approvals": [try entry(own)], "next": ""] as [String: Any]), + ("an extra entry field", ["approvals": [extra]] as [String: Any]), + ("an unknown approval field", ["approvals": [unknown]] as [String: Any]), + ("a policy_sha256 this Mac does not derive", ["approvals": [try entry(own, policy: ClusterApprovalMacs.hash("0"))]] as [String: Any]), + ("too many entries", ["approvals": Array(repeating: try entry(own), count: ClusterApprovalFetch.maximumApprovals + 1)] as [String: Any]), + ("not a list", ["approvals": "none"] as [String: Any]), + ] + for (name, object) in refused { + #expect(throws: ClusterConfigurationError.self, "\(name) was taken") { + try ClusterApprovalFetch.decodeOwned(try JSONSerialization.data(withJSONObject: object)) + } + } + // A registration's answer is one entry, read the same way. + #expect(throws: ClusterConfigurationError.self) { + try ClusterApprovalFetch.decodeOwnedEntry(try JSONSerialization.data(withJSONObject: try entry(own, policy: ClusterApprovalMacs.hash("0")))) + } + #expect(throws: ClusterConfigurationError.self) { + try ClusterApprovalFetch.decodeOwnedEntry(try owned([own])) + } + } +}