mattermost-mobile-upstream/app/store/ephemeral_store.test.ts
Felipe Martin 9ccfa0ebe9
Some checks are pending
ci / lint-typecheck (push) Waiting to run
ci / detox-lint-typecheck (push) Waiting to run
ci / test (push) Waiting to run
[MM-70605][MM-70607] Scope pre-auth secret storage per server (#10149)
* [MM-70605][MM-70607] Scope pre-auth secret storage per server

The pre-auth secret was written with react-native-keychain's generic-password
API using the `server` option, which those calls do not read. Every server
therefore resolved to one shared entry, and a falsy secret argument deleted it,
so ordinary operations such as building a client, refreshing the token header or
removing another server discarded the stored value.

Key the entry per server instead. On Android the alias namespace is shared with
internet credentials, so the service is prefixed to keep it away from the
session token; iOS uses the bare server URL, which is what the native reader in
Gekidou already queries. The account value is renamed to `preauth_secret` on
both sides. Writing the token no longer touches the secret: removal is explicit,
via removePreauthSecret.

A one-time migration adopts the previously shared entry when a single server
makes ownership unambiguous, and discards it otherwise. It only deletes the old
entry once the new one is confirmed stored, and defers when no server is active.

Also forward the secret through the login screen to SSO, and fix loginOptions to
count only enabled providers so the single-provider redirect works. Relands the
`.enabled` filter from #9585 by @pltnm239.

Edit Server now updates the live client's headers rather than invalidating the
session, and validates with the candidate secret so a value the server rejects
cannot be saved.

* [MM-70605] Harden preauth secret flows and fix Edit Server Detox on iOS

Address review feedback around migration markers, credential errors, and
keeping re-login secrets out of nav params. Focus the empty Authentication
secret field via Display Name return so iOS Detox can type into it.

Co-authored-by: Cursor <cursoragent@cursor.com>

* [MM-70605] Fix lines-around-comment in Edit Server Detox helper

Co-authored-by: Cursor <cursoragent@cursor.com>

* [MM-70605] Roll back preauth keychain when Edit Server client sync fails

After the secret is stored, header apply or createClient failures left the
new value in secure storage while UI state still held the old baseline.
Restore the previous secret (and live header) before surfacing the error.

Co-authored-by: Cursor <cursoragent@cursor.com>

* [MM-70605] Preserve exact preauth secret on Edit Server rollback

Avoid trimming during keychain restore so boundary whitespace from the
previously stored value is not altered.

Co-authored-by: Cursor <cursoragent@cursor.com>

* [MM-70605] Harden preauth migration ownership and secret handoff

Adopt the legacy secret only when a single server exists in the app DB,
keep add-server candidates in EphemeralStore instead of nav params, and
resync the live client to stored credentials when keychain rollback fails.

Co-authored-by: Cursor <cursoragent@cursor.com>

* [MM-70605] Discard the legacy preauth secret when no server can own it

* [MM-70605] Shorten the preauth migration docblock

* [MM-70605] Skip the Authorization header when there is no bearer token

* [MM-70605] Surface preauth secret rejections with a specific error message

* [MM-70605] Mock clearPendingPreauthSecret in session action tests

* [MM-70605] Remove the unreachable catch from restorePreviousPreauthSecret

setPreauthSecret and removePreauthSecret never reject, and the returned promise was not awaited, so the catch could not run.

* [MM-70605] Use network-client fix for the iOS addHeaders crash

Temporary pin to mattermost/react-native-network-client#175 to check CI. Replace with the released version before merge.

* [MM-70605] Bump react-native-network-client to 1.11.5

1.11.5 gives each recreated iOS session its own delegate in addHeaders, which fixes the SIGTRAP on pre-auth secret changes.

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-23 12:02:41 +02:00

271 lines
12 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {CLASSIFICATION_BANNER_CACHE_TTL} from '@constants/classification';
import {toMilliseconds} from '@utils/datetime';
import EphemeralStore from './ephemeral_store';
describe('EphemeralStore', () => {
afterEach(() => {
jest.resetModules();
});
it('theme observable', () => {
const {Preferences} = require('@constants');
// Initial value should be the default theme
const initialTheme = EphemeralStore.getTheme();
expect(initialTheme).toBeDefined();
// Set theme
const theme = Preferences.THEMES.denim;
EphemeralStore.setTheme(theme);
expect(EphemeralStore.getTheme()).toBe(theme);
// Observable should emit values
const mockCallback = jest.fn();
const subscription = EphemeralStore.observeTheme().subscribe(mockCallback);
// Should immediately get current value
expect(mockCallback).toHaveBeenCalledWith(theme);
// Should get new values when theme changes
const newTheme = Preferences.THEMES.sapphire;
EphemeralStore.setTheme(newTheme);
expect(mockCallback).toHaveBeenCalledWith(newTheme);
expect(mockCallback).toHaveBeenCalledTimes(2);
// Clean up
subscription.unsubscribe();
// After unsubscribe, callback should not be called
EphemeralStore.setTheme(theme);
expect(mockCallback).toHaveBeenCalledTimes(2);
});
it('playbooks sync', () => {
// Expect false if not yet set
expect(EphemeralStore.getChannelPlaybooksSynced('server-url', 'channel-id')).toBe(false);
// Expect true if set
EphemeralStore.setChannelPlaybooksSynced('server-url', 'channel-id');
expect(EphemeralStore.getChannelPlaybooksSynced('server-url', 'channel-id')).toBe(true);
// Same id, different server
expect(EphemeralStore.getChannelPlaybooksSynced('server-url-2', 'channel-id')).toBe(false);
// Set for different server
EphemeralStore.setChannelPlaybooksSynced('server-url-2', 'channel-id');
expect(EphemeralStore.getChannelPlaybooksSynced('server-url-2', 'channel-id')).toBe(true);
// Expect false if cleared
EphemeralStore.clearChannelPlaybooksSynced('server-url');
expect(EphemeralStore.getChannelPlaybooksSynced('server-url', 'channel-id')).toBe(false);
expect(EphemeralStore.getChannelPlaybooksSynced('server-url-2', 'channel-id')).toBe(true); // The other server is not cleared
// Expect false if unset
EphemeralStore.setChannelPlaybooksSynced('server-url', 'channel-id');
EphemeralStore.setChannelPlaybooksSynced('server-url', 'channel-id-2');
EphemeralStore.setChannelPlaybooksSynced('server-url', 'channel-id-3');
EphemeralStore.unsetChannelPlaybooksSynced('server-url', 'channel-id');
expect(EphemeralStore.getChannelPlaybooksSynced('server-url', 'channel-id')).toBe(false);
expect(EphemeralStore.getChannelPlaybooksSynced('server-url', 'channel-id-2')).toBe(true);
expect(EphemeralStore.getChannelPlaybooksSynced('server-url', 'channel-id-3')).toBe(true);
// Expect false if cleared
EphemeralStore.clearChannelPlaybooksSynced('server-url');
expect(EphemeralStore.getChannelPlaybooksSynced('server-url', 'channel-id')).toBe(false);
expect(EphemeralStore.getChannelPlaybooksSynced('server-url', 'channel-id-2')).toBe(false);
expect(EphemeralStore.getChannelPlaybooksSynced('server-url', 'channel-id-3')).toBe(false);
});
describe('viewable items', () => {
afterEach(() => {
EphemeralStore.clearViewableItems();
});
it('should report items reported by any mounted list', () => {
EphemeralStore.setViewableItems('Channel', {'Channel-post-1': true});
EphemeralStore.setViewableItems('Thread', {'Thread-post-2': true});
expect(EphemeralStore.isItemInViewPort('Channel-post-1')).toBe(true);
expect(EphemeralStore.isItemInViewPort('Thread-post-2')).toBe(true);
});
it('should replace only the entries of the list that reported them', () => {
EphemeralStore.setViewableItems('Channel', {'Channel-post-1': true});
EphemeralStore.setViewableItems('Thread', {'Thread-post-2': true});
EphemeralStore.setViewableItems('Thread', {'Thread-post-3': true});
expect(EphemeralStore.isItemInViewPort('Channel-post-1')).toBe(true);
expect(EphemeralStore.isItemInViewPort('Thread-post-2')).toBe(false);
expect(EphemeralStore.isItemInViewPort('Thread-post-3')).toBe(true);
});
it('should drop every list when cleared', () => {
EphemeralStore.setViewableItems('Channel', {'Channel-post-1': true});
EphemeralStore.setViewableItems('Thread', {'Thread-post-2': true});
EphemeralStore.clearViewableItems();
expect(EphemeralStore.isItemInViewPort('Channel-post-1')).toBe(false);
expect(EphemeralStore.isItemInViewPort('Thread-post-2')).toBe(false);
});
});
describe('classification banner cache', () => {
const serverUrl = 'classification-server';
const otherServerUrl = 'classification-server-2';
afterEach(() => {
EphemeralStore.clearClassificationCache(serverUrl);
EphemeralStore.clearClassificationCache(otherServerUrl);
jest.useRealTimers();
});
it('should need a fetch until marked, then respect the TTL', () => {
jest.useFakeTimers({doNotFake: ['nextTick']});
expect(EphemeralStore.shouldFetchClassificationBanner(serverUrl)).toBe(true);
EphemeralStore.setClassificationBannerFetched(serverUrl);
expect(EphemeralStore.shouldFetchClassificationBanner(serverUrl)).toBe(false);
jest.advanceTimersByTime(CLASSIFICATION_BANNER_CACHE_TTL);
expect(EphemeralStore.shouldFetchClassificationBanner(serverUrl)).toBe(true);
});
it('should track freshness independently per server', () => {
EphemeralStore.setClassificationBannerFetched(serverUrl);
expect(EphemeralStore.shouldFetchClassificationBanner(serverUrl)).toBe(false);
expect(EphemeralStore.shouldFetchClassificationBanner(otherServerUrl)).toBe(true);
});
it('should guard field sync attempts scoped per server and option', () => {
expect(EphemeralStore.getClassificationFieldSyncAttempted(serverUrl, 'opt-1')).toBe(false);
EphemeralStore.setClassificationFieldSyncAttempted(serverUrl, 'opt-1');
expect(EphemeralStore.getClassificationFieldSyncAttempted(serverUrl, 'opt-1')).toBe(true);
expect(EphemeralStore.getClassificationFieldSyncAttempted(serverUrl, 'opt-2')).toBe(false);
expect(EphemeralStore.getClassificationFieldSyncAttempted(otherServerUrl, 'opt-1')).toBe(false);
});
it('should reset both freshness and the field sync guard on clearClassificationCache', () => {
EphemeralStore.setClassificationBannerFetched(serverUrl);
EphemeralStore.setClassificationFieldSyncAttempted(serverUrl, 'opt-1');
EphemeralStore.clearClassificationCache(serverUrl);
expect(EphemeralStore.shouldFetchClassificationBanner(serverUrl)).toBe(true);
expect(EphemeralStore.getClassificationFieldSyncAttempted(serverUrl, 'opt-1')).toBe(false);
});
});
describe('pendingPreauthSecret', () => {
const serverUrl = 'https://example.com';
afterEach(() => {
EphemeralStore.clearPendingPreauthSecret(serverUrl);
});
it('should store and return a pending add-server secret', () => {
expect(EphemeralStore.getPendingPreauthSecret(serverUrl)).toBeUndefined();
EphemeralStore.setPendingPreauthSecret(serverUrl, 'candidate-secret');
expect(EphemeralStore.getPendingPreauthSecret(serverUrl)).toBe('candidate-secret');
});
it('should clear a pending secret for a server', () => {
EphemeralStore.setPendingPreauthSecret(serverUrl, 'candidate-secret');
EphemeralStore.clearPendingPreauthSecret(serverUrl);
expect(EphemeralStore.getPendingPreauthSecret(serverUrl)).toBeUndefined();
});
});
describe('recently unsaved saved posts', () => {
const serverUrl = 'server-url';
const otherServerUrl = 'server-url-2';
const postId = 'post-id';
beforeEach(() => {
jest.useFakeTimers({doNotFake: ['nextTick']});
});
afterEach(() => {
// Clear any pending timers so they don't leak across tests
EphemeralStore.clearRecentlyUnsavedSavedPost(serverUrl, postId);
EphemeralStore.clearRecentlyUnsavedSavedPost(otherServerUrl, postId);
jest.useRealTimers();
});
it('marks a post as recently unsaved and isolates by server', () => {
expect(EphemeralStore.isRecentlyUnsavedSavedPost(serverUrl, postId)).toBe(false);
EphemeralStore.addRecentlyUnsavedSavedPost(serverUrl, postId);
expect(EphemeralStore.isRecentlyUnsavedSavedPost(serverUrl, postId)).toBe(true);
// A different server with the same postId is unaffected
expect(EphemeralStore.isRecentlyUnsavedSavedPost(otherServerUrl, postId)).toBe(false);
});
it('clears the flag automatically after the TTL', () => {
EphemeralStore.addRecentlyUnsavedSavedPost(serverUrl, postId);
expect(EphemeralStore.isRecentlyUnsavedSavedPost(serverUrl, postId)).toBe(true);
jest.advanceTimersByTime(toMilliseconds({minutes: 2}));
expect(EphemeralStore.isRecentlyUnsavedSavedPost(serverUrl, postId)).toBe(false);
});
it('clearRecentlyUnsavedSavedPost cancels the pending TTL immediately', () => {
EphemeralStore.addRecentlyUnsavedSavedPost(serverUrl, postId);
expect(EphemeralStore.isRecentlyUnsavedSavedPost(serverUrl, postId)).toBe(true);
EphemeralStore.clearRecentlyUnsavedSavedPost(serverUrl, postId);
expect(EphemeralStore.isRecentlyUnsavedSavedPost(serverUrl, postId)).toBe(false);
});
it('observeRecentlyUnsavedSavedPost emits the unsaved state changes', () => {
const mockCallback = jest.fn();
const subscription = EphemeralStore.observeRecentlyUnsavedSavedPost(serverUrl, postId).subscribe(mockCallback);
// Immediately gets the current (false) value
expect(mockCallback).toHaveBeenCalledWith(false);
EphemeralStore.addRecentlyUnsavedSavedPost(serverUrl, postId);
expect(mockCallback).toHaveBeenCalledWith(true);
// After the TTL expires it should emit false again
jest.advanceTimersByTime(toMilliseconds({minutes: 2}));
expect(mockCallback).toHaveBeenLastCalledWith(false);
subscription.unsubscribe();
});
it('observeRecentlyUnsavedSavedPosts emits the set of unsaved posts', () => {
const mockCallback = jest.fn();
const subscription = EphemeralStore.observeRecentlyUnsavedSavedPosts(serverUrl).subscribe(mockCallback);
EphemeralStore.addRecentlyUnsavedSavedPost(serverUrl, postId);
EphemeralStore.addRecentlyUnsavedSavedPost(serverUrl, 'post-id-2');
const calls = mockCallback.mock.calls;
const lastSet = calls[calls.length - 1][0] as Set<string>;
expect(lastSet.size).toBe(2);
expect(lastSet.has(postId)).toBe(true);
expect(lastSet.has('post-id-2')).toBe(true);
EphemeralStore.clearRecentlyUnsavedSavedPost(serverUrl, 'post-id-2');
const afterClearSet = calls[calls.length - 1][0] as Set<string>;
expect(afterClearSet.size).toBe(1);
expect(afterClearSet.has(postId)).toBe(true);
expect(afterClearSet.has('post-id-2')).toBe(false);
subscription.unsubscribe();
});
});
});