Anki-Android icon indicating copy to clipboard operation
Anki-Android copied to clipboard

fix: Refactor AnkiServer for future HTTPS support (Issue #15991)

Open mixelas opened this issue 7 months ago • 13 comments

Purpose / Description

This PR prepares the codebase for HTTPS support by refactoring AnkiServer to support SSL/TLS configuration, while maintaining backward compatibility.

Fixes

  • Fixes #15991

Approach

Added Context parameter to AnkiServer constructor to enable SSL setup when needed

  • Created SslUtil as a placeholder for future certificate generation
  • Updated all AnkiServer instantiations to pass context where available
  • Added unit tests for AnkiServer and SslUtil to verify basic functionality
  • Maintained full backward compatibility

How Has This Been Tested?

  • Full gradle build was successful
  • Kotlin compilation was successful
  • Unit tests created for: AnkiServer baseUrl() returning HTTP when context not provided AnkiServer baseUrl() containing localhost address SslUtil placeholder initialization

Tested on:

  • Android Gradle Plugin 9.3.1
  • Kotlin 1.9.x
  • Java 21

Learning (optional, can help others)

While i was working with Android SDK, i noticed that it doesn't include sun.security internal APIs in modern versions. The proper approach for self-signed certificate generation on Android involves either:

  1. Using BouncyCastle library
  2. Using Android's KeyStore and KeyGenParameterSpec APIs

Checklist

Please, go through these checks before submitting the PR.

  • [x] You have a descriptive commit message with a short title (first line, max 50 chars).
  • [x] You have commented your code, particularly in hard-to-understand areas
  • [x] You have performed a self-review of your own code
  • [ ] UI changes: include screenshots of all affected screens (in particular showing any new or changed strings)
  • [ ] UI Changes: You have tested your change using the Google Accessibility Scanner

mixelas avatar Apr 28 '26 19:04 mixelas

This was initially a placeholder as i didn't think that I had to make the complete HTTPS support. That is why it looks bad and AI generated, as I tried to do a simple fix. I will get on with pushing a PR with complete HTTPS support and give it my best.

mixelas avatar Apr 29 '26 17:04 mixelas

@david-allison can you please review again.

mixelas avatar May 02 '26 15:05 mixelas

The emulator tests are broken (and please remove the merge commit and rebase/force push onto main)

https://github.com/ankidroid/Anki-Android/blob/main/CONTRIBUTING.md#:~:text=AnkiDroid%20expects%20use%20of%20git%20rebase%20and%20git%20push%20%2D%2Dforce%20to%20PR%20branches.%20PRs%20with%20merge%20commits%20will%20not%20be%20merged.

david-allison avatar May 03 '26 13:05 david-allison

Heyy... there's a lot of changes here which aren't relevant to the PR. Take a look at this from a reviewer's perspective:

  • https://github.com/ankidroid/Anki-Android/pull/20885/changes

The 'git' window can show you what's relevant, and you can revert the changes which aren't necessary

Screenshot 2026-05-04 at 23 53 50

This design seems complex. Moving reviewerViewModelFactory to a separate file seems unnecessary.

It might be worth explaining the design, I'm sure it can be simplified

david-allison avatar May 04 '26 23:05 david-allison

I addressed the points you raised. I inlined the ViewModel creation into the fragments and kept the cache-dir threading as small as possible. The goal was just to pass the local directory through to the server setup without adding extra architectural layers. Let me know if there is anything else that i need to do.

mixelas avatar May 05 '26 09:05 mixelas

could you rebase or squash the PR so it doesn't have merge commits?

BrayanDSO avatar May 12 '26 01:05 BrayanDSO

Truly, thanks for your time, but I'm going to close this. Let's revisit it when:

  • HTTPS works end-to-end
  • The PR is tested, and there are test instructions

This is security-related and needs to clear a high bar, I'm going to spend a LOT of time verifying the implementation, but I don't feel we're there yet.

As far as I understand it, leaving the certificate generation as a TODO means that the server won't work.

            val keyPair = generateKeyPair()
            // TODO: Generate and sign X.509 certificate
            // Temporary approach: Store raw key pair until certificate generation is implemented
            // This allows HTTPS connections but without proper certificate validation
            keyStore.setKeyEntry(
                KEYSTORE_ALIAS,
                keyPair.private,
                KEY_PASSWORD.toCharArray(),
                arrayOfNulls(0), // Empty certificate chain for now
            )

On using cacheDir: I don't have the timing numbers to hand, but I suspect they're significant enough that using a file is the correct approach. If this is the case, the OS shouldn't wipe it. I'd need to think this through to confirm, but I don't think a per-profile AnkiServer would be useful, since it's process-bounded.

david-allison avatar May 12 '26 11:05 david-allison

I’m sorry for the confusion. I genuinely didn’t think the expected outcome was full end-to-end HTTPS support yet. I understood this as scaffolding for the feature, which is why I left the certificate generation as a TODO. I assumed that part would need someone with more authority or security context than me, since it’s a more sensitive piece of the implementation. If you decide to reopen it later, I’d be happy to keep working on it once I can complete the certificate generation and proper end-to-end testing.

mixelas avatar May 12 '26 13:05 mixelas

SORRY! That isn't what I understood from - Fixes #NNNN

Fixes == close the issue when the PR is merged

and the implementation wasn't behind a flag, so [AFAIK] it would have gone live as a non-working server

david-allison avatar May 12 '26 17:05 david-allison

You're absolutely right. I didn't intend to ship a non-working server to production. If you decide to reopen the PR, I can add a debug flag now and fully implement the HTTPS setup along with proper tests.

mixelas avatar May 13 '26 08:05 mixelas

If you're happy, I'm happy. I wouldn't put it into "developer options" until it's working

The PR still needs work, from recollection, using "localhost" as a password, rather than an inlined empty string/byte aware with a comment that it's an app-accessible only key store would be acceptable

david-allison avatar May 14 '26 08:05 david-allison

@david-allison I implemented HTTPS using self-signed certificates from BouncyCastle with CA + leaf chain architecture. Does this approach work for you?

mixelas avatar May 14 '26 17:05 mixelas

Snapshot diff report vs main. Open screenshot-diff for diffs.

  • PreferencesScreenshotTest: 1 change
All 1 changed screenshots

PreferencesScreenshotTest

  • ReviewerOptionsFragment_compare.png

github-actions[bot] avatar Jun 25 '26 17:06 github-actions[bot]

38814554: Old APK size 40236643: New APK size

github-actions[bot] avatar Jun 26 '26 04:06 github-actions[bot]

38814554: Old APK size 40236643: New APK size

Yowch... not feasible.

david-allison avatar Jun 26 '26 05:06 david-allison

Thanks for the review, I originally picked BouncyCastle because it made it straightforward to generate a CA plus leaf chain and rotate cert material at runtime. After your feedback, I revisited this and switched to Android Keystore based key generation instead. You are correct that localhost is a potentially trustworthy origin for secure context semantics. The practical issue on Android here is transport policy and WebView behavior around cleartext restrictions. The server now enables TLS when available and otherwise degrades safely.

mixelas avatar Jun 26 '26 16:06 mixelas

I feel this should be un-drafted after the following is handled, and the PR description/commit messages are fixed:

https://github.com/ankidroid/Anki-Android/pull/20885#issuecomment-4430252310

david-allison avatar Jun 28 '26 21:06 david-allison

Thanks for the review, I have now completed the remaining items needed before undrafting. HTTPS is wired end-to-end for the embedded local server path, and the WebView handling is restricted to loopback-only hosts so this does not broaden trust for external hosts. I also added and ran dedicated tests for the SSL handling behavior so this is not just a code-path change without verification. Specifically, the new test coverage checks that SSL errors are only proceeded for localhost and loopback addresses and are not proceeded for non-loopback hosts, and I ran the targeted unit test task locally for this new coverage. For verification, the intended manual check is to open the reviewer/preview flow and confirm locally served content loads over HTTPS while external behavior remains unchanged.

mixelas avatar Jun 30 '26 11:06 mixelas