Skip to content

Commit 990a5fc

Browse files
authored
Treat username "UnknownUser" as explicit unauthenticated access (#366)
* Treat username "UnknownUser" as explicit unauthenticated access - BasicAuthorization: UnknownUser is resolved with an empty accessToken, empty header and no credentials; empty passwords are ignored, as for OAuth2 tokens - createSession: a blank or typed UnknownUser needs no password; a requested user that differs from the configured one does not inherit the configured password - resolveCredentials passes the session username through instead of mapping UnknownUser to "" - Settings schema: password requires username and is rejected alongside UnknownUser (any casing) - Add-server wizard writes username UnknownUser for the Unauthenticated choice - README documents UnknownUser as the only way to request unauthenticated access * Probe username-less servers once per session and record UnknownUser through a serialized settings writer - serverSetting.ts: updateConfig(scope, update) hands the 'intersystems.servers' value at each writable target to a pure function and writes back what it returns, queued behind earlier writes; undefined entries are ignored rather than deleting a target - getServerSpec: for a stored definition with neither username nor password, GET the Atelier root once per session per folder in the background; on a genuine server-info response set username UnknownUser at the defining target and toast. Legacy embedded servers are not probed - addServer and the registry import write through updateConfig - IServerSetting is based on IJSONServerSpec so it no longer carries name * update * no timeout needed * clean up * Move BasicAuthorization into the types package and adopt the IJSONServerSpec/IServerSpec reshaping types 3.15.0-beta.2, generated from a single types/index.ts: - BasicAuthorization is exported for all extensions; base64 via TextEncoder/btoa so it also runs in the web bundle, and httpAuthorizationHeader is undefined while unresolved - IJSONServerSpec is one intersystems.servers entry (gains oauth2, loses auth); IServerSpec adds name and auth and deprecates username/password; IServerSpecWithAuth removed - Authorization and ResolvedAuthorization unchanged - index.js and index.d.ts are build outputs, kept committed and regenerated by prepublishOnly Extension: pin the published beta exactly; drop the local class and the internal IServerSetting/ OAuth2Config in favour of the package types; exclude types/ from the root tsconfig. * Stop committing the generated types/index.js and index.d.ts They are build outputs of types/index.ts, produced by npm run build and by prepublishOnly.
1 parent 5878ad8 commit 990a5fc

23 files changed

Lines changed: 396 additions & 232 deletions

‎.gitignore‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,5 @@ dist/
55
.vscode-test
66
.vscode-test-web
77
*.vsix
8+
types/index.js
9+
types/index.d.ts

‎README.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,10 @@ If instead you press 'Enter' the password will be available only until you resta
6161

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

64+
### Unauthenticated Access
65+
66+
To connect without credentials, set `"username": "UnknownUser"`. Omitting `username` does not request unauthenticated access; expect to be prompted for one.
67+
6468
### Trusting Other Extensions
6569

6670
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):

‎package-lock.json‎

Lines changed: 4 additions & 4 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json‎

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@
5353
"node-cmd": "^6.0.1"
5454
},
5555
"devDependencies": {
56-
"@intersystems-community/intersystems-servermanager": "^3.14.1",
56+
"@intersystems-community/intersystems-servermanager": "3.15.0-beta.2",
5757
"@types/glob": "^7.1.1",
5858
"@types/mocha": "^9.0.0",
5959
"@types/node": "^20.14.0",
@@ -199,7 +199,7 @@
199199
},
200200
"username": {
201201
"type": "string",
202-
"description": "Username to connect as. If not set here it must be provided when connecting."
202+
"description": "Username to connect as. Set to 'UnknownUser' for unauthenticated access. If not set here it must be provided when connecting."
203203
},
204204
"password": {
205205
"type": "string",
@@ -247,7 +247,28 @@
247247
"required": [
248248
"webServer"
249249
],
250-
"additionalProperties": false
250+
"additionalProperties": false,
251+
"dependencies": {
252+
"password": [
253+
"username"
254+
]
255+
},
256+
"allOf": [
257+
{
258+
"not": {
259+
"required": [
260+
"username",
261+
"password"
262+
],
263+
"properties": {
264+
"username": {
265+
"pattern": "^[Uu][Nn][Kk][Nn][Oo][Ww][Nn][Uu][Ss][Ee][Rr]$"
266+
}
267+
}
268+
},
269+
"errorMessage": "'password' must not be set when 'username' is 'UnknownUser' (unauthenticated access)."
270+
}
271+
]
251272
}
252273
},
253274
"properties": {

‎src/api/addServer.ts‎

Lines changed: 18 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1+
import { IJSONServerSpec } from "@intersystems-community/intersystems-servermanager";
12
import * as vscode from "vscode";
23
import { promptOAuth2Authority, promptOAuth2ClientId } from "../oauth2Prompts";
3-
import { IServerSetting } from "../serverSetting";
4+
import { updateConfig } from "../serverSetting";
45
import { getServerNames } from "./getServerNames";
56

67
export async function addServer(
@@ -107,7 +108,7 @@ export async function addServer(
107108
{ ignoreFocusOut: true, title: "Select the authentication method" },
108109
))?.label;
109110
if (authMethod === undefined) { return; }
110-
let authDetails: Pick<IServerSetting, "username" | "oauth2">;
111+
let authDetails: Pick<IJSONServerSpec, "username" | "oauth2">;
111112
if (authMethod === "OAuth2") {
112113
const authority = (await promptOAuth2Authority(name))?.trim();
113114
if (!authority) { return; }
@@ -126,7 +127,7 @@ export async function addServer(
126127
username = username.trim();
127128
authDetails = { username };
128129
} else if (authMethod === "Unauthenticated") {
129-
authDetails = {};
130+
authDetails = { username: "UnknownUser" };
130131
} else {
131132
throw Error(`Unreachable! ${authMethod} must be either "Basic Auth", "OAuth2", or "Unauthenticated".`);
132133
}
@@ -152,29 +153,23 @@ export async function addServer(
152153
quickPick.show();
153154
});
154155
if (scheme === undefined) { return; }
155-
const levelStr =
156+
const [levelStr, level] =
156157
target == vscode.ConfigurationTarget.WorkspaceFolder
157-
? "workspace-folder"
158+
? ["workspace-folder", "workspaceFolderValue"] as const
158159
: target == vscode.ConfigurationTarget.Workspace
159-
? "workspace"
160-
: "user";
160+
? ["workspace", "workspaceValue"] as const
161+
: ["user", "globalValue"] as const;
161162
try {
162-
const config = vscode.workspace.getConfiguration(
163-
"intersystems",
164-
scope,
165-
);
166-
const serversInspection = config.inspect<Record<string, Omit<IServerSetting, "name">>>("servers");
167-
const servers = (
168-
target == vscode.ConfigurationTarget.WorkspaceFolder ? serversInspection?.workspaceFolderValue :
169-
target == vscode.ConfigurationTarget.Workspace ? serversInspection?.workspaceValue :
170-
serversInspection?.globalValue
171-
) ?? {};
172-
servers[name] = {
173-
webServer: { scheme, host, port: +port, pathPrefix },
174-
...(description ? { description } : {}),
175-
...authDetails,
176-
};
177-
await config.update("servers", servers, target);
163+
await updateConfig(scope, (targets) => ({
164+
[level]: {
165+
...targets[level],
166+
[name]: {
167+
webServer: { scheme, host, port: +port, pathPrefix },
168+
...(description ? { description } : {}),
169+
...authDetails,
170+
}
171+
}
172+
}));
178173
vscode.window.showInformationMessage(`Server '${name}' stored in ${levelStr}-level settings.`);
179174
return name;
180175
} catch (error) {

‎src/api/getServerNames.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,11 @@
1-
import { IServerName } from "@intersystems-community/intersystems-servermanager";
1+
import { IJSONServerSpec, IServerName } from "@intersystems-community/intersystems-servermanager";
22
import * as vscode from "vscode";
3-
import { IServerSetting } from "../serverSetting";
43
import { serverDetail } from "./getServerSummary";
54

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

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

‎src/api/getServerSpec.ts‎

Lines changed: 84 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,71 @@
1-
import { IServerSpec, Authorization, VSCodeObjectScriptAPI } from "@intersystems-community/intersystems-servermanager";
1+
import { IServerSpec, IJSONServerSpec, IWebServerSpec, Authorization, BasicAuthorization, VSCodeObjectScriptAPI } from "@intersystems-community/intersystems-servermanager";
2+
import axios from "axios";
23
import * as vscode from "vscode";
3-
import { OAuth2Authorization, OBJECTSCRIPT_EXTENSIONID, BasicAuthorization } from "../commonActivate";
4-
import { IServerSetting } from "../serverSetting";
4+
import { OAuth2Authorization, OBJECTSCRIPT_EXTENSIONID } from "../commonActivate";
5+
import { updateConfig } from "../serverSetting";
6+
import { logger } from "../logger";
7+
import { atelierTarget } from "../atelier";
8+
9+
/** A spec as returned by getServerSpec: web server defaults applied and credentials configuration turned into `auth`. */
10+
export type NormalizedServerSpec = IServerSpec & { auth: Authorization; webServer: Required<IWebServerSpec> };
11+
12+
const firstTimed = new Set<string>();
13+
function isFirstTime(scope: vscode.ConfigurationScope | undefined, { name, webServer }: Pick<NormalizedServerSpec, "name" | "webServer">): boolean {
14+
const { scheme, host, port, pathPrefix } = webServer;
15+
const uri = scope instanceof vscode.Uri ? scope : scope?.uri;
16+
const folder = uri && vscode.workspace.getWorkspaceFolder(uri)?.uri.toString();
17+
const id = `${folder ?? ""}|${name}@${scheme}://${host}:${port}${pathPrefix}`;
18+
if (firstTimed.has(id)) {
19+
return false;
20+
} else {
21+
firstTimed.add(id);
22+
return true;
23+
}
24+
}
25+
26+
/** Probe whether the endpoint allows unauthenticated access. */
27+
async function allowsUnknownUser(webServer: NormalizedServerSpec["webServer"]): Promise<boolean> {
28+
try {
29+
const { url, httpsAgent } = atelierTarget(webServer);
30+
const response = await axios.get(encodeURI(url), { httpsAgent, validateStatus: () => true });
31+
const cookies: string[] = response.headers["set-cookie"] ?? [];
32+
if (cookies.length > 0) {
33+
axios.head(encodeURI(`${url}?CacheLogout=end`), { httpsAgent, validateStatus: () => true, headers: { Cookie: cookies.join("; ") } })
34+
.catch((error) => logger?.warn(`Probed ${url} for unauthenticated access (to record username 'UnknownUser') but failed to end the server session it opened: ${error}`));
35+
}
36+
// Require a genuine Atelier server-info document, so a proxy or login page answering 200 is not mistaken for access
37+
return response.status === 200 && Array.isArray(response.data?.result?.content?.namespaces);
38+
} catch {
39+
return false;
40+
}
41+
}
42+
43+
/** Probe once per session in the background and record UnknownUser if the server allows it. */
44+
async function tryRecordUnknownUser(scope: vscode.ConfigurationScope | undefined, { name, webServer }: Pick<NormalizedServerSpec, "name" | "webServer">): Promise<void> {
45+
try {
46+
if (!await allowsUnknownUser(webServer)) {
47+
return;
48+
}
49+
let written = false;
50+
await updateConfig(scope, (targets) => {
51+
for (const [key, servers] of Object.entries(targets)) {
52+
if (servers?.[name] && !servers[name].username) {
53+
written = true;
54+
return { [key]: { ...servers, [name]: { ...servers[name], username: "UnknownUser" } } };
55+
}
56+
}
57+
return {};
58+
});
59+
if (written) {
60+
vscode.window.showInformationMessage(
61+
`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.`,
62+
"Dismiss",
63+
);
64+
}
65+
} catch (error) {
66+
logger?.warn(`Failed to set username of '${name}' to UnknownUser: ${error}`);
67+
}
68+
}
569

670
/**
771
* Get a server specification.
@@ -13,9 +77,10 @@ import { IServerSetting } from "../serverSetting";
1377
export async function getServerSpec(
1478
name: string,
1579
scope?: vscode.ConfigurationScope,
16-
): Promise<IServerSpec & { auth: Authorization } | undefined> {
80+
): Promise<NormalizedServerSpec | undefined> {
1781
// To avoid breaking existing users, continue to return a default server definition even after we dropped that feature
18-
const setting = vscode.workspace.getConfiguration("intersystems.servers", scope).get(name) as IServerSetting | undefined || legacyEmbeddedServer(name);
82+
const settingFromConfig = vscode.workspace.getConfiguration("intersystems.servers", scope).get<IJSONServerSpec>(name);
83+
const setting = settingFromConfig || legacyEmbeddedServer(name);
1984
// Unknown server
2085
if (!setting) {
2186
const folder = vscode.workspace.workspaceFolders?.find((f) => f.name === name);
@@ -52,19 +117,25 @@ export async function getServerSpec(
52117
};
53118
} else {
54119
// Found a setting
55-
const { username, password, oauth2, ...spec } = setting;
56-
spec.name = name;
57-
spec.description = spec.description || "";
58-
spec.webServer.scheme = spec.webServer.scheme || "http";
59-
spec.webServer.port = spec.webServer.port || (spec.webServer.scheme === "https" ? 443 : 80);
60-
spec.webServer.pathPrefix = spec.webServer.pathPrefix || "";
120+
const { username, password, oauth2, webServer, ...kept } = setting;
121+
const scheme = webServer.scheme || "http";
122+
const spec = {
123+
...kept,
124+
name,
125+
description: kept.description || "",
126+
webServer: { ...webServer, scheme, port: webServer.port || (scheme === "https" ? 443 : 80), pathPrefix: webServer.pathPrefix || "" },
127+
};
61128
if (spec.superServer) {
62129
// Fall back to default if appropriate
63130
spec.superServer.host = spec.superServer.host || spec.webServer.host;
64131
}
65132
const auth = oauth2
66133
? new OAuth2Authorization(oauth2)
67-
: new BasicAuthorization(username, password);
134+
: new BasicAuthorization(username, username ? password : undefined);
135+
// Only a stored definition can be updated; legacy embedded servers have nowhere to record UnknownUser
136+
if (settingFromConfig && !oauth2 && !username && !password && isFirstTime(scope, spec)) {
137+
tryRecordUnknownUser(scope, spec);
138+
}
68139
return {
69140
...spec,
70141
auth,
@@ -81,10 +152,9 @@ export async function getServerSpec(
81152
* @param name The name.
82153
* @returns Server specification or undefined.
83154
*/
84-
export function legacyEmbeddedServer(name: string): IServerSetting | undefined {
155+
export function legacyEmbeddedServer(name: string): IJSONServerSpec | undefined {
85156
return {
86157
"default~iris": {
87-
name: "default~iris",
88158
webServer: {
89159
scheme: "http",
90160
host: "127.0.0.1",
@@ -93,7 +163,6 @@ export function legacyEmbeddedServer(name: string): IServerSetting | undefined {
93163
description: "Connection to local InterSystems IRIS™ installed with default settings.",
94164
},
95165
"default~cache": {
96-
name: "default~cache",
97166
webServer: {
98167
scheme: "http",
99168
host: "127.0.0.1",
@@ -102,7 +171,6 @@ export function legacyEmbeddedServer(name: string): IServerSetting | undefined {
102171
description: "Connection to local InterSystems Caché installed with default settings.",
103172
},
104173
"default~ensemble": {
105-
name: "default~ensemble",
106174
webServer: {
107175
scheme: "http",
108176
host: "127.0.0.1",

‎src/api/getServerSummary.ts‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,16 @@
1-
import { IServerName } from "@intersystems-community/intersystems-servermanager";
1+
import { IJSONServerSpec, IServerName } from "@intersystems-community/intersystems-servermanager";
22
import * as vscode from "vscode";
3-
import { IServerSetting } from "../serverSetting";
43
import { legacyEmbeddedServer } from "./getServerSpec";
54

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

15-
export function serverDetail(connSpec: IServerSetting): string {
14+
export function serverDetail(connSpec: IJSONServerSpec): string {
1615
return `${connSpec.webServer.scheme || "http"}://${connSpec.webServer.host}:${connSpec.webServer.port}${connSpec.webServer.pathPrefix || ""}/`;
1716
}

‎src/atelier.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import { IWebServerSpec } from "@intersystems-community/intersystems-servermanager";
2+
import * as https from "https";
3+
import * as vscode from "vscode";
4+
5+
/** The Atelier REST root of a web server, and the agent to reach it with. */
6+
export function atelierTarget({ scheme, host, port, pathPrefix }: Required<IWebServerSpec>): { url: string, httpsAgent: https.Agent | undefined } {
7+
const url = `${scheme}://${host}:${port}${pathPrefix}/api/atelier/`;
8+
const httpsAgent = typeof https.Agent == "function" ? new https.Agent({ rejectUnauthorized: vscode.workspace.getConfiguration("http").get("proxyStrictSSL") }) : undefined;
9+
return { url, httpsAgent };
10+
}

0 commit comments

Comments
 (0)