diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e72e069..df35c5f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -104,9 +104,22 @@ jobs: - name: medium lane if: ${{ !cancelled() }} run: scripts/ci.sh medium + # The real learner-server, through one throwaway test device. The minter's key goes + # to these two steps only; pull requests from forks get no secrets and skip by name. + - name: prod-device (a throwaway test device on the real server) + if: ${{ !cancelled() }} + env: + LEARNER_CI_MINT_KEY: ${{ secrets.LEARNER_CI_MINT_KEY }} + LEARNER_FORK_PR: ${{ github.event.pull_request.head.repo.fork == true }} + run: scripts/ci.sh prod-device - name: heavy lane if: ${{ !cancelled() }} run: scripts/ci.sh heavy + - name: prod-revoke (the test device and all it wrote, removed) + if: ${{ always() }} + env: + LEARNER_CI_MINT_KEY: ${{ secrets.LEARNER_CI_MINT_KEY }} + run: scripts/ci.sh prod-revoke - name: updater (automatic updates' LaunchAgent loads) if: ${{ !cancelled() }} run: scripts/ci.sh updater diff --git a/Tests/HeavyTests/ProductionServerTests.swift b/Tests/HeavyTests/ProductionServerTests.swift new file mode 100644 index 0000000..437afd4 --- /dev/null +++ b/Tests/HeavyTests/ProductionServerTests.swift @@ -0,0 +1,127 @@ +import Foundation +import Testing +@testable import LearnerDesktop +import TestSupport + +// The owner's REAL learner-server, through one throwaway test device per CI run (scripts/ci.sh +// prod-device: createTestDevice + seedMasteryGain with the CI minter's key; prod-revoke +// removes the device and everything it wrote, and it dies at its TTL regardless). The app's +// own code pairs from the device's pairing code, heartbeats, and runs the mastery feed +// against production. The device key is kept in memory and never printed or asserted on: a +// failed #expect prints its operands, and these logs are public. +// +// GitHub runner only, and only when prod-device made a device (no secret on forks). +private struct ProdDevice: CustomStringConvertible { + let code: String, clientId: String, runId: String, conceptId: String, completedAt: Date, apiUrl: String + /// Never the code (it carries the device key): a failed #expect prints its operands. + var description: String { "ProdDevice(\(clientId), run \(runId))" } + + static let loaded: ProdDevice? = { + guard TestEnvironment.isRunner, Live.env["GITHUB_ACTIONS"] == "true", + let path = Live.env["LEARNER_PROD_DEVICE_FILE"], let data = FileManager.default.contents(atPath: path), + let o = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any], + let code = o["pairingCode"] as? String, let id = o["clientId"] as? String, + let run = o["runId"] as? String, let concept = o["conceptId"] as? String, + let completed = (o["completedAt"] as? String).flatMap(ProdDevice.parseDate), + let api = o["apiUrl"] as? String else { return nil } + return ProdDevice(code: code, clientId: id, runId: run, conceptId: concept, completedAt: completed, apiUrl: api) + }() + + static func parseDate(_ s: String) -> Date? { + let f = ISO8601DateFormatter() + f.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + return f.date(from: s) ?? ISO8601DateFormatter().date(from: s) + } +} + +@Suite("Production learner-server (a throwaway test device)", .tags(.heavy, .outbox), .quietLog, .serialized, + .timeLimit(.minutes(3)), + .enabled(if: Live.heavy, "heavy lane only (LEARNER_HEAVY=1)"), + .enabled(if: ProdDevice.loaded != nil, "no production test device (GitHub runner with LEARNER_CI_MINT_KEY only)")) +struct ProductionServerTests { + /// Paired as the app pairs (from the code, its health and identity checked), into scratch + /// defaults; the key in memory only. + func paired() throws -> (rpc: LearnerRPC, defaults: UserDefaults, link: PairingLink, dir: TempDir) { + let device = try #require(ProdDevice.loaded) + let defaults = ScratchDefaults("prod-device") + let key = Locked(nil) + let result = Pairing.importCode(device.code, defaults: defaults, transport: URLSessionTransport(), + store: { _, k in key.value = k; return .success(()) }) + guard case .success(let p) = result else { throw ToolError("the pairing code did not import: \(result)") } + let (pairedId, deviceId) = (p.clientId, device.clientId) + #expect(pairedId == deviceId) + let pinned = try #require(Pairing.pinned(defaults)) + // Production itself, not the runner's own local learner-server (which would pass the + // same identity check): the code pins the URL prod-device created the device on. + let (pinnedURL, prodURL) = (Pairing.normalized(pinned.apiUrl), Pairing.normalized(device.apiUrl)) + #expect(pinnedURL == prodURL) + FileHandle.standardError.write(Data("PRODUCTION: paired with \(URL(string: pinnedURL)?.host ?? pinnedURL) as \(deviceId)\n".utf8)) + let dir = TempDir("prod-device") + let rpc = LearnerRPC(baseURL: pinned.apiUrl, clientId: pinned.clientId, key: { _ in key.value }) + return (rpc, defaults, PairingLink(path: dir.file("endpoints.json")), dir) + } + + @Test func theDevicePairsHeartbeatsAndIsConfinedToItself() throws { + let (rpc, _, link, dir) = try paired() + _ = dir // keeps the scratch folder (endpoints.json) for the whole test + let first = link.refresh(rpc: rpc) + try #require(first.kind == .ok, "getPairingEndpoints: \(first.describe) \(first.message ?? "")") + let e = try #require(link.held) + #expect(e.topology == "remote", "production is another machine") + #expect(link.moved == nil, "production advertises \(e.apiBase), the code pinned \(rpc.baseURL)") + + let beat = TrayAppManager.heartbeat(AppStatus(capture: .recording), appVersion: "ci-prod", screenpipeVersion: nil, capturePhase: nil, + lastSentAt: nil, lastExport: nil, outboxStatus: "ci-prod", + pairing: link.report(apiUrlInUse: rpc.baseURL, services: [("screenpipe", "http://localhost:3030")]), + clientId: rpc.clientId) + let reply = rpc.call("recordAppHeartbeat", beat) + try #require(reply.kind == .ok, "heartbeat: \(reply.describe) \(reply.message ?? "")") + link.refresh(rpc: rpc) + #expect(link.held?.pairingState == "ok", "pairing state \(link.held?.pairingState ?? "?")") + + // Confined: another device's endpoints, and a (read-only) RPC outside a test device's + // allowance. (getBaselineStatus is inside it: the feed calls it.) + #expect(rpc.call("getPairingEndpoints", ["clientId": "not-this-device"]).status == 403) + let outside = rpc.call("getMasteryProgress", [:]) + #expect(outside.status == 403, "a test device's key reached getMasteryProgress: HTTP \(outside.status)") + } + + @Test func theSeededGainIsAnnouncedAndItsFeedbackRecordedOnce() throws { + let device = try #require(ProdDevice.loaded) + let (rpc, defaults, _, dir) = try paired() + // As if installed just before the gain was seeded: however long the lanes before this + // took, the feed's first look reaches it (it keeps gains completed after install). + defaults.set(device.completedAt.addingTimeInterval(-60), forKey: MasteryFeed.Key.installedAt) + defaults.set(device.completedAt.addingTimeInterval(-60), forKey: MasteryFeed.Key.since) + let feed = MasteryFeed(rpc: rpc, defaults: defaults, jobName: "prod-device-\(UUID().uuidString.prefix(8))", + stateDir: dir.file("jobs"), sendFeedbackAtOnce: false) + let outcome = feed.runOnce() + if case .ok = outcome {} else { Issue.record("the feed run did not succeed against production: \(outcome)") } + #expect(feed.pending.map(\.runId) == [device.runId], "exactly the seeded gain") + #expect(feed.pending.first?.conceptId == device.conceptId) + + // The server's idempotence (not the app's click path, which the local harness covers): + // opened twice, one row. + let first = rpc.call("recordNotificationFeedback", ["runId": device.runId, "action": "opened"]) + let r1 = try #require(first.body as? [String: Any], "feedback: \(first.describe)") + #expect(r1["recorded"] as? Bool == true) + let at = try #require(r1["at"] as? String) + let again = rpc.call("recordNotificationFeedback", ["runId": device.runId, "action": "opened"]).body as? [String: Any] + #expect(again?["at"] as? String == at, "a replay made a second row") + } + + /// The confinement that matters: a test device cannot read the owner's mastery. Asked for + /// everything since 1970, the server answers only this device's seeded run. Counts only + /// in any message: a failure must not print the owner's rows into a public log. + @Test func theDeviceCannotSeeTheOwnersMastery() throws { + let device = try #require(ProdDevice.loaded) + let (rpc, _, _, dir) = try paired() + _ = dir + let reply = rpc.call("getMasteryNotifications", ["since": "1970-01-01T00:00:00.000Z", "limit": 50]) + try #require(reply.kind == .ok, "getMasteryNotifications: HTTP \(reply.status)") + let rows = (reply.body as? [String: Any])?["notifications"] as? [[String: Any]] ?? [] + let foreign = rows.filter { ($0["runId"] as? String) != device.runId }.count + #expect(foreign == 0, "\(foreign) of \(rows.count) notification(s) since 1970 are not this test device's seed") + #expect(rows.count == 1, "\(rows.count) notification(s) since 1970; want exactly the seed") + } +} diff --git a/menu-bar-app/Pairing.swift b/menu-bar-app/Pairing.swift index 95b0091..25625fc 100644 --- a/menu-bar-app/Pairing.swift +++ b/menu-bar-app/Pairing.swift @@ -26,10 +26,12 @@ enum Pairing { ?? NSHomeDirectory() + "/Library/Application Support/Learner/desktop-pairing.json" } - struct Payload: Equatable { + struct Payload: Equatable, CustomStringConvertible { let apiUrl: String let clientId: String let apiKey: String + /// Never the key: payloads end up in logs and in test failure output. + var description: String { "Payload(apiUrl: \(apiUrl), clientId: \(clientId), apiKey: <\(apiKey.count) characters>)" } } /// The contract's DesktopClientId. diff --git a/scripts/ci.sh b/scripts/ci.sh index fe8dd89..be1be2b 100755 --- a/scripts/ci.sh +++ b/scripts/ci.sh @@ -13,6 +13,8 @@ # mic-e2e speech played into the virtual mic is heard by the installed app; the # default input is switched and the app follows it and hears again # light/medium/heavy scripts/test.sh, with LEARNER_TEST_ENV=runner (owner-only suites skip, by name) +# prod-device a throwaway test device on the owner's REAL learner-server, with a seeded gain +# prod-revoke that device and everything it wrote, removed (always runs) # updater scripts/install-updater.sh: the automatic updater's LaunchAgent loads # uninstall scripts/uninstall-app.sh with PURGE_DATA=1: nothing may be left behind, # the updater included @@ -269,9 +271,12 @@ speech() { # them is on; the owner's Mac has Siri on ("Assistant Enabled"). Both, for the runner. defaults write com.apple.assistant.support "Assistant Enabled" -bool true defaults write com.apple.assistant.support "Dictation Enabled" -bool true - killall assistantd corespeechd 2>/dev/null || true # they reread the settings on relaunch + killall assistantd 2>/dev/null || true # it rereads the settings on relaunch defaults read com.apple.assistant.support | grep -E '"(Assistant|Dictation) Enabled"' | sed 's/^ */ /' - ensure_say + # Checked here for the record only: every phase that speaks checks again and fails then. + # Right after the daemons restart, say can stay silent for a minute (PR #7's run) and be + # fine by the next phase. + ensure_say || echo "::warning title=say::silent right after the speech daemons restarted; each phase that speaks checks again" } # Many checks speak with `say` (the mic end to end, the speech model, screenpipe's rows, @@ -388,10 +393,67 @@ lane() { fi if [ -f "$OUT/server.env" ]; then set -a; . "$OUT/server.env"; set +a; fi export LEARNER_SERVER_SECRETS="$HOME/.learner-ci-secrets.env" + export LEARNER_PROD_DEVICE_FILE="$PROD_DEVICE" if [ "$1" != light ]; then ensure_say || return 1; fi scripts/test.sh "$1" } +# The owner's REAL learner-server, through one throwaway test device per run. The CI +# minter's key (secret LEARNER_CI_MINT_KEY, scope ci-mint: create, seed and revoke test +# devices only) is given to these two steps alone. The device's pairing code stays in a +# mode-600 file outside ci-out (its logs are public); the device sees only its own seeded +# data and dies at its TTL even if prod-revoke never ran. +PROD_API="https://dev.biztoolz.app/learner-api" +PROD_DEVICE="$HOME/.learner-prod-device.json" + +# rpc NAME JSON: one RPC with the minter's key; prints the reply's `data`, exit 1 on non-200. +prod_rpc() { + local reply status + # The key reaches curl on stdin (-H @-), never in its arguments. + reply="$(printf 'x-api-key: %s\n' "$LEARNER_CI_MINT_KEY" | curl -s -m 30 -w '\n%{http_code}' -X POST "$PROD_API/rpc/$1" \ + -H 'content-type: application/json' -H @- -d "{\"data\":$2}")" + status="${reply##*$'\n'}" + reply="${reply%$'\n'*}" + if [ "$status" != 200 ]; then echo "$1: HTTP $status $(head -c 300 <<< "$reply")" >&2; return 1; fi + python3 -c 'import json,sys; o=json.load(sys.stdin); print(json.dumps(o.get("data", o)))' <<< "$reply" +} + +prod_device() { + rm -f "$PROD_DEVICE" + if [ -z "${LEARNER_CI_MINT_KEY:-}" ]; then + # Only a fork's pull request may go without it (GitHub gives forks no secrets). + if [ "${LEARNER_FORK_PR:-false}" = true ]; then + echo "::warning title=production server::a fork's pull request gets no LEARNER_CI_MINT_KEY: the production-server suite skips" + return 0 + fi + echo "LEARNER_CI_MINT_KEY is not set for this repository's own run: the production-server suite cannot run" + return 1 + fi + local run="gh-${GITHUB_RUN_ID:-local}-${GITHUB_RUN_ATTEMPT:-1}" device seeded + device="$(prod_rpc createTestDevice "{\"runId\":\"$run\",\"ttlMinutes\":120}")" || return 1 + # Written at once (mode 600, outside ci-out), so prod-revoke finds the device whatever + # fails next. The reply goes to python on stdin, never in its arguments. + umask 077 + python3 -c 'import json,sys; d=json.load(sys.stdin); o={k: d[k] for k in ("clientId", "pairingCode", "expiresAt")}; o["apiUrl"]=sys.argv[2]; json.dump(o, open(sys.argv[1], "w"))' "$PROD_DEVICE" "$PROD_API" <<< "$device" + umask 022 + seeded="$(prod_rpc seedMasteryGain "{\"clientId\":$(python3 -c 'import json,sys; print(json.dumps(json.load(open(sys.argv[1]))["clientId"]))' "$PROD_DEVICE")}")" || { + echo "seeding failed; revoking the device"; prod_revoke; return 1; } + python3 -c 'import json,sys; p=sys.argv[1]; d=json.load(open(p)); g=json.load(sys.stdin); d.update({k: g[k] for k in ("runId", "conceptId", "completedAt")}); json.dump(d, open(p, "w"))' "$PROD_DEVICE" <<< "$seeded" + # Ids only (no key, no code). + python3 -c 'import json,sys; d=json.load(open(sys.argv[1])); print("test device %s on %s (expires %s); seeded gain run %s, concept %s" % (d["clientId"], sys.argv[2], d["expiresAt"], d["runId"], d["conceptId"]))' "$PROD_DEVICE" "$PROD_API" +} + +prod_revoke() { + [ -f "$PROD_DEVICE" ] || { echo "no production test device to revoke"; return 0; } + [ -n "${LEARNER_CI_MINT_KEY:-}" ] || { echo "no LEARNER_CI_MINT_KEY to revoke with; the device expires at its TTL"; return 1; } + local id out + id="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["clientId"])' "$PROD_DEVICE")" + out="$(prod_rpc revokeTestDevice "{\"clientId\":\"$id\"}")" || return 1 + rm -f "$PROD_DEVICE" + echo "revoked $id: $out" + python3 -c 'import json,sys; sys.exit(0 if json.loads(sys.argv[1]).get("revoked") else 1)' "$out" +} + # The automatic updater installs and loads (on the runner it finds no GitHub token and # waits); uninstall must then remove it with everything else. updater() { @@ -410,9 +472,13 @@ report() { [ -f "$RESULTS" ] || failed=1 # A phase that never reported (its step skipped or killed) is a failure, not a gap. local p missing="" - for p in fetch virtual-mic grant fixtures screenpipe server speech install mic-e2e light medium heavy updater uninstall; do + for p in fetch virtual-mic grant fixtures screenpipe server speech install mic-e2e light medium prod-device heavy prod-revoke updater uninstall; do grep -q " $p " "$RESULTS" 2>/dev/null || { missing="$missing $p"; failed=1; } done + # A production device was made but its suite did not run: not a pass. + if grep -q "^test device ci-" "$OUT/prod-device.log" 2>/dev/null && grep -qE 'Suite "Production learner-server.*" skipped' "$OUT/heavy.log" 2>/dev/null; then + failed=1; missing="$missing production-suite-skipped" + fi # Swift Testing names every skip and cancellation: `➜ Test x() skipped: "why"`. skips="$(cat "$OUT"/light.log "$OUT"/medium.log "$OUT"/heavy.log 2>/dev/null \ | grep -E '^➜ (Test|Suite) .* (skipped|was cancelled)' | sed -E 's/^➜ //' | sort -u)" @@ -464,14 +530,16 @@ run() { install) phase install install ;; mic-e2e) phase mic-e2e mic_e2e ;; light|medium|heavy) phase "$1" lane "$1" ;; + prod-device) phase prod-device prod_device ;; + prod-revoke) phase prod-revoke prod_revoke ;; updater) phase updater updater ;; uninstall) keep_app_log; phase uninstall uninstall ;; report) report ;; all) rm -f "$RESULTS" - for p in fetch virtual-mic grant fixtures screenpipe server speech install mic-e2e light medium heavy updater uninstall; do run "$p" || true; done + for p in fetch virtual-mic grant fixtures screenpipe server speech install mic-e2e light medium prod-device heavy prod-revoke updater uninstall; do run "$p" || true; done report ;; - *) echo "usage: scripts/ci.sh fetch|virtual-mic|grant|fixtures|screenpipe|server|speech|install|mic-e2e|light|medium|heavy|updater|uninstall|report|all" >&2; return 2 ;; + *) echo "usage: scripts/ci.sh fetch|virtual-mic|grant|fixtures|screenpipe|server|speech|prod-device|prod-revoke|install|mic-e2e|light|medium|heavy|updater|uninstall|report|all" >&2; return 2 ;; esac }