From dd0d032f6f855c1e7bc64483b08481e9a787278b Mon Sep 17 00:00:00 2001 From: slamhan Date: Thu, 19 Nov 2026 17:20:19 +0800 Subject: [PATCH 01/12] docs(app-compliance): design doc for China mainland compliance declarations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit App Compliance (Security Assessment, AI Generated or Synthetic Content) has no public API or SDK support; the web UI uses the private /ppm/compliancerequirements endpoint with iris session cookies. Design only — build is blocked on capturing the requirements and save calls. Co-Authored-By: Claude Opus 5.5 --- docs/features/app-compliance/design.md | 180 +++++++++++++++++++++++++ 1 file changed, 180 insertions(+) create mode 100644 docs/features/app-compliance/design.md diff --git a/docs/features/app-compliance/design.md b/docs/features/app-compliance/design.md new file mode 100644 index 00000000..614005eb --- /dev/null +++ b/docs/features/app-compliance/design.md @@ -0,0 +1,180 @@ +# App Compliance — "Does your app offer AIGC services in China mainland?" + +**Status: DESIGN. Nothing is built.** Apple has no public API for App Compliance: it is absent from appstoreconnect-swift-sdk 4.6.1 and from Apple's own OpenAPI spec 4.6 (checked 2026-11-17). The web UI reads it from a private endpoint outside `/iris/v1`, which uses the same Apple ID session cookies. One read call has been captured (below). The requirements list, the save call and the document upload have **not** been captured, and slices that depend on them are marked *blocked*. + +This document owns **the declarations an app keeps current so it can stay on the store in a regulated region**. Its neighbours own the rest: + +| For | Read | +|---|---| +| Getting an Apple ID session (cookies, `teamId`) | [Iris](../iris/README.md), [Iris SRP login](../iris/iris-srp-login.md) | +| Build export compliance (`usesNonExemptEncryption`) | [`asc builds`](../../commands.md#asc-builds), a different public-API resource | +| Age rating declaration | [Age rating](../age-rating/README.md), a different public-API resource | +| Whether a version is ready to submit | [Check readiness](../version-check-readiness/README.md). It does not read compliance yet; see Open question 6 | + +--- + +## What the product already says + +``` + "App Compliance" ← the page; one per app + "Regulations and permits relevant to your app in the App Store" + COMPLIANCE NAME "Security Assessment" ← a requirement has a human name + "AI Generated or Synthetic Content" + COUNTRIES OR REGIONS "China mainland" ← a requirement applies to a region + LAST UPDATED "Nov 17, 2026" / "-" ← "-" = never answered + STATUS "Active" / "Missing Info" ← help page adds "Pending Verification", "Verification Failed" + "Edit" / "Add Info" ← the next action depends on status + "Does your app offer AIGC services in China mainland?" Yes / No + Help: "complete the AI-generated/synthetic content and Security Assessment declarations" + Help: Yes → filing number + filing name (AIGC); proof screenshot + assessment report (Security Assessment) +``` + +So the domain is a **checklist of requirements**, and each requirement takes a **yes/no declaration**. Answering Yes also requires evidence, and the kind of evidence depends on the requirement. Answering No requires none. + +The same page also holds the Digital Services Act trader status, the ICP filing number, the Vietnam game license and the regulated medical device declaration. They are **out of scope** for this lap. They are separate cards with their own shapes and haven't been captured. + +## The one sentence + +**An app's compliance is the list of regional requirements that apply to it, each answered by a declaration whose status says whether the app may stay on sale in that region.** + +``` + App 1234567890 + ├─ Security Assessment China mainland declaration: No → Active + └─ AI Generated or Synthetic China mainland (none) → Missing Info → declare +``` + +## The captured wire format + +``` +GET https://appstoreconnect.apple.com/ppm/compliancerequirements/v1/accounts/{accountId}/entities/{appId}/forms +``` + +```json +{ "data": [ { + "id": "form-1", + "requirementId": "req-1", + "formName": "SECURITYASF395E", + "fields": [ { "id": "field-1", "sValue": "NO", "verificationStatus": "FIELD_VERIFY_NOT_NECESSARY" } ], + "status": "COLLECTED_VERIFY_NOT_NECESSARY", + "createdAt": "1794879753633", "updatedAt": "1794879753633", + "createdBy": "user-1", "updatedBy": "user-1" +} ] } +``` + +- `accountId` is the team's **`publicProviderId`** from `olympus/v1/session`. It already arrives as `IrisAuthSession.teamId`, and the captured URL matched a saved session's `teamId`. It is **not** the numeric `providerID`. +- `entities/{appId}` is the numeric App Store app ID. +- Timestamps are epoch milliseconds, encoded as strings. +- The second captured form was `AIGENERATEFD1DE`, with the same shape. +- **Only answered requirements come back.** A "Missing Info" row has no form, so the list of what applies has to come from another call (Open question 1). + +--- + +## 1 · Ubiquitous language + +| Term | Meaning | Not to be confused with | +|---|---|---| +| **App Compliance** | The page: every compliance requirement for one app | Export compliance on a build | +| **Compliance requirement** | One regulation that applies to the app in a region ("Security Assessment, China mainland"). Apple's API calls it a *requirement* | The help-page article about it | +| **Kind** | Which regulation the requirement is. This lap covers Security Assessment and AI Generated or Synthetic Content | Apple's `formName` code, which is only how the wire spells it | +| **Declaration** | The developer's answer to one requirement. Apple's API calls it a *form* | `AgeRatingDeclaration`, `AppEncryptionDeclaration`, `AccessibilityDeclaration`: public-API resources with no relation to this one | +| **Answer** | Yes (the app offers the regulated feature in the region) or No (it doesn't, or the feature is disabled or geoblocked there) | | +| **Evidence** | What a Yes must carry: filing number and filing name (AIGC), or proof screenshot and assessment report (Security Assessment) | | +| **Status** | Missing Info · Pending Verification · Verification Failed · Active | The raw wire value (`COLLECTED_VERIFY_NOT_NECESSARY`) | +| **Account** | The team, identified by `publicProviderId` (a UUID) | `providerID`, the numeric ID | + +**"Declaration", not "form".** *Form* is Apple's backstage word. Apple's help page and the people filling it in say *declaration*. The `formName` code stays in the infrastructure mapper. + +## 2 · The aggregate — from the root down + +``` +ComplianceRequirement one row on the App Compliance page (aggregate root) + ├─ id : String Apple's requirementId; stable before and after answering + ├─ appId : String parent; injected by the adapter (the API omits it) + ├─ kind : ComplianceKind which regulation; decides what a Yes must carry + ├─ region : String? "China mainland"; from the requirements call (blocked) + ├─ updatedAt : Date? nil = never answered ("-") + ├─ declaration : ComplianceDeclaration? nil ⇒ MISSING INFO, always + │ ├─ id : String Apple's form id; what an update targets (assumed, Open question 2) + │ └─ answer : ComplianceAnswer .notOffered | .offered(Evidence) — EVIDENCE ONLY ON YES + └─ status : ComplianceStatus derived: no declaration → missingInfo; else mapped from wire +``` + +There is no `AppCompliance` wrapper type. It would just be the plural of `ComplianceRequirement`, with no rule of its own yet. It earns a type if Open question 6 ("may this app ship in region X?") gets answered, because that rule belongs to the collection. + +## 3 · The kinds and the rich types + +| Kind | Wire `formName` | A Yes must carry | Its own rules | +|---|---|---|---| +| **securityAssessment** | `SECURITYASF395E` | proof-of-pass screenshot + assessment report (sealed) | Required when the app distributes AIGC or offers encrypted instant messaging | +| **aiGeneratedContent** | `AIGENERATEFD1DE` | LLM/algorithm filing number + filing name; optional third-party authorization | | +| **unrecognized(formName)** | anything else | unknown | Listed as-is, never offered `declare` | + +### `ComplianceAnswer` — the developer's Yes or No + +> **Pointable as:** the radio button the developer ticked in the Yes/No dialog. + +| | | +|---|---| +| **Owns — a Yes carries its kind's evidence; a No carries nothing** | `.notOffered` has no payload. `.offered(SecurityAssessmentEvidence)` and `.offered(AIGCFilingEvidence)` are different shapes, so a Yes without a filing number can't be built | +| **It answers** | `wireValue` → `"YES"` / `"NO"` | +| **Never** | A `filingNumber` field that "is ignored when the answer is No" | + +### `ComplianceStatus` — what the STATUS column says + +> **Pointable as:** the icon and label in the STATUS column. + +| | | +|---|---| +| **Owns — an unknown wire status still lists** | `.missingInfo · .pendingVerification · .verificationFailed · .active · .unrecognized(raw)` | +| **It answers** | `isActive` (the app may stay on sale in the region) · `needsAction` (Missing Info or Verification Failed) · `isPendingVerification` | +| **Never** | Guess a mapping. Only `COLLECTED_VERIFY_NOT_NECESSARY → active` is observed; every other wire value is `.unrecognized` until captured (Open question 3) | + +## 4 · The tells + +``` +asc iris app-compliance list --app-id 1234567890 + → [ComplianceRequirement]: each row knows its own status and next command + +asc iris app-compliance declare --app-id 1234567890 --requirement-id req-1 --answer no + → requirement.declare(.notOffered, repo:) the requirement checks it may be declared + (recognized kind, not pending) + +requirement.structuredAffordances + → "declare" only when kind is recognized and !status.isPendingVerification +``` + +The adapter resolves the account itself: it uses `IrisAuthSession.teamId` when the session came from `asc iris auth login`, and otherwise calls `olympus/v1/session` (browser cookies and `ASC_IRIS_COOKIES` don't carry a team ID). The command never asks for `--account-id`, because a user can't see that value anywhere. + +`IrisClient` hard-codes the base `…/iris/v1`. It gets a second entry point for `…/ppm/compliancerequirements/v1` with the same cookies and headers. There is no new auth path. + +## 5 · Invariants (each law, one owner) + +| # | Law | Owner | +|---|---|---| +| 1 | A requirement nobody has answered shows Missing Info | `ComplianceRequirement` (derives `status`) | +| 2 | A requirement always belongs to the app it was listed under | adapter mapper (injects `appId`) | +| 3 | A Yes always carries its kind's evidence; a No carries none | `ComplianceAnswer` (shape) | +| 4 | An unknown form or status is still listed, never dropped and never a crash | `ComplianceKind` / `ComplianceStatus` (`.unrecognized`) | +| 5 | You're offered `declare` only for a recognized kind that isn't awaiting verification | `ComplianceRequirement.structuredAffordances` | +| 6 | The account in the URL is the team's `publicProviderId`, never the numeric `providerID` | adapter (account resolution) | + +## 6 · Build sequence (test-first, each slice green) + +0. **Capture** *(blocking 2–5)*: in the browser network tab, capture the requirements/applicability call (names, regions, IDs for unanswered rows), the Save request for No and for Yes, the status values for Pending/Failed, and the document upload calls. +1. **Domain**: `ComplianceKind`, `ComplianceStatus`, `ComplianceAnswer` (No only), `ComplianceRequirement` + affordances, `@Mockable IrisComplianceRepository`. *Pinned: laws 1, 3 (No), 4, 5.* +2. **Infrastructure read**: `IrisClient` ppm base; account resolution; `listRequirements(session:appId:)` decoding the captured fixture, with placeholder IDs. *Pinned: laws 2, 6; epoch-ms dates; unknown `formName` survives.* +3. **`asc iris app-compliance list` + REST** `GET /api/v1/iris/apps/:appId/compliance-requirements`. *Pinned: full JSON snapshot; `_links.declare` only on eligible rows.* +4. **`declare --answer no` + REST** `POST /api/v1/iris/compliance-requirements/:requirementId/declare` *(blocked on the Save capture)*. +5. **Yes with evidence** *(blocked on the upload capture)*: per-kind evidence types and file flags. +6. **Docs**: `README.md` for users, one CHANGELOG line, `make docs`, and a link from the iris README's "Other iris commands". + +## 7 · Open questions + +1. **Where does the list of applicable requirements come from?** `/forms` returns only answered ones, so a Missing Info row is invisible to it. A sibling call (likely `…/entities/{appId}/requirements`) is expected to provide names, regions and IDs. *Blocking for slice 2.* Hard-coding the two China requirements is the fallback, but that breaks as soon as Apple adds a region. +2. **What does Save target: the requirement or the form?** A first answer has no form yet, so it probably POSTs against `requirementId` and later edits PATCH the form `id`. Decide from the capture. +3. **What are the wire values for Pending Verification, Verification Failed and a Yes awaiting review?** Until captured, they map to `.unrecognized(raw)` and are shown raw. +4. **Are `formName` codes stable?** `SECURITYASF395E` / `AIGENERATEFD1DE` look like a prefix plus a hash. Recommendation: match the exact code and fall through to `.unrecognized`. If the requirements call gives a stable key, use that instead. +5. **Who can edit?** The help page requires Account Holder or Admin for the China identity verification. If declarations need it too, a 403 should say so rather than surfacing as a bare HTTP error. +6. **Should check-readiness warn?** Apple removes non-compliant apps from the China mainland store (deadline 2027-01-31), and a failed verification removes the app there. A readiness check "China mainland compliance not Active" would be the first rule that needs an `AppCompliance` collection type. Deferred until the list ships. +7. ~~**Is there a public API or SDK support?**~~ **ANSWERED: no.** Not in appstoreconnect-swift-sdk 4.6.0/4.6.1 or Apple's OpenAPI 4.6 (checked 2026-11-17). Private `/ppm/` endpoint only. +8. ~~**Where does `accountId` come from?**~~ **ANSWERED: olympus `publicProviderId`.** It matched the `teamId` saved by `asc iris auth login`. From 27d18887a47df42024055bf31887a9fbdde9fceb Mon Sep 17 00:00:00 2001 From: slamhan Date: Thu, 19 Nov 2026 18:12:00 +0800 Subject: [PATCH 02/12] docs(app-compliance): capture the full wire contract and settle the open questions The requirements list (?entity_id=), the form metadata POST and its answer tree, inline base64 files, the first-answer POST and the PUT that changes an Active declaration are all captured now, with every id replaced by a placeholder. Pending declarations are read-only; declare checks Apple's editable flag before writing. Readiness warns only when the app is sold in the requirement's region. Co-Authored-By: Claude Opus 5.5 --- docs/features/app-compliance/design.md | 428 +++++++++++++++++++++++-- 1 file changed, 394 insertions(+), 34 deletions(-) diff --git a/docs/features/app-compliance/design.md b/docs/features/app-compliance/design.md index 614005eb..7c217abc 100644 --- a/docs/features/app-compliance/design.md +++ b/docs/features/app-compliance/design.md @@ -1,6 +1,6 @@ # App Compliance — "Does your app offer AIGC services in China mainland?" -**Status: DESIGN. Nothing is built.** Apple has no public API for App Compliance: it is absent from appstoreconnect-swift-sdk 4.6.1 and from Apple's own OpenAPI spec 4.6 (checked 2026-11-17). The web UI reads it from a private endpoint outside `/iris/v1`, which uses the same Apple ID session cookies. One read call has been captured (below). The requirements list, the save call and the document upload have **not** been captured, and slices that depend on them are marked *blocked*. +**Status: DESIGN. Nothing is built.** Apple has no public API for App Compliance: it is absent from appstoreconnect-swift-sdk 4.6.1 and from Apple's own OpenAPI spec 4.6 (checked 2026-11-17). The web UI reads it from a private service outside `/iris/v1`, `ppm/compliancerequirements/v1`, which uses the same Apple ID session cookies. These calls have been captured (below): the requirements list (before and after a Yes was saved), the declarations, the form metadata for both kinds, with its request, and with Yes picked for each, a draft carrying files, the save of a first No (on two apps) and the save of an AIGC Yes with a file. and the save of a change to an Active declaration. Every read and write the page makes is captured. This document owns **the declarations an app keeps current so it can stay on the store in a regulated region**. Its neighbours own the rest: @@ -23,15 +23,42 @@ This document owns **the declarations an app keeps current so it can stay on the COUNTRIES OR REGIONS "China mainland" ← a requirement applies to a region LAST UPDATED "Nov 17, 2026" / "-" ← "-" = never answered STATUS "Active" / "Missing Info" ← help page adds "Pending Verification", "Verification Failed" - "Edit" / "Add Info" ← the next action depends on status + "Add Info" / "Edit" / "View" ← the next action depends on status: Missing Info → Add Info, + Active → Edit, Pending Verification (with a ? tooltip) → View "Does your app offer AIGC services in China mainland?" Yes / No + Security Assessment modal: "Chinese law requires apps with features like end-to-end encrypted + instant messaging or distribution of AI-generated content (AIGC) offered in China mainland to + complete a Security Assessment with the National Internet Security Management Service Platform." + "Does your app include features that require a security assessment in China mainland?" Yes / No · Save + Yes → "Proof of a Completed Security Assessment" (?) [Choose File (Required)] + "Security Assessment Report" (?) [Choose File (Required)] + a chosen file shows its name and "Delete"; Save enables once both are chosen + AI Generated or Synthetic Content modal: "AI-generated or synthetic content (AIGC) services, such as + AI chatbots, AI image or video generation or processing, AI voice or face alteration or generation, + are subject to the regulatory requirements by the Cyberspace Administration of China (CAC)." + "Does your app offer AIGC services in China mainland?" Yes / No · Save + Yes → "Which filing information would you like to provide?" (?) Large Language Model (LLM) / Algorithm (Algo) + Algo → "Algorithm Name" (?) [text] "Algorithm Filing Number" (?) [text] + "Are your app's AI features powered by third-party technology?" Yes / No + Yes → "Authorization or usage agreement from third-party technology" [Choose File (Required)] Help: "complete the AI-generated/synthetic content and Security Assessment declarations" Help: Yes → filing number + filing name (AIGC); proof screenshot + assessment report (Security Assessment) ``` +The version page carries one banner per unanswered requirement, each linking to the page: + +``` + "Security Assessment Required for China Mainland Distribution" + "provide proof of a completed Security Assessment and a report. + Existing apps must comply by Jan 31, 2027; new apps should submit immediately." + "AIGC Services Declaration Required for China Mainland Distribution" + "submit an AI-generated or synthetic content (AIGC) services declaration and filing information. …" + "Go to App Compliance" +``` + So the domain is a **checklist of requirements**, and each requirement takes a **yes/no declaration**. Answering Yes also requires evidence, and the kind of evidence depends on the requirement. Answering No requires none. -The same page also holds the Digital Services Act trader status, the ICP filing number, the Vietnam game license and the regulated medical device declaration. They are **out of scope** for this lap. They are separate cards with their own shapes and haven't been captured. +The same page also holds the Digital Services Act trader status, the ICP filing number, the Vietnam game license and the regulated medical device declaration. They are **out of scope** for this lap. They are separate cards with their own shapes and haven't been captured here. ## The one sentence @@ -45,6 +72,47 @@ The same page also holds the Digital Services Act trader status, the ICP filing ## The captured wire format +All IDs and dates below are placeholders. Every call is on the same service, scoped by the same account. + +### The requirements — what applies (every row on the page) + +``` +GET https://appstoreconnect.apple.com/ppm/compliancerequirements/v1/accounts/{accountId}/requirements?entity_id={appId} +``` + +```json +{ "data": [ + { "id": "req-1", "formName": "SECURITYASF395E", "entityId": "1234567890", "entityType": "APP", + "status": "PENDING_COLLECT", "isRequired": true, "countries": [ "CHN" ] }, + { "id": "req-2", "formName": "AIGENERATEFD1DE", "entityId": "1234567890", "entityType": "APP", + "status": "PENDING_COLLECT", "isRequired": true, "countries": [ "CHN" ] } +] } +``` + +- Unanswered requirements **do** come back here, with `status: PENDING_COLLECT`. This is the Missing Info source. +- The app is a query parameter, spelled `entity_id` (snake case), not a path segment. +- `countries` holds ISO 3166-1 alpha-3 codes. `CHN` is what the page shows as "China mainland". +- `formName` is the only kind key. There is no human name and no other stable token, so the page's "Security Assessment" is a client-side label. +- An unanswered requirement has no date and no form. + +**After a Yes was saved**, the same call returns the answered requirement with more fields: + +```json +{ "id": "req-1", "formName": "SECURITYASF395E", "entityId": "1234567890", "entityType": "APP", + "status": "COLLECTED_VERIFY_PENDING", "isRequired": true, "countries": [ "CHN" ], + "formId": "form-1", + "dateSigned": "2026-01-01T00:00:00.000Z", "lastUpdatedDate": "2026-01-01T00:00:00.000Z", + "requiredActions": [ "APP_BINARY_SUBMISSION" ] } +``` + +- `formId` names the declaration, so the requirement already says which form answers it. +- `lastUpdatedDate` (ISO 8601, unlike the declarations' epoch milliseconds) is the page's LAST UPDATED. `dateSigned` is when it was first answered; it matched `lastUpdatedDate` here only because the row hadn't been changed since. +- A Yes with evidence goes to `COLLECTED_VERIFY_PENDING`: Apple has the files and has not verified them. The captured No went to `COLLECTED_VERIFY_NOT_NECESSARY` (on the declaration). +- `requiredActions: ["APP_BINARY_SUBMISSION"]` appeared with the pending Yes. The likely reading is that verification happens with the app's next submission for review (Open question 10). +- So the list, status and date of every row come from this one call. The declarations call is needed only for the answer itself (`sValue`). + +### The declarations — what was answered + ``` GET https://appstoreconnect.apple.com/ppm/compliancerequirements/v1/accounts/{accountId}/entities/{appId}/forms ``` @@ -61,11 +129,284 @@ GET https://appstoreconnect.apple.com/ppm/compliancerequirements/v1/accounts/{ac } ] } ``` -- `accountId` is the team's **`publicProviderId`** from `olympus/v1/session`. It already arrives as `IrisAuthSession.teamId`, and the captured URL matched a saved session's `teamId`. It is **not** the numeric `providerID`. -- `entities/{appId}` is the numeric App Store app ID. +- **Only answered requirements come back.** A declaration joins its requirement on `requirementId` = requirement `id`. - Timestamps are epoch milliseconds, encoded as strings. -- The second captured form was `AIGENERATEFD1DE`, with the same shape. -- **Only answered requirements come back.** A "Missing Info" row has no form, so the list of what applies has to come from another call (Open question 1). +- The second captured declaration was `AIGENERATEFD1DE`, with the same shape. The spelling is the same in both calls. + +### The form metadata — what a declaration asks + +``` +POST https://appstoreconnect.apple.com/ppm/compliancerequirements/v1/accounts/{accountId}/entities/{appId}/requirements/{requirementId}/metadata +``` + +```json +{ "accountId": "{accountId}", "entityId": "{appId}", "requirementId": "{requirementId}", + "form": { "fields": [] } } +``` + +Opening the modal sends the empty draft above. The response, for Security Assessment: + +```json +{ + "formName": "SECURITYASF395E", + "formMode": "MODAL", + "formLabel": "PPM.compliance.form.SECURITYASF395E.title", + "description": "PPM.compliance.form.SECURITYASF395E.description", + "form": {}, + "constraints": { + "field-1": { + "presentation": { + "id": "field-1", + "inputType": "RADIO", + "label": "PPM.compliance.form.SECURITYASF395E.field.doesyourap2852f.label", + "options": [ + { "valueId": "YES", "locKey": "PPM.compliance.form.SECURITYASF395E.field.doesyourap2852f.option.YES" }, + { "valueId": "NO", "locKey": "PPM.compliance.form.SECURITYASF395E.field.doesyourap2852f.option.NO" } + ], + "valueDeterminesMetadata": true + }, + "validation": { "required": true, "editable": true } + } + } +} +``` + +- It is a `POST` because it computes the form for a draft: the body repeats the URL's ids and carries the draft in `form.fields`. +- This is the form's schema, read when the developer taps Add Info. An unanswered requirement has one field: the Yes/No question, a `RADIO` whose `valueId`s (`YES` / `NO`) are the `sValue`s a declaration stores. +- `constraints` is keyed by field id. The declaration's `fields[].id` is assumed to be this same id (Open question 2), so the id is read from here, never hard-coded. +- Every visible word is a localization key (`formLabel`, `description`, `label`, `locKey`), not text. The web client resolves them; the page renders the label as "Does your app include features that require a security assessment in China mainland?". A CLI has to supply its own words per kind. +- `valueDeterminesMetadata: true` means the answer changes the form: picking an option fetches the metadata again with that value (below). A No needs nothing more. +- `form` is the draft the metadata was computed for: `{}` before anything is picked. +- The field key inside the loc key (`doesyourap2852f`) is a label slug plus a hash, like `formName`. +- **AI Generated or Synthetic Content opens the same way**: one required `RADIO` with `YES` / `NO` and `valueDeterminesMetadata: true`, its own constraint id, and loc keys under `PPM.compliance.form.AIGENERATEFD1DE` (field `doesyourap268df2`). The page renders its label as "Does your app offer AIGC services in China mainland?". Its Yes branch is deeper (below). + +### The form metadata with Yes picked — the evidence a Yes asks for + +Picking Yes posts to the same `…/requirements/{requirementId}/metadata` URL again, presumably with `"form": { "fields": [ { "id": "field-1", "sValue": "YES" } ] }` in the body (the request for this step wasn't copied, but the opening request's shape and the echo below agree). The response echoes the draft in `form` and adds the Yes branch's fields (the Yes/No constraint is unchanged and omitted here): + +```json +{ + "formName": "SECURITYASF395E", + "form": { "fields": [ { "id": "field-1", "sValue": "YES" } ] }, + "constraints": { + "field-1": { "…": "the Yes/No RADIO, as above" }, + "field-2": { + "presentation": { + "id": "field-2", "inputType": "FILE", + "label": "PPM.compliance.form.SECURITYASF395E.field.proofofacocb097.label", + "tooltip": "PPM.compliance.form.SECURITYASF395E.field.proofofacocb097.tooltip" + }, + "validation": { "required": true, "editable": true, + "allowedFileTypes": [ ".doc", ".docx", ".jpeg", ".jpg", ".pdf", ".png" ] } + }, + "field-3": { + "presentation": { + "id": "field-3", "inputType": "FILE", + "label": "PPM.compliance.form.SECURITYASF395E.field.securityascf4ff1.label", + "tooltip": "PPM.compliance.form.SECURITYASF395E.field.securityascf4ff1.tooltip" + }, + "validation": { "required": true, "editable": true, + "allowedFileTypes": [ ".doc", ".docx", ".jpeg", ".jpg", ".pdf", ".png" ] } + } + } +} +``` + +- **The draft's `fields[].id` is the constraint id.** This confirms the shape a save is expected to send: `fields: [{ "id": , "sValue": … }]`. +- Security Assessment's Yes asks for two required files: **Proof of a Completed Security Assessment** (`proofofaco…`) and the **Security Assessment Report** (`securityasc…`), each `.doc`, `.docx`, `.jpeg`, `.jpg`, `.pdf` or `.png`. The file size limit is not in the metadata. +- What a `FILE` field's `sValue` holds once uploaded (an upload id, a file name) is not captured. + +### The AIGC form with Yes picked — a tree of questions + +AIGC's Yes branch is not a flat list of evidence. Each answer can bring more fields, and each `RADIO` that does is marked `valueDeterminesMetadata: true`. The draft is posted again after every such pick. The captured request, after picking Yes: + +```json +{ "accountId": "{accountId}", "entityId": "{appId}", "requirementId": "req-2", + "form": { "fields": [ { "id": "aigc-offers", "sValue": "YES" } ] } } +``` + +The full tree, from that response and the next one (after Algorithm and third-party Yes were picked). Field ids are placeholders; the slug in brackets is the field key inside each loc key: + +``` +aigc-offers RADIO YES | NO [doesyourap268df2] "Does your app offer AIGC services in China mainland?" +└─ YES + ├─ filing-type RADIO LARGE | ALGOR (tooltip) [whichfilinc6deb2] "Which filing information would you like to provide?" + │ ├─ ALGOR + │ │ ├─ algorithm-name TEXT (tooltip) [algorithmname2] "Algorithm Name" + │ │ └─ algorithm-filing TEXT (tooltip) [algorithmf737252] "Algorithm Filing Number" + │ └─ LARGE + │ ├─ llm-name TEXT (tooltip) [llmname2] "LLM Name" + │ └─ llm-filing TEXT (tooltip) [llmfilingnumber4] "LLM Filing Number" + └─ third-party RADIO YES | NO [areyourappd75c12] "Are your app's AI features powered by third-party technology?" + ├─ YES + │ └─ authorization FILE .doc .docx .jpeg .jpg .pdf .png [authorizat9286a3] + │ "Authorization or usage agreement from third-party technology" + └─ NO (not captured; presumably nothing more) +``` + +Every field is `required: true, editable: true`. The response's `form` after the second pick: + +```json +{ "fields": [ + { "id": "aigc-offers", "sValue": "YES" }, + { "id": "filing-type", "sValue": "ALGOR" }, + { "id": "algorithm-name", "sValue": "" }, + { "id": "algorithm-filing", "sValue": "" }, + { "id": "third-party", "sValue": "YES" } +] } +``` + +- A `TEXT` field the branch opens is echoed with `sValue: ""`, and the web client sends a `RADIO` nobody has picked yet as `sValue: ""` too. A `FILE` field is **not** in the draft until a file is attached. +- The tooltips and the field order on the page come from the metadata; the page's order is the constraints' order. +- So what an AIGC Yes must carry is: the filing type and its name and filing number, and whether third-party technology is used, with the authorization file if it is. The help page's "optional third-party authorization" is optional only in the sense that answering No skips it. + +The web client also reads `GET …/accounts/{accountId}/entities/{appId}/forms` (the declarations) while the modal is open, with the same headers as the metadata `POST`. + +### Saving a declaration — first answer + +``` +POST https://appstoreconnect.apple.com/ppm/compliancerequirements/v1/accounts/{accountId}/entities/{appId}/forms +``` + +```json +{ "accountId": "{accountId}", "entityId": "{appId}", "requirementId": "req-2", + "fields": [ { "id": "aigc-offers", "sValue": "NO" } ] } +``` + +```json +{ "data": { + "id": "form-2", + "requirementId": "req-2", + "formName": "AIGENERATEFD1DE", + "fields": [ { "id": "aigc-offers", "sValue": "NO", "verificationStatus": "FIELD_VERIFY_NOT_NECESSARY" } ], + "status": "COLLECTED_VERIFY_NOT_NECESSARY", + "createdAt": "1790000000000", "updatedAt": "1790000000000", + "createdBy": "user-1", "updatedBy": "user-1" +} } +``` + +- **Saving posts the draft to the declarations collection**, the URL the declarations are read from. The body is the metadata draft's fields, but at the top level (`fields`), not under `form`. +- **The response is the new declaration**, the same shape as one item of the declarations `GET`, with its new form id. A No is not verified (`FIELD_VERIFY_NOT_NECESSARY`). +- Picking No had already posted the draft to `…/metadata`, which answered with no further fields: a No ends the tree. A tool can use that answer the same way, and save once the metadata asks for nothing it hasn't filled. +- `createdBy` / `updatedBy` are the signed-in person's numeric Apple user id. +- Afterwards the requirement reads `status: COLLECTED_VERIFY_NOT_NECESSARY`, with `formId`, `dateSigned` and `lastUpdatedDate`, and **no** `requiredActions`. A No needs nothing further from Apple. + +### Saving a declaration — a change + +``` +PUT https://appstoreconnect.apple.com/ppm/compliancerequirements/v1/accounts/{accountId}/entities/{appId}/forms/{formId} +``` + +```json +{ "accountId": "{accountId}", "entityId": "{appId}", "requirementId": "req-1", "formId": "form-1", + "fields": [ { "id": "field-1", "sValue": "NO" } ] } +``` + +- **A change updates the same declaration**: the form id in the URL and as `formId` in the body; otherwise the first-answer body. The response is the declaration with the **same id**, the same `createdAt` and a new `updatedAt`. +- Afterwards the requirement keeps its `formId` and its `dateSigned` (when it was first answered) and gets a new `lastUpdatedDate` (the page's LAST UPDATED). +- Only an Active declaration can be changed; a pending one is read-only. Captured as an Active No saved again as No. + +### A stored Yes with files + +The declarations `GET`, after the Security Assessment Yes was saved: + +```json +{ "id": "form-1", "requirementId": "req-1", "formName": "SECURITYASF395E", + "fields": [ + { "id": "field-1", "sValue": "YES", "verificationStatus": "FIELD_VERIFY_NOT_NECESSARY" }, + { "id": "field-2", "verificationStatus": "FIELD_VERIFY_PENDING", + "fileContent": { "fileId": "file-1", "fileName": "proof.png", "fileType": "image/png", "fileSizeBytes": "34188" } }, + { "id": "field-3", "verificationStatus": "FIELD_VERIFY_PENDING", + "fileContent": { "fileId": "file-2", "fileName": "report.pdf", "fileType": "application/pdf", "fileSizeBytes": "120000" } } + ], + "status": "COLLECTED_VERIFY_PENDING", + "createdAt": "1790000000000", "updatedAt": "1790000000000", "createdBy": "user-1", "updatedBy": "user-1" } +``` + +- **A `FILE` field holds `fileContent`, not `sValue`**: Apple's `fileId` plus the name, MIME type and size (a string) of the file as uploaded. +- **Verification is per field.** The Yes itself is `FIELD_VERIFY_NOT_NECESSARY`; each file is `FIELD_VERIFY_PENDING`. The declaration's status follows its files. +- Apple issues the `fileId` when it stores the file; the client never sends one (below). + +### Files travel inside the draft + +There is no upload request. Choosing a file puts its bytes into the draft, base64-encoded, and every later `…/metadata` post carries them: + +```json +{ "accountId": "{accountId}", "entityId": "{appId}", "requirementId": "req-1", + "form": { "fields": [ + { "id": "field-1", "sValue": "NO" }, + { "id": "field-2", "fileContent": { "fileData": "iVBORw0KGgo…", "fileName": "proof.png", "fileType": "image/png" } }, + { "id": "field-3", "fileContent": { "fileData": "iVBORw0KGgo…", "fileName": "report.png", "fileType": "image/png" } } + ] } } +``` + +- **A draft file is `fileContent: { fileData, fileName, fileType }`**: the whole file as base64, its name and its MIME type. A stored one is `{ fileId, fileName, fileType, fileSizeBytes }`. Apple turns the first into the second when it saves. +- This capture had Yes, two files chosen, then No picked. The metadata answered with only the Yes/No field and dropped the two files from `form`: **fields the current answers don't ask for are dropped**. A tool should drop them itself before saving rather than rely on that. +- **A Yes with files is saved the same way** (captured on AIGC): the first-answer `POST …/forms` with every field, a file as `{ id, fileContent: { fileData, fileName, fileType } }`. The response carries the stored form, the file now `{ fileId, fileName, fileType, fileSizeBytes }`. +- No size limit is in the metadata. A base64 body grows by a third; a large assessment report makes a large `POST`. + +### Opening an answered requirement + +Edit posts the **stored declaration** as the draft: + +```json +{ "accountId": "{accountId}", "entityId": "{appId}", "requirementId": "req-1", + "form": { "id": "form-1", "requirementId": "req-1", "formName": "SECURITYASF395E", + "fields": [ …the stored fields, fileContent included… ], "status": "COLLECTED_VERIFY_PENDING", … } } +``` + +The response echoes the stored fields in `form`, and the constraints come back **without `editable: true`** (`validation` is only `{ "required": true, … }`). While a declaration is pending verification, Apple serves it read-only: seen on both Security Assessment and AIGC, and the page shows every field greyed out with Save disabled. An Active declaration **is** editable: its row offers Edit, the modal opens on the stored answer with live controls, and Save enables once something changes. Picking a different answer in Edit posts a draft that keeps `requirementId` but **drops the form `id`** (`form: { requirementId, fields }`), and the response is the new branch's form (No → Yes brought back both file fields, editable). Saving the change is nonetheless a `PUT` on the existing form (below): the dropped `id` comes back as `formId` in the save body. + +### The same requirement on a second app + +Picking Yes on Security Assessment for a second app of the same account sent the same request with the other app's `entityId`, and: + +- **The requirement id was the same** as on the first app. A requirement id names the regulation for the account, not one app's row; the row is the requirement id plus `entityId`. +- **Every constraint id was the same** (the Yes/No and both `FILE` fields), with the same loc keys and the same `allowedFileTypes`. + +Not yet seen: an app on another account, so whether these ids are global or per account is open. + +### Saving an AIGC Yes + +```json +{ "accountId": "{accountId}", "entityId": "{appId}", "requirementId": "req-2", + "fields": [ + { "id": "aigc-offers", "sValue": "YES" }, + { "id": "filing-type", "sValue": "LARGE" }, + { "id": "llm-name", "sValue": "Example Model" }, + { "id": "llm-filing", "sValue": "Example-0000" }, + { "id": "third-party", "sValue": "YES" }, + { "id": "authorization", "fileContent": { "fileData": "JVBERi0…", "fileName": "agreement.pdf", "fileType": "application/pdf" } } + ] } +``` + +The answer, in the response and afterwards on the requirement: + +| Field | `verificationStatus` | +|---|---| +| the Yes/No answers and the filing type | `FIELD_VERIFY_NOT_NECESSARY` | +| LLM name, LLM filing number | `FIELD_VERIFY_PENDING` | +| the authorization file | `FIELD_VERIFY_PENDING` | + +The declaration is `COLLECTED_VERIFY_PENDING`, and the requirement gains `requiredActions: ["APP_BINARY_SUBMISSION"]`, as the Security Assessment Yes did. **Apple verifies what a person typed as well as what they attached**: a filing name and number are checked, not just stored. + +### Request headers + +``` +Referer: https://appstoreconnect.apple.com/apps/{appId}/distribution/compliance +Content-Type: application/json +x-csrf-itc: [asc-ui] ← on the requirements GET +Accept: application/vnd.api+json, application/json, text/csv ← requirements GET +Accept: application/json ← metadata POST +``` + +Neither the copied metadata `POST` nor the save `POST` carried `x-csrf-itc`, so this service doesn't ask for it (unlike its sibling `complianceform/v1`, which rejects writes without it). Sending it anyway does no harm; the requirements `GET` does. + +### All calls + +- `accountId` is the team's **`publicProviderId`** from `olympus/v1/session`. It already arrives as `IrisAuthSession.teamId`, and the captured URLs matched a saved session's `teamId`. It is **not** the numeric `providerID`. +- `{appId}` is the numeric App Store app ID. +- A sibling service, `ppm/complianceform/v1`, serves the regulated medical device declaration with a different shape (`requirementData[].requirements[]`, `contentId`). It is not this one; see Open question 2 for what it suggests about saving. --- @@ -76,10 +417,13 @@ GET https://appstoreconnect.apple.com/ppm/compliancerequirements/v1/accounts/{ac | **App Compliance** | The page: every compliance requirement for one app | Export compliance on a build | | **Compliance requirement** | One regulation that applies to the app in a region ("Security Assessment, China mainland"). Apple's API calls it a *requirement* | The help-page article about it | | **Kind** | Which regulation the requirement is. This lap covers Security Assessment and AI Generated or Synthetic Content | Apple's `formName` code, which is only how the wire spells it | +| **Region** | Where the requirement applies, as Apple's `countries` code (`CHN`). Shown by its name ("China mainland") | A storefront | | **Declaration** | The developer's answer to one requirement. Apple's API calls it a *form* | `AgeRatingDeclaration`, `AppEncryptionDeclaration`, `AccessibilityDeclaration`: public-API resources with no relation to this one | +| **Question** | The one Yes/No field a declaration answers. Apple's metadata calls it a *constraint*; its id is what a save names | The localized label text | | **Answer** | Yes (the app offers the regulated feature in the region) or No (it doesn't, or the feature is disabled or geoblocked there) | | -| **Evidence** | What a Yes must carry: filing number and filing name (AIGC), or proof screenshot and assessment report (Security Assessment) | | -| **Status** | Missing Info · Pending Verification · Verification Failed · Active | The raw wire value (`COLLECTED_VERIFY_NOT_NECESSARY`) | +| **Evidence** | What a Yes must carry: filing number and filing name (AIGC), or the proof of a completed assessment and the assessment report, as files (Security Assessment) | | +| **Status** | Missing Info · Pending Verification · Verification Failed · Active | The raw wire values (`PENDING_COLLECT`, `COLLECTED_VERIFY_PENDING`, `COLLECTED_VERIFY_NOT_NECESSARY`) | +| **Required action** | What Apple still needs before it verifies a declaration (`APP_BINARY_SUBMISSION`) | Something the developer must fill in on the form | | **Account** | The team, identified by `publicProviderId` (a UUID) | `providerID`, the numeric ID | **"Declaration", not "form".** *Form* is Apple's backstage word. Apple's help page and the people filling it in say *declaration*. The `formName` code stays in the infrastructure mapper. @@ -88,25 +432,30 @@ GET https://appstoreconnect.apple.com/ppm/compliancerequirements/v1/accounts/{ac ``` ComplianceRequirement one row on the App Compliance page (aggregate root) - ├─ id : String Apple's requirementId; stable before and after answering - ├─ appId : String parent; injected by the adapter (the API omits it) - ├─ kind : ComplianceKind which regulation; decides what a Yes must carry - ├─ region : String? "China mainland"; from the requirements call (blocked) - ├─ updatedAt : Date? nil = never answered ("-") - ├─ declaration : ComplianceDeclaration? nil ⇒ MISSING INFO, always - │ ├─ id : String Apple's form id; what an update targets (assumed, Open question 2) - │ └─ answer : ComplianceAnswer .notOffered | .offered(Evidence) — EVIDENCE ONLY ON YES - └─ status : ComplianceStatus derived: no declaration → missingInfo; else mapped from wire + ├─ id : String Apple's requirement id; stable before and after answering, and the SAME for every app + │ (it names the regulation, not the row): a row is identified by (id, appId) + ├─ appId : String parent; injected by the adapter (also `entityId` on the wire) + ├─ kind : ComplianceKind which regulation, from `formName`; decides what a Yes must carry + ├─ regions : [String] `countries`, e.g. ["CHN"] + ├─ isRequired : Bool + ├─ updatedAt : Date? `lastUpdatedDate`; nil = never answered, shown "-" + ├─ requiredActions : [RequiredAction] e.g. .appBinarySubmission; unknown values kept raw + ├─ declaration : ComplianceDeclaration? nil ⇒ never answered + │ ├─ id : String Apple's form id (`formId` on the requirement); what an update targets (assumed, Open question 2) + │ └─ answer : ComplianceAnswer .notOffered | .offered(Evidence) — EVIDENCE ONLY ON YES + └─ status : ComplianceStatus mapped from the requirement's `status` ``` +The adapter makes the two reads and joins them: every requirement is a row, and its declaration is the form whose `id` is the requirement's `formId` (equivalently, whose `requirementId` is the requirement's `id`). A form with no matching requirement is kept as its own row with `.unrecognized` kind (law 4), never dropped. A list that doesn't need the answer itself can skip the declarations call. + There is no `AppCompliance` wrapper type. It would just be the plural of `ComplianceRequirement`, with no rule of its own yet. It earns a type if Open question 6 ("may this app ship in region X?") gets answered, because that rule belongs to the collection. ## 3 · The kinds and the rich types | Kind | Wire `formName` | A Yes must carry | Its own rules | |---|---|---|---| -| **securityAssessment** | `SECURITYASF395E` | proof-of-pass screenshot + assessment report (sealed) | Required when the app distributes AIGC or offers encrypted instant messaging | -| **aiGeneratedContent** | `AIGENERATEFD1DE` | LLM/algorithm filing number + filing name; optional third-party authorization | | +| **securityAssessment** | `SECURITYASF395E` | two files, each `.doc`/`.docx`/`.jpeg`/`.jpg`/`.pdf`/`.png`: proof of a completed assessment, and the assessment report | Required when the app distributes AIGC or offers encrypted instant messaging | +| **aiGeneratedContent** | `AIGENERATEFD1DE` | the filing type (LLM or Algorithm) with its name and filing number (text), and whether third-party technology powers it, with the authorization or usage agreement (a file) when it does | Offered for AI chatbots, AI image or video generation or processing, AI voice or face alteration or generation (the modal's examples) | | **unrecognized(formName)** | anything else | unknown | Listed as-is, never offered `declare` | ### `ComplianceAnswer` — the developer's Yes or No @@ -116,6 +465,7 @@ There is no `AppCompliance` wrapper type. It would just be the plural of `Compli | | | |---|---| | **Owns — a Yes carries its kind's evidence; a No carries nothing** | `.notOffered` has no payload. `.offered(SecurityAssessmentEvidence)` and `.offered(AIGCFilingEvidence)` are different shapes, so a Yes without a filing number can't be built | +| **The evidence shapes** | `SecurityAssessmentEvidence(proof: File, report: File)`, where a `File` is a local document (name, MIME type, bytes) going in, and Apple's `fileId`, name, type and size coming back. `AIGCFilingEvidence(filing: AIGCFiling, thirdParty: ThirdPartyTechnology)`, where `AIGCFiling` is `.algorithm(name, filingNumber)` or `.largeLanguageModel(name, filingNumber)` and `ThirdPartyTechnology` is `.none` or `.used(authorization: File)`. Each branch of Apple's tree is one case, so a combination the form can't hold can't be built | | **It answers** | `wireValue` → `"YES"` / `"NO"` | | **Never** | A `filingNumber` field that "is ignored when the answer is No" | @@ -127,7 +477,7 @@ There is no `AppCompliance` wrapper type. It would just be the plural of `Compli |---|---| | **Owns — an unknown wire status still lists** | `.missingInfo · .pendingVerification · .verificationFailed · .active · .unrecognized(raw)` | | **It answers** | `isActive` (the app may stay on sale in the region) · `needsAction` (Missing Info or Verification Failed) · `isPendingVerification` | -| **Never** | Guess a mapping. Only `COLLECTED_VERIFY_NOT_NECESSARY → active` is observed; every other wire value is `.unrecognized` until captured (Open question 3) | +| **Never** | Guess a mapping. Observed so far, on the requirement and the declaration alike: `PENDING_COLLECT → missingInfo`, `COLLECTED_VERIFY_PENDING → pendingVerification`, `COLLECTED_VERIFY_NOT_NECESSARY → active` (a No). Every other wire value is `.unrecognized` until captured (Open question 3) | ## 4 · The tells @@ -152,29 +502,39 @@ The adapter resolves the account itself: it uses `IrisAuthSession.teamId` when t | # | Law | Owner | |---|---|---| | 1 | A requirement nobody has answered shows Missing Info | `ComplianceRequirement` (derives `status`) | -| 2 | A requirement always belongs to the app it was listed under | adapter mapper (injects `appId`) | +| 2 | A requirement always belongs to the app it was listed under, and is addressed by its id **and** that app, never by its id alone (the id is shared across apps) | adapter mapper (injects `appId`) | | 3 | A Yes always carries its kind's evidence; a No carries none | `ComplianceAnswer` (shape) | | 4 | An unknown form or status is still listed, never dropped and never a crash | `ComplianceKind` / `ComplianceStatus` (`.unrecognized`) | -| 5 | You're offered `declare` only for a recognized kind that isn't awaiting verification | `ComplianceRequirement.structuredAffordances` | +| 5 | You're offered `declare` only for a recognized kind that isn't awaiting verification: Missing Info (a first answer), Active (a change) and Verification Failed (a resubmission, assumed) | `ComplianceRequirement.structuredAffordances` | +| 5a | `declare` saves only if the requirement's metadata says its fields are `editable`; otherwise it refuses without writing. Apple's own answer decides, so a wrong guess about a status never writes to a read-only declaration | adapter (`declare` reads metadata first) | | 6 | The account in the URL is the team's `publicProviderId`, never the numeric `providerID` | adapter (account resolution) | +| 7 | Every requirement is a row whether or not it was answered; a declaration attaches to the requirement whose `id` is its `requirementId` | adapter (the join) | +| 8 | A declaration names each field by the id the requirement's metadata gives, read for the chosen answers before every save; an id is never hard-coded or guessed. The adapter finds which constraint is which by the field key in its `label` loc key (`algorithmname2`), and walks the tree one pick at a time | adapter (`declare` reads metadata first) | +| 9 | A file is offered for a `FILE` field only if its extension is in that field's `allowedFileTypes` | `ComplianceAnswer` evidence types, from the metadata | +| 10 | A save sends only the fields the metadata asks for under the chosen answers; a field from an abandoned branch (a file chosen before switching to No) is dropped | adapter (`declare` builds the body from the metadata) | ## 6 · Build sequence (test-first, each slice green) -0. **Capture** *(blocking 2–5)*: in the browser network tab, capture the requirements/applicability call (names, regions, IDs for unanswered rows), the Save request for No and for Yes, the status values for Pending/Failed, and the document upload calls. +0. ~~**Capture**~~ Done. Every call the page makes is captured; nothing blocks slices 1–6. Also the AIGC Yes metadata, `metadata` for an answered requirement, and the Verification Failed status. The reads, and their responses after a Yes, are captured. 1. **Domain**: `ComplianceKind`, `ComplianceStatus`, `ComplianceAnswer` (No only), `ComplianceRequirement` + affordances, `@Mockable IrisComplianceRepository`. *Pinned: laws 1, 3 (No), 4, 5.* -2. **Infrastructure read**: `IrisClient` ppm base; account resolution; `listRequirements(session:appId:)` decoding the captured fixture, with placeholder IDs. *Pinned: laws 2, 6; epoch-ms dates; unknown `formName` survives.* +2. **Infrastructure read**: `IrisClient` ppm base; account resolution; `listRequirements(session:appId:)` reading both captured fixtures (placeholder IDs) and joining them. *Pinned: laws 2, 6, 7; epoch-ms dates; `entity_id` query; unknown `formName` survives; an orphan declaration survives.* 3. **`asc iris app-compliance list` + REST** `GET /api/v1/iris/apps/:appId/compliance-requirements`. *Pinned: full JSON snapshot; `_links.declare` only on eligible rows.* -4. **`declare --answer no` + REST** `POST /api/v1/iris/compliance-requirements/:requirementId/declare` *(blocked on the Save capture)*. -5. **Yes with evidence** *(blocked on the upload capture)*: per-kind evidence types and file flags. -6. **Docs**: `README.md` for users, one CHANGELOG line, `make docs`, and a link from the iris README's "Other iris commands". +4. **`declare --answer no` + REST** (reads the requirement's metadata for the question's id, then saves; *pinned: law 8*) `POST /api/v1/iris/apps/:appId/compliance-requirements/:requirementId/declare` (the app is in the path because a requirement id alone names no row). A first answer is a `POST …/forms`; a change to an Active one is a `PUT …/forms/{formId}` (the requirement's `formId`). A pending one is never offered `declare`. +5. **Yes with evidence**: per-kind evidence types and file flags; files read from disk and sent base64 in `fileContent.fileData`. *Pinned: laws 9, 10.* The body is captured (AIGC Yes with a file). +6. **Readiness** (after the list ships): `AppCompliance` collection + availability; check-readiness warns for a non-Active requirement only in a region the app is sold in (Open question 6). +7. **Docs**: `README.md` for users, one CHANGELOG line, `make docs`, and a link from the iris README's "Other iris commands". ## 7 · Open questions -1. **Where does the list of applicable requirements come from?** `/forms` returns only answered ones, so a Missing Info row is invisible to it. A sibling call (likely `…/entities/{appId}/requirements`) is expected to provide names, regions and IDs. *Blocking for slice 2.* Hard-coding the two China requirements is the fallback, but that breaks as soon as Apple adds a region. -2. **What does Save target: the requirement or the form?** A first answer has no form yet, so it probably POSTs against `requirementId` and later edits PATCH the form `id`. Decide from the capture. -3. **What are the wire values for Pending Verification, Verification Failed and a Yes awaiting review?** Until captured, they map to `.unrecognized(raw)` and are shown raw. -4. **Are `formName` codes stable?** `SECURITYASF395E` / `AIGENERATEFD1DE` look like a prefix plus a hash. Recommendation: match the exact code and fall through to `.unrecognized`. If the requirements call gives a stable key, use that instead. -5. **Who can edit?** The help page requires Account Holder or Admin for the China identity verification. If declarations need it too, a 403 should say so rather than surfacing as a bare HTTP error. -6. **Should check-readiness warn?** Apple removes non-compliant apps from the China mainland store (deadline 2027-01-31), and a failed verification removes the app there. A readiness check "China mainland compliance not Active" would be the first rule that needs an `AppCompliance` collection type. Deferred until the list ships. +1. ~~**Where does the list of applicable requirements come from?**~~ **ANSWERED: `…/accounts/{accountId}/requirements?entity_id={appId}`.** It lists answered and unanswered requirements, with `formName`, `countries`, `isRequired` and `status` (`PENDING_COLLECT` when unanswered). No hard-coded list is needed. +2. ~~**What does Save target, and what does it send?**~~ **ANSWERED.** A first answer: `POST …/entities/{appId}/forms` with `{ accountId, entityId, requirementId, fields }`, answered with the new declaration. A change: `PUT …/entities/{appId}/forms/{formId}` with the same body plus `formId`, answered with the same declaration and a new `updatedAt`. A `RADIO` or `TEXT` field is `{ id, sValue }`; a `FILE` field is `{ id, fileContent: { fileData: , fileName, fileType } }`, stored as `{ fileId, fileName, fileType, fileSizeBytes }`. +3. **What are the other wire values?** Seen, on the requirement and the declaration alike: `PENDING_COLLECT` (unanswered), `COLLECTED_VERIFY_PENDING` (a Yes awaiting Apple, with `requiredActions`) and `COLLECTED_VERIFY_NOT_NECESSARY` (a No, with no `requiredActions`). **Working assumption until Apple reviews one:** a verified Yes becomes Active, and a failed one becomes Verification Failed and editable again, so the developer can correct it and resubmit (law 5 offers `declare` on it; law 5a still lets Apple's `editable` decide). Their wire values are unseen and stay `.unrecognized(raw)`, shown raw, until captured. +4. ~~**Are `formName` codes stable?**~~ **DECIDED: match the exact `formName`.** `SECURITYASF395E` and `AIGENERATEFD1DE` map to their kinds; any other code is `.unrecognized(formName)`, listed as-is and never offered `declare` (law 4). If Apple renames a code, the row still lists and only `declare` stops until the mapping is updated. +5. ~~**Who can edit?**~~ **ANSWERED: whoever can sign in to App Store Connect with access to the app.** The tool adds no role check of its own and simply uses the signed-in session. If Apple refuses a save anyway (the help page reserves the China identity verification for Account Holder or Admin), the 403 is reported as "your App Store Connect role can't edit App Compliance for this app", never as a bare HTTP error. +6. ~~**Should check-readiness warn?**~~ **DECIDED: only when the app is available in a requirement's region.** A requirement that isn't Active (Missing Info, Pending Verification, Verification Failed) warns only if one of its `countries` (`CHN`) is among the territories the app is available in (the public API's app availability). An app not sold in China mainland gets no warning. It is a warning, not a blocker, and says the region and the deadline (2027-01-31). The rule joins compliance to availability, so it is the first one that earns an `AppCompliance` collection type; that type and the readiness rule are their own slice after the list ships. 7. ~~**Is there a public API or SDK support?**~~ **ANSWERED: no.** Not in appstoreconnect-swift-sdk 4.6.0/4.6.1 or Apple's OpenAPI 4.6 (checked 2026-11-17). Private `/ppm/` endpoint only. 8. ~~**Where does `accountId` come from?**~~ **ANSWERED: olympus `publicProviderId`.** It matched the `teamId` saved by `asc iris auth login`. +9. ~~**How is the metadata asked for with a draft?**~~ **ANSWERED: `POST …/metadata` with `{ accountId, entityId, requirementId, form: { fields: [ … ] } }`.** Opening the modal sends `fields: []`; each pick on a `valueDeterminesMetadata` field sends it again, and the response adds that branch's fields. Every AIGC branch is captured except third-party No, which presumably asks for nothing more. +10. **What does `requiredActions` mean?** **Working assumption:** `APP_BINARY_SUBMISSION` means Apple verifies the declaration when the app is next submitted for review, and the row stays Pending Verification until then. The CLI shows it as "verified at your next submission for review". Not confirmed; other values are unseen and are shown raw. +11. ~~**How is a file uploaded?**~~ **ANSWERED: it isn't, separately.** The file goes inside the draft as `fileContent: { fileData: , fileName, fileType }`, and Apple stores it on save as `{ fileId, fileName, fileType, fileSizeBytes }`. Still unknown: the size limit. +12. ~~**Are constraint ids the same for every app?**~~ **ANSWERED for one account: yes.** A second app showed the same constraint ids and even the same requirement id, so requirement and field ids belong to the regulation, not to the app. Law 8 still finds fields by their loc-key slug and never hard-codes an id, because another account is unseen and Apple can change a form; the shared requirement id is why law 2 addresses a row by requirement id and app together. From e4ee067ad6416386333696cbff59a383072ed488 Mon Sep 17 00:00:00 2001 From: slamhan Date: Thu, 19 Nov 2026 21:19:57 +0800 Subject: [PATCH 03/12] docs(app-compliance): place the build in the concept-folder layout Slices 1 and 2 now name Sources/ASCKit/Iris/Compliance/ and its Internal/, and reach the ppm service through the @Mockable IrisAPI role (IrisRequest gains the ppm base; IrisAPI gains PUT) instead of a second IrisClient entry point. IrisComplianceRepository keeps its name: it is CRUD, and declare is the model's workflow. Co-Authored-By: Claude Opus 5.5 --- docs/features/app-compliance/design.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/features/app-compliance/design.md b/docs/features/app-compliance/design.md index 7c217abc..987b4507 100644 --- a/docs/features/app-compliance/design.md +++ b/docs/features/app-compliance/design.md @@ -495,7 +495,7 @@ requirement.structuredAffordances The adapter resolves the account itself: it uses `IrisAuthSession.teamId` when the session came from `asc iris auth login`, and otherwise calls `olympus/v1/session` (browser cookies and `ASC_IRIS_COOKIES` don't carry a team ID). The command never asks for `--account-id`, because a user can't see that value anywhere. -`IrisClient` hard-codes the base `…/iris/v1`. It gets a second entry point for `…/ppm/compliancerequirements/v1` with the same cookies and headers. There is no new auth path. +The iris repositories reach Apple through the `@Mockable IrisAPI` role, played by `IrisClient` in `Iris/Internal/System/`; the requests themselves are built by `IrisRequest`, which hard-codes the base `…/iris/v1`. `IrisRequest` gains the `…/ppm/compliancerequirements/v1` base with the same cookies and headers, and `IrisAPI` gains the calls the page makes there (a `PUT` for a change, beside the `get`, `post` and `delete` it has). There is no new auth path. ## 5 · Invariants (each law, one owner) @@ -516,8 +516,8 @@ The adapter resolves the account itself: it uses `IrisAuthSession.teamId` when t ## 6 · Build sequence (test-first, each slice green) 0. ~~**Capture**~~ Done. Every call the page makes is captured; nothing blocks slices 1–6. Also the AIGC Yes metadata, `metadata` for an answered requirement, and the Verification Failed status. The reads, and their responses after a Yes, are captured. -1. **Domain**: `ComplianceKind`, `ComplianceStatus`, `ComplianceAnswer` (No only), `ComplianceRequirement` + affordances, `@Mockable IrisComplianceRepository`. *Pinned: laws 1, 3 (No), 4, 5.* -2. **Infrastructure read**: `IrisClient` ppm base; account resolution; `listRequirements(session:appId:)` reading both captured fixtures (placeholder IDs) and joining them. *Pinned: laws 2, 6, 7; epoch-ms dates; `entity_id` query; unknown `formName` survives; an orphan declaration survives.* +1. **Public face** (`Sources/ASCKit/Iris/Compliance/`): `ComplianceKind`, `ComplianceStatus`, `ComplianceAnswer` (No only), `ComplianceRequirement` + affordances, `@Mockable IrisComplianceRepository` (CRUD over requirements and declarations, so it keeps the `Repository` name; `requirement.declare(…)` is the workflow, on the model). *Pinned: laws 1, 3 (No), 4, 5.* +2. **Read** (`Sources/ASCKit/Iris/Compliance/Internal/`, through `IrisAPI`): the ppm base on `IrisRequest`; account resolution; `listRequirements(session:appId:)` reading both captured fixtures (placeholder IDs) and joining them, tested on `MockIrisAPI`. *Pinned: laws 2, 6, 7; epoch-ms dates; `entity_id` query; unknown `formName` survives; an orphan declaration survives.* 3. **`asc iris app-compliance list` + REST** `GET /api/v1/iris/apps/:appId/compliance-requirements`. *Pinned: full JSON snapshot; `_links.declare` only on eligible rows.* 4. **`declare --answer no` + REST** (reads the requirement's metadata for the question's id, then saves; *pinned: law 8*) `POST /api/v1/iris/apps/:appId/compliance-requirements/:requirementId/declare` (the app is in the path because a requirement id alone names no row). A first answer is a `POST …/forms`; a change to an Active one is a `PUT …/forms/{formId}` (the requirement's `formId`). A pending one is never offered `declare`. 5. **Yes with evidence**: per-kind evidence types and file flags; files read from disk and sent base64 in `fileContent.fileData`. *Pinned: laws 9, 10.* The body is captured (AIGC Yes with a file). From d34b7dd5de41bf42ecf2623d3401796b680c520b Mon Sep 17 00:00:00 2001 From: slamhan Date: Thu, 19 Nov 2026 21:26:39 +0800 Subject: [PATCH 04/12] feat(app-compliance): the requirement, its kind, status and declaration ComplianceRequirement is one row of an app's App Compliance page: its kind (Security Assessment, AI generated content, or an unrecognized formName kept as-is), regions, status (Missing Info, Pending Verification, Verification Failed, Active, or an unrecognized wire value), last update, required actions and the declaration that answers it. It offers declare only for a known kind Apple isn't verifying, and refuses otherwise before anything is sent. IrisComplianceRepository is the @Mockable collection. RESTPathResolver gains routes whose child is addressed under its parent by both ids, since a requirement id names the compliance on every app. Co-Authored-By: Claude Opus 5.5 --- .../Iris/Compliance/ComplianceAnswer.swift | 31 +++++ .../Iris/Compliance/ComplianceError.swift | 17 +++ .../Iris/Compliance/ComplianceKind.swift | 56 +++++++++ .../ComplianceRequirement+RESTRoutes.swift | 15 +++ .../Compliance/ComplianceRequirement.swift | 101 +++++++++++++++++ .../Iris/Compliance/ComplianceStatus.swift | 94 ++++++++++++++++ .../Compliance/IrisComplianceRepository.swift | 12 ++ Sources/ASCKit/Shared/RESTPathResolver.swift | 37 +++++- .../Iris/Compliance/ComplianceKindTests.swift | 34 ++++++ .../ComplianceRequirementTests.swift | 106 ++++++++++++++++++ .../Compliance/ComplianceStatusTests.swift | 52 +++++++++ 11 files changed, 553 insertions(+), 2 deletions(-) create mode 100644 Sources/ASCKit/Iris/Compliance/ComplianceAnswer.swift create mode 100644 Sources/ASCKit/Iris/Compliance/ComplianceError.swift create mode 100644 Sources/ASCKit/Iris/Compliance/ComplianceKind.swift create mode 100644 Sources/ASCKit/Iris/Compliance/ComplianceRequirement+RESTRoutes.swift create mode 100644 Sources/ASCKit/Iris/Compliance/ComplianceRequirement.swift create mode 100644 Sources/ASCKit/Iris/Compliance/ComplianceStatus.swift create mode 100644 Sources/ASCKit/Iris/Compliance/IrisComplianceRepository.swift create mode 100644 Tests/ASCKitTests/Iris/Compliance/ComplianceKindTests.swift create mode 100644 Tests/ASCKitTests/Iris/Compliance/ComplianceRequirementTests.swift create mode 100644 Tests/ASCKitTests/Iris/Compliance/ComplianceStatusTests.swift diff --git a/Sources/ASCKit/Iris/Compliance/ComplianceAnswer.swift b/Sources/ASCKit/Iris/Compliance/ComplianceAnswer.swift new file mode 100644 index 00000000..832aeec1 --- /dev/null +++ b/Sources/ASCKit/Iris/Compliance/ComplianceAnswer.swift @@ -0,0 +1,31 @@ +/// The developer's answer to a requirement's question ("Does your app offer AIGC +/// services in China mainland?"). A No carries nothing (law 3). +public enum ComplianceAnswer: Sendable, Equatable { + /// The app doesn't offer the regulated feature in the region, or it's disabled or geoblocked there. + case notOffered + + /// The question's option, as Apple's form names it. + var wireValue: String { + switch self { + case .notOffered: "NO" + } + } +} + +/// An answer Apple holds for a requirement. Apple's API calls it a *form*. +/// The evidence of a Yes stays with Apple; the list shows only the answer. +public struct ComplianceDeclaration: Sendable, Equatable, Codable { + public enum Answer: String, Sendable, Equatable, Codable { + case yes = "YES" + case no = "NO" + } + + /// Apple's form id: what a change updates. + public let id: String + public let answer: Answer + + public init(id: String, answer: Answer) { + self.id = id + self.answer = answer + } +} diff --git a/Sources/ASCKit/Iris/Compliance/ComplianceError.swift b/Sources/ASCKit/Iris/Compliance/ComplianceError.swift new file mode 100644 index 00000000..e66d7110 --- /dev/null +++ b/Sources/ASCKit/Iris/Compliance/ComplianceError.swift @@ -0,0 +1,17 @@ +import Foundation + +public enum ComplianceError: Error, Equatable, Sendable, CustomStringConvertible, LocalizedError { + /// Refused by the requirement itself, before anything reaches Apple (law 5). + case notDeclarable(kind: ComplianceKind, status: ComplianceStatus) + + public var description: String { + switch self { + case .notDeclarable(let kind, _) where !kind.isRecognized: + "\(kind.displayName) is a compliance asc doesn't know yet, so it can't declare it. Answer it on the App Compliance page." + case .notDeclarable(let kind, let status): + "\(kind.displayName) can't be changed while it is \(status.displayName): Apple is checking the last answer." + } + } + + public var errorDescription: String? { description } +} diff --git a/Sources/ASCKit/Iris/Compliance/ComplianceKind.swift b/Sources/ASCKit/Iris/Compliance/ComplianceKind.swift new file mode 100644 index 00000000..f5a539a8 --- /dev/null +++ b/Sources/ASCKit/Iris/Compliance/ComplianceKind.swift @@ -0,0 +1,56 @@ +/// Which compliance a requirement is — the page's COMPLIANCE NAME. It decides +/// what a Yes must carry. Apple's wire spells it as a `formName` code; that code +/// stays here, and an unknown one is kept, never dropped (law 4). +public enum ComplianceKind: Sendable, Equatable, Hashable { + /// `SECURITYASF395E`. A Yes carries the proof of a completed assessment and its report. + case securityAssessment + /// `AIGENERATEFD1DE`. A Yes carries the AIGC filing and any third-party authorization. + case aiGeneratedContent + /// A form asc doesn't know yet: listed as Apple names it, never offered `declare`. + case unrecognized(formName: String) + + public init(formName: String) { + switch formName { + case "SECURITYASF395E": self = .securityAssessment + case "AIGENERATEFD1DE": self = .aiGeneratedContent + default: self = .unrecognized(formName: formName) + } + } + + public var isRecognized: Bool { + if case .unrecognized = self { return false } + return true + } + + public var displayName: String { + switch self { + case .securityAssessment: "Security Assessment" + case .aiGeneratedContent: "AI Generated or Synthetic Content" + case .unrecognized(let formName): formName + } + } + + var jsonValue: String { + switch self { + case .securityAssessment: "SECURITY_ASSESSMENT" + case .aiGeneratedContent: "AI_GENERATED_CONTENT" + case .unrecognized(let formName): formName + } + } +} + +extension ComplianceKind: Codable { + public init(from decoder: any Decoder) throws { + let value = try decoder.singleValueContainer().decode(String.self) + switch value { + case "SECURITY_ASSESSMENT": self = .securityAssessment + case "AI_GENERATED_CONTENT": self = .aiGeneratedContent + default: self = ComplianceKind(formName: value) + } + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(jsonValue) + } +} diff --git a/Sources/ASCKit/Iris/Compliance/ComplianceRequirement+RESTRoutes.swift b/Sources/ASCKit/Iris/Compliance/ComplianceRequirement+RESTRoutes.swift new file mode 100644 index 00000000..224177a3 --- /dev/null +++ b/Sources/ASCKit/Iris/Compliance/ComplianceRequirement+RESTRoutes.swift @@ -0,0 +1,15 @@ +/// REST routes for App Compliance. +extension RESTPathResolver { + static let _complianceRoutes: Void = { + // `asc iris app-compliance list --app-id A` → GET /api/v1/iris/apps/A/compliance-requirements + // `… declare --app-id A --requirement-id R` → POST /api/v1/iris/apps/A/compliance-requirements/R/declare + // (a requirement id names the compliance on every app, so the row needs both ids) + registerRoute( + command: "iris app-compliance", + parentParam: "app-id", + parentSegment: "iris/apps", + segment: "compliance-requirements", + nestedResourceParam: "requirement-id" + ) + }() +} diff --git a/Sources/ASCKit/Iris/Compliance/ComplianceRequirement.swift b/Sources/ASCKit/Iris/Compliance/ComplianceRequirement.swift new file mode 100644 index 00000000..a463aa06 --- /dev/null +++ b/Sources/ASCKit/Iris/Compliance/ComplianceRequirement.swift @@ -0,0 +1,101 @@ +/// One row on an app's App Compliance page: a compliance that applies to the app in +/// a region, and the declaration that answers it. Apple's requirement id names the +/// compliance for the whole account, so a row is the id **and** its app (law 2). +public struct ComplianceRequirement: Sendable, Equatable, Identifiable, Codable { + public let id: String + /// Parent: Apple's `entityId`, injected by the adapter. + public let appId: String + public let kind: ComplianceKind + /// Where it applies, as Apple's `countries` codes (`CHN` = China mainland). + public let regions: [String] + public let isRequired: Bool + public let status: ComplianceStatus + /// LAST UPDATED, as Apple's ISO 8601 `lastUpdatedDate`; nil = never answered. + public let updatedAt: String? + public let requiredActions: [ComplianceRequiredAction] + /// nil = never answered. + public let declaration: ComplianceDeclaration? + + public init( + id: String, appId: String, kind: ComplianceKind, regions: [String], isRequired: Bool, + status: ComplianceStatus, updatedAt: String?, requiredActions: [ComplianceRequiredAction], + declaration: ComplianceDeclaration? + ) { + self.id = id + self.appId = appId + self.kind = kind + self.regions = regions + self.isRequired = isRequired + self.status = status + self.updatedAt = updatedAt + self.requiredActions = requiredActions + self.declaration = declaration + } + + /// A first answer (Missing Info), a change (Active) or a resubmission (Verification + /// Failed) — never while Apple is verifying, and never a kind asc doesn't know (law 5). + public var isDeclarable: Bool { kind.isRecognized && !status.isPendingVerification } + + public var isActive: Bool { status.isActive } + public var needsAction: Bool { status.needsAction } + + /// Saves `answer` through `repo`, after checking this requirement may be declared. + public func declare(_ answer: ComplianceAnswer, session: IrisSession, repo: any IrisComplianceRepository) async throws -> ComplianceRequirement { + guard isDeclarable else { throw ComplianceError.notDeclarable(kind: kind, status: status) } + return try await repo.declare(session: session, requirement: self, answer: answer) + } + + private enum CodingKeys: String, CodingKey { + case id, appId, kind, name, regions, isRequired, status, updatedAt, requiredActions, declaration + } + + public init(from decoder: any Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + self.init( + id: try c.decode(String.self, forKey: .id), + appId: try c.decode(String.self, forKey: .appId), + kind: try c.decode(ComplianceKind.self, forKey: .kind), + regions: try c.decode([String].self, forKey: .regions), + isRequired: try c.decode(Bool.self, forKey: .isRequired), + status: try c.decode(ComplianceStatus.self, forKey: .status), + updatedAt: try c.decodeIfPresent(String.self, forKey: .updatedAt), + requiredActions: try c.decode([ComplianceRequiredAction].self, forKey: .requiredActions), + declaration: try c.decodeIfPresent(ComplianceDeclaration.self, forKey: .declaration) + ) + } + + public func encode(to encoder: any Encoder) throws { + var c = encoder.container(keyedBy: CodingKeys.self) + try c.encode(id, forKey: .id) + try c.encode(appId, forKey: .appId) + try c.encode(kind, forKey: .kind) + try c.encode(kind.displayName, forKey: .name) + try c.encode(regions, forKey: .regions) + try c.encode(isRequired, forKey: .isRequired) + try c.encode(status, forKey: .status) + try c.encodeIfPresent(updatedAt, forKey: .updatedAt) + try c.encode(requiredActions, forKey: .requiredActions) + try c.encodeIfPresent(declaration, forKey: .declaration) + } +} + +extension ComplianceRequirement: AffordanceProviding { + public var structuredAffordances: [Affordance] { + var items = [ + Affordance(key: "listRequirements", command: "iris app-compliance", action: "list", params: ["app-id": appId]), + ] + if isDeclarable { + items.append(Affordance(key: "declare", command: "iris app-compliance", action: "declare", + params: ["app-id": appId, "requirement-id": id, "answer": ""])) + } + return items + } +} + +extension ComplianceRequirement: Presentable { + public static var tableHeaders: [String] { ["Requirement ID", "Compliance", "Regions", "Status", "Answer", "Last Updated"] } + public var tableRow: [String] { + [id, kind.displayName, regions.joined(separator: ", "), status.displayName, + declaration?.answer.rawValue ?? "-", updatedAt ?? "-"] + } +} diff --git a/Sources/ASCKit/Iris/Compliance/ComplianceStatus.swift b/Sources/ASCKit/Iris/Compliance/ComplianceStatus.swift new file mode 100644 index 00000000..6dfd80d8 --- /dev/null +++ b/Sources/ASCKit/Iris/Compliance/ComplianceStatus.swift @@ -0,0 +1,94 @@ +/// What the STATUS column says about a requirement. Only the wire values seen so far +/// are mapped; any other stays `.unrecognized`, shown as Apple sends it (law 4). +public enum ComplianceStatus: Sendable, Equatable, Hashable { + /// Nobody has answered it (`PENDING_COLLECT`). + case missingInfo + /// Apple is checking a Yes (`COLLECTED_VERIFY_PENDING`). + case pendingVerification + /// Apple rejected the evidence; the developer corrects and resubmits. Wire value not seen yet. + case verificationFailed + /// The app may stay on sale in the region (`COLLECTED_VERIFY_NOT_NECESSARY`, e.g. a No). + case active + case unrecognized(wireValue: String) + + public init(wireValue: String) { + switch wireValue { + case "PENDING_COLLECT": self = .missingInfo + case "COLLECTED_VERIFY_PENDING": self = .pendingVerification + case "COLLECTED_VERIFY_NOT_NECESSARY": self = .active + default: self = .unrecognized(wireValue: wireValue) + } + } + + public var isActive: Bool { self == .active } + public var isPendingVerification: Bool { self == .pendingVerification } + /// Missing Info or Verification Failed: the developer has to answer. + public var needsAction: Bool { self == .missingInfo || self == .verificationFailed } + + public var displayName: String { + switch self { + case .missingInfo: "Missing Info" + case .pendingVerification: "Pending Verification" + case .verificationFailed: "Verification Failed" + case .active: "Active" + case .unrecognized(let wireValue): wireValue + } + } + + var jsonValue: String { + switch self { + case .missingInfo: "MISSING_INFO" + case .pendingVerification: "PENDING_VERIFICATION" + case .verificationFailed: "VERIFICATION_FAILED" + case .active: "ACTIVE" + case .unrecognized(let wireValue): wireValue + } + } +} + +extension ComplianceStatus: Codable { + public init(from decoder: any Decoder) throws { + let value = try decoder.singleValueContainer().decode(String.self) + switch value { + case "MISSING_INFO": self = .missingInfo + case "PENDING_VERIFICATION": self = .pendingVerification + case "VERIFICATION_FAILED": self = .verificationFailed + case "ACTIVE": self = .active + default: self = .unrecognized(wireValue: value) + } + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(jsonValue) + } +} + +/// What Apple still needs before it verifies a declaration. +public enum ComplianceRequiredAction: Sendable, Equatable, Hashable { + /// Assumed: verified with the app's next submission for review (design, Open question 10). + case appBinarySubmission + case unrecognized(wireValue: String) + + public init(wireValue: String) { + self = wireValue == "APP_BINARY_SUBMISSION" ? .appBinarySubmission : .unrecognized(wireValue: wireValue) + } + + var wireValue: String { + switch self { + case .appBinarySubmission: "APP_BINARY_SUBMISSION" + case .unrecognized(let wireValue): wireValue + } + } +} + +extension ComplianceRequiredAction: Codable { + public init(from decoder: any Decoder) throws { + self.init(wireValue: try decoder.singleValueContainer().decode(String.self)) + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.singleValueContainer() + try container.encode(wireValue) + } +} diff --git a/Sources/ASCKit/Iris/Compliance/IrisComplianceRepository.swift b/Sources/ASCKit/Iris/Compliance/IrisComplianceRepository.swift new file mode 100644 index 00000000..59fb9352 --- /dev/null +++ b/Sources/ASCKit/Iris/Compliance/IrisComplianceRepository.swift @@ -0,0 +1,12 @@ +import Mockable + +/// An app's compliance requirements and the declarations that answer them, through +/// the iris session (`ppm/compliancerequirements/v1`). There is no public API. +@Mockable +public protocol IrisComplianceRepository: Sendable { + /// Every requirement on the app's App Compliance page, answered or not, each with its declaration. + func listRequirements(session: IrisSession, appId: String) async throws -> [ComplianceRequirement] + /// Saves `answer` for `requirement` — a first answer, or a change to the one Apple holds — + /// and answers the requirement as it now stands. + func declare(session: IrisSession, requirement: ComplianceRequirement, answer: ComplianceAnswer) async throws -> ComplianceRequirement +} diff --git a/Sources/ASCKit/Shared/RESTPathResolver.swift b/Sources/ASCKit/Shared/RESTPathResolver.swift index dce57198..397045d9 100644 --- a/Sources/ASCKit/Shared/RESTPathResolver.swift +++ b/Sources/ASCKit/Shared/RESTPathResolver.swift @@ -29,12 +29,22 @@ public final class RESTPathResolver: @unchecked Sendable { /// action it wins over the parent, so `update --image-id X --library-id L` addresses /// `/asset-images/X` rather than the library's collection. public let resourceParam: String? + /// The flag naming a child that lives *under* its parent and is addressed by both + /// (e.g. `requirement-id` under `app-id`: the same requirement id names a row on every + /// app). An action on it resolves to `/{parentSegment}/{parent}/{segment}/{child}/{action}`. + public let nestedResourceParam: String? public init(parentParam: String, parentSegment: String, segment: String, resourceParam: String? = nil) { + self.init(parentParam: parentParam, parentSegment: parentSegment, segment: segment, + resourceParam: resourceParam, nestedResourceParam: nil) + } + + public init(parentParam: String, parentSegment: String, segment: String, resourceParam: String?, nestedResourceParam: String?) { self.parentParam = parentParam self.parentSegment = parentSegment self.segment = segment self.resourceParam = resourceParam + self.nestedResourceParam = nestedResourceParam } } @@ -52,11 +62,22 @@ public final class RESTPathResolver: @unchecked Sendable { public static func registerRoute( command: String, parentParam: String, parentSegment: String, segment: String, resourceParam: String? = nil ) { + register(command: command, route: Route(parentParam: parentParam, parentSegment: parentSegment, segment: segment, resourceParam: resourceParam)) + } + + /// Registers a child addressed under its parent by both ids — see `Route.nestedResourceParam`. + public static func registerRoute( + command: String, parentParam: String, parentSegment: String, segment: String, nestedResourceParam: String + ) { + register(command: command, route: Route(parentParam: parentParam, parentSegment: parentSegment, segment: segment, + resourceParam: nil, nestedResourceParam: nestedResourceParam)) + } + + private static func register(command: String, route: Route) { lock.lock() defer { lock.unlock() } - let route = Route(parentParam: parentParam, parentSegment: parentSegment, segment: segment, resourceParam: resourceParam) var existing = routes[command] ?? [] - if let index = existing.firstIndex(where: { $0.parentParam == parentParam }) { + if let index = existing.firstIndex(where: { $0.parentParam == route.parentParam }) { existing[index] = route } else { existing.append(route) @@ -85,6 +106,17 @@ public final class RESTPathResolver: @unchecked Sendable { // `add` attaches an existing resource to a parent's collection (e.g. an item to a // review submission), so it resolves like `create`: POST to the collection. if action != "list", action != "create", action != "add" { + // A child addressed under its parent by both ids. + for route in currentRoutes[command] ?? [] { + if let childParam = route.nestedResourceParam, let childId = params[childParam], + let parentId = params[route.parentParam] { + let child = "\(base)/\(route.parentSegment)/\(parentId)/\(route.segment)/\(childId)" + switch action { + case "get", "update", "delete", "remove": return child + default: return "\(child)/\(action)" + } + } + } // Action on this resource by its own id (e.g. `versions get --version-id v-1`). if let ownId = params["\(singularize(command))-id"] { return resourcePath(base: base, segment: command, id: ownId, action: action) @@ -203,6 +235,7 @@ public final class RESTPathResolver: @unchecked Sendable { _ = _gameCenterRoutes _ = _assetLibraryRoutes _ = _screenshotImportRoutes + _ = _complianceRoutes initialized = true } diff --git a/Tests/ASCKitTests/Iris/Compliance/ComplianceKindTests.swift b/Tests/ASCKitTests/Iris/Compliance/ComplianceKindTests.swift new file mode 100644 index 00000000..8e6b956f --- /dev/null +++ b/Tests/ASCKitTests/Iris/Compliance/ComplianceKindTests.swift @@ -0,0 +1,34 @@ +import Foundation +import Testing +@testable import ASCKit + +@Suite +struct ComplianceKindTests { + @Test func `should be the Security Assessment when Apple names the form SECURITYASF395E`() { + #expect(ComplianceKind(formName: "SECURITYASF395E") == .securityAssessment) + } + + @Test func `should be AI generated content when Apple names the form AIGENERATEFD1DE`() { + #expect(ComplianceKind(formName: "AIGENERATEFD1DE") == .aiGeneratedContent) + } + + @Test func `should keep a form it doesn't know, by Apple's name for it`() { + #expect(ComplianceKind(formName: "MEDICALDEV0001") == .unrecognized(formName: "MEDICALDEV0001")) + #expect(ComplianceKind(formName: "MEDICALDEV0001").isRecognized == false) + } + + @Test func `should be named as the App Compliance page names it`() { + #expect(ComplianceKind.securityAssessment.displayName == "Security Assessment") + #expect(ComplianceKind.aiGeneratedContent.displayName == "AI Generated or Synthetic Content") + #expect(ComplianceKind.unrecognized(formName: "MEDICALDEV0001").displayName == "MEDICALDEV0001") + } + + @Test func `should write each kind as one word in JSON and read it back`() throws { + let kinds: [ComplianceKind] = [.securityAssessment, .aiGeneratedContent, .unrecognized(formName: "MEDICALDEV0001")] + + let json = String(decoding: try JSONEncoder().encode(kinds), as: UTF8.self) + + #expect(json == #"["SECURITY_ASSESSMENT","AI_GENERATED_CONTENT","MEDICALDEV0001"]"#) + #expect(try JSONDecoder().decode([ComplianceKind].self, from: Data(json.utf8)) == kinds) + } +} diff --git a/Tests/ASCKitTests/Iris/Compliance/ComplianceRequirementTests.swift b/Tests/ASCKitTests/Iris/Compliance/ComplianceRequirementTests.swift new file mode 100644 index 00000000..adf7ac9a --- /dev/null +++ b/Tests/ASCKitTests/Iris/Compliance/ComplianceRequirementTests.swift @@ -0,0 +1,106 @@ +import Foundation +import Mockable +import Testing +@testable import ASCKit + +@Suite +struct ComplianceRequirementTests { + private let session = IrisSession(cookies: "myacinfo=a") + + private func requirement( + _ kind: ComplianceKind = .securityAssessment, + status: ComplianceStatus, + declaration: ComplianceDeclaration? = nil, + requiredActions: [ComplianceRequiredAction] = [] + ) -> ComplianceRequirement { + ComplianceRequirement( + id: "req-1", appId: "1234567890", kind: kind, regions: ["CHN"], isRequired: true, + status: status, updatedAt: declaration == nil ? nil : "2026-11-17T00:00:00.000Z", + requiredActions: requiredActions, declaration: declaration + ) + } + + // MARK: - affordances (law 5) + + @Test func `should offer to declare a requirement nobody has answered`() { + #expect(requirement(status: .missingInfo).affordances["declare"] + == "asc iris app-compliance declare --answer --app-id 1234567890 --requirement-id req-1") + } + + @Test func `should offer to change an active declaration and to resubmit a failed one`() { + let answered = ComplianceDeclaration(id: "form-1", answer: .no) + #expect(requirement(status: .active, declaration: answered).affordances["declare"] != nil) + #expect(requirement(status: .verificationFailed, declaration: answered).affordances["declare"] != nil) + } + + @Test func `should not offer to declare while Apple is verifying the answer`() { + let yes = ComplianceDeclaration(id: "form-1", answer: .yes) + #expect(requirement(status: .pendingVerification, declaration: yes).affordances["declare"] == nil) + } + + @Test func `should not offer to declare a kind it doesn't know`() { + #expect(requirement(.unrecognized(formName: "MEDICALDEV0001"), status: .missingInfo).affordances["declare"] == nil) + } + + @Test func `should always point back to the app's compliance list`() { + #expect(requirement(status: .active).affordances["listRequirements"] + == "asc iris app-compliance list --app-id 1234567890") + } + + @Test func `should link a declaration over REST under its app`() { + #expect(requirement(status: .missingInfo).apiLinks["declare"] + == APILink(href: "/api/v1/iris/apps/1234567890/compliance-requirements/req-1/declare", method: "POST")) + #expect(requirement(status: .missingInfo).apiLinks["listRequirements"] + == APILink(href: "/api/v1/iris/apps/1234567890/compliance-requirements", method: "GET")) + } + + // MARK: - declare (law 5, refused by the model before anything is sent) + + @Test func `should send a No to Apple through the repository`() async throws { + let declared = requirement(status: .active, declaration: ComplianceDeclaration(id: "form-1", answer: .no)) + let repo = MockIrisComplianceRepository() + given(repo).declare(session: .any, requirement: .any, answer: .value(.notOffered)).willReturn(declared) + + #expect(try await requirement(status: .missingInfo).declare(.notOffered, session: session, repo: repo) == declared) + } + + @Test func `should refuse to declare while Apple is verifying, sending nothing`() async { + let repo = MockIrisComplianceRepository() + + await #expect(throws: ComplianceError.notDeclarable(kind: .securityAssessment, status: .pendingVerification)) { + try await requirement(status: .pendingVerification, declaration: ComplianceDeclaration(id: "form-1", answer: .yes)) + .declare(.notOffered, session: session, repo: repo) + } + verify(repo).declare(session: .any, requirement: .any, answer: .any).called(0) + } + + @Test func `should say why a requirement can't be declared`() { + #expect(ComplianceError.notDeclarable(kind: .securityAssessment, status: .pendingVerification).description + == "Security Assessment can't be changed while it is Pending Verification: Apple is checking the last answer.") + #expect(ComplianceError.notDeclarable(kind: .unrecognized(formName: "MEDICALDEV0001"), status: .missingInfo).description + == "MEDICALDEV0001 is a compliance asc doesn't know yet, so it can't declare it. Answer it on the App Compliance page.") + } + + // MARK: - what it writes + + @Test func `should write a requirement the way the App Compliance page reads`() throws { + let row = requirement(status: .pendingVerification, declaration: ComplianceDeclaration(id: "form-1", answer: .yes), + requiredActions: [.appBinarySubmission]) + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + + #expect(String(decoding: try encoder.encode(row), as: UTF8.self) == #"{"appId":"1234567890","declaration":{"answer":"YES","id":"form-1"},"id":"req-1","isRequired":true,"kind":"SECURITY_ASSESSMENT","name":"Security Assessment","regions":["CHN"],"requiredActions":["APP_BINARY_SUBMISSION"],"status":"PENDING_VERIFICATION","updatedAt":"2026-11-17T00:00:00.000Z"}"#) + } + + @Test func `should leave out the declaration and date of a requirement nobody has answered`() throws { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + + #expect(String(decoding: try encoder.encode(requirement(status: .missingInfo)), as: UTF8.self) == #"{"appId":"1234567890","id":"req-1","isRequired":true,"kind":"SECURITY_ASSESSMENT","name":"Security Assessment","regions":["CHN"],"requiredActions":[],"status":"MISSING_INFO"}"#) + } + + @Test func `should keep a required action it has not seen`() { + #expect(ComplianceRequiredAction(wireValue: "APP_BINARY_SUBMISSION") == .appBinarySubmission) + #expect(ComplianceRequiredAction(wireValue: "SIGN_AGREEMENT") == .unrecognized(wireValue: "SIGN_AGREEMENT")) + } +} diff --git a/Tests/ASCKitTests/Iris/Compliance/ComplianceStatusTests.swift b/Tests/ASCKitTests/Iris/Compliance/ComplianceStatusTests.swift new file mode 100644 index 00000000..a994ccba --- /dev/null +++ b/Tests/ASCKitTests/Iris/Compliance/ComplianceStatusTests.swift @@ -0,0 +1,52 @@ +import Foundation +import Testing +@testable import ASCKit + +@Suite +struct ComplianceStatusTests { + @Test func `should show Missing Info for a requirement nobody has answered`() { + #expect(ComplianceStatus(wireValue: "PENDING_COLLECT") == .missingInfo) + } + + @Test func `should be pending verification while Apple checks a Yes`() { + #expect(ComplianceStatus(wireValue: "COLLECTED_VERIFY_PENDING") == .pendingVerification) + } + + @Test func `should be active once an answer needs no verification`() { + #expect(ComplianceStatus(wireValue: "COLLECTED_VERIFY_NOT_NECESSARY") == .active) + } + + @Test func `should keep a status it has not seen, never guessing`() { + #expect(ComplianceStatus(wireValue: "COLLECTED_VERIFY_REJECTED") == .unrecognized(wireValue: "COLLECTED_VERIFY_REJECTED")) + } + + @Test func `should let the app stay on sale only while active`() { + #expect(ComplianceStatus.active.isActive == true) + #expect(ComplianceStatus.missingInfo.isActive == false) + #expect(ComplianceStatus.pendingVerification.isActive == false) + } + + @Test func `should need the developer's action when info is missing or verification failed`() { + #expect(ComplianceStatus.missingInfo.needsAction == true) + #expect(ComplianceStatus.verificationFailed.needsAction == true) + #expect(ComplianceStatus.active.needsAction == false) + #expect(ComplianceStatus.pendingVerification.needsAction == false) + } + + @Test func `should be named as the STATUS column names it`() { + #expect(ComplianceStatus.missingInfo.displayName == "Missing Info") + #expect(ComplianceStatus.pendingVerification.displayName == "Pending Verification") + #expect(ComplianceStatus.verificationFailed.displayName == "Verification Failed") + #expect(ComplianceStatus.active.displayName == "Active") + #expect(ComplianceStatus.unrecognized(wireValue: "NEW_STATE").displayName == "NEW_STATE") + } + + @Test func `should write each status as one word in JSON and read it back`() throws { + let statuses: [ComplianceStatus] = [.missingInfo, .pendingVerification, .verificationFailed, .active, .unrecognized(wireValue: "NEW_STATE")] + + let json = String(decoding: try JSONEncoder().encode(statuses), as: UTF8.self) + + #expect(json == #"["MISSING_INFO","PENDING_VERIFICATION","VERIFICATION_FAILED","ACTIVE","NEW_STATE"]"#) + #expect(try JSONDecoder().decode([ComplianceStatus].self, from: Data(json.utf8)) == statuses) + } +} From 52e825355d58a46f5ccec566e4d371c3b329f7d3 Mon Sep 17 00:00:00 2001 From: slamhan Date: Thu, 19 Nov 2026 21:31:33 +0800 Subject: [PATCH 05/12] feat(app-compliance): read requirements and save a No through the iris session IrisSDKComplianceRepository talks to ppm/compliancerequirements/v1 through the IrisAPI role (IrisRequest builds the JSON requests; IrisAPI gains complianceGet/Post/Put, played by IrisClient), scoped by the team's publicProviderId from olympus. Read: the requirements and the declarations, joined so every requirement is a row and each declaration sits on the requirement it answers; an unknown compliance or status, and a declaration no requirement lists, are kept. Declare: the question's id from Apple's form, the draft re-asked with the answer picked, exactly the fields the form asks for saved (POST for a first answer, PUT on the declaration for a change), and the row read back. A read-only form is refused without saving; a 403 says the role can't edit App Compliance. Co-Authored-By: Claude Opus 5.5 --- .../Iris/Compliance/ComplianceError.swift | 12 + .../Compliance/Internal/ComplianceWire.swift | 109 +++++++ .../IrisSDKComplianceRepository.swift | 125 ++++++++ Sources/ASCKit/Iris/Internal/IrisAPI.swift | 5 + .../ASCKit/Iris/Internal/IrisRequest.swift | 20 ++ .../Iris/Internal/System/IrisClient.swift | 12 + .../IrisSDKComplianceRepositoryTests.swift | 284 ++++++++++++++++++ .../Iris/Internal/IrisRequestTests.swift | 33 ++ 8 files changed, 600 insertions(+) create mode 100644 Sources/ASCKit/Iris/Compliance/Internal/ComplianceWire.swift create mode 100644 Sources/ASCKit/Iris/Compliance/Internal/IrisSDKComplianceRepository.swift create mode 100644 Tests/ASCKitTests/Iris/Compliance/Internal/IrisSDKComplianceRepositoryTests.swift diff --git a/Sources/ASCKit/Iris/Compliance/ComplianceError.swift b/Sources/ASCKit/Iris/Compliance/ComplianceError.swift index e66d7110..d80b6e34 100644 --- a/Sources/ASCKit/Iris/Compliance/ComplianceError.swift +++ b/Sources/ASCKit/Iris/Compliance/ComplianceError.swift @@ -3,6 +3,12 @@ import Foundation public enum ComplianceError: Error, Equatable, Sendable, CustomStringConvertible, LocalizedError { /// Refused by the requirement itself, before anything reaches Apple (law 5). case notDeclarable(kind: ComplianceKind, status: ComplianceStatus) + /// The session doesn't say which team it belongs to (olympus gave no `publicProviderId`). + case teamUnknown + /// Apple serves the form without `editable` (law 5a): nothing was saved. + case readOnly(kind: ComplianceKind) + /// Apple forbade the save (403): the signed-in role can't edit App Compliance. + case roleCannotEdit(appId: String) public var description: String { switch self { @@ -10,6 +16,12 @@ public enum ComplianceError: Error, Equatable, Sendable, CustomStringConvertible "\(kind.displayName) is a compliance asc doesn't know yet, so it can't declare it. Answer it on the App Compliance page." case .notDeclarable(let kind, let status): "\(kind.displayName) can't be changed while it is \(status.displayName): Apple is checking the last answer." + case .readOnly(let kind): + "Apple won't take a change to \(kind.displayName) right now: the App Compliance page shows it read-only." + case .roleCannotEdit(let appId): + "Your App Store Connect role can't edit App Compliance for app \(appId). Ask your Account Holder or an Admin." + case .teamUnknown: + "Couldn't tell which team this App Store Connect session belongs to. Sign in again with `asc iris auth login`." } } diff --git a/Sources/ASCKit/Iris/Compliance/Internal/ComplianceWire.swift b/Sources/ASCKit/Iris/Compliance/Internal/ComplianceWire.swift new file mode 100644 index 00000000..3c0de0f3 --- /dev/null +++ b/Sources/ASCKit/Iris/Compliance/Internal/ComplianceWire.swift @@ -0,0 +1,109 @@ +import Foundation + +// The App Compliance service's JSON (`ppm/compliancerequirements/v1`), as captured in +// docs/features/app-compliance/design.md. Only what the domain reads is decoded. + +struct ComplianceRequirementsResponse: Decodable { + let data: [ComplianceRequirementResource] +} + +struct ComplianceRequirementResource: Decodable { + let id: String + let formName: String + let status: String + let isRequired: Bool? + let countries: [String]? + let formId: String? + let lastUpdatedDate: String? + let requiredActions: [String]? +} + +/// What a draft asks for: one constraint per field the current answers open. +struct ComplianceFormMetadata: Decodable { + let constraints: [String: ComplianceConstraint] + + /// The Yes/No question a form opens with: the field an empty draft is asked for. + var question: ComplianceConstraint? { + constraints.values.first { $0.presentation.inputType == "RADIO" } + } +} + +struct ComplianceConstraint: Decodable { + struct Presentation: Decodable { + let id: String + let inputType: String + } + + struct Validation: Decodable { + let required: Bool? + let editable: Bool? + } + + let presentation: Presentation + let validation: Validation? + + var id: String { presentation.id } + /// Apple marks a field `editable` only when it will take a change; a pending declaration has none. + var isEditable: Bool { validation?.editable == true } +} + +/// The draft Apple computes a form for (`…/metadata`). +struct ComplianceMetadataRequest: Encodable { + struct Draft: Encodable { + let fields: [ComplianceFieldValue] + } + + let accountId: String + let entityId: String + let requirementId: String + let form: Draft +} + +/// A declaration being saved: a first answer (`POST …/forms`) or a change (`PUT …/forms/{formId}`). +struct ComplianceSaveRequest: Encodable { + let accountId: String + let entityId: String + let requirementId: String + let formId: String? + let fields: [ComplianceFieldValue] +} + +struct ComplianceFormsResponse: Decodable { + let data: [ComplianceFormResource] +} + +struct ComplianceFormResponse: Decodable { + let data: ComplianceFormResource +} + +/// A declaration, which Apple calls a form. +struct ComplianceFormResource: Decodable { + let id: String + let requirementId: String + let formName: String + let fields: [ComplianceFieldValue] + let status: String? +} + +/// One answered field. A `RADIO` or `TEXT` holds `sValue`; a `FILE` holds `fileContent`. +struct ComplianceFieldValue: Codable, Equatable { + let id: String + let sValue: String? + + init(id: String, sValue: String) { + self.id = id + self.sValue = sValue + } +} + +extension ComplianceFormResource { + /// The answer to the form's first question, the Yes/No every form opens with. + /// Only a Yes opens further fields, so a form with more than that one is a Yes. + var answer: ComplianceDeclaration.Answer { + switch fields.first?.sValue { + case "YES": .yes + case "NO": .no + default: fields.count > 1 ? .yes : .no + } + } +} diff --git a/Sources/ASCKit/Iris/Compliance/Internal/IrisSDKComplianceRepository.swift b/Sources/ASCKit/Iris/Compliance/Internal/IrisSDKComplianceRepository.swift new file mode 100644 index 00000000..5cc3694a --- /dev/null +++ b/Sources/ASCKit/Iris/Compliance/Internal/IrisSDKComplianceRepository.swift @@ -0,0 +1,125 @@ +import Foundation + +/// `IrisComplianceRepository` over the App Compliance service. Every call is scoped by +/// the team's `publicProviderId`, which olympus gives for the session (law 6). +public struct IrisSDKComplianceRepository: IrisComplianceRepository { + private let api: any IrisAPI + private let accounts: any AppStoreConnectAccounts + + public init() { + self.init(api: IrisClient(), accounts: OlympusClient()) + } + + init(api: any IrisAPI, accounts: any AppStoreConnectAccounts) { + self.api = api + self.accounts = accounts + } + + public func listRequirements(session: IrisSession, appId: String) async throws -> [ComplianceRequirement] { + let team = try await teamId(for: session) + let (requirementsData, _) = try await api.complianceGet( + path: "accounts/\(team)/requirements", queryItems: [URLQueryItem(name: "entity_id", value: appId)], cookies: session.cookies + ) + let (formsData, _) = try await api.complianceGet( + path: "accounts/\(team)/entities/\(appId)/forms", queryItems: [], cookies: session.cookies + ) + let requirements = try JSONDecoder().decode(ComplianceRequirementsResponse.self, from: requirementsData).data + let forms = try JSONDecoder().decode(ComplianceFormsResponse.self, from: formsData).data + return Self.rows(requirements: requirements, forms: forms, appId: appId) + } + + /// Saves `answer` the way the App Compliance page does: ask Apple for the form, pick the + /// answer and ask again, then save exactly the fields the form asks for (laws 8, 10) — + /// a `POST` for a first answer, a `PUT` on the declaration for a change. + public func declare(session: IrisSession, requirement: ComplianceRequirement, answer: ComplianceAnswer) async throws -> ComplianceRequirement { + let team = try await teamId(for: session) + let entity = "accounts/\(team)/entities/\(requirement.appId)" + + // The question's id comes from Apple's form, never from asc (law 8). + let empty = try await metadata(for: [], requirement: requirement, team: team, session: session) + guard let question = empty.question, question.isEditable else { + throw ComplianceError.readOnly(kind: requirement.kind) + } + let draft = [ComplianceFieldValue(id: question.id, sValue: answer.wireValue)] + let picked = try await metadata(for: draft, requirement: requirement, team: team, session: session) + let fields = draft.filter { picked.constraints[$0.id] != nil } + + let body = try Self.encoder.encode(ComplianceSaveRequest( + accountId: team, entityId: requirement.appId, requirementId: requirement.id, + formId: requirement.declaration?.id, fields: fields + )) + do { + if let formId = requirement.declaration?.id { + _ = try await api.compliancePut(path: "\(entity)/forms/\(formId)", body: body, cookies: session.cookies) + } else { + _ = try await api.compliancePost(path: "\(entity)/forms", body: body, cookies: session.cookies) + } + } catch IrisAPIError.httpError(statusCode: 403, _) { + throw ComplianceError.roleCannotEdit(appId: requirement.appId) + } + + let rows = try await listRequirements(session: session, appId: requirement.appId) + return rows.first { $0.id == requirement.id } ?? requirement + } + + private func metadata( + for fields: [ComplianceFieldValue], requirement: ComplianceRequirement, team: String, session: IrisSession + ) async throws -> ComplianceFormMetadata { + let body = try Self.encoder.encode(ComplianceMetadataRequest( + accountId: team, entityId: requirement.appId, requirementId: requirement.id, form: .init(fields: fields) + )) + let (data, _) = try await api.compliancePost( + path: "accounts/\(team)/entities/\(requirement.appId)/requirements/\(requirement.id)/metadata", + body: body, cookies: session.cookies + ) + return try JSONDecoder().decode(ComplianceFormMetadata.self, from: data) + } + + private static let encoder: JSONEncoder = { + let encoder = JSONEncoder() + encoder.outputFormatting = [.sortedKeys] + return encoder + }() + + /// Every requirement is a row, answered or not, with the form whose `requirementId` is + /// its id (law 7). A form no requirement lists is still a row, but one that can't be + /// declared: there is no requirement to save it against (law 4). + static func rows(requirements: [ComplianceRequirementResource], forms: [ComplianceFormResource], appId: String) -> [ComplianceRequirement] { + let formsByRequirement = Dictionary(forms.map { ($0.requirementId, $0) }, uniquingKeysWith: { first, _ in first }) + let listed = requirements.map { requirement in + ComplianceRequirement( + id: requirement.id, + appId: appId, + kind: ComplianceKind(formName: requirement.formName), + regions: requirement.countries ?? [], + isRequired: requirement.isRequired ?? false, + status: ComplianceStatus(wireValue: requirement.status), + updatedAt: requirement.lastUpdatedDate, + requiredActions: (requirement.requiredActions ?? []).map(ComplianceRequiredAction.init(wireValue:)), + declaration: formsByRequirement[requirement.id].map { ComplianceDeclaration(id: $0.id, answer: $0.answer) } + ) + } + let listedIds = Set(requirements.map(\.id)) + let orphans = forms.filter { !listedIds.contains($0.requirementId) }.map { form in + ComplianceRequirement( + id: form.requirementId, + appId: appId, + kind: .unrecognized(formName: form.formName), + regions: [], + isRequired: false, + status: form.status.map(ComplianceStatus.init(wireValue:)) ?? .unrecognized(wireValue: ""), + updatedAt: nil, + requiredActions: [], + declaration: ComplianceDeclaration(id: form.id, answer: form.answer) + ) + } + return listed + orphans + } + + private func teamId(for session: IrisSession) async throws -> String { + guard let team = try await accounts.fetchSession(cookies: session.cookies).teamId, !team.isEmpty else { + throw ComplianceError.teamUnknown + } + return team + } +} diff --git a/Sources/ASCKit/Iris/Internal/IrisAPI.swift b/Sources/ASCKit/Iris/Internal/IrisAPI.swift index 2e6caf70..a4c7949c 100644 --- a/Sources/ASCKit/Iris/Internal/IrisAPI.swift +++ b/Sources/ASCKit/Iris/Internal/IrisAPI.swift @@ -10,6 +10,11 @@ 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) + + // The App Compliance service, `ppm/compliancerequirements/v1`, with the same session. + func complianceGet(path: String, queryItems: [URLQueryItem], cookies: String) async throws -> (Data, HTTPURLResponse) + func compliancePost(path: String, body: Data, cookies: String) async throws -> (Data, HTTPURLResponse) + func compliancePut(path: String, body: Data, cookies: String) async throws -> (Data, HTTPURLResponse) } extension IrisAPI { diff --git a/Sources/ASCKit/Iris/Internal/IrisRequest.swift b/Sources/ASCKit/Iris/Internal/IrisRequest.swift index 11571248..08b3330e 100644 --- a/Sources/ASCKit/Iris/Internal/IrisRequest.swift +++ b/Sources/ASCKit/Iris/Internal/IrisRequest.swift @@ -33,6 +33,26 @@ enum IrisRequest { return request } + static let complianceBaseURL = "https://appstoreconnect.apple.com/ppm/compliancerequirements/v1" + + /// A request to the App Compliance service (`ppm/compliancerequirements/v1`): plain JSON, + /// the same session cookies and browser headers as iris. + static func compliance(method: String, path: String, queryItems: [URLQueryItem], body: Data?, cookies: String) -> URLRequest { + var components = URLComponents(string: "\(complianceBaseURL)/\(path)")! + if !queryItems.isEmpty { + components.queryItems = queryItems + } + var request = URLRequest(url: components.url!) + request.httpMethod = method + request.httpBody = body + request.setValue("application/json", forHTTPHeaderField: "accept") + request.setValue("application/json", forHTTPHeaderField: "content-type") + request.setValue(cookies, forHTTPHeaderField: "cookie") + request.setValue(userAgent, forHTTPHeaderField: "user-agent") + request.setValue("[asc-ui]", forHTTPHeaderField: "x-csrf-itc") + return request + } + private static func iris(url: URL, method: String, cookies: String) -> URLRequest { var request = URLRequest(url: url) request.httpMethod = method diff --git a/Sources/ASCKit/Iris/Internal/System/IrisClient.swift b/Sources/ASCKit/Iris/Internal/System/IrisClient.swift index c703ab99..aca19f93 100644 --- a/Sources/ASCKit/Iris/Internal/System/IrisClient.swift +++ b/Sources/ASCKit/Iris/Internal/System/IrisClient.swift @@ -27,6 +27,18 @@ public struct IrisClient: IrisAPI { try await perform(IrisRequest.delete(path: path, 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)) + } + + public func compliancePost(path: String, body: Data, cookies: String) async throws -> (Data, HTTPURLResponse) { + try await perform(IrisRequest.compliance(method: "POST", path: path, queryItems: [], body: body, cookies: cookies)) + } + + public func compliancePut(path: String, body: Data, cookies: String) async throws -> (Data, HTTPURLResponse) { + try await perform(IrisRequest.compliance(method: "PUT", path: path, queryItems: [], body: body, cookies: cookies)) + } + private func perform(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { let (data, response) = try await session.data(for: request) return try IrisResponse.accepted(data: data, response: response) diff --git a/Tests/ASCKitTests/Iris/Compliance/Internal/IrisSDKComplianceRepositoryTests.swift b/Tests/ASCKitTests/Iris/Compliance/Internal/IrisSDKComplianceRepositoryTests.swift new file mode 100644 index 00000000..2984a237 --- /dev/null +++ b/Tests/ASCKitTests/Iris/Compliance/Internal/IrisSDKComplianceRepositoryTests.swift @@ -0,0 +1,284 @@ +import Foundation +import Mockable +import Testing +@testable import ASCKit + +/// Fixtures are the captured responses in docs/features/app-compliance/design.md, ids replaced. +@Suite +struct IrisSDKComplianceRepositoryTests { + private let session = IrisSession(cookies: "myacinfo=a") + + private func ok(_ json: String) -> (Data, HTTPURLResponse) { + (Data(json.utf8), HTTPURLResponse(url: URL(string: "https://appstoreconnect.apple.com")!, statusCode: 200, httpVersion: nil, headerFields: nil)!) + } + + private func signedInTo(team: String?) -> MockAppStoreConnectAccounts { + let accounts = MockAppStoreConnectAccounts() + given(accounts).fetchSession(cookies: .value("myacinfo=a")) + .willReturn(OlympusClient.OlympusSession(providerID: 42, teamId: team, userEmail: "dev@example.com")) + return accounts + } + + private func iris(requirements: String, forms: String) -> MockIrisAPI { + let api = MockIrisAPI() + given(api).complianceGet( + path: .value("accounts/team-uuid/requirements"), + queryItems: .value([URLQueryItem(name: "entity_id", value: "1234567890")]), + cookies: .value("myacinfo=a") + ).willReturn(ok(requirements)) + given(api).complianceGet( + path: .value("accounts/team-uuid/entities/1234567890/forms"), queryItems: .value([]), cookies: .value("myacinfo=a") + ).willReturn(ok(forms)) + return api + } + + private let unanswered = #""" + { "data": [ + { "id": "req-1", "formName": "SECURITYASF395E", "entityId": "1234567890", "entityType": "APP", + "status": "PENDING_COLLECT", "isRequired": true, "countries": [ "CHN" ] }, + { "id": "req-2", "formName": "AIGENERATEFD1DE", "entityId": "1234567890", "entityType": "APP", + "status": "PENDING_COLLECT", "isRequired": true, "countries": [ "CHN" ] } + ] } + """# + + @Test func `should list every requirement nobody has answered as Missing Info`() async throws { + let repo = IrisSDKComplianceRepository(api: iris(requirements: unanswered, forms: #"{ "data": [] }"#), accounts: signedInTo(team: "team-uuid")) + + let rows = try await repo.listRequirements(session: session, appId: "1234567890") + + #expect(rows == [ + ComplianceRequirement(id: "req-1", appId: "1234567890", kind: .securityAssessment, regions: ["CHN"], isRequired: true, + status: .missingInfo, updatedAt: nil, requiredActions: [], declaration: nil), + ComplianceRequirement(id: "req-2", appId: "1234567890", kind: .aiGeneratedContent, regions: ["CHN"], isRequired: true, + status: .missingInfo, updatedAt: nil, requiredActions: [], declaration: nil), + ]) + } + + @Test func `should attach each declaration to the requirement it answers`() async throws { + let requirements = #""" + { "data": [ + { "id": "req-1", "formName": "SECURITYASF395E", "entityId": "1234567890", "entityType": "APP", + "status": "COLLECTED_VERIFY_PENDING", "isRequired": true, "countries": [ "CHN" ], "formId": "form-1", + "dateSigned": "2026-01-01T00:00:00.000Z", "lastUpdatedDate": "2026-01-02T00:00:00.000Z", + "requiredActions": [ "APP_BINARY_SUBMISSION" ] }, + { "id": "req-2", "formName": "AIGENERATEFD1DE", "entityId": "1234567890", "entityType": "APP", + "status": "COLLECTED_VERIFY_NOT_NECESSARY", "isRequired": true, "countries": [ "CHN" ], "formId": "form-2", + "dateSigned": "2026-01-03T00:00:00.000Z", "lastUpdatedDate": "2026-01-03T00:00:00.000Z" } + ] } + """# + let forms = #""" + { "data": [ + { "id": "form-2", "requirementId": "req-2", "formName": "AIGENERATEFD1DE", + "fields": [ { "id": "aigc-offers", "sValue": "NO", "verificationStatus": "FIELD_VERIFY_NOT_NECESSARY" } ], + "status": "COLLECTED_VERIFY_NOT_NECESSARY", "createdAt": "1790000000000", "updatedAt": "1790000000000" }, + { "id": "form-1", "requirementId": "req-1", "formName": "SECURITYASF395E", + "fields": [ + { "id": "field-1", "sValue": "YES", "verificationStatus": "FIELD_VERIFY_NOT_NECESSARY" }, + { "id": "field-2", "verificationStatus": "FIELD_VERIFY_PENDING", + "fileContent": { "fileId": "file-1", "fileName": "proof.png", "fileType": "image/png", "fileSizeBytes": "34188" } } + ], + "status": "COLLECTED_VERIFY_PENDING", "createdAt": "1790000000000", "updatedAt": "1790000000000" } + ] } + """# + let repo = IrisSDKComplianceRepository(api: iris(requirements: requirements, forms: forms), accounts: signedInTo(team: "team-uuid")) + + let rows = try await repo.listRequirements(session: session, appId: "1234567890") + + #expect(rows == [ + ComplianceRequirement(id: "req-1", appId: "1234567890", kind: .securityAssessment, regions: ["CHN"], isRequired: true, + status: .pendingVerification, updatedAt: "2026-01-02T00:00:00.000Z", + requiredActions: [.appBinarySubmission], declaration: ComplianceDeclaration(id: "form-1", answer: .yes)), + ComplianceRequirement(id: "req-2", appId: "1234567890", kind: .aiGeneratedContent, regions: ["CHN"], isRequired: true, + status: .active, updatedAt: "2026-01-03T00:00:00.000Z", + requiredActions: [], declaration: ComplianceDeclaration(id: "form-2", answer: .no)), + ]) + } + + @Test func `should keep a compliance and a status it doesn't know`() async throws { + let requirements = #""" + { "data": [ { "id": "req-9", "formName": "MEDICALDEV0001", "entityId": "1234567890", "entityType": "APP", + "status": "COLLECTED_VERIFY_REJECTED", "isRequired": false, "countries": [ "CHN", "HKG" ] } ] } + """# + let repo = IrisSDKComplianceRepository(api: iris(requirements: requirements, forms: #"{ "data": [] }"#), accounts: signedInTo(team: "team-uuid")) + + let rows = try await repo.listRequirements(session: session, appId: "1234567890") + + #expect(rows == [ + ComplianceRequirement(id: "req-9", appId: "1234567890", kind: .unrecognized(formName: "MEDICALDEV0001"), + regions: ["CHN", "HKG"], isRequired: false, + status: .unrecognized(wireValue: "COLLECTED_VERIFY_REJECTED"), + updatedAt: nil, requiredActions: [], declaration: nil), + ]) + } + + @Test func `should keep a declaration no requirement lists, as a row it won't declare`() async throws { + let forms = #""" + { "data": [ { "id": "form-7", "requirementId": "req-7", "formName": "SECURITYASF395E", + "fields": [ { "id": "field-1", "sValue": "NO" } ], "status": "COLLECTED_VERIFY_NOT_NECESSARY" } ] } + """# + let repo = IrisSDKComplianceRepository(api: iris(requirements: #"{ "data": [] }"#, forms: forms), accounts: signedInTo(team: "team-uuid")) + + let rows = try await repo.listRequirements(session: session, appId: "1234567890") + + #expect(rows == [ + ComplianceRequirement(id: "req-7", appId: "1234567890", kind: .unrecognized(formName: "SECURITYASF395E"), + regions: [], isRequired: false, status: .active, updatedAt: nil, requiredActions: [], + declaration: ComplianceDeclaration(id: "form-7", answer: .no)), + ]) + #expect(rows[0].isDeclarable == false) + } + + @Test func `should refuse to list when the session names no team`() async { + let repo = IrisSDKComplianceRepository(api: MockIrisAPI(), accounts: signedInTo(team: nil)) + + await #expect(throws: ComplianceError.teamUnknown) { + try await repo.listRequirements(session: session, appId: "1234567890") + } + } +} + +/// `declare` with a No, against the captured metadata and save calls. +@Suite +struct IrisSDKComplianceDeclareTests { + private let session = IrisSession(cookies: "myacinfo=a") + private let forms = "accounts/team-uuid/entities/1234567890/forms" + private let metadata = "accounts/team-uuid/entities/1234567890/requirements/req-1/metadata" + + private func reply(_ status: Int, _ json: String) -> (Data, HTTPURLResponse) { + (Data(json.utf8), HTTPURLResponse(url: URL(string: "https://appstoreconnect.apple.com")!, statusCode: status, httpVersion: nil, headerFields: nil)!) + } + + private func accounts() -> MockAppStoreConnectAccounts { + let accounts = MockAppStoreConnectAccounts() + given(accounts).fetchSession(cookies: .any) + .willReturn(OlympusClient.OlympusSession(providerID: 42, teamId: "team-uuid", userEmail: "dev@example.com")) + return accounts + } + + /// The Security Assessment question, as the metadata gives it; `editable` only when Apple allows a change. + private func question(editable: Bool) -> String { + #""" + { "formName": "SECURITYASF395E", "formMode": "MODAL", "form": {}, + "constraints": { "field-1": { + "presentation": { "id": "field-1", "inputType": "RADIO", + "label": "PPM.compliance.form.SECURITYASF395E.field.doesyourap2852f.label", + "options": [ { "valueId": "YES" }, { "valueId": "NO" } ], "valueDeterminesMetadata": true }, + "validation": { "required": true\#(editable ? #", "editable": true"# : "") } } } } + """# + } + + private func savedRow(status: String, formId: String) -> String { + #""" + { "data": [ { "id": "req-1", "formName": "SECURITYASF395E", "entityId": "1234567890", "entityType": "APP", + "status": "\#(status)", "isRequired": true, "countries": [ "CHN" ], "formId": "\#(formId)", + "lastUpdatedDate": "2026-11-19T00:00:00.000Z" } ] } + """# + } + + /// Apple, as the App Compliance page meets it: the metadata for any draft, the save, and the list after it. + private func apple(editable: Bool = true, saveStatus: Int = 200, formId: String = "form-1") -> MockIrisAPI { + let api = MockIrisAPI() + given(api).compliancePost(path: .value(metadata), body: .any, cookies: .value("myacinfo=a")) + .willReturn(reply(200, question(editable: editable))) + let saved = #"{ "data": { "id": "\#(formId)", "requirementId": "req-1", "formName": "SECURITYASF395E", "fields": [ { "id": "field-1", "sValue": "NO" } ], "status": "COLLECTED_VERIFY_NOT_NECESSARY" } }"# + if saveStatus == 200 { + given(api).compliancePost(path: .value(forms), body: .any, cookies: .value("myacinfo=a")).willReturn(reply(200, saved)) + given(api).compliancePut(path: .value("\(forms)/form-1"), body: .any, cookies: .value("myacinfo=a")).willReturn(reply(200, saved)) + } else { + // IrisAPI answers a refusal by throwing, as IrisClient does. + let refusal = IrisAPIError.httpError(statusCode: saveStatus, body: "Forbidden") + given(api).compliancePost(path: .value(forms), body: .any, cookies: .value("myacinfo=a")).willThrow(refusal) + given(api).compliancePut(path: .value("\(forms)/form-1"), body: .any, cookies: .value("myacinfo=a")).willThrow(refusal) + } + given(api).complianceGet(path: .value("accounts/team-uuid/requirements"), queryItems: .any, cookies: .any) + .willReturn(reply(200, savedRow(status: "COLLECTED_VERIFY_NOT_NECESSARY", formId: formId))) + given(api).complianceGet(path: .value(forms), queryItems: .any, cookies: .any) + .willReturn(reply(200, "{ \"data\": [ \(saved.dropFirst(10).dropLast(2)) ] }")) + return api + } + + private func requirement(declaration: ComplianceDeclaration? = nil, status: ComplianceStatus = .missingInfo) -> ComplianceRequirement { + ComplianceRequirement(id: "req-1", appId: "1234567890", kind: .securityAssessment, regions: ["CHN"], isRequired: true, + status: status, updatedAt: nil, requiredActions: [], declaration: declaration) + } + + private let answeredNo = ComplianceRequirement( + id: "req-1", appId: "1234567890", kind: .securityAssessment, regions: ["CHN"], isRequired: true, + status: .active, updatedAt: "2026-11-19T00:00:00.000Z", requiredActions: [], + declaration: ComplianceDeclaration(id: "form-1", answer: .no) + ) + + @Test func `should answer No for the first time and show the requirement active`() async throws { + let api = apple() + + let row = try await IrisSDKComplianceRepository(api: api, accounts: accounts()) + .declare(session: session, requirement: requirement(), answer: .notOffered) + + #expect(row == answeredNo) + verify(api).compliancePost( + path: .value(forms), + body: .value(Data(#"{"accountId":"team-uuid","entityId":"1234567890","fields":[{"id":"field-1","sValue":"NO"}],"requirementId":"req-1"}"#.utf8)), + cookies: .any + ).called(1) + } + + @Test func `should ask Apple for the form, first empty and then with No picked, before saving`() async throws { + let api = apple() + + _ = try await IrisSDKComplianceRepository(api: api, accounts: accounts()) + .declare(session: session, requirement: requirement(), answer: .notOffered) + + verify(api).compliancePost( + path: .value(metadata), + body: .value(Data(#"{"accountId":"team-uuid","entityId":"1234567890","form":{"fields":[]},"requirementId":"req-1"}"#.utf8)), + cookies: .any + ).called(1) + verify(api).compliancePost( + path: .value(metadata), + body: .value(Data(#"{"accountId":"team-uuid","entityId":"1234567890","form":{"fields":[{"id":"field-1","sValue":"NO"}]},"requirementId":"req-1"}"#.utf8)), + cookies: .any + ).called(1) + } + + @Test func `should change an answered requirement in place, keeping its declaration`() async throws { + let api = apple() + + let row = try await IrisSDKComplianceRepository(api: api, accounts: accounts()) + .declare(session: session, requirement: requirement(declaration: ComplianceDeclaration(id: "form-1", answer: .no), status: .active), + answer: .notOffered) + + #expect(row == answeredNo) + verify(api).compliancePut( + path: .value("\(forms)/form-1"), + body: .value(Data(#"{"accountId":"team-uuid","entityId":"1234567890","fields":[{"id":"field-1","sValue":"NO"}],"formId":"form-1","requirementId":"req-1"}"#.utf8)), + cookies: .any + ).called(1) + verify(api).compliancePost(path: .value(forms), body: .any, cookies: .any).called(0) + } + + @Test func `should refuse without saving when Apple serves the form read-only`() async { + let api = apple(editable: false) + + await #expect(throws: ComplianceError.readOnly(kind: .securityAssessment)) { + try await IrisSDKComplianceRepository(api: api, accounts: accounts()) + .declare(session: session, requirement: requirement(), answer: .notOffered) + } + verify(api).compliancePost(path: .value(forms), body: .any, cookies: .any).called(0) + } + + @Test func `should say the role can't edit App Compliance when Apple forbids the save`() async { + let api = apple(saveStatus: 403) + + await #expect(throws: ComplianceError.roleCannotEdit(appId: "1234567890")) { + try await IrisSDKComplianceRepository(api: api, accounts: accounts()) + .declare(session: session, requirement: requirement(), answer: .notOffered) + } + } + + @Test func `should explain a read-only form and a forbidden save`() { + #expect(ComplianceError.readOnly(kind: .securityAssessment).description + == "Apple won't take a change to Security Assessment right now: the App Compliance page shows it read-only.") + #expect(ComplianceError.roleCannotEdit(appId: "1234567890").description + == "Your App Store Connect role can't edit App Compliance for app 1234567890. Ask your Account Holder or an Admin.") + } +} diff --git a/Tests/ASCKitTests/Iris/Internal/IrisRequestTests.swift b/Tests/ASCKitTests/Iris/Internal/IrisRequestTests.swift index 57189d54..88aa1675 100644 --- a/Tests/ASCKitTests/Iris/Internal/IrisRequestTests.swift +++ b/Tests/ASCKitTests/Iris/Internal/IrisRequestTests.swift @@ -49,6 +49,39 @@ struct IrisRequestTests { } } +@Suite +struct IrisComplianceRequestTests { + @Test func `should ask the compliance service for JSON with the session cookies`() { + let request = IrisRequest.compliance( + method: "GET", path: "accounts/team-1/requirements", + queryItems: [URLQueryItem(name: "entity_id", value: "1234567890")], body: nil, cookies: "myacinfo=abc" + ) + + #expect(request.url?.absoluteString + == "https://appstoreconnect.apple.com/ppm/compliancerequirements/v1/accounts/team-1/requirements?entity_id=1234567890") + #expect(request.httpMethod == "GET") + #expect(request.value(forHTTPHeaderField: "accept") == "application/json") + #expect(request.value(forHTTPHeaderField: "content-type") == "application/json") + #expect(request.value(forHTTPHeaderField: "cookie") == "myacinfo=abc") + #expect(request.value(forHTTPHeaderField: "x-csrf-itc") == "[asc-ui]") + #expect(request.value(forHTTPHeaderField: "user-agent") == IrisRequest.userAgent) + #expect(request.httpBody == nil) + } + + @Test func `should send a declaration as the body of a save`() { + let body = Data(#"{"fields":[]}"#.utf8) + + let request = IrisRequest.compliance( + method: "PUT", path: "accounts/team-1/entities/1234567890/forms/form-1", queryItems: [], body: body, cookies: "c" + ) + + #expect(request.url?.absoluteString + == "https://appstoreconnect.apple.com/ppm/compliancerequirements/v1/accounts/team-1/entities/1234567890/forms/form-1") + #expect(request.httpMethod == "PUT") + #expect(request.httpBody == body) + } +} + @Suite struct IrisResponseTests { private let url = URL(string: "https://appstoreconnect.apple.com/iris/v1/apps")! From 7aec7fa586d077e4f846fd0c470ec26300aa5493 Mon Sep 17 00:00:00 2001 From: slamhan Date: Thu, 19 Nov 2026 21:34:01 +0800 Subject: [PATCH 06/12] feat(app-compliance): asc iris app-compliance list / declare --answer no, and REST MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit asc iris app-compliance list --app-id A lists every requirement on the app's App Compliance page with its next commands; declare --app-id A --requirement-id R --answer no answers one, refused by the requirement while Apple verifies it. Both ship over REST: GET /api/v1/iris/apps/:appId/compliance-requirements and POST …/:requirementId/declare {"answer":"no"}, each refusal answered with its own words (404, 403, 401, 409). A row is found by requirement id and app together, in one place on the repository. Co-Authored-By: Claude Opus 5.5 --- Sources/ASCCommand/ClientProvider.swift | 4 + .../Compliance/IrisAppComplianceCommand.swift | 26 ++++ .../Compliance/IrisAppComplianceDeclare.swift | 32 +++++ .../Compliance/IrisAppComplianceList.swift | 23 ++++ .../Commands/Iris/IrisCommand.swift | 1 + .../IrisAppComplianceController.swift | 55 ++++++++ .../ASCCommand/Commands/Web/RESTRoutes.swift | 4 + .../Iris/Compliance/ComplianceError.swift | 4 + .../Compliance/IrisComplianceRepository.swift | 11 ++ .../Shared/Internal/ClientFactory.swift | 4 + .../Compliance/IrisAppComplianceTests.swift | 124 ++++++++++++++++++ .../IrisAppComplianceRoutesTests.swift | 72 ++++++++++ 12 files changed, 360 insertions(+) create mode 100644 Sources/ASCCommand/Commands/Iris/Compliance/IrisAppComplianceCommand.swift create mode 100644 Sources/ASCCommand/Commands/Iris/Compliance/IrisAppComplianceDeclare.swift create mode 100644 Sources/ASCCommand/Commands/Iris/Compliance/IrisAppComplianceList.swift create mode 100644 Sources/ASCCommand/Commands/Web/Controllers/IrisAppComplianceController.swift create mode 100644 Tests/ASCCommandTests/Commands/Iris/Compliance/IrisAppComplianceTests.swift create mode 100644 Tests/ASCCommandTests/Commands/Web/Controllers/IrisAppComplianceRoutesTests.swift diff --git a/Sources/ASCCommand/ClientProvider.swift b/Sources/ASCCommand/ClientProvider.swift index c590291f..44256597 100644 --- a/Sources/ASCCommand/ClientProvider.swift +++ b/Sources/ASCCommand/ClientProvider.swift @@ -444,6 +444,10 @@ struct ClientProvider { ClientFactory().makeIrisResolutionCenterRepository() } + static func makeIrisComplianceRepository() -> any IrisComplianceRepository { + ClientFactory().makeIrisComplianceRepository() + } + static func makeIrisCookieProvider() -> any IrisCookieProvider { ClientFactory().makeIrisCookieProvider() } diff --git a/Sources/ASCCommand/Commands/Iris/Compliance/IrisAppComplianceCommand.swift b/Sources/ASCCommand/Commands/Iris/Compliance/IrisAppComplianceCommand.swift new file mode 100644 index 00000000..6f66f8e0 --- /dev/null +++ b/Sources/ASCCommand/Commands/Iris/Compliance/IrisAppComplianceCommand.swift @@ -0,0 +1,26 @@ +import ArgumentParser +import ASCKit + +/// `asc iris app-compliance` — the app's App Compliance page (China mainland Security +/// Assessment, AI generated content). Iris private API only: there is no public endpoint. +struct IrisAppComplianceCommand: AsyncParsableCommand { + static let configuration = CommandConfiguration( + commandName: "app-compliance", + abstract: "List and answer an app's App Compliance requirements (iris session)", + subcommands: [IrisAppComplianceList.self, IrisAppComplianceDeclare.self] + ) +} + +/// The Yes or No a developer gives on the command line or in a REST body. +enum DeclaredAnswerArgument: String, ExpressibleByArgument, CaseIterable { + case yes + case no + + /// The answer to send. A Yes needs evidence (not yet supported), so only No is sent. + func answer() throws -> ComplianceAnswer { + switch self { + case .no: return .notOffered + case .yes: throw ValidationError("Answering yes needs evidence asc can't send yet. Answer yes on the App Compliance page.") + } + } +} diff --git a/Sources/ASCCommand/Commands/Iris/Compliance/IrisAppComplianceDeclare.swift b/Sources/ASCCommand/Commands/Iris/Compliance/IrisAppComplianceDeclare.swift new file mode 100644 index 00000000..9dd2e080 --- /dev/null +++ b/Sources/ASCCommand/Commands/Iris/Compliance/IrisAppComplianceDeclare.swift @@ -0,0 +1,32 @@ +import ArgumentParser +import ASCKit + +struct IrisAppComplianceDeclare: AsyncParsableCommand { + static let configuration = CommandConfiguration( + commandName: "declare", + abstract: "Answer an App Compliance requirement", + discussion: "--answer no declares the app doesn't offer the regulated feature in the region (or it is disabled or geoblocked there)." + ) + + @OptionGroup var globals: GlobalOptions + + @Option(name: .long, help: "App ID") + var appId: String + + @Option(name: .long, help: "Requirement ID, from `asc iris app-compliance list`") + var requirementId: String + + @Option(name: .long, help: "yes or no") + var answer: DeclaredAnswerArgument + + func run() async throws { + print(try await execute(cookieProvider: ClientProvider.makeIrisCookieProvider(), repo: ClientProvider.makeIrisComplianceRepository())) + } + + func execute(cookieProvider: any IrisCookieProvider, repo: any IrisComplianceRepository, affordanceMode: AffordanceMode = .cli) async throws -> String { + let session = try cookieProvider.resolveSession() + let requirement = try await repo.requirement(requirementId, appId: appId, session: session) + let declared = try await requirement.declare(try answer.answer(), session: session, repo: repo) + return try OutputFormatter(format: globals.outputFormat, pretty: globals.pretty).formatAgentItems([declared], affordanceMode: affordanceMode) + } +} diff --git a/Sources/ASCCommand/Commands/Iris/Compliance/IrisAppComplianceList.swift b/Sources/ASCCommand/Commands/Iris/Compliance/IrisAppComplianceList.swift new file mode 100644 index 00000000..a6f7b1fb --- /dev/null +++ b/Sources/ASCCommand/Commands/Iris/Compliance/IrisAppComplianceList.swift @@ -0,0 +1,23 @@ +import ArgumentParser +import ASCKit + +struct IrisAppComplianceList: AsyncParsableCommand { + static let configuration = CommandConfiguration( + commandName: "list", + abstract: "List every App Compliance requirement for an app, answered or not" + ) + + @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.makeIrisComplianceRepository())) + } + + func execute(cookieProvider: any IrisCookieProvider, repo: any IrisComplianceRepository, affordanceMode: AffordanceMode = .cli) async throws -> String { + let rows = try await repo.listRequirements(session: try cookieProvider.resolveSession(), appId: appId) + return try OutputFormatter(format: globals.outputFormat, pretty: globals.pretty).formatAgentItems(rows, affordanceMode: affordanceMode) + } +} diff --git a/Sources/ASCCommand/Commands/Iris/IrisCommand.swift b/Sources/ASCCommand/Commands/Iris/IrisCommand.swift index 92d1162d..542668e8 100644 --- a/Sources/ASCCommand/Commands/Iris/IrisCommand.swift +++ b/Sources/ASCCommand/Commands/Iris/IrisCommand.swift @@ -9,6 +9,7 @@ struct IrisCommand: AsyncParsableCommand { IrisAppsCommand.self, IrisIAPSubmissionsCommand.self, IrisResolutionCenterCommand.self, + IrisAppComplianceCommand.self, IrisAuthCommand.self, ] ) diff --git a/Sources/ASCCommand/Commands/Web/Controllers/IrisAppComplianceController.swift b/Sources/ASCCommand/Commands/Web/Controllers/IrisAppComplianceController.swift new file mode 100644 index 00000000..37bd1a7e --- /dev/null +++ b/Sources/ASCCommand/Commands/Web/Controllers/IrisAppComplianceController.swift @@ -0,0 +1,55 @@ +import ArgumentParser +import ASCKit +import Foundation +import Hummingbird +import HummingbirdWebSocket + +/// `GET /api/v1/iris/apps/:appId/compliance-requirements` — the app's App Compliance page. +/// `POST /api/v1/iris/apps/:appId/compliance-requirements/:requirementId/declare` with +/// `{"answer": "yes" | "no"}` — answers one. Iris private API only (browser-cookie auth). +struct IrisAppComplianceController: Sendable { + let cookieProvider: any IrisCookieProvider + let repo: any IrisComplianceRepository + + private struct DeclareBody: Decodable { + let answer: String + } + + func addRoutes(to group: RouterGroup) { + group.get("/iris/apps/:appId/compliance-requirements") { _, 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 { try restFormat(try await self.repo.listRequirements(session: session, appId: appId)) } + } + + group.post("/iris/apps/:appId/compliance-requirements/:requirementId/declare") { request, context -> Response in + guard let appId = context.parameters.get("appId"), + let requirementId = context.parameters.get("requirementId") else { return jsonError("Missing appId or requirementId") } + let body = try? await request.decode(as: DeclareBody.self, context: context) + guard let answer = body.flatMap({ DeclaredAnswerArgument(rawValue: $0.answer.lowercased()) }) else { + return jsonError(#"answer must be "yes" or "no""#) + } + let session = try self.cookieProvider.resolveSession() + return try await self.answering { + let requirement = try await self.repo.requirement(requirementId, appId: appId, session: session) + return try restFormat(try await requirement.declare(try answer.answer(), 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 ComplianceError { + switch error { + case .requirementNotFound: return jsonError(error.description, status: .notFound) + case .roleCannotEdit: return jsonError(error.description, status: .forbidden) + case .teamUnknown: return jsonError(error.description, status: .unauthorized) + case .notDeclarable, .readOnly: return jsonError(error.description, status: .conflict) + } + } catch let error as ValidationError { + return jsonError(error.message, status: .unprocessableContent) + } + } +} diff --git a/Sources/ASCCommand/Commands/Web/RESTRoutes.swift b/Sources/ASCCommand/Commands/Web/RESTRoutes.swift index 1b29747b..5c330b99 100644 --- a/Sources/ASCCommand/Commands/Web/RESTRoutes.swift +++ b/Sources/ASCCommand/Commands/Web/RESTRoutes.swift @@ -151,6 +151,10 @@ enum RESTRoutes { cookieProvider: ClientProvider.makeIrisCookieProvider(), repo: ClientProvider.makeIrisResolutionCenterRepository() ).addRoutes(to: v1) + IrisAppComplianceController( + cookieProvider: ClientProvider.makeIrisCookieProvider(), + repo: ClientProvider.makeIrisComplianceRepository() + ).addRoutes(to: v1) if let subSubmissionRepo = try? ClientProvider.makeSubscriptionSubmissionRepository() { SubscriptionSubmissionController(repo: subSubmissionRepo).addRoutes(to: v1) } diff --git a/Sources/ASCKit/Iris/Compliance/ComplianceError.swift b/Sources/ASCKit/Iris/Compliance/ComplianceError.swift index d80b6e34..26ec1097 100644 --- a/Sources/ASCKit/Iris/Compliance/ComplianceError.swift +++ b/Sources/ASCKit/Iris/Compliance/ComplianceError.swift @@ -5,6 +5,8 @@ public enum ComplianceError: Error, Equatable, Sendable, CustomStringConvertible case notDeclarable(kind: ComplianceKind, status: ComplianceStatus) /// The session doesn't say which team it belongs to (olympus gave no `publicProviderId`). case teamUnknown + /// No row with this requirement id on this app (a requirement is addressed by both, law 2). + case requirementNotFound(requirementId: String, appId: String) /// Apple serves the form without `editable` (law 5a): nothing was saved. case readOnly(kind: ComplianceKind) /// Apple forbade the save (403): the signed-in role can't edit App Compliance. @@ -20,6 +22,8 @@ public enum ComplianceError: Error, Equatable, Sendable, CustomStringConvertible "Apple won't take a change to \(kind.displayName) right now: the App Compliance page shows it read-only." case .roleCannotEdit(let appId): "Your App Store Connect role can't edit App Compliance for app \(appId). Ask your Account Holder or an Admin." + case .requirementNotFound(let requirementId, let appId): + "App \(appId) has no compliance requirement \(requirementId). See `asc iris app-compliance list --app-id \(appId)`." case .teamUnknown: "Couldn't tell which team this App Store Connect session belongs to. Sign in again with `asc iris auth login`." } diff --git a/Sources/ASCKit/Iris/Compliance/IrisComplianceRepository.swift b/Sources/ASCKit/Iris/Compliance/IrisComplianceRepository.swift index 59fb9352..53e91add 100644 --- a/Sources/ASCKit/Iris/Compliance/IrisComplianceRepository.swift +++ b/Sources/ASCKit/Iris/Compliance/IrisComplianceRepository.swift @@ -10,3 +10,14 @@ public protocol IrisComplianceRepository: Sendable { /// and answers the requirement as it now stands. func declare(session: IrisSession, requirement: ComplianceRequirement, answer: ComplianceAnswer) async throws -> ComplianceRequirement } + +extension IrisComplianceRepository { + /// The row for `requirementId` on `appId`: a requirement id names the compliance on every + /// app, so a row is found by both (law 2). + public func requirement(_ requirementId: String, appId: String, session: IrisSession) async throws -> ComplianceRequirement { + guard let row = try await listRequirements(session: session, appId: appId).first(where: { $0.id == requirementId }) else { + throw ComplianceError.requirementNotFound(requirementId: requirementId, appId: appId) + } + return row + } +} diff --git a/Sources/ASCKit/Shared/Internal/ClientFactory.swift b/Sources/ASCKit/Shared/Internal/ClientFactory.swift index 4f85d6b6..dcc921e4 100644 --- a/Sources/ASCKit/Shared/Internal/ClientFactory.swift +++ b/Sources/ASCKit/Shared/Internal/ClientFactory.swift @@ -365,6 +365,10 @@ public struct ClientFactory: Sendable { IrisSDKResolutionCenterRepository() } + public func makeIrisComplianceRepository() -> any IrisComplianceRepository { + IrisSDKComplianceRepository() + } + 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/Tests/ASCCommandTests/Commands/Iris/Compliance/IrisAppComplianceTests.swift b/Tests/ASCCommandTests/Commands/Iris/Compliance/IrisAppComplianceTests.swift new file mode 100644 index 00000000..5e65e95b --- /dev/null +++ b/Tests/ASCCommandTests/Commands/Iris/Compliance/IrisAppComplianceTests.swift @@ -0,0 +1,124 @@ +import Foundation +import Mockable +import Testing +@testable import ASCCommand +@testable import ASCKit + +@Suite +struct IrisAppComplianceTests { + private func cookies() -> MockIrisCookieProvider { + let provider = MockIrisCookieProvider() + given(provider).resolveSession().willReturn(IrisSession(cookies: "myacinfo=a")) + return provider + } + + private let missing = ComplianceRequirement( + id: "req-1", appId: "1234567890", kind: .securityAssessment, regions: ["CHN"], isRequired: true, + status: .missingInfo, updatedAt: nil, requiredActions: [], declaration: nil + ) + private let pending = ComplianceRequirement( + id: "req-2", appId: "1234567890", kind: .aiGeneratedContent, regions: ["CHN"], isRequired: true, + status: .pendingVerification, updatedAt: "2026-11-17T00:00:00.000Z", requiredActions: [.appBinarySubmission], + declaration: ComplianceDeclaration(id: "form-2", answer: .yes) + ) + private var declaredNo: ComplianceRequirement { + ComplianceRequirement(id: "req-1", appId: "1234567890", kind: .securityAssessment, regions: ["CHN"], isRequired: true, + status: .active, updatedAt: "2026-11-19T00:00:00.000Z", requiredActions: [], + declaration: ComplianceDeclaration(id: "form-1", answer: .no)) + } + + private func repo() -> MockIrisComplianceRepository { + let repo = MockIrisComplianceRepository() + given(repo).listRequirements(session: .any, appId: .value("1234567890")).willReturn([missing, pending]) + given(repo).declare(session: .any, requirement: .value(missing), answer: .value(.notOffered)).willReturn(declaredNo) + return repo + } + + @Test func `should list every requirement on the app's App Compliance page with what to do next`() async throws { + let cmd = try IrisAppComplianceList.parse(["--app-id", "1234567890", "--pretty"]) + + let output = try await cmd.execute(cookieProvider: cookies(), repo: repo()) + + #expect(output == """ + { + "data" : [ + { + "affordances" : { + "declare" : "asc iris app-compliance declare --answer --app-id 1234567890 --requirement-id req-1", + "listRequirements" : "asc iris app-compliance list --app-id 1234567890" + }, + "appId" : "1234567890", + "id" : "req-1", + "isRequired" : true, + "kind" : "SECURITY_ASSESSMENT", + "name" : "Security Assessment", + "regions" : [ + "CHN" + ], + "requiredActions" : [ + + ], + "status" : "MISSING_INFO" + }, + { + "affordances" : { + "listRequirements" : "asc iris app-compliance list --app-id 1234567890" + }, + "appId" : "1234567890", + "declaration" : { + "answer" : "YES", + "id" : "form-2" + }, + "id" : "req-2", + "isRequired" : true, + "kind" : "AI_GENERATED_CONTENT", + "name" : "AI Generated or Synthetic Content", + "regions" : [ + "CHN" + ], + "requiredActions" : [ + "APP_BINARY_SUBMISSION" + ], + "status" : "PENDING_VERIFICATION", + "updatedAt" : "2026-11-17T00:00:00.000Z" + } + ] + } + """) + } + + @Test func `should declare No for a requirement and show it active`() async throws { + let cmd = try IrisAppComplianceDeclare.parse(["--app-id", "1234567890", "--requirement-id", "req-1", "--answer", "no"]) + + let output = try await cmd.execute(cookieProvider: cookies(), repo: repo()) + + let json = try #require(try JSONSerialization.jsonObject(with: Data(output.utf8)) as? [String: Any]) + let row = try #require((json["data"] as? [[String: Any]])?.first) + #expect(row["status"] as? String == "ACTIVE") + #expect((row["declaration"] as? [String: Any])?["answer"] as? String == "NO") + } + + @Test func `should refuse to declare while Apple is verifying the answer`() async throws { + let cmd = try IrisAppComplianceDeclare.parse(["--app-id", "1234567890", "--requirement-id", "req-2", "--answer", "no"]) + + await #expect(throws: ComplianceError.notDeclarable(kind: .aiGeneratedContent, status: .pendingVerification)) { + try await cmd.execute(cookieProvider: cookies(), repo: repo()) + } + } + + @Test func `should say which requirement the app doesn't have`() async throws { + let cmd = try IrisAppComplianceDeclare.parse(["--app-id", "1234567890", "--requirement-id", "req-9", "--answer", "no"]) + + await #expect(throws: ComplianceError.requirementNotFound(requirementId: "req-9", appId: "1234567890")) { + try await cmd.execute(cookieProvider: cookies(), repo: repo()) + } + #expect(ComplianceError.requirementNotFound(requirementId: "req-9", appId: "1234567890").description + == "App 1234567890 has no compliance requirement req-9. See `asc iris app-compliance list --app-id 1234567890`.") + } + + @Test func `should accept only yes or no as the answer`() { + #expect(throws: (any Error).self) { + try IrisAppComplianceDeclare.parse(["--app-id", "1234567890", "--requirement-id", "req-1", "--answer", "maybe"]) + } + } +} diff --git a/Tests/ASCCommandTests/Commands/Web/Controllers/IrisAppComplianceRoutesTests.swift b/Tests/ASCCommandTests/Commands/Web/Controllers/IrisAppComplianceRoutesTests.swift new file mode 100644 index 00000000..faa3e9bd --- /dev/null +++ b/Tests/ASCCommandTests/Commands/Web/Controllers/IrisAppComplianceRoutesTests.swift @@ -0,0 +1,72 @@ +import Foundation +import Hummingbird +import HummingbirdTesting +import HummingbirdWebSocket +import Mockable +import NIOCore +import Testing +@testable import ASCCommand +@testable import ASCKit + +@Suite +struct IrisAppComplianceRoutesTests { + private let missing = ComplianceRequirement( + id: "req-1", appId: "1234567890", kind: .securityAssessment, regions: ["CHN"], isRequired: true, + status: .missingInfo, updatedAt: nil, requiredActions: [], declaration: nil + ) + private let declaredNo = ComplianceRequirement( + id: "req-1", appId: "1234567890", kind: .securityAssessment, regions: ["CHN"], isRequired: true, + status: .active, updatedAt: "2026-11-19T00:00:00.000Z", requiredActions: [], + declaration: ComplianceDeclaration(id: "form-1", answer: .no) + ) + + private func call(_ method: HTTPRequest.Method, _ uri: String, body: String? = nil) async throws -> (HTTPResponse.Status, String) { + let cookies = MockIrisCookieProvider() + given(cookies).resolveSession().willReturn(IrisSession(cookies: "myacinfo=a")) + let repo = MockIrisComplianceRepository() + given(repo).listRequirements(session: .any, appId: .value("1234567890")).willReturn([missing]) + given(repo).declare(session: .any, requirement: .value(missing), answer: .value(.notOffered)).willReturn(declaredNo) + let router = Router(context: BasicWebSocketRequestContext.self) + IrisAppComplianceController(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)) + } + } + } + + @Test func `should list an app's compliance requirements over REST with their links`() async throws { + let (status, body) = try await call(.get, "/api/v1/iris/apps/1234567890/compliance-requirements") + + #expect(status == .ok) + let row = try #require(((try JSONSerialization.jsonObject(with: Data(body.utf8)) as? [String: Any])?["data"] as? [[String: Any]])?.first) + #expect(row["status"] as? String == "MISSING_INFO") + let declare = (row["_links"] as? [String: Any])?["declare"] as? [String: String] + #expect(declare == ["href": "/api/v1/iris/apps/1234567890/compliance-requirements/req-1/declare", "method": "POST"]) + } + + @Test func `should declare No over REST`() async throws { + let (status, body) = try await call(.post, "/api/v1/iris/apps/1234567890/compliance-requirements/req-1/declare", + body: #"{"answer":"no"}"#) + + #expect(status == .ok) + let row = try #require(((try JSONSerialization.jsonObject(with: Data(body.utf8)) as? [String: Any])?["data"] as? [[String: Any]])?.first) + #expect(row["status"] as? String == "ACTIVE") + } + + @Test func `should refuse an answer that isn't yes or no`() async throws { + let (status, body) = try await call(.post, "/api/v1/iris/apps/1234567890/compliance-requirements/req-1/declare", + body: #"{"answer":"maybe"}"#) + + #expect(status == .badRequest) + #expect(body.contains("answer must be \\\"yes\\\" or \\\"no\\\"")) + } + + @Test func `should answer 404 for a requirement the app doesn't have`() async throws { + let (status, body) = try await call(.post, "/api/v1/iris/apps/1234567890/compliance-requirements/req-9/declare", + body: #"{"answer":"no"}"#) + + #expect(status == .notFound) + #expect(body.contains("App 1234567890 has no compliance requirement req-9")) + } +} From 9775c0c8af7ecbfa317189ca532cddffe5725f82 Mon Sep 17 00:00:00 2001 From: slamhan Date: Thu, 19 Nov 2026 21:42:21 +0800 Subject: [PATCH 07/12] feat(app-compliance): declare a Yes with its evidence MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Yes carries its kind's evidence, in shapes that can't hold a combination the form can't: Security Assessment's proof and report, AIGC's filing (algorithm or LLM, name and number) and whether third-party technology powers it, with its authorization file. ComplianceAnswer.offered(for:evidence:) names what's missing; a requirement refuses evidence made for another compliance. The adapter walks Apple's form as the page does: post the draft, fill each field it newly asks for (known by the key in its label), again until it asks for nothing new, then save exactly those fields. Files go base64 inside the declaration; a type the field doesn't accept, or a field asc can't fill, is refused before saving. CLI: --answer yes with --proof/--report, or --filing-type, --filing-name, --filing-number and --third-party-authorization. REST: {"answer":"yes","evidence":{…}} with files as base64. Co-Authored-By: Claude Opus 5.5 --- .../Compliance/IrisAppComplianceCommand.swift | 8 +- .../Compliance/IrisAppComplianceDeclare.swift | 43 +++- .../IrisAppComplianceController.swift | 38 +++- .../Iris/Compliance/ComplianceAnswer.swift | 128 +++++++++++- .../Iris/Compliance/ComplianceError.swift | 16 ++ .../Compliance/ComplianceRequirement.swift | 1 + .../Compliance/Internal/ComplianceWire.swift | 38 +++- .../IrisSDKComplianceRepository.swift | 95 +++++++-- .../Compliance/IrisAppComplianceTests.swift | 58 ++++++ .../IrisAppComplianceRoutesTests.swift | 20 ++ .../Compliance/ComplianceAnswerTests.swift | 92 +++++++++ .../IrisSDKComplianceDeclareYesTests.swift | 188 ++++++++++++++++++ 12 files changed, 699 insertions(+), 26 deletions(-) create mode 100644 Tests/ASCKitTests/Iris/Compliance/ComplianceAnswerTests.swift create mode 100644 Tests/ASCKitTests/Iris/Compliance/Internal/IrisSDKComplianceDeclareYesTests.swift diff --git a/Sources/ASCCommand/Commands/Iris/Compliance/IrisAppComplianceCommand.swift b/Sources/ASCCommand/Commands/Iris/Compliance/IrisAppComplianceCommand.swift index 6f66f8e0..9bbcf411 100644 --- a/Sources/ASCCommand/Commands/Iris/Compliance/IrisAppComplianceCommand.swift +++ b/Sources/ASCCommand/Commands/Iris/Compliance/IrisAppComplianceCommand.swift @@ -16,11 +16,13 @@ enum DeclaredAnswerArgument: String, ExpressibleByArgument, CaseIterable { case yes case no - /// The answer to send. A Yes needs evidence (not yet supported), so only No is sent. - func answer() throws -> ComplianceAnswer { + /// The answer for a requirement of `kind`: a No as it is, a Yes with that kind's evidence. + func answer(for kind: ComplianceKind, evidence: ComplianceEvidenceInput) throws -> ComplianceAnswer { switch self { case .no: return .notOffered - case .yes: throw ValidationError("Answering yes needs evidence asc can't send yet. Answer yes on the App Compliance page.") + case .yes: return try ComplianceAnswer.offered(for: kind, evidence: evidence) } } } + +extension AIGCFiling.FilingType: ExpressibleByArgument {} diff --git a/Sources/ASCCommand/Commands/Iris/Compliance/IrisAppComplianceDeclare.swift b/Sources/ASCCommand/Commands/Iris/Compliance/IrisAppComplianceDeclare.swift index 9dd2e080..19e6a987 100644 --- a/Sources/ASCCommand/Commands/Iris/Compliance/IrisAppComplianceDeclare.swift +++ b/Sources/ASCCommand/Commands/Iris/Compliance/IrisAppComplianceDeclare.swift @@ -1,11 +1,19 @@ import ArgumentParser +import Foundation import ASCKit struct IrisAppComplianceDeclare: AsyncParsableCommand { static let configuration = CommandConfiguration( commandName: "declare", abstract: "Answer an App Compliance requirement", - discussion: "--answer no declares the app doesn't offer the regulated feature in the region (or it is disabled or geoblocked there)." + discussion: """ + --answer no declares the app doesn't offer the regulated feature in the region (or it is \ + disabled or geoblocked there). --answer yes sends the requirement's evidence: + Security Assessment: --proof --report + AI Generated or Synthetic Content: --filing-type llm|algorithm --filing-name \ + --filing-number [--third-party-authorization when third-party technology powers it] + Files are .doc, .docx, .jpeg, .jpg, .pdf or .png. + """ ) @OptionGroup var globals: GlobalOptions @@ -19,6 +27,24 @@ struct IrisAppComplianceDeclare: AsyncParsableCommand { @Option(name: .long, help: "yes or no") var answer: DeclaredAnswerArgument + @Option(name: .long, help: "Security Assessment: the proof of a completed assessment (file)") + var proof: String? + + @Option(name: .long, help: "Security Assessment: the assessment report (file)") + var report: String? + + @Option(name: .long, help: "AIGC: llm or algorithm") + var filingType: AIGCFiling.FilingType? + + @Option(name: .long, help: "AIGC: the LLM or algorithm name, as filed") + var filingName: String? + + @Option(name: .long, help: "AIGC: the filing number") + var filingNumber: String? + + @Option(name: .long, help: "AIGC: the authorization or usage agreement for third-party technology (file)") + var thirdPartyAuthorization: String? + func run() async throws { print(try await execute(cookieProvider: ClientProvider.makeIrisCookieProvider(), repo: ClientProvider.makeIrisComplianceRepository())) } @@ -26,7 +52,20 @@ struct IrisAppComplianceDeclare: AsyncParsableCommand { func execute(cookieProvider: any IrisCookieProvider, repo: any IrisComplianceRepository, affordanceMode: AffordanceMode = .cli) async throws -> String { let session = try cookieProvider.resolveSession() let requirement = try await repo.requirement(requirementId, appId: appId, session: session) - let declared = try await requirement.declare(try answer.answer(), session: session, repo: repo) + let declared = try await requirement.declare(try answer.answer(for: requirement.kind, evidence: try evidence()), session: session, repo: repo) return try OutputFormatter(format: globals.outputFormat, pretty: globals.pretty).formatAgentItems([declared], affordanceMode: affordanceMode) } + + private func evidence() throws -> ComplianceEvidenceInput { + func read(_ path: String?) throws -> ComplianceFile? { + guard let path else { return nil } + let url = URL(fileURLWithPath: path) + return ComplianceFile(name: url.lastPathComponent, data: try Data(contentsOf: url)) + } + return ComplianceEvidenceInput( + proof: try read(proof), report: try read(report), + filingType: filingType, filingName: filingName, filingNumber: filingNumber, + thirdPartyAuthorization: try read(thirdPartyAuthorization) + ) + } } diff --git a/Sources/ASCCommand/Commands/Web/Controllers/IrisAppComplianceController.swift b/Sources/ASCCommand/Commands/Web/Controllers/IrisAppComplianceController.swift index 37bd1a7e..a479262f 100644 --- a/Sources/ASCCommand/Commands/Web/Controllers/IrisAppComplianceController.swift +++ b/Sources/ASCCommand/Commands/Web/Controllers/IrisAppComplianceController.swift @@ -1,4 +1,3 @@ -import ArgumentParser import ASCKit import Foundation import Hummingbird @@ -12,7 +11,35 @@ struct IrisAppComplianceController: Sendable { let repo: any IrisComplianceRepository private struct DeclareBody: Decodable { + struct File: Decodable { + let name: String + /// The file's bytes, base64-encoded. + let data: String + } + + struct Evidence: Decodable { + let proof: File? + let report: File? + let filingType: String? + let filingName: String? + let filingNumber: String? + let thirdPartyAuthorization: File? + } + let answer: String + let evidence: Evidence? + + func evidenceInput() -> ComplianceEvidenceInput { + func file(_ file: File?) -> ComplianceFile? { + file.flatMap { f in Data(base64Encoded: f.data).map { ComplianceFile(name: f.name, data: $0) } } + } + return ComplianceEvidenceInput( + proof: file(evidence?.proof), report: file(evidence?.report), + filingType: evidence?.filingType.flatMap(AIGCFiling.FilingType.init(rawValue:)), + filingName: evidence?.filingName, filingNumber: evidence?.filingNumber, + thirdPartyAuthorization: file(evidence?.thirdPartyAuthorization) + ) + } } func addRoutes(to group: RouterGroup) { @@ -26,13 +53,14 @@ struct IrisAppComplianceController: Sendable { guard let appId = context.parameters.get("appId"), let requirementId = context.parameters.get("requirementId") else { return jsonError("Missing appId or requirementId") } let body = try? await request.decode(as: DeclareBody.self, context: context) - guard let answer = body.flatMap({ DeclaredAnswerArgument(rawValue: $0.answer.lowercased()) }) else { + guard let body, let answer = DeclaredAnswerArgument(rawValue: body.answer.lowercased()) else { return jsonError(#"answer must be "yes" or "no""#) } let session = try self.cookieProvider.resolveSession() return try await self.answering { let requirement = try await self.repo.requirement(requirementId, appId: appId, session: session) - return try restFormat(try await requirement.declare(try answer.answer(), session: session, repo: self.repo)) + let declared = try answer.answer(for: requirement.kind, evidence: body.evidenceInput()) + return try restFormat(try await requirement.declare(declared, session: session, repo: self.repo)) } } } @@ -47,9 +75,9 @@ struct IrisAppComplianceController: Sendable { case .roleCannotEdit: return jsonError(error.description, status: .forbidden) case .teamUnknown: return jsonError(error.description, status: .unauthorized) case .notDeclarable, .readOnly: return jsonError(error.description, status: .conflict) + case .evidenceMissing, .evidenceMismatch, .fileTypeNotAllowed: return jsonError(error.description, status: .unprocessableContent) + case .formNotUnderstood: return jsonError(error.description, status: .conflict) } - } catch let error as ValidationError { - return jsonError(error.message, status: .unprocessableContent) } } } diff --git a/Sources/ASCKit/Iris/Compliance/ComplianceAnswer.swift b/Sources/ASCKit/Iris/Compliance/ComplianceAnswer.swift index 832aeec1..7416362f 100644 --- a/Sources/ASCKit/Iris/Compliance/ComplianceAnswer.swift +++ b/Sources/ASCKit/Iris/Compliance/ComplianceAnswer.swift @@ -1,17 +1,141 @@ -/// The developer's answer to a requirement's question ("Does your app offer AIGC -/// services in China mainland?"). A No carries nothing (law 3). +import Foundation + +/// The developer's answer to a requirement's question ("Does your app offer AIGC services +/// in China mainland?"). A No carries nothing; a Yes carries its kind's evidence, in a shape +/// that can't hold a combination the form can't (law 3). public enum ComplianceAnswer: Sendable, Equatable { /// The app doesn't offer the regulated feature in the region, or it's disabled or geoblocked there. case notOffered + case offered(ComplianceEvidence) /// The question's option, as Apple's form names it. var wireValue: String { switch self { case .notOffered: "NO" + case .offered: "YES" + } + } + + /// Whether this answer is one `kind` can take: a No always; a Yes only with its own evidence. + func fits(_ kind: ComplianceKind) -> Bool { + switch (self, kind) { + case (.notOffered, _): true + case (.offered(.securityAssessment), .securityAssessment): true + case (.offered(.aiGeneratedContent), .aiGeneratedContent): true + default: false + } + } + + /// A Yes to `kind`, from evidence given piece by piece (flags, a REST body). + /// Refuses, naming what's missing, when the kind's evidence isn't all there. + public static func offered(for kind: ComplianceKind, evidence: ComplianceEvidenceInput) throws -> ComplianceAnswer { + switch kind { + case .securityAssessment: + var missing: [String] = [] + if evidence.proof == nil { missing.append("the Proof of a Completed Security Assessment") } + if evidence.report == nil { missing.append("the Security Assessment Report") } + guard let proof = evidence.proof, let report = evidence.report else { + throw ComplianceError.evidenceMissing(kind: kind, missing: missing) + } + return .offered(.securityAssessment(proof: proof, report: report)) + case .aiGeneratedContent: + var missing: [String] = [] + if evidence.filingType == nil { missing.append("the filing type") } + if evidence.filingName == nil { missing.append("the filing name") } + if evidence.filingNumber == nil { missing.append("the filing number") } + guard let type = evidence.filingType, let name = evidence.filingName, let number = evidence.filingNumber else { + throw ComplianceError.evidenceMissing(kind: kind, missing: missing) + } + let filing: AIGCFiling = switch type { + case .algorithm: .algorithm(name: name, filingNumber: number) + case .largeLanguageModel: .largeLanguageModel(name: name, filingNumber: number) + } + return .offered(.aiGeneratedContent( + filing: filing, thirdParty: evidence.thirdPartyAuthorization.map { .used(authorization: $0) } ?? .none + )) + case .unrecognized: + throw ComplianceError.notDeclarable(kind: kind, status: .missingInfo) + } + } +} + +/// What a Yes must carry, per kind. +public enum ComplianceEvidence: Sendable, Equatable { + /// The proof of a completed security assessment, and the assessment report. + case securityAssessment(proof: ComplianceFile, report: ComplianceFile) + /// The AIGC filing, and whether third-party technology powers the feature. + case aiGeneratedContent(filing: AIGCFiling, thirdParty: ThirdPartyTechnology) +} + +/// The filing an AIGC Yes gives: an algorithm or a large language model, by name and filing number. +public enum AIGCFiling: Sendable, Equatable { + case algorithm(name: String, filingNumber: String) + case largeLanguageModel(name: String, filingNumber: String) + + public enum FilingType: String, Sendable, Equatable, CaseIterable { + case algorithm + case largeLanguageModel = "llm" + } +} + +/// Whether an app's AI features are powered by third-party technology; if so, the +/// authorization or usage agreement for it. +public enum ThirdPartyTechnology: Sendable, Equatable { + case none + case used(authorization: ComplianceFile) +} + +/// A local document sent as evidence. Apple stores it on save; its type comes from its extension. +public struct ComplianceFile: Sendable, Equatable { + public let name: String + public let data: Data + + public init(name: String, data: Data) { + self.name = name + self.data = data + } + + /// The extension with its dot, lowercased (`.pdf`), as Apple's `allowedFileTypes` spell it. + public var fileExtension: String { + let ext = (name as NSString).pathExtension.lowercased() + return ext.isEmpty ? "" : ".\(ext)" + } + + public var mimeType: String { + switch fileExtension { + case ".pdf": "application/pdf" + case ".png": "image/png" + case ".jpg", ".jpeg": "image/jpeg" + case ".doc": "application/msword" + case ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document" + default: "application/octet-stream" } } } +/// Evidence as it arrives, piece by piece, before it's known to be complete for a kind. +public struct ComplianceEvidenceInput: Sendable, Equatable { + public var proof: ComplianceFile? + public var report: ComplianceFile? + public var filingType: AIGCFiling.FilingType? + public var filingName: String? + public var filingNumber: String? + public var thirdPartyAuthorization: ComplianceFile? + + public init( + proof: ComplianceFile? = nil, report: ComplianceFile? = nil, + filingType: AIGCFiling.FilingType? = nil, filingName: String? = nil, filingNumber: String? = nil, + thirdPartyAuthorization: ComplianceFile? = nil + ) { + self.proof = proof + self.report = report + self.filingType = filingType + self.filingName = filingName + self.filingNumber = filingNumber + self.thirdPartyAuthorization = thirdPartyAuthorization + } +} + /// An answer Apple holds for a requirement. Apple's API calls it a *form*. /// The evidence of a Yes stays with Apple; the list shows only the answer. public struct ComplianceDeclaration: Sendable, Equatable, Codable { diff --git a/Sources/ASCKit/Iris/Compliance/ComplianceError.swift b/Sources/ASCKit/Iris/Compliance/ComplianceError.swift index 26ec1097..137ad8fa 100644 --- a/Sources/ASCKit/Iris/Compliance/ComplianceError.swift +++ b/Sources/ASCKit/Iris/Compliance/ComplianceError.swift @@ -5,6 +5,14 @@ public enum ComplianceError: Error, Equatable, Sendable, CustomStringConvertible case notDeclarable(kind: ComplianceKind, status: ComplianceStatus) /// The session doesn't say which team it belongs to (olympus gave no `publicProviderId`). case teamUnknown + /// A file whose extension the field doesn't accept (law 9). + case fileTypeNotAllowed(fileName: String, allowed: [String]) + /// Apple's form asks for a field asc can't fill from the answer: nothing was saved. + case formNotUnderstood(kind: ComplianceKind, field: String) + /// A Yes without all of its kind's evidence (law 3). + case evidenceMissing(kind: ComplianceKind, missing: [String]) + /// A Yes whose evidence belongs to another compliance. + case evidenceMismatch(kind: ComplianceKind) /// No row with this requirement id on this app (a requirement is addressed by both, law 2). case requirementNotFound(requirementId: String, appId: String) /// Apple serves the form without `editable` (law 5a): nothing was saved. @@ -24,6 +32,14 @@ public enum ComplianceError: Error, Equatable, Sendable, CustomStringConvertible "Your App Store Connect role can't edit App Compliance for app \(appId). Ask your Account Holder or an Admin." case .requirementNotFound(let requirementId, let appId): "App \(appId) has no compliance requirement \(requirementId). See `asc iris app-compliance list --app-id \(appId)`." + case .evidenceMissing(let kind, let missing): + "A Yes to \(kind.displayName) needs \(missing.joined(separator: " and "))." + case .evidenceMismatch(let kind): + "That evidence isn't for \(kind.displayName); answer it with \(kind.displayName)'s own." + case .fileTypeNotAllowed(let fileName, let allowed): + "\(fileName) can't be sent: this field takes \(allowed.joined(separator: ", "))." + case .formNotUnderstood(let kind, let field): + "Apple's \(kind.displayName) form asks for something asc doesn't know (\(field)). Answer it on the App Compliance page." case .teamUnknown: "Couldn't tell which team this App Store Connect session belongs to. Sign in again with `asc iris auth login`." } diff --git a/Sources/ASCKit/Iris/Compliance/ComplianceRequirement.swift b/Sources/ASCKit/Iris/Compliance/ComplianceRequirement.swift index a463aa06..9daf1cc0 100644 --- a/Sources/ASCKit/Iris/Compliance/ComplianceRequirement.swift +++ b/Sources/ASCKit/Iris/Compliance/ComplianceRequirement.swift @@ -42,6 +42,7 @@ public struct ComplianceRequirement: Sendable, Equatable, Identifiable, Codable /// Saves `answer` through `repo`, after checking this requirement may be declared. public func declare(_ answer: ComplianceAnswer, session: IrisSession, repo: any IrisComplianceRepository) async throws -> ComplianceRequirement { guard isDeclarable else { throw ComplianceError.notDeclarable(kind: kind, status: status) } + guard answer.fits(kind) else { throw ComplianceError.evidenceMismatch(kind: kind) } return try await repo.declare(session: session, requirement: self, answer: answer) } diff --git a/Sources/ASCKit/Iris/Compliance/Internal/ComplianceWire.swift b/Sources/ASCKit/Iris/Compliance/Internal/ComplianceWire.swift index 3c0de0f3..4457df2d 100644 --- a/Sources/ASCKit/Iris/Compliance/Internal/ComplianceWire.swift +++ b/Sources/ASCKit/Iris/Compliance/Internal/ComplianceWire.swift @@ -32,11 +32,13 @@ struct ComplianceConstraint: Decodable { struct Presentation: Decodable { let id: String let inputType: String + let label: String? } struct Validation: Decodable { let required: Bool? let editable: Bool? + let allowedFileTypes: [String]? } let presentation: Presentation @@ -45,12 +47,44 @@ struct ComplianceConstraint: Decodable { var id: String { presentation.id } /// Apple marks a field `editable` only when it will take a change; a pending declaration has none. var isEditable: Bool { validation?.editable == true } + var isRequired: Bool { validation?.required == true } + var allowedFileTypes: [String] { validation?.allowedFileTypes ?? [] } + /// The field key inside its label's loc key (`…field.proofofacocb097.label` → `proofofacocb097`): + /// how a field is known, since its id is Apple's to choose (law 8). + var fieldKey: String? { + guard let parts = presentation.label?.split(separator: "."), let at = parts.firstIndex(of: "field"), + parts.index(after: at) < parts.endIndex else { return nil } + return String(parts[parts.index(after: at)]) + } +} + +/// One field of a draft: a `RADIO` or `TEXT` as `sValue`, a `FILE` as its base64 bytes in `fileContent`. +struct ComplianceDraftField: Encodable, Equatable { + struct FileContent: Encodable, Equatable { + let fileData: String + let fileName: String + let fileType: String + } + + let id: String + let sValue: String? + let fileContent: FileContent? + + static func text(_ id: String, _ value: String) -> ComplianceDraftField { + ComplianceDraftField(id: id, sValue: value, fileContent: nil) + } + + static func file(_ id: String, _ file: ComplianceFile) -> ComplianceDraftField { + ComplianceDraftField(id: id, sValue: nil, fileContent: FileContent( + fileData: file.data.base64EncodedString(), fileName: file.name, fileType: file.mimeType + )) + } } /// The draft Apple computes a form for (`…/metadata`). struct ComplianceMetadataRequest: Encodable { struct Draft: Encodable { - let fields: [ComplianceFieldValue] + let fields: [ComplianceDraftField] } let accountId: String @@ -65,7 +99,7 @@ struct ComplianceSaveRequest: Encodable { let entityId: String let requirementId: String let formId: String? - let fields: [ComplianceFieldValue] + let fields: [ComplianceDraftField] } struct ComplianceFormsResponse: Decodable { diff --git a/Sources/ASCKit/Iris/Compliance/Internal/IrisSDKComplianceRepository.swift b/Sources/ASCKit/Iris/Compliance/Internal/IrisSDKComplianceRepository.swift index 5cc3694a..f89ab197 100644 --- a/Sources/ASCKit/Iris/Compliance/Internal/IrisSDKComplianceRepository.swift +++ b/Sources/ASCKit/Iris/Compliance/Internal/IrisSDKComplianceRepository.swift @@ -28,21 +28,33 @@ public struct IrisSDKComplianceRepository: IrisComplianceRepository { return Self.rows(requirements: requirements, forms: forms, appId: appId) } - /// Saves `answer` the way the App Compliance page does: ask Apple for the form, pick the - /// answer and ask again, then save exactly the fields the form asks for (laws 8, 10) — - /// a `POST` for a first answer, a `PUT` on the declaration for a change. + /// Saves `answer` the way the App Compliance page does: post the draft to Apple's form, + /// fill every field it newly asks for from the answer, and again until it asks for nothing + /// new; then save exactly the fields the form asks for (laws 8, 10) — a `POST` for a first + /// answer, a `PUT` on the declaration for a change. public func declare(session: IrisSession, requirement: ComplianceRequirement, answer: ComplianceAnswer) async throws -> ComplianceRequirement { let team = try await teamId(for: session) let entity = "accounts/\(team)/entities/\(requirement.appId)" - // The question's id comes from Apple's form, never from asc (law 8). - let empty = try await metadata(for: [], requirement: requirement, team: team, session: session) - guard let question = empty.question, question.isEditable else { - throw ComplianceError.readOnly(kind: requirement.kind) + var draft: [ComplianceDraftField] = [] + var form = try await metadata(for: draft, requirement: requirement, team: team, session: session) + var settled = false + for _ in 0.. ComplianceDraftField { + guard let key = field.fieldKey, let value = answer.value(forFieldKey: key) else { + throw ComplianceError.formNotUnderstood(kind: kind, field: field.fieldKey ?? field.id) + } + switch value { + case .text(let text): + return .text(field.id, text) + case .file(let file): + let allowed = field.allowedFileTypes + guard allowed.isEmpty || allowed.contains(file.fileExtension) else { + throw ComplianceError.fileTypeNotAllowed(fileName: file.name, allowed: allowed) + } + return .file(field.id, file) + } + } + private func metadata( - for fields: [ComplianceFieldValue], requirement: ComplianceRequirement, team: String, session: IrisSession + for fields: [ComplianceDraftField], requirement: ComplianceRequirement, team: String, session: IrisSession ) async throws -> ComplianceFormMetadata { let body = try Self.encoder.encode(ComplianceMetadataRequest( accountId: team, entityId: requirement.appId, requirementId: requirement.id, form: .init(fields: fields) @@ -77,7 +110,7 @@ public struct IrisSDKComplianceRepository: IrisComplianceRepository { private static let encoder: JSONEncoder = { let encoder = JSONEncoder() - encoder.outputFormatting = [.sortedKeys] + encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes] return encoder }() @@ -123,3 +156,41 @@ public struct IrisSDKComplianceRepository: IrisComplianceRepository { return team } } + +/// What an answer gives each field of Apple's forms, known by the field key in its label. +/// The keys are the captured ones (docs/features/app-compliance/design.md): a short label +/// slug with a suffix, matched by the slug so a new suffix still reads. +extension ComplianceAnswer { + enum FieldValue { + case text(String) + case file(ComplianceFile) + } + + func value(forFieldKey key: String) -> FieldValue? { + // Every form opens with its Yes/No question ("Does your app …?"). + if key.hasPrefix("doesyourap") { return .text(wireValue) } + guard case .offered(let evidence) = self else { return nil } + switch evidence { + case .securityAssessment(let proof, let report): + if key.hasPrefix("proofofaco") { return .file(proof) } + if key.hasPrefix("securityas") { return .file(report) } + case .aiGeneratedContent(let filing, let thirdParty): + switch (filing, key) { + case (_, let key) where key.hasPrefix("whichfilin"): + if case .algorithm = filing { return .text("ALGOR") } + return .text("LARGE") + case (.algorithm(let name, _), let key) where key.hasPrefix("algorithmn"): return .text(name) + case (.algorithm(_, let number), let key) where key.hasPrefix("algorithmf"): return .text(number) + case (.largeLanguageModel(let name, _), let key) where key.hasPrefix("llmname"): return .text(name) + case (.largeLanguageModel(_, let number), let key) where key.hasPrefix("llmfilingn"): return .text(number) + default: break + } + if key.hasPrefix("areyourapp") { + if case .used = thirdParty { return .text("YES") } + return .text("NO") + } + if key.hasPrefix("authorizat"), case .used(let authorization) = thirdParty { return .file(authorization) } + } + return nil + } +} diff --git a/Tests/ASCCommandTests/Commands/Iris/Compliance/IrisAppComplianceTests.swift b/Tests/ASCCommandTests/Commands/Iris/Compliance/IrisAppComplianceTests.swift index 5e65e95b..43c341c5 100644 --- a/Tests/ASCCommandTests/Commands/Iris/Compliance/IrisAppComplianceTests.swift +++ b/Tests/ASCCommandTests/Commands/Iris/Compliance/IrisAppComplianceTests.swift @@ -116,6 +116,64 @@ struct IrisAppComplianceTests { == "App 1234567890 has no compliance requirement req-9. See `asc iris app-compliance list --app-id 1234567890`.") } + // MARK: - a Yes with evidence + + private func file(_ name: String, _ contents: String) throws -> String { + let url = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString).appendingPathComponent(name) + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data(contents.utf8).write(to: url) + return url.path + } + + @Test func `should declare a Security Assessment Yes with the proof and report read from disk`() async throws { + let proof = try file("proof.pdf", "P"), report = try file("report.png", "R") + let yes = ComplianceAnswer.offered(.securityAssessment( + proof: ComplianceFile(name: "proof.pdf", data: Data("P".utf8)), report: ComplianceFile(name: "report.png", data: Data("R".utf8)) + )) + let repo = repo() + given(repo).declare(session: .any, requirement: .value(missing), answer: .value(yes)).willReturn(pending) + let cmd = try IrisAppComplianceDeclare.parse([ + "--app-id", "1234567890", "--requirement-id", "req-1", "--answer", "yes", "--proof", proof, "--report", report, + ]) + + let output = try await cmd.execute(cookieProvider: cookies(), repo: repo) + + #expect(output.contains("\"status\":\"PENDING_VERIFICATION\"")) + } + + @Test func `should say what a Yes still needs before sending anything`() async throws { + let cmd = try IrisAppComplianceDeclare.parse([ + "--app-id", "1234567890", "--requirement-id", "req-1", "--answer", "yes", "--proof", try file("proof.pdf", "P"), + ]) + let repo = repo() + + await #expect(throws: ComplianceError.evidenceMissing(kind: .securityAssessment, missing: ["the Security Assessment Report"])) { + try await cmd.execute(cookieProvider: cookies(), repo: repo) + } + verify(repo).declare(session: .any, requirement: .any, answer: .any).called(0) + } + + @Test func `should declare an AIGC Yes from its filing and third-party agreement`() async throws { + let aigc = ComplianceRequirement(id: "req-3", appId: "1234567890", kind: .aiGeneratedContent, regions: ["CHN"], isRequired: true, + status: .missingInfo, updatedAt: nil, requiredActions: [], declaration: nil) + let yes = ComplianceAnswer.offered(.aiGeneratedContent( + filing: .largeLanguageModel(name: "Example Model", filingNumber: "Example-0000"), + thirdParty: .used(authorization: ComplianceFile(name: "agreement.pdf", data: Data("A".utf8))) + )) + let repo = MockIrisComplianceRepository() + given(repo).listRequirements(session: .any, appId: .any).willReturn([aigc]) + given(repo).declare(session: .any, requirement: .value(aigc), answer: .value(yes)).willReturn(pending) + let cmd = try IrisAppComplianceDeclare.parse([ + "--app-id", "1234567890", "--requirement-id", "req-3", "--answer", "yes", + "--filing-type", "llm", "--filing-name", "Example Model", "--filing-number", "Example-0000", + "--third-party-authorization", try file("agreement.pdf", "A"), + ]) + + _ = try await cmd.execute(cookieProvider: cookies(), repo: repo) + + verify(repo).declare(session: .any, requirement: .any, answer: .value(yes)).called(1) + } + @Test func `should accept only yes or no as the answer`() { #expect(throws: (any Error).self) { try IrisAppComplianceDeclare.parse(["--app-id", "1234567890", "--requirement-id", "req-1", "--answer", "maybe"]) diff --git a/Tests/ASCCommandTests/Commands/Web/Controllers/IrisAppComplianceRoutesTests.swift b/Tests/ASCCommandTests/Commands/Web/Controllers/IrisAppComplianceRoutesTests.swift index faa3e9bd..380651e1 100644 --- a/Tests/ASCCommandTests/Commands/Web/Controllers/IrisAppComplianceRoutesTests.swift +++ b/Tests/ASCCommandTests/Commands/Web/Controllers/IrisAppComplianceRoutesTests.swift @@ -26,6 +26,9 @@ struct IrisAppComplianceRoutesTests { let repo = MockIrisComplianceRepository() given(repo).listRequirements(session: .any, appId: .value("1234567890")).willReturn([missing]) given(repo).declare(session: .any, requirement: .value(missing), answer: .value(.notOffered)).willReturn(declaredNo) + given(repo).declare(session: .any, requirement: .value(missing), answer: .value(.offered(.securityAssessment( + proof: ComplianceFile(name: "proof.pdf", data: Data("P".utf8)), report: ComplianceFile(name: "report.png", data: Data("R".utf8)) + )))).willReturn(declaredNo) let router = Router(context: BasicWebSocketRequestContext.self) IrisAppComplianceController(cookieProvider: cookies, repo: repo).addRoutes(to: router.group("/api/v1")) return try await Application(router: router).test(.router) { client in @@ -54,6 +57,23 @@ struct IrisAppComplianceRoutesTests { #expect(row["status"] as? String == "ACTIVE") } + @Test func `should declare a Yes over REST with its files as base64`() async throws { + let body = #"{"answer":"yes","evidence":{"proof":{"name":"proof.pdf","data":"UA=="},"report":{"name":"report.png","data":"Ug=="}}}"# + + let (status, _) = try await call(.post, "/api/v1/iris/apps/1234567890/compliance-requirements/req-1/declare", body: body) + + #expect(status == .ok) + } + + @Test func `should say what a Yes over REST still needs`() async throws { + let body = #"{"answer":"yes","evidence":{"proof":{"name":"proof.pdf","data":"UA=="}}}"# + + let (status, response) = try await call(.post, "/api/v1/iris/apps/1234567890/compliance-requirements/req-1/declare", body: body) + + #expect(status == .unprocessableContent) + #expect(response.contains("A Yes to Security Assessment needs the Security Assessment Report.")) + } + @Test func `should refuse an answer that isn't yes or no`() async throws { let (status, body) = try await call(.post, "/api/v1/iris/apps/1234567890/compliance-requirements/req-1/declare", body: #"{"answer":"maybe"}"#) diff --git a/Tests/ASCKitTests/Iris/Compliance/ComplianceAnswerTests.swift b/Tests/ASCKitTests/Iris/Compliance/ComplianceAnswerTests.swift new file mode 100644 index 00000000..74a61647 --- /dev/null +++ b/Tests/ASCKitTests/Iris/Compliance/ComplianceAnswerTests.swift @@ -0,0 +1,92 @@ +import Foundation +import Mockable +import Testing +@testable import ASCKit + +@Suite +struct ComplianceAnswerTests { + private let proof = ComplianceFile(name: "proof.pdf", data: Data([1])) + private let report = ComplianceFile(name: "report.png", data: Data([2])) + + // MARK: - files + + @Test func `should type a file by its extension, ignoring case`() { + #expect(ComplianceFile(name: "report.PDF", data: Data()).mimeType == "application/pdf") + #expect(ComplianceFile(name: "proof.png", data: Data()).mimeType == "image/png") + #expect(ComplianceFile(name: "proof.jpg", data: Data()).mimeType == "image/jpeg") + #expect(ComplianceFile(name: "proof.jpeg", data: Data()).mimeType == "image/jpeg") + #expect(ComplianceFile(name: "agreement.doc", data: Data()).mimeType == "application/msword") + #expect(ComplianceFile(name: "agreement.docx", data: Data()).mimeType + == "application/vnd.openxmlformats-officedocument.wordprocessingml.document") + #expect(ComplianceFile(name: "notes.bin", data: Data()).mimeType == "application/octet-stream") + } + + // MARK: - a Yes carries its kind's evidence (law 3) + + @Test func `should build a Security Assessment Yes from its proof and report`() throws { + let answer = try ComplianceAnswer.offered(for: .securityAssessment, evidence: ComplianceEvidenceInput(proof: proof, report: report)) + + #expect(answer == .offered(.securityAssessment(proof: proof, report: report))) + } + + @Test func `should refuse a Security Assessment Yes without its report`() { + #expect(throws: ComplianceError.evidenceMissing(kind: .securityAssessment, missing: ["the Security Assessment Report"])) { + try ComplianceAnswer.offered(for: .securityAssessment, evidence: ComplianceEvidenceInput(proof: proof)) + } + } + + @Test func `should build an AIGC Yes from an LLM filing that uses no third-party technology`() throws { + let answer = try ComplianceAnswer.offered(for: .aiGeneratedContent, evidence: ComplianceEvidenceInput( + filingType: .largeLanguageModel, filingName: "Example Model", filingNumber: "Example-0000" + )) + + #expect(answer == .offered(.aiGeneratedContent( + filing: .largeLanguageModel(name: "Example Model", filingNumber: "Example-0000"), thirdParty: .none + ))) + } + + @Test func `should build an AIGC Yes whose third-party technology carries its authorization`() throws { + let agreement = ComplianceFile(name: "agreement.pdf", data: Data([3])) + + let answer = try ComplianceAnswer.offered(for: .aiGeneratedContent, evidence: ComplianceEvidenceInput( + filingType: .algorithm, filingName: "Recommender", filingNumber: "Algo-1", thirdPartyAuthorization: agreement + )) + + #expect(answer == .offered(.aiGeneratedContent( + filing: .algorithm(name: "Recommender", filingNumber: "Algo-1"), thirdParty: .used(authorization: agreement) + ))) + } + + @Test func `should refuse an AIGC Yes without its filing details`() { + #expect(throws: ComplianceError.evidenceMissing(kind: .aiGeneratedContent, missing: ["the filing type", "the filing number"])) { + try ComplianceAnswer.offered(for: .aiGeneratedContent, evidence: ComplianceEvidenceInput(filingName: "Example Model")) + } + } + + @Test func `should refuse a Yes for a compliance asc doesn't know`() { + #expect(throws: ComplianceError.notDeclarable(kind: .unrecognized(formName: "MEDICALDEV0001"), status: .missingInfo)) { + try ComplianceAnswer.offered(for: .unrecognized(formName: "MEDICALDEV0001"), evidence: ComplianceEvidenceInput()) + } + } + + @Test func `should say what a Yes still needs`() { + #expect(ComplianceError.evidenceMissing(kind: .securityAssessment, missing: ["the Security Assessment Report"]).description + == "A Yes to Security Assessment needs the Security Assessment Report.") + #expect(ComplianceError.evidenceMissing(kind: .aiGeneratedContent, missing: ["the filing type", "the filing number"]).description + == "A Yes to AI Generated or Synthetic Content needs the filing type and the filing number.") + } + + // MARK: - the evidence must be the requirement's own + + @Test func `should refuse evidence made for another compliance, sending nothing`() async { + let aigc = ComplianceRequirement(id: "req-2", appId: "1234567890", kind: .aiGeneratedContent, regions: ["CHN"], isRequired: true, + status: .missingInfo, updatedAt: nil, requiredActions: [], declaration: nil) + let repo = MockIrisComplianceRepository() + + await #expect(throws: ComplianceError.evidenceMismatch(kind: .aiGeneratedContent)) { + try await aigc.declare(.offered(.securityAssessment(proof: proof, report: report)), + session: IrisSession(cookies: "c"), repo: repo) + } + verify(repo).declare(session: .any, requirement: .any, answer: .any).called(0) + } +} diff --git a/Tests/ASCKitTests/Iris/Compliance/Internal/IrisSDKComplianceDeclareYesTests.swift b/Tests/ASCKitTests/Iris/Compliance/Internal/IrisSDKComplianceDeclareYesTests.swift new file mode 100644 index 00000000..bb4b2622 --- /dev/null +++ b/Tests/ASCKitTests/Iris/Compliance/Internal/IrisSDKComplianceDeclareYesTests.swift @@ -0,0 +1,188 @@ +import Foundation +import Mockable +import Testing +@testable import ASCKit + +/// Apple's two forms as captured (docs/features/app-compliance/design.md): each metadata +/// post answers with the fields the answers so far open. +private enum CapturedForms { + static let files = #"[".doc",".docx",".jpeg",".jpg",".pdf",".png"]"# + + static func constraint(_ id: String, _ type: String, form: String, slug: String, files: Bool = false) -> String { + #""\#(id)": { "presentation": { "id": "\#(id)", "inputType": "\#(type)", "label": "PPM.compliance.form.\#(form).field.\#(slug).label" }, "validation": { "required": true, "editable": true\#(files ? #", "allowedFileTypes": \#(Self.files)"# : "") } }"# + } + + /// The Security Assessment form for a draft. + static func securityAssessment(_ draft: [String: String]) -> String { + var fields = [constraint("field-1", "RADIO", form: "SECURITYASF395E", slug: "doesyourap2852f")] + if draft["field-1"] == "YES" { + fields.append(constraint("field-2", "FILE", form: "SECURITYASF395E", slug: "proofofacocb097", files: true)) + fields.append(constraint("field-3", "FILE", form: "SECURITYASF395E", slug: "securityascf4ff1", files: true)) + } + return #"{ "formName": "SECURITYASF395E", "constraints": { \#(fields.joined(separator: ", ")) } }"# + } + + /// The AIGC form for a draft: a tree, each pick opening its branch. + static func aiGeneratedContent(_ draft: [String: String]) -> String { + let form = "AIGENERATEFD1DE" + var fields = [constraint("aigc-offers", "RADIO", form: form, slug: "doesyourap268df2")] + if draft["aigc-offers"] == "YES" { + fields.append(constraint("filing-type", "RADIO", form: form, slug: "whichfilinc6deb2")) + fields.append(constraint("third-party", "RADIO", form: form, slug: "areyourappd75c12")) + if draft["filing-type"] == "LARGE" { + fields.append(constraint("llm-name", "TEXT", form: form, slug: "llmname2")) + fields.append(constraint("llm-filing", "TEXT", form: form, slug: "llmfilingnumber4")) + } + if draft["filing-type"] == "ALGOR" { + fields.append(constraint("algorithm-name", "TEXT", form: form, slug: "algorithmname2")) + fields.append(constraint("algorithm-filing", "TEXT", form: form, slug: "algorithmf737252")) + } + if draft["third-party"] == "YES" { + fields.append(constraint("authorization", "FILE", form: form, slug: "authorizat9286a3", files: true)) + } + } + return #"{ "formName": "\#(form)", "constraints": { \#(fields.joined(separator: ", ")) } }"# + } + + /// The draft a metadata post carries: each field's `sValue`, or "FILE" for an attached file. + static func draft(of body: Data) -> [String: String] { + let json = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any] + let fields = ((json?["form"] as? [String: Any])?["fields"] as? [[String: Any]]) ?? [] + return Dictionary(uniqueKeysWithValues: fields.map { ($0["id"] as! String, ($0["sValue"] as? String) ?? "FILE") }) + } +} + +@Suite +struct IrisSDKComplianceDeclareYesTests { + private let session = IrisSession(cookies: "myacinfo=a") + private let entity = "accounts/team-uuid/entities/1234567890" + + private func ok(_ json: String) -> (Data, HTTPURLResponse) { + (Data(json.utf8), HTTPURLResponse(url: URL(string: "https://appstoreconnect.apple.com")!, statusCode: 200, httpVersion: nil, headerFields: nil)!) + } + + private func accounts() -> MockAppStoreConnectAccounts { + let accounts = MockAppStoreConnectAccounts() + given(accounts).fetchSession(cookies: .any) + .willReturn(OlympusClient.OlympusSession(providerID: 42, teamId: "team-uuid", userEmail: "dev@example.com")) + return accounts + } + + private func apple(requirementId: String, form: @escaping @Sendable ([String: String]) -> String) -> MockIrisAPI { + let api = MockIrisAPI() + given(api).compliancePost(path: .value("\(entity)/requirements/\(requirementId)/metadata"), body: .any, cookies: .any) + .willProduce { _, body, _ in self.ok(form(CapturedForms.draft(of: body))) } + given(api).compliancePost(path: .value("\(entity)/forms"), body: .any, cookies: .any) + .willReturn(ok(#"{ "data": { "id": "form-9", "requirementId": "\#(requirementId)", "formName": "X", "fields": [], "status": "COLLECTED_VERIFY_PENDING" } }"#)) + given(api).complianceGet(path: .any, queryItems: .any, cookies: .any).willReturn(ok(#"{ "data": [] }"#)) + return api + } + + private func requirement(_ id: String, _ kind: ComplianceKind) -> ComplianceRequirement { + ComplianceRequirement(id: id, appId: "1234567890", kind: kind, regions: ["CHN"], isRequired: true, + status: .missingInfo, updatedAt: nil, requiredActions: [], declaration: nil) + } + + private func savedBody(_ api: MockIrisAPI, requirementId: String, fields: String) { + verify(api).compliancePost( + path: .value("\(entity)/forms"), + body: .value(Data(#"{"accountId":"team-uuid","entityId":"1234567890","fields":[\#(fields)],"requirementId":"\#(requirementId)"}"#.utf8)), + cookies: .any + ).called(1) + } + + @Test func `should send a Security Assessment Yes with both files inside the declaration`() async throws { + let api = apple(requirementId: "req-1", form: CapturedForms.securityAssessment) + let answer = ComplianceAnswer.offered(.securityAssessment( + proof: ComplianceFile(name: "proof.png", data: Data("P".utf8)), + report: ComplianceFile(name: "report.pdf", data: Data("R".utf8)) + )) + + _ = try await IrisSDKComplianceRepository(api: api, accounts: accounts()) + .declare(session: session, requirement: requirement("req-1", .securityAssessment), answer: answer) + + savedBody(api, requirementId: "req-1", fields: [ + #"{"id":"field-1","sValue":"YES"}"#, + #"{"fileContent":{"fileData":"UA==","fileName":"proof.png","fileType":"image/png"},"id":"field-2"}"#, + #"{"fileContent":{"fileData":"Ug==","fileName":"report.pdf","fileType":"application/pdf"},"id":"field-3"}"#, + ].joined(separator: ",")) + } + + @Test func `should walk the AIGC form one answer at a time and send every field it opened`() async throws { + let api = apple(requirementId: "req-2", form: CapturedForms.aiGeneratedContent) + let answer = ComplianceAnswer.offered(.aiGeneratedContent( + filing: .largeLanguageModel(name: "Example Model", filingNumber: "Example-0000"), + thirdParty: .used(authorization: ComplianceFile(name: "agreement.pdf", data: Data("A".utf8))) + )) + + _ = try await IrisSDKComplianceRepository(api: api, accounts: accounts()) + .declare(session: session, requirement: requirement("req-2", .aiGeneratedContent), answer: answer) + + savedBody(api, requirementId: "req-2", fields: [ + #"{"id":"aigc-offers","sValue":"YES"}"#, + #"{"id":"filing-type","sValue":"LARGE"}"#, + #"{"id":"third-party","sValue":"YES"}"#, + #"{"fileContent":{"fileData":"QQ==","fileName":"agreement.pdf","fileType":"application/pdf"},"id":"authorization"}"#, + #"{"id":"llm-filing","sValue":"Example-0000"}"#, + #"{"id":"llm-name","sValue":"Example Model"}"#, + ].joined(separator: ",")) + } + + @Test func `should send an algorithm filing without third-party technology`() async throws { + let api = apple(requirementId: "req-2", form: CapturedForms.aiGeneratedContent) + let answer = ComplianceAnswer.offered(.aiGeneratedContent( + filing: .algorithm(name: "Recommender", filingNumber: "Algo-1"), thirdParty: .none + )) + + _ = try await IrisSDKComplianceRepository(api: api, accounts: accounts()) + .declare(session: session, requirement: requirement("req-2", .aiGeneratedContent), answer: answer) + + savedBody(api, requirementId: "req-2", fields: [ + #"{"id":"aigc-offers","sValue":"YES"}"#, + #"{"id":"filing-type","sValue":"ALGOR"}"#, + #"{"id":"third-party","sValue":"NO"}"#, + #"{"id":"algorithm-filing","sValue":"Algo-1"}"#, + #"{"id":"algorithm-name","sValue":"Recommender"}"#, + ].joined(separator: ",")) + } + + @Test func `should refuse a file type the form doesn't accept, without saving`() async { + let api = apple(requirementId: "req-1", form: CapturedForms.securityAssessment) + let answer = ComplianceAnswer.offered(.securityAssessment( + proof: ComplianceFile(name: "proof.zip", data: Data("P".utf8)), + report: ComplianceFile(name: "report.pdf", data: Data("R".utf8)) + )) + + await #expect(throws: ComplianceError.fileTypeNotAllowed(fileName: "proof.zip", allowed: [".doc", ".docx", ".jpeg", ".jpg", ".pdf", ".png"])) { + try await IrisSDKComplianceRepository(api: api, accounts: accounts()) + .declare(session: session, requirement: requirement("req-1", .securityAssessment), answer: answer) + } + verify(api).compliancePost(path: .value("\(entity)/forms"), body: .any, cookies: .any).called(0) + } + + @Test func `should refuse a form that asks for something asc can't answer, without saving`() async { + let api = apple(requirementId: "req-1") { draft in + var form = CapturedForms.securityAssessment(draft) + if draft["field-1"] == "YES" { + form = form.replacingOccurrences(of: "proofofacocb097", with: "businesslic0001") + } + return form + } + let answer = ComplianceAnswer.offered(.securityAssessment( + proof: ComplianceFile(name: "proof.png", data: Data()), report: ComplianceFile(name: "report.pdf", data: Data()) + )) + + await #expect(throws: ComplianceError.formNotUnderstood(kind: .securityAssessment, field: "businesslic0001")) { + try await IrisSDKComplianceRepository(api: api, accounts: accounts()) + .declare(session: session, requirement: requirement("req-1", .securityAssessment), answer: answer) + } + verify(api).compliancePost(path: .value("\(entity)/forms"), body: .any, cookies: .any).called(0) + } + + @Test func `should explain a refused file and a form it doesn't understand`() { + #expect(ComplianceError.fileTypeNotAllowed(fileName: "proof.zip", allowed: [".pdf", ".png"]).description + == "proof.zip can't be sent: this field takes .pdf, .png.") + #expect(ComplianceError.formNotUnderstood(kind: .securityAssessment, field: "businesslic0001").description + == "Apple's Security Assessment form asks for something asc doesn't know (businesslic0001). Answer it on the App Compliance page.") + } +} From 64b89ab6e7cca5de24d05999e5d06611368133dc Mon Sep 17 00:00:00 2001 From: slamhan Date: Thu, 19 Nov 2026 21:43:40 +0800 Subject: [PATCH 08/12] docs(app-compliance): user guide, REST, CHANGELOG, and what the build settled docs/features/app-compliance/README.md: list, answer No, answer Yes with evidence, what asc checks before saving, and REST. Linked from the iris README. The design is marked built (slices 1-5, 7) and records what the build settled: the listed declaration holds only the answer, the account comes from olympus on every call, declare is one loop over Apple's form, and the REST statuses. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 + docs/README.md | 1 + docs/commands.md | 32 ++++++++++ docs/features/app-compliance/README.md | 84 ++++++++++++++++++++++++++ docs/features/app-compliance/design.md | 11 +++- docs/features/iris/README.md | 3 + 6 files changed, 133 insertions(+), 1 deletion(-) create mode 100644 docs/features/app-compliance/README.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 3098f591..b94d9588 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-compliance list` and `declare` answer an app's App Compliance page (China mainland Security Assessment, AI generated content), No or Yes with its evidence, over CLI and REST. → [docs](docs/features/app-compliance/README.md) + ### Changed - `asc versions submit` and `POST /api/v1/versions/:id/submit` refuse a version that can't be edited (e.g. Ready for Sale) before calling Apple, saying which states can go to review. - **Breaking (library):** one `ASCKit` module (`import ASCKit`); 7 non-CRUD repositories take role names (`IrisAuthRepository` → `IrisSignIn`, …); `SubmissionRepository.submitVersion` → `AppStoreVersion.submitForReview(to:)`. → [design](docs/features/concept-folders/design.md) diff --git a/docs/README.md b/docs/README.md index f9f28c8d..1ec8ffea 100644 --- a/docs/README.md +++ b/docs/README.md @@ -7,6 +7,7 @@ New here? Start with the [README](../README.md). For every flag, see the [comman |---|---| | [age-rating](features/age-rating/README.md) | Read and update an app's age rating declaration (content descriptors, kids age band, regional overrides). Use when answering the age rating questionnaire or changing the store age rating. | | [app-clips](features/app-clips/README.md) | Manage App Clips, their default experiences, and the localized subtitles shown on App Clip cards. Use when setting up or editing an App Clip card. | +| [app-compliance](features/app-compliance/README.md) | List and answer an app's App Compliance requirements (China mainland Security Assessment, AI generated content) via the iris web session. Use when App Store Connect asks for compliance info to keep an app on sale in a region. | | [app-icons](features/app-icons/README.md) | REST-only option that enriches the apps list with each app's icon as a sizable image template. Use when a client needs to render app icons from asc web-server. | | [app-info-localizations](features/app-info-localizations/README.md) | Manage per-locale app metadata (name, subtitle, privacy policy URL and text) on the App Store listing. Use when renaming the app, setting a subtitle, or adding a new listing locale. | | [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. | diff --git a/docs/commands.md b/docs/commands.md index a352cfab..69abfadb 100644 --- a/docs/commands.md +++ b/docs/commands.md @@ -4311,6 +4311,38 @@ asc iris resolution-center get --submission-id [--plain-text] [- | `--plain-text` | | | Convert HTML message bodies to plain text | | `--out` | | | Directory to download attachments into (created if missing) | +### asc iris app-compliance list + +List every App Compliance requirement for an app, answered or not + +``` +asc iris app-compliance list --app-id +``` + +| Flag | Required | Default | Description | +|---|---|---|---| +| `--app-id` | yes | | App ID | + +### asc iris app-compliance declare + +Answer an App Compliance requirement + +``` +asc iris app-compliance declare --app-id --requirement-id --answer [--proof ] [--report ] [--filing-type ] [--filing-name ] [--filing-number ] [--third-party-authorization ] +``` + +| Flag | Required | Default | Description | +|---|---|---|---| +| `--app-id` | yes | | App ID | +| `--requirement-id` | yes | | Requirement ID, from `asc iris app-compliance list` | +| `--answer` | yes | | yes or no One of: yes, no. | +| `--proof` | | | Security Assessment: the proof of a completed assessment (file) | +| `--report` | | | Security Assessment: the assessment report (file) | +| `--filing-type` | | | AIGC: llm or algorithm One of: algorithm, llm. | +| `--filing-name` | | | AIGC: the LLM or algorithm name, as filed | +| `--filing-number` | | | AIGC: the filing number | +| `--third-party-authorization` | | | AIGC: the authorization or usage agreement for third-party technology (file) | + ### asc iris auth login Sign in with Apple ID + password via SRP. Prompts for the 2FA code separately. diff --git a/docs/features/app-compliance/README.md b/docs/features/app-compliance/README.md new file mode 100644 index 00000000..7f8d1225 --- /dev/null +++ b/docs/features/app-compliance/README.md @@ -0,0 +1,84 @@ +--- +description: List and answer an app's App Compliance requirements (China mainland Security Assessment, AI generated content) via the iris web session. Use when App Store Connect asks for compliance info to keep an app on sale in a region. +--- + +# App Compliance + +Read and answer the requirements on an app's **App Compliance** page: the declarations an app keeps current so it can stay on the App Store in a regulated region. Today that is China mainland's **Security Assessment** and **AI Generated or Synthetic Content** (AIGC). 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). + +## Quick start + +```bash +asc iris app-compliance list --app-id 1234567890 --pretty +asc iris app-compliance declare --app-id 1234567890 --requirement-id --answer no +``` + +## Workflows + +### See what the app still owes + +```bash +asc iris app-compliance list --app-id 1234567890 --output table +``` + +Each requirement is a row, answered or not, with the page's STATUS: + +| Status | Meaning | `declare` | +|---|---|---| +| `MISSING_INFO` | Nobody has answered it | offered: a first answer | +| `PENDING_VERIFICATION` | Apple is checking a Yes; `requiredActions: APP_BINARY_SUBMISSION` means it's checked with your next submission for review | not offered: Apple serves it read-only | +| `ACTIVE` | Answered, nothing pending: the app may stay on sale in the region | offered: a change | +| `VERIFICATION_FAILED` | Apple rejected the evidence | offered: a resubmission | + +A compliance or status asc doesn't know yet is still listed, as Apple names it, and is never offered `declare`. A row also says which next commands apply (`affordances`, or `_links` over REST). + +### Answer No + +The app doesn't offer the regulated feature in China mainland, or it's disabled or geoblocked there: + +```bash +asc iris app-compliance declare --app-id 1234567890 --requirement-id --answer no +``` + +A No needs nothing from Apple: the row turns `ACTIVE`. + +### Answer Yes with evidence + +A Yes must carry its compliance's evidence. Files are `.doc`, `.docx`, `.jpeg`, `.jpg`, `.pdf` or `.png`, and travel inside the declaration. + +```bash +# Security Assessment: the proof of a completed assessment, and the assessment report +asc iris app-compliance declare --app-id 1234567890 --requirement-id --answer yes \ + --proof ./proof.pdf --report ./report.pdf + +# AI Generated or Synthetic Content: the filing, and the third-party agreement if one applies +asc iris app-compliance declare --app-id 1234567890 --requirement-id --answer yes \ + --filing-type llm --filing-name "Example Model" --filing-number "Example-0000" \ + --third-party-authorization ./agreement.pdf +``` + +`--filing-type` is `llm` or `algorithm`. Leave out `--third-party-authorization` when the AI features aren't powered by third-party technology. A Yes goes to `PENDING_VERIFICATION`: Apple checks the files and the filing details. + +## What asc checks before it saves + +- **It asks Apple for the form first**, the way the page does, one answer at a time, and saves exactly the fields Apple asks for. A field it can't fill, or a form Apple serves read-only, stops it before anything is written. +- **Missing evidence is named** ("A Yes to Security Assessment needs the Security Assessment Report.") and nothing is sent. +- **A file type the field doesn't take** is refused before saving. +- **A requirement is found by its id and the app together**: Apple uses the same requirement id on every app. +- **If Apple forbids the save**, you're told your App Store Connect role can't edit App Compliance for that app. + +## REST + +| Method | Path | CLI equivalent | +|---|---|---| +| GET | `/api/v1/iris/apps/:appId/compliance-requirements` | `asc iris app-compliance list` | +| POST | `/api/v1/iris/apps/:appId/compliance-requirements/:requirementId/declare` | `asc iris app-compliance declare` | + +The declare body is `{"answer": "no"}`, or for a Yes, `{"answer": "yes", "evidence": {…}}` with `proof`, `report` and `thirdPartyAuthorization` as `{"name": "proof.pdf", "data": ""}`, and `filingType` (`llm` / `algorithm`), `filingName`, `filingNumber` as strings. A refusal answers with its reason: 404 (no such requirement on the app), 409 (Apple is verifying it, or serves it read-only), 422 (evidence missing or of the wrong type), 403 (your role can't edit). + +## Not the same as + +- **Export compliance** (`usesNonExemptEncryption` on a build): see `asc builds`, a public-API resource. +- **Age rating**: see [Age rating](../age-rating/README.md). + +Design, wire format and open questions: [design.md](design.md). diff --git a/docs/features/app-compliance/design.md b/docs/features/app-compliance/design.md index 987b4507..1d0a0f74 100644 --- a/docs/features/app-compliance/design.md +++ b/docs/features/app-compliance/design.md @@ -1,6 +1,6 @@ # App Compliance — "Does your app offer AIGC services in China mainland?" -**Status: DESIGN. Nothing is built.** Apple has no public API for App Compliance: it is absent from appstoreconnect-swift-sdk 4.6.1 and from Apple's own OpenAPI spec 4.6 (checked 2026-11-17). The web UI reads it from a private service outside `/iris/v1`, `ppm/compliancerequirements/v1`, which uses the same Apple ID session cookies. These calls have been captured (below): the requirements list (before and after a Yes was saved), the declarations, the form metadata for both kinds, with its request, and with Yes picked for each, a draft carrying files, the save of a first No (on two apps) and the save of an AIGC Yes with a file. and the save of a change to an Active declaration. Every read and write the page makes is captured. +**Status: BUILT** (slices 1–5 and 7: list, declare No, declare Yes with evidence, CLI and REST). Slice 6, the check-readiness warning, waits on the list shipping. User guide: [README.md](README.md). Apple has no public API for App Compliance: it is absent from appstoreconnect-swift-sdk 4.6.1 and from Apple's own OpenAPI spec 4.6 (checked 2026-11-17). The web UI reads it from a private service outside `/iris/v1`, `ppm/compliancerequirements/v1`, which uses the same Apple ID session cookies. Every read and write the page makes is captured (below). This document owns **the declarations an app keeps current so it can stay on the store in a regulated region**. Its neighbours own the rest: @@ -524,6 +524,15 @@ The iris repositories reach Apple through the `@Mockable IrisAPI` role, played b 6. **Readiness** (after the list ships): `AppCompliance` collection + availability; check-readiness warns for a non-Active requirement only in a region the app is sold in (Open question 6). 7. **Docs**: `README.md` for users, one CHANGELOG line, `make docs`, and a link from the iris README's "Other iris commands". +## 6a · What the build settled + +- **The declaration the list reads holds only the answer.** `ComplianceDeclaration` is `{ id, answer: YES | NO }`; a Yes's evidence stays with Apple, since naming its stored fields would need the metadata for every row. The evidence types (`ComplianceEvidence`) are what a Yes *sends*. +- **The account is asked of olympus on every call**, not read from a saved `teamId`, so a browser-cookie or `ASC_IRIS_COOKIES` session works the same as `asc iris auth login`. No `publicProviderId` → `ComplianceError.teamUnknown`. +- **Law 1's owner is `ComplianceStatus(wireValue:)`**: Apple already sends `PENDING_COLLECT` for an unanswered requirement. +- **The answer a form holds is its first field**, the Yes/No it opens with; only a Yes opens more fields. +- **`declare` is one loop for every answer**: post the draft to `…/metadata`, fill each field Apple newly asks for (by the key in its label), repeat until Apple asks for nothing new, then save exactly those fields. Any field Apple won't take a change to stops it (law 5a). A No ends after its first pick. +- **REST statuses**: 404 no such requirement on the app; 409 not declarable now, read-only, or a form asc doesn't understand; 422 evidence missing, mismatched or of a type the field refuses; 403 the role can't edit; 401 no team. + ## 7 · Open questions 1. ~~**Where does the list of applicable requirements come from?**~~ **ANSWERED: `…/accounts/{accountId}/requirements?entity_id={appId}`.** It lists answered and unanswered requirements, with `formName`, `countries`, `isRequired` and `status` (`PENDING_COLLECT` when unanswered). No hard-coded list is needed. diff --git a/docs/features/iris/README.md b/docs/features/iris/README.md index 78dfa5ea..bf85147c 100644 --- a/docs/features/iris/README.md +++ b/docs/features/iris/README.md @@ -96,6 +96,7 @@ Apps from `asc iris apps list` / `create` carry `listVersions` and `listAppInfos - `asc iris iap-submissions create|delete` — queue an IAP with the next app version, or dequeue it. See [Submit with products](../submit-with-products/README.md). - `asc iris resolution-center get` — read App Review's rejection messages. See [Resolution Center](../resolution-center/README.md). +- `asc iris app-compliance list|declare` — answer the App Compliance page (China mainland Security Assessment, AIGC). See [App Compliance](../app-compliance/README.md). ## REST @@ -104,6 +105,8 @@ Apps from `asc iris apps list` / `create` carry `listVersions` and `listAppInfos | POST | `/api/v1/iris/iap/:iapId/submissions` | `asc iris iap-submissions create` | | DELETE | `/api/v1/iris/iap-submissions/:submissionId` | `asc iris iap-submissions delete` | | GET | `/api/v1/iris/review-submissions/:submissionId/resolution-center` | `asc iris resolution-center get` | +| GET | `/api/v1/iris/apps/:appId/compliance-requirements` | `asc iris app-compliance list` | +| POST | `/api/v1/iris/apps/:appId/compliance-requirements/:requirementId/declare` | `asc iris app-compliance declare` | ## Gotchas From 77698e3ea33761a3998648474151839f4865ff26 Mon Sep 17 00:00:00 2001 From: slamhan Date: Thu, 19 Nov 2026 21:54:20 +0800 Subject: [PATCH 09/12] fix(app-compliance): list a new app whose declarations Apple answers as {} Seen live: for an app with no declarations, the declarations call answers {} with no data key, which failed the whole list. It now reads as no declarations. The design records it, with what was verified live on a test app: list, a first No on each form, a change, and the refusal on a Pending Verification row. Co-Authored-By: Claude Opus 5.5 --- .../Iris/Compliance/Internal/ComplianceWire.swift | 8 ++++++++ .../Internal/IrisSDKComplianceRepositoryTests.swift | 10 ++++++++++ docs/features/app-compliance/design.md | 2 ++ 3 files changed, 20 insertions(+) diff --git a/Sources/ASCKit/Iris/Compliance/Internal/ComplianceWire.swift b/Sources/ASCKit/Iris/Compliance/Internal/ComplianceWire.swift index 4457df2d..2434c3af 100644 --- a/Sources/ASCKit/Iris/Compliance/Internal/ComplianceWire.swift +++ b/Sources/ASCKit/Iris/Compliance/Internal/ComplianceWire.swift @@ -104,6 +104,14 @@ struct ComplianceSaveRequest: Encodable { struct ComplianceFormsResponse: Decodable { let data: [ComplianceFormResource] + + /// An app with no declarations yet is answered `{}`, with no `data` (seen live). + init(from decoder: any Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + data = try c.decodeIfPresent([ComplianceFormResource].self, forKey: .data) ?? [] + } + + private enum CodingKeys: String, CodingKey { case data } } struct ComplianceFormResponse: Decodable { diff --git a/Tests/ASCKitTests/Iris/Compliance/Internal/IrisSDKComplianceRepositoryTests.swift b/Tests/ASCKitTests/Iris/Compliance/Internal/IrisSDKComplianceRepositoryTests.swift index 2984a237..2be81df3 100644 --- a/Tests/ASCKitTests/Iris/Compliance/Internal/IrisSDKComplianceRepositoryTests.swift +++ b/Tests/ASCKitTests/Iris/Compliance/Internal/IrisSDKComplianceRepositoryTests.swift @@ -54,6 +54,16 @@ struct IrisSDKComplianceRepositoryTests { ]) } + @Test func `should list a new app's requirements when Apple has no declarations for it`() async throws { + // Seen live on a new app: the declarations call answers `{}`, with no `data`. + let repo = IrisSDKComplianceRepository(api: iris(requirements: unanswered, forms: "{}"), accounts: signedInTo(team: "team-uuid")) + + let rows = try await repo.listRequirements(session: session, appId: "1234567890") + + #expect(rows.map(\.status) == [.missingInfo, .missingInfo]) + #expect(rows.map(\.declaration) == [nil, nil]) + } + @Test func `should attach each declaration to the requirement it answers`() async throws { let requirements = #""" { "data": [ diff --git a/docs/features/app-compliance/design.md b/docs/features/app-compliance/design.md index 1d0a0f74..2913975d 100644 --- a/docs/features/app-compliance/design.md +++ b/docs/features/app-compliance/design.md @@ -531,6 +531,8 @@ The iris repositories reach Apple through the `@Mockable IrisAPI` role, played b - **Law 1's owner is `ComplianceStatus(wireValue:)`**: Apple already sends `PENDING_COLLECT` for an unanswered requirement. - **The answer a form holds is its first field**, the Yes/No it opens with; only a Yes opens more fields. - **`declare` is one loop for every answer**: post the draft to `…/metadata`, fill each field Apple newly asks for (by the key in its label), repeat until Apple asks for nothing new, then save exactly those fields. Any field Apple won't take a change to stops it (law 5a). A No ends after its first pick. +- **An app with no declarations gets `{}` from the declarations call**, not `{"data": []}` (seen live on a new app); it reads as no declarations. +- **Verified live** (2026-11-19, on a test app): list on a new app (both Missing Info), a first No on each form (`POST`, → Active), a change to an Active one (`PUT`, same declaration id, new LAST UPDATED), and the refusal on a Pending Verification row before anything is sent. A Yes was not sent live: it would put placeholder evidence in front of Apple. - **REST statuses**: 404 no such requirement on the app; 409 not declarable now, read-only, or a form asc doesn't understand; 422 evidence missing, mismatched or of a type the field refuses; 403 the role can't edit; 401 no team. ## 7 · Open questions From b660147c19bbca27117c1441b2985efd3447d55d Mon Sep 17 00:00:00 2001 From: slamhan Date: Thu, 19 Nov 2026 22:06:49 +0800 Subject: [PATCH 10/12] refactor(app-compliance): list from the page's own call The App Compliance page draws its table from the requirements call alone (seen in the browser), and that call carries everything the row needs: name, regions, last updated, status, and the formId a change updates. list now makes only that call, and the row carries declarationId instead of a joined, fetched answer. Gone with the join: the second request per list, the orphan-declaration rows the page can never show, and the declarations call whose {} broke a new app. The service leaves out what is empty, so the requirements list reads a missing data as empty too. Fixtures are captured shapes; the guessed {"data": []} that let {} slip past the tests is gone. Verified live: three apps list as the page shows them, and a change still updates the same declaration. Co-Authored-By: Claude Opus 5.5 --- .../Iris/Compliance/ComplianceAnswer.swift | 18 --- .../Compliance/ComplianceRequirement.swift | 23 ++-- .../Compliance/Internal/ComplianceWire.swift | 57 ++-------- .../IrisSDKComplianceRepository.swift | 62 +++-------- .../Compliance/IrisAppComplianceTests.swift | 15 +-- .../IrisAppComplianceRoutesTests.swift | 4 +- .../Compliance/ComplianceAnswerTests.swift | 2 +- .../ComplianceRequirementTests.swift | 23 ++-- .../IrisSDKComplianceDeclareYesTests.swift | 4 +- .../IrisSDKComplianceRepositoryTests.swift | 104 ++++++------------ docs/features/app-compliance/design.md | 19 ++-- 11 files changed, 102 insertions(+), 229 deletions(-) diff --git a/Sources/ASCKit/Iris/Compliance/ComplianceAnswer.swift b/Sources/ASCKit/Iris/Compliance/ComplianceAnswer.swift index 7416362f..38606e85 100644 --- a/Sources/ASCKit/Iris/Compliance/ComplianceAnswer.swift +++ b/Sources/ASCKit/Iris/Compliance/ComplianceAnswer.swift @@ -135,21 +135,3 @@ public struct ComplianceEvidenceInput: Sendable, Equatable { self.thirdPartyAuthorization = thirdPartyAuthorization } } - -/// An answer Apple holds for a requirement. Apple's API calls it a *form*. -/// The evidence of a Yes stays with Apple; the list shows only the answer. -public struct ComplianceDeclaration: Sendable, Equatable, Codable { - public enum Answer: String, Sendable, Equatable, Codable { - case yes = "YES" - case no = "NO" - } - - /// Apple's form id: what a change updates. - public let id: String - public let answer: Answer - - public init(id: String, answer: Answer) { - self.id = id - self.answer = answer - } -} diff --git a/Sources/ASCKit/Iris/Compliance/ComplianceRequirement.swift b/Sources/ASCKit/Iris/Compliance/ComplianceRequirement.swift index 9daf1cc0..b4300498 100644 --- a/Sources/ASCKit/Iris/Compliance/ComplianceRequirement.swift +++ b/Sources/ASCKit/Iris/Compliance/ComplianceRequirement.swift @@ -1,5 +1,5 @@ -/// One row on an app's App Compliance page: a compliance that applies to the app in -/// a region, and the declaration that answers it. Apple's requirement id names the +/// One row on an app's App Compliance page: a compliance that applies to the app in a +/// region, as the page draws it from Apple's requirements alone. Apple's requirement id names the /// compliance for the whole account, so a row is the id **and** its app (law 2). public struct ComplianceRequirement: Sendable, Equatable, Identifiable, Codable { public let id: String @@ -13,13 +13,13 @@ public struct ComplianceRequirement: Sendable, Equatable, Identifiable, Codable /// LAST UPDATED, as Apple's ISO 8601 `lastUpdatedDate`; nil = never answered. public let updatedAt: String? public let requiredActions: [ComplianceRequiredAction] - /// nil = never answered. - public let declaration: ComplianceDeclaration? + /// The declaration that answers it (Apple's `formId`): what a change updates. nil = never answered. + public let declarationId: String? public init( id: String, appId: String, kind: ComplianceKind, regions: [String], isRequired: Bool, status: ComplianceStatus, updatedAt: String?, requiredActions: [ComplianceRequiredAction], - declaration: ComplianceDeclaration? + declarationId: String? ) { self.id = id self.appId = appId @@ -29,7 +29,7 @@ public struct ComplianceRequirement: Sendable, Equatable, Identifiable, Codable self.status = status self.updatedAt = updatedAt self.requiredActions = requiredActions - self.declaration = declaration + self.declarationId = declarationId } /// A first answer (Missing Info), a change (Active) or a resubmission (Verification @@ -47,7 +47,7 @@ public struct ComplianceRequirement: Sendable, Equatable, Identifiable, Codable } private enum CodingKeys: String, CodingKey { - case id, appId, kind, name, regions, isRequired, status, updatedAt, requiredActions, declaration + case id, appId, kind, name, regions, isRequired, status, updatedAt, requiredActions, declarationId } public init(from decoder: any Decoder) throws { @@ -61,7 +61,7 @@ public struct ComplianceRequirement: Sendable, Equatable, Identifiable, Codable status: try c.decode(ComplianceStatus.self, forKey: .status), updatedAt: try c.decodeIfPresent(String.self, forKey: .updatedAt), requiredActions: try c.decode([ComplianceRequiredAction].self, forKey: .requiredActions), - declaration: try c.decodeIfPresent(ComplianceDeclaration.self, forKey: .declaration) + declarationId: try c.decodeIfPresent(String.self, forKey: .declarationId) ) } @@ -76,7 +76,7 @@ public struct ComplianceRequirement: Sendable, Equatable, Identifiable, Codable try c.encode(status, forKey: .status) try c.encodeIfPresent(updatedAt, forKey: .updatedAt) try c.encode(requiredActions, forKey: .requiredActions) - try c.encodeIfPresent(declaration, forKey: .declaration) + try c.encodeIfPresent(declarationId, forKey: .declarationId) } } @@ -94,9 +94,8 @@ extension ComplianceRequirement: AffordanceProviding { } extension ComplianceRequirement: Presentable { - public static var tableHeaders: [String] { ["Requirement ID", "Compliance", "Regions", "Status", "Answer", "Last Updated"] } + public static var tableHeaders: [String] { ["Requirement ID", "Compliance", "Regions", "Last Updated", "Status"] } public var tableRow: [String] { - [id, kind.displayName, regions.joined(separator: ", "), status.displayName, - declaration?.answer.rawValue ?? "-", updatedAt ?? "-"] + [id, kind.displayName, regions.joined(separator: ", "), updatedAt ?? "-", status.displayName] } } diff --git a/Sources/ASCKit/Iris/Compliance/Internal/ComplianceWire.swift b/Sources/ASCKit/Iris/Compliance/Internal/ComplianceWire.swift index 2434c3af..0e1e0a7a 100644 --- a/Sources/ASCKit/Iris/Compliance/Internal/ComplianceWire.swift +++ b/Sources/ASCKit/Iris/Compliance/Internal/ComplianceWire.swift @@ -3,8 +3,17 @@ import Foundation // The App Compliance service's JSON (`ppm/compliancerequirements/v1`), as captured in // docs/features/app-compliance/design.md. Only what the domain reads is decoded. +/// The service leaves out what is empty (a new app's declarations came back `{}`), so a +/// missing list reads as an empty one. struct ComplianceRequirementsResponse: Decodable { let data: [ComplianceRequirementResource] + + init(from decoder: any Decoder) throws { + let c = try decoder.container(keyedBy: CodingKeys.self) + data = try c.decodeIfPresent([ComplianceRequirementResource].self, forKey: .data) ?? [] + } + + private enum CodingKeys: String, CodingKey { case data } } struct ComplianceRequirementResource: Decodable { @@ -101,51 +110,3 @@ struct ComplianceSaveRequest: Encodable { let formId: String? let fields: [ComplianceDraftField] } - -struct ComplianceFormsResponse: Decodable { - let data: [ComplianceFormResource] - - /// An app with no declarations yet is answered `{}`, with no `data` (seen live). - init(from decoder: any Decoder) throws { - let c = try decoder.container(keyedBy: CodingKeys.self) - data = try c.decodeIfPresent([ComplianceFormResource].self, forKey: .data) ?? [] - } - - private enum CodingKeys: String, CodingKey { case data } -} - -struct ComplianceFormResponse: Decodable { - let data: ComplianceFormResource -} - -/// A declaration, which Apple calls a form. -struct ComplianceFormResource: Decodable { - let id: String - let requirementId: String - let formName: String - let fields: [ComplianceFieldValue] - let status: String? -} - -/// One answered field. A `RADIO` or `TEXT` holds `sValue`; a `FILE` holds `fileContent`. -struct ComplianceFieldValue: Codable, Equatable { - let id: String - let sValue: String? - - init(id: String, sValue: String) { - self.id = id - self.sValue = sValue - } -} - -extension ComplianceFormResource { - /// The answer to the form's first question, the Yes/No every form opens with. - /// Only a Yes opens further fields, so a form with more than that one is a Yes. - var answer: ComplianceDeclaration.Answer { - switch fields.first?.sValue { - case "YES": .yes - case "NO": .no - default: fields.count > 1 ? .yes : .no - } - } -} diff --git a/Sources/ASCKit/Iris/Compliance/Internal/IrisSDKComplianceRepository.swift b/Sources/ASCKit/Iris/Compliance/Internal/IrisSDKComplianceRepository.swift index f89ab197..311e4c06 100644 --- a/Sources/ASCKit/Iris/Compliance/Internal/IrisSDKComplianceRepository.swift +++ b/Sources/ASCKit/Iris/Compliance/Internal/IrisSDKComplianceRepository.swift @@ -15,17 +15,26 @@ public struct IrisSDKComplianceRepository: IrisComplianceRepository { self.accounts = accounts } + /// The page's own call: every requirement, answered or not, with its status, date and + /// the declaration that answers it. The declarations themselves aren't read. public func listRequirements(session: IrisSession, appId: String) async throws -> [ComplianceRequirement] { let team = try await teamId(for: session) - let (requirementsData, _) = try await api.complianceGet( + let (data, _) = try await api.complianceGet( path: "accounts/\(team)/requirements", queryItems: [URLQueryItem(name: "entity_id", value: appId)], cookies: session.cookies ) - let (formsData, _) = try await api.complianceGet( - path: "accounts/\(team)/entities/\(appId)/forms", queryItems: [], cookies: session.cookies - ) - let requirements = try JSONDecoder().decode(ComplianceRequirementsResponse.self, from: requirementsData).data - let forms = try JSONDecoder().decode(ComplianceFormsResponse.self, from: formsData).data - return Self.rows(requirements: requirements, forms: forms, appId: appId) + return try JSONDecoder().decode(ComplianceRequirementsResponse.self, from: data).data.map { requirement in + ComplianceRequirement( + id: requirement.id, + appId: appId, + kind: ComplianceKind(formName: requirement.formName), + regions: requirement.countries ?? [], + isRequired: requirement.isRequired ?? false, + status: ComplianceStatus(wireValue: requirement.status), + updatedAt: requirement.lastUpdatedDate, + requiredActions: (requirement.requiredActions ?? []).map(ComplianceRequiredAction.init(wireValue:)), + declarationId: requirement.formId + ) + } } /// Saves `answer` the way the App Compliance page does: post the draft to Apple's form, @@ -58,10 +67,10 @@ public struct IrisSDKComplianceRepository: IrisComplianceRepository { let body = try Self.encoder.encode(ComplianceSaveRequest( accountId: team, entityId: requirement.appId, requirementId: requirement.id, - formId: requirement.declaration?.id, fields: fields + formId: requirement.declarationId, fields: fields )) do { - if let formId = requirement.declaration?.id { + if let formId = requirement.declarationId { _ = try await api.compliancePut(path: "\(entity)/forms/\(formId)", body: body, cookies: session.cookies) } else { _ = try await api.compliancePost(path: "\(entity)/forms", body: body, cookies: session.cookies) @@ -114,41 +123,6 @@ public struct IrisSDKComplianceRepository: IrisComplianceRepository { return encoder }() - /// Every requirement is a row, answered or not, with the form whose `requirementId` is - /// its id (law 7). A form no requirement lists is still a row, but one that can't be - /// declared: there is no requirement to save it against (law 4). - static func rows(requirements: [ComplianceRequirementResource], forms: [ComplianceFormResource], appId: String) -> [ComplianceRequirement] { - let formsByRequirement = Dictionary(forms.map { ($0.requirementId, $0) }, uniquingKeysWith: { first, _ in first }) - let listed = requirements.map { requirement in - ComplianceRequirement( - id: requirement.id, - appId: appId, - kind: ComplianceKind(formName: requirement.formName), - regions: requirement.countries ?? [], - isRequired: requirement.isRequired ?? false, - status: ComplianceStatus(wireValue: requirement.status), - updatedAt: requirement.lastUpdatedDate, - requiredActions: (requirement.requiredActions ?? []).map(ComplianceRequiredAction.init(wireValue:)), - declaration: formsByRequirement[requirement.id].map { ComplianceDeclaration(id: $0.id, answer: $0.answer) } - ) - } - let listedIds = Set(requirements.map(\.id)) - let orphans = forms.filter { !listedIds.contains($0.requirementId) }.map { form in - ComplianceRequirement( - id: form.requirementId, - appId: appId, - kind: .unrecognized(formName: form.formName), - regions: [], - isRequired: false, - status: form.status.map(ComplianceStatus.init(wireValue:)) ?? .unrecognized(wireValue: ""), - updatedAt: nil, - requiredActions: [], - declaration: ComplianceDeclaration(id: form.id, answer: form.answer) - ) - } - return listed + orphans - } - private func teamId(for session: IrisSession) async throws -> String { guard let team = try await accounts.fetchSession(cookies: session.cookies).teamId, !team.isEmpty else { throw ComplianceError.teamUnknown diff --git a/Tests/ASCCommandTests/Commands/Iris/Compliance/IrisAppComplianceTests.swift b/Tests/ASCCommandTests/Commands/Iris/Compliance/IrisAppComplianceTests.swift index 43c341c5..b6a17c26 100644 --- a/Tests/ASCCommandTests/Commands/Iris/Compliance/IrisAppComplianceTests.swift +++ b/Tests/ASCCommandTests/Commands/Iris/Compliance/IrisAppComplianceTests.swift @@ -14,17 +14,17 @@ struct IrisAppComplianceTests { private let missing = ComplianceRequirement( id: "req-1", appId: "1234567890", kind: .securityAssessment, regions: ["CHN"], isRequired: true, - status: .missingInfo, updatedAt: nil, requiredActions: [], declaration: nil + status: .missingInfo, updatedAt: nil, requiredActions: [], declarationId: nil ) private let pending = ComplianceRequirement( id: "req-2", appId: "1234567890", kind: .aiGeneratedContent, regions: ["CHN"], isRequired: true, status: .pendingVerification, updatedAt: "2026-11-17T00:00:00.000Z", requiredActions: [.appBinarySubmission], - declaration: ComplianceDeclaration(id: "form-2", answer: .yes) + declarationId: "form-2" ) private var declaredNo: ComplianceRequirement { ComplianceRequirement(id: "req-1", appId: "1234567890", kind: .securityAssessment, regions: ["CHN"], isRequired: true, status: .active, updatedAt: "2026-11-19T00:00:00.000Z", requiredActions: [], - declaration: ComplianceDeclaration(id: "form-1", answer: .no)) + declarationId: "form-1") } private func repo() -> MockIrisComplianceRepository { @@ -65,10 +65,7 @@ struct IrisAppComplianceTests { "listRequirements" : "asc iris app-compliance list --app-id 1234567890" }, "appId" : "1234567890", - "declaration" : { - "answer" : "YES", - "id" : "form-2" - }, + "declarationId" : "form-2", "id" : "req-2", "isRequired" : true, "kind" : "AI_GENERATED_CONTENT", @@ -95,7 +92,7 @@ struct IrisAppComplianceTests { let json = try #require(try JSONSerialization.jsonObject(with: Data(output.utf8)) as? [String: Any]) let row = try #require((json["data"] as? [[String: Any]])?.first) #expect(row["status"] as? String == "ACTIVE") - #expect((row["declaration"] as? [String: Any])?["answer"] as? String == "NO") + #expect(row["declarationId"] as? String == "form-1") } @Test func `should refuse to declare while Apple is verifying the answer`() async throws { @@ -155,7 +152,7 @@ struct IrisAppComplianceTests { @Test func `should declare an AIGC Yes from its filing and third-party agreement`() async throws { let aigc = ComplianceRequirement(id: "req-3", appId: "1234567890", kind: .aiGeneratedContent, regions: ["CHN"], isRequired: true, - status: .missingInfo, updatedAt: nil, requiredActions: [], declaration: nil) + status: .missingInfo, updatedAt: nil, requiredActions: [], declarationId: nil) let yes = ComplianceAnswer.offered(.aiGeneratedContent( filing: .largeLanguageModel(name: "Example Model", filingNumber: "Example-0000"), thirdParty: .used(authorization: ComplianceFile(name: "agreement.pdf", data: Data("A".utf8))) diff --git a/Tests/ASCCommandTests/Commands/Web/Controllers/IrisAppComplianceRoutesTests.swift b/Tests/ASCCommandTests/Commands/Web/Controllers/IrisAppComplianceRoutesTests.swift index 380651e1..38f3761c 100644 --- a/Tests/ASCCommandTests/Commands/Web/Controllers/IrisAppComplianceRoutesTests.swift +++ b/Tests/ASCCommandTests/Commands/Web/Controllers/IrisAppComplianceRoutesTests.swift @@ -12,12 +12,12 @@ import Testing struct IrisAppComplianceRoutesTests { private let missing = ComplianceRequirement( id: "req-1", appId: "1234567890", kind: .securityAssessment, regions: ["CHN"], isRequired: true, - status: .missingInfo, updatedAt: nil, requiredActions: [], declaration: nil + status: .missingInfo, updatedAt: nil, requiredActions: [], declarationId: nil ) private let declaredNo = ComplianceRequirement( id: "req-1", appId: "1234567890", kind: .securityAssessment, regions: ["CHN"], isRequired: true, status: .active, updatedAt: "2026-11-19T00:00:00.000Z", requiredActions: [], - declaration: ComplianceDeclaration(id: "form-1", answer: .no) + declarationId: "form-1" ) private func call(_ method: HTTPRequest.Method, _ uri: String, body: String? = nil) async throws -> (HTTPResponse.Status, String) { diff --git a/Tests/ASCKitTests/Iris/Compliance/ComplianceAnswerTests.swift b/Tests/ASCKitTests/Iris/Compliance/ComplianceAnswerTests.swift index 74a61647..b9408260 100644 --- a/Tests/ASCKitTests/Iris/Compliance/ComplianceAnswerTests.swift +++ b/Tests/ASCKitTests/Iris/Compliance/ComplianceAnswerTests.swift @@ -80,7 +80,7 @@ struct ComplianceAnswerTests { @Test func `should refuse evidence made for another compliance, sending nothing`() async { let aigc = ComplianceRequirement(id: "req-2", appId: "1234567890", kind: .aiGeneratedContent, regions: ["CHN"], isRequired: true, - status: .missingInfo, updatedAt: nil, requiredActions: [], declaration: nil) + status: .missingInfo, updatedAt: nil, requiredActions: [], declarationId: nil) let repo = MockIrisComplianceRepository() await #expect(throws: ComplianceError.evidenceMismatch(kind: .aiGeneratedContent)) { diff --git a/Tests/ASCKitTests/Iris/Compliance/ComplianceRequirementTests.swift b/Tests/ASCKitTests/Iris/Compliance/ComplianceRequirementTests.swift index adf7ac9a..47c67985 100644 --- a/Tests/ASCKitTests/Iris/Compliance/ComplianceRequirementTests.swift +++ b/Tests/ASCKitTests/Iris/Compliance/ComplianceRequirementTests.swift @@ -10,13 +10,13 @@ struct ComplianceRequirementTests { private func requirement( _ kind: ComplianceKind = .securityAssessment, status: ComplianceStatus, - declaration: ComplianceDeclaration? = nil, + declarationId: String? = nil, requiredActions: [ComplianceRequiredAction] = [] ) -> ComplianceRequirement { ComplianceRequirement( id: "req-1", appId: "1234567890", kind: kind, regions: ["CHN"], isRequired: true, - status: status, updatedAt: declaration == nil ? nil : "2026-11-17T00:00:00.000Z", - requiredActions: requiredActions, declaration: declaration + status: status, updatedAt: declarationId == nil ? nil : "2026-11-17T00:00:00.000Z", + requiredActions: requiredActions, declarationId: declarationId ) } @@ -28,14 +28,12 @@ struct ComplianceRequirementTests { } @Test func `should offer to change an active declaration and to resubmit a failed one`() { - let answered = ComplianceDeclaration(id: "form-1", answer: .no) - #expect(requirement(status: .active, declaration: answered).affordances["declare"] != nil) - #expect(requirement(status: .verificationFailed, declaration: answered).affordances["declare"] != nil) + #expect(requirement(status: .active, declarationId: "form-1").affordances["declare"] != nil) + #expect(requirement(status: .verificationFailed, declarationId: "form-1").affordances["declare"] != nil) } @Test func `should not offer to declare while Apple is verifying the answer`() { - let yes = ComplianceDeclaration(id: "form-1", answer: .yes) - #expect(requirement(status: .pendingVerification, declaration: yes).affordances["declare"] == nil) + #expect(requirement(status: .pendingVerification, declarationId: "form-1").affordances["declare"] == nil) } @Test func `should not offer to declare a kind it doesn't know`() { @@ -57,7 +55,7 @@ struct ComplianceRequirementTests { // MARK: - declare (law 5, refused by the model before anything is sent) @Test func `should send a No to Apple through the repository`() async throws { - let declared = requirement(status: .active, declaration: ComplianceDeclaration(id: "form-1", answer: .no)) + let declared = requirement(status: .active, declarationId: "form-1") let repo = MockIrisComplianceRepository() given(repo).declare(session: .any, requirement: .any, answer: .value(.notOffered)).willReturn(declared) @@ -68,7 +66,7 @@ struct ComplianceRequirementTests { let repo = MockIrisComplianceRepository() await #expect(throws: ComplianceError.notDeclarable(kind: .securityAssessment, status: .pendingVerification)) { - try await requirement(status: .pendingVerification, declaration: ComplianceDeclaration(id: "form-1", answer: .yes)) + try await requirement(status: .pendingVerification, declarationId: "form-1") .declare(.notOffered, session: session, repo: repo) } verify(repo).declare(session: .any, requirement: .any, answer: .any).called(0) @@ -84,12 +82,11 @@ struct ComplianceRequirementTests { // MARK: - what it writes @Test func `should write a requirement the way the App Compliance page reads`() throws { - let row = requirement(status: .pendingVerification, declaration: ComplianceDeclaration(id: "form-1", answer: .yes), - requiredActions: [.appBinarySubmission]) + let row = requirement(status: .pendingVerification, declarationId: "form-1", requiredActions: [.appBinarySubmission]) let encoder = JSONEncoder() encoder.outputFormatting = [.sortedKeys] - #expect(String(decoding: try encoder.encode(row), as: UTF8.self) == #"{"appId":"1234567890","declaration":{"answer":"YES","id":"form-1"},"id":"req-1","isRequired":true,"kind":"SECURITY_ASSESSMENT","name":"Security Assessment","regions":["CHN"],"requiredActions":["APP_BINARY_SUBMISSION"],"status":"PENDING_VERIFICATION","updatedAt":"2026-11-17T00:00:00.000Z"}"#) + #expect(String(decoding: try encoder.encode(row), as: UTF8.self) == #"{"appId":"1234567890","declarationId":"form-1","id":"req-1","isRequired":true,"kind":"SECURITY_ASSESSMENT","name":"Security Assessment","regions":["CHN"],"requiredActions":["APP_BINARY_SUBMISSION"],"status":"PENDING_VERIFICATION","updatedAt":"2026-11-17T00:00:00.000Z"}"#) } @Test func `should leave out the declaration and date of a requirement nobody has answered`() throws { diff --git a/Tests/ASCKitTests/Iris/Compliance/Internal/IrisSDKComplianceDeclareYesTests.swift b/Tests/ASCKitTests/Iris/Compliance/Internal/IrisSDKComplianceDeclareYesTests.swift index bb4b2622..ad381555 100644 --- a/Tests/ASCKitTests/Iris/Compliance/Internal/IrisSDKComplianceDeclareYesTests.swift +++ b/Tests/ASCKitTests/Iris/Compliance/Internal/IrisSDKComplianceDeclareYesTests.swift @@ -74,13 +74,13 @@ struct IrisSDKComplianceDeclareYesTests { .willProduce { _, body, _ in self.ok(form(CapturedForms.draft(of: body))) } given(api).compliancePost(path: .value("\(entity)/forms"), body: .any, cookies: .any) .willReturn(ok(#"{ "data": { "id": "form-9", "requirementId": "\#(requirementId)", "formName": "X", "fields": [], "status": "COLLECTED_VERIFY_PENDING" } }"#)) - given(api).complianceGet(path: .any, queryItems: .any, cookies: .any).willReturn(ok(#"{ "data": [] }"#)) + given(api).complianceGet(path: .any, queryItems: .any, cookies: .any).willReturn(ok("{}")) return api } private func requirement(_ id: String, _ kind: ComplianceKind) -> ComplianceRequirement { ComplianceRequirement(id: id, appId: "1234567890", kind: kind, regions: ["CHN"], isRequired: true, - status: .missingInfo, updatedAt: nil, requiredActions: [], declaration: nil) + status: .missingInfo, updatedAt: nil, requiredActions: [], declarationId: nil) } private func savedBody(_ api: MockIrisAPI, requirementId: String, fields: String) { diff --git a/Tests/ASCKitTests/Iris/Compliance/Internal/IrisSDKComplianceRepositoryTests.swift b/Tests/ASCKitTests/Iris/Compliance/Internal/IrisSDKComplianceRepositoryTests.swift index 2be81df3..de25d377 100644 --- a/Tests/ASCKitTests/Iris/Compliance/Internal/IrisSDKComplianceRepositoryTests.swift +++ b/Tests/ASCKitTests/Iris/Compliance/Internal/IrisSDKComplianceRepositoryTests.swift @@ -3,7 +3,8 @@ import Mockable import Testing @testable import ASCKit -/// Fixtures are the captured responses in docs/features/app-compliance/design.md, ids replaced. +/// Fixtures are captured responses (docs/features/app-compliance/design.md, and live on +/// 2026-11-19), ids replaced — never a shape guessed at. @Suite struct IrisSDKComplianceRepositoryTests { private let session = IrisSession(cookies: "myacinfo=a") @@ -19,53 +20,40 @@ struct IrisSDKComplianceRepositoryTests { return accounts } - private func iris(requirements: String, forms: String) -> MockIrisAPI { + /// Apple's App Compliance service, answering only the page's own call: the requirements. + private func iris(requirements: String) -> MockIrisAPI { let api = MockIrisAPI() given(api).complianceGet( path: .value("accounts/team-uuid/requirements"), queryItems: .value([URLQueryItem(name: "entity_id", value: "1234567890")]), cookies: .value("myacinfo=a") ).willReturn(ok(requirements)) - given(api).complianceGet( - path: .value("accounts/team-uuid/entities/1234567890/forms"), queryItems: .value([]), cookies: .value("myacinfo=a") - ).willReturn(ok(forms)) return api } - private let unanswered = #""" - { "data": [ - { "id": "req-1", "formName": "SECURITYASF395E", "entityId": "1234567890", "entityType": "APP", - "status": "PENDING_COLLECT", "isRequired": true, "countries": [ "CHN" ] }, - { "id": "req-2", "formName": "AIGENERATEFD1DE", "entityId": "1234567890", "entityType": "APP", - "status": "PENDING_COLLECT", "isRequired": true, "countries": [ "CHN" ] } - ] } - """# - - @Test func `should list every requirement nobody has answered as Missing Info`() async throws { - let repo = IrisSDKComplianceRepository(api: iris(requirements: unanswered, forms: #"{ "data": [] }"#), accounts: signedInTo(team: "team-uuid")) + @Test func `should list every requirement of a new app as Missing Info, as the page does`() async throws { + // Captured live on a new app. + let repo = IrisSDKComplianceRepository(api: iris(requirements: #""" + { "data": [ + { "id": "req-1", "formName": "SECURITYASF395E", "entityId": "1234567890", "status": "PENDING_COLLECT", + "isRequired": true, "entityType": "APP", "countries": [ "CHN" ] }, + { "id": "req-2", "formName": "AIGENERATEFD1DE", "entityId": "1234567890", "status": "PENDING_COLLECT", + "isRequired": true, "entityType": "APP", "countries": [ "CHN" ] } + ] } + """#), accounts: signedInTo(team: "team-uuid")) let rows = try await repo.listRequirements(session: session, appId: "1234567890") #expect(rows == [ ComplianceRequirement(id: "req-1", appId: "1234567890", kind: .securityAssessment, regions: ["CHN"], isRequired: true, - status: .missingInfo, updatedAt: nil, requiredActions: [], declaration: nil), + status: .missingInfo, updatedAt: nil, requiredActions: [], declarationId: nil), ComplianceRequirement(id: "req-2", appId: "1234567890", kind: .aiGeneratedContent, regions: ["CHN"], isRequired: true, - status: .missingInfo, updatedAt: nil, requiredActions: [], declaration: nil), + status: .missingInfo, updatedAt: nil, requiredActions: [], declarationId: nil), ]) } - @Test func `should list a new app's requirements when Apple has no declarations for it`() async throws { - // Seen live on a new app: the declarations call answers `{}`, with no `data`. - let repo = IrisSDKComplianceRepository(api: iris(requirements: unanswered, forms: "{}"), accounts: signedInTo(team: "team-uuid")) - - let rows = try await repo.listRequirements(session: session, appId: "1234567890") - - #expect(rows.map(\.status) == [.missingInfo, .missingInfo]) - #expect(rows.map(\.declaration) == [nil, nil]) - } - - @Test func `should attach each declaration to the requirement it answers`() async throws { - let requirements = #""" + @Test func `should carry the declaration each answered requirement names, with its date and what Apple still needs`() async throws { + let repo = IrisSDKComplianceRepository(api: iris(requirements: #""" { "data": [ { "id": "req-1", "formName": "SECURITYASF395E", "entityId": "1234567890", "entityType": "APP", "status": "COLLECTED_VERIFY_PENDING", "isRequired": true, "countries": [ "CHN" ], "formId": "form-1", @@ -75,41 +63,25 @@ struct IrisSDKComplianceRepositoryTests { "status": "COLLECTED_VERIFY_NOT_NECESSARY", "isRequired": true, "countries": [ "CHN" ], "formId": "form-2", "dateSigned": "2026-01-03T00:00:00.000Z", "lastUpdatedDate": "2026-01-03T00:00:00.000Z" } ] } - """# - let forms = #""" - { "data": [ - { "id": "form-2", "requirementId": "req-2", "formName": "AIGENERATEFD1DE", - "fields": [ { "id": "aigc-offers", "sValue": "NO", "verificationStatus": "FIELD_VERIFY_NOT_NECESSARY" } ], - "status": "COLLECTED_VERIFY_NOT_NECESSARY", "createdAt": "1790000000000", "updatedAt": "1790000000000" }, - { "id": "form-1", "requirementId": "req-1", "formName": "SECURITYASF395E", - "fields": [ - { "id": "field-1", "sValue": "YES", "verificationStatus": "FIELD_VERIFY_NOT_NECESSARY" }, - { "id": "field-2", "verificationStatus": "FIELD_VERIFY_PENDING", - "fileContent": { "fileId": "file-1", "fileName": "proof.png", "fileType": "image/png", "fileSizeBytes": "34188" } } - ], - "status": "COLLECTED_VERIFY_PENDING", "createdAt": "1790000000000", "updatedAt": "1790000000000" } - ] } - """# - let repo = IrisSDKComplianceRepository(api: iris(requirements: requirements, forms: forms), accounts: signedInTo(team: "team-uuid")) + """#), accounts: signedInTo(team: "team-uuid")) let rows = try await repo.listRequirements(session: session, appId: "1234567890") #expect(rows == [ ComplianceRequirement(id: "req-1", appId: "1234567890", kind: .securityAssessment, regions: ["CHN"], isRequired: true, status: .pendingVerification, updatedAt: "2026-01-02T00:00:00.000Z", - requiredActions: [.appBinarySubmission], declaration: ComplianceDeclaration(id: "form-1", answer: .yes)), + requiredActions: [.appBinarySubmission], declarationId: "form-1"), ComplianceRequirement(id: "req-2", appId: "1234567890", kind: .aiGeneratedContent, regions: ["CHN"], isRequired: true, status: .active, updatedAt: "2026-01-03T00:00:00.000Z", - requiredActions: [], declaration: ComplianceDeclaration(id: "form-2", answer: .no)), + requiredActions: [], declarationId: "form-2"), ]) } @Test func `should keep a compliance and a status it doesn't know`() async throws { - let requirements = #""" + let repo = IrisSDKComplianceRepository(api: iris(requirements: #""" { "data": [ { "id": "req-9", "formName": "MEDICALDEV0001", "entityId": "1234567890", "entityType": "APP", "status": "COLLECTED_VERIFY_REJECTED", "isRequired": false, "countries": [ "CHN", "HKG" ] } ] } - """# - let repo = IrisSDKComplianceRepository(api: iris(requirements: requirements, forms: #"{ "data": [] }"#), accounts: signedInTo(team: "team-uuid")) + """#), accounts: signedInTo(team: "team-uuid")) let rows = try await repo.listRequirements(session: session, appId: "1234567890") @@ -117,25 +89,15 @@ struct IrisSDKComplianceRepositoryTests { ComplianceRequirement(id: "req-9", appId: "1234567890", kind: .unrecognized(formName: "MEDICALDEV0001"), regions: ["CHN", "HKG"], isRequired: false, status: .unrecognized(wireValue: "COLLECTED_VERIFY_REJECTED"), - updatedAt: nil, requiredActions: [], declaration: nil), + updatedAt: nil, requiredActions: [], declarationId: nil), ]) } - @Test func `should keep a declaration no requirement lists, as a row it won't declare`() async throws { - let forms = #""" - { "data": [ { "id": "form-7", "requirementId": "req-7", "formName": "SECURITYASF395E", - "fields": [ { "id": "field-1", "sValue": "NO" } ], "status": "COLLECTED_VERIFY_NOT_NECESSARY" } ] } - """# - let repo = IrisSDKComplianceRepository(api: iris(requirements: #"{ "data": [] }"#, forms: forms), accounts: signedInTo(team: "team-uuid")) + @Test func `should read a list Apple leaves out as empty, as the service does with every empty value`() async throws { + // The service omits what is empty: a new app's declarations came back `{}` (live). + let repo = IrisSDKComplianceRepository(api: iris(requirements: "{}"), accounts: signedInTo(team: "team-uuid")) - let rows = try await repo.listRequirements(session: session, appId: "1234567890") - - #expect(rows == [ - ComplianceRequirement(id: "req-7", appId: "1234567890", kind: .unrecognized(formName: "SECURITYASF395E"), - regions: [], isRequired: false, status: .active, updatedAt: nil, requiredActions: [], - declaration: ComplianceDeclaration(id: "form-7", answer: .no)), - ]) - #expect(rows[0].isDeclarable == false) + #expect(try await repo.listRequirements(session: session, appId: "1234567890") == []) } @Test func `should refuse to list when the session names no team`() async { @@ -202,20 +164,18 @@ struct IrisSDKComplianceDeclareTests { } given(api).complianceGet(path: .value("accounts/team-uuid/requirements"), queryItems: .any, cookies: .any) .willReturn(reply(200, savedRow(status: "COLLECTED_VERIFY_NOT_NECESSARY", formId: formId))) - given(api).complianceGet(path: .value(forms), queryItems: .any, cookies: .any) - .willReturn(reply(200, "{ \"data\": [ \(saved.dropFirst(10).dropLast(2)) ] }")) return api } - private func requirement(declaration: ComplianceDeclaration? = nil, status: ComplianceStatus = .missingInfo) -> ComplianceRequirement { + private func requirement(declarationId: String? = nil, status: ComplianceStatus = .missingInfo) -> ComplianceRequirement { ComplianceRequirement(id: "req-1", appId: "1234567890", kind: .securityAssessment, regions: ["CHN"], isRequired: true, - status: status, updatedAt: nil, requiredActions: [], declaration: declaration) + status: status, updatedAt: nil, requiredActions: [], declarationId: declarationId) } private let answeredNo = ComplianceRequirement( id: "req-1", appId: "1234567890", kind: .securityAssessment, regions: ["CHN"], isRequired: true, status: .active, updatedAt: "2026-11-19T00:00:00.000Z", requiredActions: [], - declaration: ComplianceDeclaration(id: "form-1", answer: .no) + declarationId: "form-1" ) @Test func `should answer No for the first time and show the requirement active`() async throws { @@ -254,7 +214,7 @@ struct IrisSDKComplianceDeclareTests { let api = apple() let row = try await IrisSDKComplianceRepository(api: api, accounts: accounts()) - .declare(session: session, requirement: requirement(declaration: ComplianceDeclaration(id: "form-1", answer: .no), status: .active), + .declare(session: session, requirement: requirement(declarationId: "form-1", status: .active), answer: .notOffered) #expect(row == answeredNo) diff --git a/docs/features/app-compliance/design.md b/docs/features/app-compliance/design.md index 2913975d..a5ce2e89 100644 --- a/docs/features/app-compliance/design.md +++ b/docs/features/app-compliance/design.md @@ -130,6 +130,8 @@ GET https://appstoreconnect.apple.com/ppm/compliancerequirements/v1/accounts/{ac ``` - **Only answered requirements come back.** A declaration joins its requirement on `requirementId` = requirement `id`. +- **With none, it answers `{}`** (captured live on two new apps), not `{"data": []}`: the service leaves out what is empty, here and in every other response (no `formId`, dates or `requiredActions` until they apply). +- **The page doesn't call it to draw the table** (captured in the browser): only when a row's Add Info / Edit / View dialog opens. - Timestamps are epoch milliseconds, encoded as strings. - The second captured declaration was `AIGENERATEFD1DE`, with the same shape. The spelling is the same in both calls. @@ -440,13 +442,14 @@ ComplianceRequirement one row on the App Compliance page (aggre ├─ isRequired : Bool ├─ updatedAt : Date? `lastUpdatedDate`; nil = never answered, shown "-" ├─ requiredActions : [RequiredAction] e.g. .appBinarySubmission; unknown values kept raw - ├─ declaration : ComplianceDeclaration? nil ⇒ never answered - │ ├─ id : String Apple's form id (`formId` on the requirement); what an update targets (assumed, Open question 2) - │ └─ answer : ComplianceAnswer .notOffered | .offered(Evidence) — EVIDENCE ONLY ON YES + ├─ declarationId : String? the requirement's `formId`: the declaration a change updates; nil ⇒ never answered └─ status : ComplianceStatus mapped from the requirement's `status` + +ComplianceAnswer what `declare` sends (not part of the row) + └─ .notOffered | .offered(Evidence) EVIDENCE ONLY ON YES ``` -The adapter makes the two reads and joins them: every requirement is a row, and its declaration is the form whose `id` is the requirement's `formId` (equivalently, whose `requirementId` is the requirement's `id`). A form with no matching requirement is kept as its own row with `.unrecognized` kind (law 4), never dropped. A list that doesn't need the answer itself can skip the declarations call. +**The row is what the page draws, from the page's own call.** The requirements response alone carries everything the table shows (name, regions, last updated, status) and the `formId` a change needs, so `list` makes that one call, as the page does. The declarations themselves (the stored answer, its files) aren't read for the list: the page doesn't show them in the table either, and reading them doubled the requests and was the call that answered `{}`. They belong to a future `get` of one requirement, which is what the page's dialog does. There is no `AppCompliance` wrapper type. It would just be the plural of `ComplianceRequirement`, with no rule of its own yet. It earns a type if Open question 6 ("may this app ship in region X?") gets answered, because that rule belongs to the collection. @@ -508,7 +511,7 @@ The iris repositories reach Apple through the `@Mockable IrisAPI` role, played b | 5 | You're offered `declare` only for a recognized kind that isn't awaiting verification: Missing Info (a first answer), Active (a change) and Verification Failed (a resubmission, assumed) | `ComplianceRequirement.structuredAffordances` | | 5a | `declare` saves only if the requirement's metadata says its fields are `editable`; otherwise it refuses without writing. Apple's own answer decides, so a wrong guess about a status never writes to a read-only declaration | adapter (`declare` reads metadata first) | | 6 | The account in the URL is the team's `publicProviderId`, never the numeric `providerID` | adapter (account resolution) | -| 7 | Every requirement is a row whether or not it was answered; a declaration attaches to the requirement whose `id` is its `requirementId` | adapter (the join) | +| 7 | Every requirement is a row whether or not it was answered, and names the declaration that answers it (`formId`) | adapter (the requirements mapper) | | 8 | A declaration names each field by the id the requirement's metadata gives, read for the chosen answers before every save; an id is never hard-coded or guessed. The adapter finds which constraint is which by the field key in its `label` loc key (`algorithmname2`), and walks the tree one pick at a time | adapter (`declare` reads metadata first) | | 9 | A file is offered for a `FILE` field only if its extension is in that field's `allowedFileTypes` | `ComplianceAnswer` evidence types, from the metadata | | 10 | A save sends only the fields the metadata asks for under the chosen answers; a field from an abandoned branch (a file chosen before switching to No) is dropped | adapter (`declare` builds the body from the metadata) | @@ -517,7 +520,7 @@ The iris repositories reach Apple through the `@Mockable IrisAPI` role, played b 0. ~~**Capture**~~ Done. Every call the page makes is captured; nothing blocks slices 1–6. Also the AIGC Yes metadata, `metadata` for an answered requirement, and the Verification Failed status. The reads, and their responses after a Yes, are captured. 1. **Public face** (`Sources/ASCKit/Iris/Compliance/`): `ComplianceKind`, `ComplianceStatus`, `ComplianceAnswer` (No only), `ComplianceRequirement` + affordances, `@Mockable IrisComplianceRepository` (CRUD over requirements and declarations, so it keeps the `Repository` name; `requirement.declare(…)` is the workflow, on the model). *Pinned: laws 1, 3 (No), 4, 5.* -2. **Read** (`Sources/ASCKit/Iris/Compliance/Internal/`, through `IrisAPI`): the ppm base on `IrisRequest`; account resolution; `listRequirements(session:appId:)` reading both captured fixtures (placeholder IDs) and joining them, tested on `MockIrisAPI`. *Pinned: laws 2, 6, 7; epoch-ms dates; `entity_id` query; unknown `formName` survives; an orphan declaration survives.* +2. **Read** (`Sources/ASCKit/Iris/Compliance/Internal/`, through `IrisAPI`): the ppm base on `IrisRequest`; account resolution; `listRequirements(session:appId:)` from the page's one call (captured fixtures, placeholder IDs), tested on `MockIrisAPI`. *Pinned: laws 2, 6, 7; `entity_id` query; unknown `formName` and status survive; a missing list reads as empty.* 3. **`asc iris app-compliance list` + REST** `GET /api/v1/iris/apps/:appId/compliance-requirements`. *Pinned: full JSON snapshot; `_links.declare` only on eligible rows.* 4. **`declare --answer no` + REST** (reads the requirement's metadata for the question's id, then saves; *pinned: law 8*) `POST /api/v1/iris/apps/:appId/compliance-requirements/:requirementId/declare` (the app is in the path because a requirement id alone names no row). A first answer is a `POST …/forms`; a change to an Active one is a `PUT …/forms/{formId}` (the requirement's `formId`). A pending one is never offered `declare`. 5. **Yes with evidence**: per-kind evidence types and file flags; files read from disk and sent base64 in `fileContent.fileData`. *Pinned: laws 9, 10.* The body is captured (AIGC Yes with a file). @@ -526,12 +529,12 @@ The iris repositories reach Apple through the `@Mockable IrisAPI` role, played b ## 6a · What the build settled -- **The declaration the list reads holds only the answer.** `ComplianceDeclaration` is `{ id, answer: YES | NO }`; a Yes's evidence stays with Apple, since naming its stored fields would need the metadata for every row. The evidence types (`ComplianceEvidence`) are what a Yes *sends*. +- **`list` makes only the page's own call** (requirements) and the row carries `declarationId` from `formId`. An earlier build also read the declarations and joined them (with orphan declarations as rows); it was dropped once the browser showed the page doesn't, and a new app's `{}` broke it. The evidence types (`ComplianceEvidence`) are only what a Yes *sends*. - **The account is asked of olympus on every call**, not read from a saved `teamId`, so a browser-cookie or `ASC_IRIS_COOKIES` session works the same as `asc iris auth login`. No `publicProviderId` → `ComplianceError.teamUnknown`. - **Law 1's owner is `ComplianceStatus(wireValue:)`**: Apple already sends `PENDING_COLLECT` for an unanswered requirement. - **The answer a form holds is its first field**, the Yes/No it opens with; only a Yes opens more fields. - **`declare` is one loop for every answer**: post the draft to `…/metadata`, fill each field Apple newly asks for (by the key in its label), repeat until Apple asks for nothing new, then save exactly those fields. Any field Apple won't take a change to stops it (law 5a). A No ends after its first pick. -- **An app with no declarations gets `{}` from the declarations call**, not `{"data": []}` (seen live on a new app); it reads as no declarations. +- **The service leaves out what is empty** (`{}` for no declarations, seen live on two new apps), so every response reads a missing list as empty. **Fixtures are captures**, never a shape guessed at: the guessed `{"data": []}` is how the `{}` slipped past the tests. - **Verified live** (2026-11-19, on a test app): list on a new app (both Missing Info), a first No on each form (`POST`, → Active), a change to an Active one (`PUT`, same declaration id, new LAST UPDATED), and the refusal on a Pending Verification row before anything is sent. A Yes was not sent live: it would put placeholder evidence in front of Apple. - **REST statuses**: 404 no such requirement on the app; 409 not declarable now, read-only, or a form asc doesn't understand; 422 evidence missing, mismatched or of a type the field refuses; 403 the role can't edit; 401 no team. From 1f16ea4626b65c9c516ca6331b56d1ee6147b535 Mon Sep 17 00:00:00 2001 From: slamhan Date: Thu, 19 Nov 2026 22:12:05 +0800 Subject: [PATCH 11/12] docs(app-compliance): record the live Yes tests A Security Assessment Yes with two files and all four AIGC Yes combinations (LLM / Algorithm x third-party Yes / No) were saved on test apps and each stored exactly its branch's fields; third-party No, the one uncaptured branch, asks for nothing more. Co-Authored-By: Claude Opus 5.5 --- docs/features/app-compliance/design.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/features/app-compliance/design.md b/docs/features/app-compliance/design.md index a5ce2e89..c47290ca 100644 --- a/docs/features/app-compliance/design.md +++ b/docs/features/app-compliance/design.md @@ -535,7 +535,9 @@ The iris repositories reach Apple through the `@Mockable IrisAPI` role, played b - **The answer a form holds is its first field**, the Yes/No it opens with; only a Yes opens more fields. - **`declare` is one loop for every answer**: post the draft to `…/metadata`, fill each field Apple newly asks for (by the key in its label), repeat until Apple asks for nothing new, then save exactly those fields. Any field Apple won't take a change to stops it (law 5a). A No ends after its first pick. - **The service leaves out what is empty** (`{}` for no declarations, seen live on two new apps), so every response reads a missing list as empty. **Fixtures are captures**, never a shape guessed at: the guessed `{"data": []}` is how the `{}` slipped past the tests. -- **Verified live** (2026-11-19, on a test app): list on a new app (both Missing Info), a first No on each form (`POST`, → Active), a change to an Active one (`PUT`, same declaration id, new LAST UPDATED), and the refusal on a Pending Verification row before anything is sent. A Yes was not sent live: it would put placeholder evidence in front of Apple. +- **Verified live** (2026-11-19, on test apps that won't be submitted, with files and filing values marked as tests): list on new apps (both Missing Info, as the page shows); a first No on each form (`POST`, → Active); a change to an Active one (`PUT`, same declaration id, new LAST UPDATED); a Security Assessment Yes with two PDFs (stored as files, sizes byte-exact, → Pending Verification with `APP_BINARY_SUBMISSION`); all four AIGC Yes combinations, LLM / Algorithm × third-party Yes / No, each storing only its branch's fields (one as a `PUT` changing an Active No to Yes); and the refusals that write nothing: a Pending Verification row, a Yes missing its report, a `.txt` file against Apple's own `allowedFileTypes`. +- **Third-party No asks for nothing more** (verified live; it was the one branch not captured). +- **Field ids were the same on four apps** (e.g. the AIGC question, the filing type), confirming they belong to the compliance; asc still reads them from Apple's form every time (law 8). - **REST statuses**: 404 no such requirement on the app; 409 not declarable now, read-only, or a form asc doesn't understand; 422 evidence missing, mismatched or of a type the field refuses; 403 the role can't edit; 401 no team. ## 7 · Open questions From bd600f82ea5198d6455bebd88925e8ac8664841b Mon Sep 17 00:00:00 2001 From: slamhan Date: Thu, 19 Nov 2026 22:17:59 +0800 Subject: [PATCH 12/12] docs(skill): nested REST routes and captured fixtures; app-compliance list scope implement-feature: a child addressed under its parent by both ids registers with nestedResourceParam; fixtures are captured responses, including the empty case (the guessed {"data": []} that hid a live {}). App Compliance README: the list shows what the page's table shows, not the stored answer. Co-Authored-By: Claude Opus 5.5 --- .claude/skills/implement-feature/SKILL.md | 4 ++++ docs/features/app-compliance/README.md | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/.claude/skills/implement-feature/SKILL.md b/.claude/skills/implement-feature/SKILL.md index c62313e4..647f4cfb 100644 --- a/.claude/skills/implement-feature/SKILL.md +++ b/.claude/skills/implement-feature/SKILL.md @@ -88,6 +88,8 @@ extension MyModel: AffordanceProviding { Every `registerRoute(...)` call must be reachable from `RESTPathResolver.ensureInitialized()`. Add `_ = _yourRoutes` there. Forgetting this means `_links` silently resolves to `[:]` because the route table is empty when the protocol's `apiLinks` derivation runs in tests / fresh process state. +A child that is addressed under its parent by **both** ids (an App Compliance requirement id is the same on every app, so its row is `/iris/apps/:appId/compliance-requirements/:requirementId`) registers with `registerRoute(command:parentParam:parentSegment:segment:nestedResourceParam:)`. + ### 3. Every domain model must ```swift @@ -174,6 +176,8 @@ public func getAvailability(iapId: String) async throws -> ASCKit.InAppPurchaseA } ``` +**Fixtures are captured responses, never shapes guessed at** — including the empty case. Private services (iris, `ppm`) leave out empty values: an App Compliance app with no declarations answered `{}`, not `{"data": []}`, and a guessed `{"data": []}` fixture let that past every test. Record the captured shape in the feature's design doc and copy fixtures from there. + **Test these with `StubAPIClient.willReturn(_:)` once per response type.** The stub keys responses by `String(describing: T.self)`, so each `willReturn` for a different response type queues up the next call's return value. Adding a regression test that returns 175 entries proves pagination works. --- diff --git a/docs/features/app-compliance/README.md b/docs/features/app-compliance/README.md index 7f8d1225..1691c499 100644 --- a/docs/features/app-compliance/README.md +++ b/docs/features/app-compliance/README.md @@ -30,7 +30,7 @@ Each requirement is a row, answered or not, with the page's STATUS: | `ACTIVE` | Answered, nothing pending: the app may stay on sale in the region | offered: a change | | `VERIFICATION_FAILED` | Apple rejected the evidence | offered: a resubmission | -A compliance or status asc doesn't know yet is still listed, as Apple names it, and is never offered `declare`. A row also says which next commands apply (`affordances`, or `_links` over REST). +A compliance or status asc doesn't know yet is still listed, as Apple names it, and is never offered `declare`. A row also says which next commands apply (`affordances`, or `_links` over REST). Like the page's table, the list shows each row's status and `declarationId`, not the stored answer or its files. ### Answer No