Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,10 @@ If instead you press 'Enter' the password will be available only until you resta

Either way, you are now signed in on the specified account.

### Unauthenticated Access

To connect without credentials, set `"username": "UnknownUser"`. Omitting `username` does not request unauthenticated access; expect to be prompted for one.

### Trusting Other Extensions

When another extension first asks to use an InterSystems Server Credentials account you must either allow this or deny it. For example, when the InterSystems ObjectScript extension uses the new authentication provider you get this dialog after you click the edit pencil button alongside a namespace in the [Server Manager tree](#the-server-tree):
Expand Down
25 changes: 23 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@
},
"username": {
"type": "string",
"description": "Username to connect as. If not set here it must be provided when connecting."
"description": "Username to connect as. Set to 'UnknownUser' for unauthenticated access. If not set here it must be provided when connecting."
},
"password": {
"type": "string",
Expand Down Expand Up @@ -247,7 +247,28 @@
"required": [
"webServer"
],
"additionalProperties": false
"additionalProperties": false,
"dependencies": {
"password": [
"username"
]
},
"allOf": [
{
"not": {
"required": [
"username",
"password"
],
"properties": {
"username": {
"pattern": "^[Uu][Nn][Kk][Nn][Oo][Ww][Nn][Uu][Ss][Ee][Rr]$"
}
}
},
"errorMessage": "'password' must not be set when 'username' is 'UnknownUser' (unauthenticated access)."
}
]
}
},
"properties": {
Expand Down
38 changes: 16 additions & 22 deletions src/api/addServer.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as vscode from "vscode";
import { promptOAuth2Authority, promptOAuth2ClientId } from "../oauth2Prompts";
import { IServerSetting } from "../serverSetting";
import { IServerSetting, updateConfig } from "../serverSetting";
import { getServerNames } from "./getServerNames";

export async function addServer(
Expand Down Expand Up @@ -126,7 +126,7 @@ export async function addServer(
username = username.trim();
authDetails = { username };
} else if (authMethod === "Unauthenticated") {
authDetails = {};
authDetails = { username: "UnknownUser" };
} else {
throw Error(`Unreachable! ${authMethod} must be either "Basic Auth", "OAuth2", or "Unauthenticated".`);
}
Expand All @@ -152,29 +152,23 @@ export async function addServer(
quickPick.show();
});
if (scheme === undefined) { return; }
const levelStr =
const [levelStr, level] =
target == vscode.ConfigurationTarget.WorkspaceFolder
? "workspace-folder"
? ["workspace-folder", "workspaceFolderValue"] as const
: target == vscode.ConfigurationTarget.Workspace
? "workspace"
: "user";
? ["workspace", "workspaceValue"] as const
: ["user", "globalValue"] as const;
try {
const config = vscode.workspace.getConfiguration(
"intersystems",
scope,
);
const serversInspection = config.inspect("servers");
const servers = (
target == vscode.ConfigurationTarget.WorkspaceFolder ? serversInspection?.workspaceFolderValue :
target == vscode.ConfigurationTarget.Workspace ? serversInspection?.workspaceValue :
serversInspection?.globalValue
) ?? {};
servers[name] = {
webServer: { scheme, host, port: +port, pathPrefix },
...(description ? { description } : {}),
...authDetails,
};
await config.update("servers", servers, target);
await updateConfig(scope, (targets) => ({
[level]: {
...targets[level],
[name]: {
webServer: { scheme, host, port: +port, pathPrefix },
...(description ? { description } : {}),
...authDetails,
}
}
}));
vscode.window.showInformationMessage(`Server '${name}' stored in ${levelStr}-level settings.`);
return name;
} catch (error) {
Expand Down
96 changes: 82 additions & 14 deletions src/api/getServerSpec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,71 @@
import { IServerSpec, Authorization, VSCodeObjectScriptAPI } from "@intersystems-community/intersystems-servermanager";
import { IServerSpec, IWebServerSpec, Authorization, VSCodeObjectScriptAPI } from "@intersystems-community/intersystems-servermanager";
import axios from "axios";
import * as vscode from "vscode";
import { OAuth2Authorization, OBJECTSCRIPT_EXTENSIONID, BasicAuthorization } from "../commonActivate";
import { IServerSetting } from "../serverSetting";
import { IServerSetting, updateConfig } from "../serverSetting";
import { logger } from "../logger";
import { atelierTarget } from "../atelier";

/** A spec as returned by getServerSpec: web server defaults applied and credentials configuration turned into `auth`. */
export type NormalizedServerSpec = IServerSpec & { auth: Authorization; webServer: Required<IWebServerSpec> };

const firstTimed = new Set<string>();
function isFirstTime(scope: vscode.ConfigurationScope | undefined, { name, webServer }: Pick<NormalizedServerSpec, "name" | "webServer">): boolean {
const { scheme, host, port, pathPrefix } = webServer;
const uri = scope instanceof vscode.Uri ? scope : scope?.uri;
const folder = uri && vscode.workspace.getWorkspaceFolder(uri)?.uri.toString();
const id = `${folder ?? ""}|${name}@${scheme}://${host}:${port}${pathPrefix}`;
if (firstTimed.has(id)) {
return false;
} else {
firstTimed.add(id);
return true;
}
}

/** Probe whether the endpoint allows unauthenticated access. */
async function allowsUnknownUser(webServer: NormalizedServerSpec["webServer"]): Promise<boolean> {
try {
const { url, httpsAgent } = atelierTarget(webServer);
const response = await axios.get(encodeURI(url), { httpsAgent, validateStatus: () => true });
const cookies: string[] = response.headers["set-cookie"] ?? [];
if (cookies.length > 0) {
axios.head(encodeURI(`${url}?CacheLogout=end`), { httpsAgent, validateStatus: () => true, headers: { Cookie: cookies.join("; ") } })
.catch((error) => logger?.warn(`Probed ${url} for unauthenticated access (to record username 'UnknownUser') but failed to end the server session it opened: ${error}`));
}
// Require a genuine Atelier server-info document, so a proxy or login page answering 200 is not mistaken for access
return response.status === 200 && Array.isArray(response.data?.result?.content?.namespaces);
} catch {
return false;
}
}

/** Probe once per session in the background and record UnknownUser if the server allows it. */
async function tryRecordUnknownUser(scope: vscode.ConfigurationScope | undefined, { name, webServer }: Pick<NormalizedServerSpec, "name" | "webServer">): Promise<void> {
try {
if (!await allowsUnknownUser(webServer)) {
return;
}
let written = false;
await updateConfig(scope, (targets) => {
Comment thread
isc-klu marked this conversation as resolved.
Resolved
for (const [key, servers] of Object.entries(targets)) {
if (servers?.[name] && !servers[name].username) {
written = true;
return { [key]: { ...servers, [name]: { ...servers[name], username: "UnknownUser" } } };
}
}
return {};
});
if (written) {
vscode.window.showInformationMessage(
Comment thread
isc-klu marked this conversation as resolved.
Resolved
`Server '${name}' allowed unauthenticated access, so its 'username' setting has been set to 'UnknownUser'. A future release will always prompt for a username when none is set.`,
"Dismiss",
);
}
} catch (error) {
logger?.warn(`Failed to set username of '${name}' to UnknownUser: ${error}`);
}
}

/**
* Get a server specification.
Expand All @@ -13,9 +77,10 @@ import { IServerSetting } from "../serverSetting";
export async function getServerSpec(
name: string,
scope?: vscode.ConfigurationScope,
): Promise<IServerSpec & { auth: Authorization } | undefined> {
): Promise<NormalizedServerSpec | undefined> {
// To avoid breaking existing users, continue to return a default server definition even after we dropped that feature
const setting = vscode.workspace.getConfiguration("intersystems.servers", scope).get(name) as IServerSetting | undefined || legacyEmbeddedServer(name);
const settingFromConfig = vscode.workspace.getConfiguration("intersystems.servers", scope).get<IServerSetting>(name);
const setting = settingFromConfig || legacyEmbeddedServer(name);
// Unknown server
if (!setting) {
const folder = vscode.workspace.workspaceFolders?.find((f) => f.name === name);
Expand Down Expand Up @@ -52,19 +117,25 @@ export async function getServerSpec(
};
} else {
// Found a setting
const { username, password, oauth2, ...spec } = setting;
spec.name = name;
spec.description = spec.description || "";
spec.webServer.scheme = spec.webServer.scheme || "http";
spec.webServer.port = spec.webServer.port || (spec.webServer.scheme === "https" ? 443 : 80);
spec.webServer.pathPrefix = spec.webServer.pathPrefix || "";
const { username, password, oauth2, webServer, ...kept } = setting;
const scheme = webServer.scheme || "http";
const spec = {
...kept,
name,
description: kept.description || "",
webServer: { ...webServer, scheme, port: webServer.port || (scheme === "https" ? 443 : 80), pathPrefix: webServer.pathPrefix || "" },
};
if (spec.superServer) {
// Fall back to default if appropriate
spec.superServer.host = spec.superServer.host || spec.webServer.host;
}
const auth = oauth2
? new OAuth2Authorization(oauth2)
: new BasicAuthorization(username, password);
: new BasicAuthorization(username, username ? password : undefined);
// Only a stored definition can be updated; legacy embedded servers have nowhere to record UnknownUser
if (settingFromConfig && !oauth2 && !username && !password && isFirstTime(scope, spec)) {
tryRecordUnknownUser(scope, spec);
}
return {
...spec,
auth,
Expand All @@ -84,7 +155,6 @@ export async function getServerSpec(
export function legacyEmbeddedServer(name: string): IServerSetting | undefined {
return {
"default~iris": {
name: "default~iris",
webServer: {
scheme: "http",
host: "127.0.0.1",
Expand All @@ -93,7 +163,6 @@ export function legacyEmbeddedServer(name: string): IServerSetting | undefined {
description: "Connection to local InterSystems IRIS™ installed with default settings.",
},
"default~cache": {
name: "default~cache",
webServer: {
scheme: "http",
host: "127.0.0.1",
Expand All @@ -102,7 +171,6 @@ export function legacyEmbeddedServer(name: string): IServerSetting | undefined {
description: "Connection to local InterSystems Caché installed with default settings.",
},
"default~ensemble": {
name: "default~ensemble",
webServer: {
scheme: "http",
host: "127.0.0.1",
Expand Down
10 changes: 10 additions & 0 deletions src/atelier.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { IWebServerSpec } from "@intersystems-community/intersystems-servermanager";
import * as https from "https";
import * as vscode from "vscode";

/** The Atelier REST root of a web server, and the agent to reach it with. */
export function atelierTarget({ scheme, host, port, pathPrefix }: Required<IWebServerSpec>): { url: string, httpsAgent: https.Agent | undefined } {
const url = `${scheme}://${host}:${port}${pathPrefix}/api/atelier/`;
const httpsAgent = typeof https.Agent == "function" ? new https.Agent({ rejectUnauthorized: vscode.workspace.getConfiguration("http").get("proxyStrictSSL") }) : undefined;
return { url, httpsAgent };
}
37 changes: 18 additions & 19 deletions src/authenticationProvider.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Authorization, IServerSpec, ResolvedAuthorization } from "@intersystems-community/intersystems-servermanager";
import { ResolvedAuthorization } from "@intersystems-community/intersystems-servermanager";
import {
authentication,
AuthenticationProvider,
Expand All @@ -14,7 +14,7 @@ import {
window,
workspace,
} from "vscode";
import { getServerSpec } from "./api/getServerSpec";
import { getServerSpec, NormalizedServerSpec } from "./api/getServerSpec";
import { ServerManagerAuthenticationSession } from "./authenticationSession";
import { globalState, OAuth2Authorization, BasicAuthorization } from "./commonActivate";
import { logger } from "./logger";
Expand Down Expand Up @@ -55,12 +55,12 @@ export class ServerManagerAuthenticationProvider implements AuthenticationProvid
public static oauth2SecretKey(sessionId: string): string {
return `${ServerManagerAuthenticationProvider.secretKeyPrefix}${sessionId}:oauth2`;
}
public static oauth2Config(spec: IServerSpec & { auth: Authorization }): IOAuth2Config {
public static oauth2Config(spec: NormalizedServerSpec): IOAuth2Config {
const oauth2 = (spec.auth as OAuth2Authorization).oauth2;
return {
authority: oauth2.authority,
clientId: oauth2.clientId,
audience: `${spec.webServer.scheme || "http"}://${spec.webServer.host}:${spec.webServer.port}/`,
audience: `${spec.webServer.scheme}://${spec.webServer.host}:${spec.webServer.port}/`,
};
}

Expand Down Expand Up @@ -120,36 +120,35 @@ export class ServerManagerAuthenticationProvider implements AuthenticationProvid
await this._ensureInitialized();
const serverName = scopes[0] || await this.promptServerName();
const spec = await getServerSpec(serverName);
const userName = scopes[1] || spec?.auth.username || await this.promptUserName(serverName);
const auth = spec?.auth.clone() ?? new BasicAuthorization();
// The configured credential belongs to the configured user; a different requested user must supply its own
if (scopes[1] && scopes[1].toLowerCase() !== auth.username.toLowerCase()) {
auth.clear() as void;
}
auth.resolve({ username: scopes[1] || spec?.auth.username || await this.promptUserName(serverName) || "UnknownUser" });
// Return existing session if found
const sessionId = ServerManagerAuthenticationProvider.sessionId(serverName, userName);
const sessionId = ServerManagerAuthenticationProvider.sessionId(serverName, auth.username);
const existingSession = await this.findExistingSession(sessionId);
if (existingSession !== undefined) {
return existingSession;
}
let auth: Authorization;
if (spec?.auth.resolved()) {
auth = spec.auth;
} else {
if (!auth.resolved()) {
const credentialKey = ServerManagerAuthenticationProvider.credentialKey(sessionId);
let accessToken = await this.secretStorage.get(credentialKey);
if (accessToken === undefined) {
if (spec?.auth instanceof OAuth2Authorization) {
const tokenSet = await performOAuth2Login(sessionId, ServerManagerAuthenticationProvider.oauth2Config(spec));
if (auth instanceof OAuth2Authorization) {
const tokenSet = await performOAuth2Login(sessionId, ServerManagerAuthenticationProvider.oauth2Config(spec!));
accessToken = tokenSet?.accessToken;
if (accessToken) {
await this.secretStorage.store(credentialKey, accessToken);
await this._storeOAuth2Secret(sessionId, tokenSet);
logger?.info(`OAuth2 [${sessionId}]: login complete, ${tokenSet?.refreshToken ? "refresh token stored" : "no refresh token"}`);
}
} else {
// Password is "" if userName is ""
accessToken = userName && await this.promptPassword(userName, serverName, credentialKey);
accessToken = await this.promptPassword(auth.username, serverName, credentialKey);
}

}
auth = spec?.auth.clone() ?? new BasicAuthorization();
auth.resolve({ username: userName || "UnknownUser", accessToken });
auth.resolve({ accessToken });
}
if (auth.resolved()) {
return this._finalizeSession(serverName, auth);
Expand Down Expand Up @@ -369,7 +368,7 @@ export class ServerManagerAuthenticationProvider implements AuthenticationProvid
*/
private async _tryRefresh(
session: ServerManagerAuthenticationSession,
serverSpec: IServerSpec & { auth: Authorization },
serverSpec: NormalizedServerSpec,
): Promise<ServerManagerAuthenticationSession | undefined> {
const existing = this._refreshInFlight.get(session.id);
const promise = existing ?? this._doRefresh(session.id, serverSpec);
Expand All @@ -394,7 +393,7 @@ export class ServerManagerAuthenticationProvider implements AuthenticationProvid
return refreshed;
}

private async _doRefresh(sessionId: string, serverSpec: IServerSpec & { auth: Authorization }): Promise<string | undefined> {
private async _doRefresh(sessionId: string, serverSpec: NormalizedServerSpec): Promise<string | undefined> {
const secret = await this._getOAuth2Secret(sessionId);
if (!secret?.refreshToken) {
logger?.debug(`OAuth2 [${sessionId}]: no refresh token stored`);
Expand Down
3 changes: 2 additions & 1 deletion src/commands/importFromRegistry.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as vscode from "vscode";
import { ServerManagerAuthenticationProvider } from "../authenticationProvider";
import { ServerSettings, updateConfig } from "../serverSetting";

// To avoid overhead querying the registry, cache responses (each time the command is run)
const regQueryCache = new Map<string, { data?: string }>();
Expand Down Expand Up @@ -49,7 +50,7 @@ export async function importFromRegistry(secretStorage: vscode.SecretStorage, sc
return;
}
await promptForPasswords(secretStorage, serverDefinitions, newServerNames);
await config.update(`servers`, serverDefinitions, vscode.ConfigurationTarget.Global)
await updateConfig(scope, (targets) => ({ globalValue: { ...serverDefinitions as ServerSettings, ...targets.globalValue, } }))
.then(() => {
return vscode.window.showInformationMessage("Server import completed.");
}, (reason) => {
Expand Down
Loading
Loading