diff --git a/.claude/rules/ci.md b/.claude/rules/ci.md index 60b0dc7d08..4e753adeca 100644 --- a/.claude/rules/ci.md +++ b/.claude/rules/ci.md @@ -38,7 +38,7 @@ paths: - Concurrency in `ci.yml`: a PR keeps its newest run, main pushes run one at a time and a newer pending run replaces the older, and each `release/**` commit and dispatch has its own group. `linux-packages.yml` runs only when called or dispatched, under its caller's concurrency. - `nightly.yml` is the one schedule, at 19:17 UTC: every suite in full on main, with core's Arm64 SSH tunnel tests and `build-linux.yml` extended, then `linux-packages.yml` with the Flatpak repository (arm64 too on Sundays, the second cron line), and the Release Build job, which builds and packages the app and every registry plugin as a tag does, unsigned, on `xcode-27`, and `ai-models.yml`, which regenerates the AI model catalog from models.dev and pushes it to gh-pages as `ai/models-v1.json`. No tag waits for it. GitHub mails a red run to whoever last edited the schedule. A push to main that changes `core/crates/ai/ai-models.json` runs `ai-models.yml` too, which publishes that file as committed. - macOS Tests runs the Unit and UI plans in full, with no shard, parallel, iteration or retry flag. -- `core.yml` runs the core on Windows x64 and Arm64 and on macOS, where the same job builds and tests the Swift bindings, and SQL Server's integrated login on Windows x64. The SSH tunnel tests through Windows' OpenSSH Server run on x64; Arm64, whose image installs the server in about 20 minutes, runs them nightly. +- `core.yml` runs the core on Windows x64 and Arm64 and on macOS, where the same job builds the macOS and iOS slices and tests the Swift bindings, and SQL Server's integrated login on Windows x64. iOS and Package Tests builds the Simulator's slice. The SSH tunnel tests through Windows' OpenSSH Server run on x64; Arm64, whose image installs the server in about 20 minutes, runs them nightly. - A `v*` tag runs only `release.yml`, a `linux-v*` tag only `release-linux.yml`, a `windows-v*` tag only `release-windows.yml`. The last two also run by dispatch: `release-windows.yml` then publishes nothing (`windows/RELEASING.md`), and `release-linux.yml` publishes nothing with `dry-run` and otherwise uploads a packaging fix (`linux/docs/releasing.md`). - `windows.yml`'s live job runs the interop tests against MySQL, SQL Server, ClickHouse, Cassandra, MongoDB and Redis on `windows-2025`, beside the x64 job (`windows/docs/decisions/0016-live-server-tests.md`). - `windows-grid-gate.yml` runs only by dispatch: the Windows data grid's timing and behavior gate on `windows-2025` and `windows-11-arm`, whose numbers vary too much between hosted runners to gate a merge (`windows/docs/decisions/0003-data-grid-control.md`, Gate). `windows.yml` runs the grid's tests on every change. @@ -47,7 +47,7 @@ paths: - `scripts/ci/detect-changed-paths.sh [--base ] [--head ] ` prints `true` or `false`. No base prints true; an all-zero base diffs from the merge base with `origin/main`. - Suites: `macos`, `plugins`, `ios`, `oracle`, `hana`, `swiftlint`, `linux` (`linux/`, `core/` and the Cargo workspace files at the top; no Markdown but `linux/CHANGELOG.md`, `linux/docs/regression-tests.md` and `linux/data/`), `linux-docs`, `linux-deps` (Cargo manifests and lock, toolchain, `deny.toml`, the Flatpak manifests, the Debian build dependencies), `packages` (Cargo manifests and lock, toolchain, Meson files, `linux/build-aux/` but its tests, `po/LINGUAS`; no Markdown), `core` (`core/`, `Cargo.toml`, `Cargo.lock`, `rust-toolchain.toml`, the FFI Swift package and what builds it; no Markdown), `windows` (`windows/`, `core/`, `Cargo.toml`, `Cargo.lock` and `rust-toolchain.toml` at the top; no Markdown), `release` (what the Release Build job reads) and `shipped` (`release` without `.github/`; `version.py check` reads it, and `macos` and `ios` for a test job a tag's run left out). -- `macos`, `release` and `shipped` also watch the core the app links: `core/` but its drivers, its crates' `tests/` and its Markdown, the Cargo workspace files and `apple/scripts/build-core.sh`. +- `macos`, `ios`, `release` and `shipped` also watch the core the apps link: `core/` but its drivers, its crates' `tests/` and its Markdown, the Cargo workspace files and `apple/scripts/build-core.sh`. - Every suite but `shipped` watches `ci.yml` and its own workflow. A path a suite newly reads joins its pattern in the same change. ## Runners diff --git a/.claude/rules/data-sync-storage.md b/.claude/rules/data-sync-storage.md index a3c85fe3d3..d988c7e439 100644 --- a/.claude/rules/data-sync-storage.md +++ b/.claude/rules/data-sync-storage.md @@ -25,6 +25,8 @@ paths: - "apple/TableProMobile/TableProMobile/Helpers/*Persistence.swift" - "apple/TableProMobile/TableProMobile/Helpers/LibraryFile.swift" - "apple/TableProMobile/TableProMobile/Platform/PastedSSHKeyMigration.swift" + - "apple/TableProMobile/TableProMobile/Platform/ManagedAppConfiguration.swift" + - "apple/TableProMobile/TableProMobile/Account/**/*" - "apple/Packages/TableProCore/Sources/TableProConnectionLibrary/LibraryFileRecords.swift" - "apple/Packages/TableProCore/Sources/TableProSync/**/*" - "apple/TablePro/Models/Connection/DatabaseConnection.swift" @@ -175,6 +177,9 @@ This path holds user data. A silent wrong answer here looks exactly like an empt | TablePro account: the device, the entitlement, the chosen server, a company server's license and entitlement keys | `Account/account.json` in Application Support, device-local, never synced | the core's `tablepro-account` through `AccountServices` | | The account's refresh token: tablepro.app's in the item earlier builds read, each company server's in its own | Keychain `com.TablePro.account.refreshToken`, and one item per company server, device-only | the core through `KeychainHostSecrets` | | The entitlement builds before the core kept, read once when `account.json` is missing so the update stays signed in | `Account/entitlement.jwt` in Application Support | the core (`legacy_entitlement_file`) | +| iOS: TablePro account, as on the Mac | `TableProMobile/Account/account.json` in Application Support, device-local, kept out of backups, never synced | the core's `tablepro-account` through `AccountModel` | +| iOS: the account's refresh tokens, named as on the Mac, and the device ID it registers, 32 random bytes made once | Keychain `com.TablePro.account.refreshToken` and one item per company server, `com.TablePro.account.deviceID`; this device only, after first unlock, in the app's own access group, not the widget's | the core through `KeychainHostSecrets`, `AccountDeviceID` | +| iOS: what an MDM sets for the app (core ADR 0055) | UserDefaults `com.apple.configuration.managed`, written only by the MDM | `ManagedAppConfiguration`, read by `OnboardingPreferences` and the account | | A license key an older build stored, until the key exchange trades it for an account; the digest of one the server refused | Keychain `com.TablePro.license.key`, UserDefaults `com.TablePro.license.setAside` | `StoredLicenseKey` | | Sidebar database and schema filters, recent tables | UserDefaults, device-local | `DatabaseTreeFilterStorage`, `RecentTablesStore` | | History drawer state | UserDefaults, device-local | `HistoryPanelPreferencesStorage` | diff --git a/.claude/skills/fix-issue/references/platform-apple.md b/.claude/skills/fix-issue/references/platform-apple.md index ef3546ac85..f14425cc55 100644 --- a/.claude/skills/fix-issue/references/platform-apple.md +++ b/.claude/skills/fix-issue/references/platform-apple.md @@ -43,7 +43,7 @@ The macOS app and the iOS app, with everything they build from. Every profile ha | `l10n` | none | strings, or plugin or package messages, changed. Passes only when every plugin and package string, and every string the last build of each app in the tree extracted, is in that app's catalog. Prints the `--add` command for each check that failed | | `docs` | `[docs-checkout]`, default `tablepro-docs` beside the main checkout | AGENTS Every change 4 applies, or a menu, shortcut, driver list or docs.tablepro.app link changed | -- `build`, `plugins`, `test`, `uitest`, `abi` and `package TableProFFI` first build the core the app links, with `apple/scripts/build-core.sh` for this Mac's arch, when the tree has none or a file it is built from changed after it. A first build takes several minutes. +- `build`, `plugins`, `test`, `uitest`, `abi` and `package TableProFFI` first build the core the apps link, with `apple/scripts/build-core.sh` for this Mac's arch, and `ios` adds the Simulator's slice, when the tree has none, lacks that slice, or a file it is built from changed after it. A rebuild keeps the slices the last one had. A first build takes several minutes. - Pick tests by the types you changed, not the test files you edited: `verify.sh` finds a type name in every test target of the tree. - Extra review pass: the ABI pass when PluginKit changed. - Test names, verdicts, the remedies `verify.sh` does not print, and red CI checks: `references/verification-apple.md`. diff --git a/.claude/skills/fix-issue/scripts/lib/platform-apple.sh b/.claude/skills/fix-issue/scripts/lib/platform-apple.sh index 606fa649ac..74e041786e 100644 --- a/.claude/skills/fix-issue/scripts/lib/platform-apple.sh +++ b/.claude/skills/fix-issue/scripts/lib/platform-apple.sh @@ -369,23 +369,41 @@ swiftlint_filtered_dirs() { # ---------------------------------------------------------------------------- steps -# The macOS project links the core (apple/project.yml, TableProFFI), and SwiftPM refuses to resolve it before -# apple/scripts/build-core.sh has built its binary target. Rebuilt for this Mac's architecture when a file it is -# built from changed after the last build. Fails the step when the core does not build. +# Both Apple projects link the core (TableProFFI), and SwiftPM refuses to resolve it before +# apple/scripts/build-core.sh has built its binary target. Rebuilt when a file it is built from changed after the last +# build, or when it lacks the slice this step needs: this Mac's architecture, plus the Simulator's for an iOS step. +# A rebuild keeps every slice the last one had, since each build replaces the XCFramework. Fails the step when the core +# does not build. ensure_core() { - local log="$1" built="$APPLE_ROOT/Packages/TableProFFI/Build/TableProFFIC.xcframework" changed code + local log="$1" needed="${2:-$(uname -m)}" built="$APPLE_ROOT/Packages/TableProFFI/Build/TableProFFIC.xcframework" + local changed code slices + slices="$(core_slices "$built")" if [ -d "$built" ]; then changed="$(cd "$REPO_ROOT" && find core Cargo.toml Cargo.lock rust-toolchain.toml apple/scripts/build-core.sh \ apple/scripts/lib/deployment-target.sh apple/scripts/lib/system-sqlite.sh \ -type f ! -name '*.md' -newer "$built" -print -quit 2> /dev/null)" - [ -z "$changed" ] && return 0 - note "core: $changed changed after the last core build, so it is rebuilt first" + if [ -n "$changed" ]; then + note "core: $changed changed after the last core build, so it is rebuilt first" + elif core_has_slice "$slices" "$needed"; then + return 0 + else + note "core: built without its $needed slice, so it is rebuilt first" + fi else note "core: not built in this tree, so it is built first" fi + # One macOS slice only, since build-core.sh takes arm64, x86_64 or both: a universal one already covers either. + if ! core_has_slice "$slices" "$needed"; then + case "$needed" in + arm64 | x86_64 | both) slices="$(printf '%s\n' $slices | grep -vxE 'arm64|x86_64|both')" ;; + esac + slices="$(printf '%s\n' $slices "$needed")" + fi + slices="$(printf '%s\n' $slices | sort -u | tr '\n' ' ')" require_tool cargo - echo "== apple/scripts/build-core.sh $(uname -m)" >> "$log" - nice -n 10 "$APPLE_ROOT/scripts/build-core.sh" "$(uname -m)" >> "$log" 2>&1 + echo "== apple/scripts/build-core.sh $slices" >> "$log" + # shellcheck disable=SC2086 + nice -n 10 "$APPLE_ROOT/scripts/build-core.sh" $slices >> "$log" 2>&1 code=$? [ $code -eq 0 ] && return 0 STATUS=FAIL @@ -393,6 +411,31 @@ ensure_core() { emit "$log" "$code" } +# grep reads every line rather than quitting at a match, which would leave printf a SIGPIPE under pipefail. +core_has_slice() { + case "$2" in + arm64 | x86_64) printf '%s\n' $1 | grep -xE "$2|both" > /dev/null ;; + *) printf '%s\n' $1 | grep -x "$2" > /dev/null ;; + esac +} + +# The build-core.sh slice names an XCFramework holds, read from its Info.plist. +core_slices() { + local plist="$1/Info.plist" ids + [ -f "$plist" ] || return 0 + ids="$(plutil -extract AvailableLibraries json -o - "$plist" 2> /dev/null \ + | python3 -c 'import json, sys; print("\n".join(l["LibraryIdentifier"] for l in json.load(sys.stdin)))' 2> /dev/null)" + printf '%s\n' "$ids" | while IFS= read -r id; do + case "$id" in + macos-arm64_x86_64) echo both ;; + macos-arm64) echo arm64 ;; + macos-x86_64) echo x86_64 ;; + ios-arm64) echo ios ;; + ios-arm64-simulator) echo ios-simulator ;; + esac + done +} + platform_parse() { local stem="${1%.log}" filters="${1%.log}.filters" [ -f "$filters" ] || filters=/dev/null @@ -638,6 +681,7 @@ platform_step() { if [ ! -d "$project" ]; then "$APPLE_ROOT/scripts/generate-project.sh" ios >> "$log" 2>&1 fi + ensure_core "$log" ios-simulator # CI names one simulator; this machine may not have it, so take the first available iPhone. simulator="$(xcrun simctl list devices available 2> /dev/null \ | grep -m1 -oE 'iPhone[^(]*\([0-9A-F-]{36}\)' | grep -oE '[0-9A-F-]{36}')" diff --git a/.github/workflows/core.yml b/.github/workflows/core.yml index 37d4864d74..c7fcd5ffb7 100644 --- a/.github/workflows/core.yml +++ b/.github/workflows/core.yml @@ -122,10 +122,11 @@ jobs: # Each importer reads its app's files from this platform's own places. - name: Importers from other apps run: cargo test --locked --target "$TARGET" -p tablepro-foreign-import - # Release with fat LTO, without the engines (core/docs/decisions/0010-macos-on-the-core.md). - - name: Build the static library and its Swift bindings + # Release with fat LTO, without the engines (core/docs/decisions/0010-macos-on-the-core.md). The iOS slice proves + # the core builds for an iPhone at the iOS app's floor on the system SQLite; ios-tests.yml builds the Simulator's. + - name: Build the static libraries and their Swift bindings if: ${{ !cancelled() && matrix.swift }} - run: apple/scripts/build-core.sh arm64 + run: apple/scripts/build-core.sh arm64 ios - name: Swift binding tests if: ${{ !cancelled() && matrix.swift }} run: swift test --package-path apple/Packages/TableProFFI diff --git a/.github/workflows/ios-tests.yml b/.github/workflows/ios-tests.yml index 988ae229f0..86c5103cc3 100644 --- a/.github/workflows/ios-tests.yml +++ b/.github/workflows/ios-tests.yml @@ -18,7 +18,8 @@ jobs: ios: name: iOS and Package Tests runs-on: xcode-27 - timeout-minutes: 50 + # The core's release build takes part of it when its cache is cold. + timeout-minutes: 70 env: DESTINATION: platform=iOS Simulator,name=iPhone 18 Pro defaults: @@ -38,6 +39,21 @@ jobs: GH_TOKEN: ${{ github.token }} run: scripts/download-libs.sh + - uses: dtolnay/rust-toolchain@683b588c487a69d01f6c6ddf40f036ff682cc2c8 # master + with: + toolchain: "1.98" + targets: aarch64-apple-ios-sim + + # Saved from main only, like core.yml's: a pull request's cache serves that pull request alone. + - uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 + with: + key: apple-core-ios-simulator + save-if: ${{ github.ref == 'refs/heads/main' }} + + # The app links the core for the TablePro account, and SwiftPM resolves nothing until its binary target exists. + - name: Build the shared core + run: scripts/build-core.sh ios-simulator + - name: Generate the Xcode project run: scripts/generate-project.sh ios diff --git a/ROADMAP.md b/ROADMAP.md index 388b0e60a8..38fdd4b0ec 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -591,8 +591,8 @@ Phase 7 runs now as its own lane, ahead of [Order](#order) (D-06). The account s - [ ] macOS - [ ] iOS - **T-09** iOS account: sign-in through `tablepro-account` via TableProFFI, the `tablepro-ios` OAuth client and the `ios` device platform - - [ ] server - - [ ] iOS + - [x] server + - [x] iOS - **T-10** Records in the core (`tablepro-records`): kinds, record ids, field classes, the field merge and the CloudKit mapping, one set for both providers - [ ] core - **T-11** Keys in the core (`tablepro-keys`): the end-to-end crypto, with signed logs, envelopes and recovery diff --git a/apple/AGENTS.md b/apple/AGENTS.md index 61c2240eef..ca6a9a6de4 100644 --- a/apple/AGENTS.md +++ b/apple/AGENTS.md @@ -28,7 +28,7 @@ Every capability is core, a module or a plugin. The first rule that fits decides - `Plugins/`: drivers and import/export formats as `.tableplugin` bundles, plus `TableProPluginKit`. Bundled plugins are the `copy: { destination: plugins }` targets in `project.yml`; the app never offers a registry install or update over one. - `Packages/`: `TableProCore` (both apps), `TableProMacCore` (macOS only, never in the iOS project), `TableProOracle`, `TableProEditor`, `TableProGrammars`. Edit PluginKit in `Plugins/TableProPluginKit/` only; `TableProCore` symlinks it. Never pass `SWIFT_VERSION=` to `xcodebuild`. - `Native/`: Rust and Go bridges. `Libs/`: static libraries from `scripts/download-libs.sh`, not in git. -- `Packages/TableProFFI`: the shared Rust core (`core/`) as the module `TableProFFI`. `scripts/build-core.sh` builds its XCFramework and generates its Swift from the same library, neither in git; then `swift test --package-path Packages/TableProFFI`. The app links it for the TablePro account (`core/docs/decisions/0010-macos-on-the-core.md`, `0044-sync-through-one-service-run-by-us-or-on-premises.md`), so SwiftPM resolves nothing in the macOS project until it is built; `verify.sh build` and `test` build it when stale. On Apple targets the core links the system SQLite the app opens its own files with, and `build-core.sh` fails when it would bundle its own or call a function newer than the deployment target. +- `Packages/TableProFFI`: the shared Rust core (`core/`) as the module `TableProFFI`. `scripts/build-core.sh` builds its XCFramework and generates its Swift from the same library, neither in git; then `swift test --package-path Packages/TableProFFI`. Both apps link it for the TablePro account (`core/docs/decisions/0010-macos-on-the-core.md`, `0047-the-apple-apps-sign-in-through-the-core.md`), so SwiftPM resolves nothing in either project until it is built with that app's slice; `verify.sh build`, `test` and `ios` build it when stale. On Apple targets the core links the system SQLite the app opens its own files with, and `build-core.sh` fails when it would bundle its own or call a function newer than the deployment target. The account's adapter over the core lives in `TablePro/Core/Services/Account/Shared/`, which the iOS app compiles too. - XcodeGen generates `TablePro.xcodeproj` and `TableProMobile/TableProMobile.xcodeproj`; never hand-edit them. Signing overrides go in `Configs/Secrets.xcconfig`. - Architecture lives in `.claude/rules/`: `plugin-system.md`, `connection-window.md`, `editor.md`, `theme.md` and `data-sync-storage.md`. @@ -38,7 +38,7 @@ From the repository root: ```bash apple/scripts/download-libs.sh # first time, and after a libs update -apple/scripts/build-core.sh arm64 # first time, and after a core change; verify.sh does it when stale +apple/scripts/build-core.sh arm64 ios-simulator # first time, and after a core change; verify.sh does it when stale. ios for a device apple/scripts/generate-project.sh [both|macos|ios] # after a project.yml or Configs/ edit, or a new, moved or deleted source file .claude/skills/fix-issue/scripts/verify.sh build .claude/skills/fix-issue/scripts/verify.sh test [|/()|/...] # none: the Unit plan diff --git a/apple/CONTRIBUTING.md b/apple/CONTRIBUTING.md index 88ea53e028..9c2a935bc4 100644 --- a/apple/CONTRIBUTING.md +++ b/apple/CONTRIBUTING.md @@ -11,7 +11,7 @@ This file covers the macOS and iOS apps in `apple/`, and every command in it run | SwiftLint | 0.65.1 | The version CI runs | | GitHub CLI | any | Optional: `scripts/download-libs.sh` falls back to `curl` | | Go | `toolchain` in `Native/HanaBridge/go.mod` | SAP HANA plugin only: run `scripts/build-hana.sh` with no argument before building `HanaDriver` or `AllPlugins`. When the installed `go` is another release, `go` switches to that toolchain itself | -| Rust | `rust-toolchain.toml` at the repository root | Through [rustup](https://rustup.rs), which installs it. The app links the shared core: run `scripts/build-core.sh arm64` (or `x86_64`) before the first build and after a change under `core/`. The Dameng plugin pins its own in `Native/DamengBridge/rust-toolchain.toml`: run `scripts/build-dameng.sh arm64` before building `DamengDriver` or `AllPlugins` | +| Rust | `rust-toolchain.toml` at the repository root | Through [rustup](https://rustup.rs), which installs it. Both apps link the shared core: run `scripts/build-core.sh arm64` (or `x86_64`) before the first build and after a change under `core/`, adding `ios-simulator` for the iOS app in the Simulator and `ios` for a device. The Dameng plugin pins its own in `Native/DamengBridge/rust-toolchain.toml`: run `scripts/build-dameng.sh arm64` before building `DamengDriver` or `AllPlugins` | Fork the repo on GitHub, then: diff --git a/apple/Packages/TableProFFI/Package.swift b/apple/Packages/TableProFFI/Package.swift index e342ad3a93..1b2da9df93 100644 --- a/apple/Packages/TableProFFI/Package.swift +++ b/apple/Packages/TableProFFI/Package.swift @@ -5,8 +5,10 @@ import PackageDescription // Keep generated bindings and their binary together so their UniFFI checksums agree. let package = Package( name: "TableProFFI", + // The apps' floors: project.yml and TableProMobile/project.yml, which build-core.sh builds the slices for. platforms: [ - .macOS(.v13) + .macOS(.v13), + .iOS(.v18) ], products: [ .library(name: "TableProFFI", targets: ["TableProFFI"]) diff --git a/apple/Packages/TableProFFI/Tests/TableProFFITests/AccountTests.swift b/apple/Packages/TableProFFI/Tests/TableProFFITests/AccountTests.swift index 3373c7f084..cad29730d9 100644 --- a/apple/Packages/TableProFFI/Tests/TableProFFITests/AccountTests.swift +++ b/apple/Packages/TableProFFI/Tests/TableProFFITests/AccountTests.swift @@ -91,7 +91,8 @@ private func config( managedServerUrl: String? = nil, allowOtherServers: Bool? = nil, machineId: String = macMachineId, - accountUrl: String? = nil + accountUrl: String? = nil, + client: AppClientTag = .macos ) -> AccountConfig { AccountConfig( accountUrl: accountUrl, @@ -104,7 +105,7 @@ private func config( callbackFinished: "", callbackUnknown: "", machineGuid: nil, - client: .macos, + client: client, machineId: machineId, policy: .read(values: ManagedPolicyValues( accountServerUrl: managedServerUrl, @@ -145,6 +146,22 @@ private func code(of error: any Error) -> String? { #expect(account.status().state == .signedOut) } +@Test func anIPhoneSignsInAsTheIOSClientThroughTheSameScheme() async throws { + let core = try Core(config: HostConfig(clientVersion: "test", storageDir: nil), secrets: KeychainItems()) + let session = ClosedSession() + let account = try await core.openAccount( + config: config(in: try folder(), client: .ios), browser: NoBrowser(), webAuthenticator: session, listener: Quiet() + ) + + await #expect(throws: CoreError.Cancelled) { try await account.signIn(cancel: nil) } + + let page = try #require(session.asked.first) + #expect(page.scheme == "app.tablepro") + #expect(page.url.contains("client_id=tablepro-ios")) + #expect(page.url.contains("redirect_uri=app.tablepro%3A%2Foauth%2Fcallback")) + #expect(account.status().state == .signedOut) +} + @Test func aManagedServerThatAllowsNoOtherHoldsTheMac() async throws { let core = try Core(config: HostConfig(clientVersion: "test", storageDir: nil), secrets: KeychainItems()) let account = try await core.openAccount( diff --git a/apple/RELEASING.md b/apple/RELEASING.md index 31929878b6..4c546a1cf3 100644 --- a/apple/RELEASING.md +++ b/apple/RELEASING.md @@ -195,7 +195,7 @@ gh workflow run withdraw.yml --ref v -f version=X.Y.Z By hand, on a Mac with the team's signing identity. 1. A PR raises `MARKETING_VERSION` and `CURRENT_PROJECT_VERSION` in `Configs/Version-iOS.xcconfig`. The build goes up on every upload. -2. `apple/scripts/download-libs.sh && apple/scripts/generate-project.sh ios`, then archive the `TableProMobile` scheme for Any iOS Device in Xcode. `Configs/Secrets.xcconfig` sets `POSTHOG_PROJECT_KEY` to the repository secret of that name; without it the build sends no usage data. +2. `apple/scripts/download-libs.sh && apple/scripts/build-core.sh ios && apple/scripts/generate-project.sh ios`, then archive the `TableProMobile` scheme for Any iOS Device in Xcode. `Configs/Secrets.xcconfig` sets `POSTHOG_PROJECT_KEY` to the repository secret of that name; without it the build sends no usage data. 3. Organizer: Distribute App to App Store Connect. App Privacy in App Store Connect lists the data types `TableProMobile/TableProMobile/PrivacyInfo.xcprivacy` declares. 4. TestFlight: test with internal testers. 5. Submit for App Store review, and release once approved. diff --git a/apple/TablePro/Core/Services/Account/AccountCoreSetup.swift b/apple/TablePro/Core/Services/Account/AccountCoreSetup.swift index dac9482f75..740a2781fb 100644 --- a/apple/TablePro/Core/Services/Account/AccountCoreSetup.swift +++ b/apple/TablePro/Core/Services/Account/AccountCoreSetup.swift @@ -4,30 +4,18 @@ // import Foundation +import TableProFFI // What the app hands the core's account when it opens it: where the account lives, this Mac's ID and the raw // managed values. The core resolves the server from them (core ADR 0044, App configuration). internal struct AccountCoreSetup: Equatable, Sendable { - // A local tablepro-cloud for a Debug run. The core takes them only from a build of it with debug assertions. - struct DevelopmentStack: Equatable, Sendable { - let accountURL: String - let apiURL: String - let entitlementKeys: [String] - let licenseKeys: [String] - - // TABLEPRO_API_URL is the API's origin, as for tablepro.app; the core takes the /v2 base. - var apiBase: String { - (apiURL.hasSuffix("/") ? String(apiURL.dropLast()) : apiURL) + "/v2" - } - } - let accountFile: URL // What builds before the core kept; read once, when accountFile is missing, so the update stays signed in. let legacyEntitlementFile: URL let machineID: String // The managed values as ManagedPolicyReader read them at launch: only what a configuration profile forces. let policy: ManagedPolicySnapshot - let developmentStack: DevelopmentStack? + let developmentStack: AccountDevelopmentStack? static func make( supportDirectory: URL, @@ -42,25 +30,27 @@ internal struct AccountCoreSetup: Equatable, Sendable { legacyEntitlementFile: folder.appendingPathComponent("entitlement.jwt"), machineID: machineID, policy: policy, - developmentStack: isDebugBuild ? developmentStack(environment) : nil + developmentStack: isDebugBuild ? AccountDevelopmentStack.read(environment) : nil ) } - // A core built without debug assertions refuses these and the account does not open; build one that takes them - // with CARGO_PROFILE_RELEASE_DEBUG_ASSERTIONS=true scripts/build-core.sh. - static func developmentStack(_ environment: [String: String]) -> DevelopmentStack? { - guard let account = environment["TABLEPRO_ACCOUNT_URL"], let api = environment["TABLEPRO_API_URL"] else { - return nil - } - return DevelopmentStack( - accountURL: account, - apiURL: api, - entitlementKeys: list(environment["TABLEPRO_ENTITLEMENT_KEYS"]), - licenseKeys: list(environment["TABLEPRO_LICENSE_KEYS"]) + func accountConfig(machine: MachineDescription) -> AccountConfig { + AccountConfig( + accountUrl: developmentStack?.accountURL, + apiUrl: developmentStack?.apiBase, + entitlementKeys: developmentStack?.entitlementKeys ?? [], + deviceName: machine.name, + appVersion: machine.appVersion, + osVersion: machine.osVersion, + accountFile: accountFile.path, + callbackFinished: "", + callbackUnknown: "", + machineGuid: nil, + client: .macos, + machineId: machineID, + policy: policy.coreArgument, + legacyEntitlementFile: legacyEntitlementFile.path, + licenseKeys: developmentStack?.licenseKeys ?? [] ) } - - private static func list(_ value: String?) -> [String] { - (value ?? "").split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } - } } diff --git a/apple/TablePro/Core/Services/Account/AccountError+CloudAPI.swift b/apple/TablePro/Core/Services/Account/AccountError+CloudAPI.swift new file mode 100644 index 0000000000..ad96cc8c66 --- /dev/null +++ b/apple/TablePro/Core/Services/Account/AccountError+CloudAPI.swift @@ -0,0 +1,29 @@ +// +// AccountError+CloudAPI.swift +// TablePro +// + +import Foundation +import TableProCloudAPI + +extension AccountError { + static func problem(_ problem: Components.Schemas.Problem) -> AccountError { + .server(status: Int(problem.status), code: problem.code) + } + + // The generated client wraps what a middleware or the transport throws. + static func from(_ error: any Error) -> AccountError { + switch error { + case let error as AccountError: + return error + case let error as ClientError: + return from(error.underlyingError) + case is CancellationError: + return .canceled + case let error as URLError where error.code == .cancelled: + return .canceled + default: + return .network(error.localizedDescription) + } + } +} diff --git a/apple/TablePro/Core/Services/Account/AccountKeychain.swift b/apple/TablePro/Core/Services/Account/AccountKeychain.swift index e31f9b99da..6916836db7 100644 --- a/apple/TablePro/Core/Services/Account/AccountKeychain.swift +++ b/apple/TablePro/Core/Services/Account/AccountKeychain.swift @@ -7,16 +7,10 @@ import Foundation // The account's refresh tokens for the core's HostSecrets, through the device-only Keychain and the same calls the // Swift session made before, so an update reads the item it left. -internal struct AccountKeychain: Sendable { - enum Failure: Error, Equatable { - case locked - case dismissed - case failed(String) - } - +internal struct AccountKeychain: AccountTokenKeychain { let keychain: any KeychainStoring - func refreshToken(signInKey: String?) throws(Failure) -> String? { + func refreshToken(signInKey: String?) throws(AccountKeychainFailure) -> String? { switch keychain.readStringResult(forKey: AccountRefreshTokenItem.key(signInKey: signInKey)) { case .found(let token): return token.isEmpty ? nil : token @@ -33,7 +27,7 @@ internal struct AccountKeychain: Sendable { } } - func storeRefreshToken(_ token: String, signInKey: String?) throws(Failure) { + func storeRefreshToken(_ token: String, signInKey: String?) throws(AccountKeychainFailure) { guard keychain.writeString(token, forKey: AccountRefreshTokenItem.key(signInKey: signInKey)) else { throw .failed("the Keychain did not store the item") } diff --git a/apple/TablePro/Core/Services/Account/AccountProfile.swift b/apple/TablePro/Core/Services/Account/AccountProfile+CloudAPI.swift similarity index 65% rename from apple/TablePro/Core/Services/Account/AccountProfile.swift rename to apple/TablePro/Core/Services/Account/AccountProfile+CloudAPI.swift index eb14a84599..49d983ab54 100644 --- a/apple/TablePro/Core/Services/Account/AccountProfile.swift +++ b/apple/TablePro/Core/Services/Account/AccountProfile+CloudAPI.swift @@ -1,37 +1,12 @@ // -// AccountProfile.swift +// AccountProfile+CloudAPI.swift // TablePro // import Foundation import TableProCloudAPI -internal struct AccountMembership: Equatable, Sendable, Identifiable { - let teamID: String - let teamName: String - let role: String - let hasSeat: Bool - - var id: String { teamID } - - // The roles tablepro-cloud lets write a team's library. The server still refuses a push it does not allow. - var writesTeamLibrary: Bool { - role == "owner" || role == "admin" || role == "editor" - } -} - -// GET /v2/me: who is signed in and the teams the account belongs to, with its role and seat in each. -internal struct AccountProfile: Equatable, Sendable { - let email: String - let name: String? - let memberships: [AccountMembership] - - init(email: String, name: String?, memberships: [AccountMembership]) { - self.email = email - self.name = name - self.memberships = memberships - } - +extension AccountProfile { init(_ me: Components.Schemas.Me) { let name = me.account.name?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" self.init( diff --git a/apple/TablePro/Core/Services/Account/AccountServices+Live.swift b/apple/TablePro/Core/Services/Account/AccountServices+Live.swift index 2c653e0ec4..da4e2b08f0 100644 --- a/apple/TablePro/Core/Services/Account/AccountServices+Live.swift +++ b/apple/TablePro/Core/Services/Account/AccountServices+Live.swift @@ -18,8 +18,8 @@ extension AccountServices { isDebugBuild: isDebugBuild ) let backend = CoreAccountBackend( - setup: setup, - machine: machine, + config: setup.accountConfig(machine: machine), + appVersion: machine.appVersion, keychain: AccountKeychain(keychain: environment.deviceOnlyKeychain) ) let services = AccountServices( diff --git a/apple/TablePro/Core/Services/Account/AccountServices.swift b/apple/TablePro/Core/Services/Account/AccountServices.swift index f8a15b28f5..eee56398d0 100644 --- a/apple/TablePro/Core/Services/Account/AccountServices.swift +++ b/apple/TablePro/Core/Services/Account/AccountServices.swift @@ -126,7 +126,7 @@ internal final class AccountServices: AccountBackendListener { policyCancellable = changes.sink { reader.yield($0) } policyTask = Task { [backend] in for await policy in readings { - await backend.applyPolicy(policy) + await backend.applyPolicy(policy.coreArgument) } } } @@ -382,7 +382,7 @@ internal final class AccountServices: AccountBackendListener { let entitlement = Entitlement(snapshot) var features: [ProFeature: ProFeatureAccess] = [:] for feature in ProFeature.allCases { - features[feature] = backend.featureAccess(feature) + features[feature] = backend.featureAccess(code: feature.rawValue) } let refresh: EntitlementRefreshState switch snapshot.problem { diff --git a/apple/TablePro/Core/Services/Account/AccountBackend.swift b/apple/TablePro/Core/Services/Account/Shared/AccountBackend.swift similarity index 82% rename from apple/TablePro/Core/Services/Account/AccountBackend.swift rename to apple/TablePro/Core/Services/Account/Shared/AccountBackend.swift index f259149e73..194c59eebd 100644 --- a/apple/TablePro/Core/Services/Account/AccountBackend.swift +++ b/apple/TablePro/Core/Services/Account/Shared/AccountBackend.swift @@ -4,10 +4,11 @@ // import Foundation +import TableProFFI // The server the account signs in to, as the core resolved it: a managed value, else the person's choice, else // tablepro.app (core/docs/decisions/0044-sync-through-one-service-run-by-us-or-on-premises.md, App configuration). -internal struct AccountServer: Equatable, Sendable { +nonisolated internal struct AccountServer: Equatable, Sendable { let apiOrigin: URL let accountOrigin: URL let host: String @@ -29,7 +30,7 @@ internal struct AccountServer: Equatable, Sendable { } } -internal enum AccountSignOutCause: Equatable, Sendable { +nonisolated internal enum AccountSignOutCause: Equatable, Sendable { case user case refreshRefused case deviceRevoked @@ -37,7 +38,7 @@ internal enum AccountSignOutCause: Equatable, Sendable { } // What the core holds about the account, read on its listener's thread and published on the main actor. -internal struct AccountSnapshot: Equatable, Sendable { +nonisolated internal struct AccountSnapshot: Equatable, Sendable { enum State: Equatable, Sendable { case signedOut case signedIn @@ -68,7 +69,7 @@ internal struct AccountSnapshot: Equatable, Sendable { } // The license a company server installed, as the core verified it. -internal struct AccountServerLicense: Equatable, Sendable { +nonisolated internal struct AccountServerLicense: Equatable, Sendable { enum State: Equatable, Sendable { case active // Past its end and inside the grace: everything still works. @@ -85,8 +86,17 @@ internal struct AccountServerLicense: Equatable, Sendable { let state: State } +// The core's gate for one feature code. +nonisolated internal enum ProFeatureAccess: Equatable, Sendable { + case available + case signedOut + case notIncluded + case expired + case refreshFailed +} + // A bearer with the /v2 base of the server that issued it, read together so neither is another server's. -internal struct AccountAccessToken: Equatable, Sendable { +nonisolated internal struct AccountAccessToken: Equatable, Sendable { let token: String let apiBaseURL: URL // The core's sign-in the token is of. @@ -98,16 +108,17 @@ internal protocol AccountBackendListener: AnyObject { func accountStatusChanged(signedOutBy cause: AccountSignOutCause?) } -// The core's AccountService seen from Swift, so the app and its tests share one adapter: TableProFFI in the app, -// a fake over FakeAccountServer in the tests. -internal protocol AccountBackend: AnyObject, Sendable { +// The core's AccountService seen from Swift, so both apps and their tests share one adapter: TableProFFI in the +// apps, a fake in the tests. +nonisolated internal protocol AccountBackend: AnyObject, Sendable { var machineID: String { get } // False until the account has read what the last run kept; until then it reads as signed out. var isRestored: Bool { get } func waitUntilRestored() async func status() -> AccountSnapshot - func featureAccess(_ feature: ProFeature) -> ProFeatureAccess + // By the entitlement's feature code, ProFeature's raw value on the Mac. + func featureAccess(code: String) -> ProFeatureAccess func server() -> AccountServer func license() -> AccountServerLicense? @@ -131,7 +142,7 @@ internal protocol AccountBackend: AnyObject, Sendable { // The managed values read again. When they no longer allow the server signed in to, the core calls it no more // until the next launch (core/docs/decisions/0055-managed-policies-for-the-sync-provider-and-tablepro-app-traffic.md). - func applyPolicy(_ policy: ManagedPolicySnapshot) async + func applyPolicy(_ policy: ManagedPolicyArg) async // False while the organization holds the app to its own server: the share-link read and the AI catalog refresh // ask before any request to tablepro.app. func allowsTableProRequests() async -> Bool diff --git a/apple/TablePro/Core/Services/Account/Shared/AccountCodes.swift b/apple/TablePro/Core/Services/Account/Shared/AccountCodes.swift new file mode 100644 index 0000000000..0b06b9264c --- /dev/null +++ b/apple/TablePro/Core/Services/Account/Shared/AccountCodes.swift @@ -0,0 +1,22 @@ +// +// AccountCodes.swift +// TablePro +// + +import Foundation + +// Codes a newer server adds read as neutral text, never as a failure. +nonisolated internal enum AccountCodes { + // A Linux app reports its distribution as the OS version ("Fedora 43"), and the iOS app its system with it + // ("iPadOS 26.1"). + static func systemName(platform: String, osVersion: String) -> String { + switch platform { + case "macos": + return osVersion.isEmpty ? "macOS" : String(format: String(localized: "macOS %@"), osVersion) + case "linux": + return osVersion.isEmpty ? "Linux" : osVersion + default: + return osVersion + } + } +} diff --git a/apple/TablePro/Core/Services/Account/Shared/AccountDevelopmentStack.swift b/apple/TablePro/Core/Services/Account/Shared/AccountDevelopmentStack.swift new file mode 100644 index 0000000000..b3e9f8db53 --- /dev/null +++ b/apple/TablePro/Core/Services/Account/Shared/AccountDevelopmentStack.swift @@ -0,0 +1,36 @@ +// +// AccountDevelopmentStack.swift +// TablePro +// + +import Foundation + +// A local tablepro-cloud for a Debug run, named by the run's environment. The core takes it only from a build of it +// with debug assertions; build one that does with CARGO_PROFILE_RELEASE_DEBUG_ASSERTIONS=true scripts/build-core.sh. +nonisolated internal struct AccountDevelopmentStack: Equatable, Sendable { + let accountURL: String + let apiURL: String + let entitlementKeys: [String] + let licenseKeys: [String] + + // TABLEPRO_API_URL is the API's origin, as for tablepro.app; the core takes the /v2 base. + var apiBase: String { + (apiURL.hasSuffix("/") ? String(apiURL.dropLast()) : apiURL) + "/v2" + } + + static func read(_ environment: [String: String]) -> AccountDevelopmentStack? { + guard let account = environment["TABLEPRO_ACCOUNT_URL"], let api = environment["TABLEPRO_API_URL"] else { + return nil + } + return AccountDevelopmentStack( + accountURL: account, + apiURL: api, + entitlementKeys: list(environment["TABLEPRO_ENTITLEMENT_KEYS"]), + licenseKeys: list(environment["TABLEPRO_LICENSE_KEYS"]) + ) + } + + private static func list(_ value: String?) -> [String] { + (value ?? "").split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } + } +} diff --git a/apple/TablePro/Core/Services/Account/AccountDevice.swift b/apple/TablePro/Core/Services/Account/Shared/AccountDevice.swift similarity index 72% rename from apple/TablePro/Core/Services/Account/AccountDevice.swift rename to apple/TablePro/Core/Services/Account/Shared/AccountDevice.swift index 547c9a6056..9ba703958a 100644 --- a/apple/TablePro/Core/Services/Account/AccountDevice.swift +++ b/apple/TablePro/Core/Services/Account/Shared/AccountDevice.swift @@ -6,10 +6,10 @@ import Foundation // A device of the account as the core lists it, or names it in a device_limit_reached answer. -internal struct AccountDevice: Equatable, Sendable, Identifiable { +nonisolated internal struct AccountDevice: Equatable, Sendable, Identifiable { let id: String - // The core tells this Mac apart by its machine ID, which it does not hand out for other devices. - let isThisMac: Bool + // The core tells this device apart by its machine ID, which it does not hand out for other devices. + let isThisDevice: Bool let name: String let platform: String let osVersion: String diff --git a/apple/TablePro/Core/Services/Account/AccountError.swift b/apple/TablePro/Core/Services/Account/Shared/AccountError.swift similarity index 60% rename from apple/TablePro/Core/Services/Account/AccountError.swift rename to apple/TablePro/Core/Services/Account/Shared/AccountError.swift index 14483eb80c..c23048b3dc 100644 --- a/apple/TablePro/Core/Services/Account/AccountError.swift +++ b/apple/TablePro/Core/Services/Account/Shared/AccountError.swift @@ -4,9 +4,8 @@ // import Foundation -import TableProCloudAPI -internal enum AccountError: Error, Equatable { +nonisolated internal enum AccountError: Error, Equatable { enum OfflineFileProblem: Equatable, Sendable { case otherMachine // Another account's file, on a Mac signed in to this one. @@ -17,14 +16,14 @@ internal enum AccountError: Error, Equatable { } enum CompanyServerProblem: Equatable, Sendable { - // Not an https origin, or http away from this Mac. + // Not an https origin, or http away from this device. case invalidAddress // Its metadata or OpenID configuration does not name a TablePro server at this address. case notATableProServer case licenseMissing // The license does not verify with a key this build ships, or names another server. case licenseInvalid - // A configuration profile sets the server, so the person cannot choose another. + // The organization sets the server, so the person cannot choose another. case managed // A company server takes neither a license key nor an offline file. case unsupported @@ -44,27 +43,7 @@ internal enum AccountError: Error, Equatable { case signOutFirst } -extension AccountError { - static func problem(_ problem: Components.Schemas.Problem) -> AccountError { - .server(status: Int(problem.status), code: problem.code) - } - - // The generated client wraps what a middleware or the transport throws. - static func from(_ error: any Error) -> AccountError { - switch error { - case let error as AccountError: - return error - case let error as ClientError: - return from(error.underlyingError) - case is CancellationError: - return .canceled - case let error as URLError where error.code == .cancelled: - return .canceled - default: - return .network(error.localizedDescription) - } - } - +nonisolated extension AccountError { var problemCode: String? { guard case .server(_, let code) = self else { return nil } return code diff --git a/apple/TablePro/Core/Services/Account/Shared/AccountProfile.swift b/apple/TablePro/Core/Services/Account/Shared/AccountProfile.swift new file mode 100644 index 0000000000..3cd8c733c0 --- /dev/null +++ b/apple/TablePro/Core/Services/Account/Shared/AccountProfile.swift @@ -0,0 +1,27 @@ +// +// AccountProfile.swift +// TablePro +// + +import Foundation + +nonisolated internal struct AccountMembership: Equatable, Sendable, Identifiable { + let teamID: String + let teamName: String + let role: String + let hasSeat: Bool + + var id: String { teamID } + + // The roles tablepro-cloud lets write a team's library. The server still refuses a push it does not allow. + var writesTeamLibrary: Bool { + role == "owner" || role == "admin" || role == "editor" + } +} + +// GET /v2/me: who is signed in and the teams the account belongs to, with its role and seat in each. +nonisolated internal struct AccountProfile: Equatable, Sendable { + let email: String + let name: String? + let memberships: [AccountMembership] +} diff --git a/apple/TablePro/Core/Services/Account/AccountRefreshTokenItem.swift b/apple/TablePro/Core/Services/Account/Shared/AccountRefreshTokenItem.swift similarity index 91% rename from apple/TablePro/Core/Services/Account/AccountRefreshTokenItem.swift rename to apple/TablePro/Core/Services/Account/Shared/AccountRefreshTokenItem.swift index 6f23851e14..cbc843a212 100644 --- a/apple/TablePro/Core/Services/Account/AccountRefreshTokenItem.swift +++ b/apple/TablePro/Core/Services/Account/Shared/AccountRefreshTokenItem.swift @@ -7,7 +7,7 @@ import Foundation // The Keychain items the core keeps the account's refresh tokens in, device-only. tablepro.app's is the item builds // before the core wrote, so an update stays signed in; a company server's carries the core's key for that server. -internal enum AccountRefreshTokenItem { +nonisolated internal enum AccountRefreshTokenItem { static let production = "com.TablePro.account.refreshToken" static func key(signInKey: String?) -> String { diff --git a/apple/TablePro/Core/Services/Account/CoreAccountBackend.swift b/apple/TablePro/Core/Services/Account/Shared/CoreAccountBackend.swift similarity index 84% rename from apple/TablePro/Core/Services/Account/CoreAccountBackend.swift rename to apple/TablePro/Core/Services/Account/Shared/CoreAccountBackend.swift index 23f7383014..4a0057576c 100644 --- a/apple/TablePro/Core/Services/Account/CoreAccountBackend.swift +++ b/apple/TablePro/Core/Services/Account/Shared/CoreAccountBackend.swift @@ -6,11 +6,12 @@ import Foundation import os import TableProFFI +import TableProLogRedaction // The core's AccountService (core/docs/decisions/0047-the-apple-apps-sign-in-through-the-core.md). It opens on a task // at launch and restores the last run's sign-in after that; until then the account reads as signed out, and a call // waits for the open. -internal final class CoreAccountBackend: AccountBackend, @unchecked Sendable { +nonisolated internal final class CoreAccountBackend: AccountBackend, @unchecked Sendable { private static let logger = Logger(subsystem: "com.TablePro", category: "CoreAccountBackend") let machineID: String @@ -21,16 +22,16 @@ internal final class CoreAccountBackend: AccountBackend, @unchecked Sendable { private let opened = OSAllocatedUnfairLock(initialState: nil) private let opening: Task - init(setup: AccountCoreSetup, machine: MachineDescription, keychain: AccountKeychain) { - machineID = setup.machineID - isDevelopmentStack = setup.developmentStack != nil + // Each app's own config: its client, machine ID, files and managed values. + init(config: AccountConfig, appVersion: String, keychain: any AccountTokenKeychain) { + machineID = config.machineId ?? "" + isDevelopmentStack = config.apiUrl != nil listenerBridge = CoreAccountListener(restored: restored) - let config = Self.config(setup, machine: machine) let (authenticator, listener, opened, restored) = (authenticator, listenerBridge, opened, restored) opening = Task.detached(priority: .userInitiated) { do { let core = try Core( - config: HostConfig(clientVersion: machine.appVersion, storageDir: nil), + config: HostConfig(clientVersion: appVersion, storageDir: nil), secrets: KeychainHostSecrets(keychain: keychain) ) let service = try await core.openAccount( @@ -44,7 +45,9 @@ internal final class CoreAccountBackend: AccountBackend, @unchecked Sendable { await listener.notify(signedOutBy: nil) return service } catch { - Self.logger.error("The account did not open: \(error.publicLogShape, privacy: .public)") + Self.logger.error( + "The account did not open: \(LogRedaction.publicDescription(of: error), privacy: .public)" + ) restored.mark(.opened) restored.mark(.restored) await listener.notify(signedOutBy: nil) @@ -66,27 +69,6 @@ internal final class CoreAccountBackend: AccountBackend, @unchecked Sendable { listenerBridge.target = listener } - private static func config(_ setup: AccountCoreSetup, machine: MachineDescription) -> AccountConfig { - let stack = setup.developmentStack - return AccountConfig( - accountUrl: stack?.accountURL, - apiUrl: stack?.apiBase, - entitlementKeys: stack?.entitlementKeys ?? [], - deviceName: machine.name, - appVersion: machine.appVersion, - osVersion: machine.osVersion, - accountFile: setup.accountFile.path, - callbackFinished: "", - callbackUnknown: "", - machineGuid: nil, - client: .macos, - machineId: setup.machineID, - policy: setup.policy.coreArgument, - legacyEntitlementFile: setup.legacyEntitlementFile.path, - licenseKeys: stack?.licenseKeys ?? [] - ) - } - private var service: AccountService? { opened.withLock { $0 } } @@ -103,9 +85,9 @@ internal final class CoreAccountBackend: AccountBackend, @unchecked Sendable { return CoreAccountMapping.snapshot(service.status()) } - func featureAccess(_ feature: ProFeature) -> ProFeatureAccess { + func featureAccess(code: String) -> ProFeatureAccess { guard let service else { return .signedOut } - return CoreAccountMapping.access(service.featureAccess(feature: feature.rawValue)) + return CoreAccountMapping.access(service.featureAccess(feature: code)) } func server() -> AccountServer { @@ -183,9 +165,9 @@ internal final class CoreAccountBackend: AccountBackend, @unchecked Sendable { await service.accessTokenRejected(token: token) } - func applyPolicy(_ policy: ManagedPolicySnapshot) async { + func applyPolicy(_ policy: ManagedPolicyArg) async { guard let service = await opening.value else { return } - service.applyPolicy(policy: policy.coreArgument) + service.applyPolicy(policy: policy) } // An account that did not open holds no values to allow anything by. @@ -220,7 +202,9 @@ internal final class CoreAccountBackend: AccountBackend, @unchecked Sendable { } catch let error as CoreError { guard let failure = CoreAccountMapping.signInError(error, during: operation) else { return } if CoreAccountMapping.keptSignIn(before: before, after: service.status()) { - logger.notice("Signed in; what followed failed: \(failure.publicLogShape, privacy: .public)") + logger.notice( + "Signed in; what followed failed: \(LogRedaction.publicDescription(of: failure), privacy: .public)" + ) return } throw failure @@ -233,7 +217,7 @@ internal final class CoreAccountBackend: AccountBackend, @unchecked Sendable { // The core calls the callbacks below on threads it lets block; each hops to the main actor and waits there. // Shows the sign-in page in the window that asked for it, and returns the app.tablepro: redirect. -private final class CoreWebAuthenticator: HostWebAuthenticator, @unchecked Sendable { +nonisolated private final class CoreWebAuthenticator: HostWebAuthenticator, @unchecked Sendable { private let current = OSAllocatedUnfairLock<(any WebAuthenticating)?>(initialState: nil) func use(_ authenticator: (any WebAuthenticating)?) { @@ -270,14 +254,15 @@ private final class CoreWebAuthenticator: HostWebAuthenticator, @unchecked Senda } } -// The Mac signs in through its web authenticator; the core asks the loopback browser only of a client that has none. -private final class NoLoopbackBrowser: HostBrowser, @unchecked Sendable { +// The Apple apps sign in through their web authenticator; the core asks the loopback browser only of a client that has +// none. +nonisolated private final class NoLoopbackBrowser: HostBrowser, @unchecked Sendable { func openUrl(url: String) throws { - throw HostBrowserError.Failed(detail: "the Mac signs in through its web authenticator") + throw HostBrowserError.Failed(detail: "the app signs in through its web authenticator") } } -private final class CoreAccountListener: AccountListener, @unchecked Sendable { +nonisolated private final class CoreAccountListener: AccountListener, @unchecked Sendable { // Set once at launch and read only in notify, both on the main actor. nonisolated(unsafe) weak var target: (any AccountBackendListener)? private let restored: RestoredLatch @@ -305,7 +290,7 @@ private final class CoreAccountListener: AccountListener, @unchecked Sendable { } // The core can publish the restored status before openAccount returns the service that reads it, so both count. -private final class RestoredLatch: Sendable { +nonisolated private final class RestoredLatch: Sendable { enum Step { case opened case restored @@ -350,7 +335,7 @@ private final class RestoredLatch: Sendable { } } -private final class BlockingResult: @unchecked Sendable { +nonisolated private final class BlockingResult: @unchecked Sendable { private let semaphore = DispatchSemaphore(value: 0) private let value = OSAllocatedUnfairLock(initialState: nil) diff --git a/apple/TablePro/Core/Services/Account/CoreAccountMapping.swift b/apple/TablePro/Core/Services/Account/Shared/CoreAccountMapping.swift similarity index 98% rename from apple/TablePro/Core/Services/Account/CoreAccountMapping.swift rename to apple/TablePro/Core/Services/Account/Shared/CoreAccountMapping.swift index f2964d7fda..cc3493fc93 100644 --- a/apple/TablePro/Core/Services/Account/CoreAccountMapping.swift +++ b/apple/TablePro/Core/Services/Account/Shared/CoreAccountMapping.swift @@ -8,7 +8,7 @@ import TableProFFI // The core's account records and errors in the app's terms. Codes are the core's stable `code()` strings // (core/crates/account/src/{account_error,server,license}.rs). -internal enum CoreAccountMapping { +nonisolated internal enum CoreAccountMapping { enum Operation { case signIn case licenseKey @@ -74,7 +74,7 @@ internal enum CoreAccountMapping { static func device(_ info: DeviceInfo) -> AccountDevice { AccountDevice( id: info.id, - isThisMac: info.isThisMachine, + isThisDevice: info.isThisMachine, name: info.name, platform: info.platform, osVersion: info.osVersion, diff --git a/apple/TablePro/Core/Services/Account/Entitlement.swift b/apple/TablePro/Core/Services/Account/Shared/Entitlement.swift similarity index 92% rename from apple/TablePro/Core/Services/Account/Entitlement.swift rename to apple/TablePro/Core/Services/Account/Shared/Entitlement.swift index 269223832e..7e86067db3 100644 --- a/apple/TablePro/Core/Services/Account/Entitlement.swift +++ b/apple/TablePro/Core/Services/Account/Shared/Entitlement.swift @@ -5,7 +5,7 @@ import Foundation -internal struct EntitlementLicense: Equatable, Sendable { +nonisolated internal struct EntitlementLicense: Equatable, Sendable { struct Team: Equatable, Sendable { let id: String let name: String @@ -23,7 +23,7 @@ internal struct EntitlementLicense: Equatable, Sendable { } // The entitlement the core verified, for display. Only the core's gate decides what it unlocks. -internal struct Entitlement: Equatable, Sendable { +nonisolated internal struct Entitlement: Equatable, Sendable { let accountID: String let features: Set let licenses: [EntitlementLicense] diff --git a/apple/TablePro/Core/Services/Account/KeychainHostSecrets.swift b/apple/TablePro/Core/Services/Account/Shared/KeychainHostSecrets.swift similarity index 62% rename from apple/TablePro/Core/Services/Account/KeychainHostSecrets.swift rename to apple/TablePro/Core/Services/Account/Shared/KeychainHostSecrets.swift index 20dd06b823..99cc966863 100644 --- a/apple/TablePro/Core/Services/Account/KeychainHostSecrets.swift +++ b/apple/TablePro/Core/Services/Account/Shared/KeychainHostSecrets.swift @@ -6,19 +6,32 @@ import Foundation import TableProFFI -// The core's secret store on the Mac. Only the account asks it for anything: the Mac keeps its connections' and AI -// providers' secrets in Swift until their slices move (core ADR 0010). -internal final class KeychainHostSecrets: HostSecrets, @unchecked Sendable { - private let keychain: AccountKeychain +nonisolated internal enum AccountKeychainFailure: Error, Equatable { + case locked + case dismissed + case failed(String) +} + +// Each app's device-only Keychain items for the account's refresh tokens, named by AccountRefreshTokenItem. +nonisolated internal protocol AccountTokenKeychain: Sendable { + func refreshToken(signInKey: String?) throws(AccountKeychainFailure) -> String? + func storeRefreshToken(_ token: String, signInKey: String?) throws(AccountKeychainFailure) + func deleteRefreshToken(signInKey: String?) +} + +// The core's secret store in the Apple apps. Only the account asks it for anything: they keep their connections' and +// AI providers' secrets in Swift until their slices move (core ADR 0010). +nonisolated internal final class KeychainHostSecrets: HostSecrets, @unchecked Sendable { + private let keychain: any AccountTokenKeychain - init(keychain: AccountKeychain) { + init(keychain: any AccountTokenKeychain) { self.keychain = keychain } func loadItem(item: SecretItemTag) throws -> SecretString? { do { return try keychain.refreshToken(signInKey: try Self.signInKey(item)) - } catch let failure as AccountKeychain.Failure { + } catch let failure as AccountKeychainFailure { throw Self.error(failure) } } @@ -26,7 +39,7 @@ internal final class KeychainHostSecrets: HostSecrets, @unchecked Sendable { func storeItem(item: SecretItemTag, secret: SecretString) throws { do { try keychain.storeRefreshToken(secret, signInKey: try Self.signInKey(item)) - } catch let failure as AccountKeychain.Failure { + } catch let failure as AccountKeychainFailure { throw Self.error(failure) } } @@ -55,7 +68,7 @@ internal final class KeychainHostSecrets: HostSecrets, @unchecked Sendable { throw Self.notHere } - private static let notHere = HostSecretError.Unavailable(detail: "the Mac keeps this secret in Swift") + private static let notHere = HostSecretError.Unavailable(detail: "the app keeps this secret in Swift") // Nil is tablepro.app's item. private static func signInKey(_ item: SecretItemTag) throws -> String? { @@ -69,7 +82,7 @@ internal final class KeychainHostSecrets: HostSecrets, @unchecked Sendable { } } - private static func error(_ failure: AccountKeychain.Failure) -> HostSecretError { + private static func error(_ failure: AccountKeychainFailure) -> HostSecretError { switch failure { case .locked: .Locked case .dismissed: .Dismissed diff --git a/apple/TablePro/Core/Services/Account/WebAuthenticator.swift b/apple/TablePro/Core/Services/Account/Shared/WebAuthenticator.swift similarity index 91% rename from apple/TablePro/Core/Services/Account/WebAuthenticator.swift rename to apple/TablePro/Core/Services/Account/Shared/WebAuthenticator.swift index e5ed5ed475..59d1161a5b 100644 --- a/apple/TablePro/Core/Services/Account/WebAuthenticator.swift +++ b/apple/TablePro/Core/Services/Account/Shared/WebAuthenticator.swift @@ -3,7 +3,6 @@ // TablePro // -import AppKit import AuthenticationServices import Foundation @@ -18,14 +17,15 @@ extension WebAuthenticating { func cancel() {} } -// Opens the account pages in an ASWebAuthenticationSession sheet and returns the app.tablepro: redirect. +// Opens the account pages in an ASWebAuthenticationSession sheet over the anchor's window and returns the +// app.tablepro: redirect. @MainActor internal final class WebAuthenticationSessionAuthenticator: NSObject, WebAuthenticating, ASWebAuthenticationPresentationContextProviding { - private let anchor: () -> NSWindow? + private let anchor: () -> ASPresentationAnchor? private var session: ASWebAuthenticationSession? - init(anchor: @escaping () -> NSWindow? = { NSApp.keyWindow ?? NSApp.mainWindow }) { + init(anchor: @escaping () -> ASPresentationAnchor?) { self.anchor = anchor } @@ -41,7 +41,7 @@ internal final class WebAuthenticationSessionAuthenticator: NSObject, WebAuthent } } let session: ASWebAuthenticationSession - if #available(macOS 14.4, *) { + if #available(macOS 14.4, iOS 17.4, *) { session = ASWebAuthenticationSession( url: url, callback: .customScheme(callbackScheme), diff --git a/apple/TablePro/Models/Settings/ProFeature.swift b/apple/TablePro/Models/Settings/ProFeature.swift index 097a22179a..2ee4924021 100644 --- a/apple/TablePro/Models/Settings/ProFeature.swift +++ b/apple/TablePro/Models/Settings/ProFeature.swift @@ -93,11 +93,3 @@ internal enum ProFeature: String, CaseIterable { String(format: String(localized: "%@ needs a paid plan"), displayName) } } - -internal enum ProFeatureAccess: Equatable { - case available - case signedOut - case notIncluded - case expired - case refreshFailed -} diff --git a/apple/TablePro/Resources/ThirdPartyLicenses/licenses.yml b/apple/TablePro/Resources/ThirdPartyLicenses/licenses.yml index a0f8a0524e..5d90086e58 100644 --- a/apple/TablePro/Resources/ThirdPartyLicenses/licenses.yml +++ b/apple/TablePro/Resources/ThirdPartyLicenses/licenses.yml @@ -771,9 +771,9 @@ textFile: texts/tablepro-core-crates.txt source: manual patched: false - platforms: [macos] - notes: The crates the core library links (scripts/build-core.sh, no engines). scripts/update-core-licenses.sh writes - the text from Cargo.lock with cargo-about, and core.yml fails while it is out of date. + platforms: [macos, ios] + notes: The crates the core library links in both apps (scripts/build-core.sh, no engines). scripts/update-core-licenses.sh + writes the text from Cargo.lock with cargo-about, and core.yml fails while it is out of date. - id: swift-argument-parser name: swift-argument-parser version: 1.8.2 diff --git a/apple/TablePro/Resources/ThirdPartyLicenses/texts/tablepro-core-crates.txt b/apple/TablePro/Resources/ThirdPartyLicenses/texts/tablepro-core-crates.txt index b0a8f4e008..81d918f159 100644 --- a/apple/TablePro/Resources/ThirdPartyLicenses/texts/tablepro-core-crates.txt +++ b/apple/TablePro/Resources/ThirdPartyLicenses/texts/tablepro-core-crates.txt @@ -3104,6 +3104,7 @@ MIT License Used by: cfg-if 1.0.4 oauth2 5.0.0 + openssl-probe 0.2.1 socket2 0.6.5 Copyright (c) 2014 Alex Crichton diff --git a/apple/TablePro/Views/Account/DeviceLimitSheet.swift b/apple/TablePro/Views/Account/DeviceLimitSheet.swift index 44560203c7..c79b64f171 100644 --- a/apple/TablePro/Views/Account/DeviceLimitSheet.swift +++ b/apple/TablePro/Views/Account/DeviceLimitSheet.swift @@ -142,8 +142,8 @@ internal enum AccountDeviceText { } // This Mac is the one showing the list, so it is seen now whatever the server last recorded. - static func detail(system: String, lastSeenAt: Date, isThisMac: Bool) -> String { - guard isThisMac else { return detail(system: system, lastSeenAt: lastSeenAt) } + static func detail(system: String, lastSeenAt: Date, isThisDevice: Bool) -> String { + guard isThisDevice else { return detail(system: system, lastSeenAt: lastSeenAt) } return String(format: String(localized: "%@ ยท %@"), String(localized: "This Mac"), detail(system: system, lastSeenAt: Date())) } diff --git a/apple/TablePro/Views/Settings/Account/AccountSettingsContent.swift b/apple/TablePro/Views/Settings/Account/AccountSettingsContent.swift index b093da0b34..c65b0e86c4 100644 --- a/apple/TablePro/Views/Settings/Account/AccountSettingsContent.swift +++ b/apple/TablePro/Views/Settings/Account/AccountSettingsContent.swift @@ -58,12 +58,12 @@ internal struct AccountSettingsContent: Equatable { let name: String let system: String let lastSeenAt: Date - let isThisMac: Bool + let isThisDevice: Bool // Set while the device's offline file is valid, which keeps it from being removed. let offlineUntil: Date? var canRemove: Bool { - !isThisMac && offlineUntil == nil + !isThisDevice && offlineUntil == nil } } @@ -281,12 +281,12 @@ internal struct AccountSettingsContent: Equatable { name: device.name, system: AccountCodes.systemName(platform: device.platform, osVersion: device.osVersion), lastSeenAt: device.lastSeenAt, - isThisMac: device.isThisMac, + isThisDevice: device.isThisDevice, offlineUntil: device.offlineFileValid(at: now) ? device.offlineUntil : nil ) } .sorted { lhs, rhs in - if lhs.isThisMac != rhs.isThisMac { return lhs.isThisMac } + if lhs.isThisDevice != rhs.isThisDevice { return lhs.isThisDevice } return lhs.lastSeenAt > rhs.lastSeenAt } } @@ -365,8 +365,7 @@ private extension EntitlementRefreshState { } } -// Codes a newer server adds read as neutral text, never as a failure. -internal enum AccountCodes { +extension AccountCodes { static func planName(_ code: String) -> String { switch code { case "starter": String(localized: "Pro") @@ -398,16 +397,4 @@ internal enum AccountCodes { default: nil } } - - // A Linux app reports its distribution as the OS version ("Fedora 43"). - static func systemName(platform: String, osVersion: String) -> String { - switch platform { - case "macos": - return osVersion.isEmpty ? "macOS" : String(format: String(localized: "macOS %@"), osVersion) - case "linux": - return osVersion.isEmpty ? "Linux" : osVersion - default: - return osVersion - } - } } diff --git a/apple/TablePro/Views/Settings/Account/AccountSettingsView.swift b/apple/TablePro/Views/Settings/Account/AccountSettingsView.swift index 0c4f8de735..bab743e793 100644 --- a/apple/TablePro/Views/Settings/Account/AccountSettingsView.swift +++ b/apple/TablePro/Views/Settings/Account/AccountSettingsView.swift @@ -164,7 +164,7 @@ private struct AccountIdentitySection: View { Button(String(localized: "Sign In")) { Task { - await model.signIn(using: WebAuthenticationSessionAuthenticator()) + await model.signIn(using: WebAuthenticationSessionAuthenticator { NSApp.keyWindow ?? NSApp.mainWindow }) } } .disabled(model.isBusy) @@ -522,7 +522,7 @@ private struct AccountDeviceRow: View { var body: some View { SettingsRecordRow( title: device.name, - subtitle: AccountDeviceText.detail(system: device.system, lastSeenAt: device.lastSeenAt, isThisMac: device.isThisMac) + subtitle: AccountDeviceText.detail(system: device.system, lastSeenAt: device.lastSeenAt, isThisDevice: device.isThisDevice) ) { if let offlineUntil = device.offlineUntil { Text(AccountDeviceText.offlineFile(until: offlineUntil)) diff --git a/apple/TableProMobile/TableProMobile/Account/AccountError+Mobile.swift b/apple/TableProMobile/TableProMobile/Account/AccountError+Mobile.swift new file mode 100644 index 0000000000..3a77045ebe --- /dev/null +++ b/apple/TableProMobile/TableProMobile/Account/AccountError+Mobile.swift @@ -0,0 +1,44 @@ +import Foundation + +// The iOS app's wording for what the account's calls can end with. A license key and an offline file are the Mac's. +nonisolated extension AccountError { + // Nil when there is nothing to say: the person closed the sign-in sheet or declined on the confirmation page. + var mobileDescription: String? { + switch self { + case .canceled, .oauth("access_denied", _): + return nil + case .network: + return String(localized: "Could not reach the server. Check your internet connection and try again.") + case .oauth("temporarily_unavailable", _): + return String(localized: "The server is busy. Try again in a few minutes.") + case .signedOut: + return String(localized: "You were signed out. Sign in again.") + case .server(_, "offline_file_active"): + return String(localized: "This device has a valid offline file, so it keeps its license slot until the file expires.") + case .server(_, "not_found"): + return String(localized: "This device was already removed.") + case .server(let status, _) where status > 0: + return String(format: String(localized: "Something went wrong (error %d). Try again in a moment."), status) + case .server: + return String(localized: "The server refused the request. Try again in a moment.") + case .oauth, .invalidResponse, .offlineFileRejected: + return String(localized: "Could not read the server response. Try again in a moment.") + case .otherIssuer: + return String(localized: "Could not confirm the sign-in came from the server TablePro asked. Sign in again.") + case .companyServer(.invalidAddress): + return String(localized: "Enter the server's https address, such as https://tablepro.example.com.") + case .companyServer(.notATableProServer): + return String(localized: "This address does not answer as a TablePro server. Check it with your administrator.") + case .companyServer(.licenseMissing): + return String(localized: "This server has no TablePro license installed. Ask your administrator to install one.") + case .companyServer(.licenseInvalid): + return String(localized: "This server's TablePro license is not valid for this server. Ask your administrator.") + case .companyServer(.managed): + return String(localized: "Your organization manages which server TablePro signs in to.") + case .companyServer(.unsupported): + return String(localized: "Your organization's server does not take this request.") + case .signOutFirst: + return String(localized: "Sign out first, then sign in to the other account or server.") + } + } +} diff --git a/apple/TableProMobile/TableProMobile/Account/AccountKeychainItems.swift b/apple/TableProMobile/TableProMobile/Account/AccountKeychainItems.swift new file mode 100644 index 0000000000..9c20638c05 --- /dev/null +++ b/apple/TableProMobile/TableProMobile/Account/AccountKeychainItems.swift @@ -0,0 +1,146 @@ +import Foundation +import Security + +// The account's Keychain items: this device only, readable once the device was first unlocked, so a background +// refresh can read them, and in the app's own access group, never the one the widget shares. +nonisolated struct AccountKeychainItems: Sendable { + static let service = "com.TablePro" + static let deviceIDItem = "com.TablePro.account.deviceID" + + let items: any KeychainItemStore + let accessGroup: String? + + init(items: any KeychainItemStore = SystemKeychainItemStore(), accessGroup: String? = Self.appAccessGroup) { + self.items = items + self.accessGroup = accessGroup + } + + // The application identifier, which the system adds to the app's access groups; without a set group an item + // would join the first group the entitlements list, the widget's. + static var appAccessGroup: String? { + guard let prefix = Bundle.main.infoDictionary?["AppIdentifierPrefix"] as? String, !prefix.isEmpty, + !prefix.hasPrefix("$("), let bundleID = Bundle.main.bundleIdentifier else { return nil } + return prefix + bundleID + } + + func read(_ account: String) throws(AccountKeychainFailure) -> Data? { + let found = items.copyItem(query(account)) + switch found.status { + case errSecSuccess: + return found.data + case errSecItemNotFound: + return nil + default: + throw Self.failure(found.status) + } + } + + func write(_ data: Data, to account: String) throws(AccountKeychainFailure) { + let attributes: [String: Any] = [ + kSecValueData as String: data, + kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly, + ] + var status = items.update(query(account), attributes: attributes) + if status == errSecItemNotFound { + status = items.add(query(account).merging(attributes) { _, new in new }) + } + guard status == errSecSuccess else { throw Self.failure(status) } + } + + // Adds only when absent: two launches racing for a first device ID keep the one written first. + func add(_ data: Data, to account: String) throws(AccountKeychainFailure) -> Bool { + var attributes = query(account) + attributes[kSecValueData as String] = data + attributes[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly + let status = items.add(attributes) + switch status { + case errSecSuccess: return true + case errSecDuplicateItem: return false + default: throw Self.failure(status) + } + } + + func delete(_ account: String) { + _ = items.delete(query(account)) + } + + private func query(_ account: String) -> [String: Any] { + var query: [String: Any] = [ + kSecClass as String: kSecClassGenericPassword, + kSecAttrService as String: Self.service, + kSecAttrAccount as String: account, + kSecAttrSynchronizable as String: false, + kSecUseDataProtectionKeychain as String: true, + ] + if let accessGroup { + query[kSecAttrAccessGroup as String] = accessGroup + } + return query + } + + private static func failure(_ status: OSStatus) -> AccountKeychainFailure { + switch status { + case errSecInteractionNotAllowed: .locked + case errSecUserCanceled: .dismissed + default: .failed("Keychain error \(status)") + } + } +} + +// The refresh tokens the core keeps, one item per server, named as on the Mac. +nonisolated struct MobileAccountKeychain: AccountTokenKeychain { + let items: AccountKeychainItems + + func refreshToken(signInKey: String?) throws(AccountKeychainFailure) -> String? { + guard let data = try items.read(AccountRefreshTokenItem.key(signInKey: signInKey)) else { return nil } + let token = String(data: data, encoding: .utf8) ?? "" + return token.isEmpty ? nil : token + } + + func storeRefreshToken(_ token: String, signInKey: String?) throws(AccountKeychainFailure) { + try items.write(Data(token.utf8), to: AccountRefreshTokenItem.key(signInKey: signInKey)) + } + + func deleteRefreshToken(signInKey: String?) { + items.delete(AccountRefreshTokenItem.key(signInKey: signInKey)) + } +} + +// The machine ID the account registers this device under: 32 random bytes made the first time the account opens. A +// backup restored to another device brings no item of this device's, so that device gets an ID of its own. +nonisolated enum AccountDeviceID { + static func current( + items: AccountKeychainItems, + random: () -> Data? = randomBytes + ) throws(AccountKeychainFailure) -> String { + let stored = try items.read(AccountKeychainItems.deviceIDItem) + if let stored, stored.count == 32 { + return hex(stored) + } + guard let fresh = random(), fresh.count == 32 else { + throw .failed("no random bytes for a device ID") + } + // An item of another length is no ID this app wrote, so it is replaced. + if stored != nil { + try items.write(fresh, to: AccountKeychainItems.deviceIDItem) + return hex(fresh) + } + if try items.add(fresh, to: AccountKeychainItems.deviceIDItem) { + return hex(fresh) + } + guard let stored = try items.read(AccountKeychainItems.deviceIDItem), stored.count == 32 else { + throw .failed("the device ID another launch wrote does not read") + } + return hex(stored) + } + + static func randomBytes() -> Data? { + var bytes = [UInt8](repeating: 0, count: 32) + guard SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) == errSecSuccess else { return nil } + return Data(bytes) + } + + static func hex(_ data: Data) -> String { + data.map { String(format: "%02x", $0) }.joined() + } +} diff --git a/apple/TableProMobile/TableProMobile/Account/AccountModel.swift b/apple/TableProMobile/TableProMobile/Account/AccountModel.swift new file mode 100644 index 0000000000..a823395b73 --- /dev/null +++ b/apple/TableProMobile/TableProMobile/Account/AccountModel.swift @@ -0,0 +1,283 @@ +import Foundation +import Observation +import os +import TableProFFI +import TableProLogRedaction +import UIKit + +// The TablePro account on this device: the core's account (core/docs/decisions/0047-the-apple-apps-sign-in-through- +// the-core.md) through the adapter the Mac uses. The app gates nothing on it: the server checks every call. +@MainActor @Observable +final class AccountModel: AccountBackendListener { + typealias Opener = @MainActor (any AccountBackendListener, ManagedAppConfiguration) + throws(AccountKeychainFailure) -> any AccountBackend + + enum Availability: Equatable { + case opening + case open + // The Keychain is locked until the device is first unlocked; the next activation opens it. + case waitingForUnlock + case unavailable + } + + private static let logger = Logger(subsystem: "com.TablePro", category: "AccountModel") + + private(set) var availability: Availability = .opening + private(set) var snapshot = AccountSnapshot() + private(set) var server: AccountServer = .production + private(set) var license: AccountServerLicense? + private(set) var isRestored = false + private(set) var isBusy = false + // A sign-out the person did not ask for, shown until the next sign-in. + private(set) var involuntarySignOut: AccountSignOutCause? + + @ObservationIgnored private var backend: (any AccountBackend)? + @ObservationIgnored private let opener: Opener + @ObservationIgnored private var configuration: ManagedAppConfiguration + // Every reading reaches the core in order, so one that stops the server is never overtaken by an older one. + @ObservationIgnored private let readings: AsyncStream + @ObservationIgnored private let reader: AsyncStream.Continuation + + init(configuration: ManagedAppConfiguration = .unmanaged, opener: @escaping Opener) { + self.configuration = configuration + self.opener = opener + (readings, reader) = AsyncStream.makeStream(of: ManagedPolicyArg.self) + } + + var isSignedIn: Bool { + snapshot.state == .signedIn + } + + var isPastDeviceLimit: Bool { + if case .deviceLimitReached = snapshot.problem { return true } + return false + } + + func openIfNeeded() { + guard backend == nil, availability != .unavailable else { return } + do throws(AccountKeychainFailure) { + let opened = try opener(self, configuration) + backend = opened + availability = .open + publish() + let readings = readings + Task { + for await policy in readings { + await opened.applyPolicy(policy) + } + } + Task { + await opened.waitUntilRestored() + publish() + } + } catch .locked { + availability = .waitingForUnlock + } catch { + Self.logger.error("The account did not open: \(LogRedaction.publicDescription(of: error), privacy: .public)") + availability = .unavailable + } + } + + // The organization's values read again. When they no longer allow the server signed in to, the core calls it no + // more until the next launch (core ADR 0055); an account not open yet opens with them. + func apply(_ configuration: ManagedAppConfiguration) { + guard configuration != self.configuration else { return } + self.configuration = configuration + reader.yield(configuration.coreArgument) + } + + // Back in the foreground: a device another one removed may have freed a slot. + func sceneBecameActive() { + openIfNeeded() + guard let backend, isPastDeviceLimit else { return } + Task { + do throws(AccountError) { + _ = try await backend.refreshPastDeviceLimit() + } catch { + Self.logger.warning("Refresh past the device limit failed: \(error.logShape, privacy: .public)") + } + publish() + } + } + + func signIn(using authenticator: some WebAuthenticating) async throws(AccountError) { + let backend = try await restoredBackend() + guard backend.status().state != .signedIn else { throw .signOutFirst } + isBusy = true + defer { isBusy = false } + involuntarySignOut = nil + try await backend.signIn(using: authenticator) + publish() + } + + // Signs out here even when the server could not be told. + func signOut() async { + guard let backend else { return } + isBusy = true + defer { isBusy = false } + do throws(AccountError) { + try await backend.signOut() + } catch { + Self.logger.warning("The server was not told of the sign-out: \(error.logShape, privacy: .public)") + } + publish() + } + + // Nil drops the choice, for the organization's server or else tablepro.app. + func chooseServer(_ url: URL?) async throws(AccountError) { + let backend = try await restoredBackend() + guard backend.status().state != .signedIn else { throw .signOutFirst } + isBusy = true + defer { isBusy = false } + try await backend.chooseServer(url) + publish() + } + + func refresh() async throws(AccountError) { + let backend = try await restoredBackend() + defer { publish() } + try await backend.refresh() + } + + func devices() async throws(AccountError) -> [AccountDevice] { + try await restoredBackend().devices() + } + + func removeDevice(_ id: String) async throws(AccountError) { + let backend = try await restoredBackend() + try await backend.removeDevice(id) + do throws(AccountError) { + try await backend.refresh() + } catch { + Self.logger.warning("Refresh after removing a device failed: \(error.logShape, privacy: .public)") + } + publish() + } + + // MARK: - AccountBackendListener + + func accountStatusChanged(signedOutBy cause: AccountSignOutCause?) { + publish() + guard let cause, cause != .user, !isSignedIn else { return } + Self.logger.notice("Signed out on this device: \(String(describing: cause), privacy: .public)") + involuntarySignOut = cause + } + + // MARK: - Private + + private func restoredBackend() async throws(AccountError) -> any AccountBackend { + guard let backend else { throw .network("the account is not open") } + await backend.waitUntilRestored() + return backend + } + + private func publish() { + guard let backend else { return } + // Read before the snapshot: once the restore is marked, the snapshot read after it holds what it restored. + isRestored = backend.isRestored + snapshot = backend.status() + server = backend.server() + license = backend.license() + } +} + +extension AccountModel { + // The account at its place in Application Support, under the organization's managed server values. + static func live(configuration: ManagedAppConfiguration, supportDirectory: URL = LibraryStorage.defaultDirectory) + -> AccountModel { + let device = MobileAccountSetup.Device.current() + let developmentStack = isDebugBuild ? AccountDevelopmentStack.read(ProcessInfo.processInfo.environment) : nil + return AccountModel(configuration: configuration) { listener, managed throws(AccountKeychainFailure) in + let items = AccountKeychainItems() + let config = MobileAccountSetup.config( + deviceID: try AccountDeviceID.current(items: items), + device: device, + accountFolder: MobileAccountSetup.accountFolder(in: supportDirectory), + managed: managed, + developmentStack: developmentStack + ) + let backend = CoreAccountBackend( + config: config, + appVersion: device.appVersion, + keychain: MobileAccountKeychain(items: items) + ) + backend.setListener(listener) + return backend + } + } + + private static var isDebugBuild: Bool { + #if DEBUG + true + #else + false + #endif + } +} + +// What the iOS app hands the core's account when it opens it. +nonisolated enum MobileAccountSetup { + struct Device: Equatable, Sendable { + let name: String + let appVersion: String + // With the system's name, "iOS 26.1" or "iPadOS 26.1", as the server lists it. + let osVersion: String + + @MainActor + static func current() -> Device { + let device = UIDevice.current + return Device( + name: device.name, + appVersion: Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "", + osVersion: "\(device.systemName) \(device.systemVersion)" + ) + } + } + + // Kept out of backups: a restore onto another device brings none of the Keychain items the file goes with. + static func accountFolder(in supportDirectory: URL) -> URL { + var folder = supportDirectory.appendingPathComponent("Account", isDirectory: true) + do { + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + var values = URLResourceValues() + values.isExcludedFromBackup = true + try folder.setResourceValues(values) + } catch { + Logger(subsystem: "com.TablePro", category: "AccountModel") + .warning("The account folder is not kept out of backups: \(LogRedaction.publicDescription(of: error), privacy: .public)") + } + return folder + } + + static func config( + deviceID: String, + device: Device, + accountFolder: URL, + managed: ManagedAppConfiguration, + developmentStack: AccountDevelopmentStack? + ) -> AccountConfig { + AccountConfig( + accountUrl: developmentStack?.accountURL, + apiUrl: developmentStack?.apiBase, + entitlementKeys: developmentStack?.entitlementKeys ?? [], + deviceName: device.name, + appVersion: device.appVersion, + osVersion: device.osVersion, + accountFile: accountFolder.appendingPathComponent("account.json").path, + callbackFinished: "", + callbackUnknown: "", + machineGuid: nil, + client: .ios, + machineId: deviceID, + policy: managed.coreArgument, + legacyEntitlementFile: nil, + licenseKeys: developmentStack?.licenseKeys ?? [] + ) + } +} + +nonisolated extension AccountError { + var logShape: String { + LogRedaction.publicDescription(of: self) + } +} diff --git a/apple/TableProMobile/TableProMobile/Acknowledgements/Acknowledgements.json b/apple/TableProMobile/TableProMobile/Acknowledgements/Acknowledgements.json index cf8e86ca43..348162c1b2 100644 --- a/apple/TableProMobile/TableProMobile/Acknowledgements/Acknowledgements.json +++ b/apple/TableProMobile/TableProMobile/Acknowledgements/Acknowledgements.json @@ -287,5 +287,16 @@ ], "homepageURL": "https://github.com/apple/swift-nio-ssl", "textFile": "texts/swift-nio-ssl.txt" + }, + { + "id": "tablepro-core-crates", + "name": "TablePro core's Rust crates", + "version": "Cargo.lock", + "spdx": "MIT AND Apache-2.0 AND ISC AND BSD-3-Clause AND MPL-2.0 AND OpenSSL AND Unicode-3.0 AND Zlib", + "copyrights": [ + "Each crate's own, in the license text that lists it" + ], + "homepageURL": "https://crates.io", + "textFile": "texts/tablepro-core-crates.txt" } ] diff --git a/apple/TableProMobile/TableProMobile/AppState.swift b/apple/TableProMobile/TableProMobile/AppState.swift index 82edcab4f3..f244555122 100644 --- a/apple/TableProMobile/TableProMobile/AppState.swift +++ b/apple/TableProMobile/TableProMobile/AppState.swift @@ -43,6 +43,7 @@ final class AppState { let catalogChanges = CatalogChangeBoard() let sessionModels = ConnectionSessionModels() let syncCoordinator: IOSSyncCoordinator + let account: AccountModel @ObservationIgnored private var automaticPresentationOwner: UUID? @ObservationIgnored private var pastedSSHKeysAwaitingKeychain: [UUID: String] = [:] @@ -71,7 +72,8 @@ final class AppState { localDatabaseFiles: LocalDatabaseFileLocator = .live, bookmarkStore: FileBookmarkStore = FileBookmarkStore(), libraryPublisher: ConnectionLibraryPublisher? = nil, - driverFactory injectedDriverFactory: (any DriverFactory)? = nil + driverFactory injectedDriverFactory: (any DriverFactory)? = nil, + account injectedAccount: AccountModel? = nil ) { self.sampleInstaller = sampleInstaller self.libraryPublisher = libraryPublisher ?? .live(defaults: defaults) @@ -80,6 +82,7 @@ final class AppState { onboarding = OnboardingPreferences(defaults: defaults) libraryPreferences = ConnectionLibraryPreferences(defaults: defaults) syncCoordinator = injectedSyncCoordinator ?? IOSSyncCoordinator() + account = injectedAccount ?? .live(configuration: onboarding.managed) storage = ConnectionPersistence(directory: libraryDirectory) queryHistory = QueryHistoryStorage(directory: libraryDirectory) savedQueries = SavedQueryLibrary(directory: libraryDirectory, syncCoordinator: syncCoordinator) @@ -118,6 +121,9 @@ final class AppState { guard !TestRuntime.isActive else { return } + account.openIfNeeded() + observeManagedConfiguration() + if loadStatus == .ready { removeWhatDeletedConnectionsLeft() Task { @@ -715,6 +721,8 @@ final class AppState { hasConnections: loadedConnectionIds.map { !$0.isEmpty }, syncChoice: onboarding.syncChoice, usageDataChoice: onboarding.usageDataChoice, + iCloudSyncAllowed: !onboarding.managed.locksICloudSync, + usageDataAllowed: onboarding.managed.allowsUsageData, lastSeenVersion: onboarding.lastSeenVersion, currentVersion: version, hasHighlightsForCurrentVersion: FeatureHighlights.release(version) != nil @@ -752,6 +760,26 @@ final class AppState { onboarding.setUsageDataChoice(enabled) } + // ADR 0055: iCloud sync stops at once when the organization takes it away, with no last pass, starts when it + // forces it, and comes back to the person's own choice when it lets go. + func refreshManagedConfiguration() { + let wasEnabled = onboarding.isCloudSyncEnabled + onboarding.refreshManagedConfiguration() + account.apply(onboarding.managed) + let enabled = onboarding.isCloudSyncEnabled + guard enabled != wasEnabled else { return } + syncCoordinator.setEnabled(enabled) + } + + // An MDM's new values post a defaults change, as any write to the domain does (Apple's managed app configuration). + private func observeManagedConfiguration() { + Task { [weak self] in + for await _ in NotificationCenter.default.notifications(named: UserDefaults.didChangeNotification) { + self?.refreshManagedConfiguration() + } + } + } + // MARK: - Sample Database func openSampleDatabase() throws -> UUID { diff --git a/apple/TableProMobile/TableProMobile/Localizable.xcstrings b/apple/TableProMobile/TableProMobile/Localizable.xcstrings index 16bb9eda63..8b7844128f 100644 --- a/apple/TableProMobile/TableProMobile/Localizable.xcstrings +++ b/apple/TableProMobile/TableProMobile/Localizable.xcstrings @@ -420,6 +420,26 @@ } } }, + "%@ ยท %@" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "%1$@ ยท %2$@" + } + } + } + }, + "%@ ยท Last seen %@" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "%1$@ ยท Last seen %2$@" + } + } + } + }, "%@ โ†’ %@" : { "extractionState" : "stale", "localizations" : { @@ -5816,6 +5836,9 @@ }, "Commit the Transaction?" : { + }, + "Company Server" : { + }, "Compress the file using Gzip" : { @@ -7061,6 +7084,9 @@ } } } + }, + "Could not confirm the sign-in came from the server TablePro asked. Sign in again." : { + }, "Could not connect to the database: %@" : { "localizations" : { @@ -7339,6 +7365,9 @@ } } } + }, + "Could not reach the server. Check your internet connection and try again." : { + }, "Could not read %@ from the workbook." : { "extractionState" : "manual", @@ -7371,6 +7400,9 @@ } } } + }, + "Could not read the server response. Try again in a moment." : { + }, "Could not read the settings %@ was created with, so it restores under the dump's SQL mode." : { @@ -8562,6 +8594,9 @@ "Device" : { "extractionState" : "manual", "generatesSymbol" : false + }, + "Devices" : { + }, "Diamond" : { "extractionState" : "manual", @@ -9595,6 +9630,9 @@ }, "Enter the server details yourself." : { + }, + "Enter the server's https address, such as https://tablepro.example.com." : { + }, "Enter the start URL and SSO Region in this connection's Authentication section, then sign in." : { @@ -13193,6 +13231,9 @@ } } } + }, + "It is signed out of TablePro and frees its slot." : { + }, "It never contains a hostname, username, password, query, or any data from your databases. You can change this in Settings." : { "localizations" : { @@ -14253,6 +14294,9 @@ }, "Mac socket %@" : { + }, + "macOS %@" : { + }, "macOS blocks a library downloaded from the internet. If you trust it, run: xattr -d com.apple.quarantine %@" : { "extractionState" : "manual", @@ -14348,6 +14392,9 @@ } } } + }, + "Managed by your organization" : { + }, "Manual" : { "localizations" : { @@ -19745,6 +19792,9 @@ } } } + }, + "Remove โ€œ%@โ€?" : { + }, "Remove from Favorites" : { "localizations" : { @@ -22244,12 +22294,24 @@ } } } + }, + "Sign Out" : { + + }, + "Sign out first, then sign in to the other account or server." : { + + }, + "Sign out of TablePro on this device?" : { + }, "Sign-In Denied" : { }, "Sign-In Timed Out" : { + }, + "Signed In As" : { + }, "Signing the service account token failed." : { "extractionState" : "manual", @@ -22352,6 +22414,9 @@ }, "Some of the file does not read as %@. Choose the encoding it was saved in." : { + }, + "Something went wrong (error %d). Try again in a moment." : { + }, "Sort" : { "localizations" : { @@ -23944,6 +24009,9 @@ } } } + }, + "TablePro Account" : { + }, "TablePro and the SSH server could not agree on how to encrypt the connection." : { "extractionState" : "manual", @@ -24921,6 +24989,9 @@ "The Access Token contains a control character. Copy it again from MotherDuck." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "The account could not be refreshed." : { + }, "The action of foreign key %@ cannot be written as SQL." : { @@ -25753,6 +25824,9 @@ "The default of column %@ is not one SQL expression, so it cannot be written." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "The devices could not be loaded." : { + }, "The document changed on the server after it was opened, so nothing was saved. Copy your text, then open it again." : { @@ -27085,6 +27159,9 @@ }, "The server fills in %@, so it cannot be given a value." : { + }, + "The server is busy. Try again in a few minutes." : { + }, "The server is not responding. Check the host and port." : { "localizations" : { @@ -27129,6 +27206,9 @@ "The server offers only MAC algorithms TablePro no longer supports: %@." : { "extractionState" : "manual", "generatesSymbol" : false + }, + "The server refused the request. Try again in a moment." : { + }, "The server requires a client certificate for TLS mutual authentication." : { "extractionState" : "manual", @@ -27838,6 +27918,9 @@ }, "This action cannot be undone." : { + }, + "This address does not answer as a TablePro server. Check it with your administrator." : { + }, "This also commits the open transaction, keeping its uncommitted changes." : { @@ -28521,9 +28604,18 @@ } } } + }, + "This Device" : { + }, "This device cannot check a SQL Server certificate, so it does not connect in this mode. Choose Required to connect without the check." : { + }, + "This device has a valid offline file, so it keeps its license slot until the file expires." : { + + }, + "This device was already removed." : { + }, "This document has no _id, so it cannot be edited here." : { @@ -28993,6 +29085,9 @@ } } } + }, + "This server has no TablePro license installed. Ask your administrator to install one." : { + }, "This server is not running in cluster mode. Set Connection Mode to Standalone, or point Cluster mode at a node started with cluster-enabled yes." : { "extractionState" : "manual", @@ -29064,6 +29159,9 @@ }, "This server runs Atlas Search but cannot list its search indexes, so one that uses the field cannot be ruled out. Check the collection's search indexes in Atlas, then change the field from a query tab." : { + }, + "This server's TablePro license is not valid for this server. Ask your administrator." : { + }, "This SSH private key belongs to a security key (FIDO), which TablePro on iPhone and iPad cannot sign with." : { @@ -30130,6 +30228,9 @@ }, "Unlock TablePro to add rows to %@." : { + }, + "Unlock this device to use your TablePro account." : { + }, "Unlocked" : { "extractionState" : "manual", @@ -30531,6 +30632,9 @@ } } } + }, + "Use This Server" : { + }, "Username" : { "localizations" : { @@ -31384,6 +31488,18 @@ } } } + }, + "You were signed out because the server changed." : { + + }, + "You were signed out because the server no longer accepts this sign-in. Sign in again." : { + + }, + "You were signed out because this device was removed from your account." : { + + }, + "You were signed out. Sign in again." : { + }, "Your account is not allowed to read the source of %@" : { "extractionState" : "manual", @@ -31473,6 +31589,36 @@ }, "Your Mac reaches the SSH server through these hosts from its ~/.ssh/config, and this device dials the same route with its own keys. Changing the SSH server or jump hosts above replaces it." : { + }, + "Your organization manages iCloud sync for TablePro." : { + + }, + "Your organization manages which server TablePro signs in to." : { + + }, + "Your organization turned off iCloud sync for TablePro." : { + + }, + "Your organization turned off usage data for TablePro." : { + + }, + "Your organization's server does not take this request." : { + + }, + "Your organization's server." : { + + }, + "Your organization's TablePro license expired on %@. Ask your administrator to renew it." : { + + }, + "Your organization's TablePro server, if it runs one. Ask your administrator for its address." : { + + }, + "Your plan's devices are all in use. Remove one in Devices to use this device." : { + + }, + "Your TablePro account could not open on this device." : { + } }, "version" : "1.0" diff --git a/apple/TableProMobile/TableProMobile/Onboarding/FirstRunPlan.swift b/apple/TableProMobile/TableProMobile/Onboarding/FirstRunPlan.swift index 7478bcbede..0dea023ec5 100644 --- a/apple/TableProMobile/TableProMobile/Onboarding/FirstRunPlan.swift +++ b/apple/TableProMobile/TableProMobile/Onboarding/FirstRunPlan.swift @@ -18,6 +18,9 @@ nonisolated struct FirstRunPlan: Sendable { let hasConnections: Bool? let syncChoice: Bool? let usageDataChoice: Bool? + // False when the organization's managed configuration answers the question for the person. + var iCloudSyncAllowed = true + var usageDataAllowed = true let lastSeenVersion: String? let currentVersion: String let hasHighlightsForCurrentVersion: Bool @@ -42,11 +45,11 @@ nonisolated struct FirstRunPlan: Sendable { if hasConnections == false { pages.append(.origin) } - if syncChoice == nil { + if syncChoice == nil, iCloudSyncAllowed { pages.append(.iCloud) } } - if usageDataChoice == nil { + if usageDataChoice == nil, usageDataAllowed { pages.append(.usageData) } return pages diff --git a/apple/TableProMobile/TableProMobile/Platform/AppPreferences.swift b/apple/TableProMobile/TableProMobile/Platform/AppPreferences.swift index 8d4c76673c..0c1f9fc585 100644 --- a/apple/TableProMobile/TableProMobile/Platform/AppPreferences.swift +++ b/apple/TableProMobile/TableProMobile/Platform/AppPreferences.swift @@ -13,7 +13,7 @@ nonisolated enum AppPreferences { static let pageSizeOptions: [Int] = [50, 100, 200, 500] static var isCloudSyncEnabled: Bool { - UserDefaults.standard.bool(forKey: cloudSyncEnabledKey) + ManagedAppConfiguration.current().settledICloudSync(UserDefaults.standard.bool(forKey: cloudSyncEnabledKey)) } static var syncsPasswords: Bool { diff --git a/apple/TableProMobile/TableProMobile/Platform/ManagedAppConfiguration.swift b/apple/TableProMobile/TableProMobile/Platform/ManagedAppConfiguration.swift new file mode 100644 index 0000000000..77d256b413 --- /dev/null +++ b/apple/TableProMobile/TableProMobile/Platform/ManagedAppConfiguration.swift @@ -0,0 +1,132 @@ +import Foundation +import os +import TableProFFI + +// The keys an MDM sets for this app as managed app configuration (core/docs/decisions/0055-managed-policies-for-the-sync- +// provider-and-tablepro-app-traffic.md). The raw values go to the core, which applies them by the rule every app shares. +// Absent, or of another type, a key leaves the person's own setting. +nonisolated struct ManagedAppConfiguration: Equatable, Sendable { + static let defaultsKey = "com.apple.configuration.managed" + // Until TablePro Sync ships here, iOS offers Off and iCloud, and the iCloud switch is its picker. + static let offeredProviders: [SyncProviderTag] = [.off, .icloud] + + private static let logger = Logger(subsystem: "com.TablePro", category: "ManagedAppConfiguration") + + var accountServerURL: String? + var allowOtherAccountServers: Bool? + var personalSyncProvider: [String]? + var usageDataAllowed: Bool? + var iCloudSyncAllowed: Bool? + + static let unmanaged = ManagedAppConfiguration() + + // Only an MDM writes this dictionary: the app has no code that sets it. + static func current(defaults: UserDefaults = .standard) -> ManagedAppConfiguration { + ManagedAppConfiguration(defaults.dictionary(forKey: defaultsKey)) + } + + init( + accountServerURL: String? = nil, + allowOtherAccountServers: Bool? = nil, + personalSyncProvider: [String]? = nil, + usageDataAllowed: Bool? = nil, + iCloudSyncAllowed: Bool? = nil + ) { + self.accountServerURL = accountServerURL + self.allowOtherAccountServers = allowOtherAccountServers + self.personalSyncProvider = personalSyncProvider + self.usageDataAllowed = usageDataAllowed + self.iCloudSyncAllowed = iCloudSyncAllowed + } + + init(_ values: [String: Any]?) { + let values = values ?? [:] + self.init( + accountServerURL: Self.string(values, "AccountServerURL"), + allowOtherAccountServers: Self.bool(values, "AllowOtherAccountServers"), + personalSyncProvider: Self.strings(values, "PersonalSyncProvider"), + usageDataAllowed: Self.bool(values, "UsageDataAllowed"), + iCloudSyncAllowed: Self.bool(values, "ICloudSyncAllowed") + ) + } + + // iOS has no plugin catalog and no update checks of its own, so it reads neither key. + var coreArgument: ManagedPolicyArg { + .read(values: ManagedPolicyValues( + accountServerUrl: accountServerURL, + allowOtherAccountServers: allowOtherAccountServers, + personalSyncProvider: personalSyncProvider, + usageDataAllowed: usageDataAllowed, + pluginCatalogAllowed: nil, + updateChecksAllowed: nil, + icloudSyncAllowed: iCloudSyncAllowed + )) + } + + // A boolean that is true or absent leaves the person's own setting. + var allowsUsageData: Bool { + usageDataAllowed != false + } + + // PersonalSyncProvider and ICloudSyncAllowed together, as the core reads them. + var allowsICloudSync: Bool { + iCloudChoices.providers.contains(.icloud) + } + + // One choice or none: the iCloud switch is the organization's. + var locksICloudSync: Bool { + iCloudChoices.locked + } + + // A forced iCloud turns sync on as the person would, and iCloud taken away turns it off; with a choice left, the + // person's own stands. + func settledICloudSync(_ chosen: Bool) -> Bool { + settledSyncProvider( + policy: coreArgument, + offered: Self.offeredProviders, + current: chosen ? .icloud : .off, + tableproSyncAvailable: false + ) == .icloud + } + + private var iCloudChoices: PersonalSyncChoices { + personalSyncChoices(policy: coreArgument, offered: Self.offeredProviders) + } + + private static func string(_ values: [String: Any], _ key: String) -> String? { + guard let value = values[key] else { return nil } + guard let string = value as? String else { + refused(key, expected: "string") + return nil + } + return string + } + + // A number is not a boolean, though NSNumber bridges both. + private static func bool(_ values: [String: Any], _ key: String) -> Bool? { + guard let value = values[key] else { return nil } + guard let number = value as? NSNumber, CFGetTypeID(number) == CFBooleanGetTypeID() else { + refused(key, expected: "boolean") + return nil + } + return number.boolValue + } + + // An entry that is not a string is left out; the core skips a name it does not know. + private static func strings(_ values: [String: Any], _ key: String) -> [String]? { + guard let value = values[key] else { return nil } + guard let list = value as? [Any] else { + refused(key, expected: "stringArray") + return nil + } + let names = list.compactMap { $0 as? String } + if names.count != list.count { + logger.warning("Managed \(key, privacy: .public) holds entries that are not strings, which are left out") + } + return names + } + + private static func refused(_ key: String, expected: String) { + logger.warning("Managed \(key, privacy: .public) is not a \(expected, privacy: .public), so it counts as absent") + } +} diff --git a/apple/TableProMobile/TableProMobile/Platform/OnboardingPreferences.swift b/apple/TableProMobile/TableProMobile/Platform/OnboardingPreferences.swift index 2c489c3a22..7df59c38f5 100644 --- a/apple/TableProMobile/TableProMobile/Platform/OnboardingPreferences.swift +++ b/apple/TableProMobile/TableProMobile/Platform/OnboardingPreferences.swift @@ -15,6 +15,8 @@ final class OnboardingPreferences { private(set) var usageDataChoice: Bool? private(set) var hasSeenOrigin: Bool private(set) var lastSeenVersion: String? + // What the organization decides over the person's choices; their choices stay for when it lets go. + private(set) var managed: ManagedAppConfiguration init(defaults: UserDefaults = .standard) { self.defaults = defaults @@ -23,14 +25,22 @@ final class OnboardingPreferences { usageDataChoice = defaults.object(forKey: AppPreferences.usageDataKey) as? Bool hasSeenOrigin = defaults.bool(forKey: Self.hasSeenOriginKey) lastSeenVersion = defaults.string(forKey: Self.lastSeenVersionKey) + managed = ManagedAppConfiguration.current(defaults: defaults) } var isCloudSyncEnabled: Bool { - syncChoice == true + managed.settledICloudSync(syncChoice == true) } var isUsageDataEnabled: Bool { - usageDataChoice == true + usageDataChoice == true && managed.allowsUsageData + } + + // An MDM changes the managed configuration while the app runs. + func refreshManagedConfiguration() { + let current = ManagedAppConfiguration.current(defaults: defaults) + guard current != managed else { return } + managed = current } func setSyncChoice(_ enabled: Bool) { diff --git a/apple/TableProMobile/TableProMobile/Platform/SceneLifecycle.swift b/apple/TableProMobile/TableProMobile/Platform/SceneLifecycle.swift index daa639a3c8..946b60c0af 100644 --- a/apple/TableProMobile/TableProMobile/Platform/SceneLifecycle.swift +++ b/apple/TableProMobile/TableProMobile/Platform/SceneLifecycle.swift @@ -106,6 +106,13 @@ final class TableProSceneDelegate: NSObject, UIWindowSceneDelegate, ObservableOb onDisconnect = nil } + // The window a sheet UIKit presents, such as the sign-in page, goes over: this scene's, never the lock cover. On an + // iPad two scenes can both be in front. + var presentationWindow: UIWindow? { + let windows = windowScene?.windows.filter { $0 !== coverWindow && !$0.isHidden } ?? [] + return windows.first { $0.isKeyWindow } ?? windows.first + } + func showCover(_ mode: LockCoverMode?, lockState: AppLockState) { guard let mode else { hideCover() diff --git a/apple/TableProMobile/TableProMobile/Sync/IOSSyncCoordinator.swift b/apple/TableProMobile/TableProMobile/Sync/IOSSyncCoordinator.swift index b7c119779c..5e5bff4139 100644 --- a/apple/TableProMobile/TableProMobile/Sync/IOSSyncCoordinator.swift +++ b/apple/TableProMobile/TableProMobile/Sync/IOSSyncCoordinator.swift @@ -500,6 +500,12 @@ final class IOSSyncCoordinator { let heldDownload: SyncStepFailure? = applied == .saved ? nil : .pullNotSaved guard admission == .full else { return RunResult(admission: admission, failure: heldDownload) } + // Turned off during the download, by the person or by the organization's managed configuration (core ADR + // 0055), which takes effect with no setEnabled call: nothing more leaves the device. + guard isEnabled() else { + decide(.disabled(.userDisabled)) + return nil + } let pushed = await push(using: transport) let download = heldDownload ?? (pushed.adoptedMergedSaves ? nil : .pullNotSaved) guard let pushFailure = pushed.failure else { @@ -817,9 +823,11 @@ final class IOSSyncCoordinator { deletions: batch.deletions, edits: edits ) { - try await transport.push(records: $0, deletions: $1) + guard self.isEnabled() else { throw CancellationError() } + return try await transport.push(records: $0, deletions: $1) } fetch: { - try await transport.fetch(recordIDs: $0) + guard self.isEnabled() else { throw CancellationError() } + return try await transport.fetch(recordIDs: $0) } } catch let interrupted as SyncPushInterruption { outcome = interrupted.completed diff --git a/apple/TableProMobile/TableProMobile/TableProMobileApp.swift b/apple/TableProMobile/TableProMobile/TableProMobileApp.swift index aff9ff2c59..1d5168fa5d 100644 --- a/apple/TableProMobile/TableProMobile/TableProMobileApp.swift +++ b/apple/TableProMobile/TableProMobile/TableProMobileApp.swift @@ -60,6 +60,8 @@ struct TableProMobileApp: App { lockState.handleScenePhase(phase) switch phase { case .active: + appState.refreshManagedConfiguration() + appState.account.sceneBecameActive() Task { await appState.queryActivities.reapOrphans() } appState.backgroundRelease.cancelPreparation() MemoryPressureMonitor.shared.start() @@ -88,9 +90,9 @@ struct TableProMobileApp: App { break } } - .onChange(of: appState.onboarding.usageDataChoice) { _, choice in + .onChange(of: appState.onboarding.isUsageDataEnabled) { _, enabled in guard !TestRuntime.isActive else { return } - Telemetry.shared.setEnabled(choice == true) + Telemetry.shared.setEnabled(enabled) } .backgroundTask(.appRefresh(Self.backgroundSyncIdentifier)) { await runBackgroundSync() diff --git a/apple/TableProMobile/TableProMobile/Views/Account/AccountDevicesPage.swift b/apple/TableProMobile/TableProMobile/Views/Account/AccountDevicesPage.swift new file mode 100644 index 0000000000..058cd26fb8 --- /dev/null +++ b/apple/TableProMobile/TableProMobile/Views/Account/AccountDevicesPage.swift @@ -0,0 +1,103 @@ +import SwiftUI + +// The devices the account is signed in on. Removing one signs it out and frees its slot. +struct AccountDevicesPage: View { + private enum Devices { + case loading + case loaded([AccountDevice]) + case failed(String) + } + + let account: AccountModel + + @State private var devices: Devices = .loading + @State private var pendingRemoval: AccountDevice? + @State private var failure: String? + + var body: some View { + List { + switch devices { + case .loading: + ProgressView() + case .failed(let message): + Text(message) + .foregroundStyle(.secondary) + case .loaded(let devices): + Section { + ForEach(devices) { device in + row(device) + } + } footer: { + if let failure { + Text(failure) + .foregroundStyle(.red) + } + } + } + } + .navigationTitle(String(localized: "Devices")) + .navigationBarTitleDisplayMode(.inline) + .refreshable { await load() } + .task { await load() } + .confirmationDialog( + pendingRemoval.map { String(format: String(localized: "Remove โ€œ%@โ€?"), $0.name) } ?? "", + isPresented: Binding(get: { pendingRemoval != nil }, set: { if !$0 { pendingRemoval = nil } }), + titleVisibility: .visible, + presenting: pendingRemoval + ) { device in + Button(String(localized: "Remove"), role: .destructive) { + Task { await remove(device) } + } + } message: { _ in + Text("It is signed out of TablePro and frees its slot.") + } + } + + private func row(_ device: AccountDevice) -> some View { + VStack(alignment: .leading, spacing: 2) { + Text(verbatim: device.name) + Text(detail(device)) + .font(.footnote) + .foregroundStyle(.secondary) + } + .swipeActions { + if !device.isThisDevice { + Button(String(localized: "Remove"), role: .destructive) { + pendingRemoval = device + } + } + } + } + + private func detail(_ device: AccountDevice) -> String { + let system = AccountCodes.systemName(platform: device.platform, osVersion: device.osVersion) + guard !device.isThisDevice else { + return String(format: String(localized: "%@ ยท %@"), String(localized: "This Device"), system) + } + let lastSeen = device.lastSeenAt.formatted(.relative(presentation: .named)) + return String(format: String(localized: "%@ ยท Last seen %@"), system, lastSeen) + } + + private func load() async { + do throws(AccountError) { + devices = .loaded(try await account.devices()) + } catch { + // A refresh keeps the list it has. + guard case .loaded = devices else { + devices = .failed(error.mobileDescription ?? String(localized: "The devices could not be loaded.")) + return + } + failure = error.mobileDescription + } + } + + private func remove(_ device: AccountDevice) async { + failure = nil + do throws(AccountError) { + try await account.removeDevice(device.id) + await load() + } catch { + failure = error.mobileDescription + } + } +} diff --git a/apple/TableProMobile/TableProMobile/Views/Account/AccountSection.swift b/apple/TableProMobile/TableProMobile/Views/Account/AccountSection.swift new file mode 100644 index 0000000000..729ee98ce1 --- /dev/null +++ b/apple/TableProMobile/TableProMobile/Views/Account/AccountSection.swift @@ -0,0 +1,183 @@ +import SwiftUI +import UIKit + +// Settings' TablePro Account: sign in to tablepro.app or the organization's server, this account's devices, sign out. +struct AccountSection: View { + let account: AccountModel + let managed: ManagedAppConfiguration + + @EnvironmentObject private var sceneDelegate: TableProSceneDelegate + + @State private var failure: String? + @State private var confirmsSignOut = false + + var body: some View { + Section { + switch account.availability { + case .opening: + ProgressView() + case .waitingForUnlock: + Text("Unlock this device to use your TablePro account.") + .foregroundStyle(.secondary) + case .unavailable: + Text("Your TablePro account could not open on this device.") + .foregroundStyle(.secondary) + case .open: + if !account.isRestored { + ProgressView() + } else if account.isSignedIn { + signedIn + } else { + signedOut + } + } + } header: { + Text("TablePro Account") + } footer: { + if let notice = signOutNotice { + Text(notice) + } + } + .alert( + String(localized: "Account"), + isPresented: Binding(get: { failure != nil }, set: { if !$0 { failure = nil } }) + ) { + Button(String(localized: "OK"), role: .cancel) {} + } message: { + Text(failure ?? "") + } + .confirmationDialog( + String(localized: "Sign out of TablePro on this device?"), + isPresented: $confirmsSignOut, + titleVisibility: .visible + ) { + Button(String(localized: "Sign Out"), role: .destructive) { + Task { await account.signOut() } + } + } + } + + @ViewBuilder + private var signedOut: some View { + Button(String(localized: "Sign In")) { + Task { await signIn() } + } + .disabled(account.isBusy) + .accessibilityIdentifier("account-sign-in") + NavigationLink { + AccountServerPage(account: account, managed: managed) + } label: { + serverRow + } + .disabled(!account.server.othersAllowed) + } + + @ViewBuilder + private var signedIn: some View { + if let email = account.snapshot.email { + LabeledContent(String(localized: "Signed In As")) { + VStack(alignment: .trailing) { + if let name = account.snapshot.name, !name.isEmpty { + Text(verbatim: name) + } + Text(verbatim: email) + .foregroundStyle(.secondary) + } + } + } + serverRow + if let notice = account.license.flatMap(AccountServerLicenseText.notice) { + Label(notice, systemImage: "exclamationmark.triangle") + .foregroundStyle(.orange) + } + problemRow + NavigationLink(String(localized: "Devices")) { + AccountDevicesPage(account: account) + } + Button(String(localized: "Sign Out"), role: .destructive) { + confirmsSignOut = true + } + .disabled(account.isBusy) + } + + private var serverRow: some View { + LabeledContent { + Text(verbatim: account.server.host) + .lineLimit(1) + .truncationMode(.middle) + } label: { + Text("Server") + if account.server.isManaged { + Text("Managed by your organization") + } + } + } + + @ViewBuilder + private var problemRow: some View { + switch account.snapshot.problem { + case .deviceLimitReached: + Label( + String(localized: "Your plan's devices are all in use. Remove one in Devices to use this device."), + systemImage: "exclamationmark.triangle" + ) + .foregroundStyle(.orange) + case .refreshFailed(let error): + VStack(alignment: .leading, spacing: 8) { + Label( + error.mobileDescription ?? String(localized: "The account could not be refreshed."), + systemImage: "exclamationmark.triangle" + ) + .foregroundStyle(.orange) + Button(String(localized: "Try Again")) { + Task { await refresh() } + } + } + case .expired, nil: + EmptyView() + } + } + + private var signOutNotice: String? { + switch account.involuntarySignOut { + case .refreshRefused: + String(localized: "You were signed out because the server no longer accepts this sign-in. Sign in again.") + case .deviceRevoked: + String(localized: "You were signed out because this device was removed from your account.") + case .serverChanged: + String(localized: "You were signed out because the server changed.") + case .user, nil: + nil + } + } + + private func signIn() async { + do throws(AccountError) { + try await account.signIn(using: WebAuthenticationSessionAuthenticator { [sceneDelegate] in + sceneDelegate.presentationWindow + }) + } catch { + failure = error.mobileDescription + } + } + + private func refresh() async { + do throws(AccountError) { + try await account.refresh() + } catch { + failure = error.mobileDescription + } + } +} + +enum AccountServerLicenseText { + // Past its end the organization's license still lets this device sign in; it only says so. + static func notice(_ license: AccountServerLicense) -> String? { + guard license.state != .active else { return nil } + let date = license.expiresAt?.formatted(date: .abbreviated, time: .omitted) ?? "" + return String( + format: String(localized: "Your organization's TablePro license expired on %@. Ask your administrator to renew it."), + date + ) + } +} diff --git a/apple/TableProMobile/TableProMobile/Views/Account/AccountServerPage.swift b/apple/TableProMobile/TableProMobile/Views/Account/AccountServerPage.swift new file mode 100644 index 0000000000..7b3401cee3 --- /dev/null +++ b/apple/TableProMobile/TableProMobile/Views/Account/AccountServerPage.swift @@ -0,0 +1,94 @@ +import SwiftUI + +// Where the account signs in: tablepro.app, or the organization's own TablePro server (core ADR 0047, The server). +struct AccountServerPage: View { + private static let addressExample = "https://tablepro.example.com" + + let account: AccountModel + let managed: ManagedAppConfiguration + + @Environment(\.dismiss) private var dismiss + @State private var address = "" + @State private var failure: String? + + var body: some View { + Form { + Section { + Button { + Task { await choose(nil) } + } label: { + LabeledContent { + if isDefault { + Image(systemName: "checkmark") + .foregroundStyle(.tint) + } + } label: { + Text(verbatim: defaultHost) + .foregroundStyle(.primary) + } + } + .disabled(account.isBusy) + } footer: { + if managedHost != nil { + Text("Your organization's server.") + } + } + + Section { + LiteralTextField(Self.addressExample, text: $address, keyboardType: .URL) + .accessibilityIdentifier("account-server-address") + Button(String(localized: "Use This Server")) { + guard let url = URL(string: trimmedAddress) else { + failure = AccountError.companyServer(.invalidAddress).mobileDescription + return + } + Task { await choose(url) } + } + .disabled(trimmedAddress.isEmpty || account.isBusy) + } header: { + Text("Company Server") + } footer: { + if let failure { + Text(failure) + .foregroundStyle(.red) + } else { + Text("Your organization's TablePro server, if it runs one. Ask your administrator for its address.") + } + } + } + .navigationTitle(String(localized: "Server")) + .navigationBarTitleDisplayMode(.inline) + .onAppear { + if !account.server.isProduction, !account.server.isManaged { + address = account.server.apiOrigin.absoluteString + } + } + } + + private var trimmedAddress: String { + address.trimmingCharacters(in: .whitespacesAndNewlines) + } + + private var managedHost: String? { + managed.accountServerURL.flatMap { URL(string: $0)?.host() } + } + + // With no choice of the person's, the organization's server, else tablepro.app. + private var defaultHost: String { + managedHost ?? AccountServer.production.host + } + + private var isDefault: Bool { + account.server.isManaged || (managedHost == nil && account.server.isProduction) + } + + private func choose(_ url: URL?) async { + failure = nil + do throws(AccountError) { + try await account.chooseServer(url) + dismiss() + } catch { + failure = error.mobileDescription + } + } +} diff --git a/apple/TableProMobile/TableProMobile/Views/SettingsView.swift b/apple/TableProMobile/TableProMobile/Views/SettingsView.swift index d5b8957505..783fbb6c00 100644 --- a/apple/TableProMobile/TableProMobile/Views/SettingsView.swift +++ b/apple/TableProMobile/TableProMobile/Views/SettingsView.swift @@ -18,6 +18,7 @@ struct SettingsView: View { var body: some View { Form { + AccountSection(account: appState.account, managed: appState.onboarding.managed) biometricSection iCloudSection defaultsSection @@ -55,6 +56,7 @@ struct SettingsView: View { private var iCloudSection: some View { Section { Toggle(String(localized: "iCloud Sync"), isOn: cloudSyncBinding) + .disabled(appState.onboarding.managed.locksICloudSync) if appState.onboarding.isCloudSyncEnabled { LabeledContent(String(localized: "Last Sync")) { lastSyncLabel @@ -67,7 +69,11 @@ struct SettingsView: View { } header: { Text("iCloud") } footer: { - if appState.onboarding.isCloudSyncEnabled { + if !appState.onboarding.managed.allowsICloudSync { + Text("Your organization turned off iCloud sync for TablePro.") + } else if appState.onboarding.managed.locksICloudSync { + Text("Your organization manages iCloud sync for TablePro.") + } else if appState.onboarding.isCloudSyncEnabled { Text("Passwords sync through iCloud Keychain, which is end-to-end encrypted. Turning it on affects new saves only, so re-save a password to sync it.") } else { Text("When off, nothing is sent to iCloud and nothing already there is deleted. Changes you make meanwhile sync once you turn it back on.") @@ -146,13 +152,22 @@ struct SettingsView: View { private var usageDataSection: some View { Section { Toggle(String(localized: "Share Usage Data"), isOn: usageDataBinding) + .disabled(!appState.onboarding.managed.allowsUsageData) } header: { Text("Privacy") } footer: { - Text("Off until you turn it on. Sent to PostHog with a random ID: app and iOS versions, device model, screen size, language, time zone, network type, database types, connection count, and first connection and query. PostHog derives an approximate location from your IP address. Never hostnames, credentials, queries, or rows.") + if !appState.onboarding.managed.allowsUsageData { + Text("Your organization turned off usage data for TablePro.") + } else { + usageDataExplanation + } } } + private var usageDataExplanation: some View { + Text("Off until you turn it on. Sent to PostHog with a random ID: app and iOS versions, device model, screen size, language, time zone, network type, database types, connection count, and first connection and query. PostHog derives an approximate location from your IP address. Never hostnames, credentials, queries, or rows.") + } + private var liveActivitySection: some View { Section { Toggle(String(localized: "Hide Query"), isOn: $hideQueryPreviewInActivity) diff --git a/apple/TableProMobile/TableProMobileTests/Account/AccountCoreSignInTests.swift b/apple/TableProMobile/TableProMobileTests/Account/AccountCoreSignInTests.swift new file mode 100644 index 0000000000..2b1c031f23 --- /dev/null +++ b/apple/TableProMobile/TableProMobileTests/Account/AccountCoreSignInTests.swift @@ -0,0 +1,95 @@ +import Foundation +import TableProFFI +@testable import TableProMobile +import Testing + +// Stands in for ASWebAuthenticationSession: keeps the page the core opened, then the person closes it. +@MainActor +private final class ClosedPage: WebAuthenticating { + private(set) var asked: [(url: URL, scheme: String)] = [] + + func authenticate(url: URL, callbackScheme: String) async throws(AccountError) -> URL { + asked.append((url, callbackScheme)) + throw .canceled + } +} + +// The core's iOS slice in the app, through the adapter the Mac shares, with the config the app opens it with. +@MainActor +struct AccountCoreSignInTests { + private static let device = MobileAccountSetup.Device(name: "Ada's iPhone", appVersion: "1.4", osVersion: "iOS 26.1") + + private func folder() throws -> URL { + let folder = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + return folder + } + + private func backend(in folder: URL, managed: ManagedAppConfiguration = .unmanaged) -> CoreAccountBackend { + CoreAccountBackend( + config: MobileAccountSetup.config( + deviceID: String(repeating: "5f", count: 32), + device: Self.device, + accountFolder: folder, + managed: managed, + developmentStack: nil + ), + appVersion: Self.device.appVersion, + keychain: MobileAccountKeychain(items: AccountKeychainItems(items: InMemoryKeychainItems(), accessGroup: nil)) + ) + } + + @Test("An iPhone signs in to tablepro.app as the iOS client, through the Mac's scheme, and a closed page cancels") + func signsInAsTheIOSClient() async throws { + let backend = backend(in: try folder()) + let page = ClosedPage() + await backend.waitUntilRestored() + + await #expect(throws: AccountError.canceled) { try await backend.signIn(using: page) } + + let opened = try #require(page.asked.first) + let query = URLComponents(url: opened.url, resolvingAgainstBaseURL: false)?.queryItems ?? [] + #expect(opened.scheme == "app.tablepro") + #expect(opened.url.absoluteString.hasPrefix("https://account.tablepro.app/oauth/authorize?")) + #expect(query.first { $0.name == "client_id" }?.value == "tablepro-ios") + #expect(query.first { $0.name == "redirect_uri" }?.value == "app.tablepro:/oauth/callback") + #expect(backend.status().state == .signedOut) + #expect(backend.machineID == String(repeating: "5f", count: 32)) + } + + @Test("A managed server that allows no other holds the account, and a choice is refused") + func managedServerHolds() async throws { + let backend = backend( + in: try folder(), + managed: ManagedAppConfiguration(accountServerURL: "https://127.0.0.1:1", allowOtherAccountServers: false) + ) + await backend.waitUntilRestored() + + let server = backend.server() + await #expect(throws: AccountError.companyServer(.managed)) { + try await backend.chooseServer(URL(string: "https://tablepro.example.com")) + } + #expect(server.isManaged && !server.othersAllowed && !server.isProduction) + #expect(server.apiOrigin.absoluteString == "https://127.0.0.1:1") + } + + @Test("The config names the iOS client, the device's system with its version, the managed values and no file from before the core") + func config() { + let managed = ManagedAppConfiguration(accountServerURL: "https://tablepro.example.com", personalSyncProvider: ["off"]) + let config = MobileAccountSetup.config( + deviceID: "id", + device: Self.device, + accountFolder: URL(fileURLWithPath: "/data/Account", isDirectory: true), + managed: managed, + developmentStack: nil + ) + + #expect(config.client == .ios) + #expect(config.machineId == "id") + #expect(config.osVersion == "iOS 26.1") + #expect(config.accountFile == "/data/Account/account.json") + #expect(config.policy == managed.coreArgument) + #expect(config.legacyEntitlementFile == nil) + #expect(config.accountUrl == nil && config.apiUrl == nil) + } +} diff --git a/apple/TableProMobile/TableProMobileTests/Account/AccountKeychainItemsTests.swift b/apple/TableProMobile/TableProMobileTests/Account/AccountKeychainItemsTests.swift new file mode 100644 index 0000000000..9c8becd799 --- /dev/null +++ b/apple/TableProMobile/TableProMobileTests/Account/AccountKeychainItemsTests.swift @@ -0,0 +1,112 @@ +import Foundation +import Security +@testable import TableProMobile +import Testing + +// A Keychain whose reads fail as a locked device's do before its first unlock. +private final class LockedKeychainItems: KeychainItemStore, @unchecked Sendable { + private let lock = NSLock() + private var writes = 0 + + var writeCount: Int { lock.withLock { writes } } + + func add(_ attributes: [String: Any]) -> OSStatus { + lock.withLock { writes += 1 } + return errSecInteractionNotAllowed + } + + func update(_ query: [String: Any], attributes: [String: Any]) -> OSStatus { + lock.withLock { writes += 1 } + return errSecInteractionNotAllowed + } + + func copyItem(_ query: [String: Any]) -> KeychainCopiedItem { + KeychainCopiedItem(status: errSecInteractionNotAllowed, data: nil, modified: nil) + } + + func accounts(_ query: [String: Any]) -> [String] { [] } + + func delete(_ query: [String: Any]) -> OSStatus { errSecInteractionNotAllowed } +} + +struct AccountDeviceIDTests { + @Test("The first open makes 32 random bytes, kept on this device only, and every later open reads them back") + func madeOnceAndKept() throws { + let keychain = InMemoryKeychainItems() + let items = AccountKeychainItems(items: keychain, accessGroup: nil) + let bytes = Data((0..<32).map { UInt8($0) }) + + let first = try AccountDeviceID.current(items: items) { bytes } + let second = try AccountDeviceID.current(items: items) { Data(repeating: 0xff, count: 32) } + + #expect(first == "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f") + #expect(second == first) + #expect( + keychain.accessibility(account: AccountKeychainItems.deviceIDItem, synchronizable: false) + == kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly as String + ) + #expect(keychain.value(account: AccountKeychainItems.deviceIDItem, synchronizable: true) == nil) + } + + @Test("A locked Keychain is no missing ID: nothing is made, and the open waits for the unlock") + func lockedWritesNothing() { + let keychain = LockedKeychainItems() + let items = AccountKeychainItems(items: keychain, accessGroup: nil) + + #expect(throws: AccountKeychainFailure.locked) { + try AccountDeviceID.current(items: items) { Data(repeating: 1, count: 32) } + } + #expect(keychain.writeCount == 0) + } + + @Test("An item of another length is replaced by a new ID") + func wrongLengthIsReplaced() throws { + let keychain = InMemoryKeychainItems() + keychain.seed("short", account: AccountKeychainItems.deviceIDItem, synchronizable: false) + let items = AccountKeychainItems(items: keychain, accessGroup: nil) + + let id = try AccountDeviceID.current(items: items) { Data(repeating: 0xab, count: 32) } + + #expect(id == String(repeating: "ab", count: 32)) + #expect(try AccountDeviceID.current(items: items) { nil } == id) + } +} + +struct MobileAccountKeychainTests { + @Test("tablepro.app's refresh token and each company server's get the Mac's item names, on this device only") + func itemsPerServer() throws { + let keychain = InMemoryKeychainItems() + let tokens = MobileAccountKeychain(items: AccountKeychainItems(items: keychain, accessGroup: nil)) + + try tokens.storeRefreshToken("production-token", signInKey: nil) + try tokens.storeRefreshToken("company-token", signInKey: "a1b2") + + #expect(try tokens.refreshToken(signInKey: nil) == "production-token") + #expect(try tokens.refreshToken(signInKey: "a1b2") == "company-token") + #expect(keychain.value(account: "com.TablePro.account.refreshToken", synchronizable: false) == "production-token") + #expect(keychain.value(account: "com.TablePro.account.refreshToken.a1b2", synchronizable: false) == "company-token") + + tokens.deleteRefreshToken(signInKey: "a1b2") + + #expect(try tokens.refreshToken(signInKey: "a1b2") == nil) + #expect(try tokens.refreshToken(signInKey: nil) == "production-token") + } + + @Test("A rotated token replaces the one before") + func rotationReplaces() throws { + let tokens = MobileAccountKeychain(items: AccountKeychainItems(items: InMemoryKeychainItems(), accessGroup: nil)) + + try tokens.storeRefreshToken("first", signInKey: nil) + try tokens.storeRefreshToken("second", signInKey: nil) + + #expect(try tokens.refreshToken(signInKey: nil) == "second") + } + + @Test("A locked Keychain reaches the core as locked, so it keeps the sign-in for the next try") + func lockedIsLocked() { + let tokens = MobileAccountKeychain(items: AccountKeychainItems(items: LockedKeychainItems(), accessGroup: nil)) + + #expect(throws: AccountKeychainFailure.locked) { try tokens.refreshToken(signInKey: nil) } + #expect(throws: AccountKeychainFailure.locked) { try tokens.storeRefreshToken("token", signInKey: nil) } + } +} diff --git a/apple/TableProMobile/TableProMobileTests/Account/AccountModelTests.swift b/apple/TableProMobile/TableProMobileTests/Account/AccountModelTests.swift new file mode 100644 index 0000000000..e85d87d945 --- /dev/null +++ b/apple/TableProMobile/TableProMobileTests/Account/AccountModelTests.swift @@ -0,0 +1,250 @@ +import Foundation +import os +import TableProFFI +@testable import TableProMobile +import TableProTestSupport +import Testing + +// The core's account as AccountModel reaches it, with what each call did. +private final class ScriptedAccountBackend: AccountBackend, @unchecked Sendable { + private struct State { + var snapshot = AccountSnapshot() + var server = AccountServer.production + var chosen: [URL?] = [] + var signIns = 0 + var refreshesPastLimit = 0 + var signInError: AccountError? + var policies: [ManagedPolicyArg] = [] + } + + let machineID = String(repeating: "5f", count: 32) + private let state = OSAllocatedUnfairLock(initialState: State()) + + var isRestored: Bool { true } + func waitUntilRestored() async {} + + var signIns: Int { state.withLock { $0.signIns } } + var chosen: [URL?] { state.withLock { $0.chosen } } + var refreshesPastLimit: Int { state.withLock { $0.refreshesPastLimit } } + var policies: [ManagedPolicyArg] { state.withLock { $0.policies } } + + func set(_ snapshot: AccountSnapshot) { + state.withLock { $0.snapshot = snapshot } + } + + func failSignIn(with error: AccountError) { + state.withLock { $0.signInError = error } + } + + func status() -> AccountSnapshot { state.withLock { $0.snapshot } } + func featureAccess(code: String) -> ProFeatureAccess { .signedOut } + func server() -> AccountServer { state.withLock { $0.server } } + func license() -> AccountServerLicense? { nil } + + func signIn(using authenticator: any WebAuthenticating) async throws(AccountError) { + let failure = state.withLock { state -> AccountError? in + state.signIns += 1 + guard state.signInError == nil else { return state.signInError } + state.snapshot = AccountSnapshot(state: .signedIn, accountID: "acct", email: "ada@example.com") + return nil + } + if let failure { throw failure } + } + + func signOut() async throws(AccountError) { + state.withLock { $0.snapshot = AccountSnapshot() } + } + + func refresh() async throws(AccountError) {} + + func refreshPastDeviceLimit() async throws(AccountError) -> Bool { + state.withLock { $0.refreshesPastLimit += 1 } + return true + } + + func useLicenseKey(_ key: String) async throws(AccountError) {} + func importOfflineFile(at url: URL) async throws(AccountError) {} + + func chooseServer(_ url: URL?) async throws(AccountError) { + state.withLock { $0.chosen.append(url) } + } + + func profile() async throws(AccountError) -> AccountProfile { + AccountProfile(email: "ada@example.com", name: nil, memberships: []) + } + + func devices() async throws(AccountError) -> [AccountDevice] { [] } + func removeDevice(_ id: String) async throws(AccountError) {} + + func accessToken() async throws(AccountError) -> AccountAccessToken { + throw .signedOut + } + + func accessTokenRejected(_ token: String) async {} + + func applyPolicy(_ policy: ManagedPolicyArg) async { + state.withLock { $0.policies.append(policy) } + } + + func allowsTableProRequests() async -> Bool { true } +} + +@MainActor +private struct NoPage: WebAuthenticating { + func authenticate(url: URL, callbackScheme: String) async throws(AccountError) -> URL { + throw .canceled + } +} + +@MainActor +struct AccountModelTests { + private func opened(_ backend: ScriptedAccountBackend) -> AccountModel { + let account = AccountModel { _, _ in backend } + account.openIfNeeded() + return account + } + + @Test("Opening reads what the core restored") + func opensAndPublishes() { + let backend = ScriptedAccountBackend() + backend.set(AccountSnapshot(state: .signedIn, accountID: "acct", email: "ada@example.com")) + + let account = opened(backend) + + #expect(account.availability == .open) + #expect(account.isRestored) + #expect(account.isSignedIn) + #expect(account.snapshot.email == "ada@example.com") + } + + @Test("A Keychain locked before the first unlock leaves the account to the next activation") + func lockedWaitsForUnlock() { + let backend = ScriptedAccountBackend() + var locked = true + let account = AccountModel { _, _ throws(AccountKeychainFailure) in + if locked { throw .locked } + return backend + } + + account.openIfNeeded() + #expect(account.availability == .waitingForUnlock) + + locked = false + account.sceneBecameActive() + #expect(account.availability == .open) + } + + @Test("A Keychain that refuses for good leaves the account unavailable, and it is not asked again") + func failedStaysUnavailable() { + var opens = 0 + let account = AccountModel { _, _ throws(AccountKeychainFailure) in + opens += 1 + throw .failed("Keychain error -34018") + } + + account.openIfNeeded() + account.sceneBecameActive() + + #expect(account.availability == .unavailable) + #expect(opens == 1) + } + + @Test("Sign in goes through the authenticator it is given and publishes the account") + func signIn() async throws { + let backend = ScriptedAccountBackend() + let account = opened(backend) + + try await account.signIn(using: NoPage()) + + #expect(backend.signIns == 1) + #expect(account.isSignedIn) + #expect(!account.isBusy) + } + + @Test("Signed in, another sign-in or another server goes through Sign Out first") + func signedInRefusesASwitch() async { + let backend = ScriptedAccountBackend() + backend.set(AccountSnapshot(state: .signedIn, accountID: "acct")) + let account = opened(backend) + + await #expect(throws: AccountError.signOutFirst) { try await account.signIn(using: NoPage()) } + await #expect(throws: AccountError.signOutFirst) { + try await account.chooseServer(URL(string: "https://tablepro.example.com")) + } + #expect(backend.signIns == 0) + #expect(backend.chosen.isEmpty) + } + + @Test("A canceled sign-in leaves the account signed out") + func canceledSignIn() async { + let backend = ScriptedAccountBackend() + backend.failSignIn(with: .canceled) + let account = opened(backend) + + await #expect(throws: AccountError.canceled) { try await account.signIn(using: NoPage()) } + #expect(!account.isSignedIn) + #expect(!account.isBusy) + } + + @Test("A sign-out the person did not ask for is kept to show, and a sign-in clears it") + func involuntarySignOut() async throws { + let backend = ScriptedAccountBackend() + backend.set(AccountSnapshot(state: .signedIn, accountID: "acct")) + let account = opened(backend) + + backend.set(AccountSnapshot()) + account.accountStatusChanged(signedOutBy: .deviceRevoked) + #expect(account.involuntarySignOut == .deviceRevoked) + + try await account.signIn(using: NoPage()) + #expect(account.involuntarySignOut == nil) + } + + @Test("Back in the foreground past the device limit, it asks again whether a slot was freed") + func pastDeviceLimitRefreshesOnActivation() async throws { + let backend = ScriptedAccountBackend() + backend.set(AccountSnapshot(state: .signedIn, accountID: "acct", problem: .deviceLimitReached([]))) + let account = opened(backend) + + account.sceneBecameActive() + + try await waitUntil { backend.refreshesPastLimit == 1 } + #expect(account.isPastDeviceLimit) + } + + @Test("New values from the organization reach the core in order, and the same values do not again") + func valuesReachTheCore() async throws { + let backend = ScriptedAccountBackend() + var opened: [ManagedAppConfiguration] = [] + let account = AccountModel { _, managed in + opened.append(managed) + return backend + } + account.openIfNeeded() + let held = ManagedAppConfiguration(accountServerURL: "https://tablepro.example.com", allowOtherAccountServers: false) + let released = ManagedAppConfiguration(usageDataAllowed: false) + + account.apply(held) + account.apply(held) + account.apply(released) + + try await waitUntil { backend.policies.count == 2 } + #expect(backend.policies == [held.coreArgument, released.coreArgument]) + #expect(opened == [.unmanaged]) + } + + @Test("An account opened after new values came opens with them") + func laterOpenTakesTheValues() { + var opened: [ManagedAppConfiguration] = [] + let account = AccountModel { _, managed throws(AccountKeychainFailure) in + opened.append(managed) + throw .locked + } + let held = ManagedAppConfiguration(accountServerURL: "https://tablepro.example.com", allowOtherAccountServers: false) + + account.apply(held) + account.openIfNeeded() + + #expect(opened == [held]) + } +} diff --git a/apple/TableProMobile/TableProMobileTests/Onboarding/AppStateManagedConfigurationTests.swift b/apple/TableProMobile/TableProMobileTests/Onboarding/AppStateManagedConfigurationTests.swift new file mode 100644 index 0000000000..0234d0a32d --- /dev/null +++ b/apple/TableProMobile/TableProMobileTests/Onboarding/AppStateManagedConfigurationTests.swift @@ -0,0 +1,41 @@ +import Foundation +@testable import TableProMobile +import TableProSyncTransport +import Testing + +@MainActor +struct AppStateManagedConfigurationTests { + @Test("ICloudSyncAllowed turned off stops iCloud sync at once, and lifting it brings the person's choice back") + func iCloudFollowsTheManagedConfiguration() throws { + let fixture = try AppStateFixture() + fixture.defaults.set(true, forKey: AppPreferences.cloudSyncEnabledKey) + let state = fixture.makeState(syncEnabled: true) + + fixture.defaults.set(["ICloudSyncAllowed": false], forKey: ManagedAppConfiguration.defaultsKey) + state.refreshManagedConfiguration() + + #expect(!state.onboarding.isCloudSyncEnabled) + #expect(state.syncCoordinator.status == .disabled(.userDisabled)) + #expect(state.onboarding.syncChoice == true) + + fixture.defaults.removeObject(forKey: ManagedAppConfiguration.defaultsKey) + state.refreshManagedConfiguration() + + #expect(state.onboarding.isCloudSyncEnabled) + #expect(state.syncCoordinator.status != .disabled(.userDisabled)) + } + + @Test("A first run that skipped the iCloud question for the organization leaves sync off once the policy goes") + func skippedQuestionIsNoConsent() throws { + let fixture = try AppStateFixture() + fixture.defaults.set(["ICloudSyncAllowed": false], forKey: ManagedAppConfiguration.defaultsKey) + let state = fixture.makeState(syncEnabled: false) + + state.finishFirstRun(pages: [.origin, .usageData]) + fixture.defaults.removeObject(forKey: ManagedAppConfiguration.defaultsKey) + let relaunched = OnboardingPreferences(defaults: fixture.defaults) + + #expect(relaunched.syncChoice == nil) + #expect(!relaunched.isCloudSyncEnabled) + } +} diff --git a/apple/TableProMobile/TableProMobileTests/Onboarding/FirstRunPlanTests.swift b/apple/TableProMobile/TableProMobileTests/Onboarding/FirstRunPlanTests.swift index caa8d18a4a..25fe662779 100644 --- a/apple/TableProMobile/TableProMobileTests/Onboarding/FirstRunPlanTests.swift +++ b/apple/TableProMobile/TableProMobileTests/Onboarding/FirstRunPlanTests.swift @@ -9,6 +9,8 @@ struct FirstRunPlanTests { hasConnections: Bool? = false, syncChoice: Bool? = nil, usageDataChoice: Bool? = nil, + iCloudSyncAllowed: Bool = true, + usageDataAllowed: Bool = true, lastSeenVersion: String? = nil, currentVersion: String = "1.1", hasHighlights: Bool = true @@ -18,6 +20,8 @@ struct FirstRunPlanTests { hasConnections: hasConnections, syncChoice: syncChoice, usageDataChoice: usageDataChoice, + iCloudSyncAllowed: iCloudSyncAllowed, + usageDataAllowed: usageDataAllowed, lastSeenVersion: lastSeenVersion, currentVersion: currentVersion, hasHighlightsForCurrentVersion: hasHighlights @@ -29,6 +33,8 @@ struct FirstRunPlanTests { hasConnections: Bool? = false, syncChoice: Bool? = nil, usageDataChoice: Bool? = nil, + iCloudSyncAllowed: Bool = true, + usageDataAllowed: Bool = true, lastSeenVersion: String? = nil, currentVersion: String = "1.1", hasHighlights: Bool = true @@ -38,6 +44,8 @@ struct FirstRunPlanTests { hasConnections: hasConnections, syncChoice: syncChoice, usageDataChoice: usageDataChoice, + iCloudSyncAllowed: iCloudSyncAllowed, + usageDataAllowed: usageDataAllowed, lastSeenVersion: lastSeenVersion, currentVersion: currentVersion, hasHighlights: hasHighlights @@ -50,6 +58,13 @@ struct FirstRunPlanTests { #expect(plan() == .firstRun([.origin, .iCloud, .usageData])) } + @Test("A question the organization's managed configuration answers is not asked") + func managedQuestionsAreSkipped() { + #expect(plan(iCloudSyncAllowed: false) == .firstRun([.origin, .usageData])) + #expect(plan(usageDataAllowed: false) == .firstRun([.origin, .iCloud])) + #expect(plan(hasSeenOrigin: true, syncChoice: true, usageDataAllowed: false) == .none) + } + @Test("A fresh install never shows What's New") func freshInstallSkipsWhatsNew() { #expect(plan(lastSeenVersion: nil) == .firstRun([.origin, .iCloud, .usageData])) diff --git a/apple/TableProMobile/TableProMobileTests/Onboarding/OnboardingPreferencesTests.swift b/apple/TableProMobile/TableProMobileTests/Onboarding/OnboardingPreferencesTests.swift index 6804f4d2f3..e454bf91cb 100644 --- a/apple/TableProMobile/TableProMobileTests/Onboarding/OnboardingPreferencesTests.swift +++ b/apple/TableProMobile/TableProMobileTests/Onboarding/OnboardingPreferencesTests.swift @@ -90,4 +90,34 @@ struct OnboardingPreferencesTests { #expect(OnboardingPreferences(defaults: defaults).lastSeenVersion == "1.10") } + + @Test("The organization's managed configuration turns iCloud sync and usage data off over the person's choice") + func managedConfigurationWins() { + defaults.set(true, forKey: AppPreferences.cloudSyncEnabledKey) + defaults.set(true, forKey: AppPreferences.usageDataKey) + defaults.set( + ["ICloudSyncAllowed": false, "UsageDataAllowed": false], + forKey: ManagedAppConfiguration.defaultsKey + ) + + let preferences = OnboardingPreferences(defaults: defaults) + + #expect(preferences.syncChoice == true) + #expect(preferences.usageDataChoice == true) + #expect(!preferences.isCloudSyncEnabled) + #expect(!preferences.isUsageDataEnabled) + } + + @Test("A configuration the MDM changes while the app runs is read again, and the person's choice comes back") + func managedConfigurationRefreshes() { + defaults.set(true, forKey: AppPreferences.cloudSyncEnabledKey) + defaults.set(["ICloudSyncAllowed": false], forKey: ManagedAppConfiguration.defaultsKey) + let preferences = OnboardingPreferences(defaults: defaults) + + defaults.removeObject(forKey: ManagedAppConfiguration.defaultsKey) + preferences.refreshManagedConfiguration() + + #expect(preferences.managed == .unmanaged) + #expect(preferences.isCloudSyncEnabled) + } } diff --git a/apple/TableProMobile/TableProMobileTests/Platform/ManagedAppConfigurationTests.swift b/apple/TableProMobile/TableProMobileTests/Platform/ManagedAppConfigurationTests.swift new file mode 100644 index 0000000000..6b30389a01 --- /dev/null +++ b/apple/TableProMobile/TableProMobileTests/Platform/ManagedAppConfigurationTests.swift @@ -0,0 +1,92 @@ +import Foundation +import TableProFFI +@testable import TableProMobile +import Testing + +struct ManagedAppConfigurationTests { + @Test("Each key core ADR 0055 gives iOS reads from its AppConfig type and reaches the core as read") + func readsEveryKey() { + let managed = ManagedAppConfiguration([ + "AccountServerURL": "https://tablepro.example.com", + "AllowOtherAccountServers": false, + "PersonalSyncProvider": ["tablepro-sync", "off"], + "UsageDataAllowed": false, + "ICloudSyncAllowed": false, + ]) + + #expect(managed.coreArgument == .read(values: ManagedPolicyValues( + accountServerUrl: "https://tablepro.example.com", + allowOtherAccountServers: false, + personalSyncProvider: ["tablepro-sync", "off"], + usageDataAllowed: false, + pluginCatalogAllowed: nil, + updateChecksAllowed: nil, + icloudSyncAllowed: false + ))) + #expect(!managed.allowsUsageData) + #expect(!managed.allowsICloudSync) + } + + @Test("No configuration leaves every setting to the person") + func absentIsUnmanaged() { + let managed = ManagedAppConfiguration(nil) + + #expect(managed == .unmanaged) + #expect(managed.allowsUsageData) + #expect(managed.allowsICloudSync) + #expect(!managed.locksICloudSync) + #expect(managed.settledICloudSync(true)) + #expect(!managed.settledICloudSync(false)) + } + + @Test("A value of another type counts as absent: a number is not a boolean, a string is not a list") + func otherTypesAreAbsent() { + let managed = ManagedAppConfiguration([ + "AccountServerURL": 42, + "AllowOtherAccountServers": "false", + "PersonalSyncProvider": "icloud", + "UsageDataAllowed": NSNumber(value: 0), + "ICloudSyncAllowed": [false], + ]) + + #expect(managed == .unmanaged) + } + + @Test("A list entry that is not a string is left out, and the core skips a name it does not know") + func listEntries() { + let mixed = ManagedAppConfiguration(["PersonalSyncProvider": ["icloud", 1, "dropbox"] as [Any]]) + + #expect(mixed.personalSyncProvider == ["icloud", "dropbox"]) + #expect(mixed.allowsICloudSync) + #expect(mixed.locksICloudSync) + } + + @Test("PersonalSyncProvider forces iCloud on or keeps it off, by the core's rule") + func providerListSettlesICloud() { + let forced = ManagedAppConfiguration(personalSyncProvider: ["icloud"]) + let off = ManagedAppConfiguration(personalSyncProvider: ["off"]) + let either = ManagedAppConfiguration(personalSyncProvider: ["off", "icloud"]) + let none = ManagedAppConfiguration(personalSyncProvider: []) + + #expect(forced.settledICloudSync(false) && forced.locksICloudSync) + #expect(!off.settledICloudSync(true) && off.locksICloudSync && !off.allowsICloudSync) + #expect(either.settledICloudSync(true) && !either.settledICloudSync(false) && !either.locksICloudSync) + #expect(!none.settledICloudSync(true) && none.locksICloudSync) + } + + @Test("ICloudSyncAllowed=false takes iCloud away even where the list names it") + func iCloudSyncAllowedWins() { + let managed = ManagedAppConfiguration(personalSyncProvider: ["icloud"], iCloudSyncAllowed: false) + + #expect(!managed.allowsICloudSync) + #expect(!managed.settledICloudSync(true)) + } + + @Test("It is read from the managed configuration key, where an MDM writes it") + func readsTheManagedKey() throws { + let defaults = try #require(UserDefaults(suiteName: "com.TablePro.tests.Managed.\(UUID().uuidString)")) + defaults.set(["ICloudSyncAllowed": false], forKey: "com.apple.configuration.managed") + + #expect(ManagedAppConfiguration.current(defaults: defaults).iCloudSyncAllowed == false) + } +} diff --git a/apple/TableProMobile/TableProMobileTests/Sync/IOSSyncCoordinatorTests.swift b/apple/TableProMobile/TableProMobileTests/Sync/IOSSyncCoordinatorTests.swift index d4e08f766c..21d97abe24 100644 --- a/apple/TableProMobile/TableProMobileTests/Sync/IOSSyncCoordinatorTests.swift +++ b/apple/TableProMobile/TableProMobileTests/Sync/IOSSyncCoordinatorTests.swift @@ -249,6 +249,22 @@ struct IOSSyncCoordinatorTests { #expect(pushed.first { $0.id == local.id }?.name == "New") } + @Test("Sync turned off during the download, as a managed configuration does, uploads nothing") + func turnedOffDuringPullUploadsNothing() async throws { + let box = LibraryStateBox() + let local = DatabaseConnection(name: "Prod", type: .postgresql) + box.connections = [local] + let transport = FakeSyncTransport(remoteRecords: [], box: box) + let coordinator = makeCoordinator(box: box, transport: transport) + coordinator.markDirty(local.id) + box.duringPull = { box.syncEnabled = false } + + await coordinator.sync() + + #expect(await transport.pushedRecords.isEmpty) + #expect(coordinator.status == .disabled(.userDisabled)) + } + @Test("A copy stored before this build read it takes the profile link from the cached record") func olderCopyTakesProfileFromTheCache() async throws { let box = LibraryStateBox() diff --git a/apple/TableProMobile/project.yml b/apple/TableProMobile/project.yml index e887f6a3ef..b183d2bb74 100644 --- a/apple/TableProMobile/project.yml +++ b/apple/TableProMobile/project.yml @@ -30,6 +30,10 @@ packages: path: ../Packages/TableProCore TableProOracle: path: ../Packages/TableProOracle + # The shared Rust core, for the TablePro account (core ADR 0047). ../scripts/build-core.sh ios-simulator, or ios for a + # device, builds its binary target first: SwiftPM resolves nothing here without it. + TableProFFI: + path: ../Packages/TableProFFI # Usage data (clients.md, iOS). The same pin as ../project.yml; a build sends it only with POSTHOG_PROJECT_KEY set. PostHog: url: https://github.com/PostHog/posthog-ios @@ -85,6 +89,8 @@ targets: - ../TablePro/Theme/MotionAccessibility.swift # The PostHog client and what it may collect, the same in both apps. - ../TablePro/Core/Services/Telemetry/PostHogTelemetryClient.swift + # The account's adapter over the core, its Keychain host secrets and its sign-in sheet, the same in both apps. + - ../TablePro/Core/Services/Account/Shared # The ClickHouse plugin driver runs whole behind PluginBackedDriver, so every file of the plugin is compiled in. - path: ../Plugins/ClickHouseDriverPlugin excludes: @@ -289,6 +295,7 @@ targets: - TableProWireIO - package: TableProOracle product: TableProOracleCore + - package: TableProFFI - package: PostHog - framework: ../Libs/ios/DuckDB.xcframework embed: false diff --git a/apple/TableProTests/Core/Services/Account/AccountCoreSetupTests.swift b/apple/TableProTests/Core/Services/Account/AccountCoreSetupTests.swift index 500abafd9b..8a26a8f037 100644 --- a/apple/TableProTests/Core/Services/Account/AccountCoreSetupTests.swift +++ b/apple/TableProTests/Core/Services/Account/AccountCoreSetupTests.swift @@ -5,6 +5,7 @@ import Foundation @testable import TablePro +import TableProFFI import Testing struct AccountCoreSetupTests { @@ -77,6 +78,44 @@ struct AccountCoreSetupTests { } } +struct AccountCoreSetupConfigTests { + @Test("The core gets the Mac's client, its machine ID, the profile's values and the entitlement file from before") + func configIsTheMacs() { + let setup = AccountCoreSetup.make( + supportDirectory: URL(fileURLWithPath: "/Users/ada/Library/Application Support/TablePro", isDirectory: true), + machineID: "mid", + policy: ManagedPolicySnapshot(accountServerURL: "https://tablepro.example.com", allowOtherAccountServers: false), + environment: [:], isDebugBuild: false + ) + let machine = MachineDescription(machineID: "mid", name: "Ada's Mac", appVersion: "0.90.0", osVersion: "26.1") + + let config = setup.accountConfig(machine: machine) + + #expect(config.client == .macos) + #expect(config.machineId == "mid") + #expect(config.deviceName == "Ada's Mac") + #expect(config.policy == setup.policy.coreArgument) + #expect(config.legacyEntitlementFile == setup.legacyEntitlementFile.path) + #expect(config.accountUrl == nil && config.apiUrl == nil && config.licenseKeys.isEmpty) + } + + @Test("A development stack's addresses and keys reach the core with the /v2 base") + func developmentStackReachesTheCore() { + let setup = AccountCoreSetup.make( + supportDirectory: URL(fileURLWithPath: "/tmp", isDirectory: true), machineID: "mid", + policy: ManagedPolicySnapshot(), + environment: ["TABLEPRO_ACCOUNT_URL": "http://account.localhost:5284", "TABLEPRO_API_URL": "http://api.localhost:5284/"], + isDebugBuild: true + ) + let machine = MachineDescription(machineID: "mid", name: "Mac", appVersion: "0.90.0", osVersion: "26.1") + + let config = setup.accountConfig(machine: machine) + + #expect(config.accountUrl == "http://account.localhost:5284") + #expect(config.apiUrl == "http://api.localhost:5284/v2") + } +} + struct AccountRefreshTokenItemTests { @Test("tablepro.app's refresh token stays in the item earlier builds wrote, so an update stays signed in") func productionKeepsTheItem() { diff --git a/apple/TableProTests/Core/Services/Account/AccountServicesTests.swift b/apple/TableProTests/Core/Services/Account/AccountServicesTests.swift index 61ba37e985..270d25a538 100644 --- a/apple/TableProTests/Core/Services/Account/AccountServicesTests.swift +++ b/apple/TableProTests/Core/Services/Account/AccountServicesTests.swift @@ -7,6 +7,7 @@ import Combine import Foundation @testable import TablePro import TableProCloudAPI +import TableProFFI import TableProTestSupport import Testing @@ -464,7 +465,7 @@ struct AccountServicesTests { readings.send(held) - try await waitUntil { fixture.backend.appliedPolicies.last == held } + try await waitUntil { fixture.backend.appliedPolicies.last == held.coreArgument } fixture.services.stop() } diff --git a/apple/TableProTests/Core/Services/Account/CoreAccountMappingTests.swift b/apple/TableProTests/Core/Services/Account/CoreAccountMappingTests.swift index a3775c1e15..9f4c4d5fdf 100644 --- a/apple/TableProTests/Core/Services/Account/CoreAccountMappingTests.swift +++ b/apple/TableProTests/Core/Services/Account/CoreAccountMappingTests.swift @@ -144,7 +144,7 @@ struct CoreAccountMappingTests { } #expect(holders.map(\.name) == ["Workstation"]) #expect(holders.first?.holdsLicense == true) - #expect(holders.first?.isThisMac == false) + #expect(holders.first?.isThisDevice == false) } @Test("A company server and its license read as the core verified them") diff --git a/apple/TableProTests/Core/Services/Account/FakeAccountBackend.swift b/apple/TableProTests/Core/Services/Account/FakeAccountBackend.swift index 30f62e1ab7..88c870b028 100644 --- a/apple/TableProTests/Core/Services/Account/FakeAccountBackend.swift +++ b/apple/TableProTests/Core/Services/Account/FakeAccountBackend.swift @@ -6,6 +6,7 @@ import Foundation @testable import TablePro import TableProCloudAPI +import TableProFFI struct FakeEntitlementAnswer: @unchecked Sendable { let isOffline: Bool @@ -53,7 +54,7 @@ final class FakeAccountBackend: AccountBackend, @unchecked Sendable { private var keychainRefuses = false private var bearerFailure: AccountError? private var allowsTableProRequestsValue = true - private var policies: [ManagedPolicySnapshot] = [] + private var policies: [ManagedPolicyArg] = [] // Runs as the core is told its token was refused, as if the person changed server at that moment. var onTokenRejected: (@Sendable (FakeAccountBackend) -> Void)? @@ -74,7 +75,7 @@ final class FakeAccountBackend: AccountBackend, @unchecked Sendable { locked { allowsTableProRequestsValue = !held } } - var appliedPolicies: [ManagedPolicySnapshot] { + var appliedPolicies: [ManagedPolicyArg] { locked { policies } } @@ -164,7 +165,7 @@ final class FakeAccountBackend: AccountBackend, @unchecked Sendable { locked { snapshot } } - func featureAccess(_ feature: ProFeature) -> ProFeatureAccess { + func featureAccess(code: String) -> ProFeatureAccess { let snapshot = status() let current = snapshot.expiresAt.map { now() < $0 } ?? false switch snapshot.state { @@ -172,15 +173,15 @@ final class FakeAccountBackend: AccountBackend, @unchecked Sendable { return .signedOut case .offline: guard current else { return .expired } - return snapshot.features.contains(feature.rawValue) ? .available : .notIncluded + return snapshot.features.contains(code) ? .available : .notIncluded case .signedIn: // As the core: past a company license's grace only the Team Library works. - if let graceEndsAt = license()?.graceEndsAt, now() >= graceEndsAt, feature != .teamLibrary, - snapshot.features.contains(feature.rawValue) { + if let graceEndsAt = license()?.graceEndsAt, now() >= graceEndsAt, code != ProFeature.teamLibrary.rawValue, + snapshot.features.contains(code) { return .expired } if current { - return snapshot.features.contains(feature.rawValue) ? .available : .notIncluded + return snapshot.features.contains(code) ? .available : .notIncluded } switch snapshot.problem { case .deviceLimitReached: return .notIncluded @@ -342,7 +343,7 @@ final class FakeAccountBackend: AccountBackend, @unchecked Sendable { onTokenRejected?(self) } - func applyPolicy(_ policy: ManagedPolicySnapshot) async { + func applyPolicy(_ policy: ManagedPolicyArg) async { locked { policies.append(policy) } } @@ -432,7 +433,7 @@ final class FakeAccountBackend: AccountBackend, @unchecked Sendable { private static func device(_ json: [String: Any]) -> AccountDevice { AccountDevice( id: json["id"] as? String ?? "", - isThisMac: json["machine_id"] as? String == FakeAccountServer.machine.machineID, + isThisDevice: json["machine_id"] as? String == FakeAccountServer.machine.machineID, name: json["name"] as? String ?? "", platform: json["platform"] as? String ?? "", osVersion: json["os_version"] as? String ?? "", diff --git a/apple/TableProTests/Views/Settings/AccountSettingsContentTests.swift b/apple/TableProTests/Views/Settings/AccountSettingsContentTests.swift index 430a7b2f92..908968d31a 100644 --- a/apple/TableProTests/Views/Settings/AccountSettingsContentTests.swift +++ b/apple/TableProTests/Views/Settings/AccountSettingsContentTests.swift @@ -367,7 +367,7 @@ struct AccountSettingsContentTests { func devices() throws { func device(_ id: String, machineID: String, lastSeen: TimeInterval, offlineUntil: Date? = nil) -> AccountDevice { AccountDevice( - id: id, isThisMac: machineID == Self.machineID, name: id, platform: "linux", osVersion: "Fedora 43", + id: id, isThisDevice: machineID == Self.machineID, name: id, platform: "linux", osVersion: "Fedora 43", lastSeenAt: Self.now.addingTimeInterval(lastSeen), holdsLicense: true, offlineUntil: offlineUntil ) } @@ -465,10 +465,10 @@ struct AccountSettingsContentTests { @Test("This Mac's row says so and reads as seen now; another device keeps its last check") func deviceDetail() { let lastSeen = Date().addingTimeInterval(-3 * Self.day) - let thisMac = AccountDeviceText.detail(system: "macOS 27.0", lastSeenAt: lastSeen, isThisMac: true) + let thisMac = AccountDeviceText.detail(system: "macOS 27.0", lastSeenAt: lastSeen, isThisDevice: true) #expect(thisMac == AccountDeviceText.detail(system: "This Mac ยท macOS 27.0", lastSeenAt: Date())) - let other = AccountDeviceText.detail(system: "macOS 15.1", lastSeenAt: lastSeen, isThisMac: false) + let other = AccountDeviceText.detail(system: "macOS 15.1", lastSeenAt: lastSeen, isThisDevice: false) #expect(other == AccountDeviceText.detail(system: "macOS 15.1", lastSeenAt: lastSeen)) } diff --git a/apple/TableProTests/Views/Settings/AccountSettingsModelTests.swift b/apple/TableProTests/Views/Settings/AccountSettingsModelTests.swift index 0b5b012f9c..3787637e68 100644 --- a/apple/TableProTests/Views/Settings/AccountSettingsModelTests.swift +++ b/apple/TableProTests/Views/Settings/AccountSettingsModelTests.swift @@ -20,7 +20,7 @@ struct AccountSettingsModelTests { AccountMembership(teamID: "team_acme", teamName: "Acme", role: "member", hasSeat: false) ]) #expect(model.devices.value?.map { $0.id } == [FakeAccountServer.deviceID]) - #expect(model.content.devices?.first?.isThisMac == true) + #expect(model.content.devices?.first?.isThisDevice == true) #expect(model.content.teams?.first?.hasSeat == false) } @@ -90,7 +90,7 @@ struct AccountSettingsModelTests { #expect(model.content.devices?.first { $0.id == "dev_air" }?.canRemove == false) await model.removeDevice(.init( - id: row.id, name: row.name, system: "", lastSeenAt: row.lastSeenAt, isThisMac: false, offlineUntil: nil + id: row.id, name: row.name, system: "", lastSeenAt: row.lastSeenAt, isThisDevice: false, offlineUntil: nil )) #expect(model.actionFailure?.message == AccountError.server(status: 409, code: "offline_file_active").deviceRemovalDescription) diff --git a/apple/changelog.d/4492.added.1.md b/apple/changelog.d/4492.added.1.md new file mode 100644 index 0000000000..90fe803db7 --- /dev/null +++ b/apple/changelog.d/4492.added.1.md @@ -0,0 +1 @@ +On iPhone and iPad, an organization's MDM can set the account server and turn off iCloud sync or usage data. diff --git a/apple/changelog.d/4492.added.md b/apple/changelog.d/4492.added.md new file mode 100644 index 0000000000..809d660d66 --- /dev/null +++ b/apple/changelog.d/4492.added.md @@ -0,0 +1 @@ +Sign in to a TablePro account, or your organization's TablePro server, on iPhone and iPad. diff --git a/apple/scripts/build-core.sh b/apple/scripts/build-core.sh index 1494632779..71a8949201 100755 --- a/apple/scripts/build-core.sh +++ b/apple/scripts/build-core.sh @@ -1,8 +1,12 @@ #!/usr/bin/env bash -# Builds the shared Rust core as the static library the Apple apps link, and its Swift bindings from that same -# library, into Packages/TableProFFI (core/docs/decisions/0010-macos-on-the-core.md). Neither is in git. +# Builds the shared Rust core as the static libraries the Apple apps link, and its Swift bindings from one of them, +# into Packages/TableProFFI (core/docs/decisions/0010-macos-on-the-core.md). Neither is in git. # -# Usage: build-core.sh [arm64|x86_64|both] both, the default, is the universal slice the app ships +# Usage: build-core.sh [slice...] +# arm64, x86_64, both the macOS slice for that architecture; both is the universal one the app ships +# ios the iOS slice, for the iPhone and iPad +# ios-simulator the iOS Simulator slice, Apple silicon only like the other iOS libraries +# With no slice it builds both. Each run replaces the XCFramework, so name every slice this checkout builds. set -euo pipefail APPLE_DIR="$(cd "$(dirname "$0")/.." && pwd)" @@ -10,19 +14,41 @@ REPO_ROOT="$(cd "$APPLE_DIR/.." && pwd)" PACKAGE_DIR="$APPLE_DIR/Packages/TableProFFI" BUILD_DIR="$PACKAGE_DIR/Build" TARGET_DIR="${CARGO_TARGET_DIR:-$REPO_ROOT/target}" -ARCH="${1:-both}" source "$APPLE_DIR/scripts/lib/deployment-target.sh" source "$APPLE_DIR/scripts/lib/system-sqlite.sh" -case "$ARCH" in - arm64) TRIPLES=(aarch64-apple-darwin) ;; - x86_64) TRIPLES=(x86_64-apple-darwin) ;; - both) TRIPLES=(aarch64-apple-darwin x86_64-apple-darwin) ;; - *) - echo "Usage: $0 [arm64|x86_64|both]" >&2 - exit 1 - ;; -esac +usage() { + echo "Usage: $0 [arm64|x86_64|both] [ios] [ios-simulator]" >&2 + exit 1 +} + +MACOS_TRIPLES=() +IOS=false +IOS_SIMULATOR=false +[ $# -gt 0 ] || set -- both +for slice in "$@"; do + case "$slice" in + arm64 | x86_64 | both) + [ ${#MACOS_TRIPLES[@]} -eq 0 ] || usage + case "$slice" in + arm64) MACOS_TRIPLES=(aarch64-apple-darwin) ;; + x86_64) MACOS_TRIPLES=(x86_64-apple-darwin) ;; + both) MACOS_TRIPLES=(aarch64-apple-darwin x86_64-apple-darwin) ;; + esac + ;; + ios) IOS=true ;; + ios-simulator) IOS_SIMULATOR=true ;; + *) usage ;; + esac +done + +# Bash 3.2, which macOS ships, calls an empty array unbound under set -u, hence the ${a[@]+...} forms. +TRIPLES=(${MACOS_TRIPLES[@]+"${MACOS_TRIPLES[@]}"}) +[ "$IOS" = false ] || TRIPLES+=(aarch64-apple-ios) +[ "$IOS_SIMULATOR" = false ] || TRIPLES+=(aarch64-apple-ios-sim) +if [ "$IOS" = true ] || [ "$IOS_SIMULATOR" = true ]; then + IOS_TARGET="$(ios_deployment_target)" +fi archive() { echo "$TARGET_DIR/$1/release/libtablepro_ffi.a" @@ -33,29 +59,54 @@ cd "$REPO_ROOT" rustup target add "${TRIPLES[@]}" for triple in "${TRIPLES[@]}"; do + # rustc and the cc crate read the minimum OS from these, IPHONEOS_ for the device and the Simulator alike. + case "$triple" in + *-apple-darwin) minimum=(MACOSX_DEPLOYMENT_TARGET="$DEPLOY_TARGET") ;; + *) minimum=(IPHONEOS_DEPLOYMENT_TARGET="$IOS_TARGET") ;; + esac # The crate is a cdylib for Windows; the Apple apps link a static library, without the engines no slice moves yet. - env MACOSX_DEPLOYMENT_TARGET="$DEPLOY_TARGET" cargo rustc --locked -p tablepro-ffi --lib --release \ + env "${minimum[@]}" cargo rustc --locked -p tablepro-ffi --lib --release \ --no-default-features --target "$triple" --crate-type staticlib done rm -rf "$BUILD_DIR" -mkdir -p "$BUILD_DIR/lib" "$BUILD_DIR/include" "$PACKAGE_DIR/Sources/TableProFFI" -ARCHIVES=() -for triple in "${TRIPLES[@]}"; do - ARCHIVES+=("$(archive "$triple")") -done -lipo -create "${ARCHIVES[@]}" -output "$BUILD_DIR/lib/libtablepro_ffi.a" -lipo -info "$BUILD_DIR/lib/libtablepro_ffi.a" -verify_deployment_target "$BUILD_DIR/lib/libtablepro_ffi.a" -verify_system_sqlite "$BUILD_DIR/lib/libtablepro_ffi.a" +mkdir -p "$BUILD_DIR/include" "$PACKAGE_DIR/Sources/TableProFFI" +LIBRARIES=() + +if [ ${#MACOS_TRIPLES[@]} -gt 0 ]; then + mkdir -p "$BUILD_DIR/macos" + ARCHIVES=() + for triple in ${MACOS_TRIPLES[@]+"${MACOS_TRIPLES[@]}"}; do + ARCHIVES+=("$(archive "$triple")") + done + lipo -create "${ARCHIVES[@]}" -output "$BUILD_DIR/macos/libtablepro_ffi.a" + lipo -info "$BUILD_DIR/macos/libtablepro_ffi.a" + verify_deployment_target "$BUILD_DIR/macos/libtablepro_ffi.a" + verify_system_sqlite "$BUILD_DIR/macos/libtablepro_ffi.a" + LIBRARIES+=("$BUILD_DIR/macos/libtablepro_ffi.a") +fi -# Generated from the library just built: UniFFI checks at load that the two carry the same API checksums. +# The Simulator and the device read the same header, so one SDK's marks check both. +ios_slice() { + mkdir -p "$BUILD_DIR/$1" + cp "$(archive "$2")" "$BUILD_DIR/$1/libtablepro_ffi.a" + verify_deployment_target_for iOS "$IOS_TARGET" "$BUILD_DIR/$1/libtablepro_ffi.a" + verify_system_sqlite "$BUILD_DIR/$1/libtablepro_ffi.a" iphoneos ios "$IOS_TARGET" iOS + LIBRARIES+=("$BUILD_DIR/$1/libtablepro_ffi.a") +} +[ "$IOS" = false ] || ios_slice ios aarch64-apple-ios +[ "$IOS_SIMULATOR" = false ] || ios_slice ios-simulator aarch64-apple-ios-sim + +# Generated from a library just built: UniFFI checks at load that the two carry the same API checksums, and every +# slice exports the same API. cargo run --locked --quiet -p tablepro-bindgen --bin uniffi-bindgen-swift -- \ --swift-sources --headers --modulemap --module-name TableProFFIC --modulemap-filename module.modulemap \ - "${ARCHIVES[0]}" "$BUILD_DIR/include" + "$(archive "${TRIPLES[0]}")" "$BUILD_DIR/include" mv "$BUILD_DIR/include/TableProFFI.swift" "$PACKAGE_DIR/Sources/TableProFFI/TableProFFI.swift" -xcodebuild -create-xcframework \ - -library "$BUILD_DIR/lib/libtablepro_ffi.a" -headers "$BUILD_DIR/include" \ - -output "$BUILD_DIR/TableProFFIC.xcframework" -echo "Built $BUILD_DIR/TableProFFIC.xcframework for macOS $DEPLOY_TARGET (${TRIPLES[*]})" +XCFRAMEWORK_ARGS=() +for library in "${LIBRARIES[@]}"; do + XCFRAMEWORK_ARGS+=(-library "$library" -headers "$BUILD_DIR/include") +done +xcodebuild -create-xcframework "${XCFRAMEWORK_ARGS[@]}" -output "$BUILD_DIR/TableProFFIC.xcframework" +echo "Built $BUILD_DIR/TableProFFIC.xcframework: $*" diff --git a/apple/scripts/lib/deployment-target.sh b/apple/scripts/lib/deployment-target.sh index 314088b8f0..a9554092f9 100644 --- a/apple/scripts/lib/deployment-target.sh +++ b/apple/scripts/lib/deployment-target.sh @@ -1,6 +1,7 @@ # The macOS deployment target every native library and bridge is built for, read from project.yml, -# and the check that a built Mach-O stays at or below it. Sourced, never executed. Unlike common.sh -# it sets no LIBS_DIR or REPO_ROOT, so a script with its own can source it. +# the iOS one from TableProMobile/project.yml, and the check that a built Mach-O stays at or below +# it. Sourced, never executed. Unlike common.sh it sets no LIBS_DIR or REPO_ROOT, so a script with +# its own can source it. # # shellcheck shell=bash # shellcheck disable=SC2034 # DEPLOY_TARGET is read by the scripts that source this @@ -23,7 +24,7 @@ if [ -z "$DEPLOY_TARGET" ]; then exit 1 fi -# The highest minimum macOS across every slice and archive member, from LC_BUILD_VERSION or the +# The highest minimum OS across every slice and archive member, from LC_BUILD_VERSION or the # older LC_VERSION_MIN_MACOSX: one newer object is enough to keep the whole file off the floor. macho_min_version() { otool -arch all -l "$1" 2> /dev/null | awk ' @@ -33,21 +34,44 @@ macho_min_version() { ' | sort -V | tail -1 } +# Read when a script asks, so a macOS-only script never depends on the iOS project. +ios_deployment_target() { + local target + target="$( + awk ' + /^ deploymentTarget:/ { inTarget = 1; next } + inTarget && /^ iOS:/ { gsub(/[" ]/, "", $2); print $2; exit } + inTarget && /^[^ ]/ { exit } + ' "$TABLEPRO_DEPLOY_TARGET_ROOT/TableProMobile/project.yml" + )" + if [ -z "$target" ]; then + echo "Could not read deploymentTarget.iOS from $TABLEPRO_DEPLOY_TARGET_ROOT/TableProMobile/project.yml" >&2 + return 1 + fi + echo "$target" +} + verify_deployment_target() { - local file name version failed=0 + verify_deployment_target_for macOS "$DEPLOY_TARGET" "$@" +} + +# Usage: verify_deployment_target_for ... +verify_deployment_target_for() { + local system="$1" target="$2" file name version failed=0 + shift 2 echo "" echo "๐Ÿ” Verifying deployment targets..." for file in "$@"; do [ -f "$file" ] || continue name=$(basename "$file") if ! version=$(macho_min_version "$file") || [ -z "$version" ]; then - echo " โŒ $name records no minimum macOS" + echo " โŒ $name records no minimum $system" failed=1 - elif [ "$(printf '%s\n' "$DEPLOY_TARGET" "$version" | sort -V | tail -1)" != "$DEPLOY_TARGET" ]; then - echo " โŒ $name targets macOS $version (expected $DEPLOY_TARGET)" + elif [ "$(printf '%s\n' "$target" "$version" | sort -V | tail -1)" != "$target" ]; then + echo " โŒ $name targets $system $version (expected $target)" failed=1 else - echo " โœ… $name targets macOS $version" + echo " โœ… $name targets $system $version" fi done if [ "$failed" -eq 1 ]; then diff --git a/apple/scripts/lib/system-sqlite.sh b/apple/scripts/lib/system-sqlite.sh index bb1e2994e8..75104f7f31 100644 --- a/apple/scripts/lib/system-sqlite.sh +++ b/apple/scripts/lib/system-sqlite.sh @@ -1,6 +1,6 @@ # The check that the core's static library takes SQLite from the system, as the app does. Sourced, never executed. # Two copies in one process break each other's POSIX locks on the same file (core/docs/decisions/0010-macos-on-the-core.md), -# and the system's library only has the functions the deployment target's macOS shipped: the SDK header marks each newer +# and the system's library only has the functions the deployment target's OS shipped: the SDK header marks each newer # one with API_AVAILABLE, which the core's generated bindings drop. # # shellcheck shell=bash @@ -10,12 +10,14 @@ TABLEPRO_SYSTEM_SQLITE_SOURCED=1 source "$(dirname "${BASH_SOURCE[0]}")/deployment-target.sh" -# Every function and variable sqlite3.h declares, with the macOS release that added it, or 0 when it carries no mark. +# Every function and variable sqlite3.h declares, with the release of (macos, ios) that added it, or 0 when +# it carries no mark. +# Usage: sqlite_header_availability
[platform] sqlite_header_availability() { - awk ' + awk -v platform="${2:-macos}" ' /^API_AVAILABLE\(/ { since = "0" - if (match($0, /macos\([0-9.]+\)/)) since = substr($0, RSTART + 6, RLENGTH - 7) + if (match($0, platform "\\([0-9.]+\\)")) since = substr($0, RSTART + length(platform) + 1, RLENGTH - length(platform) - 2) next } /^SQLITE_API/ { @@ -31,9 +33,12 @@ sqlite_header_availability() { ' "$1" } +# Usage: verify_system_sqlite [sdk platform target system], macOS by default: +# verify_system_sqlite libtablepro_ffi.a iphoneos ios 18.0 iOS verify_system_sqlite() { - local archive="$1" header sdk defined called failed=0 name since - sdk="$(xcrun --sdk macosx --show-sdk-path)" || return 1 + local archive="$1" sdk_name="${2:-macosx}" platform="${3:-macos}" target="${4:-$DEPLOY_TARGET}" system="${5:-macOS}" + local header sdk defined called failed=0 name since + sdk="$(xcrun --sdk "$sdk_name" --show-sdk-path)" || return 1 header="$sdk/usr/include/sqlite3.h" echo "" echo "๐Ÿ” Verifying the system SQLite linkage..." @@ -49,21 +54,21 @@ verify_system_sqlite() { return 1 fi local available - available="$(sqlite_header_availability "$header")" + available="$(sqlite_header_availability "$header" "$platform")" while IFS= read -r name; do [ -n "$name" ] || continue since="$(awk -v n="$name" '$1 == n { print $2; exit }' <<< "$available")" if [ -z "$since" ]; then echo " โŒ $name is not in $header" >&2 failed=1 - elif [ "$(printf '%s\n' "$DEPLOY_TARGET" "$since" | sort -V | tail -1)" != "$DEPLOY_TARGET" ]; then - echo " โŒ $name needs macOS $since, above the deployment target $DEPLOY_TARGET" >&2 + elif [ "$(printf '%s\n' "$target" "$since" | sort -V | tail -1)" != "$target" ]; then + echo " โŒ $name needs $system $since, above the deployment target $target" >&2 failed=1 fi done < <(sed -n 's/^_\(sqlite3_[A-Za-z0-9_]*\)$/\1/p' <<< "$called" | sort -u) if [ "$failed" -ne 0 ]; then - echo "โŒ FATAL: the core calls SQLite functions macOS $DEPLOY_TARGET does not have" >&2 + echo "โŒ FATAL: the core calls SQLite functions $system $target does not have" >&2 return 1 fi - echo " โœ… $(basename "$archive") calls the system SQLite, every function present on macOS $DEPLOY_TARGET" + echo " โœ… $(basename "$archive") calls the system SQLite, every function present on $system $target" } diff --git a/apple/scripts/probes/account-local-stack/main.swift b/apple/scripts/probes/account-local-stack/main.swift index 5467e0bc5b..96a49e5937 100644 --- a/apple/scripts/probes/account-local-stack/main.swift +++ b/apple/scripts/probes/account-local-stack/main.swift @@ -128,7 +128,7 @@ struct AccountLocalStackProbe { script: script, rowsScript: rowsScript, steps: Set((environment["PROBE_STEPS"] ?? "").split(separator: ",").map(String.init)), - stack: AccountCoreSetup.developmentStack(environment) + stack: AccountDevelopmentStack.read(environment) ) await probe.run() print("\(probe.report.passed) passed, \(probe.report.failed) failed") @@ -144,7 +144,7 @@ private final class Probe { private let script: String private let rowsScript: String private let steps: Set - private let stack: AccountCoreSetup.DevelopmentStack? + private let stack: AccountDevelopmentStack? private let machine = MachineDescription.current() private let scratch = "account-local-stack-\(UUID().uuidString)" private var directory: URL { FileManager.default.temporaryDirectory.appendingPathComponent(scratch, isDirectory: true) } @@ -155,7 +155,7 @@ private final class Probe { script: String, rowsScript: String, steps: Set, - stack: AccountCoreSetup.DevelopmentStack? + stack: AccountDevelopmentStack? ) { self.config = config self.library = library @@ -230,7 +230,7 @@ private final class Probe { let devices = try? await services.fetchDevices() report.expect( - devices?.contains { $0.isThisMac && $0.holdsLicense } == true, + devices?.contains { $0.isThisDevice && $0.holdsLicense } == true, "GET /v2/devices lists this Mac as licensed" ) do throws(AccountError) { @@ -316,7 +316,7 @@ private final class Probe { let devices = (try? await services.fetchDevices()) ?? [] report.expect( - devices.count == 4 && devices.contains { $0.isThisMac && !$0.holdsLicense }, + devices.count == 4 && devices.contains { $0.isThisDevice && !$0.holdsLicense }, "GET /v2/devices lists the holders and this Mac without a slot", "\(devices.map { "\($0.name) \($0.holdsLicense)" })" ) @@ -705,7 +705,11 @@ private final class Probe { policy: ManagedPolicySnapshot(), developmentStack: stack ) - let backend = CoreAccountBackend(setup: setup, machine: machine, keychain: AccountKeychain(keychain: keychain)) + let backend = CoreAccountBackend( + config: setup.accountConfig(machine: machine), + appVersion: machine.appVersion, + keychain: AccountKeychain(keychain: keychain) + ) let services = AccountServices( backend: backend, transport: LoggedTransport(log: log), diff --git a/apple/scripts/probes/check-account-local-stack.sh b/apple/scripts/probes/check-account-local-stack.sh index 6ca778b3d5..83b83c6fd4 100755 --- a/apple/scripts/probes/check-account-local-stack.sh +++ b/apple/scripts/probes/check-account-local-stack.sh @@ -68,7 +68,7 @@ node "$PROBE/seed-library.cjs" "$WORK/library.json" "$DOMAIN" || cannot_run "see mkdir -p "$WORK/Sources/Probe" SOURCES="$WORK/Sources/Probe" -for source in "$ROOT"/TablePro/Core/Services/Account/*.swift; do +for source in "$ROOT"/TablePro/Core/Services/Account/*.swift "$ROOT"/TablePro/Core/Services/Account/Shared/*.swift; do case "$(basename "$source")" in AccountServices+Live.swift) continue ;; esac diff --git a/apple/scripts/update-core-licenses.sh b/apple/scripts/update-core-licenses.sh index ff706b2ee4..97e57e27c6 100755 --- a/apple/scripts/update-core-licenses.sh +++ b/apple/scripts/update-core-licenses.sh @@ -23,13 +23,14 @@ fi work="$(mktemp -d)" trap 'rm -rf "$work"' EXIT -# The library build-core.sh makes: no engines, both Apple architectures. +# The libraries build-core.sh makes: no engines, every macOS and iOS slice. generate() { cargo about generate --locked --fail \ --config "$REPO_ROOT/linux/about.toml" \ --manifest-path "$REPO_ROOT/core/crates/ffi/Cargo.toml" \ --no-default-features \ --target aarch64-apple-darwin --target x86_64-apple-darwin \ + --target aarch64-apple-ios --target aarch64-apple-ios-sim \ --output-file "$2" \ "$1" } diff --git a/core/crates/account/src/account/mac_tests.rs b/core/crates/account/src/account/mac_tests.rs index 86d442b318..4805f67586 100644 --- a/core/crates/account/src/account/mac_tests.rs +++ b/core/crates/account/src/account/mac_tests.rs @@ -78,11 +78,30 @@ fn approved(url: &Url) -> Result { } fn mac(dir: &Path, endpoints: Endpoints, keyring: Arc, authenticator: Option>) -> Account { - let settings = AccountSettings { - client: AppClient::MACOS, - legacy_entitlement_file: Some(dir.join("Account").join("entitlement.jwt")), - ..stub_settings(dir, endpoints) - }; + apple( + AccountSettings { + client: AppClient::MACOS, + legacy_entitlement_file: Some(dir.join("Account").join("entitlement.jwt")), + ..stub_settings(dir, endpoints) + }, + keyring, + authenticator, + ) +} + +// The iOS app has no sign-in from before the core to adopt. +fn iphone(dir: &Path, endpoints: Endpoints, keyring: Arc, authenticator: Arc) -> Account { + apple( + AccountSettings { + client: AppClient::IOS, + ..stub_settings(dir, endpoints) + }, + keyring, + Some(authenticator), + ) +} + +fn apple(settings: AccountSettings, keyring: Arc, authenticator: Option>) -> Account { let hosts = AccountHosts { vaults: Arc::new(crate::token_vault::SingleVault(keyring)), browser: Arc::new(super::tests::NoBrowser), @@ -167,6 +186,48 @@ async fn a_mac_signs_in_through_its_web_authenticator_as_its_own_client() { ); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn an_iphone_signs_in_through_the_same_scheme_as_its_own_client_and_registers_as_ios() { + let dir = tempfile::tempdir().expect("a temporary directory"); + let requests = Asked::default(); + let authenticator = Authenticator::answering(approved); + let account = iphone( + dir.path(), + production_stub(requests.clone()), + Keyring::holding(None), + authenticator.clone(), + ); + + account.sign_in(std::future::pending()).await.expect("signed in"); + + let [(url, scheme)] = authenticator.asked().try_into().expect("one page"); + assert_eq!(scheme, "app.tablepro"); + assert_eq!(query(&url, "client_id").as_deref(), Some("tablepro-ios")); + assert_eq!( + query(&url, "redirect_uri").as_deref(), + Some("app.tablepro:/oauth/callback") + ); + let sent = asked(&requests); + let exchange = sent + .iter() + .find(|request| request.starts_with("POST /oauth/token")) + .expect("the exchange"); + assert_eq!( + form(exchange.splitn(3, ' ').nth(2).unwrap_or_default()) + .get("client_id") + .map(String::as_str), + Some("tablepro-ios") + ); + let registration = sent + .iter() + .find_map(|request| request.strip_prefix("POST /v2/devices ")) + .expect("the device registration"); + let body: serde_json::Value = serde_json::from_str(registration).expect("a JSON body"); + assert_eq!(body["platform"], "ios"); + assert_eq!(body["machine_id"], machine().as_str()); + assert!(signed_in(&account).entitlement.is_some()); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn a_web_sign_in_that_is_canceled_or_comes_back_elsewhere_signs_nothing_in() { let answers: [(Answer, &str); 4] = [ diff --git a/core/crates/account/src/account_settings.rs b/core/crates/account/src/account_settings.rs index 43a889f175..e00ce46c42 100644 --- a/core/crates/account/src/account_settings.rs +++ b/core/crates/account/src/account_settings.rs @@ -9,8 +9,8 @@ use crate::machine_id::MachineId; use crate::server::{ServerSettings, origin_text}; // tablepro-cloud registers one public OAuth client per app, each with its own redirect: Linux's and Windows's take -// the loopback one this crate listens on, on any port (api.md, OAuth). The Mac's is a custom scheme, which the host's -// web authenticator answers. +// the loopback one this crate listens on, on any port (api.md, OAuth). The Mac's and iOS's are the same custom scheme, +// which the host's web authenticator answers, so only the client ID and PKCE keep each app to its own codes. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct AppClient { pub client_id: &'static str, @@ -53,6 +53,13 @@ impl AppClient { system: "macOS", redirect: Redirect::Scheme("app.tablepro"), }; + + pub const IOS: Self = Self { + client_id: "tablepro-ios", + platform: Platform::Ios, + system: "iOS", + redirect: Redirect::Scheme("app.tablepro"), + }; } #[derive(Debug, Clone, PartialEq, Eq)] @@ -183,8 +190,13 @@ mod tests { (AppClient::MACOS.client_id, AppClient::MACOS.platform.to_string()), ("tablepro-macos", "macos".to_owned()) ); + assert_eq!( + (AppClient::IOS.client_id, AppClient::IOS.platform.to_string()), + ("tablepro-ios", "ios".to_owned()) + ); assert_eq!(AppClient::LINUX.redirect, Redirect::Loopback); assert_eq!(AppClient::MACOS.redirect, Redirect::Scheme("app.tablepro")); + assert_eq!(AppClient::IOS.redirect, Redirect::Scheme("app.tablepro")); } #[test] diff --git a/core/crates/cloud-api/openapi/v2.openapi-3.0.json b/core/crates/cloud-api/openapi/v2.openapi-3.0.json index 48ad3775fb..9b0cf3181b 100644 --- a/core/crates/cloud-api/openapi/v2.openapi-3.0.json +++ b/core/crates/cloud-api/openapi/v2.openapi-3.0.json @@ -53,6 +53,7 @@ "AssignableRole": { "enum": [ "admin", + "editor", "member" ], "type": "string" @@ -235,13 +236,14 @@ "type": "string" }, "platform": { - "description": "Extensible enum: macos, linux, windows", + "description": "Extensible enum: macos, linux, windows, ios", "example": "macos", "type": "string", "x-extensible-enum": [ "macos", "linux", - "windows" + "windows", + "ios" ] } }, @@ -440,6 +442,11 @@ }, "Invitation": { "properties": { + "accept_url": { + "description": "On a self-hosted install, which sends no email: the link to accept, for the inviter to pass on. Only in the answer that created or resent the invitation, since only its hash is kept", + "format": "uri", + "type": "string" + }, "created_at": { "format": "date-time", "type": "string" @@ -464,11 +471,12 @@ "type": "string" }, "role": { - "description": "Extensible enum: admin, member", + "description": "Extensible enum: admin, editor, member", "example": "admin", "type": "string", "x-extensible-enum": [ "admin", + "editor", "member" ] }, @@ -619,7 +627,7 @@ "type": "string" }, "updated_by_name": { - "description": "The last writer's name, as the portal's library shows it. Without one, its address for an owner or admin, who may read the member list, and absent for a member. Absent once that account is deleted", + "description": "The last writer's name, as the portal's library shows it. Without one, its address for an owner or admin, who may read the member list, and absent for an editor or member. Absent once that account is deleted", "example": "Grace Hopper", "type": "string" }, @@ -922,13 +930,14 @@ "type": "string" }, "platform": { - "description": "Extensible enum: macos, linux, windows", + "description": "Extensible enum: macos, linux, windows, ios", "example": "macos", "type": "string", "x-extensible-enum": [ "macos", "linux", - "windows" + "windows", + "ios" ] } }, @@ -1001,12 +1010,13 @@ "type": "string" }, "role": { - "description": "Extensible enum: owner, admin, member", + "description": "Extensible enum: owner, admin, editor, member", "example": "owner", "type": "string", "x-extensible-enum": [ "owner", "admin", + "editor", "member" ] } @@ -1060,12 +1070,13 @@ "type": "boolean" }, "role": { - "description": "Extensible enum: owner, admin, member", + "description": "Extensible enum: owner, admin, editor, member", "example": "owner", "type": "string", "x-extensible-enum": [ "owner", "admin", + "editor", "member" ] }, @@ -1227,7 +1238,8 @@ "enum": [ "macos", "linux", - "windows" + "windows", + "ios" ], "type": "string" }, @@ -1913,12 +1925,13 @@ "type": "string" }, "role": { - "description": "Extensible enum: owner, admin, member. The caller's role", + "description": "Extensible enum: owner, admin, editor, member. The caller's role", "example": "owner", "type": "string", "x-extensible-enum": [ "owner", "admin", + "editor", "member" ] } @@ -1947,12 +1960,13 @@ "type": "string" }, "role": { - "description": "Extensible enum: owner, admin, member. The caller's role; absent for a team API token", + "description": "Extensible enum: owner, admin, editor, member. The caller's role; absent for a team API token", "example": "owner", "type": "string", "x-extensible-enum": [ "owner", "admin", + "editor", "member" ] }, @@ -2041,6 +2055,12 @@ } }, "securitySchemes": { + "license_file": { + "bearerFormat": "license+jwt", + "description": "A self-hosted install's license file, as tablepro.app recorded it when it was signed.", + "scheme": "bearer", + "type": "http" + }, "oauth": { "description": "An access token from the TablePro app's sign-in.", "flows": { @@ -3449,6 +3469,123 @@ ] } }, + "/licenses/latest": { + "get": { + "description": "A self-hosted server with LICENSE_RENEWAL=on sends its installed license file as the bearer, once a day and at each start, and gets the newest file tablepro.app requested and recorded for that license: the bearer itself until a later one is signed. A file tablepro.app did not request and record, or one of a license TablePro ended for good, answers 401. The bearer's exp is not read, so an install in grace or past it gets its next file. Only tablepro.app answers it; a self-hosted server answers 404. 60 an hour per IP, then 30 an hour per license.", + "operationId": "get-latest-license", + "responses": { + "200": { + "content": { + "application/jwt": { + "schema": { + "description": "The license file in JWS compact serialization, typ license+jwt, signed with Ed25519 by TablePro", + "type": "string" + } + } + }, + "description": "The license file, to verify and install", + "headers": { + "Cache-Control": { + "schema": { + "type": "string" + } + }, + "Content-Type": { + "schema": { + "type": "string" + } + }, + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "401": { + "content": { + "application/json": { + "examples": { + "unauthorized": { + "summary": "Unauthorized", + "value": { + "code": "unauthorized", + "detail": "tablepro.app has no record of this license file.", + "status": 401, + "title": "Unauthorized", + "type": "https://api.tablepro.app/problems/unauthorized" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Unauthorized" + }, + "429": { + "content": { + "application/json": { + "examples": { + "rate_limited": { + "summary": "Rate limited", + "value": { + "code": "rate_limited", + "detail": "Too many requests. Try again later.", + "status": 429, + "title": "Rate limited", + "type": "https://api.tablepro.app/problems/rate-limited" + } + } + }, + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Too Many Requests", + "headers": { + "Retry-After": { + "$ref": "#/components/headers/Retry-After" + }, + "X-RateLimit-Limit": { + "$ref": "#/components/headers/X-RateLimit-Limit" + }, + "X-RateLimit-Remaining": { + "$ref": "#/components/headers/X-RateLimit-Remaining" + }, + "X-RateLimit-Reset": { + "$ref": "#/components/headers/X-RateLimit-Reset" + } + } + }, + "500": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Problem" + } + } + }, + "description": "Internal Server Error" + } + }, + "security": [ + { + "license_file": [] + } + ], + "summary": "The newest file of a self-hosted license", + "tags": [ + "License" + ] + } + }, "/me": { "get": { "description": "The account, the teams it belongs to with its role and seat in each, and the licenses whose features it can use.", @@ -4200,16 +4337,16 @@ }, "/shares": { "get": { - "description": "The caller's personal links, or with team a team's links: every one for its owner and admins, its own for a seated member, seat_required for a member without a seat. Newest first, without sql.", + "description": "The caller's personal links, or with team a team's links: every one for its owner and admins, its own for a seated editor or member, seat_required for an editor or member without a seat. Newest first, without sql.", "operationId": "list-shares", "parameters": [ { - "description": "Team TypeID: that team's links, every one for its owner and admins, a seated member's own for a member; omit for the caller's personal links", + "description": "Team TypeID: that team's links, every one for its owner and admins, its own for a seated editor or member; omit for the caller's personal links", "explode": false, "in": "query", "name": "team", "schema": { - "description": "Team TypeID: that team's links, every one for its owner and admins, a seated member's own for a member; omit for the caller's personal links", + "description": "Team TypeID: that team's links, every one for its owner and admins, its own for a seated editor or member; omit for the caller's personal links", "maxLength": 64, "type": "string" } @@ -5949,7 +6086,7 @@ ] }, "post": { - "description": "Owners and admins, or a team API token of the team with the invitations:write scope. Emails a link valid for 7 days. With a seat, it needs a free one and reserves it while pending. Creating and resending together: 50 an hour per caller and team, and 100 an hour per team, whoever sends them; one that fails is not counted against the team.", + "description": "Owners and admins, or a team API token of the team with the invitations:write scope. Emails a link valid for 7 days. With a seat, it needs a free one and reserves it while pending. Creating and resending together: 50 an hour per caller and team, and 100 an hour per team, whoever sends them; one that fails is not counted against the team. An app's sign-in is refused an invitation to admin with app_sign_in_forbidden: the portal, which asks for a new sign-in, or a team API token makes it.", "operationId": "create-team-invitation", "parameters": [ { @@ -6021,6 +6158,16 @@ "content": { "application/json": { "examples": { + "app_sign_in_forbidden": { + "summary": "App sign in forbidden", + "value": { + "code": "app_sign_in_forbidden", + "detail": "An app's sign-in cannot change roles, remove members or invite admins. Do it in the portal, or with a team API token.", + "status": 403, + "title": "App sign in forbidden", + "type": "https://api.tablepro.app/problems/app-sign-in-forbidden" + } + }, "forbidden": { "summary": "Forbidden", "value": { @@ -6439,7 +6586,7 @@ }, "/teams/{team_id}/invitations/{invitation_id}/resend": { "post": { - "description": "Owners and admins, or a team API token of the team with the invitations:write scope. The new link replaces the old one and lasts 7 days. An invitation is sent at most once every 10 minutes. It keeps its seat as it is: an expired one still holds its reservation, and one whose reservation was taken back stays without a seat, so accepting it needs a free seat at that moment. Creating and resending together: 50 an hour per caller and team, and 100 an hour per team, whoever sends them; one that fails is not counted against the team.", + "description": "Owners and admins, or a team API token of the team with the invitations:write scope. The new link replaces the old one and lasts 7 days. An invitation is sent at most once every 10 minutes. It keeps its seat as it is: an expired one still holds its reservation, and one whose reservation was taken back stays without a seat, so accepting it needs a free seat at that moment. Creating and resending together: 50 an hour per caller and team, and 100 an hour per team, whoever sends them; one that fails is not counted against the team. An app's sign-in is refused a new link to an invitation to admin with app_sign_in_forbidden: the portal, which asks for a new sign-in, or a team API token makes it.", "operationId": "resend-team-invitation", "parameters": [ { @@ -6511,6 +6658,16 @@ "content": { "application/json": { "examples": { + "app_sign_in_forbidden": { + "summary": "App sign in forbidden", + "value": { + "code": "app_sign_in_forbidden", + "detail": "An app's sign-in cannot change roles, remove members or invite admins. Do it in the portal, or with a team API token.", + "status": 403, + "title": "App sign in forbidden", + "type": "https://api.tablepro.app/problems/app-sign-in-forbidden" + } + }, "forbidden": { "summary": "Forbidden", "value": { @@ -6840,6 +6997,16 @@ "content": { "application/json": { "examples": { + "cursor_expired": { + "summary": "Cursor expired", + "value": { + "code": "cursor_expired", + "detail": "The cursor is from a library history this server no longer has; pull without one for a fresh snapshot.", + "status": 422, + "title": "Cursor expired", + "type": "https://api.tablepro.app/problems/cursor-expired" + } + }, "validation_failed": { "summary": "Validation failed", "value": { @@ -6925,7 +7092,7 @@ ] }, "post": { - "description": "Owners and admins with a seat and the team_library feature. Up to 500 changes, applied in one transaction and judged item by item. An item's data is at most 256 KiB of JSON and the body at most 4 MiB. A change the server refuses, such as data with a secret-bearing key, refuses the whole push.", + "description": "Owners, admins and editors with a seat and the team_library feature. Up to 500 changes, applied in one transaction and judged item by item. An item's data is at most 256 KiB of JSON and the body at most 4 MiB. A change the server refuses, such as data with a secret-bearing key, refuses the whole push.", "operationId": "push-library-changes", "parameters": [ { @@ -7031,11 +7198,21 @@ "summary": "Library write forbidden", "value": { "code": "library_write_forbidden", - "detail": "Only the team's owner and admins publish to its library.", + "detail": "Only the team's owner, admins and editors publish to its library.", "status": 403, "title": "Library write forbidden", "type": "https://api.tablepro.app/problems/library-write-forbidden" } + }, + "license_expired": { + "summary": "License expired", + "value": { + "code": "license_expired", + "detail": "This server's license is past its grace: pushes are refused, pulls keep working.", + "status": 403, + "title": "License expired", + "type": "https://api.tablepro.app/problems/license-expired" + } } }, "schema": { @@ -7431,7 +7608,7 @@ }, "/teams/{team_id}/members/{member_id}": { "delete": { - "description": "Owners and admins, or a team API token of the team with the members:write scope. The owner cannot be removed.", + "description": "Owners and admins, or a team API token of the team with the members:write scope. The owner cannot be removed. An app's sign-in is refused a removal with app_sign_in_forbidden: the portal, which asks for a new sign-in, or a team API token makes it.", "operationId": "delete-team-member", "parameters": [ { @@ -7496,6 +7673,16 @@ "content": { "application/json": { "examples": { + "app_sign_in_forbidden": { + "summary": "App sign in forbidden", + "value": { + "code": "app_sign_in_forbidden", + "detail": "An app's sign-in cannot change roles, remove members or invite admins. Do it in the portal, or with a team API token.", + "status": 403, + "title": "App sign in forbidden", + "type": "https://api.tablepro.app/problems/app-sign-in-forbidden" + } + }, "forbidden": { "summary": "Forbidden", "value": { @@ -7650,7 +7837,7 @@ ] }, "patch": { - "description": "Owners and admins, or a team API token of the team with the members:write scope. The owner's role changes only by a transfer in the portal, and only the owner changes its own seat.", + "description": "Owners and admins, or a team API token of the team with the members:write scope. The owner's role changes only by a transfer in the portal, and only the owner changes its own seat. An app's sign-in is refused a role change; a seat change alone is not with app_sign_in_forbidden: the portal, which asks for a new sign-in, or a team API token makes it.", "operationId": "update-team-member", "parameters": [ { @@ -7732,6 +7919,16 @@ "content": { "application/json": { "examples": { + "app_sign_in_forbidden": { + "summary": "App sign in forbidden", + "value": { + "code": "app_sign_in_forbidden", + "detail": "An app's sign-in cannot change roles, remove members or invite admins. Do it in the portal, or with a team API token.", + "status": 403, + "title": "App sign in forbidden", + "type": "https://api.tablepro.app/problems/app-sign-in-forbidden" + } + }, "forbidden": { "summary": "Forbidden", "value": { diff --git a/core/crates/ffi/src/account/account_info.rs b/core/crates/ffi/src/account/account_info.rs index 379ae0fc0f..73d0236a44 100644 --- a/core/crates/ffi/src/account/account_info.rs +++ b/core/crates/ffi/src/account/account_info.rs @@ -106,6 +106,7 @@ pub enum AppClientTag { Linux, Windows, Macos, + Ios, } // The server the account signs in to. `api_origin` is what a person or an organization names it by. @@ -169,6 +170,7 @@ impl From for AppClient { AppClientTag::Linux => Self::LINUX, AppClientTag::Windows => Self::WINDOWS, AppClientTag::Macos => Self::MACOS, + AppClientTag::Ios => Self::IOS, } } } diff --git a/core/crates/ffi/src/account/account_service.rs b/core/crates/ffi/src/account/account_service.rs index 3fa64058ed..0cad030ad5 100644 --- a/core/crates/ffi/src/account/account_service.rs +++ b/core/crates/ffi/src/account/account_service.rs @@ -603,4 +603,25 @@ mod tests { assert!(mac.legacy_entitlement_file.is_some()); assert_eq!(short.unwrap_err().code(), "account.no_machine_id"); } + + #[test] + fn an_iphone_passes_its_client_and_the_device_id_it_keeps() { + let device_id = "5f".repeat(32); + let iphone = settings( + AccountConfig { + client: AppClientTag::Ios, + machine_guid: None, + machine_id: Some(device_id.clone()), + os_version: "iOS 26.1".to_owned(), + ..config() + }, + false, + ) + .unwrap(); + + assert_eq!(iphone.client, AppClient::IOS); + assert_eq!(iphone.machine_id.as_str(), device_id); + assert_eq!(iphone.device.os_version, "iOS 26.1"); + assert!(iphone.legacy_entitlement_file.is_none()); + } } diff --git a/core/docs/decisions/0047-the-apple-apps-sign-in-through-the-core.md b/core/docs/decisions/0047-the-apple-apps-sign-in-through-the-core.md index 02f6a4ec90..ad3f88b838 100644 --- a/core/docs/decisions/0047-the-apple-apps-sign-in-through-the-core.md +++ b/core/docs/decisions/0047-the-apple-apps-sign-in-through-the-core.md @@ -20,14 +20,14 @@ The `tablepro-macos` client redirects to `app.tablepro:/oauth/callback`, which ` The account takes the Mac's seams through the FFI, resolves and discovers the server itself, and verifies a company server's license before any of its entitlements. -| Seam | Mac | -| --- | --- | -| `AppClient` | `AppClient::MACOS`: client `tablepro-macos`, platform `macos`, redirect `Redirect::Scheme("app.tablepro")` | -| Sign-in page | `HostWebAuthenticator::authenticate(url, callback_scheme)`, which returns the callback URL or `HostBrowserError::Cancelled`, and `cancel()`, which closes the session when the core stops waiting | -| Machine ID | `AccountConfig::machine_id`, the host's 64 hex characters, through `MachineId::from_hex` | -| Refresh token | tablepro.app's in `SecretItemTag::AccountRefreshToken`, the Keychain item above; any other server's in `AccountRefreshTokenFor { sign_in_key }` | -| Server policy | `managed_server_url` and `allow_other_servers`, each only when `objectIsForced` says so | -| Old entitlement | `legacy_entitlement_file`, the path of `Account/entitlement.jwt` | +| Seam | Mac | iOS | +| --- | --- | --- | +| `AppClient` | `AppClient::MACOS`: client `tablepro-macos`, platform `macos`, redirect `Redirect::Scheme("app.tablepro")` | `AppClient::IOS`: client `tablepro-ios`, platform `ios`, the same redirect | +| Sign-in page | `HostWebAuthenticator::authenticate(url, callback_scheme)`, which returns the callback URL or `HostBrowserError::Cancelled`, and `cancel()`, which closes the session when the core stops waiting | The same, over the window of the scene in front | +| Machine ID | `AccountConfig::machine_id`, the host's 64 hex characters, through `MachineId::from_hex` | 32 random bytes made once and kept in a Keychain item of this device only, so a backup restored onto another device gets an ID of its own | +| Refresh token | tablepro.app's in `SecretItemTag::AccountRefreshToken`, the Keychain item above; any other server's in `AccountRefreshTokenFor { sign_in_key }` | The same items, readable after the first unlock, in the app's own access group and never the widget's | +| Server policy | `managed_server_url` and `allow_other_servers`, each only when `objectIsForced` says so | The same values from managed app configuration ([0055](0055-managed-policies-for-the-sync-provider-and-tablepro-app-traffic.md)) | +| Old entitlement | `legacy_entitlement_file`, the path of `Account/entitlement.jwt` | None: no build before the core had an account | ### The server @@ -69,7 +69,7 @@ The account takes the Mac's seams through the FFI, resolves and discovers the se - `AccountSettings` takes a `ServerSettings` in place of endpoints and keys; the Linux app passes tablepro.app or its development stack. - A release build trusts the two license keys whose private halves are the KMS keys of 0044, Key custody: `Yo4CIBJnxzUMSLPnsLId8ngVVe5xuZgHkOU9Z-Hgo04`, current, and `J5yCP_8iTKHyXvyYQ9y4-D2-Z_U4hbtGDvwkfzv57R0`, next. Test keys reach only a development build. - RFC 9207's `iss` is compared exactly with the issuer the sign-in went to, on a code and on an error, and a code from another issuer is never exchanged. It is required from tablepro.app, whose compiled endpoints come with the knowledge that it sends one, and from a company server whose discovery says `authorization_response_iss_parameter_supported`; a server that says nothing may leave it out but never name another. A refusal is `account.sign_in_issuer_mismatch`. -- The iOS app takes the same seams once it has an account. +- The iOS app signs in through the same adapter as the Mac, with the seams above, and gates nothing on the entitlement. It reports `ios`, which a server takes from the release after the one that added `tablepro-ios`. ## Alternatives considered diff --git a/scripts/ci/detect-changed-paths.sh b/scripts/ci/detect-changed-paths.sh index 9fdad3afb9..37e33f761e 100755 --- a/scripts/ci/detect-changed-paths.sh +++ b/scripts/ci/detect-changed-paths.sh @@ -61,7 +61,11 @@ case "$SUITE" in # The TableProCore package tests read the function names and the script corpus the Linux app shares. 'core/crates/core/tests/fixtures/(state_changing_functions|sql_script_corpus)\.json$' # The app bundles the sample database the core holds; the spec scan below reads only apple/ paths. - 'core/resources/Chinook\.sqlite$') + 'core/resources/Chinook\.sqlite$' + # The app links the core's FFI crate without the engines, as the Mac app does. + 'core/' 'Cargo\.(toml|lock)$' 'rust-toolchain\.toml$' 'apple/scripts/build-core\.sh$') + SKIP='core/crates/drivers/|core/crates/[^/]+/tests/|core/.*\.md$' + KEEP='core/crates/core/tests/fixtures/(state_changing_functions|sql_script_corpus)\.json$' # The iOS project compiles files from Plugins/, Packages/ and TablePro/, so every path its # spec reaches outside TableProMobile/ is read from the spec instead of copied here. SHARED="$(grep -oE '\.\./(Configs|Packages|Plugins|TablePro)/[^"[:space:]]*' apple/TableProMobile/project.yml \ diff --git a/scripts/ci/test_detect_changed_paths.py b/scripts/ci/test_detect_changed_paths.py index 916ec47d3d..426cc1bca3 100644 --- a/scripts/ci/test_detect_changed_paths.py +++ b/scripts/ci/test_detect_changed_paths.py @@ -439,7 +439,11 @@ def test_the_mac_app_runs_on_the_client_catalog_it_bundles(self): self.assertEqual(self.verdict_after(suite, catalog), "true") self.assertEqual(self.verdict_after("plugins", catalog), "false") - def test_the_mac_app_runs_on_the_core_it_links(self): + def test_the_apple_apps_run_on_the_core_they_link(self): + spec = self.repo / "apple/TableProMobile/project.yml" + spec.parent.mkdir(parents=True) + spec.write_text("sources:\n - path: ../Packages/TableProCore\n", encoding="utf-8") + self.seed = self.commit([]) for path in [ "core/crates/ffi/src/lib.rs", "core/crates/ffi/uniffi.toml", @@ -452,11 +456,15 @@ def test_the_mac_app_runs_on_the_core_it_links(self): "apple/scripts/build-core.sh", "apple/scripts/lib/system-sqlite.sh", ]: - for suite in ["macos", "release", "shipped"]: + for suite in ["macos", "ios", "release", "shipped"]: with self.subTest(path=path, suite=suite): self.assertEqual(self.verdict_after(suite, path), "true") - def test_the_mac_app_skips_the_core_it_does_not_link(self): + def test_the_apple_apps_skip_the_core_they_do_not_link(self): + spec = self.repo / "apple/TableProMobile/project.yml" + spec.parent.mkdir(parents=True) + spec.write_text("sources:\n - path: ../Packages/TableProCore\n", encoding="utf-8") + self.seed = self.commit([]) for path in [ "core/crates/drivers/sqlite/src/driver.rs", "core/crates/drivers/postgres/Cargo.toml", @@ -469,7 +477,11 @@ def test_the_mac_app_skips_the_core_it_does_not_link(self): "deny.toml", ".config/nextest.toml", ]: - for suite in ["macos", "release", "shipped"]: + # The iOS tests read the function names (test_ios_and_linux_run_on_the_function_names_both_apps_share). + suites = ["macos", "release", "shipped"] + if not path.endswith("state_changing_functions.json"): + suites.append("ios") + for suite in suites: with self.subTest(path=path, suite=suite): self.assertEqual(self.verdict_after(suite, path), "false") diff --git a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs index 0b80927743..b40d32e9b0 100644 --- a/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs +++ b/windows/src/TablePro.Interop/Generated/tablepro_ffi.cs @@ -21983,7 +21983,8 @@ public override void Write(AiStopTag value, BigEndianStream stream) { internal enum AppClientTag: int { Linux, Windows, - Macos + Macos, + Ios } class FfiConverterTypeAppClientTag: FfiConverterRustBuffer { @@ -21995,6 +21996,7 @@ public override AppClientTag Read(BigEndianStream stream) { case 1: return AppClientTag.Linux; case 2: return AppClientTag.Windows; case 3: return AppClientTag.Macos; + case 4: return AppClientTag.Ios; default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeAppClientTag.Read()", value)); } } @@ -22008,6 +22010,7 @@ public override void Write(AppClientTag value, BigEndianStream stream) { case AppClientTag.Linux: stream.WriteInt(1); break; case AppClientTag.Windows: stream.WriteInt(2); break; case AppClientTag.Macos: stream.WriteInt(3); break; + case AppClientTag.Ios: stream.WriteInt(4); break; default: throw new InternalException(String.Format("invalid enum value '{0}' in FfiConverterTypeAppClientTag.Write()", value)); } }