Skip to content

perf: remove CryptoSwift, add streaming file TDF I/O, and fix hot-path bottlenecks - #71

Merged
arkavo-com merged 3 commits into
mainfrom
perf/codebase-optimizations
Nov 26, 2026
Merged

arkavo-com merged 3 commits into
mainfrom
perf/codebase-optimizations

Conversation

@arkavo-com

@arkavo-com arkavo-com commented Nov 26, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Implements the prioritized performance, memory, dependency, and deduplication refactor across OpenTDFKit:

P0 — Remove CryptoSwift Dependency

  • Replaced CryptoSwift.AES CBC encrypt/decrypt in TDFCrypto with hardware-accelerated CommonCrypto (CCCrypt) and branchless constant-time PKCS#7 unpadding validation (zeroing buffers on failure and eliminating Array(...) payload copies).
  • Removed CryptoSwift from Package.swift and Package.resolved.
  • Added AES-128/192/256-CBC round-trip, block-boundary, invalid-IV, and corrupted-padding tests.

P1 — Hot-Path Crypto, Concurrency & Algorithmic Fixes

  • Parallel collection decryption & zero-alloc nonces: Removed mutable nonceBuffer from NanoTDFCollectionDecryptor, marked decryptItem/decryptBatch/tryDecryptItem nonisolated (preserving async source compatibility + adding decryptItemSync), and eliminated per-item Data nonce allocations in NanoTDFCollection and NanoTDFCollectionDecryptor.
  • Eliminated redundant ECDH + HKDF:
    • KASRewrapClient.rewrapAndUnwrapTDFShares now derives the session KEK once per response instead of per share.
    • KASService.processKeyAccess(header:...) reuses the already-derived primary key instead of running ECDH + HKDF twice.
  • O(1) key pop, core-chunked keygen & zero-copy serialization:
    • Replaced O(n) keys.removeFirst() in PublicKeyStore with an amortized O(1) head-cursor queue.
    • Chunked KeyStore.generateAndStoreKeyPairs by activeProcessorCount, serialized directly from SecureKeyPairStorage without intermediate unzeroed private-key Data copies, and replaced String(format:) hex encoding with a lookup table.
  • Precomputed invariants & micro-optimizations: standardTDFSessionSalt as static let, pre-parsed kasIdentityURL in KASRewrapClient.init, fast ASCII/hex normalizedPercentEncoding, Date().formatted(.iso8601) in TDFJSONBuilder, zero-copy StrictJSON byte scanning, direct big-endian reads in BinaryParser, and capacity pre-reservation in NanoTDF / TDFProcessor.

P2 — True Streaming File I/O

  • Added single-pass streaming multi-segment decryption to a private (0600) atomic staging file in StreamingTDFCrypto (halving disk I/O and AES-GCM CPU vs. two-pass) and eliminated per-segment Data copies in decryptPayloadMultiSegmentFromMemory.
  • Made TDFDecryptor.decryptFile / decryptFileMultiSegment stream via TDFArchiveReader.writePayload(to:) + single-pass decryption while honoring chunkSize.
  • Added TDFEncryptor.encryptFileStreaming + TDFStreamingFileEncryptionResult for bounded O(segmentSize) file encryption.

P3 — Deduplication & Cleanup

  • Removed unused NoRedirectDelegate, deduplicated createSignedJWT, removed duplicate constantTimeEquals helpers, unified PEM body decoding and EC curve wrapping while eliminating sealed.combined! force-unwraps, routed file encryptors through shared makeManifest/makeResult, and shared single-split EC unwrap logic across TDFCBORDecryptor and TDFJSONDecryptor.

Verification

  • swiftformat --lint . — 0/80 files require formatting
  • swift test — 480 tests executed, 0 failures (15 env-gated integration tests skipped)
  • swift build -c release --product OpenTDFKitCLI — succeeded
  • scripts/interop/ec-wrapped Go verify on Swift-generated fixture — OK
  • CI Swift and X-Test (Swift ↔ Go cross-SDK) workflows triggered on this PR

Comment thread OpenTDFKit/TDF/TDFProcessor.swift Resolved
Comment thread OpenTDFKit/KeyStore.swift

@gitar-bot gitar-bot Bot Nov 26, 2026 •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 91-93

💡 Quality: KeyStore.keyPairs/totalBytesStored lost private(set) in this commit

This commit changes keyPairs and totalBytesStored from public private(set) var to public var. The PR description says both should stay public private(set). As public var, code in any module can write them from an actor extension or an isolated context. Something like keyPairs[id] = nil then skips recalculateTotalBytesStored(), so the memory accounting goes stale, and the stored key material can be overwritten without the store's validation. Put the private(set) back on both properties.

Restore read-only external access:

public private(set) var keyPairs: [KeyPairIdentifier: StoredKeyPair]
/// Track total memory used
public private(set) var totalBytesStored: Int = 0

Was this helpful? React with 👍 / 👎

@gitar-bot gitar-bot Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gitar has auto-approved this PR (configure)

@gitar-bot

gitar-bot Bot commented Nov 26, 2026 •

Copy link
Copy Markdown
Code Review 👍 Approved with suggestions 🔴 High risk 1 closed / 2 findings

Replacing AES-CBC and changing streaming TDF encryption/decryption alters cryptographic confidentiality and integrity boundaries; implementation errors could expose or corrupt protected payloads.

Removes CryptoSwift in favor of CommonCrypto, adds single-pass streaming file TDF decryption and encryption, and applies hot-path performance and deduplication refactors across OpenTDFKit. The streaming decryptFile 512 MiB payload limit was resolved. One open minor finding remains: KeyStore.keyPairs and totalBytesStored lost their private(set) modifier and should be restored so external writes cannot bypass memory accounting and validation.

  • Restore private(set) on keyPairs and totalBytesStored in OpenTDFKit/KeyStore.swift
💡 Quality: KeyStore.keyPairs/totalBytesStored lost private(set) in this commit

📄 OpenTDFKit/KeyStore.swift:91-93

This commit changes keyPairs and totalBytesStored from public private(set) var to public var. The PR description says both should stay public private(set). As public var, code in any module can write them from an actor extension or an isolated context. Something like keyPairs[id] = nil then skips recalculateTotalBytesStored(), so the memory accounting goes stale, and the stored key material can be overwritten without the store's validation. Put the private(set) back on both properties.

Restore read-only external access
public private(set) var keyPairs: [KeyPairIdentifier: StoredKeyPair]
/// Track total memory used
public private(set) var totalBytesStored: Int = 0
✅ 1 closed
✅ Edge Case: Streaming decryptFile still rejects payloads over 512 MiB

📄 OpenTDFKit/TDF/TDFProcessor.swift:219-233 📄 OpenTDFKit/TDF/TDFProcessor.swift:665
The new encryptFileStreaming is meant to encrypt arbitrarily large files with bounded memory. The matching decryptFileStreaming path, though, calls reader.writePayload(to: tempHandle) with its default maxSize = TDFArchiveReader.defaultPayloadMaxSize (512 MiB). So decryptFile / decryptFileMultiSegment throw TDFArchiveError.payloadTooLarge on any archive whose payload is over 512 MiB, including archives that encryptFileStreaming just wrote. The cap was there to bound RAM. This path now streams to a temp file and checks the actual size against the manifest's segment sizes, so the cap no longer protects memory and only breaks the round trip. Fix: pass a cap derived from the manifest (the sum of encryptedSegmentSize), pass nil, or expose a maxPayloadSize parameter on the file decrypt APIs. Also add a test that covers a payload above the cap, or a configurable smaller cap.

🤖 Prompt for agents
Code Review: Removes CryptoSwift in favor of CommonCrypto, adds single-pass streaming file TDF decryption and encryption, and applies hot-path performance and deduplication refactors across OpenTDFKit. The streaming decryptFile 512 MiB payload limit was resolved. One open minor finding remains: `KeyStore.keyPairs` and `totalBytesStored` lost their `private(set)` modifier and should be restored so external writes cannot bypass memory accounting and validation.
  
  - Restore `private(set)` on `keyPairs` and `totalBytesStored` in `OpenTDFKit/KeyStore.swift`

1. 💡 Quality: KeyStore.keyPairs/totalBytesStored lost private(set) in this commit
   Files: OpenTDFKit/KeyStore.swift:91-93

   This commit changes `keyPairs` and `totalBytesStored` from `public private(set) var` to `public var`. The PR description says both should stay `public private(set)`. As `public var`, code in any module can write them from an actor extension or an isolated context. Something like `keyPairs[id] = nil` then skips `recalculateTotalBytesStored()`, so the memory accounting goes stale, and the stored key material can be overwritten without the store's validation. Put the `private(set)` back on both properties.

   Fix (Restore read-only external access):
   public private(set) var keyPairs: [KeyPairIdentifier: StoredKeyPair]
   /// Track total memory used
   public private(set) var totalBytesStored: Int = 0

Verification

Rules No rules evaluated

Functional validation Not enabled

Set up

Auto-approval Approved

For more verification details, comment gitar display:verbose.

Options

Auto-apply is off → Gitar will not commit updates to this branch.
Display: compact → Showing compact verification results.

Comment with these commands to change the behavior for this request:

Auto-apply Compact
gitar auto-apply:on         
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Gitar

@arkavo-com
arkavo-com merged commit 51c1aa7 into main Nov 26, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant