Add lookupZones, fetchRecordChanges, and uploadAssets operations#204
Add lookupZones, fetchRecordChanges, and uploadAssets operations#204
Conversation
|
Important Review skippedDraft detected. Please check the settings in the CodeRabbit UI or the You can disable this status message by setting the
✨ Finishing touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #204 +/- ##
==========================================
- Coverage 18.05% 17.95% -0.11%
==========================================
Files 78 78
Lines 7830 7830
==========================================
- Hits 1414 1406 -8
- Misses 6416 6424 +8
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
Code Review: Add lookupZones, fetchRecordChanges, and uploadAssets operationsSummaryThis PR adds three important CloudKit Web Services operations, improving API coverage from 35% to 53%. The implementation is well-structured and follows MistKit patterns consistently. Great work overall! 🎉 ✅ StrengthsCode Quality
Architecture
Demo Integration
🔍 Issues & ConcernsCritical: Missing Test Coverage
|
|
Hi, I'm trying to use the .uploadAssets function on this branch, however it fails with the following error message: Any ETA when it becomes stable? I want to use it for mp3 audio assets. |
I'm in the very early stages of adding this. It's good to know someone is interested. I'll bump this up in my priorities for now. Probably in the next 2 weeks or so. I need to:
|
1badf6d to
4cc91cf
Compare
95d2cae to
51b7883
Compare
- Update BushelCloud and CelestraCloud subrepo parent commits to 95d4942 - Fixes git-subrepo push/pull errors after branch divergence - Enable enhanced compiler checking flags in Package.swift: - Warn about functions with >100 lines - Warn about slow type checking expressions >100ms Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Implements proper CLI subcommand architecture and integration tests that demonstrate the three new CloudKit operations (lookupZones, fetchRecordChanges, uploadAssets) working together in realistic workflows. New CLI Subcommands: - upload-asset: Upload binary assets to CloudKit - lookup-zones: Look up specific zones by name - fetch-changes: Fetch record changes with incremental sync - test-integration: Run comprehensive 8-phase integration tests Integration Test Suite (8 Phases): 1. Zone verification with lookupZones 2. Asset upload with uploadAssets (programmatic PNG generation) 3. Record creation with uploaded assets 4. Initial sync with fetchRecordChanges 5. Record modifications 6. Incremental sync demonstrating sync token usage 7. Final zone verification 8. Automatic cleanup Infrastructure: - CloudKitCommand protocol for shared functionality across subcommands - IntegrationTestRunner orchestrates all test phases - IntegrationTestData generates test PNG images programmatically - IntegrationTestError provides typed error handling - schema.ckdb defines MistKitIntegrationTest record type Architecture Changes: - Converted MistDemo from flag-based to subcommand architecture - Added Commands/ directory for subcommand implementations - Added Integration/ directory for test infrastructure - CloudKitCommand protocol resolves API tokens from env or options Documentation: - README-INTEGRATION-TESTS.md with complete usage guide - Schema deployment instructions - Troubleshooting guide - Example outputs for all commands All subcommands support: - API token from --api-token or CLOUDKIT_API_TOKEN env var - Container identifier configuration - Development/production environment selection Test integration features: - Configurable record count (--record-count) - Configurable asset size (--asset-size) - Verbose mode for detailed output (--verbose) - Skip cleanup flag for manual inspection (--skip-cleanup) Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
…ew CloudKit APIs - Add private database support to integration tests with AdaptiveTokenManager - Implement web authentication server with CloudKit.js integration - Add web auth token options to CLI commands (--web-auth-token) - Support CLOUDKIT_WEBAUTH_TOKEN environment variable - Update integration test runner to handle both public/private databases - Add comprehensive CloudKit.js authentication flow with multiple token extraction methods - Create browser-based authentication interface with proper error handling - Document testing status and next steps in TESTING_STATUS.md New CLI options: - test-integration --database [public|private] --web-auth-token TOKEN - All commands now support web authentication for private database access Authentication flow: 1. swift run mistdemo auth (starts web server) 2. Browser-based Apple ID sign-in with CloudKit.js 3. Automatic web auth token extraction and display 4. Use token with integration tests and individual operations Ready to test lookupZones, fetchRecordChanges, and uploadAssets APIs once web authentication token extraction is working correctly. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
…g status MAJOR IMPROVEMENTS: - Enhanced postMessage listener with origin verification (icloud.com, apple-cloudkit.com) - Added network request interception (fetch/XHR) as fallback token capture method - Extended timeout from 5s to 10s for token arrival - Added browser debugging helpers (mistKitDebug.*) - Simplified handleAuthentication() removing 160+ lines of non-working detection code IMPLEMENTATION DETAILS: Phase 1: Enhanced postMessage capture - Origin validation for security - Support for multiple token formats (plain string `158__54__...`, object properties) - Global token storage in window.cloudKitWebAuthToken Phase 2: Network interception fallback - Intercepts fetch() and XMLHttpRequest - Captures tokens from CloudKit API responses - Logs all CloudKit requests for debugging Phase 3: Simplified authentication flow - Removed localStorage, cookies, property access strategies (didn't work) - Clean token promise with 10s timeout - Manual extraction instructions on failure Phase 5: Debugging helpers - mistKitDebug.container() - Get CloudKit container - mistKitDebug.token() - Get current token - mistKitDebug.setToken(tok) - Manually set token - mistKitDebug.sendToServer() - Send token to server - mistKitDebug.inspectContainer() - Inspect container for token TESTING STATUS UPDATE: - Web auth token successfully extracted manually (158__54__... format verified) - Implementation complete and ready for testing - Blocked on CloudKit container configuration (421 Misdirected Request) - Need to verify container setup at icloud.developer.apple.com/dashboard FILES MODIFIED: - Examples/MistDemo/Sources/MistDemo/Resources/index.html - Examples/MistDemo/Sources/MistDemo/MistDemo.swift - Examples/MistDemo/TESTING_STATUS.md Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
ecc682c to
03771e8
Compare
PR Review: Add lookupZones, fetchRecordChanges, and uploadAssets operations (#204)Overall: Meaningful API coverage expansion, but this PR has several issues that need to be addressed before merging — most critically a committed API token and two tracking files that do not belong in source control. CRITICAL: API token committed in
|
Code Review: Add lookupZones, fetchRecordChanges, and uploadAssets OperationsSignificant PR that increases API coverage from 35% → 53%. The architectural direction is right, but several issues need to be addressed before this is ready to merge. 🔴 CriticalHardcoded API token in ```
A real development API token is committed in plain text. Even though it's a development environment token, this should be revoked in the CloudKit dashboard immediately and removed from the file before merge. Tokens committed to public repos are indexed by secret scanners and can be used before they expire.
The PR uncomments: SPM refuses to use a library containing 🟠 High priority
This file reads as an in-progress debugging scratchpad (
This file is a proposal for the CLI commands return exit code 0 on validation failure In ```swift // Should be: No unit tests for the three new service operations The PR adds 🟡 Medium priorityLocal filesystem path leaked in Line ~410 references Debug scaffolding in The added JS monkey-patches
The runner constructs ✅ What's good
Summary
|
PR Review: Add lookupZones, fetchRecordChanges, and uploadAssets operationsThe CRITICAL: Hardcoded API token in
|
Code Review — PR #204: Add lookupZones, fetchRecordChanges, and uploadAssets operationsGood progress on API coverage. The new operations follow MistKit patterns well. A few issues to address: Temporary/debug files committed to the repo
Commented-out compiler strictness (
|
Code Review — PR #204: Add lookupZones, fetchRecordChanges, and uploadAssets operationsOverviewThis PR significantly expands MistKit's CloudKit Web Services coverage (35% → 53%) by adding three new operations: zone lookup, incremental record sync, and binary asset uploads. The architecture is consistent with existing MistKit patterns (async/await, typed errors, proper transport separation for assets). Security Concern — Hardcoded API Token
Even if expired or for a dev container, hardcoding credentials in committed documentation is a security anti-pattern. Please remove this token and replace it with a placeholder like Other IssuesLocal file path in documentation This is a local machine path that should be removed from committed docs. Invalid PNG CRC checksums in test data ( // Simple CRC32 (not accurate, but sufficient for test data)
data.append(contentsOf: [0x00, 0x00, 0x00, 0x00])PNG parsers (including those used by CDN/CloudKit) validate CRC32. Invalid chunks may cause the asset to be rejected at upload or storage time, making the integration tests unreliable. Either generate valid CRC32s or — simpler — just generate random non-PNG bytes padded to the target size (CloudKit doesn't validate image content at upload). Authentication inconsistency in let tokenManager = APITokenManager(apiToken: resolvedToken)
let service = try CloudKitService(..., database: .public)Per CLAUDE.md and PR #205's documentation updates, public database operations require server-to-server key authentication (
ProcessInfo.processInfo.environment["CLOUDKIT_WEBAUTH_TOKEN"]The new canonical name (per PR #205 updates) is
router.middlewares.add(
FileMiddleware(
resourcesPath,
searchForIndexHtml: true
)
)Where is CI workflows hardcoded to feature branch PR is blocked per
This means the new operations have not been validated against a real CloudKit container. The unit tests cover the Swift layer, but end-to-end correctness of the wire format, response parsing, and sync token handling is unverified. This should be resolved before moving out of Draft.
let assetToken = try await phase2UploadAsset(service: service)
// ...
for i in 1...recordCount {
// same assetToken used for every record
let asset = FieldValue.Asset(..., downloadURL: assetToken.url)CloudKit asset tokens are typically single-use per record association. Reusing the same token across multiple records may silently fail or create broken asset references. Each record creation should ideally upload its own asset or at minimum this assumption should be documented. Positives
Summary
|
Code Review: Add lookupZones, fetchRecordChanges, and uploadAssets OperationsOverviewThis PR adds CLI commands and a comprehensive 8-phase integration test suite to API coverage moves from 35% → 53% (9/17 operations). ✅ Strengths
🔐 Security Concern — Hardcoded API Token
If this is a live token it should be invalidated and replaced with a 🐛 Potential Issues1. Silent return on missing auth token Several commands use // LookupZones.swift, FetchChanges.swift
guard !resolvedToken.isEmpty else {
print("Error: API token is required")
return // ← should be: throw SomeError.missingToken
}
2. Potentially invalid PNG in The generated PNG uses a manually assembled byte sequence with a comment acknowledging the CRC32 is not accurate. CloudKit's CDN may validate image integrity and reject malformed PNGs. Consider either:
3. Phase 6 hard-dependency on Phase 4 sync token If the development database is empty, Phase 4 may return no records and no sync token. Phase 6 then throws 4. Hardcoded If the CloudKit schema in the target container uses a different name, every phase fails without a useful error. Making this configurable via 🔬 Test Coverage Observations
💅 Style / Minor
SummarySolid integration test coverage for three new operations. Before merging:
The |
Code Review: PR #204 — Add lookupZones, fetchRecordChanges, and uploadAssetsOverviewThis PR increases CloudKit Web Services API coverage from 35% to 53% by implementing three new operations: Security Concerns 🔴API token committed to A CloudKit API token is committed in plaintext to IssuesModerateEnvironment variable inconsistency in
let resolvedWebAuthToken = webAuthToken.isEmpty ?
ProcessInfo.processInfo.environment["CLOUDKIT_WEBAUTH_TOKEN"] ?? "" :
webAuthTokenBut the rest of the PR standardizes on
The factory method previously fell back gracefully to
The runner references Commented-out strict concurrency flags in // .unsafeFlags([
// "-warn-concurrency",
// "-strict-concurrency=complete",
// ...
// ])These were enabled as part of the project's quality bar. Commenting them out to make the build pass may be hiding data-race issues introduced in this PR. Consider resolving the underlying concurrency warnings rather than silencing them.
router.middlewares.add(
FileMiddleware(resourcesPath, searchForIndexHtml: true)
)This is inserted into what appears to be server setup code without a corresponding comment explaining why it's needed here or when this code path is even reached. It also doesn't appear in the diff with a clear setup — this should be explained. Invalid PNG structure in The function appends IDAT chunks after the IEND chunk, which is technically invalid per the PNG specification. IEND must be the last chunk. Most parsers tolerate this, but CloudKit's CDN may validate PNG structure strictly. The padding should be inserted before IEND, and the fake CRC32 values ( MinorHardcoded container ID in multiple command files
@Option(name: .long, help: "Web auth token for private database access")
var webAuthToken: String = ""Using What's Good
Summary
Given that the PR is still in draft state and |
Code Review — PR #204: Add lookupZones, fetchRecordChanges, and uploadAssetsOverviewThis PR improves CloudKit API coverage from 35% to 53% by adding three new operations. The architecture follows MistKit conventions well. Most concerns are about the MistDemo integration layer rather than the core library itself. Misplaced
|
| Area | Status |
|---|---|
lookupZones / fetchRecordChanges / uploadAssets core implementation |
✅ Follows conventions |
FileMiddleware in CLI entry point |
|
| Env var alignment with PR #205 | CLOUDKIT_WEBAUTH_TOKEN |
| Commented-out concurrency flags | |
| Local path in committed docs | |
AdaptiveTokenManager availability |
|
Asset downloadURL semantics |
|
| Unit tests for new service methods | ❌ Missing |
| Integration test runner | ✅ Well-structured |
Code Review: Add lookupZones, fetchRecordChanges, and uploadAssets operations (#204)OverviewThis PR adds three new CloudKit Web Services operations to the core library ( Core Library —
|
| Area | Status |
|---|---|
lookupZones / fetchRecordChanges / uploadAssets implementation |
✅ |
fetchAllRecordChanges infinite-loop risk |
|
| Zone capabilities always empty | |
Asset receipt vs downloadURL association |
|
| CLI options duplication (4 commands × 3 fields) | @OptionGroup |
| Silent return on missing token (should throw) | |
Env var name inconsistency (WEB_AUTH_TOKEN vs WEBAUTH_TOKEN) |
|
Raw API token committed in TESTING_STATUS.md |
🔴 Must remove before merge |
| CelestraCloud concurrency flags disabled | |
swift-build-issue-proposal.md in repo root |
|
| Unit tests for new operations | |
| Invalid PNG padding in test data | ℹ️ Comment-only fix |
The core library additions are solid. The main action item before merging is removing the committed API token and re-enabling the CelestraCloud concurrency flags (or explaining why they are off).
Code Review: Add lookupZones, fetchRecordChanges, and uploadAssetsSummaryThis PR adds three new CloudKit operations, improving API coverage from 35% to 53%. The core implementations are architecturally sound and follow MistKit conventions well. The asset upload implementation is particularly notable for correctly following the connection pool separation requirement. However, there are meaningful test coverage gaps for Recommendation: Request changes — primarily for test coverage gaps Asset Upload Safety — CRITICAL ✅This is the most important thing to verify per CLAUDE.md, and the implementation gets it right:
No issues here. The implementation matches the design requirements in CLAUDE.md exactly. Test Coverage ❌This is the primary concern:
These two operations need test coverage before merge. The existing API Design Observations
The method accepts
If CloudKit returns a response without a
When
The automatic pagination loop accumulates all results in a single
Code Quality ✅Strengths:
Performance
Security
Swift Conventions ✅
Specific RecommendationsBefore merge:
Follow-up issues (already created per PR description, just confirming alignment):
🤖 Generated with Claude Code |
Code Review: Add lookupZones, fetchRecordChanges, and uploadAssets OperationsOverviewThis PR adds three CloudKit Web Services operations, increasing API coverage from 35% to 53% (9/17 operations). New types include ✅ Strengths
🔴 Critical Issues1. Compiler warning flags uncommitted in 2. Hardcoded container identifier 🟠 High-Priority Issues3. No unit tests for the three new operations 4. Missing file validation in 5. No timeout protection in 🟡 Medium-Priority Issues6. Pagination resumability not documented at call site 7. 8. Incomplete integration test setup documentation
|
| Operation | Unit Tests | Integration Tests |
|---|---|---|
lookupZones |
❌ None | ✅ Via --test-lookup-zones |
fetchRecordChanges |
❌ None | ✅ Via --test-fetch-changes |
uploadAssets |
❌ None | ✅ Via --test-upload-asset |
Target: add @Test Swift Testing unit tests using mock transports for each operation, matching the pattern in existing Tests/MistKitTests/.
Summary
This is a valuable feature addition with a solid integration test framework. The following must be addressed before merging:
Blocking:
- Revert or fix the
-warn-long-function-bodies=100compiler flag change - Remove or parameterize the hardcoded container identifier
Strongly Recommended:
3. Add unit tests for all three new operations
4. Add file size validation in UploadAsset
5. Add timeout protection to IntegrationTestRunner
6. Mask sync tokens/record IDs in IntegrationTestError descriptions
Code Review — PR #204: Add lookupZones, fetchRecordChanges, and uploadAssetsOverviewThis PR adds three new CloudKit Web Services operations, bringing API coverage from 35% to 53%. The new MistDemo commands provide integration-test entry points for all three. Overall the structure is solid, but there are a few design and safety concerns worth addressing. ✅ What's Done Well
|
|
Code Review: PR 204 - Add lookupZones, fetchRecordChanges, and uploadAssets (Draft) This is a draft PR so this is early feedback rather than a blocking review. Overview Adds three new CloudKit Web Services operations, bringing API coverage from 35% to 53%. The implementation follows existing MistKit patterns (async/await, typed errors, dependency injection). MistDemo integration tests provide good end-to-end coverage. Issues to Address Before Marking Ready
TestIntegration.swift reads CLOUDKIT_WEBAUTH_TOKEN (line ~769), but PR 205 has renamed this env var to CLOUDKIT_WEB_AUTH_TOKEN across all docs. Since 205 will likely merge first, update this file to use CLOUDKIT_WEB_AUTH_TOKEN.
The padding IDAT chunks use [0x00, 0x00, 0x00, 0x00] as CRC32. If CloudKit's asset upload pipeline validates PNG structure, this will fail. Recommend either:
In IntegrationTestData.generateTestImage's padding loop, the variable is declared var but never mutated.
Both commands unconditionally create the service with .public database. If users want to look up zones or fetch changes in a private database, these commands won't work. Consider adding a --database option or at least documenting this limitation.
The setup-mistkit GitHub Action has a branch input but the workflow files call it without providing branch, so it always uses the keep-local path behavior. The action appears designed to optionally switch to a remote branch reference, but the intent isn't fully wired up. Minor Issues
Positive Highlights
|
Code Review: Add lookupZones, fetchRecordChanges, and uploadAssets operations
OverviewAdds three new CloudKit Web Services operations, advancing API coverage from 35% to 53%. The core implementation follows MistKit's established patterns well — async/await, typed errors, MistKitLogger throughout — and the integration test suite ( Blocking Issues🔴 CLI
|
| Feature | Unit Tests | Notes |
|---|---|---|
uploadAssets |
✅ | Success, validation, error scenarios covered |
lookupZones |
❌ | No unit tests |
fetchRecordChanges |
❌ | No unit tests |
fetchAllRecordChanges pagination |
❌ | No unit tests |
| Integration (all three) | ✅ | IntegrationTestRunner 8-phase workflow |
lookupZones and fetchRecordChanges need unit tests before merging — particularly for:
- Empty input validation (
lookupZoneswith zero IDs) moreComing: falsevstruehandling infetchRecordChangessyncTokenround-trip (returned token fed back correctly on next call)
Security
- Token redaction in debug output is handled correctly (
.prefix(20)in log output) - The HTML token extraction in
index.htmlvalidates origins againsticloud.com/apple-cloudkit.com— appropriate for its purpose - No rate limiting in
fetchAllRecordChangespagination — could trigger CloudKit throttling on large datasets. Not a security issue but worth a note in docs
Summary
| Category | Status |
|---|---|
| Compilation | 🔴 CLI upload command broken |
| Core API logic | 🟢 Solid |
| Asset upload transport | 🟢 Correctly separated |
| Test coverage | 🟡 uploadAssets only; lookupZones/fetchRecordChanges untested |
| Zone capabilities | 🟡 Hardcoded empty — misleading |
| Documentation | 🟢 Comprehensive README and docstrings |
| Memory (fetchAll) | 🟡 In-memory accumulation, tracked as #200 |
Before graduating from draft:
- Fix the
UploadAsset.swiftcompilation errors - Add unit tests for
lookupZonesandfetchRecordChanges - Fix or remove zone capabilities extraction
Everything else can reasonably land as follow-up issues, several of which are already filed (#200–#203).
…, #46, #30)
Implement three CloudKit Web Services operations to improve API coverage from 35% to 53% (9/17 operations):
New public types:
MistDemo integration tests:
Created GitHub issues for future enhancements:
All operations follow MistKit patterns: async/await, typed errors, proper logging, and comprehensive error handling.
Perform an AI-assisted review on