Skip to content

Commit cc6b882

Browse files
isc-kluclaude
andcommitted
Treat username "UnknownUser" as explicit unauthenticated access (#365)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
1 parent f4c1eb0 commit cc6b882

8 files changed

Lines changed: 86 additions & 51 deletions

File tree

‎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, the server definition must set `"username": "UnknownUser"`. An omitted `username` means you will 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.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -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",

‎src/api/addServer.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ export async function addServer(
126126
username = username.trim();
127127
authDetails = { username };
128128
} else if (authMethod === "Unauthenticated") {
129-
authDetails = {};
129+
authDetails = { username: "UnknownUser" };
130130
} else {
131131
throw Error(`Unreachable! ${authMethod} must be either "Basic Auth", "OAuth2", or "Unauthenticated".`);
132132
}

‎src/authenticationProvider.ts‎

Lines changed: 16 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -120,36 +120,29 @@ export class ServerManagerAuthenticationProvider implements AuthenticationProvid
120120
await this._ensureInitialized();
121121
const serverName = scopes[0] || await this.promptServerName();
122122
const spec = await getServerSpec(serverName);
123-
const userName = scopes[1] || spec?.auth.username || await this.promptUserName(serverName);
124-
// Return existing session if found
125-
const sessionId = ServerManagerAuthenticationProvider.sessionId(serverName, userName);
123+
const auth = spec?.auth.clone() ?? new BasicAuthorization();
124+
auth.resolve({ username: scopes[1] || auth.username || await this.promptUserName(serverName) });
125+
const sessionId = ServerManagerAuthenticationProvider.sessionId(serverName, auth.username);
126126
const existingSession = await this.findExistingSession(sessionId);
127127
if (existingSession !== undefined) {
128128
return existingSession;
129129
}
130-
let auth: Authorization;
131-
if (spec?.auth.resolved()) {
132-
auth = spec.auth;
133-
} else {
130+
if (!auth.resolved()) {
134131
const credentialKey = ServerManagerAuthenticationProvider.credentialKey(sessionId);
135132
let accessToken = await this.secretStorage.get(credentialKey);
136133
if (accessToken === undefined) {
137-
if (spec?.auth instanceof OAuth2Authorization) {
138-
const tokenSet = await performOAuth2Login(sessionId, ServerManagerAuthenticationProvider.oauth2Config(spec));
139-
accessToken = tokenSet?.accessToken;
140-
if (accessToken) {
141-
await this.secretStorage.store(credentialKey, accessToken);
142-
await this._storeOAuth2Secret(sessionId, tokenSet);
143-
logger?.info(`OAuth2 [${sessionId}]: login complete, ${tokenSet?.refreshToken ? "refresh token stored" : "no refresh token"}`);
144-
}
134+
if (auth instanceof OAuth2Authorization) {
135+
// spec is certainly defined because an OAuth2Authorization must originate from spec.
136+
const tokenSet = await performOAuth2Login(sessionId, ServerManagerAuthenticationProvider.oauth2Config({ ...spec!, auth }));
137+
accessToken = tokenSet.accessToken;
138+
await this.secretStorage.store(credentialKey, accessToken);
139+
await this._storeOAuth2Secret(sessionId, tokenSet);
140+
logger?.info(`OAuth2 [${sessionId}]: login complete, ${tokenSet.refreshToken ? "refresh token stored" : "no refresh token"}`);
145141
} else {
146-
// Password is "" if userName is ""
147-
accessToken = userName && await this.promptPassword(userName, serverName, credentialKey);
142+
accessToken = await this.promptPassword(auth.username, serverName, credentialKey);
148143
}
149-
150144
}
151-
auth = spec?.auth.clone() ?? new BasicAuthorization();
152-
auth.resolve({ username: userName || "UnknownUser", accessToken });
145+
auth.resolve({ accessToken });
153146
}
154147
if (auth.resolved()) {
155148
return this._finalizeSession(serverName, auth);
@@ -225,8 +218,8 @@ export class ServerManagerAuthenticationProvider implements AuthenticationProvid
225218
return serverName;
226219
}
227220

221+
/** Returns the entered username, or UnknownUser if left blank to request unauthenticated access. Throws if the prompt is dismissed. */
228222
private async promptUserName(serverName: string): Promise<string> {
229-
// Prompt for the username.
230223
const enteredUserName = await window.showInputBox({
231224
ignoreFocusOut: true,
232225
placeHolder: `Username on server '${serverName}'`,
@@ -236,7 +229,7 @@ export class ServerManagerAuthenticationProvider implements AuthenticationProvid
236229
if (enteredUserName === undefined) {
237230
throw new Error(`${AUTHENTICATION_PROVIDER_LABEL}: Username is required.`);
238231
}
239-
return enteredUserName;
232+
return enteredUserName || "UnknownUser";
240233
}
241234

242235
private async findExistingSession(sessionId: string): Promise<AuthenticationSession | undefined> {
@@ -254,6 +247,7 @@ export class ServerManagerAuthenticationProvider implements AuthenticationProvid
254247
}
255248
}
256249

250+
/** Returns a non-empty password. Throws if the prompt is dismissed or left blank. */
257251
private async promptPassword(userName: string, serverName: string, credentialKey: string): Promise<string> {
258252
const doInputBox = async (): Promise<string | undefined> => {
259253
return await new Promise<string | undefined>((resolve, reject) => {

‎src/commonActivate.ts‎

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,10 @@ export const OBJECTSCRIPT_EXTENSIONID = "intersystems-community.vscode-objectscr
1717

1818
export let globalState: vscode.Memento;
1919

20+
export function isUnknownUser(username?: string): boolean {
21+
return username?.toLowerCase() === "unknownuser";
22+
}
23+
2024
export function getAccountFromParts(serverName: string, userName?: string): vscode.AuthenticationSessionAccountInformation | undefined {
2125
const accountId = userName ? `${serverName}/${userName}` : undefined;
2226
return accountId ? { id: accountId, label: `${userName} on ${serverName}` } : undefined;
@@ -39,18 +43,21 @@ export class BasicAuthorization implements Authorization {
3943
}
4044

4145
public get accessToken(): string | undefined {
42-
return this.#password;
46+
return isUnknownUser(this.#username) ? this.#password ?? "" : this.#password;
4347
}
4448

45-
public get httpAuthorizationHeader(): string {
49+
public get httpAuthorizationHeader(): string | undefined {
50+
if (isUnknownUser(this.#username)) {
51+
return undefined;
52+
}
4653
return `Basic ${Buffer.from(`${this.#username}:${this.#password}`).toString("base64")}`;
4754
}
4855

4956
public resolved(): this is ResolvedAuthorization {
50-
return this.username !== "" && this.#password !== undefined;
57+
return isUnknownUser(this.#username) || (this.username !== "" && this.#password !== undefined);
5158
}
5259

53-
public resolve({ accessToken, username }): this is ResolvedAuthorization {
60+
public resolve({ accessToken, username }: { accessToken?: string; username?: string }): this is ResolvedAuthorization {
5461
this.#username = username ?? this.#username;
5562
this.#password = accessToken ?? this.#password;
5663
return this.resolved();
@@ -60,14 +67,18 @@ export class BasicAuthorization implements Authorization {
6067
this.#password = undefined;
6168
}
6269

63-
public get credentials(): { auth: { username: string; password: string }; headers?: Record<string, string> } {
64-
return {
65-
auth: {
66-
username: this.username,
67-
password: this.password!,
68-
},
69-
headers: {},
70-
};
70+
public get credentials(): { auth?: { username: string; password: string }; headers?: Record<string, string> } {
71+
if (isUnknownUser(this.#username)) {
72+
return { headers: {} };
73+
} else {
74+
return {
75+
auth: {
76+
username: this.username,
77+
password: this.password!,
78+
},
79+
headers: {},
80+
};
81+
}
7182
}
7283

7384
public clone(): BasicAuthorization {
@@ -92,7 +103,7 @@ export class OAuth2Authorization implements Authorization {
92103
return this.#bearer ? true : false;
93104
}
94105

95-
public resolve({ accessToken, username }): this is ResolvedAuthorization {
106+
public resolve({ accessToken, username }: { accessToken?: string; username?: string }): this is ResolvedAuthorization {
96107
// empty accessTokens are ignored.
97108
if (accessToken) {
98109
this.#bearer = accessToken;

‎src/makeRESTRequest.ts‎

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ import * as vscode from "vscode";
88
import { getServerSpec } from "./api/getServerSpec";
99
import { AUTHENTICATION_PROVIDER } from "./authenticationProvider";
1010
import { getAccountFromParts } from "./commonActivate";
11+
import { logger } from "./logger";
12+
import { IServerSetting } from "./serverSetting";
1113

1214
export interface IServerSession {
1315
serverName: string;
@@ -93,9 +95,11 @@ export async function makeRESTRequest(
9395
if (cookies.length > 0 || !server.auth.username) {
9496
request.headers.Cookie = cookies.join("; ");
9597
respdata = await axios.request(request);
96-
if (respdata?.status === 401) {
98+
if (respdata.status === 401) {
9799
delete request.headers.Cookie;
98100
respdata = undefined;
101+
} else if (respdata.status < 300 && cookies.length === 0) {
102+
rememberUnknownUser(server.name);
99103
}
100104
}
101105
// Make the request w/ credentials
@@ -175,6 +179,31 @@ export async function logout(serverName: string) {
175179
} catch { }
176180
}
177181

182+
async function rememberUnknownUser(name: string): Promise<void> {
183+
const inspect = (scope?: vscode.ConfigurationScope) =>
184+
vscode.workspace.getConfiguration("intersystems", scope).inspect<Record<string, IServerSetting>>("servers");
185+
const candidates: Array<{ scope?: vscode.ConfigurationScope; servers?: Record<string, IServerSetting>; target: vscode.ConfigurationTarget }> = [
186+
...(vscode.workspace.workspaceFolders ?? []).map((scope) =>
187+
({ scope, servers: inspect(scope)?.workspaceFolderValue, target: vscode.ConfigurationTarget.WorkspaceFolder })),
188+
{ servers: inspect()?.workspaceValue, target: vscode.ConfigurationTarget.Workspace },
189+
{ servers: inspect()?.globalValue, target: vscode.ConfigurationTarget.Global },
190+
];
191+
const found = candidates.find(({ servers }) => servers?.[name]);
192+
const setting = found?.servers?.[name];
193+
if (!found || !setting || setting.username || setting.oauth2) {
194+
return;
195+
}
196+
try {
197+
await vscode.workspace.getConfiguration("intersystems", found.scope)
198+
.update("servers", { ...found.servers, [name]: { ...setting, username: "UnknownUser" } }, found.target);
199+
vscode.window.showInformationMessage(
200+
`Server '${name}' allowed unauthenticated access, so its 'username' setting has been set to 'UnknownUser'. A future release will prompt for a username whenever none is set.`,
201+
);
202+
} catch (error) {
203+
logger?.warn(`Failed to set username of '${name}' to UnknownUser: ${error}`);
204+
}
205+
}
206+
178207
async function resolveCredentials(spec: IServerSpec & { auth: Authorization }): Promise<void> {
179208
// This arises if setting says to use authentication provider
180209
if (!spec.auth.resolved()) {
@@ -192,10 +221,10 @@ async function resolveCredentials(spec: IServerSpec & { auth: Authorization }):
192221
{ createIfNone: true, account },
193222
);
194223
}
195-
if (session && session.accessToken) {
224+
if (session) {
196225
spec.auth.resolve({
197226
accessToken: session.accessToken,
198-
username: session.scopes[1].toLowerCase() === "unknownuser" ? "" : session.scopes[1],
227+
username: session.scopes[1],
199228
});
200229
}
201230
}

‎src/oauth2Flow.ts‎

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -47,14 +47,15 @@ function tokenSetFromResponse(label: string, data: any): IOAuth2TokenSet | undef
4747
* Perform an OAuth2 Authorization Code + PKCE flow: open the browser for login,
4848
* listen for the callback, exchange the code for an access token (and refresh token if issued).
4949
*/
50-
export async function performOAuth2Login(label: string, config: IOAuth2Config): Promise<IOAuth2TokenSet | undefined> {
50+
/** Returns the token set from an interactive login. Throws if discovery, the login, or the token exchange fails, or the login is cancelled or times out. */
51+
export async function performOAuth2Login(label: string, config: IOAuth2Config): Promise<IOAuth2TokenSet> {
5152
logger?.info(`OAuth2 [${label}]: starting interactive login`);
5253
const codeVerifier = generateCodeVerifier();
5354
const codeChallenge = await generateCodeChallenge(codeVerifier);
5455
const state = generateRandomHex(32); // CSRF protection
5556

5657
const endpoints = await discoverEndpoints(label, config.authority);
57-
if (!endpoints) { return undefined; }
58+
if (!endpoints) { throw new Error("OAuth2: Failed to discover endpoints"); }
5859
const { authorizationEndpoint, tokenEndpoint } = endpoints;
5960

6061
const callbackUri = vscode.Uri.parse(`${vscode.env.uriScheme}://intersystems-community.servermanager/oauth2-callback`);
@@ -105,7 +106,7 @@ export async function performOAuth2Login(label: string, config: IOAuth2Config):
105106
await vscode.env.openExternal(vscode.Uri.parse(authUrl.toString()));
106107

107108
const code = await codePromise;
108-
if (!code) { return undefined; }
109+
if (!code) { throw new Error("OAuth2: Login was cancelled or timed out"); }
109110

110111
try {
111112
const tokenResponse = await axios.post(tokenEndpoint, new URLSearchParams({
@@ -118,15 +119,12 @@ export async function performOAuth2Login(label: string, config: IOAuth2Config):
118119
headers: { "Content-Type": "application/x-www-form-urlencoded" },
119120
});
120121
const tokenSet = tokenSetFromResponse(label, tokenResponse.data);
121-
if (!tokenSet) {
122-
vscode.window.showErrorMessage("OAuth2: No access token in response", "Dismiss");
123-
}
122+
if (!tokenSet) { throw new Error("OAuth2: No access token in response"); }
124123
return tokenSet;
125124
} catch (err: any) {
126125
const detail = err.response?.data?.error_description || err.message;
127126
logger?.error(`OAuth2 [${label}]: token exchange failed - ${detail}`);
128-
vscode.window.showErrorMessage(`OAuth2: Token exchange failed - ${detail}`, "Dismiss");
129-
return undefined;
127+
throw new Error(`OAuth2: Token exchange failed - ${detail}`);
130128
}
131129
}
132130

‎types/index.d.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -108,9 +108,8 @@ export interface Authorization {
108108

109109
/** Narrowed `Authorization` known to hold usable credentials, per `resolved()`. */
110110
export interface ResolvedAuthorization extends Authorization {
111-
get accessToken(): string;
112-
get httpAuthorizationHeader(): string;
113-
get credentials(): { auth?: { username: string; password: string }; headers?: Record<string, string> };
111+
get accessToken(): NonNullable<Authorization["accessToken"]>;
112+
get credentials(): NonNullable<Authorization["credentials"]>;
114113
}
115114

116115
export interface ServerForUri {

0 commit comments

Comments
 (0)