@forge/cli-shared
9.10.0-next.49.10.0-next.1-experimental-1e95696
out/auth/personal/credential-store.js~
out/auth/personal/credential-store.jsModified+196−120
Index: package/out/auth/personal/credential-store.js
===================================================================
--- package/out/auth/personal/credential-store.js
+++ package/out/auth/personal/credential-store.js
@@ -1,37 +1,36 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
-exports.CredentialStoreImpl = exports.KeytarAccessError = exports.NoKeytarError = exports.NoTokenInStoreError = exports.personalApiCredentialsValidatedShape = exports.personalApiCredentialsShape = exports.API_TOKEN_KEY = exports.EMAIL_KEY = void 0;
+exports.FileCredentialStore = exports.CredentialStoreSecurityError = exports.NoTokenInStoreError = exports.personalApiCredentialsValidatedShape = exports.personalApiCredentialsShape = exports.API_TOKEN_KEY = exports.EMAIL_KEY = void 0;
+exports.getCredentialsFilePath = getCredentialsFilePath;
exports.getCredentialStore = getCredentialStore;
const tslib_1 = require("tslib");
+const child_process_1 = require("child_process");
+const fs_1 = require("fs");
const os_1 = require("os");
+const path_1 = tslib_1.__importDefault(require("path"));
+const util_1 = require("util");
const Either_1 = require("fp-ts/lib/Either");
const t = tslib_1.__importStar(require("io-ts"));
-const cache_1 = require("../../cache");
-const instruction_1 = require("../instruction");
const graphql_1 = require("../../graphql");
const shared_1 = require("../../shared");
const ui_1 = require("../../ui");
exports.EMAIL_KEY = 'FORGE_EMAIL';
exports.API_TOKEN_KEY = 'FORGE_API_TOKEN';
-const KEYTAR_SERVICE = 'Atlassian';
-const CACHE_CREDENTIALS_KEY = 'forge-credentials';
-var KeytarAccount;
-(function (KeytarAccount) {
- KeytarAccount["DEV"] = "Ecosystem-staging";
- KeytarAccount["STG"] = "Ecosystem-staging";
- KeytarAccount["PROD"] = "Ecosystem";
- KeytarAccount["FEDRAMP_MODERATE_STAGING"] = "Ecosystem-fedm-staging";
- KeytarAccount["FEDRAMP_MODERATE_PROD"] = "Ecosystem-fedm-prod";
-})(KeytarAccount || (KeytarAccount = {}));
-function getKeytar() {
- try {
- return require('keytar');
- }
- catch {
- return null;
- }
-}
+const CREDENTIALS_FILE_NAME = 'credentials.json';
+const CREDENTIALS_DIRECTORY_MODE = 0o700;
+const CREDENTIALS_FILE_MODE = 0o600;
+const PERMISSION_BITS_MASK = 0o777;
+const WINDOWS_SYSTEM_SID = 'S-1-5-18';
+const WINDOWS_ADMINISTRATORS_SID = 'S-1-5-32-544';
+var CredentialAccount;
+(function (CredentialAccount) {
+ CredentialAccount["DEV"] = "Ecosystem-staging";
+ CredentialAccount["STG"] = "Ecosystem-staging";
+ CredentialAccount["PROD"] = "Ecosystem";
+ CredentialAccount["FEDRAMP_MODERATE_STAGING"] = "Ecosystem-fedm-staging";
+ CredentialAccount["FEDRAMP_MODERATE_PROD"] = "Ecosystem-fedm-prod";
+})(CredentialAccount || (CredentialAccount = {}));
exports.personalApiCredentialsShape = t.type({
email: t.string,
token: t.string
});
@@ -45,147 +44,224 @@
super(ui_1.Text.error.noTokenStored);
}
}
exports.NoTokenInStoreError = NoTokenInStoreError;
-class NoKeytarError extends shared_1.UserError {
+class CredentialStoreSecurityError extends shared_1.UserError {
constructor() {
- super(ui_1.Text.error.noKeytar);
+ super(ui_1.Text.error.credentialsFilePermissions);
}
}
-exports.NoKeytarError = NoKeytarError;
-class KeytarAccessError extends shared_1.UserError {
+exports.CredentialStoreSecurityError = CredentialStoreSecurityError;
+const execFileAsync = (0, util_1.promisify)(child_process_1.execFile);
+const runCredentialStoreCommand = async (command, args) => {
+ const { stdout } = await execFileAsync(command, [...args], { encoding: 'utf8', windowsHide: true });
+ return stdout;
+};
+const credentialsByAccountShape = t.record(t.string, exports.personalApiCredentialsValidatedShape);
+function isFileNotFoundError(error) {
+ return typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT';
}
-exports.KeytarAccessError = KeytarAccessError;
-class CredentialStoreImpl {
- logger;
- instructionsURL;
- keytar;
- cachedConfig;
+function getCredentialsFilePath(currentPlatform = (0, os_1.platform)(), environment = process.env, userHome = (0, os_1.homedir)()) {
+ const platformPath = currentPlatform === 'win32' ? path_1.default.win32 : path_1.default.posix;
+ let credentialsDirectory;
+ switch (currentPlatform) {
+ case 'darwin':
+ credentialsDirectory = platformPath.join(userHome, 'Library', 'Application Support', 'Atlassian', 'Forge');
+ break;
+ case 'win32':
+ credentialsDirectory = platformPath.join(environment.LOCALAPPDATA || platformPath.join(userHome, 'AppData', 'Local'), 'Atlassian', 'Forge');
+ break;
+ default:
+ credentialsDirectory = platformPath.join(environment.XDG_DATA_HOME || platformPath.join(userHome, '.local', 'share'), 'Atlassian', 'Forge');
+ }
+ return platformPath.join(credentialsDirectory, CREDENTIALS_FILE_NAME);
+}
+class FileCredentialStore {
userRepository;
- keytarAccount;
- constructor(logger, instructionsURL, keytar, cachedConfig, userRepository) {
- this.logger = logger;
- this.instructionsURL = instructionsURL;
- this.keytar = keytar;
- this.cachedConfig = cachedConfig;
+ account;
+ credentialsFilePath;
+ currentPlatform;
+ commandRunner;
+ windowsUserSid;
+ constructor(userRepository, account, credentialsFilePath = getCredentialsFilePath(), currentPlatform = (0, os_1.platform)(), commandRunner = runCredentialStoreCommand) {
this.userRepository = userRepository;
- this.keytarAccount = (0, graphql_1.getEnvironmentConfig)(KeytarAccount);
+ this.account = account;
+ this.credentialsFilePath = credentialsFilePath;
+ this.currentPlatform = currentPlatform;
+ this.commandRunner = commandRunner;
}
- wrapKeytarError(e) {
- const message = (0, shared_1.wrapError)(e).message;
- let error;
- const currentPlatform = (0, os_1.platform)();
- switch (currentPlatform) {
- case 'darwin':
- error = ui_1.Text.error.keytarAccessError.mac(message);
- break;
- case 'linux':
- error = ui_1.Text.error.keytarAccessError.linux(message);
- break;
- case 'win32':
- error = ui_1.Text.error.keytarAccessError.windows(message);
- break;
- default:
- error = ui_1.Text.error.keytarAccessError.other(message);
- }
- throw new KeytarAccessError(error);
+ async getWindowsUserSid() {
+ this.windowsUserSid ??= this.commandRunner('whoami.exe', ['/user', '/fo', 'csv', '/nh']).then((output) => {
+ const sid = output.trim().match(/"?(S-\d(?:-\d+)+)"?$/)?.[1];
+ if (!sid) {
+ throw new Error('Could not determine the current Windows user SID');
+ }
+ return sid;
+ });
+ return this.windowsUserSid;
}
- decodeCredentials(credentialsString) {
- if (!credentialsString) {
- throw new NoTokenInStoreError();
- }
- let credentials;
+ async applyWindowsAcl(targetPath, directory) {
+ const userSid = await this.getWindowsUserSid();
+ const permission = directory ? '(OI)(CI)F' : 'F';
+ await this.commandRunner('icacls.exe', [
+ targetPath,
+ '/inheritance:r',
+ '/grant:r',
+ `*${userSid}:${permission}`,
+ `*${WINDOWS_SYSTEM_SID}:${permission}`,
+ `*${WINDOWS_ADMINISTRATORS_SID}:${permission}`
+ ]);
+ }
+ async secureWindowsStorage(createFile) {
+ let fileExists = true;
try {
- credentials = JSON.parse(credentialsString);
+ await fs_1.promises.access(this.credentialsFilePath);
}
- catch {
- throw new NoTokenInStoreError();
+ catch (error) {
+ if (!isFileNotFoundError(error)) {
+ throw error;
+ }
+ fileExists = false;
}
- const decodeResult = exports.personalApiCredentialsValidatedShape.decode(credentials);
- if ((0, Either_1.isLeft)(decodeResult)) {
- throw new NoTokenInStoreError();
+ if (!fileExists && !createFile) {
+ return;
}
- return decodeResult.right;
+ const credentialsDirectory = path_1.default.dirname(this.credentialsFilePath);
+ await fs_1.promises.mkdir(credentialsDirectory, { recursive: true });
+ await this.applyWindowsAcl(credentialsDirectory, true);
+ if (!fileExists) {
+ await fs_1.promises.writeFile(this.credentialsFilePath, '', { flag: 'wx' });
+ }
+ await this.applyWindowsAcl(this.credentialsFilePath, false);
}
- async getCredentialsKeytar(keytar) {
- let stringifiedPersonalApiCredentials;
+ async securePosixStorage(createFile) {
+ let fileExists = true;
try {
- stringifiedPersonalApiCredentials = await keytar.getPassword(KEYTAR_SERVICE, this.keytarAccount);
+ await fs_1.promises.access(this.credentialsFilePath);
}
- catch (e) {
- this.wrapKeytarError(e);
+ catch (error) {
+ if (!isFileNotFoundError(error)) {
+ throw error;
+ }
+ fileExists = false;
}
- if (!stringifiedPersonalApiCredentials) {
- return undefined;
+ if (!fileExists && !createFile) {
+ return;
}
- return this.decodeCredentials(stringifiedPersonalApiCredentials);
- }
- popInsecurePlaintextCredentials() {
- const result = this.cachedConfig.get(CACHE_CREDENTIALS_KEY);
- if (result) {
- this.logger.warn(ui_1.Text.warning.plaintextCredentialsFound(this.instructionsURL));
- this.deleteInsecurePlaintextCredentials();
+ const credentialsDirectory = path_1.default.dirname(this.credentialsFilePath);
+ await fs_1.promises.mkdir(credentialsDirectory, {
+ recursive: true,
+ mode: CREDENTIALS_DIRECTORY_MODE
+ });
+ await fs_1.promises.chmod(credentialsDirectory, CREDENTIALS_DIRECTORY_MODE);
+ const directoryStat = await fs_1.promises.stat(credentialsDirectory);
+ const currentUserId = process.getuid?.();
+ if (currentUserId === undefined ||
+ !directoryStat.isDirectory() ||
+ directoryStat.uid !== currentUserId ||
+ (directoryStat.mode & PERMISSION_BITS_MASK) !== CREDENTIALS_DIRECTORY_MODE) {
+ throw new Error('The credentials directory is not owned exclusively by the current user');
}
- return result;
+ if (!fileExists) {
+ const file = await fs_1.promises.open(this.credentialsFilePath, 'wx', CREDENTIALS_FILE_MODE);
+ await file.close();
+ }
+ await fs_1.promises.chmod(this.credentialsFilePath, CREDENTIALS_FILE_MODE);
+ const fileStat = await fs_1.promises.stat(this.credentialsFilePath);
+ if (!fileStat.isFile() ||
+ fileStat.uid !== currentUserId ||
+ (fileStat.mode & PERMISSION_BITS_MASK) !== CREDENTIALS_FILE_MODE) {
+ throw new Error('Could not restrict access to the credentials file');
+ }
}
- deleteInsecurePlaintextCredentials() {
- this.cachedConfig.delete(CACHE_CREDENTIALS_KEY);
- }
- async getCredentials() {
- let result;
- const plaintextCredentials = this.popInsecurePlaintextCredentials();
- if (plaintextCredentials) {
- if (this.keytar) {
- await this.setCredentials(plaintextCredentials);
- this.logger.warn(ui_1.Text.warning.plaintextCredentialsMigrated);
+ async secureStorage(createFile) {
+ try {
+ if (this.currentPlatform === 'win32') {
+ await this.secureWindowsStorage(createFile);
}
else {
- this.logger.warn(ui_1.Text.warning.plaintextCredentialsNotMigrated);
+ await this.securePosixStorage(createFile);
}
}
+ catch {
+ await fs_1.promises.rm(this.credentialsFilePath, { force: true }).catch(() => undefined);
+ throw new CredentialStoreSecurityError();
+ }
+ }
+ async readCredentialsFile() {
+ let contents;
+ try {
+ await this.secureStorage(false);
+ contents = await fs_1.promises.readFile(this.credentialsFilePath, 'utf8');
+ }
+ catch (error) {
+ if (isFileNotFoundError(error)) {
+ return {};
+ }
+ throw error;
+ }
+ let parsed;
+ try {
+ parsed = JSON.parse(contents);
+ }
+ catch {
+ throw new NoTokenInStoreError();
+ }
+ const decodeResult = credentialsByAccountShape.decode(parsed);
+ if ((0, Either_1.isLeft)(decodeResult)) {
+ throw new NoTokenInStoreError();
+ }
+ return decodeResult.right;
+ }
+ async getCredentials() {
if (process.env[exports.API_TOKEN_KEY] && process.env[exports.EMAIL_KEY]) {
const credentials = {
email: process.env[exports.EMAIL_KEY],
token: process.env[exports.API_TOKEN_KEY]
};
const { accountId } = await this.userRepository.getUser(credentials);
- result = { ...credentials, accountId };
+ return { ...credentials, accountId };
}
- else if (this.keytar) {
- result = await this.getCredentialsKeytar(this.keytar);
+ const credentials = (await this.readCredentialsFile())[this.account];
+ if (!credentials) {
+ throw new NoTokenInStoreError();
}
- if (result) {
- return result;
- }
- throw new NoTokenInStoreError();
+ return credentials;
}
async setCredentials(credentials) {
- if (this.keytar) {
- try {
- await this.keytar.setPassword(KEYTAR_SERVICE, this.keytarAccount, JSON.stringify(credentials));
+ let credentialsByAccount;
+ try {
+ credentialsByAccount = await this.readCredentialsFile();
+ }
+ catch (error) {
+ if (!(error instanceof NoTokenInStoreError)) {
+ throw error;
}
- catch (e) {
- throw new NoKeytarError();
- }
+ credentialsByAccount = {};
}
- else {
- throw new NoKeytarError();
- }
+ credentialsByAccount[this.account] = credentials;
+ await this.secureStorage(true);
+ await fs_1.promises.writeFile(this.credentialsFilePath, `${JSON.stringify(credentialsByAccount, null, 2)}\n`, 'utf8');
+ await this.secureStorage(false);
}
async deleteCredentials() {
- if (this.keytar) {
+ const credentialsByAccount = await this.readCredentialsFile();
+ delete credentialsByAccount[this.account];
+ if (Object.keys(credentialsByAccount).length === 0) {
try {
- await this.keytar.deletePassword(KEYTAR_SERVICE, this.keytarAccount);
+ await fs_1.promises.unlink(this.credentialsFilePath);
}
- catch (e) {
+ catch (error) {
+ if (!isFileNotFoundError(error)) {
+ throw error;
+ }
}
+ return;
}
- this.deleteInsecurePlaintextCredentials();
+ await fs_1.promises.writeFile(this.credentialsFilePath, `${JSON.stringify(credentialsByAccount, null, 2)}\n`, 'utf8');
+ await this.secureStorage(false);
}
}
-exports.CredentialStoreImpl = CredentialStoreImpl;
-function getCredentialStore(logger, userRepository) {
- const keytar = getKeytar();
- const cachedConfig = cache_1.CachedConf.getCache(cache_1.CONFIG_PROJECT_NAME);
- const instructionsUrl = (0, instruction_1.getInstructionsUrl)();
- return new CredentialStoreImpl(logger, instructionsUrl, keytar, cachedConfig, userRepository);
+exports.FileCredentialStore = FileCredentialStore;
+function getCredentialStore(userRepository) {
+ return new FileCredentialStore(userRepository, (0, graphql_1.getEnvironmentConfig)(CredentialAccount));
}