mattermost-mobile-upstream/app/utils/server/index.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

243 lines
9.1 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import {Alert, type AlertButton} from 'react-native';
import {Screens, Sso, SupportedServer, Launch} from '@constants';
import {navigateToScreen} from '@screens/navigation';
import {getErrorMessage} from '@utils/errors';
import {isMinimumServerVersion} from '@utils/helpers';
import {tryOpenURL} from '@utils/url';
import type ServersModel from '@typings/database/models/app/servers';
import type {DeepLinkWithData} from '@typings/launch';
import type {IntlShape} from 'react-intl';
export function isSupportedServer(currentVersion: string) {
return isMinimumServerVersion(currentVersion, SupportedServer.MAJOR_VERSION, SupportedServer.MIN_VERSION, SupportedServer.PATCH_VERSION);
}
export function unsupportedServer(serverDisplayName: string, isSystemAdmin: boolean, intl: IntlShape, onPress?: () => void) {
if (isSystemAdmin) {
unsupportedServerAdminAlert(serverDisplayName, intl, onPress);
}
}
export function semverFromServerVersion(value: string) {
if (!value || typeof value !== 'string') {
return undefined;
}
const split = value.split('.');
const major = parseInt(split[0], 10);
const minor = parseInt(split[1] || '0', 10);
const patch = parseInt(split[2] || '0', 10);
return `${major}.${minor}.${patch}`;
}
export async function addNewServer(theme: Theme, serverUrl?: string, displayName?: string, deepLinkProps?: DeepLinkWithData) {
const props = {
displayName,
launchType: deepLinkProps ? Launch.AddServerFromDeepLink : Launch.AddServer,
serverUrl,
theme,
extra: deepLinkProps,
isModal: true,
isStackRoot: true,
};
navigateToScreen(Screens.SERVER, props);
}
export function loginOptions(config: ClientConfig, license: ClientLicense) {
const isLicensed = license.IsLicensed === 'true';
const samlEnabled = config.EnableSaml === 'true' && isLicensed && license.SAML === 'true';
const gitlabEnabled = config.EnableSignUpWithGitLab === 'true';
const isMinServerVersionForCloudOAuthChanges = isMinimumServerVersion(config.Version, 7, 6);
let googleEnabled = false;
let o365Enabled = false;
let openIdEnabled = false;
if (isMinServerVersionForCloudOAuthChanges) {
googleEnabled = config.EnableSignUpWithGoogle === 'true';
o365Enabled = config.EnableSignUpWithOffice365 === 'true';
openIdEnabled = config.EnableSignUpWithOpenId === 'true';
} else {
googleEnabled = config.EnableSignUpWithGoogle === 'true' && isLicensed;
o365Enabled = config.EnableSignUpWithOffice365 === 'true' && isLicensed && license.Office365OAuth === 'true';
openIdEnabled = config.EnableSignUpWithOpenId === 'true' && isLicensed;
}
const ldapEnabled = isLicensed && config.EnableLdap === 'true' && license.LDAP === 'true';
const hasLoginForm = config.EnableSignInWithEmail === 'true' || config.EnableSignInWithUsername === 'true' || ldapEnabled;
const ssoOptions: SsoWithOptions = {
[Sso.SAML]: {enabled: samlEnabled, text: config.SamlLoginButtonText},
[Sso.GITLAB]: {enabled: gitlabEnabled},
[Sso.GOOGLE]: {enabled: googleEnabled},
[Sso.OFFICE365]: {enabled: o365Enabled},
[Sso.OPENID]: {enabled: openIdEnabled, text: config.OpenIdButtonText},
};
const enabledSSOs = Object.keys(ssoOptions).filter((key) => ssoOptions[key].enabled);
const numberSSOs = enabledSSOs.length;
return {
enabledSSOs,
hasLoginForm,
numberSSOs,
ssoOptions,
};
}
/**
* With no login form and a single SSO provider there is nothing to choose, so the login screen is
* skipped. Shared so the add-server and re-login flows cannot disagree.
*/
export function getLoginScreen(enabledSSOs: string[], hasLoginForm: boolean) {
if (!hasLoginForm && enabledSSOs.length === 1) {
return {screen: Screens.SSO, ssoType: enabledSSOs[0]};
}
return {screen: Screens.LOGIN, ssoType: undefined};
}
export async function loginToServer(theme: Theme, serverUrl: string, displayName: string, config: ClientConfig, license: ClientLicense) {
const {enabledSSOs, hasLoginForm, ssoOptions} = loginOptions(config, license);
const {screen, ssoType} = getLoginScreen(enabledSSOs, hasLoginForm);
// Re-login and add-server both resolve pre-auth secrets outside nav params (keychain or
// EphemeralStore) so they are never JSON-serialized into Expo Router.
navigateToScreen(screen, {
config,
hasLoginForm,
launchType: Launch.AddServer,
license,
serverDisplayName: displayName,
serverUrl,
ssoOptions,
ssoType,
theme,
isModal: true,
isStackRoot: true,
});
}
export async function editServer(theme: Theme, serverId: string) {
const props = {
serverId,
theme,
};
navigateToScreen(Screens.EDIT_SERVER, props);
}
export async function alertServerLogout(displayName: string, onPress: () => void, intl: IntlShape) {
Alert.alert(
intl.formatMessage({
id: 'server.logout.alert_title',
defaultMessage: 'Are you sure you want to log out of {displayName}?',
}, {displayName}),
intl.formatMessage({
id: 'server.logout.alert_description',
defaultMessage: 'All associated data will be removed',
}),
[{
style: 'cancel',
text: intl.formatMessage({id: 'mobile.post.cancel', defaultMessage: 'Cancel'}),
}, {
style: 'destructive',
text: intl.formatMessage({id: 'servers.logout', defaultMessage: 'Log out'}),
onPress,
}],
);
}
export async function alertServerRemove(displayName: string, onPress: () => void, intl: IntlShape) {
Alert.alert(
intl.formatMessage({
id: 'server.remove.alert_title',
defaultMessage: 'Are you sure you want to remove {displayName}?',
}, {displayName}),
intl.formatMessage({
id: 'server.remove.alert_description',
defaultMessage: 'This will remove it from your list of servers. All associated data will be removed',
}),
[{
style: 'cancel',
text: intl.formatMessage({id: 'mobile.post.cancel', defaultMessage: 'Cancel'}),
}, {
style: 'destructive',
text: intl.formatMessage({id: 'servers.remove', defaultMessage: 'Remove'}),
onPress,
}],
);
}
export function alertServerError(intl: IntlShape, error: unknown) {
const message = getErrorMessage(error, intl);
Alert.alert(
intl.formatMessage({
id: 'server.websocket.unreachable',
defaultMessage: 'Server is unreachable.',
}),
message,
);
}
export function alertServerAlreadyConnected(intl: IntlShape) {
Alert.alert(
'',
intl.formatMessage({
id: 'mobile.server_identifier.exists',
defaultMessage: 'You are already connected to this server.',
}),
);
}
export const sortServersByDisplayName = (servers: ServersModel[], intl: IntlShape) => {
function serverName(s: ServersModel) {
if (s.displayName === s.url) {
return intl.formatMessage({id: 'servers.default', defaultMessage: 'Default Server'});
}
return s.displayName;
}
return servers.sort((a, b) => {
return serverName(a).localeCompare(serverName(b));
});
};
function unsupportedServerAdminAlert(serverDisplayName: string, intl: IntlShape, onPress?: () => void) {
const title = intl.formatMessage({id: 'mobile.server_upgrade.title', defaultMessage: 'Server upgrade required'});
const message = intl.formatMessage({
id: 'server_upgrade.alert_description',
defaultMessage: 'Your server, {serverDisplayName}, is running an unsupported server version. Users will be exposed to compatibility issues that cause crashes or severe bugs breaking core functionality of the app. Upgrading to server version {supportedServerVersion} or later is required.',
}, {serverDisplayName, supportedServerVersion: SupportedServer.FULL_VERSION});
const cancel: AlertButton = {
text: intl.formatMessage({id: 'server_upgrade.dismiss', defaultMessage: 'Dismiss'}),
style: 'default',
onPress,
};
const learnMore: AlertButton = {
text: intl.formatMessage({id: 'server_upgrade.learn_more', defaultMessage: 'Learn More'}),
style: 'cancel',
onPress: () => {
const url = 'https://docs.mattermost.com/administration/release-lifecycle.html';
const onError = () => {
Alert.alert(
intl.formatMessage({id: 'mobile.link.error.title', defaultMessage: 'Error'}),
intl.formatMessage({id: 'mobile.link.error.text', defaultMessage: 'Unable to open the link.'}),
);
};
tryOpenURL(url, onError);
},
};
const buttons: AlertButton[] = [cancel, learnMore];
const options = {cancelable: false};
Alert.alert(title, message, buttons, options);
}