Skip to content

feat(android): core:cloudtts vendor adapters — 5 vendors, real API shapes verified (#451) - #465

Merged
github-actions[bot] merged 2 commits into
devfrom
feature/cloudtts-android-vendors
Aug 23, 2026
Merged

github-actions[bot] merged 2 commits into
devfrom
feature/cloudtts-android-vendors

Conversation

@libravault-xyz

@libravault-xyz libravault-xyz commented Aug 23, 2026 •

Copy link
Copy Markdown
Collaborator

What

PR 2 of 4 for Android's half of Premium Cloud TTS Voices (BYOK) — part of #451. Builds on the merged foundation PR (#462). Adds the five vendor HTTP adapters + RealCloudTtsProvider (play flavor). Still no TTS engine wiring, no Settings UI — nothing in this PR is reachable at runtime yet (next two PRs).

What's verified, not assumed

Before writing any adapter code, I fetched each vendor's actual current REST API documentation rather than working from training-data memory:

  • ElevenLabs: POST /v1/text-to-speech/{voice_id}, xi-api-key header, raw audio response.
  • OpenAI: POST /v1/audio/speech, Authorization: Bearer, raw audio response.
  • Google Cloud TTS: POST /v1/text:synthesize?key=... — the one vendor whose response is JSON with base64-encoded audio ({"audioContent": "..."}), not raw bytes. Verified this explicitly; assuming a uniform response shape across all five would have been a real bug.
  • Azure AI Speech: region-specific host, Ocp-Apim-Subscription-Key header, SSML body. Key validation hits a second, different host (token issuance), not the synthesis host.
  • Amazon Polly: not a bearer-token REST call at all — AWS SigV4-signed, region-specific host. This is why feat(android): core:cloudtts foundation — gate, secure key storage (#451) #462's CloudApiKeyStore/CloudTtsProvider interfaces take a Map<String,String> of credential fields, not a single string — caught this during vendor research and fixed the interface before feat(android): core:cloudtts foundation — gate, secure key storage (#451) #462 merged, rather than hacking around it here.

AwsSigV4Signer — flagging a real residual risk rather than a false-confidence test

Implemented directly from AWS's published SigV4 algorithm. I looked for an official AWS test-vector fixture to assert an exact known-answer signature against, but couldn't get a trustworthy verbatim copy of one in this environment (a fetch of one came back with an obviously-corrupted hash — wrong length — so I didn't use it; asserting a wrong hardcoded value would be worse than not asserting one, since it would look like verification without being any).

Instead, AwsSigV4SignerTest covers what must hold regardless: correct AWS4-HMAC-SHA256 format, a 64-hex-char signature, determinism for identical inputs, and sensitivity to every signed input changing. This needs one real live-request (or trusted SDK cross-check) verification before Polly ships to users — filed as #466 so it doesn't get silently forgotten once this PR is just another merged commit.

Testing

New dependency: OkHttp 5.5.0 + mockwebserver3 — playImplementation/testPlayImplementation-scoped only, same convention as billing-ktx. No real network calls anywhere in the test suite.

./gradlew :core:cloudtts:testPlayDebugUnitTest :core:cloudtts:testFdroidDebugUnitTest

BUILD SUCCESSFUL, 49 tests (re-verified again after a clean rebase onto post-#462 dev — same result). Per-adapter success/failure/missing-credential-field cases, a dispatch-by-provider test, the fixed-hosts regression test (PRD §7), and the SigV4 signer's structural tests.

F-Droid isolation, checked at the module level directly (not just :app, which doesn't depend on core:cloudtts yet):

./gradlew :core:cloudtts:dependencies --configuration fdroidDebugRuntimeClasspath   # zero OkHttp
./gradlew :core:cloudtts:dependencies --configuration playDebugRuntimeClasspath     # OkHttp 5.5.0 present

Unrelated finding along the way: :app's F-Droid classpath already carries a different, pre-existing transitive OkHttp (4.12.0, via coil-base) — not caused by this change, confirmed by version mismatch and by core:cloudtts not being wired into :app yet. Filed as #463 for separate triage.

Not in this PR

  • TtsEngineFactory multibinding refactor, CloudTtsEngine, fallback-on-error wiring — next PR (the one that first makes this reachable at runtime).
  • Settings UI, disclosure modal — PR after that.

Part of #451.

…apes verified (#451)

PR 2 of 4 for Android. Builds on the merged foundation PR's CloudTtsProvider/
CloudApiKeyStore interfaces. Adds RealCloudTtsProvider (play flavor) fanning
out to five vendor HTTP adapters, verified against each vendor's actual
current REST API docs before writing any code, not assumed from training
memory:

- ElevenLabs: POST /v1/text-to-speech/{voice_id}, xi-api-key header, raw
  audio response.
- OpenAI: POST /v1/audio/speech, Bearer auth, raw audio response.
- Google Cloud TTS: POST /v1/text:synthesize?key=..., the ONE vendor whose
  response is JSON with base64-encoded audio, not raw bytes — verified this
  explicitly rather than assuming a uniform response shape across vendors.
- Azure AI Speech: region-specific host, Ocp-Apim-Subscription-Key header,
  SSML body. Key validation uses a second, different host (token issuance)
  from synthesis.
- Amazon Polly: the one vendor that isn't a bearer-token REST call at all —
  AWS SigV4-signed, region-specific host. This is why the foundation PR's
  CloudApiKeyStore/CloudTtsProvider interfaces take a credential Map, not a
  single string (caught and fixed before that PR merged).

New CloudTtsFixedHosts pins all five vendors' hosts (PRD §7 regression
requirement) — Azure/Polly pin the host *pattern* since they're
region-specific, not a literal.

AwsSigV4Signer: implemented directly from AWS's published SigV4 algorithm.
Its class doc calls out an explicit residual risk: no trustworthy AWS
test-vector fixture was available in this environment to assert an exact
known-answer signature against, so its tests verify format/determinism/
input-sensitivity rather than a hardcoded expected hash — asserting a
possibly-wrong magic value would be worse than not asserting one. Filed as
a required manual/live-verification step before Polly ships to users (see
PR description).

Testing: OkHttp 5.5.0 + mockwebserver3 (play-flavor-only, scoped the same
way billing-ktx is), no real network calls. 49 tests: per-adapter
success/failure/missing-credential cases, dispatch-by-provider test,
fixed-hosts regression, SigV4 signer structural tests.

./gradlew :core:cloudtts:testPlayDebugUnitTest — BUILD SUCCESSFUL, 49/49.
Also verified core:cloudtts's own per-flavor runtime classpath directly
(:core:cloudtts:dependencies): OkHttp 5.5.0 present only in playDebug,
absent from fdroidDebug. (Found and filed #463 for an unrelated pre-existing
OkHttp 4.12.0 already in :app's F-Droid classpath via Coil — not caused by
this change, :app doesn't depend on core:cloudtts yet.)

Part of #451. Depends on the merged core:cloudtts foundation PR.
@github-actions github-actions Bot added the risk:high Touches a sensitive path or exceeds diff-size threshold — always human merge label Aug 23, 2026
@libravault-pipeline-bot libravault-pipeline-bot Bot added the status:needs-review QA passed, awaiting principal-review-agent label Aug 23, 2026
@github-actions

Copy link
Copy Markdown
Contributor

This PR was opened outside the automated pipeline (author isn't libravault-pipeline-bot[bot]) and doesn't link an issue (no Closes #N-style line in its body), so there's no acceptance criteria for qa-agent.yml to verify against — it would otherwise sit with no risk/status label and nothing downstream would pick it up (see issue #223's actual history, and issue #343 for this issue-less case specifically). This deterministic backstop (pr-intake.yml) classified its risk and applied status:needs-review to route it straight to principal review.

@github-actions

Copy link
Copy Markdown
Contributor

Pipeline is at capacity (3/3 active runs) — skipping this review run. Re-apply status:needs-review once activity settles, or re-trigger manually via workflow_dispatch.

@github-actions

Copy link
Copy Markdown
Contributor

📱 iOS Build Status: PASSED

⏭️ iOS Simulator Build & Unit Tests - skipped
✅ Android Core Modules - success

iOS UI tests run in a separate, informational job and are not reflected above — check "iOS UI Tests (informational)" for those.

View run details

…ess, dedup

Independent review (code-review skill, high effort) on PR #465 found:

1. ElevenLabsAdapter built the request path via addPathSegments("v1/text-to-speech/\$voiceId")
   — that method splits its WHOLE argument on '/', so a voiceId containing a
   slash (however unlikely from a real vendor catalog) would add/alter path
   segments instead of being treated as one opaque value. Fixed: addPathSegment
   (singular) on voiceId, which percent-encodes it as one segment.

2. AzureSpeechAdapter escaped `text` into the SSML body but not `voiceId` in
   the same `<voice name='...'>` attribute — inconsistent, and a voiceId
   containing an apostrophe/ampersand would break or inject into the SSML.
   Fixed: both escaped the same way.

3. GoogleCloudTtsAdapter decoded the response with the default (strict) Json
   instance — any field beyond audioContent would throw and turn a
   successful synthesis into a spurious failure. Fixed: ignoreUnknownKeys.

4. The execute-and-check-2xx block was duplicated near-verbatim across all
   10 synthesize/validateKey call sites. Extracted OkHttpClient.executeOrFail()
   in VendorTtsAdapter.kt.

5. GoogleCloudTtsAdapterTest/OpenAiAdapterTest were the only two adapter test
   files missing a "fails closed on missing credential field" case (present
   in the other three) — added, plus regression tests pinning fixes 1-3.

./gradlew :core:cloudtts:testPlayDebugUnitTest — BUILD SUCCESSFUL, 54 tests
(up from 49), all passing.
@libravault-xyz

Copy link
Copy Markdown
Collaborator Author

Ran an independent review pass (code-review skill, high effort) — found and fixed 3 real bugs: (1) ElevenLabs' path-building could split/alter the URL if voiceId contained a slash — fixed via addPathSegment (singular, percent-encodes as one opaque segment). (2) Azure escaped the SSML text but not the voiceId in the same attribute — inconsistent, fixed to escape both. (3) Google's response decoder was strict and would fail a successful synthesis if the response gained any field beyond audioContent — fixed with ignoreUnknownKeys. Also deduplicated the execute-and-check-2xx logic across all 10 call sites into a shared helper, and closed a test-coverage gap on 2 adapters. 54 tests now, all passing.

@libravault-xyz libravault-xyz added status:needs-review QA passed, awaiting principal-review-agent and removed status:needs-review QA passed, awaiting principal-review-agent labels Aug 23, 2026 — with Claude
@github-actions

Copy link
Copy Markdown
Contributor

📱 iOS Build Status: PASSED

⏭️ iOS Simulator Build & Unit Tests - skipped
✅ Android Core Modules - success

iOS UI tests run in a separate, informational job and are not reflected above — check "iOS UI Tests (informational)" for those.

View run details

@github-actions

Copy link
Copy Markdown
Contributor

Principal review — verdict: human-merge

Risk classification

risk:high is correct and still current after the latest push (af98960). gradle/libs.versions.toml is changed in this diff (new okhttp version entry) and that path is an explicit sensitive_paths glob in .github/agent-policy.yml ("Dependency + toolchain pinning"). Re-checked the diff manually rather than trusting the stale-label risk — the file is still touched as of the current head, so the label doesn't need re-running. That alone forces human-merge regardless of review outcome; there are no CONFIRMED findings on top of it.

What I verified independently (not just read/trusted)

  • CI, live: Unit & Integration Tests (JVM) (run 32639470466) was still in_progress when I started reviewing — waited for it rather than trusting the PR body's local-run claim. It finished BUILD SUCCESSFUL, and the log confirms :core:cloudtts:testPlayDebugUnitTest actually executed (not skipped/cached-stale) as part of that green run. Build Android App and iOS App Build & Test also passed on this head SHA.
  • F-Droid isolation claim: ran both ./gradlew :core:cloudtts:dependencies --configuration fdroidDebugRuntimeClasspath (no okhttp — confirmed) and --configuration playDebugRuntimeClasspath (okhttp:5.5.0 present — confirmed) myself. Matches the PR description exactly.
  • Networking sign-off: .github/agent-policy.yml's spirit (no new networking without prior human sign-off) is satisfied — issue Premium Cloud TTS Voices — Android implementation (BYOK, 5 presets) #451 has an explicit "Human authorization to proceed (security-sensitive gate acknowledged)" comment from libravault-xyz (2026-08-23T08:17:27Z) covering this exact five-vendor-HTTP-adapter scope, posted before feat(android): core:cloudtts foundation — gate, secure key storage (#451) #462/feat(android): core:cloudtts vendor adapters — 5 vendors, real API shapes verified (#451) #465 were opened.
  • Issue Verify AwsSigV4Signer against a real AWS request before Amazon Polly cloud-voice support ships to users #466 exists and matches: the AWS SigV4 known-answer-test gap called out in the PR/commit body is genuinely filed and open, with an accurate description of the residual risk (structural tests only, no verified test vector).
  • Re-read the full diff, not the review-round summary — the fixes described in the second commit (af98960) are actually present: ElevenLabsAdapter uses addPathSegment (singular) for voiceId; AzureSpeechAdapter XML-escapes voiceId and locale, not just text; GoogleCloudTtsAdapter's Json instance has ignoreUnknownKeys = true; the duplicated execute-and-check-2xx logic is centralized in VendorTtsAdapter.executeOrFail(); GoogleCloudTtsAdapterTest/OpenAiAdapterTest both now have a missing-credential-field case.

Findings

No CONFIRMED-severity findings — nothing here rises to the bar that would force an issue filing on top of the risk label.

Two PLAUSIBLE/minor items for a human to weigh, neither blocking:

  1. PR description link typo — the "filed as #466" link in the PR body actually resolves to .../issues/464 (a different, already-merged, unrelated issue about Coil's transitive OkHttp) instead of .../issues/466 (the real AwsSigV4Signer follow-up). The issue itself is correctly filed with the right content — this is just a stale/wrong href in the PR text, worth a one-line edit so anyone clicking through later doesn't land on the wrong issue.
  2. localeFromVoiceId fallback gap (VendorTtsAdapter.kt) — falls back to "en-US" only when the derived locale is the empty string, not when a voiceId has no hyphen at all (e.g. a hypothetical single-word custom voice name would produce languageCode/xml:lang equal to the raw voice name rather than falling back). Every real voice ID from Google's and Azure's actual catalogs is {locale}-{name}-shaped per the PR's own vendor-doc verification, so this likely never fires in practice — flagging as a defensive-gap nit, not a reproducible bug with today's known vendor catalogs.

Process note (not a finding, for visibility)

This PR was opened outside the normal dev-agent → qa-agent pipeline (author isn't libravault-pipeline-bot[bot], no Closes #N in the body) and was routed straight to status:needs-review by the deterministic pr-intake.yml backstop, skipping the qa-agent's acceptance-criteria pass entirely. I treated that as reason to verify more directly myself rather than lean on any upstream QA signal — see the independent verification above (live CI wait, F-Droid classpath re-run, sign-off lookup) rather than taking the PR's own claims at face value. status:blocked is not present on either the PR or #451, so nothing here stops review.

Bottom line

Routing to a human purely for the risk:high sensitive-path label (gradle/libs.versions.toml) — the change itself checks out: real vendor API shapes, the three previously-flagged security bugs (path injection, XML injection, strict-JSON spurious failures) are genuinely fixed with regression tests, CI is actually green (verified live, not assumed), and the F-Droid/networking-authorization claims both check out independently.

@github-actions github-actions Bot added status:needs-human-merge Principal review done, requires human merge decision and removed status:needs-review QA passed, awaiting principal-review-agent labels Aug 23, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Reviewed as part of the human-merge-sweep pass. Code looks solid: vendor API shapes match the cited docs, credentials/keys aren't logged or leaked in error paths, XSS/injection-style concerns (SSML escaping, ElevenLabs path-segment encoding) are explicitly tested, and tests assert real, non-vacuous behavior (dispatch-by-provider, fail-closed on non-2xx/missing-field, fixed-host regression). New OkHttp dependency is properly scoped to the play flavor and covered by the recorded networking sign-off in #449. gradle/libs.versions.toml is a sensitive path, which correctly drove risk:high/status:needs-human-merge here — no other sensitive paths touched.

One small nit for the record: the PR description's link to the AwsSigV4Signer follow-up issue is broken — link text says "#466" but the URL resolves to #464 (a different, already-merged issue about Coil's OkHttp dependency). The real follow-up is #466 ("Verify AwsSigV4Signer against a real AWS request..."), which is still open and correctly filed — just flagging the description typo so nobody chasing that link ends up confused later. Not blocking.

Merging.

@github-actions
github-actions Bot merged commit d3a4c63 into dev Aug 23, 2026
14 checks passed
@github-actions
github-actions Bot deleted the feature/cloudtts-android-vendors branch August 23, 2026 12:47
libravault-xyz added a commit that referenced this pull request Aug 23, 2026
…476)

* feat(ios): core Cloud TTS foundation — Keychain store, consent, pure gate

PR 1 of 4 for iOS's half of Premium Cloud TTS Voices (BYOK), issue #452.
Mirrors Android's core:cloudtts foundation (#462), adapted where iOS's
own conventions genuinely differ rather than ported literally.

New Sources/Features/CloudTTS/:
- CloudProviderId — the PRD's closed 5-vendor list (§3).
- CloudCredentialFields — per-provider required-field sets (Amazon
  Polly's SigV4 needs 3 fields, Azure needs 2, the rest need 1 bearer
  key) — same reasoning as Android's identical Map<String,String>
  credential shape, kept in sync by hand.
- CloudApiKeyStore protocol + KeychainCloudApiKeyStore — one
  kSecClassGenericPassword item per provider, kSecAttrAccessibleWhen
  UnlockedThisDeviceOnly. Deliberately does NOT additionally wrap
  through HardwareKeyWrap/the Secure Enclave the way Android's
  RealCloudApiKeyStore wraps through HardwareKeyWrapFactory before
  writing to DataStore — that extra layer exists on Android because a
  DataStore file has no OS-level encryption-at-rest of its own; the
  Keychain already provides that here, and a BYOK vendor key isn't
  LibraVault's root of trust the way the vault master key is.
- CloudVoicePreferences — consent/selected-provider/selected-voice-id,
  mirrors SupporterStatusPersistence's shape (not bolted onto
  UserPreferencesPersistence, whose existing keys use the opposite
  "true by default" polarity).
- CloudTtsGate — pure function, not a class wrapping live
  StoreKitBillingManager/CloudVoicePreferences: StoreKitBillingManager
  needs a live SKTestSession to test for real (documented Xcode 26.5
  CLI gap), so the actual AND logic lives in a function of two Bools
  instead, letting CloudTtsGateTests cover all four quadrants with no
  StoreKit dependency at all.
- CloudTtsProvider protocol — shared shape for the 5 vendor adapters
  (next PR).

Tests: CloudTtsGateTests (4-quadrant + explicit "subscription alone
never opens the gate" regression guard), CloudVoicePreferencesTests,
CloudCredentialFieldsTests, CloudApiKeyStoreTests (real Keychain
round-trip — guarded with the same errSecMissingEntitlement XCTSkip
pattern SecureEnclaveHardwareKeyWrapTests already uses for this CI
job's CODE_SIGNING_ALLOWED=NO environment), FakeCloudApiKeyStore for
downstream test targets (engine/UI PRs).

No Xcode/macOS available in this environment — verified by careful
manual review against this codebase's existing conventions (matched
HardwareKeyWrap/SecureEnclaveHardwareKeyWrapFactory's Keychain query
style, SupporterStatusPersistence's UserDefaults shape, and the
skipIfKeychainKeyPersistenceUnavailable CI gotcha) rather than a local
build; real verification is this PR's CI run (ios-app-build.yml).

Closes nothing yet — first of 4 iOS PRs for #452.

* feat(ios): Cloud TTS vendor adapters — 5 vendors + AWS SigV4 signer

PR 2 of 4 for iOS's half of Premium Cloud TTS Voices (BYOK), progress
toward #452. Builds on the (as-yet-unmerged) foundation PR (#472).
Direct Swift port of Android's 5 vendor adapters (#465) + AwsSigV4Signer
(#467/#466) — same verified real API shapes, same algorithm, ported
rather than re-researched from scratch so both platforms stay provably
aligned.

New Sources/Features/CloudTTS/Vendors/:
- CloudTtsFixedHosts — the fixed, closed set of hosts (PRD §7); Azure/
  Polly pin the host *pattern* (region-scoped), not a literal.
- VendorTtsAdapter protocol + shared executeOrFail/localeFromVoiceID/
  jsonBody helpers. Deliberately NOT guarded by the isRunningUnderXCTest
  check TTSEngineBridge/PocketTTSEngine/StoreKitBillingManager use —
  that guard exists specifically for audio-hardware activation hangs
  in the CI Simulator, which a plain URLSession HTTP call has no
  dependency on; applying it here would also silently no-op every
  adapter test against MockURLProtocol. The engine PR's AVAudioPlayer-
  based playback is where that guard actually belongs, matching the
  precedent's real scope.
- ElevenLabsAdapter/OpenAIAdapter/GoogleCloudTtsAdapter/AzureSpeechAdapter/
  AmazonPollyAdapter — same per-vendor auth/body/host shapes as their
  Kotlin counterparts (xi-api-key header, bearer token, API-key query
  param + base64 JSON response, region-scoped SSML + Ocp-Apim key,
  SigV4).
- AwsSigV4Signer — direct port of the Kotlin signer, using CryptoKit
  (already a dependency here) instead of javax.crypto. Reuses the SAME
  known-answer test vectors already cross-checked against botocore for
  Android (#466), rather than re-deriving a second independent check —
  if both platforms' signers match the same pinned values, they're
  provably computing the same algorithm.
- RealCloudTtsProvider — dispatches to the right vendor adapter by
  CloudProviderId. No fdroid-equivalent NoOp needed (iOS has one
  distribution channel).

Testing: MockURLProtocol (hand-rolled URLProtocol mock — this repo has
no network-test dependency, matching the "no new deps" constraint) +
per-vendor test suites mirroring the Kotlin MockWebServer tests'
coverage (auth header/body shape, non-2xx fails closed, missing-
credential fails closed, path-traversal/XML-injection regression
guards for the two adapters with caller-controlled path/SSML content),
AwsSigV4SignerTests (structural + the reused known-answer vectors),
CloudTtsFixedHostsRegressionTests, RealCloudTtsProviderTests (dispatch
correctness via which real host each provider's request lands on).

No Xcode/macOS available in this environment — verified by careful
manual review and direct comparison against the already-reviewed,
already-merged Kotlin implementation, not a local build. Real
verification is this PR's own CI run.

Part of #452. Depends on #472 (not yet merged) — this branch merges
that branch's commits in directly so it builds/tests standalone;
retarget to dev once #472 merges.

* fix(cloudtts-ios): ElevenLabs voiceID path segment wasn't actually percent-encoded

Real CI failure, not caught locally (no Xcode available when this was
first written): URL.appendingPathComponent(_:) does NOT percent-encode
"/" in its argument the way Kotlin's addPathSegment (singular) does —
it treats "/" as a literal path separator (that's the whole point of
the method: appendingPathComponent("a/b/c") is the same as three
separate appends). A voiceID containing a slash was therefore NOT
percent-encoded as one opaque segment as the code's own comment
claimed — CI's testSlashInVoiceIDIsPercentEncodedNotSplitIntoExtra
PathSegments failed for real against
api.elevenlabs.io/v1/text-to-speech/abc/../admin, the exact path-
traversal shape that test exists to catch.

Fixed by percent-encoding voiceID myself first (CharacterSet
.urlPathAllowed minus "/", so "/" becomes "%2F") and assigning it via
URLComponents.percentEncodedPath, which stores/uses already-encoded
content as-is rather than re-interpreting it. No other adapter has
this bug: ElevenLabs is the only one that puts voiceID into a URL
path segment — the other four put it in a JSON body or XML-escaped
SSML, neither of which goes through appendingPathComponent.

Verified: this is exactly what the existing regression test already
asserted (abc%2F..%2Fadmin) — no test change needed, only the
production code was wrong.
libravault-xyz added a commit that referenced this pull request Aug 24, 2026
* feat(ios): core Cloud TTS foundation — Keychain store, consent, pure gate

PR 1 of 4 for iOS's half of Premium Cloud TTS Voices (BYOK), issue #452.
Mirrors Android's core:cloudtts foundation (#462), adapted where iOS's
own conventions genuinely differ rather than ported literally.

New Sources/Features/CloudTTS/:
- CloudProviderId — the PRD's closed 5-vendor list (§3).
- CloudCredentialFields — per-provider required-field sets (Amazon
  Polly's SigV4 needs 3 fields, Azure needs 2, the rest need 1 bearer
  key) — same reasoning as Android's identical Map<String,String>
  credential shape, kept in sync by hand.
- CloudApiKeyStore protocol + KeychainCloudApiKeyStore — one
  kSecClassGenericPassword item per provider, kSecAttrAccessibleWhen
  UnlockedThisDeviceOnly. Deliberately does NOT additionally wrap
  through HardwareKeyWrap/the Secure Enclave the way Android's
  RealCloudApiKeyStore wraps through HardwareKeyWrapFactory before
  writing to DataStore — that extra layer exists on Android because a
  DataStore file has no OS-level encryption-at-rest of its own; the
  Keychain already provides that here, and a BYOK vendor key isn't
  LibraVault's root of trust the way the vault master key is.
- CloudVoicePreferences — consent/selected-provider/selected-voice-id,
  mirrors SupporterStatusPersistence's shape (not bolted onto
  UserPreferencesPersistence, whose existing keys use the opposite
  "true by default" polarity).
- CloudTtsGate — pure function, not a class wrapping live
  StoreKitBillingManager/CloudVoicePreferences: StoreKitBillingManager
  needs a live SKTestSession to test for real (documented Xcode 26.5
  CLI gap), so the actual AND logic lives in a function of two Bools
  instead, letting CloudTtsGateTests cover all four quadrants with no
  StoreKit dependency at all.
- CloudTtsProvider protocol — shared shape for the 5 vendor adapters
  (next PR).

Tests: CloudTtsGateTests (4-quadrant + explicit "subscription alone
never opens the gate" regression guard), CloudVoicePreferencesTests,
CloudCredentialFieldsTests, CloudApiKeyStoreTests (real Keychain
round-trip — guarded with the same errSecMissingEntitlement XCTSkip
pattern SecureEnclaveHardwareKeyWrapTests already uses for this CI
job's CODE_SIGNING_ALLOWED=NO environment), FakeCloudApiKeyStore for
downstream test targets (engine/UI PRs).

No Xcode/macOS available in this environment — verified by careful
manual review against this codebase's existing conventions (matched
HardwareKeyWrap/SecureEnclaveHardwareKeyWrapFactory's Keychain query
style, SupporterStatusPersistence's UserDefaults shape, and the
skipIfKeychainKeyPersistenceUnavailable CI gotcha) rather than a local
build; real verification is this PR's CI run (ios-app-build.yml).

Closes nothing yet — first of 4 iOS PRs for #452.

* feat(ios): Cloud TTS vendor adapters — 5 vendors + AWS SigV4 signer

PR 2 of 4 for iOS's half of Premium Cloud TTS Voices (BYOK), progress
toward #452. Builds on the (as-yet-unmerged) foundation PR (#472).
Direct Swift port of Android's 5 vendor adapters (#465) + AwsSigV4Signer
(#467/#466) — same verified real API shapes, same algorithm, ported
rather than re-researched from scratch so both platforms stay provably
aligned.

New Sources/Features/CloudTTS/Vendors/:
- CloudTtsFixedHosts — the fixed, closed set of hosts (PRD §7); Azure/
  Polly pin the host *pattern* (region-scoped), not a literal.
- VendorTtsAdapter protocol + shared executeOrFail/localeFromVoiceID/
  jsonBody helpers. Deliberately NOT guarded by the isRunningUnderXCTest
  check TTSEngineBridge/PocketTTSEngine/StoreKitBillingManager use —
  that guard exists specifically for audio-hardware activation hangs
  in the CI Simulator, which a plain URLSession HTTP call has no
  dependency on; applying it here would also silently no-op every
  adapter test against MockURLProtocol. The engine PR's AVAudioPlayer-
  based playback is where that guard actually belongs, matching the
  precedent's real scope.
- ElevenLabsAdapter/OpenAIAdapter/GoogleCloudTtsAdapter/AzureSpeechAdapter/
  AmazonPollyAdapter — same per-vendor auth/body/host shapes as their
  Kotlin counterparts (xi-api-key header, bearer token, API-key query
  param + base64 JSON response, region-scoped SSML + Ocp-Apim key,
  SigV4).
- AwsSigV4Signer — direct port of the Kotlin signer, using CryptoKit
  (already a dependency here) instead of javax.crypto. Reuses the SAME
  known-answer test vectors already cross-checked against botocore for
  Android (#466), rather than re-deriving a second independent check —
  if both platforms' signers match the same pinned values, they're
  provably computing the same algorithm.
- RealCloudTtsProvider — dispatches to the right vendor adapter by
  CloudProviderId. No fdroid-equivalent NoOp needed (iOS has one
  distribution channel).

Testing: MockURLProtocol (hand-rolled URLProtocol mock — this repo has
no network-test dependency, matching the "no new deps" constraint) +
per-vendor test suites mirroring the Kotlin MockWebServer tests'
coverage (auth header/body shape, non-2xx fails closed, missing-
credential fails closed, path-traversal/XML-injection regression
guards for the two adapters with caller-controlled path/SSML content),
AwsSigV4SignerTests (structural + the reused known-answer vectors),
CloudTtsFixedHostsRegressionTests, RealCloudTtsProviderTests (dispatch
correctness via which real host each provider's request lands on).

No Xcode/macOS available in this environment — verified by careful
manual review and direct comparison against the already-reviewed,
already-merged Kotlin implementation, not a local build. Real
verification is this PR's own CI run.

Part of #452. Depends on #472 (not yet merged) — this branch merges
that branch's commits in directly so it builds/tests standalone;
retarget to dev once #472 merges.

* feat(ios): Cloud TTS engine wiring — makes Cloud TTS reachable

PR 3 of 4 for iOS's half of Premium Cloud TTS Voices (BYOK), progress
toward #452. Builds on the (as-yet-unmerged) vendors PR (#476). First
PR where CloudTtsEngine is actually reachable via TTSEngineType.cloud
— mirrors Android's engine-wiring PR (#468).

- TTSEngineType gains `.cloud`; LibravaultDomainBridge.switchTTSEngine
  (to:)'s ternary becomes a switch with a new .cloud branch.
- New configureCloudTts(billingManager:) on the bridge singleton — its
  only path to a live StoreKitBillingManager, called once from
  AppState.init before ttsEngineType's own didSet can ever request
  .cloud (ordering documented at both call sites).
- CloudTtsEngine (@mainactor, TTSEngineProtocol): re-checks
  CloudTtsGate on every speak() call, not just once at engine
  selection — subscribed+consent+configured-provider+voice-id all
  required, matching Android's engine. Falls back to the on-device
  engine (TTSEngineBridge) on gate-closed, not-configured, vendor
  failure, or playback failure — never a silent stall.
- Explicitly does NOT fall back on cancellation: catches both
  CancellationError (Task cancellation) AND URLError(.cancelled)
  (URLSession's own cancellation surfacing, a real Foundation nuance
  distinct from CancellationError) and returns without falling back —
  the Swift equivalent of Android's runCatchingCancellable fix.
  Covered by a dedicated regression test using a hangUntilCancelled
  fake provider, mirroring Android's SuspendingCloudTtsProvider/
  awaitCancellation() test.
- isSubscribedProvider is an injected @mainactor closure, not a direct
  StoreKitBillingManager dependency — keeps CloudTtsEngine's own unit
  tests fully StoreKit-free (only a thin wiring test would ever need
  real StoreKit, per the implementation plan's "Known gaps" section).
- CloudPlayback / AVAudioPlayerCloudPlayback: AVAudioPlayer-backed,
  always hints .mp3 (every vendor adapter explicitly requests MP3 —
  no per-format sniffing needed here, unlike VaultAudioPlaybackEngine's
  arbitrary-import case). Reuses that same file's already-proven-
  necessary "always pass an explicit fileTypeHint" fix (omitting it
  silently reports duration 0 instead of throwing — a real CI-caught
  bug there, not re-discovered here). Split into load()/play() the
  same way, so decode failures are testable without touching audio
  hardware. NSLock-guarded continuation resolution: stop() (main
  actor) and the AVAudioPlayerDelegate finish callback (AVAudioPlayer's
  own thread) can race to resolve the same continuation, which is a
  fatal double-resume, not just a logic bug — proactively applying the
  same fix Android's MediaPlayerCloudPlayback needed after review found
  the identical race there.

Testing: CloudTtsEngineTests (gate/config fallback paths, happy path,
vendor/playback failure fallback, the cancellation-doesn't-fall-back
regression test, pause/resume routing, initialize()) with fully
scripted fakes (FakeCloudTtsProvider/FakeCloudPlayback/FakeTTSEngine —
no real network/audio in any test); AVAudioPlayerCloudPlaybackTests
(load() decode-failure cases only, mirroring
VaultAudioPlaybackEngineTests' isRunningUnderXCTest-safe scope —
flagged explicitly: no "successfully decodes real MP3" test, since
hand-writing a valid MP3 fixture wasn't done here, unlike that file's
hand-written WAV).

No Xcode/macOS available in this environment — verified by careful
manual review, matching this codebase's established conventions
(VaultAudioPlaybackEngine's fileTypeHint/isRunningUnderXCTest split,
AppState's @MainActor-default-argument-initialization-order gotcha,
Android's runCatchingCancellable precedent). Real verification is this
PR's own CI run.

Part of #452. Depends on #476.

* fix(cloudtts-ios): ElevenLabs voiceID path segment wasn't actually percent-encoded

Real CI failure, not caught locally (no Xcode available when this was
first written): URL.appendingPathComponent(_:) does NOT percent-encode
"/" in its argument the way Kotlin's addPathSegment (singular) does —
it treats "/" as a literal path separator (that's the whole point of
the method: appendingPathComponent("a/b/c") is the same as three
separate appends). A voiceID containing a slash was therefore NOT
percent-encoded as one opaque segment as the code's own comment
claimed — CI's testSlashInVoiceIDIsPercentEncodedNotSplitIntoExtra
PathSegments failed for real against
api.elevenlabs.io/v1/text-to-speech/abc/../admin, the exact path-
traversal shape that test exists to catch.

Fixed by percent-encoding voiceID myself first (CharacterSet
.urlPathAllowed minus "/", so "/" becomes "%2F") and assigning it via
URLComponents.percentEncodedPath, which stores/uses already-encoded
content as-is rather than re-interpreting it. No other adapter has
this bug: ElevenLabs is the only one that puts voiceID into a URL
path segment — the other four put it in a JSON body or XML-escaped
SSML, neither of which goes through appendingPathComponent.

Verified: this is exactly what the existing regression test already
asserted (abc%2F..%2Fadmin) — no test change needed, only the
production code was wrong.

* fix(ios): resolve Task<Void, Never> type mismatch in CloudTtsEngine.speak()

self?.performSpeak(...) inside the weak-self Task closure inferred
Task<()?, Never> (optional chaining on an async call returning Void
still returns Void?), which doesn't match the declared
activeTask: Task<Void, Never>?. Unwrap self with guard let first so
the closure's return type is plain Void.

Fixes the Swift compile error blocking PR #478's CI (Build & Test iOS
(Simulator)).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

risk:high Touches a sensitive path or exceeds diff-size threshold — always human merge status:needs-human-merge Principal review done, requires human merge decision

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant