Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -755,6 +755,14 @@ Unicorn, in `libmacadi.so` (`app/src/main/cpp/macadi/`, ported from sacca97/os-f
`scripts/locate_mac_coreadi.py` re-derives and checks every constant, reading them from the Java
sources. Both the payload and the library are pinned by SHA-256, and the dispatcher offset
(`0x979A0`) is only valid for that one build.
- **A CoreADI that cannot be downloaded must not fall back to a server quietly.** Since the
2026-10-12 change a server signs in and then every fetch answers 401, so the fallback is a trap.
A failed fetch marks `unavailableReason` with `EmulatedMacAnisette.NO_COREADI_REASON`,
`AnisetteStatus` makes that `NEEDS_COREADI`, and the sign-in screen stops on the Anisette step,
**even when a stored server answers** (that used to skip straight to the account form), offering
Apple's link, **Choose a file** and **Retry**. `MacCoreAdiFetcher.importFrom` takes the iTunes
disk image or the library and checks both against the download's own pins.
`SuppliedCoreAdiFlowTest` fails if the screen skips the offer again.
- **One identity, kept forever** - rule 11, with more at stake. `files/anisette/mac/identity.json`
and `store/` belong together: the library hashes the host UUID into the machine id, Apple binds
the provisioning to the device id, and the Find My token only works alongside Anisette from the
Expand Down
11 changes: 11 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,7 @@ wizard).
| Anisette tests | `app/src/androidTest/java/.../anisette/` | as above, **opt-in** except `ApplesRealLibraryOnThisDeviceTest` | yes, and network |
| UI tests | `AppleLoginFlowTest`, `app/src/androidTest/java/.../ui/` | Espresso, on the managed device | provisioned for you |
| Wiki screenshots | `app/src/androidTest/java/.../ui/WikiScreenshots*Test` | as above, **opt-in** | a windowed emulator |
| CoreADI from the real disk image | `MacCoreAdiRealImageTest` (JVM) | Gradle / JUnit, **opt-in**: set `COREADI_DMG` | no, but the 291 MB image |
| Chaquopy bridge tests | `app/src/test/python/` | pytest | no |
| Desktop exporter tests | `python/test/` | pytest | no |
| Shared export package | `python/opentagviewer_export/tests/` | pytest | no |
Expand Down Expand Up @@ -664,6 +665,16 @@ it works and what it measured.

### The emulated Mac, on the host

**A CoreADI supplied by hand** (the sign-in screen offers this when the download fails) goes
through `MacCoreAdiFetcher.importFrom`. Its JVM tests use miniature fakes; to put Apple's real
image through it against the real pins, download `MacCoreAdiFetcher.DMG_URL` and run:

```bash
COREADI_DMG=/path/to/iTunes12.8.3.dmg ./gradlew :app:testDebugUnitTest --tests '*MacCoreAdiRealImageTest'
```

Passed on 2026-11-21 in 0.3 s (it seeks to the payload instead of reading 291 MB).

```bash
python scripts/locate_mac_coreadi.py --remote --out /tmp/CoreADI.x86_64
cmake -S app/src/test/macadi-host -B build/macadi && cmake --build build/macadi --parallel
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,236 @@
package dev.wander.android.opentagviewer;

import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.action.ViewActions.scrollTo;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.intent.Intents.intended;
import static androidx.test.espresso.intent.Intents.intending;
import static androidx.test.espresso.intent.matcher.IntentMatchers.hasAction;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
import static org.junit.Assert.assertFalse;

import android.app.Activity;
import android.app.Instrumentation.ActivityResult;
import android.content.Intent;
import android.net.Uri;
import android.os.SystemClock;

import androidx.appcompat.app.AppCompatDelegate;
import androidx.test.core.app.ActivityScenario;
import androidx.test.espresso.intent.Intents;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.filters.LargeTest;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicInteger;

import dev.wander.android.opentagviewer.anisette.EmulatedMacAnisette;
import dev.wander.android.opentagviewer.anisette.FakeAnisetteSource;
import dev.wander.android.opentagviewer.db.datastore.UserAuthDataStore;
import dev.wander.android.opentagviewer.db.datastore.UserSettingsDataStore;
import dev.wander.android.opentagviewer.db.repo.UserAuthRepository;
import dev.wander.android.opentagviewer.db.repo.UserSettingsRepository;
import dev.wander.android.opentagviewer.db.repo.model.UserSettings;
import dev.wander.android.opentagviewer.python.AppDependencies;
import dev.wander.android.opentagviewer.python.FakeAppleAuthService;
import dev.wander.android.opentagviewer.service.web.FakeAnisetteServerTester;
import dev.wander.android.opentagviewer.util.android.AppCryptographyUtil;

/**
* Signing in on a phone that could not download CoreADI.
*
* <p>The trap this guards against: a working server signs in, and then every location fetch
* answers 401. So the screen has to stop on the Anisette step and offer the file, even when a
* stored server answers, which used to send it straight to the account form.
*
* <p>A file that passes cannot be driven here: only Apple's real disk image matches the pins.
* {@code MacCoreAdiFetcherTest} covers that on the JVM. What this covers is the screen.
*/
@LargeTest
@RunWith(AndroidJUnit4.class)
public class SuppliedCoreAdiFlowTest {

private static final String SERVER = "https://ani.example.com";

private ActivityScenario<AppleLoginActivity> scenario;
private DeviceStateGuard deviceState;
private int nightModeBefore;
private final AtomicInteger sourcesMade = new AtomicInteger();

private static FakeAnisetteSource noCoreAdi() {
return FakeAnisetteSource.unavailable(EmulatedMacAnisette.NO_COREADI_REASON
+ ": could not download the library from Apple: UnknownHostException");
}

@Before
public void aPhoneThatCannotDownloadCoreAdi() {
this.deviceState = DeviceStateGuard.capture(getInstrumentation().getTargetContext());
this.nightModeBefore = AppCompatDelegate.getDefaultNightMode();

signEverybodyOut();
// A stored server that answers: the case that used to skip straight past the offer.
new UserSettingsRepository(
UserSettingsDataStore.getInstance(getInstrumentation().getTargetContext()))
.storeUserSettings(UserSettings.builder().anisetteServerUrl(SERVER).build())
.blockingAwait();

AppDependencies.replaceAuthService(FakeAppleAuthService.signsInImmediately());
AppDependencies.replaceServerTester(FakeAnisetteServerTester.thatIsUp());
AppDependencies.replaceAnisette(settings -> {
this.sourcesMade.incrementAndGet();
return noCoreAdi();
});

Intents.init();
}

@After
public void putTheRealOnesBack() {
if (this.scenario != null) {
this.scenario.close();
}
Intents.release();
AppDependencies.reset();
getInstrumentation().runOnMainSync(
() -> AppCompatDelegate.setDefaultNightMode(this.nightModeBefore));

getInstrumentation().waitForIdleSync();
signEverybodyOut();
this.deviceState.restore();
}

private void launch() {
this.scenario = ActivityScenario.launch(AppleLoginActivity.class);
TestPace.afterAStep();
}

private void shot(final String name) {
final AppleLoginActivity[] activity = {null};
this.scenario.onActivity(a -> activity[0] = a);
Shot.of(activity[0], name);
}

@Test
public void aStoredServerThatAnswersDoesNotSkipTheOffer() {
launch();

Eventually.check(() -> onView(withId(R.id.anisetteCoreAdiContainer))
.perform(scrollTo()).check(matches(isDisplayed())));
onView(withId(R.id.email_or_phone_input_field)).check(matches(not(isDisplayed())));
onView(withId(R.id.anisetteLoginFallbackReason))
.check(matches(withText(R.string.anisette_login_needs_coreadi)));

this.shot("coreadi_1_offer_light");
}

@Test
public void theOfferInDarkMode() {
getInstrumentation().runOnMainSync(
() -> AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES));
launch();

Eventually.check(() -> onView(withId(R.id.anisetteCoreAdiContainer))
.perform(scrollTo()).check(matches(isDisplayed())));

this.shot("coreadi_2_offer_dark");
}

@Test
public void choosingAFileAsksTheSystemForOne() {
stubThePickerWith(null);
launch();

Eventually.check(() -> onView(withId(R.id.anisetteChooseCoreAdiButton))
.perform(scrollTo(), click()));

Eventually.check(() -> intended(hasAction(Intent.ACTION_OPEN_DOCUMENT)));
}

@Test
public void aFileThatIsNotCoreAdiIsRefusedWithTheReason() throws Exception {
stubThePickerWith(aHolidayPhoto());
launch();

Eventually.check(() -> onView(withId(R.id.anisetteChooseCoreAdiButton))
.perform(scrollTo(), click()));

Eventually.check(() -> onView(withId(R.id.anisetteCoreAdiRejection))
.perform(scrollTo())
.check(matches(allOf(isDisplayed(), withText(containsString("too small"))))));
assertFalse("nothing may be stored from a refused file",
EmulatedMacAnisette.libraryFile(getInstrumentation().getTargetContext()).exists());

this.shot("coreadi_3_refused");
}

/** Retry after the file arrived (or the network came back) moves on to the account form. */
@Test
public void retryingOnceItWorksMovesOn() {
launch();
Eventually.check(() -> onView(withId(R.id.anisetteRetryCoreAdiButton))
.perform(scrollTo()).check(matches(isDisplayed())));

AppDependencies.replaceAnisette(settings -> FakeAnisetteSource.ready());
Eventually.perform("retry",
() -> isShown(R.id.login_maininfo_container),
() -> onView(withId(R.id.anisetteRetryCoreAdiButton)).perform(scrollTo(), click()));

Eventually.check(() -> onView(withId(R.id.email_or_phone_input_field))
.perform(scrollTo()).check(matches(isDisplayed())));
}

private boolean isShown(final int id) {
final boolean[] shown = {false};
this.scenario.onActivity(a -> shown[0] = a.findViewById(id).isShown());
return shown[0];
}

private void stubThePickerWith(final Uri chosen) {
final Intent data = chosen == null ? null : new Intent().setData(chosen);
intending(hasAction(Intent.ACTION_OPEN_DOCUMENT)).respondWith(new ActivityResult(
chosen == null ? Activity.RESULT_CANCELED : Activity.RESULT_OK, data));
}

private static Uri aHolidayPhoto() throws Exception {
final File photo = new File(getInstrumentation().getTargetContext().getCacheDir(),
"holiday.jpg");
try (FileOutputStream out = new FileOutputStream(photo)) {
out.write("not a disk image".getBytes(StandardCharsets.US_ASCII));
}
return Uri.fromFile(photo);
}

private static void signEverybodyOut() {
final UserAuthRepository auth = new UserAuthRepository(
UserAuthDataStore.getInstance(getInstrumentation().getTargetContext()),
new AppCryptographyUtil());

int consecutivelyEmpty = 0;
for (int attempt = 0; attempt < 40 && consecutivelyEmpty < 3; attempt++) {
if (auth.getUserAuth().blockingFirst().isEmpty()) {
consecutivelyEmpty++;
} else {
consecutivelyEmpty = 0;
auth.clearUser().blockingAwait();
}
SystemClock.sleep(50);
}
if (consecutivelyEmpty < 3) {
throw new IllegalStateException("a stored session kept coming back");
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,40 @@ public void aLibraryThatCrashesThisPhoneIsItsOwnState() {
assertFalse("a copy of the same library crashes the same way", status.needsOwnApk());
}

/** The emulated Mac crashing is a crash too. Its sentence differs, and it used to read as UNAVAILABLE. */
@Test
public void theEmulatedMacCrashingIsACrashToo() {
final AnisetteStatus status = AnisetteStatus.of(
FakeAnisetteSource.unavailable(EmulatedMacAnisette.CRASHES_HERE_REASON));

assertEquals(AnisetteStatus.State.CRASHES_HERE, status.state());
}

/**
* No CoreADI is its own state, offering the file and never the APK. A server would sign in and
* then fail every fetch, so it is not an answer here.
*/
@Test
public void noCoreAdiAsksForCoreAdiAndNotTheApk() {
final AnisetteStatus status = AnisetteStatus.of(FakeAnisetteSource.unavailable(
EmulatedMacAnisette.NO_COREADI_REASON
+ ": could not download the library from Apple: UnknownHostException"));

assertEquals(AnisetteStatus.State.NEEDS_COREADI, status.state());
assertTrue(status.failed());
assertTrue(status.needsCoreAdi());
assertFalse(status.needsOwnApk());
}

/** An ordinary network failure elsewhere does not ask for CoreADI. */
@Test
public void anOrdinaryFailureDoesNotAskForCoreAdi() {
final AnisetteStatus status = AnisetteStatus.of(
FakeAnisetteSource.unavailable("Unable to resolve host gsa.apple.com"));

assertFalse(status.needsCoreAdi());
}

/** No source at all is "nothing has happened yet", not "something went wrong". */
@Test
public void noSourceIsPendingRatherThanBroken() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@
import dev.wander.android.opentagviewer.R;
import dev.wander.android.opentagviewer.anisette.AnisetteStatus;
import dev.wander.android.opentagviewer.anisette.AppleLibraryCrashReport;
import dev.wander.android.opentagviewer.anisette.EmulatedMacAnisette;
import dev.wander.android.opentagviewer.anisette.LocalAnisette;
import dev.wander.android.opentagviewer.anisette.MacCoreAdiFetcher;
import dev.wander.android.opentagviewer.anisette.FakeAnisetteSource;

/**
Expand Down Expand Up @@ -186,6 +188,70 @@ public void anOrdinaryFailureAfterACrashGoesBackToTheGeneralSentence() {
View.GONE, view(R.id.anisetteReportCrashButton).getVisibility());
}

private static AnisetteStatus noCoreAdi() {
return AnisetteStatus.of(FakeAnisetteSource.unavailable(
EmulatedMacAnisette.NO_COREADI_REASON + ": Apple answered HTTP 403"));
}

/**
* Without CoreADI, the file is offered first: the link to Apple's image, choose and retry.
* The server stays reachable, but the sentence says locations will not load through it.
*/
@Test
public void noCoreAdiOffersTheFileAndWarnsAboutTheServer() {
apply(noCoreAdi());

assertEquals(View.VISIBLE, view(R.id.anisetteCoreAdiContainer).getVisibility());
assertEquals(MacCoreAdiFetcher.DMG_URL,
((TextView) view(R.id.anisetteCoreAdiLink)).getText().toString());
assertEquals(this.screen.getContext().getString(R.string.anisette_login_needs_coreadi),
((TextView) view(R.id.anisetteLoginFallbackReason)).getText().toString());
assertEquals(View.VISIBLE, view(R.id.anisetteChooseCoreAdiButton).getVisibility());
assertEquals(View.VISIBLE, view(R.id.anisetteRetryCoreAdiButton).getVisibility());
assertEquals("the server is still a way to sign in",
View.VISIBLE, view(R.id.anisetteRemoteSection).getVisibility());
assertEquals(View.GONE, view(R.id.anisetteReportCrashButton).getVisibility());
assertEquals("nothing was refused yet",
View.GONE, view(R.id.anisetteCoreAdiRejection).getVisibility());
}

/** Any other failure, or recovering, takes the offer away again. */
@Test
public void theFileIsOfferedOnlyWhileItIsMissing() {
apply(noCoreAdi());
apply(AnisetteStatus.of(FakeAnisetteSource.unavailable("Unable to resolve host")));
assertEquals(View.GONE, view(R.id.anisetteCoreAdiContainer).getVisibility());

apply(noCoreAdi());
apply(AnisetteStatus.of(FakeAnisetteSource.ready()));
assertEquals(View.GONE, view(R.id.anisetteCoreAdiContainer).getVisibility());
}

/** Somebody who chose a server is not offered a file for a machine they are not using. */
@Test
public void choosingAServerIsNotAnsweredWithTheFile() {
apply(noCoreAdi(), true);

assertEquals(View.GONE, view(R.id.anisetteCoreAdiContainer).getVisibility());
}

/** A refused file says why, and a fresh attempt clears it. */
@Test
public void aRefusedFileSaysWhyUntilTheNextTry() {
apply(noCoreAdi());
getInstrumentation().runOnMainSync(() -> SharedMainSettingsManager.applyCoreAdiRejection(
this.screen, "the library is not the expected build"));

final TextView rejection = (TextView) view(R.id.anisetteCoreAdiRejection);
assertEquals(View.VISIBLE, rejection.getVisibility());
assertTrue(rejection.getText().toString(),
rejection.getText().toString().contains("not the expected build"));

getInstrumentation().runOnMainSync(
() -> SharedMainSettingsManager.applyCoreAdiRejection(this.screen, null));
assertEquals(View.GONE, rejection.getVisibility());
}

/** The report is only worth sending if it names the phone. */
@Test
public void theReportNamesThePhone() {
Expand Down
Loading
Loading