Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Adds 'Upgrade now' banner (#82214)

Kevin Kelleherb9d8328b197e
diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.ts
index ab5d683f9ea..aae7ebeda98 100644
--- a/frontend/src/metabase-types/api/settings.ts
+++ b/frontend/src/metabase-types/api/settings.ts
@@ -206,11 +206,19 @@ export interface VersionInfoRecord {
announcement_url?: string;
}
+export interface AlertUpgradeVersion {
+ min: string;
+ fixed: string;
+ message: string;
+ id?: string;
+}
+
export interface VersionInfo {
nightly?: VersionInfoRecord;
beta?: VersionInfoRecord;
latest?: VersionInfoRecord;
older?: VersionInfoRecord[];
+ alert_upgrade_versions?: AlertUpgradeVersion[];
}
export type LocaleData = [string, string];
diff --git a/frontend/src/metabase-types/guards/settings.ts b/frontend/src/metabase-types/guards/settings.ts
index 24b10ecb975..53cddd3ef38 100644
--- a/frontend/src/metabase-types/guards/settings.ts
+++ b/frontend/src/metabase-types/guards/settings.ts
@@ -1,4 +1,5 @@
import {
+ type AlertUpgradeVersion,
type EngineKey,
type ScheduleDayType,
engineKeys,
@@ -23,3 +24,18 @@ export function isScheduleDay(value: string): value is ScheduleDayType {
// Unjustified type cast. FIXME
return SCHEDULE_DAY.includes(value as ScheduleDayType);
}
+
+export function isAlertUpgradeVersion(
+ value: unknown,
+): value is AlertUpgradeVersion {
+ return (
+ typeof value === "object" &&
+ value !== null &&
+ "min" in value &&
+ typeof value.min === "string" &&
+ "fixed" in value &&
+ typeof value.fixed === "string" &&
+ "message" in value &&
+ typeof value.message === "string"
+ );
+}
diff --git a/frontend/src/metabase/common/components/AppBanner/AppBanner.tsx b/frontend/src/metabase/common/components/AppBanner/AppBanner.tsx
index f92ce470841..6ad8e89ad58 100644
--- a/frontend/src/metabase/common/components/AppBanner/AppBanner.tsx
+++ b/frontend/src/metabase/common/components/AppBanner/AppBanner.tsx
@@ -13,6 +13,7 @@ import {
import { PaymentBanner } from "./PaymentBanner/PaymentBanner";
import { ReadOnlyBanner } from "./ReadOnlyBanner";
import { TrialBanner } from "./TrialBanner";
+import { UpgradeBanner, useUpgradeBanner } from "./UpgradeBanner";
import { getCurrentUTCTimestamp, shouldShowTrialBanner } from "./utils";
export const AppBanner = () => {
@@ -26,6 +27,7 @@ export const AppBanner = () => {
const migrateReadOnly = useSetting("read-only-mode");
const isDevMode = useSetting("development-mode?");
+ const upgradeBannerProps = useUpgradeBanner();
const { shouldShowLicenseTokenMissingBanner, dismissBanner } =
useLicenseTokenMissingBanner(isAdmin);
@@ -51,6 +53,10 @@ export const AppBanner = () => {
return <ReadOnlyBanner />;
}
+ if (upgradeBannerProps) {
+ return <UpgradeBanner {...upgradeBannerProps} />;
+ }
+
if (shouldShowLicenseTokenMissingBanner) {
return <LicenseTokenMissingBanner onClose={dismissBanner} />;
}
diff --git a/frontend/src/metabase/common/components/AppBanner/AppBanner.unit.spec.tsx b/frontend/src/metabase/common/components/AppBanner/AppBanner.unit.spec.tsx
index 211825d433f..beae9e3aba6 100644
--- a/frontend/src/metabase/common/components/AppBanner/AppBanner.unit.spec.tsx
+++ b/frontend/src/metabase/common/components/AppBanner/AppBanner.unit.spec.tsx
@@ -1,4 +1,7 @@
-import { setupDatabasesEndpoints } from "__support__/server-mocks";
+import {
+ setupDatabasesEndpoints,
+ setupSettingEndpoint,
+} from "__support__/server-mocks";
import { mockSettings } from "__support__/settings";
import { createMockState } from "__support__/state";
import { renderWithProviders, screen } from "__support__/ui";
@@ -8,6 +11,7 @@ import {
createMockDatabase,
createMockTokenStatus,
createMockUser,
+ createMockVersionInfo,
} from "metabase-types/api/mocks";
import { createSampleDatabase } from "metabase-types/api/mocks/presets";
@@ -32,6 +36,10 @@ function setup({
tokenStatus,
}: SetupOpts) {
setupDatabasesEndpoints([TEST_DB, DATA_WAREHOUSE_DB]);
+ setupSettingEndpoint({
+ settingKey: "version-info",
+ settingValue: createMockVersionInfo(),
+ });
const state = createMockState({
currentUser: createMockUser({ is_superuser: isAdmin }),
diff --git a/frontend/src/metabase/common/components/AppBanner/UpgradeBanner/UpgradeBanner.module.css b/frontend/src/metabase/common/components/AppBanner/UpgradeBanner/UpgradeBanner.module.css
new file mode 100644
index 00000000000..9848ada9aba
--- /dev/null
+++ b/frontend/src/metabase/common/components/AppBanner/UpgradeBanner/UpgradeBanner.module.css
@@ -0,0 +1,3 @@
+.banner {
+ border-bottom: 1px solid var(--mb-color-feedback-warning);
+}
diff --git a/frontend/src/metabase/common/components/AppBanner/UpgradeBanner/UpgradeBanner.tsx b/frontend/src/metabase/common/components/AppBanner/UpgradeBanner/UpgradeBanner.tsx
new file mode 100644
index 00000000000..9ebc71d6cb3
--- /dev/null
+++ b/frontend/src/metabase/common/components/AppBanner/UpgradeBanner/UpgradeBanner.tsx
@@ -0,0 +1,19 @@
+import { Banner } from "metabase/common/components/Banner";
+import { Markdown } from "metabase/common/components/Markdown";
+
+import S from "./UpgradeBanner.module.css";
+
+export interface UpgradeBannerProps {
+ message: string;
+}
+
+export function UpgradeBanner({ message }: UpgradeBannerProps) {
+ return (
+ <Banner
+ icon="info"
+ bg="background_surface-warning"
+ className={S.banner}
+ body={<Markdown>{message}</Markdown>}
+ />
+ );
+}
diff --git a/frontend/src/metabase/common/components/AppBanner/UpgradeBanner/index.ts b/frontend/src/metabase/common/components/AppBanner/UpgradeBanner/index.ts
new file mode 100644
index 00000000000..88771573d47
--- /dev/null
+++ b/frontend/src/metabase/common/components/AppBanner/UpgradeBanner/index.ts
@@ -0,0 +1,2 @@
+export * from "./UpgradeBanner";
+export * from "./useUpgradeBanner";
diff --git a/frontend/src/metabase/common/components/AppBanner/UpgradeBanner/useUpgradeBanner.ts b/frontend/src/metabase/common/components/AppBanner/UpgradeBanner/useUpgradeBanner.ts
new file mode 100644
index 00000000000..77aaed89342
--- /dev/null
+++ b/frontend/src/metabase/common/components/AppBanner/UpgradeBanner/useUpgradeBanner.ts
@@ -0,0 +1,37 @@
+import { getUserIsAdmin } from "metabase/current-user";
+import { useSelector } from "metabase/redux";
+import { useGetVersionInfoQuery, useSetting } from "metabase/settings";
+import { isWithinIframe } from "metabase/utils/iframe";
+
+import type { UpgradeBannerProps } from "./UpgradeBanner";
+import { getAlertUpgradeVersion } from "./utils";
+
+export function useUpgradeBanner(): UpgradeBannerProps | null {
+ const isAdmin = useSelector(getUserIsAdmin);
+ const isHosted = useSetting("is-hosted?");
+ const version = useSetting("version");
+
+ const { data: versionInfo } = useGetVersionInfoQuery(undefined, {
+ skip: !isAdmin,
+ });
+
+ if (
+ !isAdmin ||
+ isWithinIframe() ||
+ isHosted ||
+ !version.tag ||
+ !versionInfo
+ ) {
+ return null;
+ }
+
+ const alertUpgradeVersion = getAlertUpgradeVersion(version.tag, versionInfo);
+
+ if (!alertUpgradeVersion) {
+ return null;
+ }
+
+ return {
+ message: alertUpgradeVersion.message,
+ };
+}
diff --git a/frontend/src/metabase/common/components/AppBanner/UpgradeBanner/useUpgradeBanner.unit.spec.ts b/frontend/src/metabase/common/components/AppBanner/UpgradeBanner/useUpgradeBanner.unit.spec.ts
new file mode 100644
index 00000000000..644ad5da303
--- /dev/null
+++ b/frontend/src/metabase/common/components/AppBanner/UpgradeBanner/useUpgradeBanner.unit.spec.ts
@@ -0,0 +1,97 @@
+import { findRequests, setupSettingEndpoint } from "__support__/server-mocks";
+import { mockSettings } from "__support__/settings";
+import { createMockState } from "__support__/state";
+import { renderHookWithProviders, waitFor } from "__support__/ui";
+import * as iframeUtils from "metabase/utils/iframe";
+import {
+ createMockUser,
+ createMockVersion,
+ createMockVersionInfo,
+} from "metabase-types/api/mocks";
+
+import { useUpgradeBanner } from "./useUpgradeBanner";
+
+const CURRENT_VERSION = "v0.63.5";
+const ALERT_MESSAGE = "Please upgrade to v0.63.10";
+
+const MATCHING_VERSION_INFO = createMockVersionInfo({
+ alert_upgrade_versions: [
+ {
+ min: "v0.63.0",
+ fixed: "v0.63.10",
+ message: ALERT_MESSAGE,
+ },
+ ],
+});
+
+function setup({
+ isAdmin = true,
+ isHosted = false,
+ isEmbedded = false,
+}: {
+ isAdmin?: boolean;
+ isHosted?: boolean;
+ isEmbedded?: boolean;
+} = {}) {
+ jest.spyOn(iframeUtils, "isWithinIframe").mockReturnValue(isEmbedded);
+
+ setupSettingEndpoint({
+ settingKey: "version-info",
+ settingValue: MATCHING_VERSION_INFO,
+ });
+
+ return renderHookWithProviders(() => useUpgradeBanner(), {
+ storeInitialState: createMockState({
+ currentUser: createMockUser({ is_superuser: isAdmin }),
+ settings: mockSettings({
+ "is-hosted?": isHosted,
+ version: createMockVersion({ tag: CURRENT_VERSION }),
+ }),
+ }),
+ });
+}
+
+async function waitForVersionInfoRequest() {
+ await waitFor(async () => {
+ const requests = await findRequests("GET");
+ expect(
+ requests.some((request) =>
+ request.url.includes("/api/setting/version-info"),
+ ),
+ ).toBe(true);
+ });
+}
+
+describe("useUpgradeBanner", () => {
+ afterEach(() => {
+ jest.restoreAllMocks();
+ });
+
+ it("returns the alert message for an admin on a self-hosted instance", async () => {
+ const { result } = setup();
+
+ await waitFor(() => {
+ expect(result.current).toEqual({ message: ALERT_MESSAGE });
+ });
+ });
+
+ it("returns null for non-admins", () => {
+ const { result } = setup({ isAdmin: false });
+
+ expect(result.current).toBeNull();
+ });
+
+ it("returns null on hosted instances", async () => {
+ const { result } = setup({ isHosted: true });
+
+ await waitForVersionInfoRequest();
+ expect(result.current).toBeNull();
+ });
+
+ it("returns null when embedded in an iframe", async () => {
+ const { result } = setup({ isEmbedded: true });
+
+ await waitForVersionInfoRequest();
+ expect(result.current).toBeNull();
+ });
+});
diff --git a/frontend/src/metabase/common/components/AppBanner/UpgradeBanner/utils.ts b/frontend/src/metabase/common/components/AppBanner/UpgradeBanner/utils.ts
new file mode 100644
index 00000000000..4b513a616db
--- /dev/null
+++ b/frontend/src/metabase/common/components/AppBanner/UpgradeBanner/utils.ts
@@ -0,0 +1,33 @@
+import { compareVersions } from "metabase/utils/version";
+import type { AlertUpgradeVersion, VersionInfo } from "metabase-types/api";
+import { isAlertUpgradeVersion } from "metabase-types/guards/settings";
+
+export function getAlertUpgradeVersion(
+ versionTag: string,
+ versionInfo: VersionInfo,
+): AlertUpgradeVersion | undefined {
+ const matching = versionInfo.alert_upgrade_versions
+ ?.filter(isAlertUpgradeVersion)
+ .filter((v) => {
+ const minResult = compareVersions(v.min, versionTag);
+ const fixedResult = compareVersions(v.fixed, versionTag);
+ return (
+ minResult != null &&
+ fixedResult != null &&
+ minResult <= 0 &&
+ fixedResult > 0
+ );
+ });
+
+ if (!matching?.length) {
+ return undefined;
+ }
+
+ return matching.reduce((highest, current) => {
+ const cmp = compareVersions(current.fixed, highest.fixed);
+ if (cmp == null) {
+ return highest;
+ }
+ return cmp > 0 ? current : highest;
+ });
+}
diff --git a/frontend/src/metabase/common/components/AppBanner/UpgradeBanner/utils.unit.spec.ts b/frontend/src/metabase/common/components/AppBanner/UpgradeBanner/utils.unit.spec.ts
new file mode 100644
index 00000000000..d45bdf93619
--- /dev/null
+++ b/frontend/src/metabase/common/components/AppBanner/UpgradeBanner/utils.unit.spec.ts
@@ -0,0 +1,82 @@
+import type { AlertUpgradeVersion } from "metabase-types/api";
+import { createMockVersionInfo } from "metabase-types/api/mocks";
+
+import { getAlertUpgradeVersion } from "./utils";
+
+const entry = (
+ opts: Partial<AlertUpgradeVersion> &
+ Pick<AlertUpgradeVersion, "min" | "fixed">,
+): AlertUpgradeVersion => ({
+ message: `${opts.min} -> ${opts.fixed}`,
+ ...opts,
+});
+
+describe("getAlertUpgradeVersion", () => {
+ it("returns undefined when no ranges match", () => {
+ expect(
+ getAlertUpgradeVersion(
+ "v0.63.10",
+ createMockVersionInfo({
+ alert_upgrade_versions: [
+ entry({ min: "v0.63.0", fixed: "v0.63.10" }),
+ ],
+ }),
+ ),
+ ).toBeUndefined();
+ });
+
+ it("returns the matching range", () => {
+ const matching = entry({ min: "v0.63.0", fixed: "v0.63.10" });
+
+ expect(
+ getAlertUpgradeVersion(
+ "v0.63.5",
+ createMockVersionInfo({
+ alert_upgrade_versions: [matching],
+ }),
+ ),
+ ).toEqual(matching);
+ });
+
+ it("picks the matching range with the highest fixed when ranges overlap", () => {
+ const lowerFixed = entry({ min: "v0.63.0", fixed: "v0.63.10" });
+ const higherFixed = entry({ min: "v0.50.0", fixed: "v0.64.0" });
+
+ expect(
+ getAlertUpgradeVersion(
+ "v0.63.5",
+ createMockVersionInfo({
+ alert_upgrade_versions: [lowerFixed, higherFixed],
+ }),
+ ),
+ ).toEqual(higherFixed);
+ });
+
+ it("skips entries whose min/fixed cannot be compared to the version tag", () => {
+ const invalid = entry({ min: "not-a-version", fixed: "also-bad" });
+ const valid = entry({ min: "v0.63.0", fixed: "v0.63.10" });
+
+ expect(
+ getAlertUpgradeVersion(
+ "v0.63.5",
+ createMockVersionInfo({
+ alert_upgrade_versions: [invalid, valid],
+ }),
+ ),
+ ).toEqual(valid);
+ });
+
+ it("skips a matching-min range when compareVersions cannot parse fixed", () => {
+ const first = entry({ min: "v0.0.0", fixed: "v0.63.10" });
+ const second = entry({ min: "v0.0.0", fixed: "vLOCAL_DEV" });
+
+ expect(
+ getAlertUpgradeVersion(
+ "v0.50.0",
+ createMockVersionInfo({
+ alert_upgrade_versions: [first, second],
+ }),
+ ),
+ ).toEqual(first);
+ });
+});
diff --git a/frontend/src/metabase/nav/components/WhatsNewNotification/utils.ts b/frontend/src/metabase/nav/components/WhatsNewNotification/utils.ts
index 07529d5d9a5..9d7260117cf 100644
--- a/frontend/src/metabase/nav/components/WhatsNewNotification/utils.ts
+++ b/frontend/src/metabase/nav/components/WhatsNewNotification/utils.ts
@@ -47,6 +47,6 @@ export const getLatestEligibleReleaseNotes = ({
});
return eligibleVersions
- .sort((a, b) => compareVersions(b.version, a.version))
+ .sort((a, b) => compareVersions(b.version, a.version) ?? 0)
.find(({ announcement_url }) => announcement_url);
};
diff --git a/frontend/src/metabase/utils/version.ts b/frontend/src/metabase/utils/version.ts
index 5e7a078f305..ed1805cca2e 100644
--- a/frontend/src/metabase/utils/version.ts
+++ b/frontend/src/metabase/utils/version.ts
@@ -55,11 +55,6 @@ export const isLocalOrSnapshotVersion = (version: string) =>
* 0.0.9, 0.0.10-snapshot, 0.0.10-alpha1, 0.0.10-rc1, 0.0.10-rc2, 0.0.10-rc10
* 0.0.10, 0.1.0, 0.2.0, 0.10.0, 1.1.0
*/
-export function compareVersions(aVersion: string, bVersion: string): -1 | 0 | 1;
-export function compareVersions(
- aVersion: string | null | undefined,
- bVersion: string | null | undefined,
-): null;
export function compareVersions(
aVersion: string | null | undefined,
bVersion: string | null | undefined,
diff --git a/release/.gitignore b/release/.gitignore
index 5efaf1a6bd6..a0b5dd672bf 100644
--- a/release/.gitignore
+++ b/release/.gitignore
@@ -5,4 +5,6 @@ cache.json
dist/
version.properties
version-info.json
+version-info-ee.json
+version-info-out/
v*.html
diff --git a/release/alert-upgrade-versions.ts b/release/alert-upgrade-versions.ts
new file mode 100644
index 00000000000..569e6d7662a
--- /dev/null
+++ b/release/alert-upgrade-versions.ts
@@ -0,0 +1,374 @@
+import { mkdir, readFile, writeFile } from "node:fs/promises";
+import path from "node:path";
+import { stdin, stdout } from "node:process";
+import * as readline from "node:readline/promises";
+
+import { Octokit } from "@octokit/rest";
+import fetch from "node-fetch";
+
+import {
+ type AlertUpgradeRange,
+ type AlertUpgradeVersionsDiff,
+ advisoryToRanges,
+ assertValidAlertUpgradeVersions,
+ buildMessage,
+ diffAlertUpgradeVersions,
+ fetchAdvisory,
+ normalizeAdvisoryVersion,
+ parseGhsaId,
+ toEditionEntry,
+ upsertAlertUpgradeVersions,
+} from "./src/alert-upgrade-versions";
+import type { AlertUpgradeVersion, VersionInfoFile } from "./src/types";
+import {
+ getVersionInfoAwsEnv,
+ publishVersionInfoFiles,
+} from "./version-info-s3";
+
+const DEFAULT_OUT_DIR = "./version-info-out";
+const OSS_FILE = "version-info.json";
+const EE_FILE = "version-info-ee.json";
+const VERSION_INFO_PUBLIC_ORIGIN = "https://static.metabase.com";
+
+type GenerateArgs = {
+ command: "generate";
+ ghsa?: string;
+ min?: string;
+ fixed?: string;
+ id?: string;
+ message?: string;
+ out: string;
+};
+
+type PublishArgs = {
+ command: "publish";
+ out: string;
+};
+
+type CliArgs = GenerateArgs | PublishArgs;
+
+const USAGE = `Usage:
+ bun alert-upgrade-versions generate <GHSA id or URL> [--message "..."] [--out ${DEFAULT_OUT_DIR}]
+ bun alert-upgrade-versions generate --min x.63.0 --fixed x.63.10 [--id some-id] [--message "..."] [--out ${DEFAULT_OUT_DIR}]
+ bun alert-upgrade-versions publish [--out ${DEFAULT_OUT_DIR}]`;
+
+async function main() {
+ const args = parseCliArgs(process.argv.slice(2));
+
+ if (args.command === "generate") {
+ await generate(args);
+ return;
+ }
+
+ await publish(args);
+}
+
+async function generate(args: GenerateArgs) {
+ const { ranges, warnings, id, severity, url } = await resolveRanges(args);
+ const template = args.message;
+
+ await mkdir(args.out, { recursive: true });
+
+ for (const edition of ["oss", "ee"] as const) {
+ const remote = await fetchVersionInfoFile(edition);
+ const entries = ranges.map((range) =>
+ editionEntry({ range, edition, template, severity, url, id }),
+ );
+ const local = upsertAlertUpgradeVersions(remote, entries, id);
+ const fileName = edition === "ee" ? EE_FILE : OSS_FILE;
+ const filePath = path.join(args.out, fileName);
+ await writeFile(filePath, `${JSON.stringify(local, null, 2)}\n`);
+
+ const diff = diffAlertUpgradeVersions(remote, local);
+ printEditionSummary(edition, filePath, diff);
+ }
+
+ if (warnings.length > 0) {
+ console.log("\nParser warnings:");
+ for (const warning of warnings) {
+ console.log(` - ${warning}`);
+ }
+ }
+}
+
+async function publish(args: PublishArgs) {
+ const { bucket, distributionId } = getVersionInfoAwsEnv();
+ const ossPath = path.join(args.out, OSS_FILE);
+ const eePath = path.join(args.out, EE_FILE);
+
+ const localOss = await readVersionInfoFile(ossPath);
+ const localEe = await readVersionInfoFile(eePath);
+ assertValidAlertUpgradeVersions(localOss.alert_upgrade_versions ?? []);
+ assertValidAlertUpgradeVersions(localEe.alert_upgrade_versions ?? []);
+
+ const remoteOss = await fetchVersionInfoFile("oss");
+ const remoteEe = await fetchVersionInfoFile("ee");
+ const ossDiff = diffAlertUpgradeVersions(remoteOss, localOss);
+ const eeDiff = diffAlertUpgradeVersions(remoteEe, localEe);
+
+ if (ossDiff.otherKeysDiffer || eeDiff.otherKeysDiffer) {
+ throw new Error(
+ "Refusing to publish: a key other than alert_upgrade_versions changed vs remote. Re-run generate.",
+ );
+ }
+
+ if (!hasEntryChanges(ossDiff) && !hasEntryChanges(eeDiff)) {
+ throw new Error("No alert_upgrade_versions changes to publish");
+ }
+
+ console.log("OSS diff vs remote:");
+ printDiff(ossDiff);
+ console.log("\nEE diff vs remote:");
+ printDiff(eeDiff);
+
+ await confirmPublish();
+
+ await publishVersionInfoFiles({
+ files: [ossPath, eePath],
+ bucket,
+ distributionId,
+ });
+
+ console.log(`Published ${OSS_FILE} and ${EE_FILE} to s3://${bucket}`);
+}
+
+async function resolveRanges(args: GenerateArgs): Promise<{
+ ranges: AlertUpgradeRange[];
+ warnings: string[];
+ id?: string;
+ severity: string;
+ url: string;
+}> {
+ if (args.min || args.fixed) {
+ if (!args.min || !args.fixed) {
+ throw new Error("Both --min and --fixed are required for a manual range");
+ }
+ return {
+ ranges: [
+ {
+ min: normalizeAdvisoryVersion(args.min),
+ fixed: normalizeAdvisoryVersion(args.fixed),
+ },
+ ],
+ warnings: [],
+ id: args.id ?? (args.ghsa ? parseGhsaId(args.ghsa) : undefined),
+ severity: "critical",
+ url: "",
+ };
+ }
+
+ if (!args.ghsa) {
+ throw new Error(`Missing GHSA id or --min/--fixed\n\n${USAGE}`);
+ }
+
+ const ghsaId = parseGhsaId(args.ghsa);
+ const github = new Octokit({ auth: process.env.GITHUB_TOKEN });
+ const advisory = await fetchAdvisory({
+ github,
+ owner: process.env.GITHUB_OWNER ?? "metabase",
+ repo: process.env.GITHUB_REPO ?? "metabase",
+ ghsaId,
+ });
+ const { ranges, warnings } = advisoryToRanges(advisory);
+
+ return {
+ ranges,
+ warnings,
+ id: args.id ?? ghsaId,
+ severity: advisory.severity ?? "critical",
+ url: advisory.html_url,
+ };
+}
+
+function editionEntry({
+ range,
+ edition,
+ template,
+ severity,
+ url,
+ id,
+}: {
+ range: AlertUpgradeRange;
+ edition: "oss" | "ee";
+ template?: string;
+ severity: string;
+ url: string;
+ id?: string;
+}): AlertUpgradeVersion {
+ const { min, fixed } = toEditionEntry(range, edition, "");
+ const message = buildMessage({
+ template,
+ fixed: fixed.replace(/^v/, ""),
+ severity,
+ url,
+ });
+ return id ? { min, fixed, message, id } : { min, fixed, message };
+}
+
+async function fetchVersionInfoFile(
+ edition: "oss" | "ee",
+): Promise<VersionInfoFile> {
+ const fileName = edition === "ee" ? EE_FILE : OSS_FILE;
+ const url = `${VERSION_INFO_PUBLIC_ORIGIN}/${fileName}`;
+ const response = await fetch(url);
+ if (!response.ok) {
+ throw new Error(`Failed to fetch ${url}: ${response.status}`);
+ }
+ const payload: unknown = await response.json();
+ return parseVersionInfoFile(payload, url);
+}
+
+async function readVersionInfoFile(filePath: string): Promise<VersionInfoFile> {
+ const text = await readFile(filePath, "utf8");
+ const parsed: unknown = JSON.parse(text);
+ return parseVersionInfoFile(parsed, filePath);
+}
+
+function parseVersionInfoFile(value: unknown, label: string): VersionInfoFile {
+ if (typeof value !== "object" || value === null) {
+ throw new Error(`${label} is not a JSON object`);
+ }
+ if (!("latest" in value) || !("older" in value)) {
+ throw new Error(`${label} is missing latest/older`);
+ }
+ // Remote/local JSON is a VersionInfoFile; extra keys must be preserved for the publish guard.
+ return value as VersionInfoFile;
+}
+
+function printEditionSummary(
+ edition: "oss" | "ee",
+ filePath: string,
+ diff: AlertUpgradeVersionsDiff,
+) {
+ console.log(`\n${edition.toUpperCase()} wrote ${filePath}`);
+ printDiff(diff);
+}
+
+function printDiff(diff: AlertUpgradeVersionsDiff) {
+ printEntryList("added", diff.added);
+ printEntryList("removed", diff.removed);
+ if (diff.changed.length === 0) {
+ console.log(" changed: (none)");
+ } else {
+ console.log(" changed:");
+ for (const change of diff.changed) {
+ console.log(
+ ` - ${formatEntry(change.from)} -> ${formatEntry(change.to)}`,
+ );
+ }
+ }
+}
+
+function printEntryList(label: string, entries: AlertUpgradeVersion[]) {
+ if (entries.length === 0) {
+ console.log(` ${label}: (none)`);
+ return;
+ }
+ console.log(` ${label}:`);
+ for (const entry of entries) {
+ console.log(` - ${formatEntry(entry)}`);
+ }
+}
+
+function formatEntry(entry: AlertUpgradeVersion): string {
+ const id = entry.id ? ` id=${entry.id}` : "";
+ return `${entry.min} -> ${entry.fixed}${id}`;
+}
+
+function hasEntryChanges(diff: AlertUpgradeVersionsDiff): boolean {
+ return (
+ diff.added.length > 0 || diff.removed.length > 0 || diff.changed.length > 0
+ );
+}
+
+async function confirmPublish() {
+ if (!stdin.isTTY) {
+ throw new Error(
+ "Publish requires interactive confirmation (stdin is not a TTY)",
+ );
+ }
+
+ const rl = readline.createInterface({ input: stdin, output: stdout });
+ try {
+ const answer = await rl.question("Publish these files to S3? [y/N] ");
+ const normalized = answer.trim().toLowerCase();
+ if (normalized !== "y" && normalized !== "yes") {
+ throw new Error("Publish aborted");
+ }
+ } finally {
+ rl.close();
+ }
+}
+
+function parseCliArgs(argv: string[]): CliArgs {
+ if (argv.length === 0 || argv[0] === "--help" || argv[0] === "-h") {
+ throw new Error(USAGE);
+ }
+
+ const [command, ...rest] = argv;
+ if (command !== "generate" && command !== "publish") {
+ throw new Error(`Unknown command: ${command}\n\n${USAGE}`);
+ }
+
+ const tokens = [...rest];
+ const out = takeFlag(tokens, "--out") ?? DEFAULT_OUT_DIR;
+
+ if (command === "publish") {
+ rejectUnknownFlags(tokens, "publish");
+ return { command, out };
+ }
+
+ const message = takeFlag(tokens, "--message");
+ const min = takeFlag(tokens, "--min");
+ const fixed = takeFlag(tokens, "--fixed");
+ const id = takeFlag(tokens, "--id");
+ const positional = tokens.filter((token) => !token.startsWith("--"));
+ rejectUnknownFlags(
+ tokens.filter((token) => token.startsWith("--")),
+ "generate",
+ );
+
+ if (positional.length > 1) {
+ throw new Error(`Unexpected arguments: ${positional.slice(1).join(" ")}`);
+ }
+
+ return {
+ command,
+ ghsa: positional[0],
+ min,
+ fixed,
+ id,
+ message,
+ out,
+ };
+}
+
+function takeFlag(tokens: string[], name: string): string | undefined {
+ const index = tokens.indexOf(name);
+ if (index === -1) {
+ return undefined;
+ }
+ const value = tokens[index + 1];
+ if (!value || value.startsWith("--")) {
+ throw new Error(`${name} requires a value`);
+ }
+ tokens.splice(index, 2);
+ return value;
+}
+
+function rejectUnknownFlags(tokens: string[], command: string) {
+ const unknown = tokens.filter((token) => token.startsWith("--"));
+ if (unknown.length > 0) {
+ throw new Error(
+ `Unknown flag(s) for ${command}: ${unknown.join(", ")}\n\n${USAGE}`,
+ );
+ }
+}
+
+try {
+ await main();
+} catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ console.error(message);
+ process.exit(1);
+}
diff --git a/release/package.json b/release/package.json
index 230a1ecb5c7..dc35fb1e399 100644
--- a/release/package.json
+++ b/release/package.json
@@ -10,6 +10,7 @@
"scripts": {
"build": "esbuild src/index.ts --bundle --outfile=dist/index.cjs --platform=node --target=node16",
"generate-changelog": "bun generate-changelog.ts",
+ "alert-upgrade-versions": "bun alert-upgrade-versions.ts",
"format": "oxfmt --write",
"release-offline": "tsx release-offline.ts",
"test:unit": "jest --testPathPattern unit",
diff --git a/release/release-offline.ts b/release/release-offline.ts
index 6bc02dce968..63b52fdf523 100644
--- a/release/release-offline.ts
+++ b/release/release-offline.ts
@@ -22,6 +22,9 @@ import {
publishRelease,
versionRequirements,
} from "./src";
+import {
+ publishVersionInfoFiles,
+} from "./version-info-s3";
const {
GITHUB_TOKEN,
@@ -304,13 +307,11 @@ async function versionInfo() {
fs.writeFileSync(versionInfoName, JSON.stringify(newVersionInfo, null, 2));
- await $`aws s3 cp ${versionInfoName} s3://${AWS_S3_STATIC_BUCKET}/${versionInfoName}`.pipe(
- process.stdout,
- );
-
- await $`aws cloudfront create-invalidation \
- --distribution-id ${AWS_CLOUDFRONT_STATIC_ID} \
- --paths /${versionInfoName}`.pipe(process.stdout);
+ await publishVersionInfoFiles({
+ files: [versionInfoName],
+ bucket: AWS_S3_STATIC_BUCKET,
+ distributionId: AWS_CLOUDFRONT_STATIC_ID,
+ });
log(`✅ Published ${versionInfoName} to s3`);
}
diff --git a/release/src/alert-upgrade-versions.ts b/release/src/alert-upgrade-versions.ts
new file mode 100644
index 00000000000..8590e03ff92
--- /dev/null
+++ b/release/src/alert-upgrade-versions.ts
@@ -0,0 +1,453 @@
+import type {
+ AlertUpgradeVersion,
+ GithubProps,
+ VersionInfoFile,
+} from "./types";
+import {
+ getCanonicalVersion,
+ getOSSVersion,
+ isValidVersionString,
+ versionSort,
+} from "./version-helpers";
+
+const GHSA_RE = /GHSA-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}/i;
+const MIN_VERSION = "v0.0.0";
+
+export const DEFAULT_ALERT_MESSAGE_TEMPLATE =
+ "**This version of Metabase has a {severity} security vulnerability. Upgrade to {fixed} or later to receive important security updates. [View upgrade instructions](https://www.metabase.com/docs/latest/installation-and-operation/upgrading-metabase)**";
+
+export type AlertUpgradeRange = {
+ min: string;
+ fixed: string;
+};
+
+export type AdvisoryVulnerability = {
+ vulnerable_version_range: string | null;
+ patched_versions: string | null;
+};
+
+export type Advisory = {
+ id: string;
+ html_url: string;
+ severity: string | null;
+ summary: string | null;
+ vulnerabilities: AdvisoryVulnerability[];
+};
+
+export type AdvisoryGithub = {
+ rest: {
+ securityAdvisories: {
+ getRepositoryAdvisory: (params: {
+ owner: string;
+ repo: string;
+ ghsa_id: string;
+ }) => Promise<{ data: unknown }>;
+ };
+ };
+};
+
+export type AlertUpgradeVersionsDiff = {
+ added: AlertUpgradeVersion[];
+ removed: AlertUpgradeVersion[];
+ changed: Array<{ from: AlertUpgradeVersion; to: AlertUpgradeVersion }>;
+ otherKeysDiffer: boolean;
+};
+
+export function parseGhsaId(input: string): string {
+ const match = GHSA_RE.exec(input.trim());
+ if (!match) {
+ throw new Error(`Not a GHSA id or advisory URL: ${input}`);
+ }
+ return `GHSA-${match[0].slice(5).toLowerCase()}`;
+}
+
+export function normalizeAdvisoryVersion(raw: string): string {
+ const trimmed = raw.trim();
+ if (isValidVersionString(trimmed)) {
+ return getOSSVersion(trimmed);
+ }
+
+ const normalized = trimmed.replace(/^v/i, "").replace(/^(x|0|1)\./, "v0.");
+ if (isValidVersionString(normalized)) {
+ return normalized;
+ }
+
+ throw new Error(`Cannot normalize version: ${raw}`);
+}
+
+export async function fetchAdvisory({
+ github,
+ owner,
+ repo,
+ ghsaId,
+}: Pick<GithubProps, "owner" | "repo"> & {
+ github: AdvisoryGithub;
+ ghsaId: string;
+}): Promise<Advisory> {
+ const { data } = await github.rest.securityAdvisories.getRepositoryAdvisory({
+ owner,
+ repo,
+ ghsa_id: ghsaId,
+ });
+ return mapAdvisory(data);
+}
+
+export function advisoryToRanges(advisory: Advisory): {
+ ranges: AlertUpgradeRange[];
+ warnings: string[];
+} {
+ const warnings: string[] = [];
+ const parsed: AlertUpgradeRange[] = [];
+
+ if (advisory.vulnerabilities.length === 0) {
+ throw new Error(
+ "Advisory has no vulnerabilities; pass --min and --fixed instead",
+ );
+ }
+
+ for (const vulnerability of advisory.vulnerabilities) {
+ parsed.push(parseVulnerability(vulnerability, warnings));
+ }
+
+ const ranges = collapseRanges(parsed, warnings);
+ ranges.sort((a, b) => versionSort(a.min, b.min));
+ return { ranges, warnings };
+}
+
+export function toEditionEntry(
+ range: AlertUpgradeRange,
+ edition: "oss" | "ee",
+ message: string,
+): AlertUpgradeVersion {
+ return {
+ min: getCanonicalVersion(normalizeAdvisoryVersion(range.min), edition),
+ fixed: getCanonicalVersion(normalizeAdvisoryVersion(range.fixed), edition),
+ message,
+ };
+}
+
+export function buildMessage({
+ template = DEFAULT_ALERT_MESSAGE_TEMPLATE,
+ fixed,
+ severity,
+ url,
+}: {
+ template?: string;
+ fixed: string;
+ severity: string;
+ url: string;
+}): string {
+ return template
+ .replaceAll("{fixed}", fixed)
+ .replaceAll("{severity}", severity)
+ .replaceAll("{url}", url);
+}
+
+export function isAlertUpgradeVersion(
+ value: unknown,
+): value is AlertUpgradeVersion {
+ if (typeof value !== "object" || value === null) {
+ return false;
+ }
+ if (!("min" in value) || typeof value.min !== "string") {
+ return false;
+ }
+ if (!("fixed" in value) || typeof value.fixed !== "string") {
+ return false;
+ }
+ if (!("message" in value) || typeof value.message !== "string") {
+ return false;
+ }
+ if ("id" in value && value.id !== undefined && typeof value.id !== "string") {
+ return false;
+ }
+ return true;
+}
+
+export function assertValidAlertUpgradeVersions(
+ entries: unknown,
+): asserts entries is AlertUpgradeVersion[] {
+ if (!Array.isArray(entries)) {
+ throw new Error("alert_upgrade_versions must be an array");
+ }
+
+ for (const entry of entries) {
+ if (!isAlertUpgradeVersion(entry)) {
+ throw new Error(
+ `Invalid alert_upgrade_versions entry: ${JSON.stringify(entry)}`,
+ );
+ }
+ if (versionSort(entry.fixed, entry.min) <= 0) {
+ throw new Error(
+ `fixed must be greater than min: ${entry.min} -> ${entry.fixed}`,
+ );
+ }
+ }
+}
+
+export function upsertAlertUpgradeVersions(
+ versionInfo: VersionInfoFile,
+ entries: AlertUpgradeVersion[],
+ id?: string,
+): VersionInfoFile {
+ const existing = versionInfo.alert_upgrade_versions ?? [];
+ const kept = id ? existing.filter((entry) => entry.id !== id) : existing;
+ const alert_upgrade_versions = [...kept, ...entries].sort((a, b) =>
+ versionSort(a.min, b.min),
+ );
+
+ return {
+ ...versionInfo,
+ alert_upgrade_versions,
+ };
+}
+
+export function diffAlertUpgradeVersions(
+ remote: VersionInfoFile,
+ local: VersionInfoFile,
+): AlertUpgradeVersionsDiff {
+ const remoteEntries = remote.alert_upgrade_versions ?? [];
+ const localEntries = local.alert_upgrade_versions ?? [];
+
+ const remoteByKey = new Map(
+ remoteEntries.map((entry) => [entryIdentity(entry), entry]),
+ );
+ const localByKey = new Map(
+ localEntries.map((entry) => [entryIdentity(entry), entry]),
+ );
+
+ const added: AlertUpgradeVersion[] = [];
+ const removed: AlertUpgradeVersion[] = [];
+ const changed: Array<{ from: AlertUpgradeVersion; to: AlertUpgradeVersion }> =
+ [];
+
+ for (const [key, localEntry] of localByKey) {
+ const remoteEntry = remoteByKey.get(key);
+ if (!remoteEntry) {
+ added.push(localEntry);
+ } else if (remoteEntry.message !== localEntry.message) {
+ changed.push({ from: remoteEntry, to: localEntry });
+ }
+ }
+
+ for (const [key, remoteEntry] of remoteByKey) {
+ if (!localByKey.has(key)) {
+ removed.push(remoteEntry);
+ }
+ }
+
+ return {
+ added,
+ removed,
+ changed,
+ otherKeysDiffer:
+ stringifyWithoutAlertVersions(remote) !==
+ stringifyWithoutAlertVersions(local),
+ };
+}
+
+function mapAdvisory(data: unknown): Advisory {
+ if (typeof data !== "object" || data === null) {
+ throw new Error("Invalid advisory response");
+ }
+
+ if (!("ghsa_id" in data) || typeof data.ghsa_id !== "string") {
+ throw new Error("Advisory response missing ghsa_id");
+ }
+ if (!("html_url" in data) || typeof data.html_url !== "string") {
+ throw new Error("Advisory response missing html_url");
+ }
+
+ const severity =
+ "severity" in data && typeof data.severity === "string"
+ ? data.severity
+ : null;
+ const summary =
+ "summary" in data && typeof data.summary === "string" ? data.summary : null;
+
+ const rawVulnerabilities =
+ "vulnerabilities" in data && Array.isArray(data.vulnerabilities)
+ ? data.vulnerabilities
+ : [];
+
+ return {
+ id: data.ghsa_id,
+ html_url: data.html_url,
+ severity,
+ summary,
+ vulnerabilities: rawVulnerabilities.map(mapVulnerability),
+ };
+}
+
+function mapVulnerability(value: unknown): AdvisoryVulnerability {
+ if (typeof value !== "object" || value === null) {
+ return { vulnerable_version_range: null, patched_versions: null };
+ }
+
+ const vulnerable_version_range =
+ "vulnerable_version_range" in value &&
+ typeof value.vulnerable_version_range === "string"
+ ? value.vulnerable_version_range
+ : null;
+
+ return {
+ vulnerable_version_range,
+ patched_versions: readPatchedVersions(value),
+ };
+}
+
+function readPatchedVersions(value: object): string | null {
+ if (
+ "patched_versions" in value &&
+ typeof value.patched_versions === "string" &&
+ value.patched_versions.trim() !== ""
+ ) {
+ return value.patched_versions;
+ }
+
+ if (
+ "first_patched_version" in value &&
+ typeof value.first_patched_version === "object" &&
+ value.first_patched_version !== null &&
+ "identifier" in value.first_patched_version &&
+ typeof value.first_patched_version.identifier === "string" &&
+ value.first_patched_version.identifier.trim() !== ""
+ ) {
+ return value.first_patched_version.identifier;
+ }
+
+ return null;
+}
+
+const RANGE_OPS = [">=", "<=", ">", "<", "="] as const;
+type RangeOp = (typeof RANGE_OPS)[number];
+
+type RangeBound = {
+ op: RangeOp;
+ version: string;
+};
+
+function isRangeOp(value: string | undefined): value is RangeOp {
+ return value !== undefined && RANGE_OPS.some((op) => op === value);
+}
+
+function parseVulnerability(
+ vulnerability: AdvisoryVulnerability,
+ warnings: string[],
+): AlertUpgradeRange {
+ const rangeText = vulnerability.vulnerable_version_range;
+ if (!rangeText) {
+ throw new Error(
+ "Vulnerability is missing vulnerable_version_range; pass --min and --fixed instead",
+ );
+ }
+
+ const bounds = parseRangeBounds(rangeText);
+ const hasInclusiveUpper = bounds.some(
+ (bound) => bound.op === "<=" || bound.op === "=",
+ );
+ const hasExclusiveUpper = bounds.some((bound) => bound.op === "<");
+ const hasUnsupportedLower = bounds.some((bound) => bound.op === ">");
+
+ if (hasUnsupportedLower) {
+ throw new Error(
+ `Unsupported version range "${rangeText}"; pass --min and --fixed instead`,
+ );
+ }
+
+ const lower = bounds.find((bound) => bound.op === ">=");
+ const exclusiveUpper = bounds.find((bound) => bound.op === "<");
+ const exact = bounds.find((bound) => bound.op === "=");
+
+ const patched = vulnerability.patched_versions
+ ? normalizeAdvisoryVersion(
+ stripPatchedPrefix(vulnerability.patched_versions),
+ )
+ : null;
+
+ if (hasInclusiveUpper && !hasExclusiveUpper && !patched) {
+ throw new Error(
+ `Range "${rangeText}" uses <= or = without a patched version; pass --min and --fixed instead`,
+ );
+ }
+
+ const min = exact
+ ? normalizeAdvisoryVersion(exact.version)
+ : lower
+ ? normalizeAdvisoryVersion(lower.version)
+ : MIN_VERSION;
+
+ const exclusiveFixed = exclusiveUpper
+ ? normalizeAdvisoryVersion(exclusiveUpper.version)
+ : null;
+ const fixed = patched ?? exclusiveFixed;
+
+ if (!fixed) {
+ throw new Error(
+ `Range "${rangeText}" has no exclusive upper bound or patched version; pass --min and --fixed instead`,
+ );
+ }
+
+ if (patched && exclusiveFixed && patched !== exclusiveFixed) {
+ warnings.push(
+ `patched_versions ${patched} disagrees with < bound ${exclusiveFixed} in "${rangeText}"; using patched version`,
+ );
+ }
+
+ return { min, fixed };
+}
+
+function parseRangeBounds(rangeText: string): RangeBound[] {
+ const parts = rangeText
+ .split(",")
+ .map((part) => part.trim())
+ .filter((part) => part.length > 0);
+
+ return parts.map((part) => {
+ const match = /^(>=|<=|>|<|=)\s*(.+)$/.exec(part);
+ if (!match || !isRangeOp(match[1])) {
+ throw new Error(
+ `Cannot parse version range "${rangeText}"; pass --min and --fixed instead`,
+ );
+ }
+ return { op: match[1], version: match[2].trim() };
+ });
+}
+
+function stripPatchedPrefix(patched: string): string {
+ return patched.replace(/^(>=|>)\s*/, "").trim();
+}
+
+function collapseRanges(
+ ranges: AlertUpgradeRange[],
+ warnings: string[],
+): AlertUpgradeRange[] {
+ const lowestMinByFixed = new Map<string, string>();
+
+ for (const range of ranges) {
+ const existingMin = lowestMinByFixed.get(range.fixed);
+ if (!existingMin || versionSort(range.min, existingMin) < 0) {
+ lowestMinByFixed.set(range.fixed, range.min);
+ }
+ }
+
+ if (lowestMinByFixed.size < ranges.length) {
+ warnings.push(
+ `Collapsed ${ranges.length} vulnerability ranges into ${lowestMinByFixed.size} by taking the lowest min for each fixed version`,
+ );
+ }
+
+ return [...lowestMinByFixed.entries()].map(([fixed, min]) => ({
+ min,
+ fixed,
+ }));
+}
+
+function entryIdentity(entry: AlertUpgradeVersion): string {
+ return [entry.id ?? "", entry.min, entry.fixed].join("\0");
+}
+
+function stringifyWithoutAlertVersions(file: VersionInfoFile): string {
+ const { alert_upgrade_versions: _ignored, ...rest } = file;
+ return JSON.stringify(rest);
+}
diff --git a/release/src/alert-upgrade-versions.unit.spec.ts b/release/src/alert-upgrade-versions.unit.spec.ts
new file mode 100644
index 00000000000..23f9c5dc9a1
--- /dev/null
+++ b/release/src/alert-upgrade-versions.unit.spec.ts
@@ -0,0 +1,495 @@
+import {
+ type Advisory,
+ type AdvisoryGithub,
+ DEFAULT_ALERT_MESSAGE_TEMPLATE,
+ advisoryToRanges,
+ assertValidAlertUpgradeVersions,
+ buildMessage,
+ diffAlertUpgradeVersions,
+ fetchAdvisory,
+ isAlertUpgradeVersion,
+ normalizeAdvisoryVersion,
+ parseGhsaId,
+ toEditionEntry,
+ upsertAlertUpgradeVersions,
+} from "./alert-upgrade-versions";
+import type { VersionInfoFile } from "./types";
+
+const sampleVersionInfo = (): VersionInfoFile => ({
+ latest: {
+ version: "v0.63.10",
+ released: "2026-01-01",
+ patch: true,
+ highlights: [],
+ },
+ older: [],
+});
+
+const ghsaAdvisory = (): Advisory => ({
+ id: "GHSA-r495-55cx-fjh7",
+ html_url:
+ "https://github.com/metabase/metabase/security/advisories/GHSA-r495-55cx-fjh7",
+ severity: "critical",
+ summary: "Multiple vulnerabilities",
+ vulnerabilities: [
+ {
+ vulnerable_version_range: ">= x.58.0, < x.58.28",
+ patched_versions: "x.58.28",
+ },
+ {
+ vulnerable_version_range: ">= x.59.0, < x.59.25",
+ patched_versions: "x.59.25",
+ },
+ {
+ vulnerable_version_range: ">= x.63.0, < x.63.10",
+ patched_versions: "x.63.10",
+ },
+ {
+ vulnerable_version_range: "< x.58.28",
+ patched_versions: "x.58.28",
+ },
+ ],
+});
+
+describe("alert-upgrade-versions", () => {
+ describe("parseGhsaId", () => {
+ it("accepts a bare GHSA id", () => {
+ expect(parseGhsaId("GHSA-r495-55cx-fjh7")).toEqual("GHSA-r495-55cx-fjh7");
+ });
+
+ it("accepts a repository advisory URL", () => {
+ expect(
+ parseGhsaId(
+ "https://github.com/metabase/metabase/security/advisories/GHSA-r495-55cx-fjh7",
+ ),
+ ).toEqual("GHSA-r495-55cx-fjh7");
+ });
+
+ it("accepts the github.com/advisories URL", () => {
+ expect(
+ parseGhsaId("https://github.com/advisories/GHSA-r495-55cx-fjh7"),
+ ).toEqual("GHSA-r495-55cx-fjh7");
+ });
+
+ it("normalizes case", () => {
+ expect(parseGhsaId("ghsa-R495-55CX-FJH7")).toEqual("GHSA-r495-55cx-fjh7");
+ });
+
+ it("rejects non-GHSA input", () => {
+ expect(() => parseGhsaId("CVE-2026-1234")).toThrow(
+ /Not a GHSA id or advisory URL/,
+ );
+ });
+ });
+
+ describe("normalizeAdvisoryVersion", () => {
+ it("normalizes x. / 0. / 1. / v0. / v1. prefixes to v0.", () => {
+ expect(normalizeAdvisoryVersion("x.63.10")).toEqual("v0.63.10");
+ expect(normalizeAdvisoryVersion("0.63.10")).toEqual("v0.63.10");
+ expect(normalizeAdvisoryVersion("1.63.10")).toEqual("v0.63.10");
+ expect(normalizeAdvisoryVersion("v0.63.10")).toEqual("v0.63.10");
+ expect(normalizeAdvisoryVersion("v1.63.10")).toEqual("v0.63.10");
+ });
+
+ it("rejects unparseable versions", () => {
+ expect(() => normalizeAdvisoryVersion("latest")).toThrow(
+ /Cannot normalize version/,
+ );
+ });
+ });
+
+ describe("fetchAdvisory", () => {
+ it("maps a repository advisory response", async () => {
+ const getRepositoryAdvisory = jest.fn().mockResolvedValue({
+ data: {
+ ghsa_id: "GHSA-r495-55cx-fjh7",
+ html_url:
+ "https://github.com/metabase/metabase/security/advisories/GHSA-r495-55cx-fjh7",
+ severity: "critical",
+ summary: "Multiple vulnerabilities",
+ vulnerabilities: [
+ {
+ vulnerable_version_range: ">= x.63.0, < x.63.10",
+ patched_versions: "x.63.10",
+ },
+ ],
+ },
+ });
+ const github: AdvisoryGithub = {
+ rest: { securityAdvisories: { getRepositoryAdvisory } },
+ };
+
+ await expect(
+ fetchAdvisory({
+ github,
+ owner: "metabase",
+ repo: "metabase",
+ ghsaId: "GHSA-r495-55cx-fjh7",
+ }),
+ ).resolves.toEqual({
+ id: "GHSA-r495-55cx-fjh7",
+ html_url:
+ "https://github.com/metabase/metabase/security/advisories/GHSA-r495-55cx-fjh7",
+ severity: "critical",
+ summary: "Multiple vulnerabilities",
+ vulnerabilities: [
+ {
+ vulnerable_version_range: ">= x.63.0, < x.63.10",
+ patched_versions: "x.63.10",
+ },
+ ],
+ });
+
+ expect(getRepositoryAdvisory).toHaveBeenCalledWith({
+ owner: "metabase",
+ repo: "metabase",
+ ghsa_id: "GHSA-r495-55cx-fjh7",
+ });
+ });
+
+ it("falls back to first_patched_version.identifier", async () => {
+ const github: AdvisoryGithub = {
+ rest: {
+ securityAdvisories: {
+ getRepositoryAdvisory: jest.fn().mockResolvedValue({
+ data: {
+ ghsa_id: "GHSA-aaaa-bbbb-cccc",
+ html_url: "https://github.com/advisories/GHSA-aaaa-bbbb-cccc",
+ severity: "high",
+ summary: "example",
+ vulnerabilities: [
+ {
+ vulnerable_version_range: "< 0.63.10",
+ first_patched_version: { identifier: "0.63.10" },
+ },
+ ],
+ },
+ }),
+ },
+ },
+ };
+
+ const advisory = await fetchAdvisory({
+ github,
+ owner: "metabase",
+ repo: "metabase",
+ ghsaId: "GHSA-aaaa-bbbb-cccc",
+ });
+
+ expect(advisory.vulnerabilities[0].patched_versions).toEqual("0.63.10");
+ });
+ });
+
+ describe("advisoryToRanges", () => {
+ it("parses GHSA-style ranges and collapses the catch-all row", () => {
+ const { ranges, warnings } = advisoryToRanges(ghsaAdvisory());
+
+ expect(ranges).toEqual([
+ { min: "v0.0.0", fixed: "v0.58.28" },
+ { min: "v0.59.0", fixed: "v0.59.25" },
+ { min: "v0.63.0", fixed: "v0.63.10" },
+ ]);
+ expect(warnings).toEqual([
+ expect.stringMatching(/Collapsed 4 vulnerability ranges into 3/),
+ ]);
+ });
+
+ it("uses < bound when patched_versions is absent", () => {
+ const { ranges } = advisoryToRanges({
+ ...ghsaAdvisory(),
+ vulnerabilities: [
+ {
+ vulnerable_version_range: ">= x.63.0, < x.63.10",
+ patched_versions: null,
+ },
+ ],
+ });
+
+ expect(ranges).toEqual([{ min: "v0.63.0", fixed: "v0.63.10" }]);
+ });
+
+ it("warns when patched_versions disagrees with the < bound", () => {
+ const { ranges, warnings } = advisoryToRanges({
+ ...ghsaAdvisory(),
+ vulnerabilities: [
+ {
+ vulnerable_version_range: ">= x.63.0, < x.63.9",
+ patched_versions: "x.63.10",
+ },
+ ],
+ });
+
+ expect(ranges).toEqual([{ min: "v0.63.0", fixed: "v0.63.10" }]);
+ expect(warnings).toEqual([
+ expect.stringMatching(/disagrees with < bound v0\.63\.9/),
+ ]);
+ });
+
+ it("collapses oss/ee prefix duplicates to one edition-agnostic range", () => {
+ const { ranges } = advisoryToRanges({
+ ...ghsaAdvisory(),
+ vulnerabilities: [
+ {
+ vulnerable_version_range: ">= 0.63.0, < 0.63.10",
+ patched_versions: "0.63.10",
+ },
+ {
+ vulnerable_version_range: ">= 1.63.0, < 1.63.10",
+ patched_versions: "1.63.10",
+ },
+ ],
+ });
+
+ expect(ranges).toEqual([{ min: "v0.63.0", fixed: "v0.63.10" }]);
+ });
+
+ it("errors on <= / = ranges without a patched version", () => {
+ expect(() =>
+ advisoryToRanges({
+ ...ghsaAdvisory(),
+ vulnerabilities: [
+ {
+ vulnerable_version_range: "<= x.63.9",
+ patched_versions: null,
+ },
+ ],
+ }),
+ ).toThrow(/pass --min and --fixed instead/);
+
+ expect(() =>
+ advisoryToRanges({
+ ...ghsaAdvisory(),
+ vulnerabilities: [
+ {
+ vulnerable_version_range: "= x.63.9",
+ patched_versions: null,
+ },
+ ],
+ }),
+ ).toThrow(/pass --min and --fixed instead/);
+ });
+
+ it("uses patched version for <= ranges when present", () => {
+ const { ranges } = advisoryToRanges({
+ ...ghsaAdvisory(),
+ vulnerabilities: [
+ {
+ vulnerable_version_range: ">= x.63.0, <= x.63.9",
+ patched_versions: "x.63.10",
+ },
+ ],
+ });
+
+ expect(ranges).toEqual([{ min: "v0.63.0", fixed: "v0.63.10" }]);
+ });
+
+ it("errors when there are no vulnerabilities", () => {
+ expect(() =>
+ advisoryToRanges({ ...ghsaAdvisory(), vulnerabilities: [] }),
+ ).toThrow(/pass --min and --fixed instead/);
+ });
+ });
+
+ describe("toEditionEntry", () => {
+ it("applies v0. / v1. prefixes", () => {
+ const range = { min: "x.63.0", fixed: "x.63.10" };
+
+ expect(toEditionEntry(range, "oss", "upgrade")).toEqual({
+ min: "v0.63.0",
+ fixed: "v0.63.10",
+ message: "upgrade",
+ });
+ expect(toEditionEntry(range, "ee", "upgrade")).toEqual({
+ min: "v1.63.0",
+ fixed: "v1.63.10",
+ message: "upgrade",
+ });
+ });
+ });
+
+ describe("buildMessage", () => {
+ it("substitutes fixed, severity, and url in the default template", () => {
+ const message = buildMessage({
+ fixed: "1.63.10",
+ severity: "critical",
+ url: "https://example.com",
+ });
+
+ expect(message).toContain("critical security vulnerability");
+ expect(message).toContain("Upgrade to 1.63.10 or later");
+ expect(message).not.toContain("{fixed}");
+ expect(message).not.toContain("{severity}");
+ });
+
+ it("uses --message as a template override", () => {
+ expect(
+ buildMessage({
+ template: "See {url} and upgrade to {fixed} ({severity})",
+ fixed: "0.63.10",
+ severity: "high",
+ url: "https://ghsa.example",
+ }),
+ ).toEqual("See https://ghsa.example and upgrade to 0.63.10 (high)");
+ });
+
+ it("matches the UpgradeBanner stub wording", () => {
+ expect(DEFAULT_ALERT_MESSAGE_TEMPLATE).toContain(
+ "View upgrade instructions",
+ );
+ expect(DEFAULT_ALERT_MESSAGE_TEMPLATE).toContain("{fixed}");
+ expect(DEFAULT_ALERT_MESSAGE_TEMPLATE).toContain("{severity}");
+ });
+ });
+
+ describe("upsertAlertUpgradeVersions", () => {
+ it("appends without an id and sorts by min", () => {
+ const first = upsertAlertUpgradeVersions(sampleVersionInfo(), [
+ {
+ min: "v0.63.0",
+ fixed: "v0.63.10",
+ message: "later",
+ },
+ ]);
+ const result = upsertAlertUpgradeVersions(first, [
+ {
+ min: "v0.58.0",
+ fixed: "v0.58.28",
+ message: "earlier",
+ },
+ ]);
+
+ expect(result.alert_upgrade_versions?.map((entry) => entry.min)).toEqual([
+ "v0.58.0",
+ "v0.63.0",
+ ]);
+ expect(result.latest).toEqual(sampleVersionInfo().latest);
+ });
+
+ it("replaces existing entries with the same id", () => {
+ const withOld = upsertAlertUpgradeVersions(
+ sampleVersionInfo(),
+ [
+ {
+ min: "v0.63.0",
+ fixed: "v0.63.9",
+ message: "old",
+ id: "GHSA-r495-55cx-fjh7",
+ },
+ {
+ min: "v0.50.0",
+ fixed: "v0.50.1",
+ message: "other",
+ id: "other-id",
+ },
+ ],
+ "GHSA-r495-55cx-fjh7",
+ );
+
+ const result = upsertAlertUpgradeVersions(
+ withOld,
+ [
+ {
+ min: "v0.63.0",
+ fixed: "v0.63.10",
+ message: "new",
+ id: "GHSA-r495-55cx-fjh7",
+ },
+ ],
+ "GHSA-r495-55cx-fjh7",
+ );
+
+ expect(result.alert_upgrade_versions).toEqual([
+ {
+ min: "v0.50.0",
+ fixed: "v0.50.1",
+ message: "other",
+ id: "other-id",
+ },
+ {
+ min: "v0.63.0",
+ fixed: "v0.63.10",
+ message: "new",
+ id: "GHSA-r495-55cx-fjh7",
+ },
+ ]);
+ });
+ });
+
+ describe("diffAlertUpgradeVersions", () => {
+ it("reports added, removed, and changed entries", () => {
+ const remote: VersionInfoFile = {
+ ...sampleVersionInfo(),
+ alert_upgrade_versions: [
+ { min: "v0.58.0", fixed: "v0.58.28", message: "keep" },
+ { min: "v0.59.0", fixed: "v0.59.25", message: "old" },
+ { min: "v0.60.0", fixed: "v0.60.1", message: "gone" },
+ ],
+ };
+ const local: VersionInfoFile = {
+ ...sampleVersionInfo(),
+ alert_upgrade_versions: [
+ { min: "v0.58.0", fixed: "v0.58.28", message: "keep" },
+ { min: "v0.59.0", fixed: "v0.59.25", message: "new" },
+ { min: "v0.63.0", fixed: "v0.63.10", message: "added" },
+ ],
+ };
+
+ expect(diffAlertUpgradeVersions(remote, local)).toEqual({
+ added: [{ min: "v0.63.0", fixed: "v0.63.10", message: "added" }],
+ removed: [{ min: "v0.60.0", fixed: "v0.60.1", message: "gone" }],
+ changed: [
+ {
+ from: { min: "v0.59.0", fixed: "v0.59.25", message: "old" },
+ to: { min: "v0.59.0", fixed: "v0.59.25", message: "new" },
+ },
+ ],
+ otherKeysDiffer: false,
+ });
+ });
+
+ it("flags when a non-alert_upgrade_versions key differs", () => {
+ const remote = sampleVersionInfo();
+ const local: VersionInfoFile = {
+ ...remote,
+ latest: { ...remote.latest, version: "v0.64.0" },
+ };
+
+ expect(diffAlertUpgradeVersions(remote, local).otherKeysDiffer).toBe(
+ true,
+ );
+ });
+ });
+
+ describe("isAlertUpgradeVersion / assertValidAlertUpgradeVersions", () => {
+ it("accepts optional id", () => {
+ expect(
+ isAlertUpgradeVersion({
+ min: "v0.63.0",
+ fixed: "v0.63.10",
+ message: "go",
+ }),
+ ).toBe(true);
+ expect(
+ isAlertUpgradeVersion({
+ min: "v0.63.0",
+ fixed: "v0.63.10",
+ message: "go",
+ id: "GHSA-r495-55cx-fjh7",
+ }),
+ ).toBe(true);
+ });
+
+ it("rejects fixed <= min", () => {
+ expect(() =>
+ assertValidAlertUpgradeVersions([
+ { min: "v0.63.10", fixed: "v0.63.10", message: "same" },
+ ]),
+ ).toThrow(/fixed must be greater than min/);
+ expect(() =>
+ assertValidAlertUpgradeVersions([
+ { min: "v0.63.10", fixed: "v0.63.0", message: "backwards" },
+ ]),
+ ).toThrow(/fixed must be greater than min/);
+ });
+ });
+});
diff --git a/release/src/index.ts b/release/src/index.ts
index d8301ed8bfe..645d5a1a40e 100644
--- a/release/src/index.ts
+++ b/release/src/index.ts
@@ -1,3 +1,4 @@
+export * from "./alert-upgrade-versions";
export * from "./backports";
export * from "./github";
export * from "./linked-issues";
diff --git a/release/src/types.ts b/release/src/types.ts
index 16f5a78b2ef..41f49a1d0c6 100644
--- a/release/src/types.ts
+++ b/release/src/types.ts
@@ -40,12 +40,20 @@ export interface MajorVersionSupport {
eol: string;
}
+export interface AlertUpgradeVersion {
+ min: string;
+ fixed: string;
+ message: string;
+ id?: string;
+}
+
export interface VersionInfoFile {
latest: VersionInfo;
beta?: VersionInfo;
nightly?: VersionInfo;
older: VersionInfo[];
major_version_support?: MajorVersionSupport[];
+ alert_upgrade_versions?: AlertUpgradeVersion[];
}
export type Issue = {
diff --git a/release/version-info-s3.ts b/release/version-info-s3.ts
new file mode 100644
index 00000000000..0598144bc39
--- /dev/null
+++ b/release/version-info-s3.ts
@@ -0,0 +1,43 @@
+import path from "node:path";
+
+import { $ } from "zx";
+
+$.verbose = false;
+
+export function getVersionInfoAwsEnv(): {
+ bucket: string;
+ distributionId: string;
+} {
+ const bucket = process.env.AWS_S3_STATIC_BUCKET;
+ const distributionId = process.env.AWS_CLOUDFRONT_STATIC_ID;
+ const accessKeyId = process.env.AWS_ACCESS_KEY_ID;
+ const secretAccessKey = process.env.AWS_SECRET_ACCESS_KEY;
+
+ if (!bucket || !distributionId || !accessKeyId || !secretAccessKey) {
+ throw new Error(
+ "You must provide AWS_S3_STATIC_BUCKET, AWS_CLOUDFRONT_STATIC_ID, AWS_ACCESS_KEY_ID, and AWS_SECRET_ACCESS_KEY",
+ );
+ }
+
+ return { bucket, distributionId };
+}
+
+export async function publishVersionInfoFiles({
+ files,
+ bucket,
+ distributionId,
+}: {
+ files: readonly string[];
+ bucket: string;
+ distributionId: string;
+}): Promise<void> {
+ for (const file of files) {
+ const name = path.basename(file);
+ await $`aws s3 cp ${file} s3://${bucket}/${name}`.pipe(process.stdout);
+ }
+
+ const cloudFrontPaths = files.map((file) => `/${path.basename(file)}`);
+ await $`aws cloudfront create-invalidation --distribution-id ${distributionId} --paths ${cloudFrontPaths}`.pipe(
+ process.stdout,
+ );
+}
diff --git a/src/metabase/version/task/upgrade_checks.clj b/src/metabase/version/task/upgrade_checks.clj
index 453f7af2d36..d24d1932afa 100644
--- a/src/metabase/version/task/upgrade_checks.clj
+++ b/src/metabase/version/task/upgrade_checks.clj
@@ -46,14 +46,13 @@
(def ^:private trigger-key "metabase.task.upgrade-checks.trigger")
(defn- rand-hours
- "Give a random hour plus the hour 12 hours away, i.e. one of [0 12], [1 13], [2 14], etc"
+ "Give a random hour plus the hours 6, 12, and 18 hours away, i.e. one of [0 6 12 18], [1 7 13 19], etc"
[]
- (let [hour-1 (rand-int 24)
- hour-2 (mod (+ hour-1 12) 24)]
- [hour-1 hour-2]))
+ (let [hour-1 (rand-int 24)]
+ (mapv #(mod (+ hour-1 %) 24) [0 6 12 18])))
(defmethod task/init! ::CheckForNewVersions [_]
- (let [[rand-hour-1 rand-hour-2] (rand-hours)
+ (let [[h1 h2 h3 h4] (rand-hours)
rand-minute (rand-int 60)
job (jobs/build
(jobs/of-type CheckForNewVersions)
@@ -62,6 +61,6 @@
(triggers/with-identity (triggers/key trigger-key))
(triggers/start-now)
(triggers/with-schedule
- ;; run twice a day
- (cron/cron-schedule (format "0 %d %d,%d * * ? *" rand-minute rand-hour-1 rand-hour-2))))]
+ ;; run every 6 hours, at a random hour/minute offset to spread load
+ (cron/cron-schedule (format "0 %d %d,%d,%d,%d * * ? *" rand-minute h1 h2 h3 h4))))]
(task/schedule-task! job trigger)))