refactor: 💡 window postmessage pattern -> contextbridge boundary api (#3167)

* refactor: 💡 postmessage pattern -> contextbridge boundary api

* refactor: 💡 use sinon stub for boundary api mock test helper

* refactor: 💡 updated tests

* refactor: 💡 renamed boundary mock api

* chore: 🤖 addressed feedback

* refactor: 💡 updated context bridge name, added nested objects
This commit is contained in:
Priya Patel authored and GitHub committed 2026-03-13 15:14:38 -07:00
1 parent eba17d3c71
commit 392e49bf49
45 files changed
+744 -1062

No files matched your search

@@ -11,7 +11,7 @@ import { underscore } from '@ember/string';
/**
* This test helper can be used to help setup your sinon stubs in your tests.
* Must be called after setupMirage.
* Must be called after setupMirage and setupDesktopContextBridgeApiMock in tests.
*
* ```js
* import setupStubs from 'api/test-support/handlers/cache-daemon-search';
@@ -19,14 +19,15 @@ import { underscore } from '@ember/string';
* module('Acceptance | my test', function(hooks) {
* setupApplicationTest(hooks);
* setupMirage(hooks);
* setupDesktopContextBridgeApiMock(hooks);
* setupStubs(hooks);
*
* // add your actual tests here
* });
* ```
*
* This will setup a stub for the IPC service and include helper methods to
* help setup what the cache daemon search command returns.
* This will setup a stub for window.desktop.daemon.searchCacheDaemon and include
* helper methods to help setup what the cache daemon search command returns.
*
* @module Test Helpers
* @public
@@ -35,9 +36,6 @@ export default function setupStubs(hooks) {
let stubTypes = [];
hooks.beforeEach(function () {
const ipcService = this.owner.lookup('service:ipc');
this.ipcStub = sinon.stub(ipcService, 'invoke');
/**
* We aim to still use mirage data when stubbing out the cache daemon
* search. However, the handler expects the search data to be raw JSON from
@@ -56,34 +54,32 @@ export default function setupStubs(hooks) {
stubTypes = types;
types.forEach((type, i) => {
this.ipcStub
.withArgs('searchCacheDaemon')
.onCall(i)
.callsFake(() => {
let models;
let resourceName;
if (typeOf(type) === 'object') {
models = type.func();
resourceName = type.resource;
} else {
models = this.server.schema[type].all().models;
resourceName = type;
}
this.searchCacheDaemonStub.onCall(i).callsFake(() => {
let models;
let resourceName;
if (typeOf(type) === 'object') {
models = type.func();
resourceName = type.resource;
} else {
models = this.server.schema[type].all().models;
resourceName = type;
}
return {
[underscore(resourceNames[singularize(resourceName)])]:
models.map((model) => {
// Use internal serializer to serialize the model correctly
// according to our mirage serializers
const modelData =
this.server.serializerOrRegistry.serialize(model);
return {
[underscore(resourceNames[singularize(resourceName)])]: models.map(
(model) => {
// Use internal serializer to serialize the model correctly
// according to our mirage serializers
const modelData =
this.server.serializerOrRegistry.serialize(model);
// Serialize the data properly to standard JSON as that is what
// we're expecting from the cache daemon response
return JSON.parse(JSON.stringify(modelData));
}),
};
});
// Serialize the data properly to standard JSON as that is what
// we're expecting from the cache daemon response
return JSON.parse(JSON.stringify(modelData));
},
),
};
});
});
};
});
@@ -91,22 +87,19 @@ export default function setupStubs(hooks) {
hooks.afterEach(function () {
// Verify the number of mocks we set up match with how
// many times the cache daemon was called with
sinon.assert.callCount(
this.ipcStub.withArgs('searchCacheDaemon'),
stubTypes.length,
);
sinon.assert.callCount(this.searchCacheDaemonStub, stubTypes.length);
stubTypes.forEach((type, i) => {
// Assert that the stub was called with the resource we're trying to mock
// so we don't mistakenly mock the wrong resource
const ipcCall = this.ipcStub.withArgs('searchCacheDaemon').getCall(i);
const call = this.searchCacheDaemonStub.getCall(i);
let resource = type;
if (typeOf(type) === 'object') {
resource = type.resource;
}
const mappedResourceName = resourceNames[singularize(resource)];
sinon.assert.match(ipcCall.args[1], { resource: mappedResourceName });
sinon.assert.match(call.args[0], { resource: mappedResourceName });
});
sinon.restore();
@@ -59,7 +59,6 @@ const fetchControllerData = async (context, next) => {
*/
export default class CacheDaemonHandler {
@service session;
@service ipc;
constructor(context) {
setOwner(this, getOwner(context));
@@ -70,9 +69,8 @@ export default class CacheDaemonHandler {
case 'query': {
const { store, data } = context.request;
const { type, query, options: { pushToStore = true } = {} } = data;
const isCacheDaemonRunning = await this.ipc.invoke(
'isCacheDaemonRunning',
);
const isCacheDaemonRunning =
await window.desktop.daemon.isCacheDaemonRunning();
// eslint-disable-next-line no-unused-vars
let { recursive, scope_id, page, pageSize, ...remainingQuery } = query;
@@ -119,23 +117,19 @@ export default class CacheDaemonHandler {
let cacheDaemonResults = {};
try {
cacheDaemonResults = await this.ipc.invoke(
'searchCacheDaemon',
remainingQuery,
);
cacheDaemonResults =
await window.desktop.daemon.searchCacheDaemon(remainingQuery);
} catch (e) {
// If we got a 403, most likely the cache daemon was restarted and our token is no longer valid
// I'm not sure if we can get a 401 since we always send a token but we'll handle it in the same way
if (e.statusCode === 403 || e.statusCode === 401) {
try {
await this.ipc.invoke('addTokenToDaemons', {
await window.desktop.daemon.addTokenToDaemons({
tokenId: auth_token_id,
token,
});
cacheDaemonResults = await this.ipc.invoke(
'searchCacheDaemon',
remainingQuery,
);
cacheDaemonResults =
await window.desktop.daemon.searchCacheDaemon(remainingQuery);
} catch (err) {
// If it fails again just fall back to fetching controller data
__electronLog?.error(
+4 -4
View File
@@ -7,7 +7,7 @@ import { createServer, Response } from 'miragejs';
import { authHandler, deauthHandler } from './route-handlers/auth';
import { targetHandler } from './route-handlers/target';
import { pickRandomStatusString } from './factories/session';
import initializeMockIPC from './scenarios/ipc';
import initializeMockDesktopContextBridgeAPI from './scenarios/ipc/desktop-context-bridge-api';
import makeBooleanFilter from './helpers/bexpr-filter';
import { faker } from '@faker-js/faker';
import { asciicasts } from './data/asciicasts';
@@ -66,7 +66,7 @@ import workerSerializer from './serializers/worker';
// mirage scenarios (alphabetical)
import defaultScenario from './scenarios/default';
import ipcScenario from './scenarios/ipc';
import desktopContextBridgeApiScenario from './scenarios/ipc/desktop-context-bridge-api';
// mirage factories (alphabetical)
import accountFactory from './factories/account';
@@ -103,7 +103,7 @@ export default function (mirageConfig) {
scenarios: {
default: defaultScenario,
ipcScenario: ipcScenario,
desktopContextBridgeApiScenario: desktopContextBridgeApiScenario,
},
factories: {
@@ -190,7 +190,7 @@ export default function (mirageConfig) {
// Only routes are defined here
function routes() {
initializeMockIPC(this, environmentConfig);
initializeMockDesktopContextBridgeAPI(this, environmentConfig);
this.passthrough();
// make this `http://localhost:8080`, for example, if your API is on a different server
-296
View File
@@ -1,296 +0,0 @@
/**
* Copyright IBM Corp. 2021, 2026
* SPDX-License-Identifier: BUSL-1.1
*/
import { faker } from '@faker-js/faker';
export default function initializeMockIPC(server, config) {
const isTesting = config.environment === 'test';
/**
* We strive to make this application runnable in a regular web browser, since
* it is a convenient environment for development and testing. But only an
* Electron environment has true IPC. Outside of Electron or with mirage,
* we mock the handling of the message-based IPC requests originating from the
* renderer (the Ember app).
*/
class MockIPC {
async invoke(method, payload) {
return await this[method](payload);
}
clusterUrl = null;
checkOS() {
return {
isLinux: false,
isMac: true,
isWindows: false,
};
}
getClusterUrl() {
return this.clusterUrl;
}
setClusterUrl(clusterUrl) {
this.clusterUrl = clusterUrl;
return this.clusterUrl;
}
resetClusterUrl() {
this.clusterUrl = null;
}
openExternal(href) {
window.open(href);
}
cliExists() {
return true;
}
/**
* Creates a new session instance associated with the specified target.
* @param connect_details
* @param
*/
connect({ target_id }) {
const target = server.schema.targets.find(target_id);
const { scope, type } = target;
const newSession = server.schema.sessions.create({
scope,
target,
userId: 'authenticateduser',
type,
created_time: new Date().toISOString(),
expiration_time: faker.date.soon(),
});
const decoded = {
key1: 'value 1',
key2: true,
key3: 'test',
};
const raw = btoa(JSON.stringify(decoded));
return {
address: window.location.hostname,
port: faker.internet.port(),
protocol: type,
session_id: newSession.id,
credentials: [
{
credential_source: {
id: 'clvlt_4cvscMTl0N',
name: 'Credential Library 1',
description: 'Source Description',
credential_store_id: 'csvlt_Q1HFGt7Jpm',
type: 'vault',
},
secret: {
raw: btoa('just-a-random-string'),
},
},
{
credential_source: {
id: 'clvlt_4cvscMTl0N',
name: 'Credential Library 0',
description: 'Source Description',
credential_store_id: 'csvlt_Q1HFGt7Jpm',
type: 'vault-generic',
},
secret: {
raw: 'eyJhcnJheSI6WyJvbmUiLCJ0d28iLCJ0aHJlZSIsIm9uZSIsInR3byIsInRocmVlIiwib25lIiwidHdvIiwidGhyZWUiLCJvbmUiLCJ0d28iLCJ0aHJlZSJdLCJuZXN0ZWQiOnsiYm9vbCI6dHJ1ZSwibG9uZyI6IjEyMjM1MzQ1NmFzZWRmYTQzd3J0ZjIzNGYyM2FzZGdmYXNkZnJnYXdzZWZhd3NlZnNkZjQiLCJzZWNlcmV0Ijoic28gbmVzdGVkIn0sInRlc3QiOiJwaHJhc2UifQ',
decoded: {
data: {
backslash: 'password\\withslash\\',
backslash1: 'password\\fwithslash\\f',
password: '123',
username: 'test',
email: {
address: 'test.com',
},
},
metadata: {
created_time: '2024-04-12T18:38:36.226715555Z',
custom_metadata: null,
deletion_time: '',
destroyed: false,
version: 8,
},
},
},
},
{
credential_source: {
id: 'credjson_7cKBbBEkC3',
credential_store_id: 'csst_yzlsot2pum',
type: 'static',
credential_type: 'json',
},
secret: {
raw: 'eyJhcnJheSI6WyJvbmUiLCJ0d28iLCJ0aHJlZSIsIm9uZSIsInR3byIsInRocmVlIiwib25lIiwidHdvIiwidGhyZWUiLCJvbmUiLCJ0d28iLCJ0aHJlZSJdLCJuZXN0ZWQiOnsiYm9vbCI6dHJ1ZSwibG9uZyI6IjEyMjM1MzQ1NmFzZWRmYTQzd3J0ZjIzNGYyM2FzZGdmYXNkZnJnYXdzZWZhd3NlZnNkZjQiLCJzZWNlcmV0Ijoic28gbmVzdGVkIn0sInRlc3QiOiJwaHJhc2UifQ==',
decoded: {
secret_key: 'QWERTYUIOP',
secret_access_key: 'QWERT.YUIOP234567890',
nested_secret: {
session_token: 'ZXCVBNMLKJHGFDSAQWERTYUIOP0987654321',
complex_nest: {
blackslash: 'password\\withslash\\',
hash: 'qazxswedcvfrtgbnjhyujm.1234567890',
},
},
},
},
credential: {
secret_key: 'QWERTYUIOP',
secret_access_key: 'QWERT.YUIOP234567890',
nested_secret: {
session_token: 'ZXCVBNMLKJHGFDSAQWERTYUIOP0987654321',
complex_nest: {
hash: 'qazxswedcvfrtgbnjhyujm.1234567890',
},
},
},
},
{
credential_source: {
id: 'clvlt_4cvscMTl0N',
name: 'Credential Library 2',
description: 'Source Description',
credential_store_id: 'csvlt_Q1HFGt7Jpm',
type: 'vault',
},
secret: {
raw,
decoded,
},
},
{
credential_source: {
id: 'clvlt_9KWscxpcY7',
name: 'Credential Library 3',
description: 'Source Description',
credential_store_id: 'csvlt_Q1HFGt7Jpm',
type: 'vault',
},
secret: {
raw: btoa('just-a-random-string'),
},
},
{
credential_source: {
id: 'clvlt_9KWscxpcY7',
name: 'Credential Library 4',
description: 'Source Description',
credential_store_id: 'csvlt_Q1HFGt7Jpm',
type: 'vault',
},
secret: {
raw,
decoded,
},
},
],
};
}
/**
* Check for window chrome on MacOS
*/
hasMacOSChrome() {
return true;
}
/**
* Check for OS chrome state
*/
showWindowActions() {
if (navigator.userAgent.includes('Mac')) {
return false;
}
return true;
}
/**
* Do nothing when attempting to minimize, toggle fullscreen,
* and close a browser window
* * Do nothing when canceling a session invokes the stop method
*/
minimizeWindow() {}
closeWindow() {}
toggleFullscreenWindow() {}
stop() {}
checkCommand() {
return faker.system.filePath();
}
addTokenToDaemons() {}
searchCacheDaemon() {}
isCacheDaemonRunning() {
return false;
}
isClientAgentRunning() {
return false;
}
cacheDaemonStatus() {
return { version: 'Boundary v1.0.0' };
}
getCliVersion() {
return { versionNumber: '1.0.0' };
}
getDesktopVersion() {
return { desktopVersion: '1.0.0' };
}
getLogLevel() {
return 'info';
}
getLogPath() {
return '~/.config/Boundary/logs/desktop-client.log';
}
setLogLevel() {}
clientAgentStatus() {
return { version: '0.0.1-dev', status: 'running' };
}
pauseClientAgent() {}
resumeClientAgent() {}
hasRunningSessions() {}
stopAll() {}
getRdpClients() {
return ['windows-app', 'none', 'mstsc'];
}
getPreferredRdpClient() {
return 'windows-app';
}
getRecommendedRdpClient() {
return {
name: 'windows-app',
link: 'https://apps.apple.com/us/app/windows-app/id1295203466',
};
}
setPreferredRdpClient() {}
launchRdpClient() {}
}
/**
* Establishes a mock IPC handler, which mimics the behavior of the Electron
* main process, and routes messages to it in a way similar to our
* preload.js script.
*
* Initializes mock IPC only in a non-testing context and when mirage is turned on.
* We mock certain functions even in electron (e.g. hasMacOSChrome) when running
* locally which will force a certain appearance regardless of platform
*/
if (config.mirage?.enabled && !isTesting) {
const mockIPC = new MockIPC();
window.addEventListener('message', async function (event) {
if (event.origin !== window.location.origin) return;
const { method, payload } = event?.data ?? {};
if (method) {
const response = await mockIPC.invoke(method, payload);
event.ports[0].postMessage(response);
}
});
}
}
@@ -0,0 +1,318 @@
/**
* Copyright IBM Corp. 2021, 2026
* SPDX-License-Identifier: BUSL-1.1
*/
import { faker } from '@faker-js/faker';
export default function initializeMockDesktopContextBridgeAPI(server, config) {
const isTesting = config.environment === 'test';
/**
* We strive to make this application runnable in a regular web browser, since
* it is a convenient environment for development and testing. But only an
* Electron environment has the desktop API exposed via contextBridge.
* Outside of Electron or with mirage, we mock the desktop API object to
* simulate the Electron preload script's exposed API.
*/
class MockDesktopContextBridgeAPI {
clusterUrl = null;
cluster = {
getClusterUrl: () => {
return this.clusterUrl;
},
setClusterUrl: (clusterUrl) => {
this.clusterUrl = clusterUrl;
return this.clusterUrl;
},
resetClusterUrl: () => {
this.clusterUrl = null;
},
};
system = {
checkOS: () => {
return {
isLinux: false,
isMac: true,
isWindows: false,
};
},
openExternal: (href) => {
window.open(href);
},
cliExists: () => {
return true;
},
checkCommand: () => {
return faker.system.filePath();
},
getCliVersion: () => {
return { versionNumber: '1.0.0' };
},
getDesktopVersion: () => {
return { desktopVersion: '1.0.0' };
},
};
session = {
/**
* Creates a new session instance associated with the specified target.
* @param connect_details
* @param
*/
connectSession: ({ target_id }) => {
const target = server.schema.targets.find(target_id);
const { scope, type } = target;
const newSession = server.schema.sessions.create({
scope,
target,
userId: 'authenticateduser',
type,
created_time: new Date().toISOString(),
expiration_time: faker.date.soon(),
});
const decoded = {
key1: 'value 1',
key2: true,
key3: 'test',
};
const raw = btoa(JSON.stringify(decoded));
return {
address: window.location.hostname,
port: faker.internet.port(),
protocol: type,
session_id: newSession.id,
credentials: [
{
credential_source: {
id: 'clvlt_4cvscMTl0N',
name: 'Credential Library 1',
description: 'Source Description',
credential_store_id: 'csvlt_Q1HFGt7Jpm',
type: 'vault',
},
secret: {
raw: btoa('just-a-random-string'),
},
},
{
credential_source: {
id: 'clvlt_4cvscMTl0N',
name: 'Credential Library 0',
description: 'Source Description',
credential_store_id: 'csvlt_Q1HFGt7Jpm',
type: 'vault-generic',
},
secret: {
raw: 'eyJhcnJheSI6WyJvbmUiLCJ0d28iLCJ0aHJlZSIsIm9uZSIsInR3byIsInRocmVlIiwib25lIiwidHdvIiwidGhyZWUiLCJvbmUiLCJ0d28iLCJ0aHJlZSJdLCJuZXN0ZWQiOnsiYm9vbCI6dHJ1ZSwibG9uZyI6IjEyMjM1MzQ1NmFzZWRmYTQzd3J0ZjIzNGYyM2FzZGdmYXNkZnJnYXdzZWZhd3NlZnNkZjQiLCJzZWNlcmV0Ijoic28gbmVzdGVkIn0sInRlc3QiOiJwaHJhc2UifQ',
decoded: {
data: {
backslash: 'password\\withslash\\',
backslash1: 'password\\fwithslash\\f',
password: '123',
username: 'test',
email: {
address: 'test.com',
},
},
metadata: {
created_time: '2024-04-12T18:38:36.226715555Z',
custom_metadata: null,
deletion_time: '',
destroyed: false,
version: 8,
},
},
},
},
{
credential_source: {
id: 'credjson_7cKBbBEkC3',
credential_store_id: 'csst_yzlsot2pum',
type: 'static',
credential_type: 'json',
},
secret: {
raw: 'eyJhcnJheSI6WyJvbmUiLCJ0d28iLCJ0aHJlZSIsIm9uZSIsInR3byIsInRocmVlIiwib25lIiwidHdvIiwidGhyZWUiLCJvbmUiLCJ0d28iLCJ0aHJlZSJdLCJuZXN0ZWQiOnsiYm9vbCI6dHJ1ZSwibG9uZyI6IjEyMjM1MzQ1NmFzZWRmYTQzd3J0ZjIzNGYyM2FzZGdmYXNkZnJnYXdzZWZhd3NlZnNkZjQiLCJzZWNlcmV0Ijoic28gbmVzdGVkIn0sInRlc3QiOiJwaHJhc2UifQ==',
decoded: {
secret_key: 'QWERTYUIOP',
secret_access_key: 'QWERT.YUIOP234567890',
nested_secret: {
session_token: 'ZXCVBNMLKJHGFDSAQWERTYUIOP0987654321',
complex_nest: {
blackslash: 'password\\withslash\\',
hash: 'qazxswedcvfrtgbnjhyujm.1234567890',
},
},
},
},
credential: {
secret_key: 'QWERTYUIOP',
secret_access_key: 'QWERT.YUIOP234567890',
nested_secret: {
session_token: 'ZXCVBNMLKJHGFDSAQWERTYUIOP0987654321',
complex_nest: {
hash: 'qazxswedcvfrtgbnjhyujm.1234567890',
},
},
},
},
{
credential_source: {
id: 'clvlt_4cvscMTl0N',
name: 'Credential Library 2',
description: 'Source Description',
credential_store_id: 'csvlt_Q1HFGt7Jpm',
type: 'vault',
},
secret: {
raw,
decoded,
},
},
{
credential_source: {
id: 'clvlt_9KWscxpcY7',
name: 'Credential Library 3',
description: 'Source Description',
credential_store_id: 'csvlt_Q1HFGt7Jpm',
type: 'vault',
},
secret: {
raw: btoa('just-a-random-string'),
},
},
{
credential_source: {
id: 'clvlt_9KWscxpcY7',
name: 'Credential Library 4',
description: 'Source Description',
credential_store_id: 'csvlt_Q1HFGt7Jpm',
type: 'vault',
},
secret: {
raw,
decoded,
},
},
],
};
},
stopSession: () => {},
hasRunningSessions: () => {},
stopAllSessions: () => {},
};
windowAction = {
/**
* Check for window chrome on MacOS
*/
hasMacOSChrome: () => {
return true;
},
/**
* Check for OS chrome state
*/
showWindowActions: () => {
if (navigator.userAgent.includes('Mac')) {
return false;
}
return true;
},
/**
* Do nothing when attempting to minimize, toggle fullscreen,
* and close a browser window
*/
minimizeWindow: () => {},
closeWindow: () => {},
toggleFullscreenWindow: () => {},
focusWindow: () => {},
};
daemon = {
addTokenToDaemons: () => {},
searchCacheDaemon: () => {},
isCacheDaemonRunning: () => {
return false;
},
cacheDaemonStatus: () => {
return { version: 'Boundary v1.0.0' };
},
};
clientAgent = {
getClientAgentSessions: () => {},
isClientAgentRunning: () => {
return false;
},
clientAgentStatus: () => {
return { version: '0.0.1-dev', status: 'running' };
},
pauseClientAgent: () => {},
resumeClientAgent: () => {},
};
logging = {
getLogLevel: () => {
return 'info';
},
getLogPath: () => {
return '~/.config/Boundary/logs/desktop-client.log';
},
setLogLevel: () => {},
};
rdp = {
getRdpClients: () => {
return ['windows-app', 'none', 'mstsc'];
},
getPreferredRdpClient: () => {
return 'windows-app';
},
getRecommendedRdpClient: () => {
return {
name: 'windows-app',
link: 'https://apps.apple.com/us/app/windows-app/id1295203466',
};
},
setPreferredRdpClient: () => {},
launchRdpClient: () => {},
};
app = {
onAppQuit: (callback) => {
const listenerCallback = () => callback();
window.addEventListener('onAppQuit', listenerCallback);
return () => {
window.removeEventListener('onAppQuit', listenerCallback);
};
},
};
}
/**
* Initializes mock only in a non-testing environment and when mirage is enabled.
* In browser mode, creates the API. In Electron mode, the API already exists
* from contextBridge and we can't override it
*/
if (config.mirage?.enabled && !isTesting) {
const desktopContextBridgeAPIMock = new MockDesktopContextBridgeAPI();
// Only in browser mode, we create the desktop API object not in Electron mode because they already exist from contextBridge
if (!window.desktop) {
window.desktop = desktopContextBridgeAPIMock;
}
}
}