apple_kit

Apple-native services for Radroots iOS and macOS apps
git clone https://radroots.dev/git/apple_kit.git
Log | Files | Refs | README | LICENSE

commit 619a5c09814129b553d81d45c46e25d0a08fc0d0
parent c27dae18746654ff77d5fc37059f7e5ba0664e3a
Author: triesap <tyson@radroots.org>
Date:   Wed, 14 Oct 2026 07:40:03 +0000

fix: Reject unrepresentable Apple time inputs

- Check callback and native location time before conversion or provider startup.
- Validate telemetry milliseconds and keep rendering conversion nontrapping.
- Preserve fractional finite controls and retain actual admission regressions.
- Verify formatting build all 330 tests exact API and supply-chain boundaries.

Diffstat:
MREADME | 8++++++++
MSources/RadrootsKit/RadrootsAppleLocationServices.swift | 40++++++++++++++++++++++++++++------------
MSources/RadrootsKit/RadrootsAppleLoggerTelemetry.swift | 17++++++++++++-----
MSources/RadrootsKit/RadrootsAppleMediaPicker.swift | 85++++++++++++++++++++++++++++++++++++++++++++++++-------------------------------
ASources/RadrootsKit/RadrootsAppleTimeConversion.swift | 16++++++++++++++++
MSources/RadrootsKit/RadrootsPermissionLocation.swift | 28++++++++++++++++------------
MSources/RadrootsKit/RadrootsTelemetry.swift | 9+++++----
ATests/RadrootsKitTests/RadrootsTimeAdmissionTests.swift | 74++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
8 files changed, 211 insertions(+), 66 deletions(-)

diff --git a/README b/README @@ -54,6 +54,14 @@ fields. Header names allow 80 characters and values 8,192; metadata keys allow 80 characters and values 500. Accepted values retain their original whitespace and Unicode form. Blank fields remain invalid. +## Time admission + +Capture and location timeouts must fit their nanosecond representation; +telemetry dates must fit signed Unix milliseconds. Unrepresentable inputs +return `invalidRequest` before callbacks or rendering. Valid fractional values +retain truncation toward zero. Finite zero or negative capture timeouts remain +immediate timeouts; location timeouts remain strictly positive. + ## Copyright Except as otherwise noted, all files in the `apple_kit` distribution are diff --git a/Sources/RadrootsKit/RadrootsAppleLocationServices.swift b/Sources/RadrootsKit/RadrootsAppleLocationServices.swift @@ -8,7 +8,8 @@ public struct RadrootsAppleLocationServicesAdapters: Sendable { public let now: @Sendable () -> Date public let locationServicesEnabled: @Sendable () -> Bool public let authorizationStatus: @Sendable () -> RadrootsLocationAuthorization - public let requestWhenInUseAuthorization: @Sendable (TimeInterval) async throws -> RadrootsLocationAuthorization + public let requestWhenInUseAuthorization: + @Sendable (TimeInterval) async throws -> RadrootsLocationAuthorization public let requestCurrentLocation: @Sendable (RadrootsCurrentLocationRequest) async throws -> RadrootsLocationReading @@ -19,7 +20,8 @@ public struct RadrootsAppleLocationServicesAdapters: Sendable { requestWhenInUseAuthorization: @escaping @Sendable (TimeInterval) async throws -> RadrootsLocationAuthorization, requestCurrentLocation: - @escaping @Sendable (RadrootsCurrentLocationRequest) async throws -> RadrootsLocationReading + @escaping @Sendable (RadrootsCurrentLocationRequest) async throws -> + RadrootsLocationReading ) { self.now = now self.locationServicesEnabled = locationServicesEnabled @@ -41,7 +43,8 @@ public struct RadrootsAppleLocationServicesAdapters: Sendable { ) }, requestWhenInUseAuthorization: { timeoutSeconds in - try await RadrootsCoreLocationAuthorizationSession().start(timeoutSeconds: timeoutSeconds) + try await RadrootsCoreLocationAuthorizationSession().start( + timeoutSeconds: timeoutSeconds) }, requestCurrentLocation: { request in try await RadrootsCoreLocationReadingSession().start(request: request) @@ -112,7 +115,7 @@ public final class RadrootsAppleLocationServices: RadrootsLocationServices, Send switch availability.authorization { case .notDetermined: do { - return try await adapters.requestWhenInUseAuthorization(12) + return try await adapters.requestWhenInUseAuthorization(12) } catch let error as RadrootsLocationServicesError { throw error } catch { @@ -166,7 +169,9 @@ public final class RadrootsAppleLocationServices: RadrootsLocationServices, Send throw RadrootsLocationServicesError.permanentFailure } if let maximumAgeSeconds = request.maximumCachedReadingAgeSeconds { - guard try reading.isFresh(relativeTo: adapters.now(), maximumAgeSeconds: maximumAgeSeconds) + guard + try reading.isFresh( + relativeTo: adapters.now(), maximumAgeSeconds: maximumAgeSeconds) else { throw RadrootsLocationServicesError.transientFailure } @@ -188,14 +193,18 @@ public final class RadrootsAppleLocationServices: RadrootsLocationServices, Send private var timeoutTask: Task<Void, Never>? func start(timeoutSeconds: TimeInterval) async throws -> RadrootsLocationAuthorization { - try await withTaskCancellationHandler { + guard timeoutSeconds > 0, + let nanoseconds = RadrootsAppleTimeConversion.nanoseconds(timeoutSeconds) + else { + throw RadrootsLocationServicesError.invalidRequest + } + return try await withTaskCancellationHandler { try await withCheckedThrowingContinuation { continuation in self.continuation = continuation let manager = CLLocationManager() self.manager = manager manager.delegate = self timeoutTask = Task { [weak self] in - let nanoseconds = UInt64(timeoutSeconds * 1_000_000_000) try? await Task.sleep(nanoseconds: nanoseconds) self?.finish(.failure(.timeout)) } @@ -247,8 +256,13 @@ public final class RadrootsAppleLocationServices: RadrootsLocationServices, Send private var manager: CLLocationManager? private var timeoutTask: Task<Void, Never>? - func start(request: RadrootsCurrentLocationRequest) async throws -> RadrootsLocationReading { - try await withTaskCancellationHandler { + func start(request: RadrootsCurrentLocationRequest) async throws -> RadrootsLocationReading + { + guard let nanoseconds = RadrootsAppleTimeConversion.nanoseconds(request.timeoutSeconds) + else { + throw RadrootsLocationServicesError.invalidRequest + } + return try await withTaskCancellationHandler { try await withCheckedThrowingContinuation { continuation in self.continuation = continuation let manager = CLLocationManager() @@ -258,7 +272,6 @@ public final class RadrootsAppleLocationServices: RadrootsLocationServices, Send manager.desiredAccuracy = desiredAccuracyMeters } timeoutTask = Task { [weak self] in - let nanoseconds = UInt64(request.timeoutSeconds * 1_000_000_000) try? await Task.sleep(nanoseconds: nanoseconds) self?.finish(.failure(.timeout)) } @@ -302,7 +315,9 @@ public final class RadrootsAppleLocationServices: RadrootsLocationServices, Send } } - private func finish(_ result: Result<RadrootsLocationReading, RadrootsLocationServicesError>) { + private func finish( + _ result: Result<RadrootsLocationReading, RadrootsLocationServicesError> + ) { guard let continuation else { return } @@ -327,7 +342,8 @@ public final class RadrootsAppleLocationServices: RadrootsLocationServices, Send ), horizontalAccuracyMeters: location.horizontalAccuracy, altitudeMeters: location.verticalAccuracy >= 0 ? location.altitude : nil, - verticalAccuracyMeters: location.verticalAccuracy >= 0 ? location.verticalAccuracy : nil, + verticalAccuracyMeters: location.verticalAccuracy >= 0 + ? location.verticalAccuracy : nil, speedMetersPerSecond: location.speed >= 0 ? location.speed : nil, courseDegrees: location.course >= 0 ? location.course : nil, capturedAt: location.timestamp diff --git a/Sources/RadrootsKit/RadrootsAppleLoggerTelemetry.swift b/Sources/RadrootsKit/RadrootsAppleLoggerTelemetry.swift @@ -87,15 +87,20 @@ public final class RadrootsAppleLoggerTelemetry: RadrootsTelemetry, Sendable { for event: RadrootsTelemetryEvent, maximumLength: Int = 1000 ) -> String { + guard let milliseconds = RadrootsAppleTimeConversion.unixMilliseconds(event.occurredAt) + else { + return "{\"event\":\"\(event.name)\",\"level\":\"\(event.level.rawValue)\"}" + } let payload = RadrootsAppleTelemetryPayload( category: event.category, event: event.name, - fields: Dictionary(uniqueKeysWithValues: event.fields.map { field in - (field.key, field.value.renderedValue) - }), + fields: Dictionary( + uniqueKeysWithValues: event.fields.map { field in + (field.key, field.value.renderedValue) + }), level: event.level.rawValue, message: event.message, - occurredAtUnixMilliseconds: Int64(event.occurredAt.timeIntervalSince1970 * 1000) + occurredAtUnixMilliseconds: milliseconds ) let rendered: String do { @@ -124,7 +129,9 @@ public final class RadrootsAppleLoggerTelemetry: RadrootsTelemetry, Sendable { } var normalized = "" for scalar in trimmed.unicodeScalars { - if CharacterSet.alphanumerics.contains(scalar) || scalar == "." || scalar == "_" || scalar == "-" { + if CharacterSet.alphanumerics.contains(scalar) || scalar == "." || scalar == "_" + || scalar == "-" + { normalized.append(String(scalar)) } else { normalized.append("_") diff --git a/Sources/RadrootsKit/RadrootsAppleMediaPicker.swift b/Sources/RadrootsKit/RadrootsAppleMediaPicker.swift @@ -89,12 +89,13 @@ public final class RadrootsAppleMediaPicker: RadrootsMediaPicker, @unchecked Sen guard support.importAvailable else { throw RadrootsCaptureIntakeError.unavailable } - let writer = RadrootsAppleMediaAssetWriter(fileAccess: fileAccess, fileManager: fileManager) + let writer = RadrootsAppleMediaAssetWriter( + fileAccess: fileAccess, fileManager: fileManager) let presenter: UIViewController do { presenter = try await MainActor.run { - try viewControllerProvider() - } + try viewControllerProvider() + } } catch { throw Self.adapt(error: error) } @@ -134,12 +135,13 @@ public final class RadrootsAppleMediaPicker: RadrootsMediaPicker, @unchecked Sen throw RadrootsCaptureIntakeError.unavailable } try await Self.requestCameraAccessIfNeeded() - let writer = RadrootsAppleMediaAssetWriter(fileAccess: fileAccess, fileManager: fileManager) + let writer = RadrootsAppleMediaAssetWriter( + fileAccess: fileAccess, fileManager: fileManager) let presenter: UIViewController do { presenter = try await MainActor.run { - try viewControllerProvider() - } + try viewControllerProvider() + } } catch { throw Self.adapt(error: error) } @@ -262,11 +264,13 @@ public final class RadrootsAppleMediaPicker: RadrootsMediaPicker, @unchecked Sen let scenes = UIApplication.shared.connectedScenes .compactMap { $0 as? UIWindowScene } .filter { scene in - scene.activationState == .foregroundActive || scene.activationState == .foregroundInactive + scene.activationState == .foregroundActive + || scene.activationState == .foregroundInactive } let windows = scenes.flatMap(\.windows) guard - let window = windows.first(where: \.isKeyWindow) ?? windows.first(where: { !$0.isHidden }) + let window = windows.first(where: \.isKeyWindow) + ?? windows.first(where: { !$0.isHidden }) else { throw RadrootsCaptureIntakeError.unavailable } @@ -276,17 +280,19 @@ public final class RadrootsAppleMediaPicker: RadrootsMediaPicker, @unchecked Sen return topViewController(rootViewController) } - private static func topViewController(_ viewController: UIViewController) -> UIViewController { + private static func topViewController(_ viewController: UIViewController) + -> UIViewController + { if let presentedViewController = viewController.presentedViewController { return topViewController(presentedViewController) } if let navigationController = viewController as? UINavigationController, - let visibleViewController = navigationController.visibleViewController + let visibleViewController = navigationController.visibleViewController { return topViewController(visibleViewController) } if let tabBarController = viewController as? UITabBarController, - let selectedViewController = tabBarController.selectedViewController + let selectedViewController = tabBarController.selectedViewController { return topViewController(selectedViewController) } @@ -295,8 +301,11 @@ public final class RadrootsAppleMediaPicker: RadrootsMediaPicker, @unchecked Sen } @MainActor - private final class RadrootsApplePhotoPickerCoordinator: NSObject, PHPickerViewControllerDelegate { - var completion: (@Sendable (Result<RadrootsMediaImportResult, RadrootsCaptureIntakeError>) -> Void)? + private final class RadrootsApplePhotoPickerCoordinator: NSObject, + PHPickerViewControllerDelegate + { + var completion: + (@Sendable (Result<RadrootsMediaImportResult, RadrootsCaptureIntakeError>) -> Void)? private let writer: RadrootsAppleMediaAssetWriter private let request: RadrootsMediaImportRequest @@ -338,7 +347,8 @@ public final class RadrootsAppleMediaPicker: RadrootsMediaPicker, @unchecked Sen let provider = selectedResults[index].itemProvider let suggestedName = provider.suggestedName ?? "photo" guard - provider.hasItemConformingToTypeIdentifier(RadrootsAppleMediaPicker.imageTypeIdentifier()) + provider.hasItemConformingToTypeIdentifier( + RadrootsAppleMediaPicker.imageTypeIdentifier()) else { finish(.failure(.transientFailure)) return @@ -405,7 +415,8 @@ public final class RadrootsAppleMediaPicker: RadrootsMediaPicker, @unchecked Sen finish(.failure(.transientFailure)) } - private func finish(_ result: Result<RadrootsMediaImportResult, RadrootsCaptureIntakeError>) { + private func finish(_ result: Result<RadrootsMediaImportResult, RadrootsCaptureIntakeError>) + { guard !didResolve else { return } didResolve = true let completion = completion @@ -419,7 +430,8 @@ public final class RadrootsAppleMediaPicker: RadrootsMediaPicker, @unchecked Sen private final class RadrootsAppleCameraCaptureCoordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate { - var completion: (@Sendable (Result<RadrootsMediaCaptureResult, RadrootsCaptureIntakeError>) -> Void)? + var completion: + (@Sendable (Result<RadrootsMediaCaptureResult, RadrootsCaptureIntakeError>) -> Void)? private let writer: RadrootsAppleMediaAssetWriter private let request: RadrootsMediaCaptureRequest @@ -466,8 +478,9 @@ public final class RadrootsAppleMediaPicker: RadrootsMediaPicker, @unchecked Sen mediaTypeHint: nil ) } - guard let image = (info[.editedImage] as? UIImage) ?? (info[.originalImage] as? UIImage), - let jpegData = image.jpegData(compressionQuality: 0.92) + guard + let image = (info[.editedImage] as? UIImage) ?? (info[.originalImage] as? UIImage), + let jpegData = image.jpegData(compressionQuality: 0.92) else { throw RadrootsCaptureIntakeError.transientFailure } @@ -484,7 +497,9 @@ public final class RadrootsAppleMediaPicker: RadrootsMediaPicker, @unchecked Sen finish(.failure(.transientFailure)) } - private func finish(_ result: Result<RadrootsMediaCaptureResult, RadrootsCaptureIntakeError>) { + private func finish( + _ result: Result<RadrootsMediaCaptureResult, RadrootsCaptureIntakeError> + ) { guard !didResolve else { return } didResolve = true let completion = completion @@ -594,11 +609,11 @@ private final class RadrootsAppleMediaAssetWriter: @unchecked Sendable { ) throws -> RadrootsFileReference { let namespace = switch source { - case .libraryImport: - "library_import" - case .cameraCapture: - "camera_capture" - } + case .libraryImport: + "library_import" + case .cameraCapture: + "camera_capture" + } let validatedFilename = try RadrootsCaptureIntakeValidation.normalizedFilename(filename) return RadrootsFileReference( scope: scope, @@ -640,7 +655,7 @@ private final class RadrootsAppleMediaAssetWriter: @unchecked Sendable { } #if canImport(UniformTypeIdentifiers) if let type = UTType(filenameExtension: URL(fileURLWithPath: filename).pathExtension), - let preferredMIMEType = type.preferredMIMEType + let preferredMIMEType = type.preferredMIMEType { return try RadrootsCaptureIntakeValidation.normalizedMediaType(preferredMIMEType) } @@ -666,10 +681,10 @@ private final class RadrootsAppleMediaAssetWriter: @unchecked Sendable { guard let imageSource = CGImageSourceCreateWithURL(fileURL as CFURL, nil), let properties = CGImageSourceCopyPropertiesAtIndex(imageSource, 0, nil) as? [CFString: Any], - let width = properties[kCGImagePropertyPixelWidth] as? NSNumber, - let height = properties[kCGImagePropertyPixelHeight] as? NSNumber, - width.uint32Value > 0, - height.uint32Value > 0 + let width = properties[kCGImagePropertyPixelWidth] as? NSNumber, + let height = properties[kCGImagePropertyPixelHeight] as? NSNumber, + width.uint32Value > 0, + height.uint32Value > 0 else { return nil } @@ -693,16 +708,20 @@ enum RadrootsAppleCaptureAsyncSupport { timeoutMessage: String, operation: @escaping @MainActor ( - @escaping @Sendable (Result<Value, RadrootsCaptureIntakeError>) -> Void, - @escaping @MainActor @Sendable (@escaping @MainActor @Sendable () -> Void) -> Void - ) -> Void + @escaping @Sendable (Result<Value, RadrootsCaptureIntakeError>) -> Void, + @escaping @MainActor @Sendable (@escaping @MainActor @Sendable () -> Void) -> Void + ) -> Void ) async throws -> Value { + guard timeout.isFinite, + let nanoseconds = RadrootsAppleTimeConversion.nanoseconds(max(timeout, 0)) + else { + throw RadrootsCaptureIntakeError.invalidRequest + } let state = RadrootsAppleCaptureAsyncCallbackState<Value>() return try await withTaskCancellationHandler { try await withCheckedThrowingContinuation { continuation in state.start(continuation: continuation) let timeoutTask = Task { - let nanoseconds = UInt64(max(timeout, 0) * 1_000_000_000) do { try await Task.sleep(nanoseconds: nanoseconds) } catch { diff --git a/Sources/RadrootsKit/RadrootsAppleTimeConversion.swift b/Sources/RadrootsKit/RadrootsAppleTimeConversion.swift @@ -0,0 +1,16 @@ +import Foundation + +enum RadrootsAppleTimeConversion { + static func nanoseconds(_ seconds: TimeInterval) -> UInt64? { + guard seconds.isFinite, seconds >= 0 else { return nil } + let scaled = seconds * 1_000_000_000 + guard scaled.isFinite else { return nil } + return UInt64(exactly: scaled.rounded(.towardZero)) + } + + static func unixMilliseconds(_ date: Date) -> Int64? { + let scaled = date.timeIntervalSince1970 * 1000 + guard scaled.isFinite else { return nil } + return Int64(exactly: scaled.rounded(.towardZero)) + } +} diff --git a/Sources/RadrootsKit/RadrootsPermissionLocation.swift b/Sources/RadrootsKit/RadrootsPermissionLocation.swift @@ -101,10 +101,10 @@ public struct RadrootsLocationCoordinate: Sendable, Equatable, Hashable { public let longitude: Double public init(latitude: Double, longitude: Double) throws { - guard latitude.isFinite, (-90.0 ... 90.0).contains(latitude) else { + guard latitude.isFinite, (-90.0...90.0).contains(latitude) else { throw RadrootsLocationServicesError.invalidRequest } - guard longitude.isFinite, (-180.0 ... 180.0).contains(longitude) else { + guard longitude.isFinite, (-180.0...180.0).contains(longitude) else { throw RadrootsLocationServicesError.invalidRequest } self.latitude = latitude @@ -165,7 +165,8 @@ public struct RadrootsLocationReading: Sendable, Equatable, Hashable { return currentAge >= 0 && currentAge <= normalizedMaximumAge } - public static func normalizedNonNegativeFinite(_ value: Double, field: String) throws -> Double { + public static func normalizedNonNegativeFinite(_ value: Double, field: String) throws -> Double + { guard value.isFinite, value >= 0 else { throw RadrootsLocationServicesError.invalidRequest } @@ -195,7 +196,7 @@ public struct RadrootsLocationReading: Sendable, Equatable, Hashable { guard let value else { return nil } - guard value.isFinite, (0.0 ..< 360.0).contains(value) else { + guard value.isFinite, (0.0..<360.0).contains(value) else { throw RadrootsLocationServicesError.invalidRequest } return value @@ -212,19 +213,22 @@ public struct RadrootsCurrentLocationRequest: Sendable, Equatable, Hashable { desiredAccuracyMeters: Double? = nil, maximumCachedReadingAgeSeconds: TimeInterval? = nil ) throws { - guard timeoutSeconds.isFinite, timeoutSeconds > 0 else { + guard timeoutSeconds > 0, + RadrootsAppleTimeConversion.nanoseconds(timeoutSeconds) != nil + else { throw RadrootsLocationServicesError.invalidRequest } self.timeoutSeconds = timeoutSeconds - self.desiredAccuracyMeters = try RadrootsLocationReading.normalizedOptionalNonNegativeFinite( - desiredAccuracyMeters, - field: "desired accuracy" - ) + self.desiredAccuracyMeters = + try RadrootsLocationReading.normalizedOptionalNonNegativeFinite( + desiredAccuracyMeters, + field: "desired accuracy" + ) self.maximumCachedReadingAgeSeconds = try RadrootsLocationReading.normalizedOptionalNonNegativeFinite( - maximumCachedReadingAgeSeconds, - field: "maximum cached reading age" - ) + maximumCachedReadingAgeSeconds, + field: "maximum cached reading age" + ) } } diff --git a/Sources/RadrootsKit/RadrootsTelemetry.swift b/Sources/RadrootsKit/RadrootsTelemetry.swift @@ -8,7 +8,8 @@ extension RadrootsTelemetryError: LocalizedError { public var errorDescription: String? { "The telemetry request is invalid." } } -public enum RadrootsTelemetryLevel: String, Sendable, Equatable, Hashable, CaseIterable, Comparable { +public enum RadrootsTelemetryLevel: String, Sendable, Equatable, Hashable, CaseIterable, Comparable +{ case trace case debug case info @@ -157,7 +158,7 @@ public struct RadrootsTelemetryEvent: Sendable, Equatable, Hashable { maximumLength: 80 ) let normalizedMessage = try RadrootsTelemetryValidation.normalizedMessage(message) - guard occurredAt.timeIntervalSinceReferenceDate.isFinite else { + guard RadrootsAppleTimeConversion.unixMilliseconds(occurredAt) != nil else { throw RadrootsTelemetryError.invalidRequest } let duplicateFieldKeys = Set(fields.map(\.key)).count != fields.count @@ -334,8 +335,8 @@ public enum RadrootsTelemetryValidation { } guard trimmed.range( - of: "^[a-z][a-z0-9._-]*$", - options: .regularExpression + of: "^[a-z][a-z0-9._-]*$", + options: .regularExpression ) != nil else { throw RadrootsTelemetryError.invalidRequest diff --git a/Tests/RadrootsKitTests/RadrootsTimeAdmissionTests.swift b/Tests/RadrootsKitTests/RadrootsTimeAdmissionTests.swift @@ -0,0 +1,74 @@ +import Foundation +import Testing + +@testable import RadrootsKit + +@Test(arguments: [ + Double.nan, Double.infinity, -Double.infinity, Double.greatestFiniteMagnitude, + Double(UInt64.max) / 1_000_000_000, Double(UInt64.max), +]) +func appleTimeAdmissionRejectsUnrepresentableCaptureTimeout(timeout: Double) async { + await #expect(throws: RadrootsCaptureIntakeError.invalidRequest) { + let _: Int = try await RadrootsAppleCaptureAsyncSupport.awaitMainActorCallback( + timeout: timeout, + timeoutMessage: "unused" + ) { _, _ in + Issue.record("An invalid timeout must not start a capture operation") + } + } +} + +@Test(arguments: [ + Double.greatestFiniteMagnitude, Double(UInt64.max) / 1_000_000_000, Double(UInt64.max), +]) +func appleTimeAdmissionRejectsUnrepresentableLocationTimeout(timeout: Double) { + #expect(throws: RadrootsLocationServicesError.invalidRequest) { + _ = try RadrootsCurrentLocationRequest(timeoutSeconds: timeout) + } +} + +@Test(arguments: [ + Double.greatestFiniteMagnitude, -Double.greatestFiniteMagnitude, + Double(Int64.max) / 1000, Double(Int64.min) / 1000 - 4096, +]) +func appleTimeAdmissionRejectsUnrepresentableTelemetryTime(seconds: Double) { + #expect(throws: RadrootsTelemetryError.invalidRequest) { + _ = try RadrootsTelemetryEvent( + name: "time_admission.invalid", + occurredAt: Date(timeIntervalSince1970: seconds) + ) + } +} + +@Test func appleTimeAdmissionPreservesFiniteBoundaryControls() async throws { + let value: Int = try await RadrootsAppleCaptureAsyncSupport.awaitMainActorCallback( + timeout: 10, + timeoutMessage: "unused" + ) { completion, _ in + completion(.success(42)) + } + #expect(value == 42) + for timeout in [0.0, -1.0] { + await #expect(throws: RadrootsCaptureIntakeError.transientFailure) { + let _: Int = try await RadrootsAppleCaptureAsyncSupport.awaitMainActorCallback( + timeout: timeout, + timeoutMessage: "unused" + ) { _, _ in } + } + } + for timeout in [12.0, 0.000_000_000_001, 1_000_000_000.0] { + #expect( + try RadrootsCurrentLocationRequest(timeoutSeconds: timeout).timeoutSeconds == timeout) + } + for (seconds, expectedMilliseconds) in [(0.0, 0), (1.25, 1250), (-1.25, -1250)] { + let event = try RadrootsTelemetryEvent( + name: "time_admission.control", + occurredAt: Date(timeIntervalSince1970: seconds) + ) + let payload = Data(RadrootsAppleLoggerTelemetry.renderedMessage(for: event).utf8) + #expect(payload.count <= 1024) + let object = try #require(try JSONSerialization.jsonObject(with: payload) as? [String: Any]) + #expect( + (object["occurred_at_unix_ms"] as? NSNumber)?.int64Value == Int64(expectedMilliseconds)) + } +}