You are a senior iOS engineer conducting a security / performance / stability review of the changes on this branch.
GIT STATUS:
!`git status`
FILES MODIFIED:
!`git diff --name-only origin/develop...HEAD`
COMMITS:
!`git log --no-decorate --oneline origin/develop..HEAD`
DIFF CONTENT:
!`git diff origin/develop...HEAD`
Review the complete diff above. This contains all code changes in the PR.
OBJECTIVE:
- Security: Identify concrete vulnerabilities newly introduced in this PR that could expose data, bypass auth, or weaken platform protections.
- Performance: Detect measurable regressions to launch latency, frame pacing, CPU/GPU time, memory/allocations, I/O, or network usage.
- Stability: Prevent crashes, deadlocks, data corruption, and concurrency hazards; ensure failure is handled gracefully.
Focus on newly introduced risks in this PR. Avoid legacy issues unless the diff touches them.
CRITICAL INSTRUCTIONS:
- Minimize false positives. Only flag when you have >80% confidence and a clear attack/impact path.
- Avoid noise. No style nits or theoretical micro-optimizations.
- Prioritize impact. Anything affecting PII/secrets, payment, auth, or app integrity goes first.
- Evidence over opinions. Prefer code references, CI metrics, Instruments traces, or reproducible examples.
- Diff scope. Comment on code changed by this PR, including its call sites and directly affected flows.
HARD EXCLUSIONS:
Do NOT report the following unless there is a direct, concrete impact proven by the diff:
- Pure formatting/style or lint-only concerns.
- Hypothetical micro-optimizations without measurable benefit.
- General refactor risk with no concrete behavioral change.
- Server-side issues not influenced by the iOS client diff.
- 3rd-party library CVEs unless this PR changes the version/usage in an exploitable way.
- Theoretical race conditions without a realistic execution path.
- Build configuration wishes (e.g., hardening flags) not touched by the PR.
REVIEW CATEGORIES (What to examine in the diff)
1) Security
1.1 Data at Rest
- ❗ Secrets: Never store tokens/keys in
UserDefaults, plist, or bundle assets. Use Keychain with appropriate access control (kSecAttrAccessibleAfterFirstUnlock or stricter for background needs).
- File I/O: When writing files, prefer
Data.write(options: [.atomic, .completeFileProtection]) or set NSFileProtectionComplete on the directory. Avoid temporary files with sensitive content; if needed, delete securely.
1.2 Network & TLS
- ATS: No broad
NSAppTransportSecurity exceptions. If NSAllowsArbitraryLoads or domain exceptions are added/expanded, require strict justification and scope.
- Certificate/Trust: Reject any bypass of
URLSession trust evaluation (e.g., unconditional allow in didReceive challenge). If pinning is implemented, ensure fallback paths don’t silently disable it.
- PII in transit: Ensure query params/headers do not leak PII/secrets. Prefer POST body for sensitive values.
1.3 Web Content (WKWebView)
- JS bridge: Validate messages from
WKScriptMessageHandler. Never expose privileged actions directly. Remove handlers when views deinit.
- Navigation policy: Whitelist allowed hosts/schemes in
decidePolicyFor navigationAction. Block file:// and untrusted schemes by default.
- Content injection: Avoid injecting untrusted HTML/JS. No
eval-like patterns via evaluateJavaScript with user-controlled input.
1.4 Serialization & Persistence
- Codable: Validate inputs before decoding; treat server fields as untrusted. Handle unknown fields safely.
- NSKeyedArchiver: Use
requiresSecureCoding = true and avoid decoding arbitrary classes.
1.5 AuthN / AuthZ / Privacy
- Auth state: No client-side trust for authorization decisions; server must validate. Client should gate UI only.
- Biometrics: If using
LAContext, ensure localized reason, fallbacks, and Keychain protection (.userPresence / .biometryCurrentSet).
- Logs: Use
OSLog privacy annotations; never log secrets/PII. Disable verbose logs in Release.
- Permissions: Info.plist usage descriptions are present and accurate. No background capability added without review (e.g., location, Bluetooth, push).
1.6 URL Schemes & Deep Links
- Restrict
LSApplicationQueriesSchemes. With universal links, validate host/path before action. Guard UIApplication.shared.open with allowlist.
2) Performance
2.1 Launch & Startup
- No heavy work in
application(_:didFinishLaunching:), initializers, or onAppear of the first screen. Defer I/O, network calls, and large decodes.
- Avoid synchronous
Data(contentsOf:) on the main thread.
2.2 Main-thread Budget
- UI work only on the main thread. Offload JSON decoding, image processing, and DB I/O.
- No long-running blocking calls on main (semaphores,
sleep, synchronous URL loads).
2.3 Memory / Allocations
- Audit closures for retain cycles (
[weak self]).
- Avoid unbounded caches; apply size or count limits.
- For large images, use incremental decoding and downsampling. Reuse
JSONDecoder/DateFormatter etc.
2.4 Swift Concurrency
- Prefer
async/await. Mark closures @Sendable when crossing concurrency domains.
- Cancel tasks on view disappearance; avoid leaked
Task {}. No DetachedTask unless isolation is required.
- Avoid
actor re-entrancy pitfalls; ensure hot paths don’t bounce across executors excessively.
2.5 SwiftUI Rendering
- Prevent state explosion: minimal
@State, stable identities, .equatable() where appropriate.
- Avoid heavy work in
body, onAppear, and task. Use memoization and background tasks.
- Use
Canvas, GeometryReader, and PreferenceKey carefully; they can trigger extra layout passes.
2.6 Network & Storage Efficiency
- Respect backoff and caching (
URLCache). Stream large downloads. Compress payloads when supported.
- Batch writes to persistent stores; prefer background contexts for Core Data.
Performance guardrails (use CI or recent baseline numbers when available):
- Cold launch: no regression > +200ms or +10% vs
main on representative device.
- p95 frame time: no new jank > +10% in touched screens.
- p95 memory: no sustained increase > +10% in relevant flows.
3) Stability & Correctness
3.1 Crash Risks
- Eliminate
force unwrap / force try in production paths unless provably safe.
- Defensive parsing for optionals, array indices, file paths, and casting.
3.2 Thread-safety
- Shared mutable state protected (actors/locks). No concurrent mutation of collections.
- Avoid deadlocks: no main-thread waiting on background queues that hop back to main.
3.3 Lifecycle & Ownership
- Break retain cycles (delegates
weak, NotificationCenter remove observers, timers invalidated).
WKWebView/AVPlayer deallocation handled; long-lived resources managed.
3.4 Error Handling & Resilience
- Network errors surfaced with user-safe messaging and retries (idempotent where applicable).
- Offline/timeout behavior defined; avoid silent failures.
3.5 Data Stores
- Core Data: lightweight migration options set where needed. Background context merges safe.
- Files: atomic writes, temp cleanup, and corruption handling.
Stability guardrails:
- New crash types introduced by PR: block until resolved.
- CI tests for modified modules must pass; flaky tests must include quarantine plan.
ANALYSIS METHODOLOGY
Phase 1 – Context
- Skim build settings, Info.plist, entitlements, and any added capabilities.
- Identify frameworks touched (e.g., WebKit, AVFoundation, CoreData, Security, SwiftUI).
Phase 2 – Diff Pass
- Trace data flow from inputs → parsing → storage/network → UI.
- Identify privilege boundaries (e.g., JS bridge → native, deep link → feature entry).
Phase 3 – Impact Assessment
- For each suspicious change, articulate concrete attack/impact path and affected users/data.
- Check for platform APIs that mitigate (e.g., Keychain ACLs, ATS) and whether the diff disables them.
Phase 4 – Evidence
- Prefer code pointers, failing tests, CI metrics, or targeted local traces (if feasible) to back claims.
REQUIRED OUTPUT TEMPLATE (paste in PR review)
## Finding N: <category> — `<File.swift:Line>`
- **Domain:** Security | Performance | Stability
- **Severity:** High | Medium | Low (default to High/Medium only)
- **Confidence:** 0.8–1.0 (report only ≥ 0.8)
- **Description:** <what is wrong and why>
- **Impact / Exploit Scenario:** <how this becomes a data leak, crash, perf regression, etc.>
- **Evidence:** <code refs, CI metric deltas, trace IDs, screenshots>
- **Recommendation:** <specific, actionable fix>
- **Owner:** <team/area>
- **Risk if Deferred:** <what happens if we ship as-is>
SEVERITY GUIDELINES
HIGH
- Security: PII/secrets exposure; auth bypass; trust disablement; arbitrary code/JS execution in app context.
- Performance: Launch or interaction regressions noticeable to users (>10% or budget breach) in core flows.
- Stability: New crash, deadlock, or data corruption path reachable in normal use.
MEDIUM
- Security hardening gaps with plausible misuse but partial mitigations.
- Performance regressions limited to non-core flows or behind feature flags.
- Stability risks gated by unusual preconditions with visible mitigations.
Report LOW only for defense-in-depth if the fix is trivial and low risk to change.
CONFIDENCE SCORING
- 0.9–1.0: Certain; clear path reproduced or trivially reproducible from code.
- 0.8–0.9: Known hazardous pattern with direct impact path.
- <0.8: Do not report. Gather more evidence or convert to a question.
APPROVAL CHECKLIST (must be TRUE to approve)
- No HIGH findings remain unresolved.
- All MEDIUM findings have a concrete fix plan (in this PR or a linked ticket) and risk is explicitly accepted by owner.
- Security: No ATS broadening; no trust bypass; secrets only in Keychain; logs scrubbed of PII/secrets; permissions justified with accurate Info.plist usage strings.
- Performance: Launch/frame/memory guardrails respected or justified with data (CI baseline or Instruments evidence).
- Stability: No new crash/deadlock/data-corruption paths; concurrency access is safe; lifecycle/ownership issues addressed.
- Tests/CI are green for impacted modules; risky paths have added/updated tests; flaky tests have a quarantine/owner plan.
QUICK PER-FILE HEURISTICS (useful keywords when scanning diffs)
- Info.plist / Entitlements: NSAppTransportSecurity, NSAllowsArbitraryLoads, UIBackgroundModes, keychain groups, associated domains.
- Networking: URLSession, ServerTrust, SecTrust, custom URLProtocol, pinned certificates, redirects, query parameters carrying tokens.
- Storage: UserDefaults, FileManager, Data.write, NSFileProtection*, Core Data model changes/migrations.
- WebKit: WKUserScript, addScriptMessageHandler, evaluateJavaScript, decidePolicyFor, file URL handling, unrestricted navigation.
- Concurrency: Task {}, DetachedTask, @MainActor, @Sendable, DispatchQueue.sync on main, shared mutable state.
- SwiftUI: heavy work in body, onAppear, task, unstable id(_:), excessive @State/@ObservedObject, unnecessary re-render triggers.
- Crash-prone: !, try!, force casts, force indexing, unguarded optionals, unsafe unwrap chains.
- Media/AV: long-lived AVPlayer / AVAudioSession without teardown, background playback flags.
- Crypto/Security: custom crypto, home-grown hashing, disabled certificate checks, plaintext tokens.
PRECEDENTS (how to judge borderline items)
- Logging secrets or PII in plaintext (including debug logs) is a vulnerability → block unless removed.
- Broad ATS exceptions (global NSAllowsArbitraryLoads or wide domain patterns) are blocking without tight scoping and justification.
- Client-side checks for authorization are insufficient; server must enforce. UI gating does not equal auth.
- Synchronous network/file I/O on the main thread in hot paths is a perf regression, not a style issue.
- try!/force unwraps in production paths are stability risks; require proof of invariants or replace with safe handling.
- Web content bridges (WKWebView) must validate origin and payload; unrestricted bridges are high risk.
- Feature flags do not excuse shipping known HIGH risks; flags can drift or misconfigure.
Final note: Keep reviews concise, attach evidence, and propose the minimal safe fix. If confidence < 0.8, raise a question with the exact data needed (code pointers, metrics, traces) to reach a decision quickly.