diff --git a/docs/features/client-oauth-login.md b/docs/features/client-oauth-login.md index 8ba837ecc..2efd54966 100644 --- a/docs/features/client-oauth-login.md +++ b/docs/features/client-oauth-login.md @@ -120,6 +120,29 @@ handed over. Everything the app reports is shown as plain text. - Without the admin API key in this browser the page asks you to open the request from the MCPProxy tray or paste the key, and makes no request until then. +### From the macOS tray + +The tray is the way to reach the consent page with the key in the browser. When an MCP client +asks to sign in, the core publishes `oauth.authorization_pending`; the tray then + +- sends one notification ("Sign-in request") naming the app, and +- adds a menu row **Approve sign-in for \…** per waiting request, newest first (five rows, + the rest in a "N more sign-in requests" submenu). + +The row opens `/ui/authorize?request=` the way "Open Web UI in Browser" opens the Web UI (the +API key travels in the same `?apikey=` parameter, which the page moves into local storage). The +tray never approves or denies anything itself; the decision is made on the page. + +A row disappears when the request is decided (`oauth.authorization_decided`) or expires (10 +minutes). On connect, reconnect and every periodic refresh the tray reloads +`GET /api/v1/oauth/authorizations`, so a request made while the tray was not listening still +shows, and stale ones are dropped. While browser login is off the endpoint answers `404 +feature_disabled` and the tray shows nothing. + +The app name is chosen by the client, so the tray treats it as untrusted text: control and +invisible characters are removed, white space is collapsed, it is cut to 40 characters, and it is +only ever shown as plain text. + ## Managing logins Everything here is for administrators. An agent token or a client credential cannot see diff --git a/e2e/web-ui-sweep/client-oauth-consent.spec.ts b/e2e/web-ui-sweep/client-oauth-consent.spec.ts index 0eb2f51b5..7791d66d0 100644 --- a/e2e/web-ui-sweep/client-oauth-consent.spec.ts +++ b/e2e/web-ui-sweep/client-oauth-consent.spec.ts @@ -268,3 +268,113 @@ test('h. the consent page is never framed (any case)', async ({ request }) => { expect(res.headers()['x-frame-options'], path).toBe('DENY') } }) + +// --------------------------------------------------------------------------- +// Spec 132 T061 (web part): /ui/clients credential list and revoke, and the +// browser-login switch on /ui/settings. The core is expected to hold +// `mcp_oauth_enabled` in its config (not only through MCPPROXY_MCP_OAUTH_ENABLED, +// which locks the Settings switch). +// --------------------------------------------------------------------------- + +// A client with an API key (POST /clients) that signed in once through the page. +async function clientWithLogin(page: Page, suffix: string): Promise { + await catchCallback(page) + const id = `e2e-hub-${suffix}-${randomBytes(3).toString('hex')}` + const created = await admin('/clients', { method: 'POST', body: JSON.stringify({ id, display_name: `Hub ${suffix}` }) }) + expect(created.status, await created.clone().text()).toBeLessThan(300) + const p = await startSignIn(`Hub ${suffix} app`, `/mcp/oauth/${id}`, `state-${suffix}`) + await page.goto(p.requestUrl) + await t(page, 'authorize-approve').click() + await page.waitForURL(/127\.0\.0\.1:54321\/callback/) + await exchange(p, new URL(page.url()).searchParams.get('code') || '') + expect(await loginCount(id)).toBe(1) + return id +} + +async function credentials(client: string): Promise { + const res = await admin(`/clients/${client}`) + expect(res.status).toBe(200) + return (await res.json()).data?.credentials || [] +} + +async function openClient(page: Page, id: string) { + await page.goto(`${BASE}/ui/clients`) + await t(page, `client-expand-${id}`).click() + await expect(t(page, `client-credentials-${id}`)).toBeVisible() +} + +test('i. /ui/clients lists the API key and the login; revoking the API key alone leaves the login', async ({ page }) => { + await withKey(page) + const id = await clientWithLogin(page, 'key') + await openClient(page, id) + await expect(t(page, 'credential-api_key')).toBeVisible() + const loginRow = page.locator('[data-test^="credential-login-"]') + await expect(loginRow).toHaveCount(1) + await expect(t(page, 'credential-reported-name')).toContainText(/hub key app/i) // the core normalises the reported name + await shot(page, 'i-clients-credentials') + + await t(page, 'revoke-api-key').click() + await shot(page, 'i-revoke-api-key-dialog') + await t(page, 'revoke-credential-confirm').click() + await expect(t(page, 'revoke-api-key')).toHaveCount(0) + await expect(t(page, 'credential-state-api_key')).toContainText('revoked') + + const creds = await credentials(id) + expect(creds.find((c) => c.kind === 'api_key')?.state).toBe('revoked') + expect(creds.filter((c) => c.kind === 'browser_login' && c.state === 'active')).toHaveLength(1) + await expect(loginRow.locator('[data-test^="revoke-login-"]')).toBeVisible() +}) + +test('j. /ui/clients revokes one login through the dialog; Cancel changes nothing', async ({ page }) => { + await withKey(page) + const id = await clientWithLogin(page, 'login') + await openClient(page, id) + const revoke = page.locator('[data-test^="revoke-login-"]') + await expect(revoke).toHaveCount(1) + await revoke.click() + await t(page, 'revoke-credential-cancel').click() + expect(await loginCount(id)).toBe(1) + + await revoke.click() + await shot(page, 'j-revoke-login-dialog') + await t(page, 'revoke-credential-confirm').click() + await expect(revoke).toHaveCount(0) + expect(await loginCount(id)).toBe(0) + // the API key is untouched + expect((await credentials(id)).find((c) => c.kind === 'api_key')?.state).toBe('active') + await expect(t(page, 'credential-api_key')).toBeVisible() + await shot(page, 'j-after-revoke') +}) + +test('k. /ui/settings shows the browser-login switch with its badge; toggling it changes mcp_oauth_enabled', async ({ page }) => { + await withKey(page) + const enabled = async () => ((await (await admin('/config')).json()).data?.config?.mcp_oauth_enabled ?? false) as boolean + expect(await enabled(), 'start the scratch core with "mcp_oauth_enabled": true in its config').toBe(true) + + await page.goto(`${BASE}/ui/settings?tab=security`) + const row = t(page, 'setting-row-mcp_oauth_enabled') + await expect(row).toBeVisible() + await expect(t(page, 'setting-badge-mcp_oauth_enabled')).toHaveText('Experimental') + await expect(row).toContainText('Browser login for MCP clients') + const toggle = t(page, 'setting-toggle-mcp_oauth_enabled') + await expect(toggle).toBeChecked() + await shot(page, 'k-settings-on') + + const save = async () => { + await page.getByRole('button', { name: 'Save changes' }).first().click() + await sleep(1500) + } + await toggle.uncheck() + await save() + expect(await enabled()).toBe(false) + // off needs no restart and hides the OAuth paths again + expect((await fetch(`${BASE}/.well-known/oauth-authorization-server`)).status).toBe(404) + await shot(page, 'k-settings-off') + + await page.reload() + await expect(t(page, 'setting-toggle-mcp_oauth_enabled')).not.toBeChecked() + await t(page, 'setting-toggle-mcp_oauth_enabled').check() + await save() + expect(await enabled()).toBe(true) + expect((await fetch(`${BASE}/.well-known/oauth-authorization-server`)).status).toBe(200) +}) diff --git a/native/macos/MCPProxy/MCPProxy/API/APIClient.swift b/native/macos/MCPProxy/MCPProxy/API/APIClient.swift index c8c567b56..b2bbc0e40 100644 --- a/native/macos/MCPProxy/MCPProxy/API/APIClient.swift +++ b/native/macos/MCPProxy/MCPProxy/API/APIClient.swift @@ -235,6 +235,16 @@ actor APIClient { return try await fetchWrapped(path: "/api/v1/attention") } + /// Pending browser sign-in requests (Spec 132). `nil` while the feature is + /// off (the core answers 404 `feature_disabled`), so the tray shows nothing. + func signInRequests() async throws -> [SignInWire.Summary]? { + do { + return try await fetchWrapped(path: "/api/v1/oauth/authorizations") + } catch APIClientError.httpError(let status, _) where status == 404 { + return nil + } + } + func reviewQueue() async throws -> ReviewQueueResponse { try await fetchWrapped(path: "/api/v1/review") } func serverReview(_ name: String) async throws -> ServerReviewResponse { try await fetchWrapped(path: "/api/v1/servers/\(Self.escapePathComponent(name))/review") } func startSecurityScan(_ id: String) async throws { try await postAction(path: "/api/v1/servers/\(Self.escapePathComponent(id))/scan") } diff --git a/native/macos/MCPProxy/MCPProxy/Core/CoreProcessManager.swift b/native/macos/MCPProxy/MCPProxy/Core/CoreProcessManager.swift index 7d2ae9019..4c9ff627f 100644 --- a/native/macos/MCPProxy/MCPProxy/Core/CoreProcessManager.swift +++ b/native/macos/MCPProxy/MCPProxy/Core/CoreProcessManager.swift @@ -1782,6 +1782,26 @@ actor CoreProcessManager { // Spec 108-f: a client's binding, credential or lock changed. scheduleClientsRefresh() + case "oauth.authorization_pending": + // Spec 132: an MCP client asked to sign in. The tray lists it and + // notifies once; approval happens on the Web UI page. + guard let pending = SignInWire.decodePending(event.data) else { break } + let label = SignInPresentation.sanitizedLabel(pending.clientLabel) + let isNew = await MainActor.run { + // An event of an earlier stream belongs to a core we left. + appState.isCurrentConnection(generation) + && appState.addSignInRequest(id: pending.requestID, rawLabel: pending.clientLabel) + } + if isNew { + await notificationService.sendSignInRequest(requestId: pending.requestID, clientLabel: label) + } + + case "oauth.authorization_decided": + guard let decided = SignInWire.decodeDecided(event.data) else { break } + await MainActor.run { + if appState.isCurrentConnection(generation) { appState.removeSignInRequest(id: decided.requestID) } + } + case "ping": // Keepalive; no action needed break @@ -1961,6 +1981,7 @@ actor CoreProcessManager { await refreshClients() await refreshAttention() await refreshReviewQueue() + await refreshSignInRequests() // Bump activityVersion so ActivityView reloads. Still needed after the // glance's SSE work: the bus emits `activity.tool_call.completed` and // `activity.internal_tool_call.completed` (internal/runtime/events.go), @@ -2044,6 +2065,41 @@ actor CoreProcessManager { } } + /// Reload the pending browser sign-in requests (Spec 132): on connect and + /// reconnect, so a request made while the tray was not listening still + /// shows, and on the periodic tick, which also drops expired ones. A core + /// with the feature off (404) leaves nothing listed. + /// Test seam: replaces the GET (nil = use `apiClient`). + private var signInRequestsFetcher: (@Sendable () async throws -> [SignInWire.Summary]?)? + + func setSignInRequestsFetcher(_ fetcher: (@Sendable () async throws -> [SignInWire.Summary]?)?) { + signInRequestsFetcher = fetcher + } + + func refreshSignInRequests() async { + // An SSE event that lands while the GET is in flight, or a reconnect, + // makes the answer stale (see `AppState.applySignInReload`): fetch again. + for _ in 0..<3 { + let ticket = await MainActor.run { appState.signInReloadTicket() } + let fetched: [SignInWire.Summary]? + do { + if let fetcher = signInRequestsFetcher { + fetched = try await fetcher() + } else if let apiClient { + fetched = try await apiClient.signInRequests() + } else { + return + } + } catch { + // Non-fatal; keep what is listed but drop what has expired. + await MainActor.run { appState.expireSignInRequests() } + return + } + let result = await MainActor.run { appState.applySignInReload(fetched, ticket: ticket) } + if result == .applied { return } + } + } + func refreshReviewQueue() async { guard let apiClient else { return } let count = (try? await apiClient.reviewQueue().count) ?? 0 diff --git a/native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift b/native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift index 769e86c5b..c5caaccbe 100644 --- a/native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift +++ b/native/macos/MCPProxy/MCPProxy/MCPProxyApp.swift @@ -1245,6 +1245,38 @@ final class AppController: NSObject, NSApplicationDelegate, NSWindowDelegate, NS menu.addItem(.separator()) } + // Browser sign-in requests (Spec 132): one "Approve sign-in for …" + // row per waiting request, newest first, folded into a submenu past + // `maxMenuRows`. Absent while the feature is off or nothing waits. The + // row only opens the consent page in the Web UI (admin key as for + // "Open Web UI in Browser"); the tray never decides a request. + let signInRows = SignInPresentation.menuRows(appState.signInRequests) + if appState.coreState == .connected, !signInRows.shown.isEmpty { + for request in signInRows.shown { + let item = NSMenuItem(title: SignInPresentation.menuTitle(for: request), + action: #selector(approveSignInFromMenu(_:)), keyEquivalent: "") + item.target = self + item.representedObject = request.id + item.image = NSImage(systemSymbolName: "person.badge.key", accessibilityDescription: "sign-in request") + menu.addItem(item) + } + let rest = signInRows.overflow + if !rest.isEmpty { + let more = NSMenuItem(title: "\(rest.count) more sign-in \(rest.count == 1 ? "request" : "requests")", action: nil, keyEquivalent: "") + let sub = NSMenu(title: "Sign-in requests") + for request in rest { + let item = NSMenuItem(title: SignInPresentation.menuTitle(for: request), + action: #selector(approveSignInFromMenu(_:)), keyEquivalent: "") + item.target = self + item.representedObject = request.id + sub.addItem(item) + } + more.submenu = sub + menu.addItem(more) + } + menu.addItem(.separator()) + } + let reviewCount = appState.reviewQueueCount if reviewCount > 0 { let item = NSMenuItem( @@ -1939,6 +1971,14 @@ final class AppController: NSObject, NSApplicationDelegate, NSWindowDelegate, NS } } + /// Open the consent page of one sign-in request (Spec 132) through the same + /// Web UI link path the other deep links use. + @objc private func approveSignInFromMenu(_ sender: NSMenuItem) { + guard let id = sender.representedObject as? String, + let path = appState.signInPath(forRequest: id) else { return } + NotificationCenter.default.post(name: .openWebUIPath, object: path) + } + @objc private func showReviewQueueFromMenu(_ sender: NSMenuItem) { showMainWindow(tab: .review) } diff --git a/native/macos/MCPProxy/MCPProxy/Services/NotificationService.swift b/native/macos/MCPProxy/MCPProxy/Services/NotificationService.swift index 9f7c2bf18..fd0a4d396 100644 --- a/native/macos/MCPProxy/MCPProxy/Services/NotificationService.swift +++ b/native/macos/MCPProxy/MCPProxy/Services/NotificationService.swift @@ -280,6 +280,23 @@ actor NotificationService { markDelivered(key: key) } + /// Notify that an MCP client asks to sign in through the browser (Spec 132). + /// `clientLabel` must already be cleaned (`SignInPresentation.sanitizedLabel`). + /// The notification only points at the tray menu; approval is on the Web UI page. + func sendSignInRequest(requestId: String, clientLabel: String) async { + let key = "signin:\(requestId)" + guard shouldDeliver(key: key) else { return } + + let content = UNMutableNotificationContent() + content.title = "Sign-in request" + content.body = "\(clientLabel) wants to sign in. Choose \"Approve sign-in\u{2026}\" in the MCPProxy menu." + content.sound = .default + content.userInfo = ["requestId": requestId] + + await deliver(content: content, identifier: "signin-\(requestId)") + markDelivered(key: key) + } + // MARK: - Rate Limiting /// Check whether a notification with the given key should be delivered, diff --git a/native/macos/MCPProxy/MCPProxy/State/AppState.swift b/native/macos/MCPProxy/MCPProxy/State/AppState.swift index 34b4b9660..acb7627cc 100644 --- a/native/macos/MCPProxy/MCPProxy/State/AppState.swift +++ b/native/macos/MCPProxy/MCPProxy/State/AppState.swift @@ -41,7 +41,13 @@ final class AppState: ObservableObject { @Published var coreState: CoreState = .idle { didSet { if coreState != oldValue { connectionGeneration &+= 1 } - if coreState != .connected { clearGlanceState() } + if coreState != .connected { + clearGlanceState() + // Requests belong to the core that announced them (Spec 132). + var store = signInRequests + store.clear() + if store != signInRequests { signInRequests = store } + } } } @@ -96,6 +102,94 @@ final class AppState: ObservableObject { /// attention count, which can contain multiple reasons for one server. @Published var reviewQueueCount: Int = 0 + /// Browser sign-in requests waiting for the administrator (Spec 132). Fed by + /// SSE `oauth.authorization_pending` / `_decided` and by a reload of + /// `GET /api/v1/oauth/authorizations`; empty while the feature is off. + @Published private(set) var signInRequests = SignInRequestStore() + + /// Returns true when the request is new (the caller sends the notification). + @MainActor @discardableResult + func addSignInRequest(id: String, rawLabel: String, now: Date = Date()) -> Bool { + var store = signInRequests + let added = store.add( + SignInRequest(id: id, clientLabel: SignInPresentation.sanitizedLabel(rawLabel), + expiresAt: now.addingTimeInterval(SignInPresentation.defaultLifetime)), + now: now) + if store != signInRequests { signInRequests = store } + return added + } + + @MainActor + func removeSignInRequest(id: String) { + var store = signInRequests + store.remove(id: id) + if store != signInRequests { signInRequests = store } + } + + /// Replace the list with the core's (reconnect, periodic refresh). + @MainActor + func replaceSignInRequests(_ summaries: [SignInWire.Summary], now: Date = Date()) { + let fresh = summaries.map { s in + SignInRequest( + id: s.id, + clientLabel: SignInPresentation.sanitizedLabel(s.clientLabel ?? ""), + expiresAt: SignInPresentation.parseDate(s.expiresAt) + ?? now.addingTimeInterval(SignInPresentation.defaultLifetime)) + } + var store = signInRequests + store.replaceAll(with: fresh, now: now) + if store != signInRequests { signInRequests = store } + } + + @MainActor + func expireSignInRequests(now: Date = Date()) { + var store = signInRequests + store.expire(now: now) + if store != signInRequests { signInRequests = store } + } + + @MainActor + func clearSignInRequests() { + var store = signInRequests + store.clear() + if store != signInRequests { signInRequests = store } + } + + /// What a list reload remembers from the moment its fetch started. + struct SignInReloadTicket: Equatable, Sendable { + let revision: Int + let generation: Int + } + + enum SignInReloadResult: Equatable, Sendable { case applied, stale } + + /// Take before the GET /oauth/authorizations fetch. + @MainActor + func signInReloadTicket() -> SignInReloadTicket { + SignInReloadTicket(revision: signInRequests.revision, generation: connectionGeneration) + } + + /// Apply a reload (`nil` = feature off). It is stale, and changes nothing, + /// when the tray reconnected or an SSE event changed the list since the + /// ticket was taken; the caller refetches. + @MainActor + @discardableResult + func applySignInReload(_ summaries: [SignInWire.Summary]?, ticket: SignInReloadTicket, + now: Date = Date()) -> SignInReloadResult { + guard isCurrentConnection(ticket.generation), ticket.revision == signInRequests.revision else { + return .stale + } + if let summaries { replaceSignInRequests(summaries, now: now) } else { clearSignInRequests() } + return .applied + } + + /// The Web UI path a menu selection opens, or nil when the request is gone + /// or past its deadline (the menu may have been built a while ago). + func signInPath(forRequest id: String, now: Date = Date()) -> String? { + guard signInRequests.live(now: now).contains(where: { $0.id == id }) else { return nil } + return SignInPresentation.webUIPath(requestID: id) + } + /// The `reload_hint` fix (`client_never_seen`, "How to restart") has no /// native client screen yet (109-h adds `/clients?focus=`). Setting /// this instead of no-op'ing lets Home surface the item's own restart diff --git a/native/macos/MCPProxy/MCPProxy/State/SignInRequests.swift b/native/macos/MCPProxy/MCPProxy/State/SignInRequests.swift new file mode 100644 index 000000000..9a2778747 --- /dev/null +++ b/native/macos/MCPProxy/MCPProxy/State/SignInRequests.swift @@ -0,0 +1,183 @@ +import Foundation + +/// A browser sign-in request waiting for the administrator (Spec 132). The core +/// emits `oauth.authorization_pending` when an MCP client asks to sign in and +/// `GET /api/v1/oauth/authorizations` lists what is still waiting. The tray only +/// shows the request and opens the consent page in the Web UI; it never decides +/// one. `clientLabel` is text the client chose, so it is stored already cleaned. +struct SignInRequest: Equatable, Identifiable, Sendable { + let id: String + let clientLabel: String + let expiresAt: Date +} + +/// Decoding of the two SSE events and of the list response. Dates in the list +/// are RFC 3339 with fractional seconds, which `JSONDecoder` does not read, so +/// they stay strings until `SignInPresentation.parseDate`. +enum SignInWire { + struct Pending: Equatable, Sendable { + let requestID: String + let clientLabel: String + } + + struct Decided: Equatable, Sendable { + let requestID: String + let status: String + } + + struct Summary: Decodable, Equatable, Sendable { + let id: String + let clientLabel: String? + let expiresAt: String? + + enum CodingKeys: String, CodingKey { + case id + case clientLabel = "client_label" + case expiresAt = "expires_at" + } + } + + /// Events arrive as `{"payload": {...}}`; a bare object is accepted too. + private static func payload(_ data: String) -> [String: Any]? { + guard let bytes = data.data(using: .utf8), + let raw = try? JSONSerialization.jsonObject(with: bytes) as? [String: Any] else { return nil } + return raw["payload"] as? [String: Any] ?? raw + } + + static func decodePending(_ data: String) -> Pending? { + guard let p = payload(data), + let id = p["request_id"] as? String, !id.isEmpty else { return nil } + return Pending(requestID: id, clientLabel: p["client_label"] as? String ?? "") + } + + static func decodeDecided(_ data: String) -> Decided? { + guard let p = payload(data), + let id = p["request_id"] as? String, !id.isEmpty else { return nil } + return Decided(requestID: id, status: p["status"] as? String ?? "") + } +} + +enum SignInPresentation { + /// How long the core keeps a request (10 minutes). The pending event carries + /// no expiry, so an event-born entry gets this from the moment it arrived; + /// the list reload replaces it with the core's own `expires_at`. + static let defaultLifetime: TimeInterval = 600 + + /// Menu rows shown before the rest fold into one "N more" row. + static let maxMenuRows = 5 + + static let labelLimit = 40 + static let fallbackLabel = "an application" + + /// The label is untrusted: another process chose it. Control and format + /// characters (bidi overrides, zero-width) are dropped, white space runs + /// (newlines included) collapse to one space, the result is cut to + /// `labelLimit` characters. The text is only ever set as a plain menu or + /// notification string, never as markup. Blank input becomes a neutral phrase. + static func sanitizedLabel(_ raw: String) -> String { + var scalars = String.UnicodeScalarView() + for scalar in raw.unicodeScalars { + switch scalar.properties.generalCategory { + case .control, .format, .lineSeparator, .paragraphSeparator, .surrogate, .privateUse, .unassigned: + if scalar == "\n" || scalar == "\t" || scalar == "\r" { scalars.append(" ") } + default: + scalars.append(scalar) + } + } + let collapsed = String(scalars).split(whereSeparator: { $0.isWhitespace }).joined(separator: " ") + guard !collapsed.isEmpty else { return fallbackLabel } + return GlanceFormatting.tailTruncated(collapsed, limit: labelLimit) + } + + /// The menu rows for `store` at `now`: expired requests never appear, the + /// first `maxMenuRows` are shown and the rest fold into a submenu. + static func menuRows(_ store: SignInRequestStore, now: Date = Date()) + -> (shown: [SignInRequest], overflow: [SignInRequest]) { + let live = store.live(now: now) + return (Array(live.prefix(maxMenuRows)), Array(live.dropFirst(maxMenuRows))) + } + + static func menuTitle(for request: SignInRequest) -> String { + // A truncated label already ends in an ellipsis; do not stack two. + request.clientLabel.hasSuffix("\u{2026}") + ? "Approve sign-in for \(request.clientLabel)" + : "Approve sign-in for \(request.clientLabel)\u{2026}" + } + + /// The Web UI route the menu item opens; `WebUILink.url` adds `/ui` and the + /// API key the way "Open Web UI in Browser" does. + static func webUIPath(requestID: String) -> String { + "/authorize?request=\(WebUILink.pathSegment(requestID))" + } + + private static let fractional: ISO8601DateFormatter = { + let f = ISO8601DateFormatter() + f.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + return f + }() + private static let plain = ISO8601DateFormatter() + + static func parseDate(_ text: String?) -> Date? { + guard let text, !text.isEmpty else { return nil } + return fractional.date(from: text) ?? plain.date(from: text) + } +} + +/// The pending requests, newest first. A value type so the reducer is tested +/// without AppState. Every mutation is idempotent: the same request can arrive +/// by event and by list reload. +struct SignInRequestStore: Equatable, Sendable { + private(set) var requests: [SignInRequest] = [] + /// Increases on every change of content, so a list reload can tell that an + /// event landed while its GET was in flight. + private(set) var revision = 0 + + var isEmpty: Bool { requests.isEmpty } + + /// Requests whose deadline has not passed. + func live(now: Date = Date()) -> [SignInRequest] { + requests.filter { $0.expiresAt > now } + } + + /// Adds a request. Returns true when it was not already listed (so the + /// caller notifies once). An already-expired request is ignored. + @discardableResult + mutating func add(_ request: SignInRequest, now: Date = Date()) -> Bool { + guard request.expiresAt > now else { return false } + if let index = requests.firstIndex(where: { $0.id == request.id }) { + requests[index] = request + revision += 1 // an accepted event, even if it changes nothing visible + return false + } + requests.insert(request, at: 0) + revision += 1 + return true + } + + mutating func remove(id: String) { + requests.removeAll { $0.id == id } + // An accepted decision advances the revision even when the id is + // absent (the pending event may have been missed): a reload snapshot + // taken before it must not be applied afterwards. + revision += 1 + } + + mutating func expire(now: Date = Date()) { + let before = requests.count + requests.removeAll { $0.expiresAt <= now } + if requests.count != before { revision += 1 } + } + + /// The core's list is authoritative: what it no longer names is gone + /// (decided, cancelled or expired while the tray was not listening). The + /// list is newest first, so its order is kept. + mutating func replaceAll(with fresh: [SignInRequest], now: Date = Date()) { + var seen = Set() + let next = fresh.filter { $0.expiresAt > now && seen.insert($0.id).inserted } + if next != requests { requests = next; revision += 1 } + } + + mutating func clear() { + if !requests.isEmpty { requests = []; revision += 1 } + } +} diff --git a/native/macos/MCPProxy/MCPProxyTests/SignInRequestsTests.swift b/native/macos/MCPProxy/MCPProxyTests/SignInRequestsTests.swift new file mode 100644 index 000000000..1cde98571 --- /dev/null +++ b/native/macos/MCPProxy/MCPProxyTests/SignInRequestsTests.swift @@ -0,0 +1,350 @@ +import XCTest +@testable import MCPProxy + +private final class CallCounter: @unchecked Sendable { + private let lock = NSLock() + private(set) var value = 0 + func next() -> Int { lock.lock(); defer { lock.unlock() }; value += 1; return value } +} + +/// Spec 132 (T054): the tray lists browser sign-in requests and opens the +/// consent page; it never decides one. +@MainActor +final class SignInRequestsTests: XCTestCase { + private let now = Date(timeIntervalSince1970: 1_800_000_000) + + private func request(_ id: String, _ label: String = "Cursor", ttl: TimeInterval = 600) -> SignInRequest { + SignInRequest(id: id, clientLabel: label, expiresAt: now.addingTimeInterval(ttl)) + } + + override func setUp() { + super.setUp() + ConnectStubURLProtocol.reset() + } + + override func tearDown() { + ConnectStubURLProtocol.reset() + super.tearDown() + } + + // MARK: Event decoding + + func testDecodesPendingEventFromEnvelope() { + let e = SignInWire.decodePending(#"{"payload":{"request_id":"r1","client_id":"cursor","client_label":"Cursor IDE"},"timestamp":1}"#) + XCTAssertEqual(e, SignInWire.Pending(requestID: "r1", clientLabel: "Cursor IDE")) + } + + func testDecodesPendingEventWithoutEnvelopeAndMissingLabel() { + XCTAssertEqual(SignInWire.decodePending(#"{"request_id":"r2"}"#), + SignInWire.Pending(requestID: "r2", clientLabel: "")) + } + + func testPendingEventWithoutIDOrGarbageIsRejected() { + XCTAssertNil(SignInWire.decodePending(#"{"payload":{"client_label":"x"}}"#)) + XCTAssertNil(SignInWire.decodePending(#"{"payload":{"request_id":""}}"#)) + XCTAssertNil(SignInWire.decodePending("not json")) + } + + func testDecodesDecidedEvent() { + XCTAssertEqual(SignInWire.decodeDecided(#"{"payload":{"request_id":"r1","status":"approved"}}"#), + SignInWire.Decided(requestID: "r1", status: "approved")) + XCTAssertNil(SignInWire.decodeDecided(#"{"payload":{"status":"denied"}}"#)) + } + + // MARK: Reducer + + func testAddDedupesAndReportsOnlyTheFirstArrival() { + var store = SignInRequestStore() + XCTAssertTrue(store.add(request("a"), now: now)) + XCTAssertFalse(store.add(request("a", "Cursor 2"), now: now)) + XCTAssertEqual(store.requests.count, 1) + XCTAssertEqual(store.requests[0].clientLabel, "Cursor 2") + } + + func testNewestFirst() { + var store = SignInRequestStore() + store.add(request("a"), now: now) + store.add(request("b"), now: now) + XCTAssertEqual(store.requests.map(\.id), ["b", "a"]) + } + + func testAnExpiredRequestIsNotAdded() { + var store = SignInRequestStore() + XCTAssertFalse(store.add(request("old", ttl: -1), now: now)) + XCTAssertTrue(store.isEmpty) + } + + func testRemoveAndExpire() { + var store = SignInRequestStore() + store.add(request("a", ttl: 10), now: now) + store.add(request("b", ttl: 600), now: now) + store.expire(now: now.addingTimeInterval(11)) + XCTAssertEqual(store.requests.map(\.id), ["b"]) + store.remove(id: "b") + store.remove(id: "missing") + XCTAssertTrue(store.isEmpty) + } + + func testReplaceAllDropsWhatTheCoreNoLongerListsAndDuplicates() { + var store = SignInRequestStore() + store.add(request("gone"), now: now) + store.replaceAll(with: [request("x"), request("y"), request("x"), request("stale", ttl: -5)], now: now) + XCTAssertEqual(store.requests.map(\.id), ["x", "y"]) + } + + // MARK: AppState + + func testAppStateAddSanitisesAndNotifiesOnceAndDecidedRemoves() { + let state = AppState() + XCTAssertTrue(state.addSignInRequest(id: "r1", rawLabel: " Cur\u{202E}sor\nIDE ", now: now)) + XCTAssertFalse(state.addSignInRequest(id: "r1", rawLabel: "Cursor", now: now)) + XCTAssertEqual(state.signInRequests.requests.map(\.clientLabel), ["Cursor"]) + XCTAssertEqual(state.signInRequests.requests.first?.expiresAt, + now.addingTimeInterval(SignInPresentation.defaultLifetime)) + state.removeSignInRequest(id: "r1") + XCTAssertTrue(state.signInRequests.isEmpty) + } + + func testReconnectReloadShowsARequestMadeWhileNotListeningAndDropsExpiredOnes() throws { + let state = AppState() + state.addSignInRequest(id: "seen", rawLabel: "Seen", now: now) + let json = """ + [{"id":"missed","client_label":"Missed App","created_at":"2026-11-23T10:00:00.123Z","expires_at":"2026-11-23T10:10:00.456Z"}, + {"id":"expired","client_label":"Late","created_at":"2020-01-01T00:00:00Z","expires_at":"2020-01-01T00:10:00Z"}] + """ + let summaries = try JSONDecoder().decode([SignInWire.Summary].self, from: Data(json.utf8)) + let reloadAt = SignInPresentation.parseDate("2026-11-23T10:05:00Z")! + state.replaceSignInRequests(summaries, now: reloadAt) + XCTAssertEqual(state.signInRequests.requests.map(\.id), ["missed"]) + XCTAssertEqual(state.signInRequests.requests[0].clientLabel, "Missed App") + XCTAssertEqual(state.signInRequests.requests[0].expiresAt, SignInPresentation.parseDate("2026-11-23T10:10:00.456Z")) + } + + func testClearEmptiesTheListWhenTheFeatureIsOff() { + let state = AppState() + state.addSignInRequest(id: "r1", rawLabel: "Cursor", now: Date()) + state.clearSignInRequests() + XCTAssertTrue(state.signInRequests.isEmpty) + } + + // MARK: Presentation + + func testLabelIsCleanedAndTruncated() { + XCTAssertEqual(SignInPresentation.sanitizedLabel(""), "an application") + XCTAssertEqual(SignInPresentation.sanitizedLabel(" \n\t "), "an application") + XCTAssertEqual(SignInPresentation.sanitizedLabel("A\u{200B}B\u{0007}C"), "ABC") + XCTAssertEqual(SignInPresentation.sanitizedLabel("Cursor & Co"), "Cursor & Co") + let long = String(repeating: "x", count: 500) + XCTAssertEqual(SignInPresentation.sanitizedLabel(long).count, SignInPresentation.labelLimit) + } + + func testMenuTitle() { + XCTAssertEqual(SignInPresentation.menuTitle(for: request("a", "Cursor")), "Approve sign-in for Cursor\u{2026}") + } + + func testTruncatedLabelDoesNotStackEllipses() { + let label = SignInPresentation.sanitizedLabel(String(repeating: "x", count: 100)) + XCTAssertTrue(SignInPresentation.menuTitle(for: request("a", label)).hasSuffix("x\u{2026}")) + } + + func testMenuItemOpensTheConsentPageThroughWebUILink() { + let path = SignInPresentation.webUIPath(requestID: "ab/c d") + XCTAssertEqual(path, "/authorize?request=ab%2Fc%20d") + let url = WebUILink.url(base: "http://127.0.0.1:8080/", path: path, apiKey: "k&ey") + XCTAssertEqual(url?.absoluteString, "http://127.0.0.1:8080/ui/authorize?request=ab%2Fc%20d&apikey=k%26ey") + } + + // MARK: SSE routing and list reload + + func testSSEEventsAddAndRemoveARequest() async { + let state = connectedState() + let manager = CoreProcessManager( + appState: state, + notificationService: NotificationService(deliveryEnabled: false), + socketPath: NSTemporaryDirectory() + "signin-\(UUID().uuidString).sock") + await manager.handleSSEEvent( + SSEEvent(event: "oauth.authorization_pending", + data: #"{"payload":{"request_id":"r1","client_id":"cursor","client_label":"Cursor"}}"#, + retry: nil, id: nil), + generation: state.connectionGeneration) + XCTAssertEqual(state.signInRequests.requests.map(\.id), ["r1"]) + await manager.handleSSEEvent( + SSEEvent(event: "oauth.authorization_decided", + data: #"{"payload":{"request_id":"r1","status":"approved"}}"#, retry: nil, id: nil), + generation: state.connectionGeneration) + XCTAssertTrue(state.signInRequests.isEmpty) + } + + // MARK: Review round 1 (P2 x3) + + private func summary(_ id: String, _ label: String = "App", ttl: TimeInterval = 600) -> SignInWire.Summary { + let iso = ISO8601DateFormatter().string(from: Date().addingTimeInterval(ttl)) + return SignInWire.Summary(id: id, clientLabel: label, expiresAt: iso) + } + + private func connectedState() -> AppState { + let state = AppState() + state.coreState = .connected + return state + } + + /// P2-1: a reload that was fetched before an SSE decision must not bring + /// the decided request back. + func testReloadFetchedBeforeADecisionDoesNotResurrectIt() { + let state = connectedState() + state.addSignInRequest(id: "r1", rawLabel: "Cursor") + let ticket = state.signInReloadTicket() // fetch starts, sees r1 + state.removeSignInRequest(id: "r1") // SSE: decided + XCTAssertEqual(state.applySignInReload([summary("r1")], ticket: ticket), .stale) + XCTAssertTrue(state.signInRequests.isEmpty) + } + + /// P2-1: ... and must not drop a request that arrived while it was in flight. + /// Round 2: the pending event was missed, so the decision removes nothing + /// locally; it must still invalidate a snapshot taken before it. + func testDecisionForAnAbsentIdStillInvalidatesAnInFlightSnapshot() { + let state = connectedState() + let ticket = state.signInReloadTicket() // GET snapshots X; store has no X + state.removeSignInRequest(id: "x") // SSE: decided X (absent locally) + XCTAssertEqual(state.applySignInReload([summary("x")], ticket: ticket), .stale) + XCTAssertTrue(state.signInRequests.isEmpty) + } + + func testRepeatedPendingEventStillInvalidatesAnInFlightSnapshot() { + let state = connectedState() + state.addSignInRequest(id: "x", rawLabel: "X") + let ticket = state.signInReloadTicket() + state.addSignInRequest(id: "x", rawLabel: "X") // accepted event, no-op on the array + XCTAssertEqual(state.applySignInReload([], ticket: ticket), .stale) + } + + func testReloadFetchedBeforeANewRequestDoesNotDropIt() { + let state = connectedState() + let ticket = state.signInReloadTicket() // fetch starts, sees nothing + state.addSignInRequest(id: "new", rawLabel: "Fresh") // SSE: pending + XCTAssertEqual(state.applySignInReload([], ticket: ticket), .stale) + XCTAssertEqual(state.signInRequests.requests.map(\.id), ["new"]) + } + + func testReloadWithNoInterveningEventApplies() { + let state = connectedState() + let ticket = state.signInReloadTicket() + XCTAssertEqual(state.applySignInReload([summary("a")], ticket: ticket), .applied) + XCTAssertEqual(state.signInRequests.requests.map(\.id), ["a"]) + } + + func testFeatureOffAnswerClearsWhenNothingIntervened() { + let state = connectedState() + state.addSignInRequest(id: "r1", rawLabel: "Cursor") + let ticket = state.signInReloadTicket() + XCTAssertEqual(state.applySignInReload(nil, ticket: ticket), .applied) + XCTAssertTrue(state.signInRequests.isEmpty) + } + + func testStaleFeatureOffAnswerDoesNotClearANewerRequest() { + let state = connectedState() + let ticket = state.signInReloadTicket() + state.addSignInRequest(id: "new", rawLabel: "Fresh") + XCTAssertEqual(state.applySignInReload(nil, ticket: ticket), .stale) + XCTAssertEqual(state.signInRequests.requests.map(\.id), ["new"]) + } + + /// The manager retries a stale reload and ends with the core's list. + func testManagerRefetchesAfterAStaleReload() async { + let state = connectedState() + let manager = CoreProcessManager( + appState: state, notificationService: NotificationService(deliveryEnabled: false), + socketPath: NSTemporaryDirectory() + "signin-\(UUID().uuidString).sock") + let counter = CallCounter() + let fresh = summary("sse", "Via SSE") + await manager.setSignInRequestsFetcher { + let n = counter.next() + if n == 1 { + // an SSE event lands while the first response is in flight + await MainActor.run { _ = state.addSignInRequest(id: "sse", rawLabel: "Via SSE") } + return [] + } + return [fresh] + } + await manager.refreshSignInRequests() + XCTAssertEqual(counter.value, 2) + XCTAssertEqual(state.signInRequests.requests.map(\.id), ["sse"]) + } + + /// P2-2: leaving .connected forgets the old core's requests. + func testLeavingConnectedClearsRequests() { + let state = connectedState() + state.addSignInRequest(id: "r1", rawLabel: "Cursor") + state.coreState = .reconnecting(attempt: 1) + XCTAssertTrue(state.signInRequests.isEmpty) + state.coreState = .connected + XCTAssertTrue(state.signInRequests.isEmpty, "a restarted core must not inherit the old requests") + } + + /// P2-2: a response issued to the previous connection is dropped. + func testDelayedOldGenerationReloadIsDropped() { + let state = connectedState() + let ticket = state.signInReloadTicket() + state.coreState = .reconnecting(attempt: 1) + state.coreState = .connected // a new core + XCTAssertEqual(state.applySignInReload([summary("old")], ticket: ticket), .stale) + XCTAssertTrue(state.signInRequests.isEmpty) + } + + /// P2-2: an SSE event of an old stream is ignored. + func testSSEEventFromAnOldGenerationIsIgnored() async { + let state = connectedState() + let oldGeneration = state.connectionGeneration + state.coreState = .reconnecting(attempt: 1) + state.coreState = .connected + let manager = CoreProcessManager( + appState: state, notificationService: NotificationService(deliveryEnabled: false), + socketPath: NSTemporaryDirectory() + "signin-\(UUID().uuidString).sock") + await manager.handleSSEEvent( + SSEEvent(event: "oauth.authorization_pending", + data: #"{"payload":{"request_id":"old","client_label":"Old"}}"#, retry: nil, id: nil), + generation: oldGeneration) + XCTAssertTrue(state.signInRequests.isEmpty) + } + + /// P2-3: the menu never lists a request past its deadline, and selecting + /// one that expired since the menu was built opens nothing. + func testMenuRowsSkipExpiredRequestsAndSelectionRechecks() { + let state = connectedState() + let t0 = Date(timeIntervalSince1970: 1_800_000_000) + state.addSignInRequest(id: "soon", rawLabel: "Soon", now: t0.addingTimeInterval(-590)) // expires t0+10 + state.addSignInRequest(id: "later", rawLabel: "Later", now: t0) // expires t0+600 + let rows = SignInPresentation.menuRows(state.signInRequests, now: t0.addingTimeInterval(20)) + XCTAssertEqual(rows.shown.map(\.id), ["later"]) + XCTAssertEqual(rows.overflow.count, 0) + XCTAssertNil(state.signInPath(forRequest: "soon", now: t0.addingTimeInterval(20))) + XCTAssertEqual(state.signInPath(forRequest: "later", now: t0.addingTimeInterval(20)), + "/authorize?request=later") + } + + func testMenuRowsFoldPastTheLimit() { + var store = SignInRequestStore() + let t0 = Date(timeIntervalSince1970: 1_800_000_000) + for i in 0..<7 { + store.add(SignInRequest(id: "r\(i)", clientLabel: "A\(i)", expiresAt: t0.addingTimeInterval(600)), now: t0) + } + let rows = SignInPresentation.menuRows(store, now: t0) + XCTAssertEqual(rows.shown.count, SignInPresentation.maxMenuRows) + XCTAssertEqual(rows.overflow.count, 2) + } + + func testListRequestReturnsNilWhenTheFeatureIsOff() async throws { + ConnectStubURLProtocol.statusCode = 404 + ConnectStubURLProtocol.responseBody = Data(#"{"success":false,"error":"browser login is turned off"}"#.utf8) + let result = try await ConnectStubURLProtocol.makeClient().signInRequests() + XCTAssertNil(result) + XCTAssertEqual(ConnectStubURLProtocol.recorded.last?.url, "http://127.0.0.1:8080/api/v1/oauth/authorizations") + } + + func testListRequestDecodesPendingSummaries() async throws { + ConnectStubURLProtocol.responseBody = ConnectStubURLProtocol.envelope( + #"[{"id":"r1","client_label":"Cursor","created_at":"2026-11-23T10:00:00Z","expires_at":"2026-11-23T10:10:00Z"}]"#) + let result = try await ConnectStubURLProtocol.makeClient().signInRequests() + XCTAssertEqual(result?.map(\.id), ["r1"]) + } +}