Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 48 additions & 5 deletions src/commands/token.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { Command } from 'commander';
import { clearToken, configDisplayPath, hostMeta, setToken, updateConfig } from '../config.js';
import { type Context, context } from '../context.js';
import { colors, formatDate, log, table } from '../output.js';
import type { IssuedToken, TokenDetails } from '../types.js';
import type { Account, IssuedToken, TokenDetails } from '../types.js';
import { CliError, parseDays, splitList } from '../util.js';
import { validateScopes } from './auth.js';

Expand Down Expand Up @@ -35,6 +35,35 @@ export function register(program: Command): void {
.action((ids: string[], _opts, command: Command) => revokeTokens(context(command), ids));
}

type TokenOrganization = TokenDetails['organization'];

/**
* Names the organization a token is pinned to. The service sends the organization's id (`org_…`), not
* an object, so the slug comes from `slugs` (id → slug) when there is one, and the id is shown otherwise.
*/
export function organizationLabel(organization: TokenOrganization | undefined, slugs: Record<string, string> = {}): string {
if (!organization) {
return '';
}
if (typeof organization === 'string') {
return slugs[organization] || organization;
}
return organization.slug || (organization.id && slugs[organization.id]) || organization.id || '';
}

/** The slug of the organization a new token is pinned to, when it is known: from the response, or the one passed with `-o`. */
function pinnedSlug(organization: TokenOrganization, requested?: string): string | undefined {
if (!organization) {
return undefined;
}
if (typeof organization !== 'string' && organization.slug) {
return organization.slug;
}
const id = typeof organization === 'string' ? organization : organization.id;
// `-o` also takes an organization id, which is not a slug
return requested && requested !== id ? requested : undefined;
}

interface CreateOptions {
name: string;
scopes: string;
Expand Down Expand Up @@ -66,7 +95,7 @@ export async function createToken(ctx: Context, opts: CreateOptions): Promise<vo
tokenName: details.name,
scopes: details.scopes,
expiresAt: details.expires_at,
organization: details.organization?.slug ?? previous.organization,
organization: pinnedSlug(details.organization, opts.organization) ?? previous.organization,
source: 'token-create',
}),
);
Expand All @@ -79,7 +108,8 @@ export async function createToken(ctx: Context, opts: CreateOptions): Promise<vo
return;
}

log.success(`Created token ${details.name} (${details.id}), scopes ${details.scopes.join(', ')}, expires ${formatDate(details.expires_at) || 'never'}${details.organization ? `, pinned to ${details.organization.slug}` : ''}.`);
const pinned = details.organization ? opts.organization || organizationLabel(details.organization) : '';
log.success(`Created token ${details.name} (${details.id}), scopes ${details.scopes.join(', ')}, expires ${formatDate(details.expires_at) || 'never'}${pinned ? `, pinned to ${pinned}` : ''}.`);
if (opts.save) {
log.info(` saved to ${configDisplayPath()} as the token for ${ctx.host}`);
}
Expand All @@ -90,7 +120,8 @@ export async function createToken(ctx: Context, opts: CreateOptions): Promise<vo
}

export async function listTokens(ctx: Context): Promise<void> {
const tokens = await ctx.authed().get<TokenDetails[]>('v1/account/tokens');
const client = ctx.authed();
const tokens = await client.get<TokenDetails[]>('v1/account/tokens');
if (ctx.json) {
log.json(tokens);
return;
Expand All @@ -100,13 +131,25 @@ export async function listTokens(ctx: Context): Promise<void> {
return;
}
const current = hostMeta(ctx.config, ctx.registry).tokenId;
// a pinned token carries its organization's id; the account knows the slug. Without it the id is shown.
const slugs: Record<string, string> = {};
if (tokens.some((t) => t.organization && (typeof t.organization === 'string' || !t.organization.slug))) {
try {
const account = await client.get<Account>('v1/account');
for (const org of account.organizations || []) {
slugs[org.id] = org.slug;
}
} catch {
// the ids still name the organizations
}
}
log.line(
table(tokens, [
{ header: 'ID', value: (t) => (t.id === current ? `${t.id} ${colors.green('*')}` : t.id) },
{ header: 'NAME', value: (t) => t.name, max: 32 },
{ header: 'TOKEN', value: (t) => t.masked },
{ header: 'SCOPES', value: (t) => t.scopes.join(',') },
{ header: 'ORG', value: (t) => t.organization?.slug || '' },
{ header: 'ORG', value: (t) => organizationLabel(t.organization, slugs) },
{ header: 'LAST USED', value: (t) => formatDate(t.last_used_at) },
{ header: 'EXPIRES', value: (t) => (t.revoked_at ? colors.red('revoked') : formatDate(t.expires_at)) },
]),
Expand Down
3 changes: 2 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ export interface TokenDetails {
prefix: string;
last_four: string;
scopes: string[];
organization: { id: string; slug: string; name: string } | null;
/** The organization the token is pinned to: the service sends its id (`org_…`); an object with a slug is read too. */
organization: string | { id?: string; slug?: string; name?: string } | null;
expires_at: string | null;
last_used_at: string | null;
revoked_at: string | null;
Expand Down
91 changes: 91 additions & 0 deletions test/unit/auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,59 @@ describe('token', () => {
expect(readConfigFile().hosts['registry.test:8000']).toMatchObject({ tokenId: 'tok_2', source: 'token-create' });
});

it('create names the organization a token is pinned to, whichever shape the service answers with', async () => {
const created = (organization: unknown) => ({
'POST /v1/account/tokens': { status: 201, body: { token: OTHER_TOKEN, token_type: 'Bearer', expires_at: null, token_details: tokenDetails({ id: 'tok_2', name: 'ci', scopes: ['install'], organization }) } },
});
const create = async (...args: string[]) => {
const out = capture();
expect(await flb('token', 'create', '--name', 'ci', '--scopes', 'install', '--show-token', ...args)).toBe(0);
return out.stderr;
};

// what the service sends: the organization's id
const { requests } = fakeRegistry(created('org_1'));
let message = await create('-o', 'acme');
expect(requests[0].body).toMatchObject({ organization: 'acme' });
expect(message).toMatch(/Created token ci \(tok_2\), scopes install, expires .*, pinned to acme\./);
expect(message).not.toContain('undefined');

// an object with a slug
fakeRegistry(created({ id: 'org_1', slug: 'acme', name: 'Acme' }));
expect(await create('-o', 'acme')).toMatch(/, pinned to acme\./);

// no slug given on the command line: the response names it, by slug when it has one
fakeRegistry(created({ id: 'org_1', slug: 'acme', name: 'Acme' }));
expect(await create()).toMatch(/, pinned to acme\./);
fakeRegistry(created('org_1'));
expect(await create()).toMatch(/, pinned to org_1\./);

// not pinned: nothing is said, even with -o
fakeRegistry(created(null));
message = await create('-o', 'acme');
expect(message).toMatch(/expires [^,]*\.\n/);
expect(message).not.toContain('pinned');
});

it('create --save keeps the pinned organization as the default, by slug', async () => {
const created = (organization: unknown) => ({
'POST /v1/account/tokens': { status: 201, body: { token: OTHER_TOKEN, token_type: 'Bearer', expires_at: null, token_details: tokenDetails({ id: 'tok_2', name: 'ci', organization }) } },
});
const saved = async (...args: string[]) => {
capture();
expect(await flb('token', 'create', '--name', 'ci', '--save', ...args)).toBe(0);
return readConfigFile().hosts['registry.test:8000'].organization;
};

fakeRegistry(created('org_1'));
expect(await saved('-o', 'acme')).toBe('acme');
fakeRegistry(created({ id: 'org_2', slug: 'globex', name: 'Globex' }));
expect(await saved('-o', 'globex')).toBe('globex');
// an id is not a slug: the default stays as it was
fakeRegistry(created('org_1'));
expect(await saved('-o', 'org_1')).toBe('globex');
});

it('create rejects unknown scopes', async () => {
fakeRegistry({});
const out = capture();
Expand All @@ -188,6 +241,44 @@ describe('token', () => {
expect(out.stdout).toContain('flbp_…Q7k2');
});

it('list names the organization of a pinned token, by slug when the account gives one', async () => {
const tokens = [
tokenDetails(),
tokenDetails({ id: 'tok_2', name: 'pinned-by-id', organization: 'org_1' }),
tokenDetails({ id: 'tok_3', name: 'pinned-by-object', organization: { id: 'org_2', slug: 'globex', name: 'Globex' } }),
tokenDetails({ id: 'tok_4', name: 'pinned-elsewhere', organization: 'org_9' }),
];
const org = (output: string, name: string) => output.split('\n').find((line) => line.includes(name))!;

const { requests } = fakeRegistry({ 'GET /v1/account/tokens': tokens, 'GET /v1/account': account });
let out = capture();
expect(await flb('token', 'list')).toBe(0);
expect(requests.map((request) => request.path)).toEqual(['/v1/account/tokens', '/v1/account']);
expect(out.stdout).not.toContain('undefined');
expect(org(out.stdout, 'pinned-by-id')).toMatch(/\bacme\b/);
expect(org(out.stdout, 'pinned-by-object')).toMatch(/\bglobex\b/);
expect(org(out.stdout, 'pinned-elsewhere')).toMatch(/\borg_9\b/);

// the account cannot be read: the ids are shown
fakeRegistry({ 'GET /v1/account/tokens': tokens });
out = capture();
expect(await flb('token', 'list')).toBe(0);
expect(org(out.stdout, 'pinned-by-id')).toMatch(/\borg_1\b/);
expect(org(out.stdout, 'pinned-by-object')).toMatch(/\bglobex\b/);

// nothing to look up when no token is pinned by id
const plain = fakeRegistry({ 'GET /v1/account/tokens': [tokenDetails(), tokens[2]], 'GET /v1/account': account });
capture();
expect(await flb('token', 'list')).toBe(0);
expect(plain.requests.map((request) => request.path)).toEqual(['/v1/account/tokens']);

// --json passes the response through
fakeRegistry({ 'GET /v1/account/tokens': tokens });
out = capture();
expect(await flb('token', 'list', '--json')).toBe(0);
expect(JSON.parse(out.stdout).map((token: { organization: unknown }) => token.organization)).toEqual([null, 'org_1', { id: 'org_2', slug: 'globex', name: 'Globex' }, 'org_9']);
});

it('revoking the current token removes it from the config', async () => {
const { requests } = fakeRegistry({ 'DELETE /v1/account/tokens/tok_1': { status: 204, body: undefined }, 'DELETE /v1/account/tokens/tok_9': { status: 404, body: { errors: ['Resource not found.'] } } });
const out = capture();
Expand Down
Loading