Skip to content

Commit

Permalink
fix: add SCA check and warning with link to activate it (#136)
Browse files Browse the repository at this point in the history
Signed-off-by: Denis Golovin <[email protected]>
  • Loading branch information
dgolovin authored Apr 30, 2024
1 parent 1855ab0 commit 8a1dc61
Show file tree
Hide file tree
Showing 2 changed files with 97 additions and 4 deletions.
77 changes: 73 additions & 4 deletions src/extension.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
* SPDX-License-Identifier: Apache-2.0
***********************************************************************/

import { beforeEach, expect, suite, test, vi } from 'vitest';
import { activate } from './extension';
import { beforeEach, afterEach, expect, suite, test, vi } from 'vitest';
import * as extension from './extension';
import {
AuthenticationGetSessionOptions,
TelemetryLogger,
Expand All @@ -28,6 +28,7 @@ import {
import { authentication, commands } from '@podman-desktop/api';
import * as podmanCli from './podman-cli';
import { ExtensionTelemetryLogger } from './telemetry';
import { OrganizationService } from '@redhat-developer/rhsm-client';

vi.mock('@podman-desktop/api', async () => {
return {
Expand Down Expand Up @@ -104,11 +105,15 @@ function createExtContext(): ExtensionContext {

beforeEach(() => {
vi.resetAllMocks();
activate(createExtContext());
});

afterEach(() => {
extension.deactivate();
});

suite('extension activation', () => {
test('register commands declared in package.json', async () => {
await extension.activate(createExtContext());
expect(commands.registerCommand).toBeCalledTimes(4);
expect(commands.registerCommand).toBeCalledWith('redhat.authentication.signin', expect.anything());
expect(commands.registerCommand).toBeCalledWith('redhat.authentication.navigate.settings', expect.anything());
Expand Down Expand Up @@ -171,7 +176,7 @@ suite('signin command telemetry reports', () => {
},
);
vi.spyOn(podmanCli, 'isPodmanMachineRunning').mockReturnValue(false);
await activate(createExtContext());
await extension.activate(createExtContext());
expect(commandFunctionCopy!).toBeDefined();
await commandFunctionCopy!();
expect(authentication.onDidChangeSessions).toBeCalled();
Expand All @@ -181,4 +186,68 @@ suite('signin command telemetry reports', () => {
errorIn: 'subscription-activation',
});
});

test('unsuccessful login when simple content access is not enabled for account', async () => {
const logSpy = vi.spyOn(ExtensionTelemetryLogger, 'logUsage').mockImplementation(() => {
return;
});
let notificationCallback: (event: any) => Promise<any>;
let session: AuthenticationSession;
vi.mocked(authentication.onDidChangeSessions).mockImplementation((callback: (event: any) => Promise<any>) => {
notificationCallback = callback;
return {
dispose: vi.fn(),
};
});
vi.mocked(authentication.getSession).mockImplementation(
async (
_p1: string,
_p2: string[],
options: AuthenticationGetSessionOptions | undefined,
): Promise<AuthenticationSession | undefined> => {
if (session) {
return Promise.resolve(session);
}
if (options?.createIfNone) {
session = {
id: '1',
accessToken: 'token',
scopes: ['scope1', 'scope2'],
account: {
id: 'accountId',
label: 'label',
},
};
await notificationCallback({
provider: {
id: 'redhat.authentication-provider',
},
});
}
return;
},
);
let commandFunctionCopy: () => Promise<void>;
vi.mocked(commands.registerCommand).mockImplementation(
(commandId: string, commandFunction: () => Promise<void>) => {
if (commandId === 'redhat.authentication.signin') {
commandFunctionCopy = commandFunction;
}
return {
dispose: vi.fn(),
};
},
);
vi.spyOn(podmanCli, 'isPodmanMachineRunning').mockReturnValue(true);
vi.spyOn(OrganizationService.prototype, 'checkOrgScaCapability').mockResolvedValue({ body: {} });
await extension.activate(createExtContext());
expect(commandFunctionCopy!).toBeDefined();
await commandFunctionCopy!();
expect(authentication.onDidChangeSessions).toBeCalled();
expect(logSpy).toBeCalledWith('signin', {
successful: false,
error: 'Error: SCA is not enabled and message closed',
errorIn: 'subscription-activation',
});
});
});
24 changes: 24 additions & 0 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,16 @@ async function createOrReuseActivationKey() {
await runSubscriptionManagerRegister('podman-desktop', accessTokenJson.organization.id);
}

async function isSimpleContentAccessEnabled(): Promise<boolean> {
const currentSession = await signIntoRedHatDeveloperAccount();
const client = new SubscriptionManagerClient({
BASE: 'https://console.redhat.com/api/rhsm/v2',
TOKEN: currentSession!.accessToken,
});
const response = await client.organization.checkOrgScaCapability();
return response.body && response.body.simpleContentAccess === 'enabled';
}

async function isSubscriptionManagerInstalled(): Promise<boolean> {
const exitCode = await runSubscriptionManager();
return exitCode === 0;
Expand Down Expand Up @@ -279,6 +289,19 @@ async function configureRegistryAndActivateSubscription() {
}
return;
} else {
if (!(await isSimpleContentAccessEnabled())) {
const choice = await extensionApi.window.showInformationMessage(
'Simple Content Access (SCA) is not enabled for your Red Hat account. Please enable it and try again.',
'Close',
'Enable SCA',
);
if (choice === 'Enable SCA') {
extensionApi.env.openExternal(extensionApi.Uri.parse('https://access.redhat.com/management'));
throw new Error('SCA is not enabled and subscription management page requested');
}
throw new Error('SCA is not enabled and message closed');
}

if (!(await isSubscriptionManagerInstalled())) {
await installSubscriptionManger();
await runStopPodmanMachine();
Expand Down Expand Up @@ -415,4 +438,5 @@ export async function activate(context: extensionApi.ExtensionContext): Promise<

export function deactivate(): void {
console.log('stopping redhat-authentication extension');
currentSession = undefined;
}

0 comments on commit 8a1dc61

Please sign in to comment.