mirror of
https://github.com/mattermost/mattermost-mobile.git
synced 2026-11-14 15:10:17 +00:00
* chore(e2e): Fix e2e artifact upload path for CMT workflow (#9955) * chore(e2e): Fix e2e artifact upload path for CMT workflow * test(e2e): Replace MM-T placeholder test keys with real Zephyr Scale IDs - Classification Banner (18 tests): MM-T6196–MM-T6205, MM-T6206–MM-T6208, MM-T6209–MM-T6213 - mm_blocks (incoming webhook + ephemeral): MM-T6214–MM-T6240 (27 tests) - Fixes TM4J test-case linking by ensuring all test titles use real MM-T#### keys - Tightens getTM4JTestCases filter regex from /(MM-T)\w+/ to /MM-T\d+/ to prevent crashes when non-numeric MM-T placeholders slip through before Zephyr linkage - Scan all Xcode_*.app directories and filter for major version >= 26 to future-proof against Xcode 30+ releases (current glob pattern maxes at 29) - Extract version from directory name, validate major >= 26, sort and select highest - Add least-privilege job-level permissions (contents: read) to build jobs (build-ios-simulator, build-android-apk, build-android-apk-maestro) to scope actions/checkout and actions/upload-artifact access * fix: apply CodeRabbit review feedback Require Xcode 26.1+ for iOS prepare, standardize E2E titles to MM-TXXXX_N, and bound Zephyr test-case id matching to complete identifiers. * fix(e2e): Grant actions:write on CMT build jobs for artifact upload Job-level contents:read alone strips upload-artifact permission; match e2e-detox-pr.yml so ios/android/maestro builds can publish artifacts. * feat(e2e): Integrate TSIO reporting (#9925) Retire legacy maestro per-platform contexts from cancel-e2e-runs and document the canonical PR, master, and CMT status context mapping. Wire Detox + Maestro (PR/main/CMT) into Test System IO with a single commit status (e2e/mobile; CMT uses e2e/compatibility-matrix-testing) and groups mobile-pr / mobile-main / cmt-mobile. Upload shard results with correct framework labels, merge Jest shards into TSIO Detox shape, stub missing/dead shards as failures, and post channel summaries after status settles. Matterwick MASTER is treated as MAIN for mobile-main routing. Also harden report/fail paths, stage Maestro screenshots per flow for TSIO galleries, fix a few Detox setup/testID issues, and skip known platform flakes so the pipeline stays actionable while TSIO lands. * ci(e2e): per-job TSIO report groups, commit statuses, and webhook sidecar (#9969) * ci(e2e): per-job TSIO report groups and commit statuses E2E jobs previously shared a single `e2e/mobile` commit status backed by one TSIO report group, so concurrent platform legs raced to finalize the group and clobbered each other's results. Give each Detox/Maestro job its own report group (`mobile-<flow>-<job>`, total_reports_expected=1) and its own commit status context (`detox-ios`, `detox-android`, `detox-ipad`, `maestro-ios`, `maestro-android`); CMT reports per shard plus an umbrella context. Channel notifications move to a single rollup step so N platform legs no longer spam the webhook, and the five-server topology is dispatched with explicit per-platform inputs that still resolve to the existing SITE_*_URL contract consumed by the test config. Also adds the webhook sidecar launcher, Android emulator CI prep, and TSIO screenshot path linking that keeps folder basenames matching Jest full names. The new detox type-check job surfaced pre-existing broken import paths in maestro/fixtures/calls_seed.ts, which pointed at detox/detox/e2e; corrected so the guard passes on its own first run. Note: the CMT matrix now reads per-platform server URLs (`ios_site_1_url`, `android_site_1_url`, `site_3_url`) instead of a single `url`, which needs the matching Matterwick dispatch change to land alongside this. Co-authored-by: Cursor <cursoragent@cursor.com> * ci(e2e): aggregate CMT channel rollup from TSIO and wire notify secrets The CMT umbrella posted a placeholder summary built from CI job outcomes (passed:0, failed:0|1, reports:[]), so the release channel message carried no per-leg detail. It now runs the same tsio-channel-notify-rollup.js path as PR/main: cmt-identity emits a per-shard TSIO config map and the rollup polls every shard group, so counts and per-leg rows come from TSIO. The rollup job also needs id-token: write to mint its OIDC token. Webhook secrets used by the per-job TSIO finalize steps were referenced but never declared in the templates' workflow_call.secrets, so GitHub resolved them to empty strings and channel notify silently no-opped. Declare them in the iOS/Android/Maestro templates and forward them from e2e-detox.yml and the CMT callers. The Maestro PR path worked only because its callers use secrets: inherit. Also from review: - split-tests.js emitted two matrix jobs at parallelism=1 when mm_blocks specs were present; merge into one shard instead of exceeding the requested count. - Move the Android ARTIFACT_RUN_ID emptiness check ahead of download-artifact, which consumes it and otherwise fails with an opaque API error. - resolve-tsio-job-config.sh now reuses webhookBucketForReportName instead of re-deriving the bucket prefix with a looser startsWith check. Co-authored-by: Cursor <cursoragent@cursor.com> * ci(e2e): add local preflight for CI PRs The webhook-secret and OIDC-permission gaps in this branch were invisible locally and in a green CI run — the affected steps exit 0 and just skip the notify or commit status. Add a script engineers can run before opening a PR that touches .github/ or detox/utils: cd detox && npm run preflight:ci # :ci-fast skips lint + tsc It runs actionlint (which flags secrets not declared in a callee's workflow_call.secrets), scans for exit-code capture broken by a trailing backslash, asserts every job running a TSIO OIDC script declares id-token: write, then runs the detox/utils tests and npm run check. actionlint and the CodeRabbit CLI are optional and skipped with an install hint when absent. Co-authored-by: Cursor <cursoragent@cursor.com> * ci(e2e): use mktemp for preflight logs Fixed /tmp log paths can be pre-created as symlinks, so the preflight script would truncate whatever they point at (CWE-377). Create both logs with mktemp and drop them on exit. Co-authored-by: Cursor <cursoragent@cursor.com> * ci(e2e): address review feedback on TSIO statuses and sidecar A cancelled E2E run reached no conclusion, so posting `success` on its commit statuses let a PR merge on a check that never ran. Cancelled runs now post `pending`; `success` is reserved for the one deliberate bypass, the E2E/Override label. Commit-status contexts move into the `e2e-test/*` namespace to match the mattermost monorepo, with the prefix owned by build-tsio-job-config.js and mirrored in the cancel action's context list. Legacy unprefixed and `e2e/*` contexts are dropped rather than carried forward. The `preflight:ci` script and its OIDC-permission checker duplicated what actionlint, the unit tests and `npm run check` already do, so they are removed and detox/CLAUDE.md documents the underlying failure modes and the commands to catch them instead. cloudflared and the TSIO CLI are pinned to known-good releases rather than `latest`, and detox/README.md now documents the webhook sidecar: when a tunnel is needed, the WEBHOOK_PUBLIC_BASE_URL / CLOUDFLARED_TUNNEL_TOKEN precedence, and why quick tunnels report callbacks as unreachable. Co-authored-by: Cursor <cursoragent@cursor.com> * ci(e2e): detect upstream cancellation and surface status reset failures generate-report runs with always(), so job.status stays "success" when an upstream job is cancelled and TSIO was published as a real failure. Read the generate-specs/e2e-* needs results so a cancelled run is reported as such. In cancel-e2e-runs, only reset the E2E commit statuses for runs that were actually stopped — a run we failed to cancel keeps publishing its own results. Aggregate createCommitStatus failures across every context and fail the action afterwards instead of silently warning, so a stale check cannot go unnoticed. --------- Co-authored-by: Cursor <cursoragent@cursor.com> * fix(e2e): Quarantine proven flakes and harden Detox harness (#9971) * ci(e2e): make E2E/Override waive checks instead of cancelling runs (#9975) * ci(e2e): make E2E/Override waive checks instead of cancelling runs E2E/Override previously cancelled in-flight E2E runs and posted success on their commit statuses. Cancelling destroys the very signal the maintainer might still want, and reporting success for a run that never finished attributes a conclusion to work that never happened. Override now means one thing only: the required e2e-test/* contexts go green so the PR can merge. Runs keep going and keep reporting to TSIO. - Add .github/actions/e2e-override-status to post success (or pending) on all five required e2e-test/* contexts for a SHA. - Label manager posts success on `labeled` and pending on `unlabeled`, so removing the escape hatch re-blocks the PR instead of leaving a stale waiver on the head SHA. It comments the runs it left running rather than killing them, and drops to `actions: read` now that it never cancels. - tsio-report-status re-reads the PR labels before posting a failure. Because runs are no longer cancelled, a result landing after the override was applied would otherwise re-red a check the maintainer deliberately bypassed. The lookup fails closed so an unreadable label list cannot turn a real failure green, and the step itself no longer fails under override. - Guard e2e-cancel-on-label-removal: stripping E2E/Run* is exactly what the Honor E2E/Override step does, so without this the indirect unlabeled event would cancel the runs the redesign is meant to preserve. - e2e-detox-pr posts the success itself when the policy skips E2E, since every downstream job is skipped and a skipped job leaves the required contexts absent, blocking the merge forever. - cancel-e2e-runs drops status_state: a cancelled run has no conclusion to report, so it always resets to pending. - Thread `issues: read` through the reusable workflow callers so finalize can read the labels; a reusable workflow cannot escalate past its caller. Co-authored-by: Cursor <cursoragent@cursor.com> * ci(e2e): derive required E2E contexts from one definition The override and cancel actions each carried their own copy of the five required e2e-test/* contexts, kept aligned with build-tsio-job-config.js by comment alone. A job renamed in PR_MAIN_JOBS would silently leave the actions waiving or resetting a context that no longer exists, so a PR either cannot merge or merges while a real context still blocks it. Export E2E_STATUS_CONTEXTS from detox/utils/build-tsio-job-config.js, derived from PR_MAIN_JOBS, and require it from both composite actions. github-script resolves relative requires against the workspace, and every call site already checks out the repo before using the action. Also set persist-credentials: false on the e2e-label-manager checkout, matching the other checkout steps. Co-authored-by: Cursor <cursoragent@cursor.com> * ci(e2e): drop the cancel action for native concurrency, keep GitHub calls in Actions Review feedback from @saturninoabril. Superseding an in-flight E2E run is what GitHub's `concurrency` already does, so `e2e-detox-pr.yml` now declares `concurrency: e2e-<ref>` with `cancel-in-progress` instead of cancelling from a step inside the run that supersedes it. The older run is cancelled the moment the new dispatch is created rather than once a runner picks up the first job. That removes the only two remaining callers of `.github/actions/cancel-e2e-runs`, along with the commit statuses it forced to `pending` on cancel — a cancelled run has no conclusion to report, so the state is left to GitHub. Forcing a commit status is now reserved for real test results and the override waiver. The action is deleted. `e2e-cancel-on-label-removal.yml` goes with it: with `E2E/Run` on its way out and override no longer cancelling, removing the label to stop a run has no remaining practical case, and dropping the workflow also removes the back-door cancel guard it needed. The `E2E/Override` lookup moves out of `tsio-report-status.js` into a new `.github/actions/e2e-override-label` composite action, which the finalize steps call and pass in via `--e2e-override`. Talking to GitHub stays in the Actions layer and the reporter is left deciding on its inputs. Co-authored-by: Cursor <cursoragent@cursor.com> * ci(e2e): paginate PR label lookups for E2E/Override Co-authored-by: Cursor <cursoragent@cursor.com> * ci(e2e): re-post E2E/Override success on new commits Override success is SHA-scoped: it is posted only on the head SHA at label-apply time (e2e-label-manager 'labeled' path) and when Matterwick dispatches e2e-detox-pr.yml (post-e2e-override-status). On a push after E2E/Override is applied, refresh-e2e-run-label strips the run labels and returns — Matterwick is not dispatched, so the new head SHA gets no e2e-test/* statuses. With those checks Required, the new commit is blocked until the label is re-toggled. Carry the override onto the new commit: refresh-e2e-run-label now emits an e2e_override output, and when it is set a gated checkout + e2e-override-status step re-posts success on the new head SHA. Reuses the existing e2e-override-status action (same 5 required e2e-test/* contexts, same 'E2E bypassed' description), so it is idempotent with the labeled path. Adds statuses: write / contents: read to the job. Note: refresh-e2e-run-label is gated on base.ref == 'main', so stacked PRs (base != main) are not covered; non-main-base already posts success at dispatch time. --------- Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: Cursor <cursoragent@cursor.com>
156 lines
5.9 KiB
TypeScript
156 lines
5.9 KiB
TypeScript
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||
// See LICENSE.txt for license information.
|
||
|
||
import http from 'http';
|
||
import https from 'https';
|
||
|
||
import {adminPassword, adminUsername} from '@support/test_config';
|
||
import axios from 'axios';
|
||
import {wrapper} from 'axios-cookiejar-support';
|
||
import {CookieJar} from 'tough-cookie';
|
||
|
||
// Force IPv4 — axios-cookiejar-support v5 uses global agents.
|
||
(http.globalAgent as any).options.family = 4;
|
||
(https.globalAgent as any).options.family = 4;
|
||
|
||
const jar = new CookieJar();
|
||
const baseClient = wrapper(axios.create({
|
||
headers: {'X-Requested-With': 'XMLHttpRequest'},
|
||
jar,
|
||
}));
|
||
|
||
// Add request interceptor to handle CSRF tokens
|
||
baseClient.interceptors.request.use(async (config) => {
|
||
// Extract CSRF token from MMCSRF cookie and add as header
|
||
const cookies = jar.getCookiesSync(config.url || '');
|
||
const csrfCookie = cookies.find((cookie) => cookie.key === 'MMCSRF');
|
||
|
||
if (csrfCookie && csrfCookie.value) {
|
||
config.headers = config.headers || {};
|
||
config.headers['X-CSRF-Token'] = csrfCookie.value;
|
||
}
|
||
|
||
return config;
|
||
});
|
||
|
||
// Auto-retry on 401 by re-logging in as admin.
|
||
let isRetrying = false;
|
||
baseClient.interceptors.response.use(
|
||
(response) => response,
|
||
async (error) => {
|
||
const originalRequest = error.config;
|
||
|
||
// Retry once on 401.
|
||
if (
|
||
error.response?.status === 401 &&
|
||
!originalRequest._retried &&
|
||
!isRetrying &&
|
||
!originalRequest.url?.endsWith('/api/v4/users/login')
|
||
) {
|
||
originalRequest._retried = true;
|
||
isRetrying = true;
|
||
|
||
try {
|
||
await clearCookies();
|
||
await baseClient.post(
|
||
`${originalRequest.url?.split('/api/')[0]}/api/v4/users/login`,
|
||
{login_id: adminUsername, password: adminPassword},
|
||
);
|
||
|
||
console.info('🔄 Admin session refreshed after 401'); // eslint-disable-line no-console
|
||
return baseClient(originalRequest);
|
||
} catch (retryErr) {
|
||
return Promise.reject(retryErr);
|
||
} finally {
|
||
isRetrying = false;
|
||
}
|
||
}
|
||
|
||
return Promise.reject(error);
|
||
},
|
||
);
|
||
|
||
/** Cloudflare edge failures — 520–524 stay retryable alongside the gateway 5xx below. */
|
||
const CLOUDFLARE_EDGE_STATUSES: ReadonlySet<number> = new Set([520, 521, 522, 523, 524]);
|
||
|
||
const TRANSIENT_HTTP_STATUSES: ReadonlySet<number> = new Set([502, 503, 504, ...CLOUDFLARE_EDGE_STATUSES]);
|
||
|
||
/**
|
||
* Cloudflare could not reach the origin, so the request provably had no side effect.
|
||
* 522 is excluded: the connection can also time out after the origin accepted the request.
|
||
*/
|
||
const PRE_ORIGIN_STATUSES: ReadonlySet<number> = new Set([521, 523]);
|
||
|
||
const IDEMPOTENT_METHODS: ReadonlySet<string> = new Set(['get', 'head', 'options']);
|
||
|
||
/** Gateway 5xx plus Cloudflare edge — shared with the apiInit retry layer in setup.ts. */
|
||
export const isTransientHttpStatus = (status?: number): status is number =>
|
||
status !== undefined && TRANSIENT_HTTP_STATUSES.has(status);
|
||
|
||
/**
|
||
* Upper bound for an honored Cloudflare `retry_after`; the advertised tens of seconds blow
|
||
* Detox's 300s beforeAll budget. Shared with the apiInit retry layer in setup.ts.
|
||
*/
|
||
export const MAX_RETRY_AFTER_SEC = 3;
|
||
|
||
// Retry transient gateway / Cloudflare edge 5xx with short backoff.
|
||
baseClient.interceptors.response.use(
|
||
(response) => response,
|
||
async (error) => {
|
||
const config = error.config as typeof error.config & {_5xxRetries?: number};
|
||
const status = error.response?.status;
|
||
|
||
// A write may already have reached the origin behind 502/503/504 and CF 520/522/524, so
|
||
// only idempotent methods are retried on those; CF 521/523 never reach the origin at all.
|
||
const isSafeToRetry = isTransientHttpStatus(status) &&
|
||
(IDEMPOTENT_METHODS.has((config.method ?? 'get').toLowerCase()) || PRE_ORIGIN_STATUSES.has(status));
|
||
|
||
if (isSafeToRetry && (config._5xxRetries ?? 0) < 3) {
|
||
config._5xxRetries = (config._5xxRetries ?? 0) + 1;
|
||
const retryAfterSec = Number(error.response?.data?.retry_after);
|
||
const cappedRetryAfterMs = Number.isFinite(retryAfterSec) && retryAfterSec > 0 ?
|
||
Math.min(retryAfterSec, MAX_RETRY_AFTER_SEC) * 1000 :
|
||
0;
|
||
const delay = cappedRetryAfterMs || (config._5xxRetries * 1000);
|
||
console.warn(`[client] ${status} from server — retry ${config._5xxRetries}/3 in ${delay}ms`); // eslint-disable-line no-console
|
||
await new Promise((r) => setTimeout(r, delay)); // eslint-disable-line no-promise-executor-return
|
||
return baseClient(config);
|
||
}
|
||
return Promise.reject(error);
|
||
},
|
||
);
|
||
|
||
// Retry cloud/inaccessible HTML responses during workspace cold starts.
|
||
baseClient.interceptors.response.use(
|
||
async (response) => {
|
||
const data = response.data;
|
||
const isInaccessible = typeof data === 'string' && data.includes('cloud/inaccessible');
|
||
|
||
if (!isInaccessible) {
|
||
return response;
|
||
}
|
||
|
||
const config = response.config as typeof response.config & {_cloudInaccessibleRetries?: number};
|
||
const attempts = (config._cloudInaccessibleRetries ?? 0) + 1;
|
||
|
||
if (attempts > 3) {
|
||
return Promise.reject(new Error(`Server returned cloud/inaccessible HTML after 3 retries for ${config.url}`));
|
||
}
|
||
|
||
config._cloudInaccessibleRetries = attempts;
|
||
const delay = attempts * 3000;
|
||
console.warn(`[client] cloud/inaccessible HTML from server — retry ${attempts}/3 in ${delay}ms for ${config.url}`); // eslint-disable-line no-console
|
||
await new Promise((r) => setTimeout(r, delay));
|
||
return baseClient(config);
|
||
},
|
||
(error) => Promise.reject(error),
|
||
);
|
||
|
||
export const clearCookies = async (): Promise<void> => {
|
||
await jar.removeAllCookies();
|
||
};
|
||
|
||
export const client = baseClient;
|
||
|
||
export default client;
|