Compare commits

..
5 changed files with 171 additions and 20 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
'eas-cli': patch
---
Have `eas whoami` resolve the current actor once, including when a session has expired.
+7
View File
@@ -0,0 +1,7 @@
---
'eas-cli': minor
---
Add JSON output to `eas whoami` and `eas account:view`. A successful lookup reports the authenticated actor and their accounts. Signed-out sessions and rejected access tokens return distinct statuses and exit with code 1.
Lookup failures return an `indeterminate` status with the diagnostic on stderr.
+13 -11
View File
@@ -31,7 +31,7 @@ import { markAsParentCommand } from '../analytics/parentCommand';
import Log, { link } from '../log';
import Sentry from '../sentry';
import SessionManager from '../user/SessionManager';
import { getActorDisplayName } from '../user/User';
import { Actor, getActorDisplayName } from '../user/User';
import { Client } from '../vcs/vcs';
export type ContextInput<
@@ -235,6 +235,16 @@ export default abstract class EasCommand extends Command {
return nullthrows(this.analyticsInternal);
}
/** Commands that report authentication failures themselves can defer the startup actor lookup. */
protected readonly deferActorLookup: boolean = false;
protected logCommand(actor: Actor | undefined): void {
if (actor) {
Sentry.setUser({ id: actor.id, username: getActorDisplayName(actor) });
}
this.analytics.logEvent(CommandEvent.ACTION, { action: `eas ${this.id}` });
}
protected abstract runAsync(): Promise<any>;
// eslint-disable-next-line async-protect/async-suffix
@@ -248,18 +258,10 @@ export default abstract class EasCommand extends Command {
this.analyticsInternal = await createAnalyticsAsync(parentCommand);
this.sessionManagerInternal = new SessionManager(this.analytics);
// this is needed for logEvent call below as it identifies the user in the analytics system
// if possible
const actor = await this.sessionManager.getUserAsync();
if (actor) {
Sentry.setUser({
id: actor.id,
username: getActorDisplayName(actor),
});
if (!this.deferActorLookup) {
this.logCommand(await this.sessionManager.getUserAsync());
}
this.analytics.logEvent(CommandEvent.ACTION, { action: command });
return await this.runAsync();
} finally {
// Commands can run inside each other, for example `eas open` runs `eas browse`.
@@ -1,13 +1,23 @@
import { CombinedError } from '@urql/core';
import chalk from 'chalk';
import { getMockOclifConfig } from '../../../__tests__/commands/utils';
import { getMockViewerUserPermission } from '../../../__tests__/viewerUserPermission';
import { Permission, Role } from '../../../graphql/generated';
import Log from '../../../log';
import Sentry from '../../../sentry';
import SessionManager from '../../../user/SessionManager';
import { Actor } from '../../../user/User';
import { printJsonOnlyOutput } from '../../../utils/json';
import AccountView from '../view';
jest.mock('../../../analytics/AnalyticsManager', () => ({
...jest.requireActual('../../../analytics/AnalyticsManager'),
createAnalyticsAsync: jest.fn(async () => ({ logEvent: jest.fn() })),
}));
jest.mock('../../../sentry');
jest.mock('../../../log');
jest.mock('../../../utils/json');
const ownerPermissions = getMockViewerUserPermission(Role.Owner).permissions;
@@ -41,12 +51,23 @@ function userActor(accounts: Actor['accounts']): Actor {
};
}
async function runAsync(actor: Actor): Promise<string[]> {
const instance = new AccountView([], getMockOclifConfig());
function command(
args: string[],
getUserAsync: () => Promise<Actor | undefined>,
accessToken: string | null = null
): AccountView {
const instance = new AccountView(args, getMockOclifConfig());
// @ts-expect-error Mock the protected context without initializing a real session.
jest.spyOn(instance, 'getContextAsync').mockResolvedValue({
maybeLoggedIn: { actor, authenticationInfo: { accessToken: null, sessionSecret: 'secret' } },
sessionManager: { getUserAsync, getAccessToken: () => accessToken },
});
// @ts-expect-error Unit tests run without the command analytics lifecycle.
jest.spyOn(instance, 'logCommand').mockImplementation(() => {});
return instance;
}
async function runAsync(actor: Actor): Promise<string[]> {
const instance = command([], async () => actor);
await instance.runAsync();
return jest.mocked(Log.log).mock.calls.map(([message]) => message);
}
@@ -108,3 +129,73 @@ it('shows the effective permissions when they do not match a role', async () =>
)})`
);
});
it('attributes a successful command to the actor fetched by whoami', async () => {
const actor = userActor([personalAccount(ownerPermissions)]);
const lookup = jest.spyOn(SessionManager.prototype, 'getUserAsync').mockResolvedValue(actor);
try {
await new AccountView([], getMockOclifConfig()).run();
expect(lookup).toHaveBeenCalledTimes(1);
expect(Sentry.setUser).toHaveBeenCalledWith({ id: 'user-id', username: 'jane' });
} finally {
lookup.mockRestore();
}
});
it('identifies the actor independently of their first account', async () => {
const actor = userActor([account('acme', ownerPermissions), personalAccount(ownerPermissions)]);
await command(['--json'], async () => actor, 'fixture-token').runAsync();
expect(printJsonOnlyOutput).toHaveBeenCalledWith({
status: 'signed-in',
actor: { id: 'user-id', type: 'User', displayName: 'jane' },
accounts: [{ name: 'acme' }, { name: 'jane' }],
});
expect(Log.log).not.toHaveBeenCalled();
});
it('propagates an indeterminate lookup failure without publishing an identity', async () => {
const error = new CombinedError({ networkError: new Error('connection reset') });
const lookup = jest.fn().mockRejectedValue(error);
await expect(command(['--json'], lookup, 'fixture-token').runAsync()).rejects.toBe(error);
expect(printJsonOnlyOutput).toHaveBeenCalledWith({ status: 'indeterminate' });
});
it.each([
['signed-out', null, jest.fn().mockResolvedValue(undefined)],
[
'token-rejected',
'fixture-token',
jest
.fn()
.mockRejectedValue(new CombinedError({ graphQLErrors: ['The bearer token is invalid.'] })),
],
] as const)('reports %s with exit code 1', async (status, token, lookup) => {
const originalExitCode = process.exitCode;
try {
await command(['--json'], lookup, token).runAsync();
expect(printJsonOnlyOutput).toHaveBeenCalledWith({ status });
expect(process.exitCode).toBe(1);
} finally {
process.exitCode = originalExitCode;
}
});
it('handles a rejected token during real command startup with one actor lookup', async () => {
const originalExitCode = process.exitCode;
const lookup = jest
.spyOn(SessionManager.prototype, 'getUserAsync')
.mockRejectedValue(new CombinedError({ graphQLErrors: ['The bearer token is invalid.'] }));
const token = jest
.spyOn(SessionManager.prototype, 'getAccessToken')
.mockReturnValue('fixture-token');
try {
await new AccountView(['--json'], getMockOclifConfig()).run();
expect(lookup).toHaveBeenCalledTimes(1);
expect(printJsonOnlyOutput).toHaveBeenCalledWith({ status: 'token-rejected' });
expect(process.exitCode).toBe(1);
} finally {
lookup.mockRestore();
token.mockRestore();
process.exitCode = originalExitCode;
}
});
+52 -6
View File
@@ -1,25 +1,64 @@
import { CombinedError } from '@urql/core';
import chalk from 'chalk';
import EasCommand from '../../commandUtils/EasCommand';
import { EasJsonOnlyFlag } from '../../commandUtils/flags';
import Log from '../../log';
import { getActorDisplayName } from '../../user/User';
import { Actor, getActorDisplayName } from '../../user/User';
import { logAccountPermissions } from '../../user/accountPermissions';
import { enableJsonOutput, printJsonOnlyOutput } from '../../utils/json';
export default class AccountView extends EasCommand {
static override description = 'show the username you are logged in as';
static override aliases = ['whoami'];
static override flags = EasJsonOnlyFlag;
protected override readonly deferActorLookup = true;
static override contextDefinition = {
...this.ContextOptions.MaybeLoggedIn,
...this.ContextOptions.SessionManagment,
};
async runAsync(): Promise<void> {
const {
maybeLoggedIn: { actor, authenticationInfo },
} = await this.getContextAsync(AccountView, { nonInteractive: true });
const { flags } = await this.parse(AccountView);
if (flags.json) {
enableJsonOutput();
}
const { sessionManager } = await this.getContextAsync(AccountView, { nonInteractive: true });
const accessToken = sessionManager.getAccessToken();
let actor: Actor | undefined;
try {
actor = await sessionManager.getUserAsync();
} catch (error) {
if (
flags.json &&
accessToken &&
error instanceof CombinedError &&
!error.networkError &&
error.graphQLErrors.some(e => e.message === 'The bearer token is invalid.')
) {
printJsonOnlyOutput({ status: 'token-rejected' });
process.exitCode = 1;
return;
}
if (flags.json) {
printJsonOnlyOutput({ status: 'indeterminate' });
}
throw error;
}
this.logCommand(actor);
if (actor) {
const displayName = getActorDisplayName(actor);
const loggedInAs = authenticationInfo.accessToken
if (flags.json) {
printJsonOnlyOutput({
status: 'signed-in',
actor: { id: actor.id, type: actor.__typename, displayName },
accounts: actor.accounts.map(({ name }) => ({ name })),
});
return;
}
const loggedInAs = accessToken
? `${displayName} (authenticated using EXPO_TOKEN)`
: displayName;
Log.log(chalk.green(loggedInAs));
@@ -36,6 +75,13 @@ export default class AccountView extends EasCommand {
)} to change the permission grant.`
);
}
} else if (flags.json) {
if (accessToken) {
printJsonOnlyOutput({ status: 'indeterminate' });
throw new Error('The server returned no actor for EXPO_TOKEN.');
}
printJsonOnlyOutput({ status: 'signed-out' });
process.exitCode = 1;
} else {
Log.warn('Not logged in');
process.exit(1);