Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support force updating to latest version #2414

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions packages/snaps-controllers/coverage.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"branches": 91.44,
"functions": 96.73,
"lines": 97.86,
"statements": 97.53
"branches": 91.54,
"functions": 96.76,
"lines": 97.87,
"statements": 97.55
}
53 changes: 53 additions & 0 deletions packages/snaps-controllers/src/snaps/SnapController.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1605,7 +1605,7 @@
});

// This isn't stable in CI unfortunately
it.skip('throws if the Snap is terminated while executing', async () => {

Check warning on line 1608 in packages/snaps-controllers/src/snaps/SnapController.test.tsx

View workflow job for this annotation

GitHub Actions / Build, lint, and test / Lint (@metamask/snaps-controllers)

Disabled test
const { manifest, sourceCode, svgIcon } =
await getMockSnapFilesWithUpdatedChecksum({
sourceCode: `
Expand Down Expand Up @@ -6439,6 +6439,59 @@
controller.destroy();
});

it('updates to latest when latest version is specified', async () => {
const { manifest } = await getMockSnapFilesWithUpdatedChecksum({
manifest: getSnapManifest({
version: '1.1.0' as SemVerVersion,
}),
});

const location = new LoopbackLocation({
manifest: manifest.result,
});

location.resolveVersion.mockImplementation(
async () => '1.1.0' as SemVerRange,
);

const messenger = getSnapControllerMessenger();
const controller = getSnapController(
getSnapControllerOptions({
messenger,
state: {
snaps: getPersistedSnapsState(),
},
detectSnapLocation: loopbackDetect(location),
}),
);

const result = await controller.installSnaps(MOCK_ORIGIN, {
[MOCK_SNAP_ID]: { version: 'latest' },
});

const newSnapTruncated = controller.getTruncated(MOCK_SNAP_ID);

const newSnap = controller.get(MOCK_SNAP_ID);

expect(result[MOCK_SNAP_ID]).toStrictEqual(newSnapTruncated);
expect(newSnap?.version).toBe('1.1.0');
expect(newSnap?.versionHistory).toStrictEqual([
{
origin: MOCK_ORIGIN,
version: '1.0.0',
date: expect.any(Number),
},
{
origin: MOCK_ORIGIN,
version: '1.1.0',
date: expect.any(Number),
},
]);
expect(newSnap?.status).toBe(SnapStatus.Running);

controller.destroy();
});

it('requests approval for new and already approved permissions and revoke unused permissions', async () => {
const rootMessenger = getControllerMessenger();
const messenger = getSnapControllerMessenger(rootMessenger);
Expand Down
9 changes: 6 additions & 3 deletions packages/snaps-controllers/src/snaps/SnapController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2129,14 +2129,17 @@ export class SnapController extends BaseController<
// Existing snaps may need to be updated, unless they should be re-installed (e.g. local snaps)
// Everything else is treated as an install
const isUpdate = this.has(snapId) && !location.shouldAlwaysReload;
const forceLatest = rawVersion === 'latest';
const resolvedVersion =
forceLatest && isUpdate ? await location.resolveVersion() : version;

if (isUpdate && this.#isValidUpdate(snapId, version)) {
if (isUpdate && this.#isValidUpdate(snapId, resolvedVersion)) {
const existingSnap = this.getExpect(snapId);
pendingUpdates.push({ snapId, oldVersion: existingSnap.version });
let rollbackSnapshot = this.#getRollbackSnapshot(snapId);
if (rollbackSnapshot === undefined) {
rollbackSnapshot = this.#createRollbackSnapshot(snapId);
rollbackSnapshot.newVersion = version;
rollbackSnapshot.newVersion = resolvedVersion;
} else {
throw new Error('This snap is already being updated.');
}
Expand All @@ -2148,7 +2151,7 @@ export class SnapController extends BaseController<
origin,
snapId,
location,
version,
resolvedVersion,
);
}

Expand Down
6 changes: 6 additions & 0 deletions packages/snaps-controllers/src/snaps/location/http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@ describe('HttpLocation', () => {
expect(bundle.toString()).toStrictEqual(DEFAULT_SNAP_BUNDLE);
});

it('resolves to *', async () => {
expect(
await new HttpLocation(new URL('http://foo.bar/foo/')).resolveVersion(),
).toBe('*');
});

it('throws if fetch fails', async () => {
const base = 'http://foo.bar';

Expand Down
5 changes: 5 additions & 0 deletions packages/snaps-controllers/src/snaps/location/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
normalizeRelative,
parseJson,
} from '@metamask/snaps-utils';
import type { SemVerRange } from '@metamask/utils';
import { assert, assertStruct } from '@metamask/utils';

import type { SnapLocation } from './location';
Expand Down Expand Up @@ -109,6 +110,10 @@ export class HttpLocation implements SnapLocation {
return this.fetch(relativePath);
}

async resolveVersion(): Promise<SemVerRange> {
return '*' as SemVerRange;
}

get root(): URL {
return new URL(this.url);
}
Expand Down
8 changes: 8 additions & 0 deletions packages/snaps-controllers/src/snaps/location/local.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,14 @@ describe('LocalLocation', () => {
).toBe(true);
});

it('resolves to *', async () => {
expect(
await new LocalLocation(
new URL('local:http://localhost'),
).resolveVersion(),
).toBe('*');
});

it.each([
[
'local:http://localhost/foo',
Expand Down
5 changes: 5 additions & 0 deletions packages/snaps-controllers/src/snaps/location/local.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { SnapManifest, VirtualFile } from '@metamask/snaps-utils';
import { LocalSnapIdStruct, SnapIdPrefixes } from '@metamask/snaps-utils';
import type { SemVerRange } from '@metamask/utils';
import { assert, assertStruct } from '@metamask/utils';

import type { HttpOptions } from './http';
Expand Down Expand Up @@ -33,6 +34,10 @@ export class LocalLocation implements SnapLocation {
return convertCanonical(await this.#http.fetch(path));
}

async resolveVersion(): Promise<SemVerRange> {
return '*' as SemVerRange;
}

get shouldAlwaysReload() {
return true;
}
Expand Down
2 changes: 2 additions & 0 deletions packages/snaps-controllers/src/snaps/location/location.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ export interface SnapLocation {
manifest(): Promise<VirtualFile<SnapManifest>>;
fetch(path: string): Promise<VirtualFile>;

resolveVersion(): Promise<SemVerRange>;

readonly shouldAlwaysReload?: boolean;
}

Expand Down
37 changes: 28 additions & 9 deletions packages/snaps-controllers/src/snaps/location/npm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,11 @@ export interface NpmOptions {
export abstract class BaseNpmLocation implements SnapLocation {
protected readonly meta: NpmMeta;

#resolvedPackage: {
tarballURL: string;
targetVersion: SemVerVersion;
} | null = null;

#validatedManifest?: VirtualFile<SnapManifest>;

#files?: Map<string, VirtualFile>;
Expand Down Expand Up @@ -165,18 +170,32 @@ export abstract class BaseNpmLocation implements SnapLocation {
return this.meta.requestedRange;
}

async resolveVersion(): Promise<SemVerRange> {
if (!this.#resolvedPackage) {
const resolvedVersion = await this.meta.resolveVersion(
this.meta.requestedRange,
);

const resolved = await resolveNpmVersion(
this.meta.packageName,
resolvedVersion,
this.meta.registry,
this.meta.fetch,
);

this.#resolvedPackage = resolved;
}

return this.#resolvedPackage.targetVersion as unknown as SemVerRange;
}

async #lazyInit() {
assert(this.#files === undefined);
const resolvedVersion = await this.meta.resolveVersion(
this.meta.requestedRange,
);

const { tarballURL, targetVersion } = await resolveNpmVersion(
this.meta.packageName,
resolvedVersion,
this.meta.registry,
this.meta.fetch,
);
const targetVersion = await this.resolveVersion();

// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const { tarballURL } = this.#resolvedPackage!;

if (!isValidUrl(tarballURL) || !tarballURL.toString().endsWith('.tgz')) {
throw new Error(
Expand Down
4 changes: 4 additions & 0 deletions packages/snaps-controllers/src/test-utils/location.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,10 @@ export class LoopbackLocation implements SnapLocation {
);
return file;
});

resolveVersion = jest.fn(async () => {
return '*' as SemVerRange;
});
/* eslint-enable @typescript-eslint/require-await */

get shouldAlwaysReload() {
Expand Down
Loading