Skip to content

Commit

Permalink
feat: specify auth strategy
Browse files Browse the repository at this point in the history
  • Loading branch information
mdonnalley committed Feb 25, 2021
1 parent acdd69d commit 7f07f22
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 25 deletions.
45 changes: 24 additions & 21 deletions src/hubAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ import * as os from 'os';
import * as shell from 'shelljs';
import { debug } from 'debug';

import { fs } from '@salesforce/core';
import { AuthFields, fs } from '@salesforce/core';
import { env } from '@salesforce/kit';

// this seems to be a known eslint error for enums
// eslint-disable-next-line no-shadow
enum AuthStrategy {
export enum AuthStrategy {
JWT = 'JWT',
AUTH_URL = 'AUTH_URL',
REUSE = 'REUSE',
Expand Down Expand Up @@ -51,23 +51,35 @@ const formatJwtKey = (): string => {
}
};

export const prepareForJwt = (homeDir: string): string => {
const jwtKey = path.join(homeDir, 'jwtKey');
fs.writeFileSync(jwtKey, formatJwtKey());
return jwtKey;
};

export const prepareForAuthUrl = (homeDir: string): string => {
const tmpUrl = path.join(homeDir, 'tmpUrl');
fs.writeFileSync(tmpUrl, env.getString('TESTKIT_AUTH_URL', ''));
return tmpUrl;
};

/**
* Inspects the environment (via AuthStrategy) and authenticates to a devhub via JWT or AuthUrl
* Sets the hub as default for use in tests
*
* @param homeDir the testSession directory where credential files will be written
* @param authStrategy the authorization method to use
*
* reads environment variables that are set by the user OR via transferExistingAuthToEnv
* for jwt: TESTKIT_HUB_USERNAME, TESTKIT_JWT_CLIENT_ID, TESTKIT_JWT_KEY
* optional but recommended: TESTKIT_HUB_INSTANCE
* required for AuthUrl:
* required for AuthUrl: TESTKIT_AUTH_URL
*/
export const testkitHubAuth = (homeDir: string): void => {
export const testkitHubAuth = (homeDir: string, authStrategy: AuthStrategy = getAuthStrategy()): void => {
const logger = debug('testkit:authFromStubbedHome');
if (getAuthStrategy() === AuthStrategy.JWT) {
if (authStrategy === AuthStrategy.JWT) {
logger('trying jwt auth');
const jwtKey = path.join(homeDir, 'jwtKey');
fs.writeFileSync(jwtKey, formatJwtKey());
const jwtKey = prepareForJwt(homeDir);

const results = shell.exec(
`sfdx auth:jwt:grant -d -u ${env.getString('TESTKIT_HUB_USERNAME', '')} -i ${env.getString(
Expand All @@ -86,11 +98,10 @@ export const testkitHubAuth = (homeDir: string): void => {
}
return;
}
if (getAuthStrategy() === AuthStrategy.AUTH_URL) {
if (authStrategy === AuthStrategy.AUTH_URL) {
logger('trying to authenticate with AuthUrl');

const tmpUrl = path.join(homeDir, 'tmpUrl');
fs.writeFileSync(tmpUrl, env.getString('TESTKIT_AUTH_URL', ''));
const tmpUrl = prepareForAuthUrl(homeDir);

const shellOutput = shell.exec(`sfdx auth:sfdxurl:store -d -f ${tmpUrl}`, { silent: true });
logger(shellOutput);
Expand Down Expand Up @@ -137,15 +148,15 @@ const getAuthStrategy = (): AuthStrategy => {
* TESTKIT_JWT_KEY,TESTKIT_JWT_CLIENT_ID,TESTKIT_HUB_INSTANCE (if using jwt)
*
*/
export const transferExistingAuthToEnv = (): void => {
export const transferExistingAuthToEnv = (authStrategy: AuthStrategy = getAuthStrategy()): void => {
// nothing to do if the variables are already provided
if (getAuthStrategy() !== AuthStrategy.REUSE) return;
if (authStrategy !== AuthStrategy.REUSE) return;

const logger = debug('testkit:AuthReuse');
logger(`reading ${env.getString('TESTKIT_HUB_USERNAME', '')}.json`);
const authFileName = `${env.getString('TESTKIT_HUB_USERNAME', '')}.json`;
const hubAuthFileSource = path.join(env.getString('HOME') || os.homedir(), '.sfdx', authFileName);
const authFileContents = (fs.readJsonSync(hubAuthFileSource) as unknown) as AuthFile;
const authFileContents = (fs.readJsonSync(hubAuthFileSource) as unknown) as AuthFields;
if (authFileContents.privateKey) {
logger('copying variables to env from AuthFile for JWT');
// this is jwt. set the appropriate env vars
Expand Down Expand Up @@ -176,14 +187,6 @@ export const transferExistingAuthToEnv = (): void => {
);
};

interface AuthFile {
username: string;
instanceUrl: string;
clientId?: string;
privateKey?: string;
refreshToken?: string;
}

interface OrgDisplayResult {
result: {
sfdxAuthUrl?: string;
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

export * from './genUniqueString';
export * from './execCmd';
export { prepareForAuthUrl, prepareForJwt } from './hubAuth';
export * from './testProject';
export * from './testSession';
export { Duration } from '@salesforce/kit';
13 changes: 9 additions & 4 deletions src/testSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { genUniqueString } from './genUniqueString';
import { zipDir } from './zip';

import { TestProject, TestProjectOptions } from './testProject';
import { testkitHubAuth, transferExistingAuthToEnv } from './hubAuth';
import { AuthStrategy, testkitHubAuth, transferExistingAuthToEnv } from './hubAuth';

export interface TestSessionOptions {
/**
Expand All @@ -34,6 +34,11 @@ export interface TestSessionOptions {
* be deleted as part of `TestSession.clean()`.
*/
setupCommands?: string[];

/**
* The preferred auth method to use
*/
authStrategy?: keyof typeof AuthStrategy;
}

/**
Expand All @@ -58,7 +63,6 @@ export interface TestSessionOptions {
* TESTKIT_JWT_KEY = JWT key (not a filepath, the actual contents of the key)
* TESTKIT_HUB_INSTANCE = instance url for the hub. Defaults to https://login.salesforce.com
* TESTKIT_AUTH_URL = auth url to be used with auth:sfdxurl:store
*/
export class TestSession {
public id: string;
Expand Down Expand Up @@ -111,14 +115,15 @@ export class TestSession {
// Write the test session options used to create this session
fsCore.writeJsonSync(path.join(this.dir, 'testSessionOptions.json'), JSON.parse(JSON.stringify(options)));

const authStrategy = options.authStrategy ? AuthStrategy[options.authStrategy] : undefined;
// have to grab this before we change the home
transferExistingAuthToEnv();
transferExistingAuthToEnv(authStrategy);

// Set the homedir used by this test, on the TestSession and the process
process.env.USERPROFILE = process.env.HOME = this.homeDir = env.getString('TESTKIT_HOMEDIR', this.dir);

process.env.SFDX_USE_GENERIC_UNIX_KEYCHAIN = 'true';
testkitHubAuth(this.homeDir);
testkitHubAuth(this.homeDir, authStrategy);
// Run all setup commands
this.setupCommands(options.setupCommands);

Expand Down

0 comments on commit 7f07f22

Please sign in to comment.