Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,5 @@ dist/
.vscode-test
.vscode-test-web
*.vsix
types/index.js
types/index.d.ts
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
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

27 changes: 24 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
"node-cmd": "^6.0.1"
},
"devDependencies": {
"@intersystems-community/intersystems-servermanager": "^3.14.1",
"@intersystems-community/intersystems-servermanager": "3.15.0-beta.2",
"@types/glob": "^7.1.1",
"@types/mocha": "^9.0.0",
"@types/node": "^20.14.0",
Expand Down 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
41 changes: 18 additions & 23 deletions src/api/addServer.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { IJSONServerSpec } from "@intersystems-community/intersystems-servermanager";
import * as vscode from "vscode";
import { promptOAuth2Authority, promptOAuth2ClientId } from "../oauth2Prompts";
import { IServerSetting } from "../serverSetting";
import { updateConfig } from "../serverSetting";
import { getServerNames } from "./getServerNames";

export async function addServer(
Expand Down Expand Up @@ -107,7 +108,7 @@ export async function addServer(
{ ignoreFocusOut: true, title: "Select the authentication method" },
))?.label;
if (authMethod === undefined) { return; }
let authDetails: Pick<IServerSetting, "username" | "oauth2">;
let authDetails: Pick<IJSONServerSpec, "username" | "oauth2">;
if (authMethod === "OAuth2") {
const authority = (await promptOAuth2Authority(name))?.trim();
if (!authority) { return; }
Expand All @@ -126,7 +127,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 +153,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<Record<string, Omit<IServerSetting, "name">>>("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
5 changes: 2 additions & 3 deletions src/api/getServerNames.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { IServerName } from "@intersystems-community/intersystems-servermanager";
import { IJSONServerSpec, IServerName } from "@intersystems-community/intersystems-servermanager";
import * as vscode from "vscode";
import { IServerSetting } from "../serverSetting";
import { serverDetail } from "./getServerSummary";

export function getServerNames(scope?: vscode.ConfigurationScope, sorted?: boolean): IServerName[] {
const allNames: IServerName[] = [];
const names: IServerName[] = [];
const servers = vscode.workspace.getConfiguration("intersystems", scope).get<Record<string, IServerSetting> & { "/default"?: string }>("servers");
const servers = vscode.workspace.getConfiguration("intersystems", scope).get<Record<string, IJSONServerSpec> & { "/default"?: string }>("servers");

if (typeof servers === "object" && servers) {

Expand Down
100 changes: 84 additions & 16 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, IJSONServerSpec, IWebServerSpec, Authorization, BasicAuthorization, 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 { OAuth2Authorization, OBJECTSCRIPT_EXTENSIONID } from "../commonActivate";
import { 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<IJSONServerSpec>(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 @@ -81,10 +152,9 @@ export async function getServerSpec(
* @param name The name.
* @returns Server specification or undefined.
*/
export function legacyEmbeddedServer(name: string): IServerSetting | undefined {
export function legacyEmbeddedServer(name: string): IJSONServerSpec | 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
7 changes: 3 additions & 4 deletions src/api/getServerSummary.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
import { IServerName } from "@intersystems-community/intersystems-servermanager";
import { IJSONServerSpec, IServerName } from "@intersystems-community/intersystems-servermanager";
import * as vscode from "vscode";
import { IServerSetting } from "../serverSetting";
import { legacyEmbeddedServer } from "./getServerSpec";

export function getServerSummary(name: string, scope?: vscode.ConfigurationScope): IServerName | undefined {
// To avoid breaking existing users, continue to return a default server definition even after we dropped that feature
const server = vscode.workspace.getConfiguration("intersystems.servers", scope).get(name) as IServerSetting | undefined || legacyEmbeddedServer(name);
const server = vscode.workspace.getConfiguration("intersystems.servers", scope).get<IJSONServerSpec>(name) || legacyEmbeddedServer(name);
if (!server) {
return undefined;
}
return { name, description: server.description || "", detail: serverDetail(server), scope };
}

export function serverDetail(connSpec: IServerSetting): string {
export function serverDetail(connSpec: IJSONServerSpec): string {
return `${connSpec.webServer.scheme || "http"}://${connSpec.webServer.host}:${connSpec.webServer.port}${connSpec.webServer.pathPrefix || ""}/`;
}
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 };
}
Loading
Loading