diff --git a/CHANGELOG.md b/CHANGELOG.md index 09e299fd..4b62bb45 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added +- `asc iris app-privacy get`, `declare` and `publish` show, replace and publish an app's App Privacy label (Data Not Collected or the data it collects), so a submission is no longer refused over unpublished data usages; over CLI and REST. → [docs](docs/features/app-privacy/README.md) ([#46](https://github.com/tddworks/asc-cli/pull/46)) + --- ## [0.19.0] - 2026-11-19 diff --git a/Sources/ASCCommand/ClientProvider.swift b/Sources/ASCCommand/ClientProvider.swift index 44256597..39f12cf1 100644 --- a/Sources/ASCCommand/ClientProvider.swift +++ b/Sources/ASCCommand/ClientProvider.swift @@ -448,6 +448,10 @@ struct ClientProvider { ClientFactory().makeIrisComplianceRepository() } + static func makeIrisAppPrivacyRepository() -> any IrisAppPrivacyRepository { + ClientFactory().makeIrisAppPrivacyRepository() + } + static func makeIrisCookieProvider() -> any IrisCookieProvider { ClientFactory().makeIrisCookieProvider() } diff --git a/Sources/ASCCommand/Commands/Iris/AppPrivacy/IrisAppPrivacyCommand.swift b/Sources/ASCCommand/Commands/Iris/AppPrivacy/IrisAppPrivacyCommand.swift new file mode 100644 index 00000000..2dd17852 --- /dev/null +++ b/Sources/ASCCommand/Commands/Iris/AppPrivacy/IrisAppPrivacyCommand.swift @@ -0,0 +1,55 @@ +import ArgumentParser +import ASCKit + +/// `asc iris app-privacy` — the app's App Privacy label ("nutrition label"). Iris private +/// API only: there is no public endpoint, yet App Review refuses a submission until it's published. +struct IrisAppPrivacyCommand: AsyncParsableCommand { + static let configuration = CommandConfiguration( + commandName: "app-privacy", + abstract: "Show, declare and publish an app's App Privacy label (iris session)", + subcommands: [IrisAppPrivacyGet.self, IrisAppPrivacyDeclare.self, IrisAppPrivacyPublish.self] + ) +} + +struct IrisAppPrivacyGet: AsyncParsableCommand { + static let configuration = CommandConfiguration( + commandName: "get", + abstract: "Show what an app's privacy label declares and whether it is published" + ) + + @OptionGroup var globals: GlobalOptions + + @Option(name: .long, help: "App ID") + var appId: String + + func run() async throws { + print(try await execute(cookieProvider: ClientProvider.makeIrisCookieProvider(), repo: ClientProvider.makeIrisAppPrivacyRepository())) + } + + func execute(cookieProvider: any IrisCookieProvider, repo: any IrisAppPrivacyRepository, affordanceMode: AffordanceMode = .cli) async throws -> String { + let privacy = try await repo.fetchPrivacy(session: try cookieProvider.resolveSession(), appId: appId) + return try OutputFormatter(format: globals.outputFormat, pretty: globals.pretty).formatAgentItems([privacy], affordanceMode: affordanceMode) + } +} + +struct IrisAppPrivacyPublish: AsyncParsableCommand { + static let configuration = CommandConfiguration( + commandName: "publish", + abstract: "Publish an app's declared privacy label so it no longer blocks review" + ) + + @OptionGroup var globals: GlobalOptions + + @Option(name: .long, help: "App ID") + var appId: String + + func run() async throws { + print(try await execute(cookieProvider: ClientProvider.makeIrisCookieProvider(), repo: ClientProvider.makeIrisAppPrivacyRepository())) + } + + func execute(cookieProvider: any IrisCookieProvider, repo: any IrisAppPrivacyRepository, affordanceMode: AffordanceMode = .cli) async throws -> String { + let session = try cookieProvider.resolveSession() + let published = try await repo.fetchPrivacy(session: session, appId: appId).publish(session: session, repo: repo) + return try OutputFormatter(format: globals.outputFormat, pretty: globals.pretty).formatAgentItems([published], affordanceMode: affordanceMode) + } +} diff --git a/Sources/ASCCommand/Commands/Iris/AppPrivacy/IrisAppPrivacyDeclare.swift b/Sources/ASCCommand/Commands/Iris/AppPrivacy/IrisAppPrivacyDeclare.swift new file mode 100644 index 00000000..178d678a --- /dev/null +++ b/Sources/ASCCommand/Commands/Iris/AppPrivacy/IrisAppPrivacyDeclare.swift @@ -0,0 +1,50 @@ +import ArgumentParser +import Foundation +import ASCKit + +struct IrisAppPrivacyDeclare: AsyncParsableCommand { + static let configuration = CommandConfiguration( + commandName: "declare", + abstract: "Replace an app's privacy label (it stays a draft until `publish`)", + discussion: """ + --not-collected declares the app collects no data. --file takes a JSON file listing what it collects: + {"collectedData": [{"category": "EMAIL_ADDRESS", "purposes": ["APP_FUNCTIONALITY"], + "isLinkedToYou": true, "isUsedToTrackYou": false}]} + the same shape `get` shows. The file may also be {"notCollected": true}. + """ + ) + + @OptionGroup var globals: GlobalOptions + + @Option(name: .long, help: "App ID") + var appId: String + + @Flag(name: .long, help: "The app collects no data") + var notCollected = false + + @Option(name: .long, help: "A JSON file of the data the app collects") + var file: String? + + func validate() throws { + guard notCollected != (file != nil) else { + throw ValidationError("Give either --not-collected or --file .") + } + } + + func run() async throws { + print(try await execute(cookieProvider: ClientProvider.makeIrisCookieProvider(), repo: ClientProvider.makeIrisAppPrivacyRepository())) + } + + func execute(cookieProvider: any IrisCookieProvider, repo: any IrisAppPrivacyRepository, affordanceMode: AffordanceMode = .cli) async throws -> String { + let declaration = try declaration() + try declaration.validate() // refused before signing in or reaching Apple (law 6) + let session = try cookieProvider.resolveSession() + let declared = try await repo.fetchPrivacy(session: session, appId: appId).declare(declaration, session: session, repo: repo) + return try OutputFormatter(format: globals.outputFormat, pretty: globals.pretty).formatAgentItems([declared], affordanceMode: affordanceMode) + } + + private func declaration() throws -> PrivacyDeclaration { + guard let file else { return .notCollected } + return try JSONDecoder().decode(PrivacyDeclaration.self, from: Data(contentsOf: URL(fileURLWithPath: file))) + } +} diff --git a/Sources/ASCCommand/Commands/Iris/IrisCommand.swift b/Sources/ASCCommand/Commands/Iris/IrisCommand.swift index 542668e8..4d3a64d7 100644 --- a/Sources/ASCCommand/Commands/Iris/IrisCommand.swift +++ b/Sources/ASCCommand/Commands/Iris/IrisCommand.swift @@ -10,6 +10,7 @@ struct IrisCommand: AsyncParsableCommand { IrisIAPSubmissionsCommand.self, IrisResolutionCenterCommand.self, IrisAppComplianceCommand.self, + IrisAppPrivacyCommand.self, IrisAuthCommand.self, ] ) diff --git a/Sources/ASCCommand/Commands/Web/Controllers/IrisAppPrivacyController.swift b/Sources/ASCCommand/Commands/Web/Controllers/IrisAppPrivacyController.swift new file mode 100644 index 00000000..dcfd5165 --- /dev/null +++ b/Sources/ASCCommand/Commands/Web/Controllers/IrisAppPrivacyController.swift @@ -0,0 +1,58 @@ +import ASCKit +import Foundation +import Hummingbird +import HummingbirdWebSocket + +/// `GET /api/v1/iris/apps/:appId/app-privacy` — the app's privacy label. +/// `POST /api/v1/iris/apps/:appId/app-privacy/declare` with `{"notCollected": true}` or +/// `{"collectedData": [...]}` — replaces it (a draft until published). +/// `POST /api/v1/iris/apps/:appId/app-privacy/publish` — makes it live. +/// Iris private API only (browser-cookie auth). +struct IrisAppPrivacyController: Sendable { + let cookieProvider: any IrisCookieProvider + let repo: any IrisAppPrivacyRepository + + func addRoutes(to group: RouterGroup) { + group.get("/iris/apps/:appId/app-privacy") { _, context -> Response in + guard let appId = context.parameters.get("appId") else { return jsonError("Missing appId") } + let session = try self.cookieProvider.resolveSession() + return try restFormat(try await self.repo.fetchPrivacy(session: session, appId: appId)) + } + + group.post("/iris/apps/:appId/app-privacy/declare") { request, context -> Response in + guard let appId = context.parameters.get("appId") else { return jsonError("Missing appId") } + let bytes = try await request.body.collect(upTo: 1_000_000) + guard let declaration = try? JSONDecoder().decode(PrivacyDeclaration.self, from: Data(buffer: bytes)) else { + return jsonError(#"Send either {"notCollected": true} or {"collectedData": [...]}"#) + } + return try await self.answering { + try declaration.validate() // refused before signing in or reaching Apple (law 6) + let session = try self.cookieProvider.resolveSession() + let privacy = try await self.repo.fetchPrivacy(session: session, appId: appId) + return try restFormat(try await privacy.declare(declaration, session: session, repo: self.repo)) + } + } + + group.post("/iris/apps/:appId/app-privacy/publish") { _, context -> Response in + guard let appId = context.parameters.get("appId") else { return jsonError("Missing appId") } + let session = try self.cookieProvider.resolveSession() + return try await self.answering { + let privacy = try await self.repo.fetchPrivacy(session: session, appId: appId) + return try restFormat(try await privacy.publish(session: session, repo: self.repo)) + } + } + } + + /// A refusal the domain explains is answered with its own words and status. + private func answering(_ handler: () async throws -> Response) async throws -> Response { + do { + return try await handler() + } catch let error as AppPrivacyError { + switch error { + case .nothingDeclared: return jsonError(error.description, status: .conflict) + case .noDataTypes, .noPurposes, .unknownCategory, .unknownPurpose, .duplicateCategory, .duplicatePurpose: + return jsonError(error.description, status: .unprocessableContent) + } + } + } +} diff --git a/Sources/ASCCommand/Commands/Web/RESTRoutes.swift b/Sources/ASCCommand/Commands/Web/RESTRoutes.swift index 5c330b99..d9e67bb6 100644 --- a/Sources/ASCCommand/Commands/Web/RESTRoutes.swift +++ b/Sources/ASCCommand/Commands/Web/RESTRoutes.swift @@ -155,6 +155,10 @@ enum RESTRoutes { cookieProvider: ClientProvider.makeIrisCookieProvider(), repo: ClientProvider.makeIrisComplianceRepository() ).addRoutes(to: v1) + IrisAppPrivacyController( + cookieProvider: ClientProvider.makeIrisCookieProvider(), + repo: ClientProvider.makeIrisAppPrivacyRepository() + ).addRoutes(to: v1) if let subSubmissionRepo = try? ClientProvider.makeSubscriptionSubmissionRepository() { SubscriptionSubmissionController(repo: subSubmissionRepo).addRoutes(to: v1) } diff --git a/Sources/ASCKit/Iris/AppPrivacy/AppPrivacy+RESTRoutes.swift b/Sources/ASCKit/Iris/AppPrivacy/AppPrivacy+RESTRoutes.swift new file mode 100644 index 00000000..fb09de52 --- /dev/null +++ b/Sources/ASCKit/Iris/AppPrivacy/AppPrivacy+RESTRoutes.swift @@ -0,0 +1,9 @@ +/// REST routes for App Privacy. +extension RESTPathResolver { + static let _appPrivacyRoutes: Void = { + // One label per app: + // `asc iris app-privacy get --app-id A` → GET /api/v1/iris/apps/A/app-privacy + // `… declare --app-id A` / `… publish …` → POST /api/v1/iris/apps/A/app-privacy/{declare|publish} + registerRoute(command: "iris app-privacy", parentParam: "app-id", parentSegment: "iris/apps", segment: "app-privacy") + }() +} diff --git a/Sources/ASCKit/Iris/AppPrivacy/AppPrivacy.swift b/Sources/ASCKit/Iris/AppPrivacy/AppPrivacy.swift new file mode 100644 index 00000000..6ad2518c --- /dev/null +++ b/Sources/ASCKit/Iris/AppPrivacy/AppPrivacy.swift @@ -0,0 +1,115 @@ +/// An app's privacy label — the App Privacy page: "Data Not Collected" or the data types it +/// collects, and whether that answer is published. One per app; the aggregate. +public struct AppPrivacy: Sendable, Equatable { + /// Parent and identity: there is one label per app. + public let appId: String + public let dataCollection: DataCollection + public let isPublished: Bool + /// When it was last published (Apple's `lastPublished`); nil = never. + public let lastPublishedAt: String? + + public init(appId: String, dataCollection: DataCollection, isPublished: Bool, lastPublishedAt: String?) { + self.appId = appId + self.dataCollection = dataCollection + self.isPublished = isPublished + self.lastPublishedAt = lastPublishedAt + } + + /// The label Apple's rows make (law 1). + public init(appId: String, dataUsages: [DataUsage], isPublished: Bool, lastPublishedAt: String?) { + let collected = CollectedData.grouping(dataUsages) + let collection: DataCollection + if !collected.isEmpty { + collection = .collected(collected) + } else if dataUsages.contains(where: { $0.protection == .notCollected }) { + collection = .notCollected + } else { + collection = .notAnswered + } + self.init(appId: appId, dataCollection: collection, isPublished: isPublished, lastPublishedAt: lastPublishedAt) + } + + public var isAnswered: Bool { dataCollection != .notAnswered } + public var isNotCollected: Bool { dataCollection == .notCollected } + /// App Review refuses a submission until the label is answered and published (law 7). + public var blocksSubmission: Bool { !(isAnswered && isPublished) } + + /// Replaces the label with `declaration` (law 3). It stays a draft until published (law 4). + public func declare(_ declaration: PrivacyDeclaration, session: IrisSession, repo: any IrisAppPrivacyRepository) async throws -> AppPrivacy { + try declaration.validate() + let plan = DataUsagePlan(current: try await repo.listDataUsages(session: session, appId: appId), wanted: declaration) + for usage in plan.deletions { + try await repo.deleteDataUsage(session: session, dataUsageId: usage.id) + } + for entry in plan.creations { + try await repo.createDataUsage(session: session, appId: appId, entry: entry) + } + return try await repo.fetchPrivacy(session: session, appId: appId) + } + + /// Makes the label live — only once something is declared (law 5). + public func publish(session: IrisSession, repo: any IrisAppPrivacyRepository) async throws -> AppPrivacy { + guard isAnswered else { throw AppPrivacyError.nothingDeclared(appId: appId) } + try await repo.publish(session: session, appId: appId) + return try await repo.fetchPrivacy(session: session, appId: appId) + } +} + +extension AppPrivacy: Codable { + private enum CodingKeys: String, CodingKey { + case appId, dataCollection, collectedData, isAnswered, isPublished, blocksSubmission, lastPublishedAt + } + + public init(from decoder: any Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + let collection: DataCollection + switch try c.decode(String.self, forKey: .dataCollection) { + case "NOT_COLLECTED": collection = .notCollected + case "COLLECTED": collection = .collected(try c.decode([CollectedData].self, forKey: .collectedData)) + default: collection = .notAnswered + } + self.init( + appId: try c.decode(String.self, forKey: .appId), + dataCollection: collection, + isPublished: try c.decode(Bool.self, forKey: .isPublished), + lastPublishedAt: try c.decodeIfPresent(String.self, forKey: .lastPublishedAt) + ) + } + + public func encode(to encoder: any Encoder) throws { + var c = encoder.container(keyedBy: CodingKeys.self) + try c.encode(appId, forKey: .appId) + try c.encode(dataCollection.wireValue, forKey: .dataCollection) + if case .collected(let data) = dataCollection { + try c.encode(data, forKey: .collectedData) + } + try c.encode(isAnswered, forKey: .isAnswered) + try c.encode(isPublished, forKey: .isPublished) + try c.encode(blocksSubmission, forKey: .blocksSubmission) + try c.encodeIfPresent(lastPublishedAt, forKey: .lastPublishedAt) + } +} + +extension AppPrivacy: AffordanceProviding { + public var structuredAffordances: [Affordance] { + let app = ["app-id": appId] + var items = [ + Affordance(key: "get", command: "iris app-privacy", action: "get", params: app), + Affordance(key: "declare", command: "iris app-privacy", action: "declare", params: app.merging(["file": ""]) { $1 }), + ] + if !isAnswered { + items.append(Affordance(key: "declareNotCollected", command: "iris app-privacy", action: "declare", params: app, flags: ["not-collected"])) + } + if isAnswered && !isPublished { + items.append(Affordance(key: "publish", command: "iris app-privacy", action: "publish", params: app)) + } + return items + } +} + +extension AppPrivacy: Presentable { + public static var tableHeaders: [String] { ["App ID", "Data Collection", "Published", "Blocks Submission"] } + public var tableRow: [String] { + [appId, dataCollection.wireValue, isPublished ? "yes" : "no", blocksSubmission ? "yes" : "no"] + } +} diff --git a/Sources/ASCKit/Iris/AppPrivacy/AppPrivacyError.swift b/Sources/ASCKit/Iris/AppPrivacy/AppPrivacyError.swift new file mode 100644 index 00000000..8a7fa50c --- /dev/null +++ b/Sources/ASCKit/Iris/AppPrivacy/AppPrivacyError.swift @@ -0,0 +1,34 @@ +import Foundation + +public enum AppPrivacyError: Error, Equatable, Sendable, CustomStringConvertible, LocalizedError { + /// Publishing a label with nothing declared (law 5). + case nothingDeclared(appId: String) + /// `collectedData` is empty: that is "Data Not Collected", said another way. + case noDataTypes + case noPurposes(category: String) + case unknownCategory(String) + case unknownPurpose(String) + case duplicateCategory(String) + case duplicatePurpose(category: String, purpose: String) + + public var description: String { + switch self { + case .nothingDeclared(let appId): + "App \(appId) has no privacy answers to publish. Declare them first: `asc iris app-privacy declare --app-id \(appId) --not-collected` or `--file `." + case .noDataTypes: + "collectedData lists no data types. If the app collects nothing, declare --not-collected." + case .noPurposes(let category): + "\(category) needs at least one purpose." + case .unknownCategory(let category): + "\(category) isn't a data type App Privacy knows (e.g. EMAIL_ADDRESS, CRASH_DATA, DEVICE_ID)." + case .unknownPurpose(let purpose): + "\(purpose) isn't a purpose App Privacy knows: APP_FUNCTIONALITY, ANALYTICS, PRODUCT_PERSONALIZATION, DEVELOPERS_ADVERTISING, THIRD_PARTY_ADVERTISING or OTHER_PURPOSES." + case .duplicateCategory(let category): + "\(category) is declared twice; list each data type once with all its purposes." + case .duplicatePurpose(let category, let purpose): + "\(category) lists \(purpose) twice; list each purpose once." + } + } + + public var errorDescription: String? { description } +} diff --git a/Sources/ASCKit/Iris/AppPrivacy/CollectedData.swift b/Sources/ASCKit/Iris/AppPrivacy/CollectedData.swift new file mode 100644 index 00000000..227c7682 --- /dev/null +++ b/Sources/ASCKit/Iris/AppPrivacy/CollectedData.swift @@ -0,0 +1,56 @@ +/// One data type an app collects, as the App Privacy page asks it: what it's used for, +/// whether it's linked to the user, whether it tracks them (law 1). +public struct CollectedData: Sendable, Equatable, Codable { + public let category: DataCategory + public let purposes: [DataPurpose] + public let isLinkedToYou: Bool + public let isUsedToTrackYou: Bool + + public init(category: DataCategory, purposes: [DataPurpose], isLinkedToYou: Bool, isUsedToTrackYou: Bool) { + self.category = category + self.purposes = purposes + self.isLinkedToYou = isLinkedToYou + self.isUsedToTrackYou = isUsedToTrackYou + } + + /// The rows Apple stores for it: one per purpose, plus a purpose-less one when it tracks. + var entries: [DataUsageEntry] { + let protection: DataProtection = isLinkedToYou ? .linkedToYou : .notLinkedToYou + var rows = purposes.map { DataUsageEntry(category: category, purpose: $0, protection: protection) } + if isUsedToTrackYou { + rows.append(DataUsageEntry(category: category, purpose: nil, protection: .usedToTrackYou)) + } + return rows + } + + /// Apple's rows joined back into one data type each, by category then purpose. + static func grouping(_ usages: [DataUsage]) -> [CollectedData] { + let byCategory = Dictionary(grouping: usages.filter { $0.category != nil }, by: { $0.category! }) + return byCategory.keys.sorted { $0.rawValue < $1.rawValue }.map { category in + let rows = byCategory[category]! + return CollectedData( + category: category, + purposes: Set(rows.compactMap(\.purpose)).sorted { $0.rawValue < $1.rawValue }, + isLinkedToYou: rows.contains { $0.protection == .linkedToYou }, + isUsedToTrackYou: rows.contains { $0.protection == .usedToTrackYou } + ) + } + } +} + +/// What the label says about collection. +public enum DataCollection: Sendable, Equatable { + /// Nothing declared yet. + case notAnswered + /// "Data Not Collected" — the whole label (law 2). + case notCollected + case collected([CollectedData]) + + var wireValue: String { + switch self { + case .notAnswered: "NOT_ANSWERED" + case .notCollected: "NOT_COLLECTED" + case .collected: "COLLECTED" + } + } +} diff --git a/Sources/ASCKit/Iris/AppPrivacy/DataUsage.swift b/Sources/ASCKit/Iris/AppPrivacy/DataUsage.swift new file mode 100644 index 00000000..56509bff --- /dev/null +++ b/Sources/ASCKit/Iris/AppPrivacy/DataUsage.swift @@ -0,0 +1,86 @@ +/// A kind of data an app may collect (Apple's `appDataUsageCategories` id, e.g. `EMAIL_ADDRESS`). +/// One Apple sends that asc doesn't know is kept as sent; asc never sends one (law 6). +public struct DataCategory: RawRepresentable, Hashable, Sendable, Codable { + public let rawValue: String + public init(rawValue: String) { self.rawValue = rawValue } + + public var isRecognized: Bool { Self.known.contains(rawValue) } + + /// The categories on the App Privacy page, by grouping. + static let known: Set = [ + "NAME", "EMAIL_ADDRESS", "PHONE_NUMBER", "PHYSICAL_ADDRESS", "OTHER_CONTACT_INFO", + "HEALTH", "FITNESS", + "PAYMENT_INFORMATION", "CREDIT_AND_FRAUD", "OTHER_FINANCIAL_INFO", + "PRECISE_LOCATION", "COARSE_LOCATION", + "SENSITIVE_INFO", + "CONTACTS", + "EMAILS_OR_TEXT_MESSAGES", "PHOTOS_OR_VIDEOS", "AUDIO", "GAMEPLAY_CONTENT", "CUSTOMER_SUPPORT", "OTHER_USER_CONTENT", + "BROWSING_HISTORY", + "SEARCH_HISTORY", + "USER_ID", "DEVICE_ID", + "PURCHASE_HISTORY", + "PRODUCT_INTERACTION", "ADVERTISING_DATA", "OTHER_USAGE_DATA", + "CRASH_DATA", "PERFORMANCE_DATA", "OTHER_DIAGNOSTIC_DATA", + "OTHER_DATA_TYPES", + ] +} + +/// Why collected data is used (Apple's `appDataUsagePurposes` id, e.g. `ANALYTICS`). +public struct DataPurpose: RawRepresentable, Hashable, Sendable, Codable { + public let rawValue: String + public init(rawValue: String) { self.rawValue = rawValue } + + public var isRecognized: Bool { Self.known.contains(rawValue) } + + static let known: Set = [ + "APP_FUNCTIONALITY", "ANALYTICS", "PRODUCT_PERSONALIZATION", + "DEVELOPERS_ADVERTISING", "THIRD_PARTY_ADVERTISING", "OTHER_PURPOSES", + ] +} + +/// How a row's data is handled (Apple's `appDataUsageDataProtections` id). +public struct DataProtection: RawRepresentable, Hashable, Sendable, Codable { + public let rawValue: String + public init(rawValue: String) { self.rawValue = rawValue } + + /// The whole label: the app collects nothing (law 2). + public static let notCollected = DataProtection(rawValue: "DATA_NOT_COLLECTED") + public static let linkedToYou = DataProtection(rawValue: "DATA_LINKED_TO_YOU") + public static let notLinkedToYou = DataProtection(rawValue: "DATA_NOT_LINKED_TO_YOU") + /// A tracking row has no purpose. + public static let usedToTrackYou = DataProtection(rawValue: "DATA_USED_TO_TRACK_YOU") +} + +/// One row as Apple stores it: a category, a purpose and a protection (law 1). asc changes +/// a label row by row, but shows and takes it as `CollectedData`. +public struct DataUsageEntry: Hashable, Sendable, Codable { + public let category: DataCategory? + public let purpose: DataPurpose? + public let protection: DataProtection + + public init(category: DataCategory?, purpose: DataPurpose?, protection: DataProtection) { + self.category = category + self.purpose = purpose + self.protection = protection + } +} + +/// A row Apple holds for an app (`appDataUsages`), with the id a change deletes it by. +public struct DataUsage: Sendable, Equatable, Identifiable, Codable { + public let id: String + /// Parent: injected by the adapter from the request. + public let appId: String + public let category: DataCategory? + public let purpose: DataPurpose? + public let protection: DataProtection + + public init(id: String, appId: String, category: DataCategory?, purpose: DataPurpose?, protection: DataProtection) { + self.id = id + self.appId = appId + self.category = category + self.purpose = purpose + self.protection = protection + } + + public var entry: DataUsageEntry { DataUsageEntry(category: category, purpose: purpose, protection: protection) } +} diff --git a/Sources/ASCKit/Iris/AppPrivacy/DataUsagePlan.swift b/Sources/ASCKit/Iris/AppPrivacy/DataUsagePlan.swift new file mode 100644 index 00000000..5327bacc --- /dev/null +++ b/Sources/ASCKit/Iris/AppPrivacy/DataUsagePlan.swift @@ -0,0 +1,14 @@ +/// How a declaration replaces the rows Apple holds (law 3): delete those not wanted, then +/// create those missing. Rows already right are left alone. +public struct DataUsagePlan: Sendable, Equatable { + public let deletions: [DataUsage] + public let creations: [DataUsageEntry] + + public init(current: [DataUsage], wanted: PrivacyDeclaration) { + let wantedEntries = wanted.entries + let held = Set(current.map(\.entry)) + let keep = Set(wantedEntries) + deletions = current.filter { !keep.contains($0.entry) } + creations = wantedEntries.filter { !held.contains($0) } + } +} diff --git a/Sources/ASCKit/Iris/AppPrivacy/Internal/AppPrivacyWire.swift b/Sources/ASCKit/Iris/AppPrivacy/Internal/AppPrivacyWire.swift new file mode 100644 index 00000000..f34bc58c --- /dev/null +++ b/Sources/ASCKit/Iris/AppPrivacy/Internal/AppPrivacyWire.swift @@ -0,0 +1,83 @@ +/// The App Privacy shapes iris sends and takes (docs/features/app-privacy/design.md). + +struct IrisReference: Codable { + let type: String + let id: String +} + +struct IrisRelationship: Codable { + let data: IrisReference? +} + +/// `GET apps/{id}/dataUsages`: the ids are in the relationships; `included` adds nothing asc reads. +struct AppDataUsagesResponse: Decodable { + struct Row: Decodable { + struct Relationships: Decodable { + let category: IrisRelationship? + let purpose: IrisRelationship? + let dataProtection: IrisRelationship? + } + + let id: String + let relationships: Relationships + } + + let data: [Row] +} + +/// `GET apps/{id}/dataUsagePublishState`. +struct AppDataUsagesPublishStateResponse: Decodable { + struct State: Decodable { + struct Attributes: Decodable { + let published: Bool? + let lastPublished: String? + } + + let attributes: Attributes + } + + let data: State +} + +/// `POST appDataUsages`: the app plus each part of the row it has. +struct AppDataUsageCreateRequest: Encodable { + struct Resource: Encodable { + let type = "appDataUsages" + let relationships: [String: IrisRelationship] + } + + let data: Resource + + init(appId: String, entry: DataUsageEntry) { + var relationships = [ + "app": IrisRelationship(data: IrisReference(type: "apps", id: appId)), + "dataProtection": IrisRelationship(data: IrisReference(type: "appDataUsageDataProtections", id: entry.protection.rawValue)), + ] + if let category = entry.category { + relationships["category"] = IrisRelationship(data: IrisReference(type: "appDataUsageCategories", id: category.rawValue)) + } + if let purpose = entry.purpose { + relationships["purpose"] = IrisRelationship(data: IrisReference(type: "appDataUsagePurposes", id: purpose.rawValue)) + } + data = Resource(relationships: relationships) + } +} + +/// `PATCH appDataUsagesPublishState/{appId}`. +struct AppDataUsagesPublishRequest: Encodable { + struct Resource: Encodable { + struct Attributes: Encodable { + let published: Bool + } + + let type = "appDataUsagesPublishState" + let id: String + let attributes: Attributes + } + + let data: Resource + + init(appId: String) { + data = Resource(id: appId, attributes: .init(published: true)) + } +} diff --git a/Sources/ASCKit/Iris/AppPrivacy/Internal/IrisSDKAppPrivacyRepository.swift b/Sources/ASCKit/Iris/AppPrivacy/Internal/IrisSDKAppPrivacyRepository.swift new file mode 100644 index 00000000..84441a4f --- /dev/null +++ b/Sources/ASCKit/Iris/AppPrivacy/Internal/IrisSDKAppPrivacyRepository.swift @@ -0,0 +1,59 @@ +import Foundation + +/// `IrisAppPrivacyRepository` over iris, making the calls the App Privacy page makes. +public struct IrisSDKAppPrivacyRepository: IrisAppPrivacyRepository { + private let api: any IrisAPI + + public init() { + self.init(api: IrisClient()) + } + + init(api: any IrisAPI) { + self.api = api + } + + public func fetchPrivacy(session: IrisSession, appId: String) async throws -> AppPrivacy { + async let usages = listDataUsages(session: session, appId: appId) + async let state = api.get(path: "apps/\(appId)/dataUsagePublishState", cookies: session.cookies) + let attributes = try JSONDecoder().decode(AppDataUsagesPublishStateResponse.self, from: try await state.0).data.attributes + return AppPrivacy(appId: appId, dataUsages: try await usages, + isPublished: attributes.published ?? false, lastPublishedAt: attributes.lastPublished) + } + + public func listDataUsages(session: IrisSession, appId: String) async throws -> [DataUsage] { + let (data, _) = try await api.get(path: "apps/\(appId)/dataUsages", queryItems: [ + URLQueryItem(name: "include", value: "category,grouping,purpose,dataProtection"), + URLQueryItem(name: "limit", value: "500"), + ], cookies: session.cookies) + return try JSONDecoder().decode(AppDataUsagesResponse.self, from: data).data.compactMap { row in + guard let protection = row.relationships.dataProtection?.data?.id else { return nil } + return DataUsage( + id: row.id, + appId: appId, + category: row.relationships.category?.data.map { DataCategory(rawValue: $0.id) }, + purpose: row.relationships.purpose?.data.map { DataPurpose(rawValue: $0.id) }, + protection: DataProtection(rawValue: protection) + ) + } + } + + public func createDataUsage(session: IrisSession, appId: String, entry: DataUsageEntry) async throws { + let body = try Self.encoder.encode(AppDataUsageCreateRequest(appId: appId, entry: entry)) + _ = try await api.post(path: "appDataUsages", body: body, cookies: session.cookies) + } + + public func deleteDataUsage(session: IrisSession, dataUsageId: String) async throws { + _ = try await api.delete(path: "appDataUsages/\(dataUsageId)", cookies: session.cookies) + } + + public func publish(session: IrisSession, appId: String) async throws { + let body = try Self.encoder.encode(AppDataUsagesPublishRequest(appId: appId)) + _ = try await api.patch(path: "appDataUsagesPublishState/\(appId)", body: body, cookies: session.cookies) + } + + private static let encoder: JSONEncoder = { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] + return encoder + }() +} diff --git a/Sources/ASCKit/Iris/AppPrivacy/IrisAppPrivacyRepository.swift b/Sources/ASCKit/Iris/AppPrivacy/IrisAppPrivacyRepository.swift new file mode 100644 index 00000000..923b64dc --- /dev/null +++ b/Sources/ASCKit/Iris/AppPrivacy/IrisAppPrivacyRepository.swift @@ -0,0 +1,15 @@ +import Mockable + +/// An app's App Privacy rows and whether they're published, through the iris session +/// (`/iris/v1`). There is no public API. +@Mockable +public protocol IrisAppPrivacyRepository: Sendable { + /// The label as the App Privacy page shows it: the rows, joined, and whether it's published. + func fetchPrivacy(session: IrisSession, appId: String) async throws -> AppPrivacy + /// Every row Apple holds for the app, with the ids a change deletes them by. + func listDataUsages(session: IrisSession, appId: String) async throws -> [DataUsage] + func createDataUsage(session: IrisSession, appId: String, entry: DataUsageEntry) async throws + func deleteDataUsage(session: IrisSession, dataUsageId: String) async throws + /// Makes the label live. + func publish(session: IrisSession, appId: String) async throws +} diff --git a/Sources/ASCKit/Iris/AppPrivacy/PrivacyDeclaration.swift b/Sources/ASCKit/Iris/AppPrivacy/PrivacyDeclaration.swift new file mode 100644 index 00000000..fbe15d11 --- /dev/null +++ b/Sources/ASCKit/Iris/AppPrivacy/PrivacyDeclaration.swift @@ -0,0 +1,54 @@ +/// What a developer declares: no data at all, or the data types the app collects. The type +/// can't hold both (law 2). As JSON — a `--file` or a REST body — it is +/// `{"notCollected": true}` or `{"collectedData": [...]}`, the shape `get` shows. +public enum PrivacyDeclaration: Sendable, Equatable { + case notCollected + case collected([CollectedData]) + + /// The rows Apple stores for it (law 1). + public var entries: [DataUsageEntry] { + switch self { + case .notCollected: [DataUsageEntry(category: nil, purpose: nil, protection: .notCollected)] + case .collected(let data): data.flatMap(\.entries) + } + } + + /// Refuses what asc won't send, before anything reaches Apple (law 6). + public func validate() throws { + guard case .collected(let data) = self else { return } + guard !data.isEmpty else { throw AppPrivacyError.noDataTypes } + var seen: Set = [] + for item in data { + guard item.category.isRecognized else { throw AppPrivacyError.unknownCategory(item.category.rawValue) } + guard seen.insert(item.category).inserted else { throw AppPrivacyError.duplicateCategory(item.category.rawValue) } + guard !item.purposes.isEmpty else { throw AppPrivacyError.noPurposes(category: item.category.rawValue) } + var purposes: Set = [] + for purpose in item.purposes { + guard purpose.isRecognized else { throw AppPrivacyError.unknownPurpose(purpose.rawValue) } + guard purposes.insert(purpose).inserted else { + throw AppPrivacyError.duplicatePurpose(category: item.category.rawValue, purpose: purpose.rawValue) + } + } + } + } +} + +extension PrivacyDeclaration: Decodable { + private enum CodingKeys: String, CodingKey { + case notCollected, collectedData + } + + public init(from decoder: any Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + let notCollected = try c.decodeIfPresent(Bool.self, forKey: .notCollected) ?? false + let data = try c.decodeIfPresent([CollectedData].self, forKey: .collectedData) + switch (notCollected, data) { + case (true, nil): self = .notCollected + case (false, let data?): self = .collected(data) + default: + throw DecodingError.dataCorrupted(.init( + codingPath: [], debugDescription: #"Give either "notCollected": true or "collectedData": [...], not both"# + )) + } + } +} diff --git a/Sources/ASCKit/Iris/Internal/IrisAPI.swift b/Sources/ASCKit/Iris/Internal/IrisAPI.swift index a4c7949c..4651e0bd 100644 --- a/Sources/ASCKit/Iris/Internal/IrisAPI.swift +++ b/Sources/ASCKit/Iris/Internal/IrisAPI.swift @@ -10,6 +10,7 @@ public protocol IrisAPI: Sendable { /// Fetch an absolute URL with the session cookies. Callers validate the host first. func download(absoluteURL: URL, cookies: String) async throws -> (Data, HTTPURLResponse) func delete(path: String, cookies: String) async throws -> (Data, HTTPURLResponse) + func patch(path: String, body: Data, cookies: String) async throws -> (Data, HTTPURLResponse) // The App Compliance service, `ppm/compliancerequirements/v1`, with the same session. func complianceGet(path: String, queryItems: [URLQueryItem], cookies: String) async throws -> (Data, HTTPURLResponse) diff --git a/Sources/ASCKit/Iris/Internal/IrisRequest.swift b/Sources/ASCKit/Iris/Internal/IrisRequest.swift index 08b3330e..8e372c1d 100644 --- a/Sources/ASCKit/Iris/Internal/IrisRequest.swift +++ b/Sources/ASCKit/Iris/Internal/IrisRequest.swift @@ -20,6 +20,12 @@ enum IrisRequest { return request } + static func patch(path: String, body: Data, cookies: String) -> URLRequest { + var request = iris(url: URL(string: "\(baseURL)/\(path)")!, method: "PATCH", cookies: cookies) + request.httpBody = body + return request + } + static func delete(path: String, cookies: String) -> URLRequest { iris(url: URL(string: "\(baseURL)/\(path)")!, method: "DELETE", cookies: cookies) } diff --git a/Sources/ASCKit/Iris/Internal/System/IrisClient.swift b/Sources/ASCKit/Iris/Internal/System/IrisClient.swift index aca19f93..66af9570 100644 --- a/Sources/ASCKit/Iris/Internal/System/IrisClient.swift +++ b/Sources/ASCKit/Iris/Internal/System/IrisClient.swift @@ -27,6 +27,10 @@ public struct IrisClient: IrisAPI { try await perform(IrisRequest.delete(path: path, cookies: cookies)) } + public func patch(path: String, body: Data, cookies: String) async throws -> (Data, HTTPURLResponse) { + try await perform(IrisRequest.patch(path: path, body: body, cookies: cookies)) + } + public func complianceGet(path: String, queryItems: [URLQueryItem], cookies: String) async throws -> (Data, HTTPURLResponse) { try await perform(IrisRequest.compliance(method: "GET", path: path, queryItems: queryItems, body: nil, cookies: cookies)) } diff --git a/Sources/ASCKit/Shared/Internal/ClientFactory.swift b/Sources/ASCKit/Shared/Internal/ClientFactory.swift index dcc921e4..5ad3bfba 100644 --- a/Sources/ASCKit/Shared/Internal/ClientFactory.swift +++ b/Sources/ASCKit/Shared/Internal/ClientFactory.swift @@ -369,6 +369,10 @@ public struct ClientFactory: Sendable { IrisSDKComplianceRepository() } + public func makeIrisAppPrivacyRepository() -> any IrisAppPrivacyRepository { + IrisSDKAppPrivacyRepository() + } + public func makeIrisCookieProvider() -> any IrisCookieProvider { // Resolution order: SRP-stored session (from `asc iris auth login`) first, // browser cookies as a fallback for users who haven't run SRP login. The diff --git a/Sources/ASCKit/Shared/RESTPathResolver.swift b/Sources/ASCKit/Shared/RESTPathResolver.swift index 397045d9..35ac168e 100644 --- a/Sources/ASCKit/Shared/RESTPathResolver.swift +++ b/Sources/ASCKit/Shared/RESTPathResolver.swift @@ -236,6 +236,7 @@ public final class RESTPathResolver: @unchecked Sendable { _ = _assetLibraryRoutes _ = _screenshotImportRoutes _ = _complianceRoutes + _ = _appPrivacyRoutes initialized = true } diff --git a/Tests/ASCCommandTests/Commands/Iris/AppPrivacy/IrisAppPrivacyTests.swift b/Tests/ASCCommandTests/Commands/Iris/AppPrivacy/IrisAppPrivacyTests.swift new file mode 100644 index 00000000..7f75a508 --- /dev/null +++ b/Tests/ASCCommandTests/Commands/Iris/AppPrivacy/IrisAppPrivacyTests.swift @@ -0,0 +1,175 @@ +import Foundation +import Mockable +import Testing +@testable import ASCCommand +@testable import ASCKit + +@Suite +struct IrisAppPrivacyTests { + private func cookies() -> MockIrisCookieProvider { + let provider = MockIrisCookieProvider() + given(provider).resolveSession().willReturn(IrisSession(cookies: "myacinfo=a")) + return provider + } + + private let unanswered = AppPrivacy(appId: "1234567890", dataCollection: .notAnswered, isPublished: false, lastPublishedAt: nil) + private let notCollected = AppPrivacy(appId: "1234567890", dataCollection: .notCollected, isPublished: false, lastPublishedAt: nil) + private let live = AppPrivacy(appId: "1234567890", dataCollection: .notCollected, isPublished: true, lastPublishedAt: "2026-11-24T00:14:02-08:00") + + private func repo(showing privacy: AppPrivacy) -> MockIrisAppPrivacyRepository { + let repo = MockIrisAppPrivacyRepository() + given(repo).fetchPrivacy(session: .any, appId: .value("1234567890")).willReturn(privacy) + given(repo).listDataUsages(session: .any, appId: .value("1234567890")).willReturn([]) + given(repo).createDataUsage(session: .any, appId: .any, entry: .any).willReturn() + given(repo).deleteDataUsage(session: .any, dataUsageId: .any).willReturn() + given(repo).publish(session: .any, appId: .any).willReturn() + return repo + } + + @Test func `should show an unanswered label as blocking review, with both ways to declare it`() async throws { + let cmd = try IrisAppPrivacyGet.parse(["--app-id", "1234567890", "--pretty"]) + + let output = try await cmd.execute(cookieProvider: cookies(), repo: repo(showing: unanswered)) + + #expect(output == """ + { + "data" : [ + { + "affordances" : { + "declare" : "asc iris app-privacy declare --app-id 1234567890 --file ", + "declareNotCollected" : "asc iris app-privacy declare --app-id 1234567890 --not-collected", + "get" : "asc iris app-privacy get --app-id 1234567890" + }, + "appId" : "1234567890", + "blocksSubmission" : true, + "dataCollection" : "NOT_ANSWERED", + "isAnswered" : false, + "isPublished" : false + } + ] + } + """) + } + + @Test func `should declare no data collected and offer to publish it`() async throws { + let cmd = try IrisAppPrivacyDeclare.parse(["--app-id", "1234567890", "--not-collected", "--pretty"]) + + let output = try await cmd.execute(cookieProvider: cookies(), repo: repo(showing: notCollected)) + + #expect(output == """ + { + "data" : [ + { + "affordances" : { + "declare" : "asc iris app-privacy declare --app-id 1234567890 --file ", + "get" : "asc iris app-privacy get --app-id 1234567890", + "publish" : "asc iris app-privacy publish --app-id 1234567890" + }, + "appId" : "1234567890", + "blocksSubmission" : true, + "dataCollection" : "NOT_COLLECTED", + "isAnswered" : true, + "isPublished" : false + } + ] + } + """) + } + + @Test func `should declare the collected data a file lists`() async throws { + let declared = AppPrivacy(appId: "1234567890", dataCollection: .collected([ + CollectedData(category: .init(rawValue: "CRASH_DATA"), purposes: [.init(rawValue: "ANALYTICS")], isLinkedToYou: false, isUsedToTrackYou: false), + ]), isPublished: false, lastPublishedAt: nil) + let file = FileManager.default.temporaryDirectory.appendingPathComponent("privacy-\(UUID().uuidString).json") + try Data(#"{"collectedData":[{"category":"CRASH_DATA","purposes":["ANALYTICS"],"isLinkedToYou":false,"isUsedToTrackYou":false}]}"#.utf8).write(to: file) + defer { try? FileManager.default.removeItem(at: file) } + let cmd = try IrisAppPrivacyDeclare.parse(["--app-id", "1234567890", "--file", file.path, "--pretty"]) + + let output = try await cmd.execute(cookieProvider: cookies(), repo: repo(showing: declared)) + + #expect(output == """ + { + "data" : [ + { + "affordances" : { + "declare" : "asc iris app-privacy declare --app-id 1234567890 --file ", + "get" : "asc iris app-privacy get --app-id 1234567890", + "publish" : "asc iris app-privacy publish --app-id 1234567890" + }, + "appId" : "1234567890", + "blocksSubmission" : true, + "collectedData" : [ + { + "category" : "CRASH_DATA", + "isLinkedToYou" : false, + "isUsedToTrackYou" : false, + "purposes" : [ + "ANALYTICS" + ] + } + ], + "dataCollection" : "COLLECTED", + "isAnswered" : true, + "isPublished" : false + } + ] + } + """) + } + + @Test func `should refuse a data type it doesn't know before reaching Apple`() async throws { + let file = FileManager.default.temporaryDirectory.appendingPathComponent("privacy-\(UUID().uuidString).json") + try Data(#"{"collectedData":[{"category":"EMAIL","purposes":["ANALYTICS"],"isLinkedToYou":true,"isUsedToTrackYou":false}]}"#.utf8).write(to: file) + defer { try? FileManager.default.removeItem(at: file) } + let cookies = cookies() + let repo = repo(showing: unanswered) + let cmd = try IrisAppPrivacyDeclare.parse(["--app-id", "1234567890", "--file", file.path]) + + await #expect(throws: AppPrivacyError.unknownCategory("EMAIL")) { + try await cmd.execute(cookieProvider: cookies, repo: repo) + } + verify(cookies).resolveSession().called(0) + verify(repo).fetchPrivacy(session: .any, appId: .any).called(0) + } + + @Test func `should refuse to be told both that nothing is collected and what is`() { + #expect(throws: (any Error).self) { + try IrisAppPrivacyDeclare.parse(["--app-id", "1234567890", "--not-collected", "--file", "privacy.json"]) + } + } + + @Test func `should refuse a declare that says neither`() { + #expect(throws: (any Error).self) { + try IrisAppPrivacyDeclare.parse(["--app-id", "1234567890"]) + } + } + + @Test func `should publish the label and show it no longer blocks review`() async throws { + let repo = MockIrisAppPrivacyRepository() + given(repo).fetchPrivacy(session: .any, appId: .value("1234567890")).willReturn(notCollected) + given(repo).fetchPrivacy(session: .any, appId: .value("1234567890")).willReturn(live) + given(repo).publish(session: .any, appId: .value("1234567890")).willReturn() + let cmd = try IrisAppPrivacyPublish.parse(["--app-id", "1234567890", "--pretty"]) + + let output = try await cmd.execute(cookieProvider: cookies(), repo: repo) + + #expect(output == """ + { + "data" : [ + { + "affordances" : { + "declare" : "asc iris app-privacy declare --app-id 1234567890 --file ", + "get" : "asc iris app-privacy get --app-id 1234567890" + }, + "appId" : "1234567890", + "blocksSubmission" : false, + "dataCollection" : "NOT_COLLECTED", + "isAnswered" : true, + "isPublished" : true, + "lastPublishedAt" : "2026-11-24T00:14:02-08:00" + } + ] + } + """) + } +} diff --git a/Tests/ASCCommandTests/Commands/Web/Controllers/IrisAppPrivacyRoutesTests.swift b/Tests/ASCCommandTests/Commands/Web/Controllers/IrisAppPrivacyRoutesTests.swift new file mode 100644 index 00000000..1da9928c --- /dev/null +++ b/Tests/ASCCommandTests/Commands/Web/Controllers/IrisAppPrivacyRoutesTests.swift @@ -0,0 +1,102 @@ +import Foundation +import Hummingbird +import HummingbirdTesting +import HummingbirdWebSocket +import Mockable +import NIOCore +import Testing +@testable import ASCCommand +@testable import ASCKit + +@Suite +struct IrisAppPrivacyRoutesTests { + private let unanswered = AppPrivacy(appId: "1234567890", dataCollection: .notAnswered, isPublished: false, lastPublishedAt: nil) + private let notCollected = AppPrivacy(appId: "1234567890", dataCollection: .notCollected, isPublished: false, lastPublishedAt: nil) + + private func call(_ method: HTTPRequest.Method, _ uri: String, body: String? = nil, showing privacy: AppPrivacy) async throws -> (HTTPResponse.Status, String) { + let cookies = MockIrisCookieProvider() + given(cookies).resolveSession().willReturn(IrisSession(cookies: "myacinfo=a")) + let repo = MockIrisAppPrivacyRepository() + given(repo).fetchPrivacy(session: .any, appId: .value("1234567890")).willReturn(privacy) + given(repo).listDataUsages(session: .any, appId: .any).willReturn([]) + given(repo).createDataUsage(session: .any, appId: .any, entry: .any).willReturn() + given(repo).publish(session: .any, appId: .any).willReturn() + let router = Router(context: BasicWebSocketRequestContext.self) + IrisAppPrivacyController(cookieProvider: cookies, repo: repo).addRoutes(to: router.group("/api/v1")) + return try await Application(router: router).test(.router) { client in + try await client.execute(uri: uri, method: method, body: body.map { ByteBuffer(string: $0) }) { + ($0.status, String(buffer: $0.body)) + } + } + } + + private func label(_ body: String) throws -> [String: Any] { + try #require(((try JSONSerialization.jsonObject(with: Data(body.utf8)) as? [String: Any])?["data"] as? [[String: Any]])?.first) + } + + @Test func `should show an app's privacy label over REST with where to declare it`() async throws { + let (status, body) = try await call(.get, "/api/v1/iris/apps/1234567890/app-privacy", showing: unanswered) + + #expect(status == .ok) + let row = try label(body) + #expect(row["dataCollection"] as? String == "NOT_ANSWERED") + #expect((row["_links"] as? [String: Any])?["declare"] as? [String: String] + == ["href": "/api/v1/iris/apps/1234567890/app-privacy/declare", "method": "POST"]) + } + + @Test func `should declare no data collected over REST and link to publishing it`() async throws { + let (status, body) = try await call(.post, "/api/v1/iris/apps/1234567890/app-privacy/declare", + body: #"{"notCollected":true}"#, showing: notCollected) + + #expect(status == .ok) + let row = try label(body) + #expect(row["dataCollection"] as? String == "NOT_COLLECTED") + #expect((row["_links"] as? [String: Any])?["publish"] as? [String: String] + == ["href": "/api/v1/iris/apps/1234567890/app-privacy/publish", "method": "POST"]) + } + + @Test func `should refuse a declaration body that says neither`() async throws { + let (status, body) = try await call(.post, "/api/v1/iris/apps/1234567890/app-privacy/declare", body: "{}", showing: unanswered) + + #expect(status == .badRequest) + #expect(body.contains(#"notCollected"#)) + } + + @Test func `should refuse a data type App Privacy doesn't know as unprocessable`() async throws { + let (status, _) = try await call(.post, "/api/v1/iris/apps/1234567890/app-privacy/declare", + body: #"{"collectedData":[{"category":"EMAIL","purposes":["ANALYTICS"],"isLinkedToYou":true,"isUsedToTrackYou":false}]}"#, + showing: unanswered) + + #expect(status == .unprocessableContent) + } + + @Test func `should refuse a data type App Privacy doesn't know without reaching Apple`() async throws { + let cookies = MockIrisCookieProvider() + given(cookies).resolveSession().willReturn(IrisSession(cookies: "myacinfo=a")) + let repo = MockIrisAppPrivacyRepository() + given(repo).fetchPrivacy(session: .any, appId: .any).willReturn(unanswered) + let router = Router(context: BasicWebSocketRequestContext.self) + IrisAppPrivacyController(cookieProvider: cookies, repo: repo).addRoutes(to: router.group("/api/v1")) + + let status = try await Application(router: router).test(.router) { client in + try await client.execute(uri: "/api/v1/iris/apps/1234567890/app-privacy/declare", method: .post, + body: ByteBuffer(string: #"{"collectedData":[{"category":"EMAIL","purposes":["ANALYTICS"],"isLinkedToYou":true,"isUsedToTrackYou":false}]}"#)) { $0.status } + } + + #expect(status == .unprocessableContent) + verify(repo).fetchPrivacy(session: .any, appId: .any).called(0) + } + + @Test func `should publish over REST`() async throws { + let (status, body) = try await call(.post, "/api/v1/iris/apps/1234567890/app-privacy/publish", showing: notCollected) + + #expect(status == .ok) + #expect(try label(body)["appId"] as? String == "1234567890") + } + + @Test func `should refuse to publish a label nothing is declared on as a conflict`() async throws { + let (status, _) = try await call(.post, "/api/v1/iris/apps/1234567890/app-privacy/publish", showing: unanswered) + + #expect(status == .conflict) + } +} diff --git a/Tests/ASCKitTests/Iris/AppPrivacy/AppPrivacyTests.swift b/Tests/ASCKitTests/Iris/AppPrivacy/AppPrivacyTests.swift new file mode 100644 index 00000000..34fb6e1b --- /dev/null +++ b/Tests/ASCKitTests/Iris/AppPrivacy/AppPrivacyTests.swift @@ -0,0 +1,140 @@ +import Foundation +import Mockable +import Testing +@testable import ASCKit + +@Suite +struct AppPrivacyTests { + private let session = IrisSession(cookies: "myacinfo=a") + + private func usage(_ id: String, _ category: String?, _ purpose: String?, _ protection: DataProtection) -> DataUsage { + DataUsage(id: id, appId: "1234567890", category: category.map(DataCategory.init(rawValue:)), + purpose: purpose.map(DataPurpose.init(rawValue:)), protection: protection) + } + + private func label(_ usages: [DataUsage], published: Bool = false) -> AppPrivacy { + AppPrivacy(appId: "1234567890", dataUsages: usages, isPublished: published, + lastPublishedAt: published ? "2026-11-24T00:14:02-08:00" : nil) + } + + private func json(_ privacy: AppPrivacy) throws -> String { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + return String(decoding: try encoder.encode(privacy), as: UTF8.self) + } + + // MARK: - what the label says (laws 1, 7) + + @Test func `should be unanswered and block review when nothing is declared`() throws { + #expect(try json(label([])) == #"{"appId":"1234567890","blocksSubmission":true,"dataCollection":"NOT_ANSWERED","isAnswered":false,"isPublished":false}"#) + } + + @Test func `should say no data is collected when its one row says so`() { + #expect(label([usage("u-1", nil, nil, .notCollected)]).dataCollection == .notCollected) + } + + @Test func `should show each collected data type once with every purpose it is used for`() { + let privacy = label([ + usage("u-1", "OTHER_USAGE_DATA", "OTHER_PURPOSES", .notLinkedToYou), + usage("u-2", "OTHER_USAGE_DATA", "ANALYTICS", .notLinkedToYou), + usage("u-3", "EMAIL_ADDRESS", "APP_FUNCTIONALITY", .linkedToYou), + usage("u-4", "EMAIL_ADDRESS", nil, .usedToTrackYou), + ]) + + #expect(privacy.dataCollection == .collected([ + CollectedData(category: .init(rawValue: "EMAIL_ADDRESS"), purposes: [.init(rawValue: "APP_FUNCTIONALITY")], + isLinkedToYou: true, isUsedToTrackYou: true), + CollectedData(category: .init(rawValue: "OTHER_USAGE_DATA"), purposes: [.init(rawValue: "ANALYTICS"), .init(rawValue: "OTHER_PURPOSES")], + isLinkedToYou: false, isUsedToTrackYou: false), + ])) + } + + @Test func `should stop blocking review once an answer is published`() throws { + #expect(try json(label([usage("u-1", "CRASH_DATA", "ANALYTICS", .notLinkedToYou)], published: true)) + == #"{"appId":"1234567890","blocksSubmission":false,"collectedData":[{"category":"CRASH_DATA","isLinkedToYou":false,"isUsedToTrackYou":false,"purposes":["ANALYTICS"]}],"dataCollection":"COLLECTED","isAnswered":true,"isPublished":true,"lastPublishedAt":"2026-11-24T00:14:02-08:00"}"#) + } + + @Test func `should still block review when the answer is declared but not published`() { + #expect(label([usage("u-1", nil, nil, .notCollected)]).blocksSubmission) + } + + @Test func `should read back the label it wrote`() throws { + let privacy = label([usage("u-1", "CRASH_DATA", "ANALYTICS", .notLinkedToYou)], published: true) + #expect(try JSONDecoder().decode(AppPrivacy.self, from: Data(try json(privacy).utf8)) == privacy) + } + + // MARK: - affordances (law 4) + + @Test func `should offer to declare an unanswered label either way, and not to publish it`() { + let privacy = label([]) + #expect(privacy.affordances == [ + "get": "asc iris app-privacy get --app-id 1234567890", + "declare": "asc iris app-privacy declare --app-id 1234567890 --file ", + "declareNotCollected": "asc iris app-privacy declare --app-id 1234567890 --not-collected", + ]) + } + + @Test func `should offer to publish a declared label that isn't live`() { + let privacy = label([usage("u-1", nil, nil, .notCollected)]) + #expect(privacy.affordances == [ + "get": "asc iris app-privacy get --app-id 1234567890", + "declare": "asc iris app-privacy declare --app-id 1234567890 --file ", + "publish": "asc iris app-privacy publish --app-id 1234567890", + ]) + } + + @Test func `should not offer to publish a label that is already live`() { + #expect(label([usage("u-1", nil, nil, .notCollected)], published: true).affordances["publish"] == nil) + } + + @Test func `should link the label over REST under its app`() { + let privacy = label([usage("u-1", nil, nil, .notCollected)]) + #expect(privacy.apiLinks["get"] == APILink(href: "/api/v1/iris/apps/1234567890/app-privacy", method: "GET")) + #expect(privacy.apiLinks["declare"] == APILink(href: "/api/v1/iris/apps/1234567890/app-privacy/declare", method: "POST")) + #expect(privacy.apiLinks["publish"] == APILink(href: "/api/v1/iris/apps/1234567890/app-privacy/publish", method: "POST")) + } + + // MARK: - publish (law 5) + + @Test func `should refuse to publish a label nothing is declared on`() async { + await #expect(throws: AppPrivacyError.nothingDeclared(appId: "1234567890")) { + try await label([]).publish(session: session, repo: MockIrisAppPrivacyRepository()) + } + } + + @Test func `should show the label live after publishing it`() async throws { + let live = label([usage("u-1", nil, nil, .notCollected)], published: true) + let repo = MockIrisAppPrivacyRepository() + given(repo).publish(session: .any, appId: .value("1234567890")).willReturn() + given(repo).fetchPrivacy(session: .any, appId: .value("1234567890")).willReturn(live) + + let published = try await label([usage("u-1", nil, nil, .notCollected)]).publish(session: session, repo: repo) + + #expect(published.isPublished) + } + + // MARK: - declare (laws 3, 6) + + @Test func `should show the label as Apple now holds it after declaring`() async throws { + let declared = label([usage("u-2", nil, nil, .notCollected)]) + let repo = MockIrisAppPrivacyRepository() + given(repo).listDataUsages(session: .any, appId: .value("1234567890")).willReturn([usage("u-1", "CRASH_DATA", "ANALYTICS", .notLinkedToYou)]) + given(repo).deleteDataUsage(session: .any, dataUsageId: .any).willReturn() + given(repo).createDataUsage(session: .any, appId: .any, entry: .any).willReturn() + given(repo).fetchPrivacy(session: .any, appId: .value("1234567890")).willReturn(declared) + + let privacy = try await label([]).declare(.notCollected, session: session, repo: repo) + + #expect(privacy.dataCollection == .notCollected) + #expect(!privacy.isPublished) + } + + @Test func `should refuse a declaration with a data type it doesn't know before anything reaches Apple`() async { + let declaration = PrivacyDeclaration.collected([ + CollectedData(category: .init(rawValue: "EMAIL"), purposes: [.init(rawValue: "ANALYTICS")], isLinkedToYou: true, isUsedToTrackYou: false), + ]) + await #expect(throws: AppPrivacyError.unknownCategory("EMAIL")) { + try await label([]).declare(declaration, session: session, repo: MockIrisAppPrivacyRepository()) + } + } +} diff --git a/Tests/ASCKitTests/Iris/AppPrivacy/DataUsagePlanTests.swift b/Tests/ASCKitTests/Iris/AppPrivacy/DataUsagePlanTests.swift new file mode 100644 index 00000000..78b6a515 --- /dev/null +++ b/Tests/ASCKitTests/Iris/AppPrivacy/DataUsagePlanTests.swift @@ -0,0 +1,40 @@ +import Testing +@testable import ASCKit + +/// Law 3: declaring replaces the label, touching only the rows that change. +@Suite +struct DataUsagePlanTests { + private func usage(_ id: String, _ category: String?, _ purpose: String?, _ protection: DataProtection) -> DataUsage { + DataUsage(id: id, appId: "1234567890", category: category.map(DataCategory.init(rawValue:)), + purpose: purpose.map(DataPurpose.init(rawValue:)), protection: protection) + } + + @Test func `should delete every collected row when the app now collects nothing`() { + let current = [usage("u-1", "CRASH_DATA", "ANALYTICS", .notLinkedToYou), usage("u-2", "CRASH_DATA", "APP_FUNCTIONALITY", .notLinkedToYou)] + + let plan = DataUsagePlan(current: current, wanted: .notCollected) + + #expect(plan.deletions == current) + #expect(plan.creations == [DataUsageEntry(category: nil, purpose: nil, protection: .notCollected)]) + } + + @Test func `should leave rows that are already right alone`() { + let current = [usage("u-1", "CRASH_DATA", "ANALYTICS", .notLinkedToYou), usage("u-2", "CRASH_DATA", "OTHER_PURPOSES", .notLinkedToYou)] + let wanted = PrivacyDeclaration.collected([ + CollectedData(category: .init(rawValue: "CRASH_DATA"), purposes: [.init(rawValue: "ANALYTICS"), .init(rawValue: "APP_FUNCTIONALITY")], + isLinkedToYou: false, isUsedToTrackYou: false), + ]) + + let plan = DataUsagePlan(current: current, wanted: wanted) + + #expect(plan.deletions == [usage("u-2", "CRASH_DATA", "OTHER_PURPOSES", .notLinkedToYou)]) + #expect(plan.creations == [DataUsageEntry(category: .init(rawValue: "CRASH_DATA"), purpose: .init(rawValue: "APP_FUNCTIONALITY"), protection: .notLinkedToYou)]) + } + + @Test func `should change nothing when the label already says it`() { + let plan = DataUsagePlan(current: [usage("u-1", nil, nil, .notCollected)], wanted: .notCollected) + + #expect(plan.deletions.isEmpty) + #expect(plan.creations.isEmpty) + } +} diff --git a/Tests/ASCKitTests/Iris/AppPrivacy/Internal/IrisSDKAppPrivacyRepositoryTests.swift b/Tests/ASCKitTests/Iris/AppPrivacy/Internal/IrisSDKAppPrivacyRepositoryTests.swift new file mode 100644 index 00000000..9e56f882 --- /dev/null +++ b/Tests/ASCKitTests/Iris/AppPrivacy/Internal/IrisSDKAppPrivacyRepositoryTests.swift @@ -0,0 +1,137 @@ +import Foundation +import Mockable +import Testing +@testable import ASCKit + +/// Fixtures are captured responses (docs/features/app-privacy/design.md, live on +/// 2026-11-24), ids replaced — never a shape guessed at. +@Suite +struct IrisSDKAppPrivacyRepositoryTests { + private let session = IrisSession(cookies: "myacinfo=a") + private static let rowsQuery = [ + URLQueryItem(name: "include", value: "category,grouping,purpose,dataProtection"), + URLQueryItem(name: "limit", value: "500"), + ] + + private func ok(_ json: String, status: Int = 200) -> (Data, HTTPURLResponse) { + (Data(json.utf8), HTTPURLResponse(url: URL(string: "https://appstoreconnect.apple.com")!, statusCode: status, httpVersion: nil, headerFields: nil)!) + } + + private static let notCollectedRows = #""" + { "data" : [ { "type" : "appDataUsages", "id" : "usage-1", "relationships" : { + "category" : { "data" : null }, "grouping" : { "data" : null }, "purpose" : { "data" : null }, + "dataProtection" : { "data" : { "type" : "appDataUsageDataProtections", "id" : "DATA_NOT_COLLECTED" } } }, + "links" : { "self" : "https://appstoreconnect.apple.com/iris/v1/appDataUsages/usage-1" } } ], + "included" : [ { "type" : "appDataUsageDataProtections", "id" : "DATA_NOT_COLLECTED", "attributes" : { "deleted" : false } } ], + "meta" : { "paging" : { "total" : 1, "limit" : 500 } } } + """# + + private static func collectedRow(_ id: String, purpose: String) -> String { + #""" + { "type" : "appDataUsages", "id" : "\#(id)", "relationships" : { + "category" : { "data" : { "type" : "appDataUsageCategories", "id" : "OTHER_USAGE_DATA" } }, + "grouping" : { "data" : { "type" : "appDataUsageGroupings", "id" : "USAGE_DATA" } }, + "purpose" : { "data" : { "type" : "appDataUsagePurposes", "id" : "\#(purpose)" } }, + "dataProtection" : { "data" : { "type" : "appDataUsageDataProtections", "id" : "DATA_NOT_LINKED_TO_YOU" } } } } + """# + } + + private static let unanswered = #""" + { "data" : [ ], "included" : [ ], "meta" : { "paging" : { "total" : 0, "limit" : 500 } } } + """# + + private static let neverPublished = #""" + { "data" : { "type" : "appDataUsagesPublishState", "id" : "1234567890", + "attributes" : { "published" : false, "lastPublished" : null, "lastPublishedBy" : null } } } + """# + + private static let published = #""" + { "data" : { "type" : "appDataUsagesPublishState", "id" : "1234567890", + "attributes" : { "published" : true, "lastPublished" : "2026-11-24T00:14:02-08:00", "lastPublishedBy" : "Dev" } } } + """# + + private func iris(rows: String, state: String = neverPublished) -> MockIrisAPI { + let api = MockIrisAPI() + given(api).get(path: .value("apps/1234567890/dataUsages"), queryItems: .value(Self.rowsQuery), cookies: .value("myacinfo=a")) + .willReturn(ok(rows)) + given(api).get(path: .value("apps/1234567890/dataUsagePublishState"), queryItems: .value([]), cookies: .value("myacinfo=a")) + .willReturn(ok(state)) + return api + } + + // MARK: - reading + + @Test func `should show a new app's label as unanswered and unpublished`() async throws { + let repo = IrisSDKAppPrivacyRepository(api: iris(rows: Self.unanswered)) + + let privacy = try await repo.fetchPrivacy(session: session, appId: "1234567890") + + #expect(privacy == AppPrivacy(appId: "1234567890", dataCollection: .notAnswered, isPublished: false, lastPublishedAt: nil)) + } + + @Test func `should show a published Data Not Collected label with when it went live`() async throws { + let repo = IrisSDKAppPrivacyRepository(api: iris(rows: Self.notCollectedRows, state: Self.published)) + + let privacy = try await repo.fetchPrivacy(session: session, appId: "1234567890") + + #expect(privacy == AppPrivacy(appId: "1234567890", dataCollection: .notCollected, isPublished: true, + lastPublishedAt: "2026-11-24T00:14:02-08:00")) + } + + @Test func `should list each row with its id under the app it belongs to`() async throws { + let rows = #"{ "data" : [ \#(Self.collectedRow("usage-1", purpose: "OTHER_PURPOSES")), \#(Self.collectedRow("usage-2", purpose: "ANALYTICS")) ], "included" : [ ] }"# + let repo = IrisSDKAppPrivacyRepository(api: iris(rows: rows)) + + let usages = try await repo.listDataUsages(session: session, appId: "1234567890") + + #expect(usages == [ + DataUsage(id: "usage-1", appId: "1234567890", category: .init(rawValue: "OTHER_USAGE_DATA"), + purpose: .init(rawValue: "OTHER_PURPOSES"), protection: .notLinkedToYou), + DataUsage(id: "usage-2", appId: "1234567890", category: .init(rawValue: "OTHER_USAGE_DATA"), + purpose: .init(rawValue: "ANALYTICS"), protection: .notLinkedToYou), + ]) + } + + // MARK: - changing + + @Test func `should create the not-collected row with the body the page sends`() async throws { + let api = MockIrisAPI() + given(api).post(path: .any, body: .any, cookies: .any).willReturn(ok("", status: 201)) + + try await IrisSDKAppPrivacyRepository(api: api).createDataUsage( + session: session, appId: "1234567890", entry: DataUsageEntry(category: nil, purpose: nil, protection: .notCollected) + ) + + verify(api).post(path: .value("appDataUsages"), body: .value(Data(#"{"data":{"relationships":{"app":{"data":{"id":"1234567890","type":"apps"}},"dataProtection":{"data":{"id":"DATA_NOT_COLLECTED","type":"appDataUsageDataProtections"}}},"type":"appDataUsages"}}"#.utf8)), cookies: .value("myacinfo=a")).called(1) + } + + @Test func `should create a collected row naming its category and purpose`() async throws { + let api = MockIrisAPI() + given(api).post(path: .any, body: .any, cookies: .any).willReturn(ok("", status: 201)) + + try await IrisSDKAppPrivacyRepository(api: api).createDataUsage( + session: session, appId: "1234567890", + entry: DataUsageEntry(category: .init(rawValue: "CRASH_DATA"), purpose: .init(rawValue: "ANALYTICS"), protection: .notLinkedToYou) + ) + + verify(api).post(path: .value("appDataUsages"), body: .value(Data(#"{"data":{"relationships":{"app":{"data":{"id":"1234567890","type":"apps"}},"category":{"data":{"id":"CRASH_DATA","type":"appDataUsageCategories"}},"dataProtection":{"data":{"id":"DATA_NOT_LINKED_TO_YOU","type":"appDataUsageDataProtections"}},"purpose":{"data":{"id":"ANALYTICS","type":"appDataUsagePurposes"}}},"type":"appDataUsages"}}"#.utf8)), cookies: .value("myacinfo=a")).called(1) + } + + @Test func `should delete a row by its own path`() async throws { + let api = MockIrisAPI() + given(api).delete(path: .any, cookies: .any).willReturn(ok("", status: 204)) + + try await IrisSDKAppPrivacyRepository(api: api).deleteDataUsage(session: session, dataUsageId: "usage-1") + + verify(api).delete(path: .value("appDataUsages/usage-1"), cookies: .value("myacinfo=a")).called(1) + } + + @Test func `should publish with the body the page sends`() async throws { + let api = MockIrisAPI() + given(api).patch(path: .any, body: .any, cookies: .any).willReturn(ok(Self.published)) + + try await IrisSDKAppPrivacyRepository(api: api).publish(session: session, appId: "1234567890") + + verify(api).patch(path: .value("appDataUsagesPublishState/1234567890"), body: .value(Data(#"{"data":{"attributes":{"published":true},"id":"1234567890","type":"appDataUsagesPublishState"}}"#.utf8)), cookies: .value("myacinfo=a")).called(1) + } +} diff --git a/Tests/ASCKitTests/Iris/AppPrivacy/PrivacyDeclarationTests.swift b/Tests/ASCKitTests/Iris/AppPrivacy/PrivacyDeclarationTests.swift new file mode 100644 index 00000000..dfbdc606 --- /dev/null +++ b/Tests/ASCKitTests/Iris/AppPrivacy/PrivacyDeclarationTests.swift @@ -0,0 +1,77 @@ +import Foundation +import Testing +@testable import ASCKit + +@Suite +struct PrivacyDeclarationTests { + private func collected(_ category: String, _ purposes: [String], linked: Bool = false, tracking: Bool = false) -> CollectedData { + CollectedData(category: .init(rawValue: category), purposes: purposes.map(DataPurpose.init(rawValue:)), + isLinkedToYou: linked, isUsedToTrackYou: tracking) + } + + // MARK: - the rows Apple stores (law 1) + + @Test func `should be one not-collected row when no data is collected`() { + #expect(PrivacyDeclaration.notCollected.entries == [DataUsageEntry(category: nil, purpose: nil, protection: .notCollected)]) + } + + @Test func `should be one row per purpose, linked or not, plus a purpose-less row when the data tracks`() { + let declaration = PrivacyDeclaration.collected([ + collected("EMAIL_ADDRESS", ["APP_FUNCTIONALITY", "ANALYTICS"], linked: true, tracking: true), + collected("CRASH_DATA", ["ANALYTICS"]), + ]) + + #expect(declaration.entries == [ + DataUsageEntry(category: .init(rawValue: "EMAIL_ADDRESS"), purpose: .init(rawValue: "APP_FUNCTIONALITY"), protection: .linkedToYou), + DataUsageEntry(category: .init(rawValue: "EMAIL_ADDRESS"), purpose: .init(rawValue: "ANALYTICS"), protection: .linkedToYou), + DataUsageEntry(category: .init(rawValue: "EMAIL_ADDRESS"), purpose: nil, protection: .usedToTrackYou), + DataUsageEntry(category: .init(rawValue: "CRASH_DATA"), purpose: .init(rawValue: "ANALYTICS"), protection: .notLinkedToYou), + ]) + } + + // MARK: - what asc refuses to send (law 6) + + @Test func `should refuse collected data with no data types`() { + #expect(throws: AppPrivacyError.noDataTypes) { try PrivacyDeclaration.collected([]).validate() } + } + + @Test func `should refuse a data type with no purpose`() { + #expect(throws: AppPrivacyError.noPurposes(category: "CRASH_DATA")) { + try PrivacyDeclaration.collected([collected("CRASH_DATA", [])]).validate() + } + } + + @Test func `should refuse a purpose it doesn't know`() { + #expect(throws: AppPrivacyError.unknownPurpose("ADS")) { + try PrivacyDeclaration.collected([collected("CRASH_DATA", ["ADS"])]).validate() + } + } + + @Test func `should refuse the same data type declared twice`() { + #expect(throws: AppPrivacyError.duplicateCategory("CRASH_DATA")) { + try PrivacyDeclaration.collected([collected("CRASH_DATA", ["ANALYTICS"]), collected("CRASH_DATA", ["APP_FUNCTIONALITY"])]).validate() + } + } + + @Test func `should refuse the same purpose listed twice for a data type`() { + #expect(throws: AppPrivacyError.duplicatePurpose(category: "CRASH_DATA", purpose: "ANALYTICS")) { + try PrivacyDeclaration.collected([collected("CRASH_DATA", ["ANALYTICS", "ANALYTICS"])]).validate() + } + } + + // MARK: - the file and REST body + + @Test func `should read a not-collected declaration from JSON`() throws { + #expect(try JSONDecoder().decode(PrivacyDeclaration.self, from: Data(#"{"notCollected":true}"#.utf8)) == .notCollected) + } + + @Test func `should read collected data from JSON in the shape get shows it`() throws { + let json = #"{"collectedData":[{"category":"CRASH_DATA","purposes":["ANALYTICS"],"isLinkedToYou":false,"isUsedToTrackYou":false}]}"# + #expect(try JSONDecoder().decode(PrivacyDeclaration.self, from: Data(json.utf8)) == .collected([collected("CRASH_DATA", ["ANALYTICS"])])) + } + + @Test func `should refuse JSON that says both not collected and what is collected`() { + let json = #"{"notCollected":true,"collectedData":[{"category":"CRASH_DATA","purposes":["ANALYTICS"],"isLinkedToYou":false,"isUsedToTrackYou":false}]}"# + #expect(throws: DecodingError.self) { try JSONDecoder().decode(PrivacyDeclaration.self, from: Data(json.utf8)) } + } +} diff --git a/Tests/ASCKitTests/Iris/Internal/IrisRequestTests.swift b/Tests/ASCKitTests/Iris/Internal/IrisRequestTests.swift index 88aa1675..de69bfbb 100644 --- a/Tests/ASCKitTests/Iris/Internal/IrisRequestTests.swift +++ b/Tests/ASCKitTests/Iris/Internal/IrisRequestTests.swift @@ -38,6 +38,15 @@ struct IrisRequestTests { #expect(request.httpMethod == "DELETE") } + @Test func `should send the body when patching iris`() { + let request = IrisRequest.patch(path: "appDataUsagesPublishState/1234567890", body: Data("{}".utf8), cookies: "c") + + #expect(request.url?.absoluteString == "https://appstoreconnect.apple.com/iris/v1/appDataUsagesPublishState/1234567890") + #expect(request.httpMethod == "PATCH") + #expect(request.httpBody == Data("{}".utf8)) + #expect(request.value(forHTTPHeaderField: "x-csrf-itc") == "[asc-ui]") + } + @Test func `should fetch a download with only the session cookies`() { let request = IrisRequest.download(absoluteURL: URL(string: "https://example.apple.com/a.png")!, cookies: "c") diff --git a/docs/README.md b/docs/README.md index 1ec8ffea..6749075f 100644 --- a/docs/README.md +++ b/docs/README.md @@ -13,6 +13,7 @@ New here? Start with the [README](../README.md). For every flag, see the [comman | [app-infos](features/app-infos/README.md) | Manage app-level metadata (name, subtitle, privacy policy, categories) that persists across versions. Use when renaming an app, adding a locale's name/subtitle, or setting App Store categories. | | [app-previews](features/app-previews/README.md) | Create App Store video preview sets per device type and upload preview videos. Use when adding or checking app preview videos on a version's product page. | | [app-pricing](features/app-pricing/README.md) | List an app's price points and set its price, including making it free. Use before a first submission, which Apple refuses until the app has a price schedule. | +| [app-privacy](features/app-privacy/README.md) | Show, declare and publish an app's App Privacy label (data collection, "nutrition label") via the iris web session. Use when App Review refuses a submission over unpublished data usages, or the app's data practices change. | | [app-shots](features/app-shots/README.md) | Compose App Store marketing screenshots from templates and gallery sets, preview as HTML or export PNG, and optionally enhance with Gemini. Use when turning raw app screenshots into styled store images. | | [app-shots-themes](features/app-shots-themes/README.md) | Browse plugin-provided visual themes and apply them to App Store screenshot templates, either per slide via AI or once-and-reuse via a cached ThemeDesign. Use when restyling app-shots with colors, backgrounds, and decorations. | | [app-wall](features/app-wall/README.md) | Add your App Store apps to the asc community app wall on asccli.app by opening a GitHub pull request. Use when showcasing apps published with asc. | diff --git a/docs/changelog/0.18.md b/docs/changelog/0.18.md index 266835ef..2404fc11 100644 --- a/docs/changelog/0.18.md +++ b/docs/changelog/0.18.md @@ -5,19 +5,19 @@ Archived unchanged from [CHANGELOG.md](../../CHANGELOG.md), which holds the curr ## [0.18.9] - 2026-11-08 ### Added -- `asc auth login`, `ASC_*` environment variables and `POST /api/v1/auth/accounts` accept individual API keys: leave out the issuer ID. → [docs](docs/features/asc-auth/README.md#use-an-individual-api-key) +- `asc auth login`, `ASC_*` environment variables and `POST /api/v1/auth/accounts` accept individual API keys: leave out the issuer ID. → [docs](../../docs/features/asc-auth/README.md#use-an-individual-api-key) --- ## [0.18.8] - 2026-11-05 ### Added -- `asc asset-placements list|create|reorder --custom-product-page-localization-id ` places screenshots, previews, header and search results assets on a custom product page, also over REST. → [docs](docs/features/asset-library/README.md) ([#41](https://github.com/tddworks/asc-cli/pull/41)) -- `asc age-rating get` and `update` handle `socialMedia`, `socialMediaAgeRestricted` and `developerAgeRatingInfoUrl`, also over REST. → [docs](docs/features/age-rating/README.md) -- `asc versions check-readiness` adds `ageRatingCheck`, which blocks `isReadyToSubmit` and names any unanswered age rating question. → [docs](docs/features/version-check-readiness/README.md) +- `asc asset-placements list|create|reorder --custom-product-page-localization-id ` places screenshots, previews, header and search results assets on a custom product page, also over REST. → [docs](../../docs/features/asset-library/README.md) ([#41](https://github.com/tddworks/asc-cli/pull/41)) +- `asc age-rating get` and `update` handle `socialMedia`, `socialMediaAgeRestricted` and `developerAgeRatingInfoUrl`, also over REST. → [docs](../../docs/features/age-rating/README.md) +- `asc versions check-readiness` adds `ageRatingCheck`, which blocks `isReadyToSubmit` and names any unanswered age rating question. → [docs](../../docs/features/version-check-readiness/README.md) ### Changed -- appstoreconnect-swift-sdk updated to 4.6 (App Store Connect API 4.6). The `INSTALLS` sales report is deprecated: Apple stopped generating new ones on November 4, 2026. → [docs](docs/features/reports/README.md) +- appstoreconnect-swift-sdk updated to 4.6 (App Store Connect API 4.6). The `INSTALLS` sales report is deprecated: Apple stopped generating new ones on November 4, 2026. → [docs](../../docs/features/reports/README.md) ### Fixed - `asc versions submit` now shows each reason Apple gives for refusing a version, instead of a generic 409. @@ -28,7 +28,7 @@ Archived unchanged from [CHANGELOG.md](../../CHANGELOG.md), which holds the curr ## [0.18.7] - 2026-11-01 ### Added -- `asc screenshots delete --screenshot-id ` and `asc screenshot-sets delete --set-id ` remove a screenshot, or a whole set with its screenshots. Listed screenshots and sets offer it as a `delete` next step; also over REST (`DELETE`). → [docs](docs/features/screenshots/README.md) ([#39](https://github.com/tddworks/asc-cli/pull/39)) +- `asc screenshots delete --screenshot-id ` and `asc screenshot-sets delete --set-id ` remove a screenshot, or a whole set with its screenshots. Listed screenshots and sets offer it as a `delete` next step; also over REST (`DELETE`). → [docs](../../docs/features/screenshots/README.md) ([#39](https://github.com/tddworks/asc-cli/pull/39)) --- @@ -36,21 +36,21 @@ Archived unchanged from [CHANGELOG.md](../../CHANGELOG.md), which holds the curr ### Changed - appstoreconnect-swift-sdk updated to 4.5.1 (App Store Connect API 4.5 and 4.5.1). -- `asc screenshot-sets`, `screenshots`, `app-preview-sets` and `app-previews` say in `--help` that Apple deprecated them; they work as before. → [docs](docs/features/asset-library/README.md) -- `asc perf-metrics`, `asc diagnostics` and `asc diagnostic-logs` are now also available over REST (`asc web-server`), with `_links` to the next call. → [docs](docs/features/performance/README.md) -- asc is now licensed under Apache 2.0 instead of MIT. It stays free and open source, and the license now also grants patent rights. → [LICENSE](LICENSE) +- `asc screenshot-sets`, `screenshots`, `app-preview-sets` and `app-previews` say in `--help` that Apple deprecated them; they work as before. → [docs](../../docs/features/asset-library/README.md) +- `asc perf-metrics`, `asc diagnostics` and `asc diagnostic-logs` are now also available over REST (`asc web-server`), with `_links` to the next call. → [docs](../../docs/features/performance/README.md) +- asc is now licensed under Apache 2.0 instead of MIT. It stays free and open source, and the license now also grants patent rights. → [LICENSE](../../LICENSE) ### Added -- `asc perf-overview get --app-id ` shows in one call what regressed in the latest version, each Xcode Organizer metric next to Apple's goal, and the top hang, launch and disk-write hotspots. Also over REST. → [docs](docs/features/performance/README.md) -- `asc asset-library`, `asset-placement-groups`, `asset-images`, `asset-videos` and `asset-placements` use the App Asset Library: upload screenshots and previews once, then place and order them on version and treatment localizations (CLI + REST). → [docs](docs/features/asset-library/README.md) -- `asc subscriptions list` shows whether a subscription supports multiple seats and its markets (App Store, Apple School, Apple Business). Change them with `asc subscriptions update --multi-seat-status` and `--market-setting`, or over REST. → [docs](docs/features/iap-subscriptions/README.md) -- `asc game-center score-moderations list|block|unblock`, `blocked-players list` and `players block|unblock` let you hide cheating leaderboard scores and block players. Game Center is now also reachable over REST. → [docs](docs/features/game-center/README.md) -- `asc screenshots import --to-library` uploads an export ZIP into the asset library once and places each screenshot in the group its size matches, per locale and in order; `--dry-run` previews it. Also over REST. → [docs](docs/features/screenshot-editor/README.md) -- `asc game-center achievements create` and `leaderboards create` are now also reachable over REST (POST to the Game Center detail's achievements or leaderboards). → [docs](docs/features/game-center/README.md) -- `asc age-rating` shows Korea's GRAC classification number, and `asc age-rating update --grac-rating-classification-number` sets it, also over REST. → [docs](docs/features/age-rating/README.md) +- `asc perf-overview get --app-id ` shows in one call what regressed in the latest version, each Xcode Organizer metric next to Apple's goal, and the top hang, launch and disk-write hotspots. Also over REST. → [docs](../../docs/features/performance/README.md) +- `asc asset-library`, `asset-placement-groups`, `asset-images`, `asset-videos` and `asset-placements` use the App Asset Library: upload screenshots and previews once, then place and order them on version and treatment localizations (CLI + REST). → [docs](../../docs/features/asset-library/README.md) +- `asc subscriptions list` shows whether a subscription supports multiple seats and its markets (App Store, Apple School, Apple Business). Change them with `asc subscriptions update --multi-seat-status` and `--market-setting`, or over REST. → [docs](../../docs/features/iap-subscriptions/README.md) +- `asc game-center score-moderations list|block|unblock`, `blocked-players list` and `players block|unblock` let you hide cheating leaderboard scores and block players. Game Center is now also reachable over REST. → [docs](../../docs/features/game-center/README.md) +- `asc screenshots import --to-library` uploads an export ZIP into the asset library once and places each screenshot in the group its size matches, per locale and in order; `--dry-run` previews it. Also over REST. → [docs](../../docs/features/screenshot-editor/README.md) +- `asc game-center achievements create` and `leaderboards create` are now also reachable over REST (POST to the Game Center detail's achievements or leaderboards). → [docs](../../docs/features/game-center/README.md) +- `asc age-rating` shows Korea's GRAC classification number, and `asc age-rating update --grac-rating-classification-number` sets it, also over REST. → [docs](../../docs/features/age-rating/README.md) ### Fixed -- `asc age-rating` now shows and sets the Korea overrides `ALL` and `TWELVE_PLUS`. Before, an app rated with either one showed no Korea override at all. → [docs](docs/features/age-rating/README.md) +- `asc age-rating` now shows and sets the Korea overrides `ALL` and `TWELVE_PLUS`. Before, an app rated with either one showed no Korea override at all. → [docs](../../docs/features/age-rating/README.md) - `asc screenshots upload`, `asc app-previews upload` and `asc builds upload` now stop with an error when App Store Connect's storage rejects part of the file, or when App Store Connect sends an incomplete upload instruction. Before, they committed the upload anyway and left a broken asset behind. --- @@ -58,16 +58,16 @@ Archived unchanged from [CHANGELOG.md](../../CHANGELOG.md), which holds the curr ## [0.18.5] - 2026-10-03 ### Changed -- Docs reorganised: a short README, one folder per feature under `docs/features/`, and a full command reference generated from the binary (`docs/commands.md`). Releases before 0.18 moved to `docs/changelog/`. → [docs](docs/README.md) ([#29](https://github.com/tddworks/asc-cli/pull/29)) +- Docs reorganised: a short README, one folder per feature under `docs/features/`, and a full command reference generated from the binary (`docs/commands.md`). Releases before 0.18 moved to `docs/changelog/`. → [docs](../../docs/README.md) ([#29](https://github.com/tddworks/asc-cli/pull/29)) - Refused review submissions now list Apple's specific reasons (missing screenshots, content rights, App Privacy, pricing) instead of only "please check associated errors". ([#27](https://github.com/tddworks/asc-cli/pull/27)) - Dependencies updated to their latest releases, including appstoreconnect-swift-sdk 4.4.3 (was 4.2.0) and Hummingbird 2.27.0; `Package.swift` minimums raised to match. ([#27](https://github.com/tddworks/asc-cli/pull/27)) ### Added -- `asc versions submit --with-products` submits every `READY_TO_SUBMIT` in-app purchase and subscription together with the app version, as first-time products require, with just your API key. `--dry-run` previews. → [docs](docs/features/submit-with-products/README.md) ([#27](https://github.com/tddworks/asc-cli/pull/27)) -- `asc review-submissions create`, `items add`, `items remove` and `submit` build a review submission step by step. → [docs](docs/features/review-submissions/README.md) ([#27](https://github.com/tddworks/asc-cli/pull/27)) +- `asc versions submit --with-products` submits every `READY_TO_SUBMIT` in-app purchase and subscription together with the app version, as first-time products require, with just your API key. `--dry-run` previews. → [docs](../../docs/features/submit-with-products/README.md) ([#27](https://github.com/tddworks/asc-cli/pull/27)) +- `asc review-submissions create`, `items add`, `items remove` and `submit` build a review submission step by step. → [docs](../../docs/features/review-submissions/README.md) ([#27](https://github.com/tddworks/asc-cli/pull/27)) - `asc iap versions list`, `asc subscriptions versions list` and `asc subscription-groups versions list` show each product's review versions and state. REST: `GET /api/v1/{iap,subscriptions,subscription-groups}/:id/versions`. ([#27](https://github.com/tddworks/asc-cli/pull/27)) -- `asc apps price-points list` and `asc apps prices set` set the app's price or make it free, fixing the "not eligible for submission until pricing has been set" refusal. → [docs](docs/features/app-pricing/README.md) ([#28](https://github.com/tddworks/asc-cli/pull/28)) -- `asc app-availability create` sets the territories an app is sold in. REST: `POST /api/v1/apps/:appId/availability`. → [docs](docs/features/iap-subscription-availability/README.md) ([#28](https://github.com/tddworks/asc-cli/pull/28)) +- `asc apps price-points list` and `asc apps prices set` set the app's price or make it free, fixing the "not eligible for submission until pricing has been set" refusal. → [docs](../../docs/features/app-pricing/README.md) ([#28](https://github.com/tddworks/asc-cli/pull/28)) +- `asc app-availability create` sets the territories an app is sold in. REST: `POST /api/v1/apps/:appId/availability`. → [docs](../../docs/features/iap-subscription-availability/README.md) ([#28](https://github.com/tddworks/asc-cli/pull/28)) - `asc perf-metrics list --metric-type STORAGE` reads Apple's new storage metrics. ([#27](https://github.com/tddworks/asc-cli/pull/27)) ### Fixed diff --git a/docs/commands.md b/docs/commands.md index 69abfadb..5d7a8935 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -4343,6 +4343,44 @@ asc iris app-compliance declare --app-id --requirement-id +``` + +| Flag | Required | Default | Description | +|---|---|---|---| +| `--app-id` | yes | | App ID | + +### asc iris app-privacy declare + +Replace an app's privacy label (it stays a draft until `publish`) + +``` +asc iris app-privacy declare --app-id [--not-collected] [--file ] +``` + +| Flag | Required | Default | Description | +|---|---|---|---| +| `--app-id` | yes | | App ID | +| `--not-collected` | | | The app collects no data | +| `--file` | | | A JSON file of the data the app collects | + +### asc iris app-privacy publish + +Publish an app's declared privacy label so it no longer blocks review + +``` +asc iris app-privacy publish --app-id +``` + +| Flag | Required | Default | Description | +|---|---|---|---| +| `--app-id` | yes | | App ID | + ### asc iris auth login Sign in with Apple ID + password via SRP. Prompts for the 2FA code separately. diff --git a/docs/features/app-privacy/README.md b/docs/features/app-privacy/README.md new file mode 100644 index 00000000..73247845 --- /dev/null +++ b/docs/features/app-privacy/README.md @@ -0,0 +1,77 @@ +--- +description: Show, declare and publish an app's App Privacy label (data collection, "nutrition label") via the iris web session. Use when App Review refuses a submission over unpublished data usages, or the app's data practices change. +--- + +# App Privacy + +Read, declare and publish an app's **App Privacy** label: "Data Not Collected", or each data type the app collects with its purposes, whether it's linked to the user and whether it tracks them. App Review refuses a submission until the label is published ("You must have published answers to your app's data usages"). Apple has no public API for this page, so it goes through the [iris](../iris/README.md) session. Every flag: [command reference](../../commands.md#asc-iris). Design and captured wire format: [design.md](design.md). + +## Quick start + +```bash +asc iris app-privacy get --app-id 1234567890 --pretty +asc iris app-privacy declare --app-id 1234567890 --not-collected +asc iris app-privacy publish --app-id 1234567890 +``` + +## Workflows + +### See whether the label blocks review + +```bash +asc iris app-privacy get --app-id 1234567890 --output table +``` + +| `dataCollection` | Meaning | +|---|---| +| `NOT_ANSWERED` | Nothing declared yet | +| `NOT_COLLECTED` | "Data Not Collected" — the whole label | +| `COLLECTED` | `collectedData` lists each data type | + +`blocksSubmission` is `true` until the label is both answered and published. `affordances` (or `_links` over REST) say what to run next: `declareNotCollected` while nothing is declared, `publish` while a declared label isn't live. + +### Declare what the app collects + +Write the data types in the same shape `get` shows them: + +```json +{ + "collectedData": [ + { "category": "EMAIL_ADDRESS", "purposes": ["APP_FUNCTIONALITY"], "isLinkedToYou": true, "isUsedToTrackYou": false }, + { "category": "CRASH_DATA", "purposes": ["ANALYTICS"], "isLinkedToYou": false, "isUsedToTrackYou": false } + ] +} +``` + +```bash +asc iris app-privacy declare --app-id 1234567890 --file privacy.json +asc iris app-privacy publish --app-id 1234567890 +``` + +`declare` replaces the whole label: data types not in the file are removed, and rows already right are left alone. The file may also be `{"notCollected": true}`. + +- **Categories:** `NAME`, `EMAIL_ADDRESS`, `PHONE_NUMBER`, `PHYSICAL_ADDRESS`, `OTHER_CONTACT_INFO`, `HEALTH`, `FITNESS`, `PAYMENT_INFORMATION`, `CREDIT_AND_FRAUD`, `OTHER_FINANCIAL_INFO`, `PRECISE_LOCATION`, `COARSE_LOCATION`, `SENSITIVE_INFO`, `CONTACTS`, `EMAILS_OR_TEXT_MESSAGES`, `PHOTOS_OR_VIDEOS`, `AUDIO`, `GAMEPLAY_CONTENT`, `CUSTOMER_SUPPORT`, `OTHER_USER_CONTENT`, `BROWSING_HISTORY`, `SEARCH_HISTORY`, `USER_ID`, `DEVICE_ID`, `PURCHASE_HISTORY`, `PRODUCT_INTERACTION`, `ADVERTISING_DATA`, `OTHER_USAGE_DATA`, `CRASH_DATA`, `PERFORMANCE_DATA`, `OTHER_DIAGNOSTIC_DATA`, `OTHER_DATA_TYPES` +- **Purposes:** `APP_FUNCTIONALITY`, `ANALYTICS`, `PRODUCT_PERSONALIZATION`, `DEVELOPERS_ADVERTISING`, `THIRD_PARTY_ADVERTISING`, `OTHER_PURPOSES` + +## REST + +| CLI | REST | +|---|---| +| `get --app-id A` | `GET /api/v1/iris/apps/A/app-privacy` | +| `declare --app-id A --not-collected` | `POST /api/v1/iris/apps/A/app-privacy/declare` with `{"notCollected": true}` | +| `declare --app-id A --file f.json` | `POST /api/v1/iris/apps/A/app-privacy/declare` with the file's JSON | +| `publish --app-id A` | `POST /api/v1/iris/apps/A/app-privacy/publish` | + +An unknown category or purpose answers `422`; publishing a label with nothing declared answers `409`. + +## Gotchas + +- **Declaring doesn't publish.** Run `publish` afterwards; until then `blocksSubmission` stays `true`. +- **Nothing unknown is sent.** A category or purpose asc doesn't know is refused before anything reaches Apple, so a typo can't leave half a label. +- **"Linked to you" is per data type.** A data type is linked if any of its purposes is. +- It's a private API: Apple can change it without notice. + +## See also + +- [Iris](../iris/README.md) — signing in +- [App Compliance](../app-compliance/README.md) — the other private-API declarations diff --git a/docs/features/app-privacy/design.md b/docs/features/app-privacy/design.md new file mode 100644 index 00000000..b6028ff6 --- /dev/null +++ b/docs/features/app-privacy/design.md @@ -0,0 +1,113 @@ +# App Privacy — "Data Not Collected", or what the app collects and why + +**Status: BUILT** (get, declare, publish; CLI and REST). User guide: [README.md](README.md). Apple has no public API for App Privacy: appstoreconnect-swift-sdk has no `appDataUsages` endpoints, yet App Review refuses a submission until the answers are published ("You must have published answers to your app's data usages"). The web page reads and writes them through iris (`/iris/v1`) with the Apple ID session cookies. + +This document owns **the privacy label an app declares and publishes**. Its neighbours own the rest: + +| For | Read | +|---|---| +| Getting an Apple ID session | [Iris](../iris/README.md) | +| Regional declarations (China AIGC, Security Assessment) | [App Compliance](../app-compliance/design.md) | +| The privacy policy URL | [App info localizations](../app-info-localizations/README.md), a public-API resource | + +--- + +## The one sentence + +**An app's privacy label is either "Data Not Collected" or the data types it collects — each with the purposes it is used for, whether it is linked to the user and whether it tracks them — and nothing counts until it is published.** + +``` + App 1234567890 published + ├─ OTHER_USAGE_DATA ANALYTICS, APP_FUNCTIONALITY not linked · no tracking + └─ EMAIL_ADDRESS APP_FUNCTIONALITY linked · no tracking +``` + +## Ubiquitous language + +| Word | Means | On the wire | +|---|---|---| +| **App privacy** | the label: one per app, the aggregate | `apps/{id}/dataUsages` + `apps/{id}/dataUsagePublishState` | +| **Data collection** | not answered / not collected / collected | no rows / the one `DATA_NOT_COLLECTED` row / rows with a category | +| **Collected data** | one data type and how it's used | every row for one `category` | +| **Data usage** | one row Apple stores; asc's internal unit of change | `appDataUsages` (category × purpose × protection) | +| **Published** | the label is live and no longer blocks review | `published: true` | + +## Laws + +1. **Collected data is the developer's unit; a row is Apple's.** asc shows and takes collected data, and turns it into rows only in `DataUsageEntry` (one row per purpose, plus a purpose-less `DATA_USED_TO_TRACK_YOU` row when it tracks). Owner: `PrivacyDeclaration.entries`. +2. **"Data Not Collected" is the whole label.** It can't be combined with a data type — the declaration type can't express both. Owner: `PrivacyDeclaration`. +3. **Declaring replaces the label.** asc deletes the rows that aren't wanted, then creates the missing ones (deletions first: a not-collected row can't sit beside a category). Rows already right are left alone. Owner: `DataUsagePlan`. +4. **Declaring does not publish.** The answer stays a draft until `publish`; the label then offers `publish`. Owner: `AppPrivacy.structuredAffordances`. +5. **Nothing is published until something is declared.** Owner: `AppPrivacy.publish(session:repo:)`. +6. **Only values asc knows are sent.** A category or purpose it doesn't know is refused before anything reaches Apple; one Apple returns is kept as Apple sent it. Owner: `PrivacyDeclaration.validate()`, `DataCategory`/`DataPurpose`. +7. **A label blocks review until it is answered and published.** Owner: `AppPrivacy.blocksSubmission`. + +## The captured wire format + +Captured live on 2026-11-24, read-only (ids replaced). Every call is on `https://appstoreconnect.apple.com/iris/v1/`, JSON:API, gzip-compressed (`URLSession` unpacks it). + +### The rows + +``` +GET apps/{appId}/dataUsages?include=category,grouping,purpose,dataProtection&limit=500 +``` + +Nothing declared — Apple answers an empty list (not `{}`): + +```json +{ "data": [], "included": [], "meta": { "paging": { "total": 0, "limit": 500 } } } +``` + +Data Not Collected — one row, every other relationship `null`: + +```json +{ "data": [ { "type": "appDataUsages", "id": "usage-1", "relationships": { + "category": { "data": null }, "grouping": { "data": null }, "purpose": { "data": null }, + "dataProtection": { "data": { "type": "appDataUsageDataProtections", "id": "DATA_NOT_COLLECTED" } } } } ] } +``` + +Collected — one row per purpose (captured: one category, three purposes, not linked): + +```json +{ "data": [ + { "type": "appDataUsages", "id": "usage-1", "relationships": { + "category": { "data": { "type": "appDataUsageCategories", "id": "OTHER_USAGE_DATA" } }, + "grouping": { "data": { "type": "appDataUsageGroupings", "id": "USAGE_DATA" } }, + "purpose": { "data": { "type": "appDataUsagePurposes", "id": "OTHER_PURPOSES" } }, + "dataProtection": { "data": { "type": "appDataUsageDataProtections", "id": "DATA_NOT_LINKED_TO_YOU" } } } }, + … ANALYTICS, APP_FUNCTIONALITY … +] } +``` + +- The ids are in the relationships; `included` adds only `deleted: false`, so asc doesn't read it. +- A tracking row (`DATA_USED_TO_TRACK_YOU`, no purpose) has not been captured: none of the account's apps track. + +### Published or not + +``` +GET apps/{appId}/dataUsagePublishState +``` + +```json +{ "data": { "type": "appDataUsagesPublishState", "id": "1234567890", + "attributes": { "published": true, "lastPublished": "2026-11-24T00:14:02-08:00", "lastPublishedBy": "…" } } } +``` + +Never published: `"published": false, "lastPublished": null`. + +### Changing it + +| Call | Body | Captured | +|---|---|---| +| `POST appDataUsages` | `{"data":{"type":"appDataUsages","relationships":{"app":…,"dataProtection":{"data":{"type":"appDataUsageDataProtections","id":"DATA_NOT_COLLECTED"}}}}}` | yes, 201 (body not read) | +| `POST appDataUsages`, collected | the same, plus `category` and `purpose` relationships | **no** — modelled on the above | +| `DELETE appDataUsages/{id}` | — | **no** — the row's own `links.self` | +| `PATCH appDataUsagesPublishState/{appId}` | `{"data":{"type":"appDataUsagesPublishState","id":"{appId}","attributes":{"published":true}}}` | yes, 200 | + +asc reads nothing back from a change: after declaring or publishing it reads the label again. + +## Open questions + +1. Is "linked to you" asked once per data type, or per purpose? asc assumes per data type (a row set mixing both shows as linked). +2. Does changing a published label unpublish it? asc doesn't assume: it reads `published` back after each declare. +3. The collected `POST` and the `DELETE` are uncaptured; confirm on a live app. diff --git a/scripts/changelog-rollover.py b/scripts/changelog-rollover.py index d3b73a4b..5a1328d1 100755 --- a/scripts/changelog-rollover.py +++ b/scripts/changelog-rollover.py @@ -1,9 +1,10 @@ #!/usr/bin/env python3 """Keep CHANGELOG.md to [Unreleased] + the current minor version. -Every released section whose minor is older than the newest release is moved, -unchanged, into docs/changelog/.md, together with its reference -link. CHANGELOG.md ends with an "Older releases" line linking every archive. +Every released section whose minor is older than the newest release is moved +into docs/changelog/.md, together with its reference link. Its text +is unchanged except root-relative links (`docs/…`), which gain `../../` so they +still resolve from docs/changelog/. CHANGELOG.md ends with an "Older releases" line linking every archive. Safe to run repeatedly; a no-op when there is nothing to move. Usage: scripts/changelog-rollover.py [CHANGELOG.md] @@ -19,6 +20,8 @@ SECTION = re.compile(r"^## \[([^\]]+)\]") LINK = re.compile(r"^\[([^\]]+)\]: \S+") OLDER = "## Older releases" +# A link written from the repo root (`docs/…`, `LICENSE`), as CHANGELOG.md writes them. +ROOT_LINK = re.compile(r"\]\((?!https?:|mailto:|#|\.\./|/)([^)\s]+)\)") def minor(version): @@ -50,6 +53,11 @@ def split(text): return header, sections, links +def from_archive(lines): + """A section's lines as read from docs/changelog/: root-relative links gain ../../.""" + return [ROOT_LINK.sub(r"](../../\1)", line) for line in lines] + + def strip(lines): while lines and lines[-1].strip() in ("", "---"): lines = lines[:-1] @@ -92,7 +100,7 @@ def main(): "Archived unchanged from [CHANGELOG.md](../../CHANGELOG.md), which holds the current releases.", "", ] - for _, lines in secs + old_secs: + for _, lines in [(v, from_archive(l)) for v, l in secs] + old_secs: body += strip(lines) + ["", "---", ""] body = strip(body) + [""] all_links = moved_links.get(m, []) + old_links diff --git a/scripts/test-changelog-release.sh b/scripts/test-changelog-release.sh index 853837cd..f986fae1 100755 --- a/scripts/test-changelog-release.sh +++ b/scripts/test-changelog-release.sh @@ -64,6 +64,21 @@ PY [ -f "docs/changelog/$MAJOR.$MINOR.md" ] && fail "patch release archived the current minor" fi + # Archived links still resolve from docs/changelog/ (checked against the real repo) + local broken; broken=$(python3 - "$ROOT" <<'PY' +import re, sys +from pathlib import Path +root = Path(sys.argv[1]) +for path in sorted(Path("docs/changelog").glob("*.md")): + for target in re.findall(r"\]\(([^)\s]+)\)", path.read_text()): + if re.match(r"^(https?:|mailto:|#)", target): + continue + if not (root / "docs" / "changelog" / target.split("#")[0]).exists(): + print(f"{path}: {target}") +PY +) + [ -z "$broken" ] || fail "archived links don't resolve from docs/changelog/: $(head -3 <<< "$broken" | tr '\n' ' ')" + # Nothing lost: every release heading still exists, plus the new one local headings_after; headings_after=$(cat CHANGELOG.md docs/changelog/*.md | grep -c '^## \[') [ "$headings_after" = $((headings_before + 1)) ] || fail "release headings $headings_before → $headings_after (expected +1)"