Skip to content

Commit

Permalink
cli: add option to enable --no-sleep for tunnel (#172043)
Browse files Browse the repository at this point in the history
Fixes microsoft/vscode-remote-release#7127

Also add auth logs for debugging, seemed like my OSS retained
a bad Github token.
  • Loading branch information
connor4312 committed Jan 23, 2023
1 parent 8cea434 commit 6d59c82
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 14 deletions.
37 changes: 26 additions & 11 deletions cli/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

use crate::{
constants::{get_default_user_agent, PRODUCT_NAME_LONG},
info, log,
debug, info, log,
state::{LauncherPaths, PersistedState},
trace,
util::{
Expand Down Expand Up @@ -112,7 +112,7 @@ pub struct StoredCredential {
}

impl StoredCredential {
pub async fn is_expired(&self, client: &reqwest::Client) -> bool {
pub async fn is_expired(&self, log: &log::Logger, client: &reqwest::Client) -> bool {
match self.provider {
AuthProvider::Microsoft => self
.expires_at
Expand All @@ -122,14 +122,29 @@ impl StoredCredential {
// Make an auth request to Github. Mark the credential as expired
// only on a verifiable 4xx code. We don't error on any failed
// request since then a drop in connection could "require" a refresh
AuthProvider::Github => client
.get("https://api.github.com/user")
.header("Authorization", format!("token {}", self.access_token))
.header("User-Agent", get_default_user_agent())
.send()
.await
.map(|r| r.status().is_client_error())
.unwrap_or(false),
AuthProvider::Github => {
let res = client
.get("https://api.github.com/user")
.header("Authorization", format!("token {}", self.access_token))
.header("User-Agent", get_default_user_agent())
.send()
.await;
let res = match res {
Ok(r) => r,
Err(e) => {
warning!(log, "failed to check Github token: {}", e);
return false;
}
};

if res.status().is_success() {
return false;
}

let err = StatusError::from_res(res).await;
debug!(log, "github token looks expired: {:?}", err);
true
}
}
}

Expand Down Expand Up @@ -453,7 +468,7 @@ impl Auth {
&self,
creds: &StoredCredential,
) -> Result<Option<StoredCredential>, AnyError> {
if !creds.is_expired(&self.client).await {
if !creds.is_expired(&self.log, &self.client).await {
return Ok(None);
}

Expand Down
1 change: 1 addition & 0 deletions src/vs/platform/remoteTunnel/common/remoteTunnel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ export interface ConnectionInfo {

export const CONFIGURATION_KEY_PREFIX = 'remote.tunnels.access';
export const CONFIGURATION_KEY_HOST_NAME = CONFIGURATION_KEY_PREFIX + '.hostNameOverride';
export const CONFIGURATION_KEY_PREVENT_SLEEP = CONFIGURATION_KEY_PREFIX + '.preventSleep';

export const LOG_FILE_NAME = 'remoteTunnelService.log';
export const LOGGER_NAME = localize('remoteTunnelLog', "Remote Tunnel Service");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import { CONFIGURATION_KEY_HOST_NAME, ConnectionInfo, IRemoteTunnelAccount, IRemoteTunnelService, LOGGER_NAME, LOG_CHANNEL_ID, LOG_FILE_NAME, TunnelStates, TunnelStatus } from 'vs/platform/remoteTunnel/common/remoteTunnel';
import { CONFIGURATION_KEY_HOST_NAME, CONFIGURATION_KEY_PREVENT_SLEEP, ConnectionInfo, IRemoteTunnelAccount, IRemoteTunnelService, LOGGER_NAME, LOG_CHANNEL_ID, LOG_FILE_NAME, TunnelStates, TunnelStatus } from 'vs/platform/remoteTunnel/common/remoteTunnel';
import { Emitter } from 'vs/base/common/event';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { INativeEnvironmentService } from 'vs/platform/environment/common/environment';
Expand All @@ -30,6 +30,11 @@ type RemoteTunnelEnablementEvent = {
enabled: boolean;
};

const restartTunnelOnConfigurationChanges: readonly string[] = [
CONFIGURATION_KEY_HOST_NAME,
CONFIGURATION_KEY_PREVENT_SLEEP,
];

/**
* This service runs on the shared service. It is running the `code-tunnel` command
* to make the current machine available for remote access.
Expand Down Expand Up @@ -82,7 +87,7 @@ export class RemoteTunnelService extends Disposable implements IRemoteTunnelServ
}));

this._register(configurationService.onDidChangeConfiguration(e => {
if (e.affectsConfiguration(CONFIGURATION_KEY_HOST_NAME)) {
if (restartTunnelOnConfigurationChanges.some(c => e.affectsConfiguration(c))) {
this._startTunnelProcessDelayer.trigger(() => this.updateTunnelProcess());
}
}));
Expand Down Expand Up @@ -183,6 +188,9 @@ export class RemoteTunnelService extends Disposable implements IRemoteTunnelServ
} else {
args.push('--random-name');
}
if (this._preventSleep()) {
args.push('--no-sleep');
}
const serveCommand = this.runCodeTunneCommand('tunnel', args, (message: string, isErr: boolean) => {
if (isErr) {
this._logger.error(message);
Expand Down Expand Up @@ -283,6 +291,10 @@ export class RemoteTunnelService extends Disposable implements IRemoteTunnelServ
return this._getHostName();
}

private _preventSleep() {
return !!this.configurationService.getValue<boolean>(CONFIGURATION_KEY_PREVENT_SLEEP);
}

private _getHostName(): string | undefined {
let name = this.configurationService.getValue<string>(CONFIGURATION_KEY_HOST_NAME) || hostname();
name = name.replace(/^-+/g, '').replace(/[^\w-]/g, '').substring(0, 20);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import { Disposable, DisposableStore } from 'vs/base/common/lifecycle';
import { Action2, MenuId, registerAction2 } from 'vs/platform/actions/common/actions';
import { IProductService } from 'vs/platform/product/common/productService';
import { CONFIGURATION_KEY_HOST_NAME, CONFIGURATION_KEY_PREFIX, ConnectionInfo, IRemoteTunnelAccount, IRemoteTunnelService, LOGGER_NAME, LOG_CHANNEL_ID, LOG_FILE_NAME } from 'vs/platform/remoteTunnel/common/remoteTunnel';
import { CONFIGURATION_KEY_HOST_NAME, CONFIGURATION_KEY_PREFIX, CONFIGURATION_KEY_PREVENT_SLEEP, ConnectionInfo, IRemoteTunnelAccount, IRemoteTunnelService, LOGGER_NAME, LOG_CHANNEL_ID, LOG_FILE_NAME } from 'vs/platform/remoteTunnel/common/remoteTunnel';
import { AuthenticationSession, AuthenticationSessionsChangeEvent, IAuthenticationService } from 'vs/workbench/services/authentication/common/authentication';
import { localize } from 'vs/nls';
import { IWorkbenchContributionsRegistry, Extensions as WorkbenchExtensions, IWorkbenchContribution } from 'vs/workbench/common/contributions';
Expand Down Expand Up @@ -756,6 +756,12 @@ Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration).regis
patternErrorMessage: localize('remoteTunnelAccess.machineNameRegex', "The name must only consist of letters, numbers, underscore and dash. It must not start with a dash."),
maxLength: 20,
default: ''
},
[CONFIGURATION_KEY_PREVENT_SLEEP]: {
description: localize('remoteTunnelAccess.preventSleep', "Prevent the computer from sleeping when remote tunnel access is turned on."),
type: 'boolean',
scope: ConfigurationScope.MACHINE,
default: false,
}
}
});

0 comments on commit 6d59c82

Please sign in to comment.