diff --git a/mobile/ios/Backplane/DataClient.swift b/mobile/ios/Backplane/DataClient.swift index 6b112869e9..d949513a9f 100644 --- a/mobile/ios/Backplane/DataClient.swift +++ b/mobile/ios/Backplane/DataClient.swift @@ -1557,12 +1557,24 @@ final class DataClient { let env = "production" #endif _ = try? await call("device.register", ["token": t, "platform": "ios", "kind": "alert", "env": env, "bundle": Bundle.main.bundleIdentifier ?? ""], as: DEmpty.self) - await pushMute() + await pushMute() // which also tells the Enterprise gateway } + /// The same token and switch, for the person's Enterprise push gateway (when signed in there). + func registerEnterprise() async { + guard let t = pushToken else { return } + #if DEBUG + let env = "sandbox" + #else + let env = "production" + #endif + await EnterprisePush.shared.registerDevice(token: t, env: env, bundle: Bundle.main.bundleIdentifier ?? "", muted: !AppSettings.shared.alerts) + } + var apnsToken: String? { pushToken } /// This phone's switch: off, only what the person let through reaches it. func pushMute() async { guard has("push"), let t = pushToken else { return } _ = try? await call("device.prefs", ["token": t, "mute": !AppSettings.shared.alerts], as: DEmpty.self) + await registerEnterprise() } func setQuiet(_ spec: String) async { quiet = spec; _ = try? await call("push.prefs", ["notify.quiet": spec], as: DEmpty.self) } func setQuietUrgent(_ on: Bool) async { quietUrgent = on; _ = try? await call("push.prefs", ["notify.quiet.urgent": on ? "on" : "off"], as: DEmpty.self) } diff --git a/mobile/ios/Backplane/DataNotify.swift b/mobile/ios/Backplane/DataNotify.swift index 75106f097d..6917330881 100644 --- a/mobile/ios/Backplane/DataNotify.swift +++ b/mobile/ios/Backplane/DataNotify.swift @@ -34,5 +34,54 @@ struct DataNotifySection: View { await client.notify.act(action: b.action, value: b.value, fields: fields) } .task(id: client.conn) { if client.conn == .online { await client.notify.load() } } + EnterprisePushSection(client: client) + } +} + +/// Alerts through the person's Enterprise server, for a hub with no APNs key of its own: sign in with an account token, and this phone registers there. +struct EnterprisePushSection: View { + @Bindable var client: DataClient + private let ep = EnterprisePush.shared + @State private var url = "" + @State private var token = "" + @State private var err = "" + + var body: some View { + VStack(alignment: .leading, spacing: 10) { + DHeading(text: Tr.t("Enterprise alerts")) + if ep.signedIn { signedIn } else { form } + let shown = err.isEmpty ? ep.lastError : err + if !shown.isEmpty { Text(shown).dmono(11).foregroundStyle(BackplaneDesign.bad).accessibilityIdentifier("notify.enterprise.error") } + } + .padding(.top, 8) + } + + @ViewBuilder private var form: some View { + TextField("https://enterprise.example.com", text: $url).dmono(13).textInputAutocapitalization(.never).autocorrectionDisabled().keyboardType(.URL) + .padding(.horizontal, 10).frame(height: 38).dbox().accessibilityIdentifier("notify.enterprise.url") + SecureField("bpe_u_…", text: $token).dmono(13).textInputAutocapitalization(.never).autocorrectionDisabled() + .padding(.horizontal, 10).frame(height: 38).dbox().accessibilityIdentifier("notify.enterprise.token") + Button(Tr.t("Sign in")) { signIn() }.buttonStyle(DButton(primary: true)) + .disabled(ep.busy || url.trimmingCharacters(in: .whitespaces).isEmpty || token.trimmingCharacters(in: .whitespaces).isEmpty) + .accessibilityIdentifier("notify.enterprise.signin") + } + + @ViewBuilder private var signedIn: some View { + VStack(alignment: .leading, spacing: 4) { + if !ep.accountEmail.isEmpty { Text(ep.accountEmail).dmono(13).foregroundStyle(BackplaneDesign.text).accessibilityIdentifier("notify.enterprise.email") } + Text(ep.baseURL).dmono(11).foregroundStyle(BackplaneDesign.dim).lineLimit(1).truncationMode(.middle).accessibilityIdentifier("notify.enterprise.server") + if !ep.lastStatus.isEmpty { Text(ep.lastStatus).dmono(11).foregroundStyle(BackplaneDesign.faint).accessibilityIdentifier("notify.enterprise.status") } + } + Button(Tr.t("Sign out")) { Task { await ep.signOut(apnsToken: client.apnsToken) } }.buttonStyle(DButton(primary: false)) + .disabled(ep.busy).accessibilityIdentifier("notify.enterprise.signout") + } + + private func signIn() { + Task { + err = await ep.signIn(urlString: url, token: token) ?? "" + guard err.isEmpty else { return } + token = ""; url = "" + if client.apnsToken != nil { await client.registerEnterprise() } else { await client.enablePush(ask: true) } + } } } diff --git a/mobile/ios/Backplane/EnterprisePush.swift b/mobile/ios/Backplane/EnterprisePush.swift new file mode 100644 index 0000000000..9c2d9a42d1 --- /dev/null +++ b/mobile/ios/Backplane/EnterprisePush.swift @@ -0,0 +1,154 @@ +import Foundation +import Observation +import Security +import UIKit + +// Enterprise push: when the person's hub has no APNs key of its own, their Enterprise server holds it. The phone signs in there with an account token (bpe_u_...) +// and registers its APNs token directly; the hub hands alerts to the server (native/host/src/push/enterprise.rs). The token lives in the Keychain, readable after the +// first unlock and never synced or backed up; the server's URL and the account's email are not secret and stay in UserDefaults. +enum EnterpriseStore { + private static let service = (Bundle.main.bundleIdentifier ?? "dev.backplane.mobile") + ".enterprise" + private static let account = "token" + private static let apnsAccount = "last_apns_token" + + private static func query(_ acct: String) -> [String: Any] { + [kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: service, + kSecAttrAccount as String: acct] + } + + static func load(_ acct: String = account) -> String? { + var q = query(acct) + q[kSecReturnData as String] = true + q[kSecMatchLimit as String] = kSecMatchLimitOne + var out: CFTypeRef? + let status = SecItemCopyMatching(q as CFDictionary, &out) + if status != errSecSuccess, status != errSecItemNotFound { NSLog("enterprise: keychain read %d", Int(status)) } + guard status == errSecSuccess, let data = out as? Data, let s = String(data: data, encoding: .utf8), !s.isEmpty else { return nil } + return s + } + + @discardableResult static func save(_ value: String, account acct: String = account) -> Bool { + let q = query(acct) + let update: [String: Any] = [kSecValueData as String: Data(value.utf8), + kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly] + var status = SecItemUpdate(q as CFDictionary, update as CFDictionary) + if status == errSecItemNotFound { + var add = q + for (k, v) in update { add[k] = v } + status = SecItemAdd(add as CFDictionary, nil) + } + if status != errSecSuccess { NSLog("enterprise: keychain %d", Int(status)) } + return status == errSecSuccess + } + + static func delete() { + SecItemDelete(query(account) as CFDictionary) + SecItemDelete(query(apnsAccount) as CFDictionary) + } + + static func loadLastApnsToken() -> String? { load(apnsAccount) } + @discardableResult static func saveLastApnsToken(_ token: String) -> Bool { save(token, account: apnsAccount) } +} + +@MainActor +@Observable +final class EnterprisePush { + static let shared = EnterprisePush() + + private static let urlKey = "app.enterprise.url" + private static let emailKey = "app.enterprise.email" + + private(set) var baseURL: String + private(set) var accountEmail: String + private(set) var signedIn: Bool + var busy = false + var lastError = "" + var lastStatus = "" + + private init() { + let d = UserDefaults.standard + baseURL = d.string(forKey: Self.urlKey) ?? "" + accountEmail = d.string(forKey: Self.emailKey) ?? "" + signedIn = !baseURL.isEmpty && EnterpriseStore.load() != nil + } + + /// https:// (or http:// for loopback tests) with no trailing slash, else nil. + static func normalize(_ s: String) -> String? { + var u = s.trimmingCharacters(in: .whitespacesAndNewlines) + while u.hasSuffix("/") { u.removeLast() } + guard let parsed = URL(string: u), let host = parsed.host?.lowercased(), !host.isEmpty else { return nil } + if u.hasPrefix("https://") { return u } + if u.hasPrefix("http://"), host == "127.0.0.1" || host == "localhost" || host == "::1" { return u } + return nil + } + + private func request(_ base: String, _ path: String, token: String, method: String = "GET", body: [String: Any]? = nil) -> URLRequest? { + guard let url = URL(string: base + path) else { return nil } + var r = URLRequest(url: url, timeoutInterval: 15) + r.httpMethod = method + r.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") + if let body { + r.setValue("application/json", forHTTPHeaderField: "Content-Type") + r.httpBody = try? JSONSerialization.data(withJSONObject: body) + } + return r + } + + /// Checks the token against the server and keeps it. nil on success, else what to tell the person. + func signIn(urlString: String, token: String) async -> String? { + guard let base = Self.normalize(urlString) else { return Tr.t("The server address must start with https://") } + let t = token.trimmingCharacters(in: .whitespacesAndNewlines) + guard !t.isEmpty else { return Tr.t("Enter your account token") } + guard let req = request(base, "/v1/me", token: t) else { return Tr.t("The server address is not valid") } + busy = true; defer { busy = false } + do { + let (data, resp) = try await URLSession.shared.data(for: req) + let code = (resp as? HTTPURLResponse)?.statusCode ?? 0 + switch code { + case 200: + let o = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] + let email = o?["email"] as? String ?? "" + guard EnterpriseStore.save(t) else { return Tr.t("The token could not be saved on this phone") } + UserDefaults.standard.set(base, forKey: Self.urlKey) + UserDefaults.standard.set(email, forKey: Self.emailKey) + baseURL = base; accountEmail = email; signedIn = true; lastError = ""; lastStatus = "" + return nil + case 401, 403: return Tr.t("That token was not accepted") + case 429: return Tr.t("Too many tries, wait a moment") + default: return Tr.t("The server answered") + " (\(code))" + } + } catch { return error.localizedDescription } + } + + /// Takes this phone off the server (best effort), then forgets the account. + func signOut(apnsToken: String?) async { + let effectiveToken = apnsToken ?? EnterpriseStore.loadLastApnsToken() + if let effectiveToken, !baseURL.isEmpty, let t = EnterpriseStore.load(), + let req = request(baseURL, "/v1/push/devices/unregister", token: t, method: "POST", body: ["token": effectiveToken]) { + _ = try? await URLSession.shared.data(for: req) + } + EnterpriseStore.delete() + UserDefaults.standard.removeObject(forKey: Self.urlKey) + UserDefaults.standard.removeObject(forKey: Self.emailKey) + baseURL = ""; accountEmail = ""; signedIn = false; lastError = ""; lastStatus = "" + } + + /// Tells the server this phone's APNs token (and whether alerts are muted). Nothing when not signed in. + func registerDevice(token: String, env: String, bundle: String, muted: Bool) async { + guard !baseURL.isEmpty, let t = EnterpriseStore.load() else { return } + if !signedIn { signedIn = true } + let body: [String: Any] = ["token": token, "platform": "ios", "kind": "alert", "env": env, "bundle": bundle, "deviceName": UIDevice.current.name, "muted": muted] + guard let req = request(baseURL, "/v1/push/devices", token: t, method: "POST", body: body) else { return } + do { + let (_, resp) = try await URLSession.shared.data(for: req) + let code = (resp as? HTTPURLResponse)?.statusCode ?? 0 + if (200..<300).contains(code) { + EnterpriseStore.saveLastApnsToken(token) + lastError = ""; lastStatus = muted ? Tr.t("Registered, alerts off") : Tr.t("Registered") + } + else if code == 401 || code == 403 { lastStatus = ""; lastError = Tr.t("Sign-in expired or revoked") } + else { lastStatus = ""; lastError = Tr.t("The server answered") + " (\(code))" } + } catch { lastStatus = ""; lastError = error.localizedDescription } + } +} diff --git a/native/host/src/push/apns.rs b/native/host/src/push/apns.rs index 9f4c4f2801..ee94677af8 100644 --- a/native/host/src/push/apns.rs +++ b/native/host/src/push/apns.rs @@ -47,7 +47,7 @@ pub fn raw_sig(der: &[u8]) -> Option<[u8; 64]> { Some(out) } /// Write `input` to `c`'s stdin and wait for stdout; kill and reap on write failure so no `` child leaks (#1607). -fn pipe_and_wait(c: &mut std::process::Command, input: &[u8], missing: &str, fail: &str) -> Result, String> { +pub(super) fn pipe_and_wait(c: &mut std::process::Command, input: &[u8], missing: &str, fail: &str) -> Result, String> { let mut ch = c.spawn().map_err(|_| missing.to_string())?; let wrote = ch.stdin.take().ok_or_else(|| "no stdin".to_string()).and_then(|mut s| s.write_all(input).map_err(|e| e.to_string())); if let Err(e) = wrote { let _ = ch.kill(); let _ = ch.wait(); return Err(e) } @@ -163,6 +163,7 @@ pub async fn credentials(hub: &Arc) -> Option<(String, String, String, &'st /// Push.undelivered.why: a send's failure as the person reads it, naming the key file when that is what is gone (never a key's contents). pub async fn explain(hub: &Arc, why: &str) -> String { + if why.starts_with("Enterprise push") { return why.to_string() } if why != "APNs is not configured" { return format!("Apple refused or did not answer the alert ({why})") } let key = hub.setting("push.apns.key").await.unwrap_or_default(); if !key.is_empty() && !Path::new(&key).is_file() { return format!("the APNs key file {key} is missing") } diff --git a/native/host/src/push/enterprise.rs b/native/host/src/push/enterprise.rs new file mode 100644 index 0000000000..4330d77791 --- /dev/null +++ b/native/host/src/push/enterprise.rs @@ -0,0 +1,166 @@ +//! The Enterprise push gateway: when this hub has no APNs key of its own, it hands the alert to the person's Enterprise server (`POST /v1/push/send`), which holds the +//! key and the phone's token (the phone registers it there directly). Both URL and bearer token live in the machine-local secret file `/secrets/enterprise.json` +//! (`{"url":"https://...","token":"..."}`), never a shared/synced setting. The token goes to `curl` on stdin, never on a command line, and is never logged. +use super::apns::Frame; +use crate::hub::{now_ms, Hub}; +use serde_json::{json, Value}; +use std::{io::Write, path::Path, sync::{atomic::{AtomicU64, Ordering}, Arc}}; use crate::plat::fs::{DirBuilderExt, OpenOptionsExt}; + +static SEQ: AtomicU64 = AtomicU64::new(0); + +fn is_loopback_http(url: &str) -> bool { + let Some(rest) = url.strip_prefix("http://") else { return false }; + let host_port = rest.split('/').next().unwrap_or(""); + if host_port.starts_with("[::1]") { return true } + let host = host_port.split(':').next().unwrap_or(""); + matches!(host, "127.0.0.1" | "localhost") +} + +fn allowed_url(url: &str) -> bool { + let u = url.trim_end_matches('/'); + (u.starts_with("https://") && u.len() > "https://".len()) || is_loopback_http(u) +} + +/// The server's URL and the person's token, when both are set in `/secrets/enterprise.json`. +pub async fn credentials(hub: &Arc) -> Option<(String, String)> { + let text = std::fs::read_to_string(hub.cfg.home.join("secrets/enterprise.json")).ok()?; + let v: Value = serde_json::from_str(&text).ok()?; + let raw_url = v["url"].as_str()?.trim(); + if !allowed_url(raw_url) { return None } + let url = raw_url.trim_end_matches('/').to_string(); + let token = v["token"].as_str()?.trim().to_string(); + (!token.is_empty()).then_some((url, token)) +} + +/// What the gateway's answer means: how many phones it reached, and why none was (None when the person simply has no phone registered there or unmuted). +pub fn outcome(code: u16, body: &str) -> (u64, Option) { + match code { + 200 => { + let v: Value = serde_json::from_str(body).unwrap_or_default(); + let (sent, failed) = (v["sent"].as_u64().unwrap_or(0), v["failed"].as_u64().unwrap_or(0)); + if sent > 0 { return (sent, None) } + if failed == 0 { return (0, None) } + let reason = v["results"].as_array() + .and_then(|a| a.iter().find_map(|r| (r["status"].as_u64() != Some(200)).then(|| r["reason"].as_str().filter(|s| !s.is_empty())).flatten())) + .or_else(|| v["errors"].as_array().and_then(|a| a.first()).and_then(|e| e.as_str().or_else(|| e["reason"].as_str())).filter(|s| !s.is_empty())) + .unwrap_or("Enterprise push delivery failed"); + (0, Some(reason.to_string())) + } + 401 | 403 => (0, Some("Enterprise push sign-in expired or revoked".into())), + 429 => (0, Some("Enterprise push rate limited".into())), + _ => (0, Some(format!("Enterprise push HTTP {code}"))), + } +} + +fn post(home: &Path, url: &str, token: &str, body: &str) -> Result<(u16, String), String> { + let tmp = home.join("tmp"); std::fs::create_dir_all(&tmp).map_err(|e| e.to_string())?; + let d = tmp.join(format!("push-ent-{}-{:x}-{}", now_ms(), std::process::id(), SEQ.fetch_add(1, Ordering::SeqCst))); + std::fs::DirBuilder::new().mode(0o700).create(&d).map_err(|e| e.to_string())?; + let file = d.join("body.json"); + let r = (|| { + std::fs::OpenOptions::new().write(true).create(true).truncate(true).mode(0o600).open(&file).and_then(|mut x| x.write_all(body.as_bytes())).map_err(|e| e.to_string())?; + let mut c = crate::proc::std_cmd(crate::proc::Kind::Net, "curl"); + c.args(["-sS", "--proto", "=http,https", "--max-time", "10", "--max-redirs", "0", "-X", "POST", "-H", "@-", "--data-binary"]).arg(format!("@{}", file.display())) + .args(["-w", "\n%{http_code}", "--url"]).arg(format!("{url}/v1/push/send")).current_dir(&d) + .stdin(std::process::Stdio::piped()).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::null()); + let headers = format!("Authorization: Bearer {token}\nContent-Type: application/json\n"); + let out = super::apns::pipe_and_wait(&mut c, headers.as_bytes(), "curl is missing", "the Enterprise server did not answer")?; + let text = String::from_utf8_lossy(&out); let (b, code) = text.rsplit_once('\n').unwrap_or(("", text.as_ref())); + Ok((code.trim().parse::().unwrap_or(0), b.to_string())) + })(); + let _ = std::fs::remove_dir_all(&d); + r +} + +/// Send one frame through the gateway: how many phones it reached, and why it reached none (never the token). +pub async fn send(hub: &Arc, url: &str, token: &str, f: &Frame, through: bool) -> (u64, Option) { + if crate::copy::on() { return (0, Some("a copy of a log sends nothing".into())) } + let body = json!({"pushType": f.push_type, "priority": f.priority, "collapseId": f.collapse, "payload": f.payload, "through": through}).to_string(); + let (home, url, token) = (hub.cfg.home.clone(), url.to_string(), token.to_string()); + match tokio::task::spawn_blocking(move || post(&home, &url, &token, &body)).await { + Ok(Ok((code, body))) => { let r = outcome(code, &body); eprintln!("push: Enterprise {} {}: HTTP {code}", f.push_type, f.collapse); r } + Ok(Err(e)) => { eprintln!("push: Enterprise not sent: {e}"); (0, Some(format!("Enterprise push not sent: {e}"))) } + Err(_) => (0, Some("Enterprise push task failed".into())), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{hub::Cfg, presenter::Canned}; + use std::io::{Read, Write as _}; + + async fn hub(tag: &str) -> crate::hub::TestHub { + let dir = crate::plat::tmp::dir(&format!("ent-push-{tag}")); + std::fs::write(dir.join("events.jsonl"), "").unwrap(); std::fs::write(dir.join("token"), "tok").unwrap(); + let h = Hub::start(Cfg { home: dir.to_path_buf(), version: "0.14.0".into(), commit: "c".into(), listen: "x".into(), os: "linux".into(), arch: "x64".into() }, Arc::new(Canned { reply: json!({}) })).await.unwrap(); + crate::hub::TestHub::new(h, dir) + } + fn frame() -> Frame { Frame { push_type: "alert", priority: 10, collapse: "k1".into(), payload: json!({"aps":{"badge":1}}) } } + /// A server that answers one request with `status` and `reply`, and hands back the raw request it got. + fn serve(status: u16, reply: &'static str) -> (String, std::thread::JoinHandle) { + let l = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let url = format!("http://127.0.0.1:{}", l.local_addr().unwrap().port()); + (url, std::thread::spawn(move || { + let (mut s, _) = l.accept().unwrap(); let mut got = Vec::new(); let mut buf = [0u8; 4096]; + loop { + let n = s.read(&mut buf).unwrap(); got.extend_from_slice(&buf[..n]); + let text = String::from_utf8_lossy(&got).to_string(); + if let Some((head, rest)) = text.split_once("\r\n\r\n") { + let len = head.lines().find_map(|l| l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::().unwrap())).unwrap_or(0); + if rest.len() >= len { break } + } + if n == 0 { break } + } + let _ = write!(s, "HTTP/1.1 {status} X\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{reply}", reply.len()); + String::from_utf8_lossy(&got).to_string() + })) + } + + #[tokio::test] async fn a_delivered_push_posts_the_frame_with_the_bearer_and_counts_phones() { + let h = hub("ok").await; let (url, srv) = serve(200, r#"{"sent":1,"failed":0}"#); + let r = send(&h, &url, "bpe_u_secret", &frame(), true).await; assert_eq!(r, (1, None)); + let req = srv.join().unwrap(); + assert!(req.starts_with("POST /v1/push/send "), "{req}"); + assert!(req.to_ascii_lowercase().contains("authorization: bearer bpe_u_secret"), "{req}"); + let v: Value = serde_json::from_str(req.split_once("\r\n\r\n").unwrap().1).unwrap(); + assert_eq!(v, json!({"pushType":"alert","priority":10,"collapseId":"k1","payload":{"aps":{"badge":1}},"through":true})); + assert!(std::fs::read_dir(h.cfg.home.join("tmp")).unwrap().next().is_none(), "the per-send folder is removed"); + } + #[tokio::test] async fn no_registered_phone_is_not_a_failure() { + let h = hub("none").await; let (url, srv) = serve(200, r#"{"sent":0,"failed":0}"#); + assert_eq!(send(&h, &url, "t", &frame(), false).await, (0, None)); srv.join().unwrap(); + } + #[tokio::test] async fn a_failed_send_gives_its_reason() { + let h = hub("fail").await; let (url, srv) = serve(200, r#"{"sent":0,"failed":1,"results":[{"handle":"abcdef012345","status":400,"reason":"BadDeviceToken"}]}"#); + assert_eq!(send(&h, &url, "t", &frame(), false).await, (0, Some("BadDeviceToken".into()))); srv.join().unwrap(); + let (url, srv) = serve(200, r#"{"sent":0,"failed":1,"errors":["APNs unreachable"]}"#); + assert_eq!(send(&h, &url, "t", &frame(), false).await, (0, Some("APNs unreachable".into()))); srv.join().unwrap(); + let (url, srv) = serve(200, r#"{"sent":0,"failed":2}"#); + assert_eq!(send(&h, &url, "t", &frame(), false).await, (0, Some("Enterprise push delivery failed".into()))); srv.join().unwrap(); + } + #[tokio::test] async fn a_refused_sign_in_is_said_plainly() { + let h = hub("401").await; let (url, srv) = serve(401, r#"{"error":"no"}"#); + assert_eq!(send(&h, &url, "t", &frame(), false).await, (0, Some("Enterprise push sign-in expired or revoked".into()))); srv.join().unwrap(); + } + #[tokio::test] async fn a_rate_limit_and_other_statuses() { + let h = hub("429").await; let (url, srv) = serve(429, "{}"); + assert_eq!(send(&h, &url, "t", &frame(), false).await, (0, Some("Enterprise push rate limited".into()))); srv.join().unwrap(); + let (url, srv) = serve(500, "{}"); + assert_eq!(send(&h, &url, "t", &frame(), false).await, (0, Some("Enterprise push HTTP 500".into()))); srv.join().unwrap(); + } + #[tokio::test] async fn credentials_come_from_the_secret_json_file() { + let h = hub("cred").await; + assert_eq!(credentials(&h).await, None, "no file yet"); + let p = h.cfg.home.join("secrets/enterprise.json"); + std::fs::create_dir_all(p.parent().unwrap()).unwrap(); + std::fs::write(&p, r#"{"url":" https://enterprise.example.com/ ","token":" bpe_u_x \n"}"#).unwrap(); + assert_eq!(credentials(&h).await, Some(("https://enterprise.example.com".into(), "bpe_u_x".into()))); + std::fs::write(&p, r#"{"url":"http://127.0.0.1:8080/","token":"t"}"#).unwrap(); + assert_eq!(credentials(&h).await, Some(("http://127.0.0.1:8080".into(), "t".into()))); + std::fs::write(&p, r#"{"url":"http://enterprise.example.com","token":"t"}"#).unwrap(); + assert_eq!(credentials(&h).await, None, "plain http rejected outside loopback"); + std::fs::write(&p, r#"{"url":"ftp://enterprise.example.com","token":"t"}"#).unwrap(); + assert_eq!(credentials(&h).await, None, "only https or loopback http is allowed"); + } + #[test] fn the_server_is_machine_local() { assert!(!crate::net::settings_sync::is_shared("enterprise.url")); } +} diff --git a/native/host/src/push/mod.rs b/native/host/src/push/mod.rs index f469985985..3c7c677ddd 100644 --- a/native/host/src/push/mod.rs +++ b/native/host/src/push/mod.rs @@ -17,6 +17,7 @@ //! thread (settings/alerts.rs decides that, as it does for the desk itself; `alert` below). Each is one order, through the same respect, book and collapsing as any other; //! the uberbot's own orders are unchanged. pub mod apns; +pub mod enterprise; pub mod page; use crate::{bots::{rpc::Bots, world::{Device, Routine, World}}, hub::{now_ms, Hub}}; @@ -325,7 +326,7 @@ pub fn start_with(hub: &Arc, bots: Arc, carrier: Arc) -> hub.register_rpc(Arc::new(PushRpc(p.clone()))); hub.register_rpc(Arc::new(page::NotifyPage(bots.clone()))); // said once at start, so a hub that cannot push says so in its log (never the values) - { let hub = hub.clone(); tokio::spawn(async move { match apns::credentials(&hub).await { Some((.., from)) => eprintln!("backplane: push: APNs configured (from {from})"), None => eprintln!("backplane: push: APNs is not configured: set push.apns.key, push.apns.keyid and push.apns.team, or write ~/.config/backplane/apns.env") } }); } + { let hub = hub.clone(); tokio::spawn(async move { match apns::credentials(&hub).await { Some((.., from)) => eprintln!("backplane: push: APNs configured (from {from})"), None => match enterprise::credentials(&hub).await { Some((url, _)) => eprintln!("backplane: push: Enterprise push gateway configured ({url})"), None => eprintln!("backplane: push: APNs is not configured: set push.apns.key, push.apns.keyid and push.apns.team, or write ~/.config/backplane/apns.env") } } }); } tokio::spawn(Worker { hub: hub.clone(), bots, carrier, book: Book::default() }.run(rx)); p } @@ -437,10 +438,12 @@ impl Worker { let badge = self.book.badge(self.asks()); let frame = apns::Frame::alert(&say, badge); let hearing: Vec<&Device> = devices.iter().filter(|d| hears(d, through)).collect(); - let (sent, why) = self.send(hearing.iter().copied(), &frame).await; + // no APNs key of this hub's own: the person's Enterprise gateway holds it (the phone registers its token there). Test doubles and the sink keep the carrier's path. + let gate = if std::env::var_os("BACKPLANE_PUSH_SINK").is_none() && apns::credentials(&self.hub).await.is_none() { enterprise::credentials(&self.hub).await } else { None }; + let (sent, why) = match &gate { Some((url, token)) => enterprise::send(&self.hub, url, token, &frame, through).await, None => self.send(hearing.iter().copied(), &frame).await }; let ev = json!({"$":"PushSent","key":say.key,"thread":say.thread,"ask":say.ask,"kind":say.reason,"title":say.title,"body":say.body,"badge":badge,"through":through,"sent":sent,"why":if sent > 0 { "" } else { why.as_deref().unwrap_or("") },"link":say.link,"at":now}); let _ = self.hub.commit(&ev).await; - if !hearing.is_empty() { self.undelivered(if sent > 0 { None } else { why }, &home, now).await } + if !hearing.is_empty() || sent > 0 || (gate.is_some() && why.is_some()) { self.undelivered(if sent > 0 { None } else { why }, &home, now).await } self.save().await; } /// Push.undelivered: phones are registered and an alert reached none of them (Nov 18: the wipe took the APNs key file, and for hours every push went to no phone while @@ -463,6 +466,9 @@ impl Worker { let frame = apns::Frame::clear(&keys, badge); // recorded first: a socket (Android, the desktop) hears the clear no later than an iOS phone does let _ = self.hub.commit(&json!({"$":"PushCleared","keys":keys,"badge":badge,"at":now_s()})).await; + if std::env::var_os("BACKPLANE_PUSH_SINK").is_none() && apns::credentials(&self.hub).await.is_none() { + if let Some((url, token)) = enterprise::credentials(&self.hub).await { let _ = enterprise::send(&self.hub, &url, &token, &frame, false).await; return } + } let _ = self.send(devices.iter().filter(|d| d.kind == "alert" && d.platform == "ios"), &frame).await; } fn asks(&self) -> u64 { crate::data::open_ask_total(&self.hub) }