Skip to content

Commit

Permalink
Trying to get login to work
Browse files Browse the repository at this point in the history
  • Loading branch information
mook-as committed Aug 19, 2024
1 parent d772964 commit 90b1bb8
Show file tree
Hide file tree
Showing 12 changed files with 160 additions and 60 deletions.
14 changes: 14 additions & 0 deletions background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ import { getVersion } from '@pkg/utils/version';
import getWSLVersion from '@pkg/utils/wslVersion';
import * as window from '@pkg/window';
import { openPreferences, preferencesSetDirtyFlag } from '@pkg/window/preferences';
import { closeDashboard, openDashboard } from '@pkg/window/dashboard';

Electron.app.setPath('cache', paths.cache);
Electron.app.setAppLogsPath(paths.logs);
Expand Down Expand Up @@ -675,6 +676,14 @@ ipcMainProxy.on('images-namespaces-read', (event) => {
}
});

ipcMainProxy.on('dashboard-open', () => {
openDashboard();
});

ipcMainProxy.on('dashboard-close', () => {
closeDashboard();
});

ipcMainProxy.on('preferences-open', () => {
openPreferences();
});
Expand All @@ -699,6 +708,11 @@ function writeSettings(arg: RecursivePartial<RecursiveReadonly<settings.Settings
ipcMainProxy.handle('settings-write', (event, arg) => {
writeSettings(arg);

// dashboard requires kubernetes, so we want to close it if kubernetes is disabled
if (arg?.kubernetes?.enabled === false) {
closeDashboard();
}

event.sender.sendToFrame(event.frameId, 'settings-update', cfg);
});

Expand Down
15 changes: 4 additions & 11 deletions pkg/rancher-desktop/backend/backendHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,7 @@ const MANIFEST_DIR = '/var/lib/rancher/k3s/server/manifests';

// Manifests are applied in sort order, so use a prefix to load them last, in the required sequence.
// Names should start with `z` followed by a digit, so that `install-k3s` cleans them up on restart.
export const MANIFEST_RUNTIMES = 'z100-runtimes';
export const MANIFEST_CERT_MANAGER_CRDS = 'z110-cert-manager.crds';
export const MANIFEST_CERT_MANAGER = 'z115-cert-manager';
export const MANIFEST_SPIN_OPERATOR_CRDS = 'z120-spin-operator.crds';
export const MANIFEST_SPIN_OPERATOR = 'z125-spin-operator';
export const MANIFEST_RANCHER = 'z130-rancher-manager';
const MANIFEST_RUNTIMES = 'z100-runtimes';

const console = Logging.kube;

Expand Down Expand Up @@ -281,10 +276,6 @@ export default class BackendHelper {
return shims;
}

private static manifestFilename(manifest: string): string {
return `${ MANIFEST_DIR }/${ manifest }.yaml`;
}

/**
* Write a k3s manifest to define a runtime class for each installed containerd shim.
*/
Expand All @@ -306,7 +297,9 @@ export default class BackendHelper {
if (runtimes.length > 0) {
const manifest = runtimes.map(r => yaml.stringify(r)).join('---\n');

await vmx.writeFile(this.manifestFilename(MANIFEST_RUNTIMES), manifest, 0o644);
await vmx.writeFile(`${ MANIFEST_DIR }/${ MANIFEST_RUNTIMES }.yaml`,
manifest,
0o644);
}
}

Expand Down
19 changes: 15 additions & 4 deletions pkg/rancher-desktop/backend/k3sHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,13 @@ import type Electron from 'electron';

const KubeContextName = 'rancher-desktop';
const RancherPassword = 'password';
// Manifests are applied in sort order, so use a prefix to load them last, in the required sequence.
// Names should start with `z` followed by a digit, so that `install-k3s` cleans them up on restart.
const MANIFEST_DIR = '/var/lib/rancher/k3s/server/manifests';
const MANIFEST_CERT_MANAGER_CRDS = 'z110-cert-manager.crds';
const MANIFEST_CERT_MANAGER = 'z115-cert-manager';
const MANIFEST_SPIN_OPERATOR_CRDS = 'z120-spin-operator.crds';
const MANIFEST_SPIN_OPERATOR = 'z125-spin-operator';
export const MANIFEST_SPIN_OPERATOR = 'z125-spin-operator';
const MANIFEST_RANCHER_MANAGER = 'z130-rancher-manager';
const STATIC_DIR = '/var/lib/rancher/k3s/server/static/rancher-desktop';
const STATIC_CERT_MANAGER_CHART = `${ STATIC_DIR }/cert-manager.tgz`;
Expand Down Expand Up @@ -1259,7 +1261,16 @@ export default class K3sHelper extends events.EventEmitter {
enabled: false,
},
extraEnv: [
{ name: 'CATTLE_FEATURES', value: 'multi-cluster-management=false' },
{ name: 'CATTLE_FEATURES',
value: [
'auth=false',
'multi-cluster-management=false',
'fleet=false',
'harvester=false',
'continuous-delivery=false',
'rke1-ui=false',
'rke2=false',
].join(',') },
]
}),
},
Expand All @@ -1270,13 +1281,13 @@ export default class K3sHelper extends events.EventEmitter {
vmx.copyFileIn(path.join(paths.resources, 'cert-manager.tgz'), STATIC_CERT_MANAGER_CHART),
vmx.writeFile(manifestFilename(MANIFEST_CERT_MANAGER), CERT_MANAGER, 0o644),
vmx.copyFileIn(path.join(paths.resources, `rancher-${ DEPENDENCY_VERSIONS.rancher }.tgz`), STATIC_RANCHER_CHART));
vmx.writeFile(manifestFilename(MANIFEST_RANCHER_MANAGER), manifests.map(obj => '---\n' + yaml.stringify(obj)).join(''), 0o644);
vmx.writeFile(manifestFilename(MANIFEST_RANCHER_MANAGER), manifests.map(m => yaml.stringify(m)).join('---\n'), 0o644);
if (spin) {
promises.push(
vmx.copyFileIn(path.join(paths.resources, 'spin-operator.crds.yaml'), manifestFilename(MANIFEST_SPIN_OPERATOR_CRDS)),
vmx.copyFileIn(path.join(paths.resources, 'spin-operator.tgz'), STATIC_SPIN_OPERATOR_CHART));
vmx.writeFile(manifestFilename(MANIFEST_SPIN_OPERATOR), SPIN_OPERATOR, 0o644);
}
}
await Promise.all(promises);
}

Expand Down
5 changes: 2 additions & 3 deletions pkg/rancher-desktop/backend/kube/lima.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ import util from 'util';
import semver from 'semver';

import { Architecture, BackendSettings, RestartReasons } from '../backend';
import BackendHelper, { MANIFEST_CERT_MANAGER, MANIFEST_SPIN_OPERATOR } from '../backendHelper';
import K3sHelper, { ExtraRequiresReasons, NoCachedK3sVersionsError, ShortVersion } from '../k3sHelper';
import BackendHelper from '../backendHelper';
import K3sHelper, { ExtraRequiresReasons, MANIFEST_SPIN_OPERATOR, NoCachedK3sVersionsError, ShortVersion } from '../k3sHelper';
import LimaBackend, { Action } from '../lima';

import INSTALL_K3S_SCRIPT from '@pkg/assets/scripts/install-k3s';
Expand Down Expand Up @@ -230,7 +230,6 @@ export default class LimaKubernetesBackend extends events.EventEmitter implement
'Removing spinkube operator',
50,
Promise.all([
this.k3sHelper.uninstallHelmChart(this.client, MANIFEST_CERT_MANAGER),
this.k3sHelper.uninstallHelmChart(this.client, MANIFEST_SPIN_OPERATOR),
]));
}
Expand Down
5 changes: 2 additions & 3 deletions pkg/rancher-desktop/backend/kube/wsl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ import util from 'util';
import semver from 'semver';

import { KubeClient } from './client';
import K3sHelper, { ExtraRequiresReasons, NoCachedK3sVersionsError, ShortVersion } from '../k3sHelper';
import K3sHelper, { ExtraRequiresReasons, MANIFEST_SPIN_OPERATOR, NoCachedK3sVersionsError, ShortVersion } from '../k3sHelper';
import WSLBackend, { Action } from '../wsl';

import INSTALL_K3S_SCRIPT from '@pkg/assets/scripts/install-k3s';
import { BackendSettings, RestartReasons } from '@pkg/backend/backend';
import BackendHelper, { MANIFEST_CERT_MANAGER, MANIFEST_SPIN_OPERATOR } from '@pkg/backend/backendHelper';
import BackendHelper from '@pkg/backend/backendHelper';
import * as K8s from '@pkg/backend/k8s';
import { ContainerEngine } from '@pkg/config/settings';
import mainEvents from '@pkg/main/mainEvents';
Expand Down Expand Up @@ -263,7 +263,6 @@ export default class WSLKubernetesBackend extends events.EventEmitter implements
'Removing spinkube operator',
50,
Promise.all([
this.k3sHelper.uninstallHelmChart(this.client, MANIFEST_CERT_MANAGER),
this.k3sHelper.uninstallHelmChart(this.client, MANIFEST_SPIN_OPERATOR),
]));
}
Expand Down
20 changes: 6 additions & 14 deletions pkg/rancher-desktop/main/networking/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import getWinCertificates from './win-ca';

import mainEvents from '@pkg/main/mainEvents';
import Logging from '@pkg/utils/logging';
import { windowMapping } from '@pkg/window';
import { getWindowName, windowMapping } from '@pkg/window';

const console = Logging.networking;

Expand Down Expand Up @@ -43,20 +43,12 @@ export default async function setupNetworking() {

// Set up certificate handling for system certificates on Windows and macOS
Electron.app.on('certificate-error', async(event, webContents, url, error, certificate, callback) => {
const tlsPort = 9443;
const dashboardUrls = [
`https://127.0.0.1:${ tlsPort }`,
`wss://127.0.0.1:${ tlsPort }`,
'http://127.0.0.1:6120',
'ws://127.0.0.1:6120',
];

const pluginDevUrls = [
`https://localhost:8888`,
`wss://localhost:8888`,
];
const windowName = getWindowName(webContents);
const pluginDevUrls = [`https://localhost:8888`, `wss://localhost:8888`];
const dashboardUrls = ['https://localhost/', 'wss://localhost/'];

if (
windowName === 'main' &&
process.env.NODE_ENV === 'development' &&
process.env.RD_ENV_PLUGINS_DEV &&
pluginDevUrls.some(x => url.startsWith(x))
Expand All @@ -68,7 +60,7 @@ export default async function setupNetworking() {
return;
}

if (dashboardUrls.some(x => url.startsWith(x)) && 'dashboard' in windowMapping) {
if (windowName === 'dashboard' && dashboardUrls.some(u => url.startsWith(u))) {
event.preventDefault();
// eslint-disable-next-line n/no-callback-literal
callback(true);
Expand Down
53 changes: 53 additions & 0 deletions pkg/rancher-desktop/preload/dashboard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { ipcRenderer } from '@pkg/utils/ipcRenderer';

export default function initDashboard(): void {
if (!document.location.href.startsWith('https://localhost/dashboard/')) {
return;
}
console.log('Will init dashboard!');
async function onNavigate(event: Event) {
console.log(`${ event.type }! -> ${ location.href }`);

const resp = await fetch('https://localhost/v3/users?me=true');

console.log(resp);
if (resp.status === 401) {
// Need to login
const token = await ipcRenderer.invoke('dashboard/get-csrf-token') ?? '';
await fetch("https://localhost/v3-public/localProviders/local?action=login", {
headers: {
'Accept': "application/json",
'Content-Type': "application/json",
'X-API-CSRF': token,
},
body: JSON.stringify({
description: 'Rancher Desktop session',
responseType: 'cookie',
username: 'admin',
password: 'password',
}),
method: "POST",
credentials: "include"
});
}

if (location.pathname === '/dashboard/auth/login') {
console.log('Logging in!');
/** Helper to evalute a singel XPath expression */
function $x<T extends Element>(expr: string) {
return document.evaluate(
expr,
document,
null,
XPathResult.FIRST_ORDERED_NODE_TYPE
).singleNodeValue as T;
}
$x<HTMLInputElement>('//*[@id="username"]/descendant-or-self:input').value = 'admin';
$x<HTMLInputElement>('//*[@id="password"]/descendant-or-self:input').value = 'password';
$x<HTMLButtonElement>('//*[@id=submit]').click();
}
}
window.addEventListener('hashchange', onNavigate);
window.addEventListener('pageshow', onNavigate);
window.addEventListener('popstate', onNavigate);
}
11 changes: 10 additions & 1 deletion pkg/rancher-desktop/preload/extensions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,16 @@ interface RDXSpawnOptions extends v1.SpawnOptions {
/**
* The identifier for the extension (the name of the image).
*/
const extensionId = location.protocol === 'app:' ? '<app>' : decodeURIComponent(location.hostname.replace(/(..)/g, '%$1'));
const extensionId = (function(){
switch (location.protocol) {
case 'app:':
return '<app>';
case 'x-rd-extension:':
return decodeURIComponent(location.hostname.replace(/(..)/g, '%$1'));
default:
return '<invalid>'
}
})();

/**
* The processes that are waiting to complete, keyed by the process ID.
Expand Down
2 changes: 2 additions & 0 deletions pkg/rancher-desktop/preload/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import initDashboard from './dashboard';
import initExtensions from './extensions';

function init() {
initExtensions();
initDashboard();
}

try {
Expand Down
8 changes: 8 additions & 0 deletions pkg/rancher-desktop/typings/electron-ipc.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,9 @@ export interface IpcMainEvents {

'show-logs': () => void;

'dashboard-open': () => void;
'dashboard-close': () => void;

'diagnostics/run': () => void;

/** Only for the preferences window */
Expand Down Expand Up @@ -148,6 +151,10 @@ export interface IpcMainInvokeEvents {
'show-snapshots-confirm-dialog': (options: { window: Partial<Electron.MessageBoxOptions>, format: SnapshotDialog }) => any;
'show-snapshots-blocking-dialog': (options: { window: Partial<Electron.MessageBoxOptions>, format: SnapshotDialog }) => any;
// #endregion

// #region dashboard
'dashboard/get-csrf-token': () => string | null;
// #endregion
}

/**
Expand Down Expand Up @@ -213,6 +220,7 @@ export interface IpcRendererEvents {
'dialog/close': (...args: any) => void;
'dialog/error': (args: any) => void;
'dialog/info': (args: Record<string, string>) => void;
'dashboard-open': () => void;
// #endregion

// #region tab navigation
Expand Down
53 changes: 31 additions & 22 deletions pkg/rancher-desktop/window/dashboard.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,43 @@
import { BrowserWindow } from 'electron';

import { windowMapping, restoreWindow } from '.';

const dashboardURL = 'http://127.0.0.1:6120/c/local/explorer';

const getDashboardWindow = () => ('dashboard' in windowMapping) ? BrowserWindow.fromId(windowMapping['dashboard']) : null;
import path from 'path';
import { createWindow, getWindow } from '.';
import paths from '@pkg/utils/paths';
import { getIpcMainProxy } from '@pkg/main/ipcMain';
import Logging from '@pkg/utils/logging';

const dashboardName = 'dashboard';
const dashboardURL = 'https://localhost/dashboard/c/local/explorer';
const console = Logging.dashboard;
const ipcMain = getIpcMainProxy(console);

ipcMain.removeHandler('dashboard/get-csrf-token');
ipcMain.handle('dashboard/get-csrf-token', async (event) => {
const webContents = event.sender;
const cookies = await webContents.session.cookies.get({
url: webContents.getURL(),
name: 'CSRF',
});
return cookies?.[0].value ?? null;
})

export function openDashboard() {
let window = getDashboardWindow();

if (restoreWindow(window)) {
return window;
}

window = new BrowserWindow({
title: 'Rancher Dashboard',
width: 800,
const window = createWindow('dashboard', dashboardURL, {
title: 'Rancher Dashboard',
width: 800,
height: 600,
show: false,
show: false,
webPreferences: {
nodeIntegration: false,
contextIsolation: true,
preload: path.join(paths.resources, 'preload.js'),
sandbox: true,
},
});

window.loadURL(dashboardURL);

windowMapping['dashboard'] = window.id;

window.once('ready-to-show', () => {
window?.show();
});
}

export function closeDashboard() {
getDashboardWindow()?.close();
getWindow(dashboardName)?.close();
}
Loading

0 comments on commit 90b1bb8

Please sign in to comment.