-
Notifications
You must be signed in to change notification settings - Fork 30k
/
credentialsMainService.ts
230 lines (195 loc) · 8.06 KB
/
credentialsMainService.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { ICredentialsChangeEvent, ICredentialsMainService, InMemoryCredentialsProvider } from 'vs/platform/credentials/common/credentials';
import { Emitter } from 'vs/base/common/event';
import { Disposable } from 'vs/base/common/lifecycle';
import { ILogService } from 'vs/platform/log/common/log';
import { isWindows } from 'vs/base/common/platform';
import { retry } from 'vs/base/common/async';
interface ChunkedPassword {
content: string;
hasNextChunk: boolean;
}
export type KeytarModule = typeof import('keytar');
export abstract class BaseCredentialsMainService extends Disposable implements ICredentialsMainService {
private static readonly MAX_PASSWORD_LENGTH = 2500;
private static readonly PASSWORD_CHUNK_SIZE = BaseCredentialsMainService.MAX_PASSWORD_LENGTH - 100;
declare readonly _serviceBrand: undefined;
private _onDidChangePassword: Emitter<ICredentialsChangeEvent> = this._register(new Emitter());
readonly onDidChangePassword = this._onDidChangePassword.event;
protected _keytarCache: KeytarModule | undefined;
constructor(
@ILogService protected readonly logService: ILogService,
) {
super();
}
//#region abstract
public abstract getSecretStoragePrefix(): Promise<string>;
protected abstract withKeytar(): Promise<KeytarModule>;
/**
* An optional method that subclasses can implement to assist in surfacing
* Keytar load errors to the user in a friendly way.
*/
protected abstract surfaceKeytarLoadError?: (err: any) => void;
//#endregion
async getPassword(service: string, account: string): Promise<string | null> {
this.logService.trace('Getting password from keytar:', service, account);
let keytar: KeytarModule;
try {
keytar = await this.withKeytar();
} catch (e) {
// for get operations, we don't want to surface errors to the user
return null;
}
const password = await retry(() => keytar.getPassword(service, account), 50, 3);
if (!password) {
this.logService.trace('Did not get a password from keytar for account:', account);
return password;
}
let content: string | undefined;
let hasNextChunk: boolean | undefined;
try {
const parsed: ChunkedPassword = JSON.parse(password);
content = parsed.content;
hasNextChunk = parsed.hasNextChunk;
} catch {
// Ignore this similar to how we ignore parse errors in the delete
// because on non-windows this will not be a JSON string.
}
if (!content || !hasNextChunk) {
this.logService.trace('Got password from keytar for account:', account);
return password;
}
try {
let index = 1;
while (hasNextChunk) {
const nextChunk = await retry(() => keytar.getPassword(service, `${account}-${index}`), 50, 3);
const result: ChunkedPassword = JSON.parse(nextChunk!);
content += result.content;
hasNextChunk = result.hasNextChunk;
index++;
}
this.logService.trace(`Got ${index}-chunked password from keytar for account:`, account);
return content;
} catch (e) {
this.logService.error(e);
return password;
}
}
async setPassword(service: string, account: string, password: string): Promise<void> {
this.logService.trace('Setting password using keytar:', service, account);
let keytar: KeytarModule;
try {
keytar = await this.withKeytar();
} catch (e) {
this.surfaceKeytarLoadError?.(e);
throw e;
}
if (isWindows && password.length > BaseCredentialsMainService.MAX_PASSWORD_LENGTH) {
let index = 0;
let chunk = 0;
let hasNextChunk = true;
while (hasNextChunk) {
const passwordChunk = password.substring(index, index + BaseCredentialsMainService.PASSWORD_CHUNK_SIZE);
index += BaseCredentialsMainService.PASSWORD_CHUNK_SIZE;
hasNextChunk = password.length - index > 0;
const content: ChunkedPassword = {
content: passwordChunk,
hasNextChunk: hasNextChunk
};
await retry(() => keytar.setPassword(service, chunk ? `${account}-${chunk}` : account, JSON.stringify(content)), 50, 3);
chunk++;
}
this.logService.trace(`Got${chunk ? ` ${chunk}-chunked` : ''} password from keytar for account:`, account);
} else {
await retry(() => keytar.setPassword(service, account, password), 50, 3);
this.logService.trace('Got password from keytar for account:', account);
}
this._onDidChangePassword.fire({ service, account });
}
async deletePassword(service: string, account: string): Promise<boolean> {
this.logService.trace('Deleting password using keytar:', service, account);
let keytar: KeytarModule;
try {
keytar = await this.withKeytar();
} catch (e) {
this.surfaceKeytarLoadError?.(e);
throw e;
}
const password = await keytar.getPassword(service, account);
if (!password) {
this.logService.trace('Did not get a password to delete from keytar for account:', account);
return false;
}
let content: string | undefined;
let hasNextChunk: boolean | undefined;
try {
const possibleChunk = JSON.parse(password);
content = possibleChunk.content;
hasNextChunk = possibleChunk.hasNextChunk;
} catch {
// When the password is saved the entire JSON payload is encrypted then stored, thus the result from getPassword might not be valid JSON
// https://github.com/microsoft/vscode/blob/c22cb87311b5eb1a3bf5600d18733f7485355dc0/src/vs/workbench/api/browser/mainThreadSecretState.ts#L83
// However in the chunked case we JSONify each chunk after encryption so for the chunked case we do expect valid JSON here
// https://github.com/microsoft/vscode/blob/708cb0c507d656b760f9d08115b8ebaf8964fd73/src/vs/platform/credentials/common/credentialsMainService.ts#L128
// Empty catch here just as in getPassword because we expect to handle both JSON cases and non JSON cases here it's not an error case to fail to parse
// https://github.com/microsoft/vscode/blob/708cb0c507d656b760f9d08115b8ebaf8964fd73/src/vs/platform/credentials/common/credentialsMainService.ts#L76
}
let index = 0;
if (content && hasNextChunk) {
try {
// need to delete additional chunks
index++;
while (hasNextChunk) {
const accountWithIndex = `${account}-${index}`;
const nextChunk = await keytar.getPassword(service, accountWithIndex);
await keytar.deletePassword(service, accountWithIndex);
const result: ChunkedPassword = JSON.parse(nextChunk!);
hasNextChunk = result.hasNextChunk;
index++;
}
} catch (e) {
this.logService.error(e);
}
}
// Delete the first account to determine deletion success
if (await keytar.deletePassword(service, account)) {
this._onDidChangePassword.fire({ service, account });
this.logService.trace(`Deleted${index ? ` ${index}-chunked` : ''} password from keytar for account:`, account);
return true;
}
this.logService.trace(`Keytar failed to delete${index ? ` ${index}-chunked` : ''} password for account:`, account);
return false;
}
async findPassword(service: string): Promise<string | null> {
let keytar: KeytarModule;
try {
keytar = await this.withKeytar();
} catch (e) {
// for get operations, we don't want to surface errors to the user
return null;
}
return await keytar.findPassword(service);
}
async findCredentials(service: string): Promise<Array<{ account: string; password: string }>> {
let keytar: KeytarModule;
try {
keytar = await this.withKeytar();
} catch (e) {
// for get operations, we don't want to surface errors to the user
return [];
}
return await keytar.findCredentials(service);
}
public clear(): Promise<void> {
if (this._keytarCache instanceof InMemoryCredentialsProvider) {
return this._keytarCache.clear();
}
// We don't know how to properly clear Keytar because we don't know
// what services have stored credentials. For reference, a "service" is an extension.
// TODO: should we clear credentials for the built-in auth extensions?
return Promise.resolve();
}
}