mattermost-mobile/app/actions/app/server.test.ts
Elias Nahum 44eb76bed7
feat(iOS): Add Microsoft Intune MAM integration with multi-server support (#9312)
* refactor: implement custom ExpoImage wrapper for cache control

Add ExpoImage component with automatic cacheKey/cachePath management and replace all expo-image imports across the app

* refactor(ios): convert Gekidou to CocoaPods

Migrate from Swift Package Manager to CocoaPods, add Keychain write operations, refactor notification handler to remove react-native-notifications headers, and upgrade Swift to 5.0

* npm audit

* update fastlane

* feat(ci): integrate Intune MAM for enterprise builds with strict OSS protection

Add Intune submodule, CI actions, Fastlane configuration, developer scripts, pre-commit hooks, and validation workflows to enable internal MAM builds while protecting OSS repository

* fix tests by mocking @mattermost/intune

* feat: implement Intune MAM integration with comprehensive security enforcement

Add IntuneManager, refactor SecurityManager/SessionManager for MAM policies, implement native OIDC auth flow, add biometric enforcement, conditional launch blocking, and file protection controls

* fix alerts when no server database is present

* Unify cache strategy

* fix emit config changed after it was stored in the db

* Handle Mid-Session Enrollment Detection

* fix ADALLogOverrideDisabled missing in Fastfile

* fix flow for initial enrollment

* fix and add unit tests

* enable Intune configuration for PR and beta builds, CLIENT_ID should be changed before actual release

* Update intune submodule with addressed feedback

* fix validate-intune-clean workflow

* feat(intune): add comprehensive error handling and SAML+Entra support

Add production-ready error handling for native Entra authentication with
user-friendly i18n messages, comprehensive test coverage, and support for
Entra login when server requires SAML.

* update i18n

* update intune submodule

* update build-pr token

* fix race condition between server auth and intune enrollment

* fix CI workflow to build with intune

* use deploy key for intune submodule

* set the config directly in the submodule .git

* debug injection

* try setting GIT_SSH_COMMAND

* remove action debug

* fix server url input

* match pod cache with intune hash

* Fastfile and envs

* have workflows check for intune/.git

* have ci cache intune frameworks as well

* update Fastlane to set no-cache to artifacts uploaded

* fix s3 upload

* fix pblist template

* Attempt to remove the cache control for PR uploads to s3

* use hash from commit for S3 path

* Implement crash-resilient selective wipe with automatic retry and add removeInternetPassword to Gekidou Keychain

* Fix surface errors from intune login

* fix postinstall scripts

* use cacheKey for draft md images

* remove unnecessary double await during test

* Have isMinimumLicenseTier accept valid license sku tier as target

* Add missing Auth error messages

* remove the last period for intune errors in i18n

* do not call unenroll with wipe on manual logout

* Fix tests and Intune error messages

* do not filter any SSO type regardless of which is used for Intune

* fix 412 to not retry

* fix tests, app logs sharing and share_extension avatar cache

* apply setScreenCapturePolicy on license change

Co-authored-by: Eva Sarafianou <eva.sarafianou@mattermost.com>

* re-apply screen capture on enrollment

Co-authored-by: Eva Sarafianou <eva.sarafianou@mattermost.com>

* use userData from intunr login and prevent getMe

Co-authored-by: Eva Sarafianou <eva.sarafianou@mattermost.com>

* Check for Biometrics and Jailbreak as we used to

---------

Co-authored-by: Eva Sarafianou <eva.sarafianou@mattermost.com>
2025-12-10 13:07:28 +02:00

185 lines
8.8 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {createIntl} from 'react-intl';
import {DeviceEventEmitter} from 'react-native';
import {Navigation} from 'react-native-navigation';
import {doPing} from '@actions/remote/general';
import {fetchConfigAndLicense} from '@actions/remote/systems';
import {Events, Preferences, Screens} from '@constants';
import DatabaseManager from '@database/manager';
import {DEFAULT_LOCALE, getTranslations} from '@i18n';
import SecurityManager from '@managers/security_manager';
import WebsocketManager from '@managers/websocket_manager';
import {getServer, getServerByIdentifier} from '@queries/app/servers';
import TestHelper from '@test/test_helper';
import {logError} from '@utils/log';
import {canReceiveNotifications} from '@utils/push_proxy';
import {alertServerAlreadyConnected, alertServerError, loginToServer} from '@utils/server';
import * as Actions from './server';
import type ServersModel from '@typings/database/models/app/servers';
jest.mock('@queries/app/servers');
jest.mock('@queries/servers/system');
jest.mock('@database/manager');
jest.mock('@managers/security_manager');
jest.mock('@managers/websocket_manager');
jest.mock('@utils/log');
jest.mock('@utils/push_proxy');
jest.mock('@utils/server');
jest.mock('@actions/remote/general');
jest.mock('@actions/remote/systems');
jest.mock('react-native-navigation');
const translations = getTranslations(DEFAULT_LOCALE);
const intl = createIntl({locale: DEFAULT_LOCALE, messages: translations});
const theme = Preferences.THEMES.denim;
// Tests for switchToServer
describe('switchToServer', () => {
const emitSpy = jest.spyOn(DeviceEventEmitter, 'emit');
beforeAll(() => {
// Register the SecurityManager listener manually since the mocked SecurityManager doesn't run its constructor
DeviceEventEmitter.addListener(Events.ACTIVE_SERVER_CHANGED, jest.mocked(SecurityManager).setActiveServer);
});
beforeEach(async () => {
// Initialize the database for each test
await DatabaseManager.init(['serverUrl']);
});
afterEach(async () => {
// Clean up
await DatabaseManager.destroyServerDatabase('serverUrl');
emitSpy.mockClear();
jest.mocked(SecurityManager).setActiveServer.mockClear();
jest.mocked(SecurityManager).isDeviceJailbroken.mockClear();
jest.mocked(SecurityManager).authenticateWithBiometricsIfNeeded.mockClear();
});
it('should log error when server is not found', async () => {
jest.mocked(getServer).mockResolvedValueOnce(undefined);
await Actions.switchToServer('serverUrl', theme, intl, jest.fn());
expect(logError).toHaveBeenCalledWith('Switch to Server with url serverUrl not found');
});
it('should switch to server when lastActiveAt is set', async () => {
const server = {url: 'serverUrl', lastActiveAt: 123} as ServersModel;
const setActiveSpy = jest.spyOn(DatabaseManager, 'setActiveServerDatabase');
jest.mocked(getServer).mockResolvedValueOnce(server);
jest.mocked(SecurityManager).isDeviceJailbroken.mockResolvedValueOnce(false);
jest.mocked(SecurityManager).authenticateWithBiometricsIfNeeded.mockResolvedValueOnce(true);
await Actions.switchToServer('serverUrl', theme, intl, jest.fn());
// Wait for the async database operation to complete (setActiveServerDatabase is called without await)
await TestHelper.wait(10);
const options = {
skipJailbreakCheck: true,
skipBiometricCheck: true,
skipMAMEnrollmentCheck: false,
forceSwitch: false,
};
expect(Navigation.updateProps).toHaveBeenCalledWith(Screens.HOME, {extra: undefined});
expect(setActiveSpy).toHaveBeenCalledWith('serverUrl', options);
expect(emitSpy).toHaveBeenCalledWith(Events.ACTIVE_SERVER_CHANGED, {serverUrl: 'serverUrl', options});
expect(SecurityManager.setActiveServer).toHaveBeenCalledWith({serverUrl: 'serverUrl', options});
expect(WebsocketManager.initializeClient).toHaveBeenCalledWith('serverUrl', 'Server Switch');
});
it('should not proceed if device is jailbroken', async () => {
const server = {url: 'serverUrl', lastActiveAt: 123} as ServersModel;
jest.mocked(getServer).mockResolvedValueOnce(server);
jest.mocked(SecurityManager.isDeviceJailbroken).mockResolvedValueOnce(true);
jest.mocked(SecurityManager.authenticateWithBiometricsIfNeeded).mockResolvedValueOnce(true);
await Actions.switchToServer('serverUrl', theme, intl, jest.fn());
expect(Navigation.updateProps).not.toHaveBeenCalled();
expect(DatabaseManager.setActiveServerDatabase).not.toHaveBeenCalled();
expect(SecurityManager.setActiveServer).not.toHaveBeenCalled();
expect(WebsocketManager.initializeClient).not.toHaveBeenCalled();
expect(SecurityManager.isDeviceJailbroken).toHaveBeenCalledWith('serverUrl');
});
});
// Tests for switchToServerAndLogin
describe('switchToServerAndLogin', () => {
it('should log error when server is not found', async () => {
jest.mocked(getServer).mockResolvedValueOnce(undefined);
await Actions.switchToServerAndLogin('serverUrl', theme, intl, jest.fn());
expect(logError).toHaveBeenCalledWith('Switch to Server with url serverUrl not found');
});
it('should alert server error when ping fails', async () => {
const server = {url: 'serverUrl'} as ServersModel;
jest.mocked(getServer).mockResolvedValueOnce(server);
jest.mocked(doPing).mockResolvedValueOnce({error: 'ping error'});
await Actions.switchToServerAndLogin('serverUrl', theme, intl, jest.fn());
expect(alertServerError).toHaveBeenCalledWith(intl, 'ping error');
});
it('should alert server error when fetching config and license fails', async () => {
const server = {url: 'serverUrl'} as ServersModel;
jest.mocked(getServer).mockResolvedValueOnce(server);
jest.mocked(doPing).mockResolvedValueOnce({});
jest.mocked(fetchConfigAndLicense).mockResolvedValueOnce({error: 'config error'});
await Actions.switchToServerAndLogin('serverUrl', theme, intl, jest.fn());
expect(alertServerError).toHaveBeenCalledWith(intl, 'config error');
});
it('should alert server already connected when server is already connected', async () => {
const server = {url: 'serverUrl'} as ServersModel;
const config = {DiagnosticId: 'diagId', MobileEnableBiometrics: 'true', SiteName: 'Site'} as ClientConfig;
jest.mocked(getServer).mockResolvedValueOnce(server);
jest.mocked(doPing).mockResolvedValueOnce({});
jest.mocked(fetchConfigAndLicense).mockResolvedValueOnce({config});
jest.mocked(getServerByIdentifier).mockResolvedValueOnce({lastActiveAt: 123} as ServersModel);
await Actions.switchToServerAndLogin('serverUrl', theme, intl, jest.fn());
expect(alertServerAlreadyConnected).toHaveBeenCalledWith(intl);
});
it('should authenticate with biometrics and login to server', async () => {
const server = {url: 'serverUrl', displayName: 'Server'} as ServersModel;
const config = {DiagnosticId: 'diagId', MobileEnableBiometrics: 'true', SiteName: 'Site'} as ClientConfig;
const license = {} as ClientLicense;
jest.mocked(getServer).mockResolvedValueOnce(server);
jest.mocked(doPing).mockResolvedValueOnce({});
jest.mocked(fetchConfigAndLicense).mockResolvedValueOnce({config, license});
jest.mocked(getServerByIdentifier).mockResolvedValueOnce(undefined);
jest.mocked(SecurityManager.authenticateWithBiometrics).mockResolvedValueOnce(true);
await Actions.switchToServerAndLogin('serverUrl', theme, intl, jest.fn());
expect(canReceiveNotifications).toHaveBeenCalledWith('serverUrl', undefined, intl);
expect(loginToServer).toHaveBeenCalledWith(theme, 'serverUrl', 'Server', config, license);
});
it('should not proceed if device is jailbroken', async () => {
const server = {url: 'serverUrl'} as ServersModel;
const config = {DiagnosticId: 'diagId', MobileJailbreakProtection: 'true'} as ClientConfig;
jest.mocked(getServer).mockResolvedValueOnce(server);
jest.mocked(doPing).mockResolvedValueOnce({});
jest.mocked(fetchConfigAndLicense).mockResolvedValueOnce({config});
jest.mocked(getServerByIdentifier).mockResolvedValueOnce(undefined);
jest.mocked(SecurityManager.isDeviceJailbroken).mockResolvedValueOnce(true);
const callback = jest.fn();
await Actions.switchToServerAndLogin('serverUrl', theme, intl, callback);
expect(SecurityManager.isDeviceJailbroken).toHaveBeenCalledWith('serverUrl');
expect(callback).toHaveBeenCalled();
});
});