diff --git a/static/app/views/settings/organizationServiceAccounts/createTokenModal.tsx b/static/app/views/settings/organizationServiceAccounts/createTokenModal.tsx new file mode 100644 index 000000000000..11afab639b63 --- /dev/null +++ b/static/app/views/settings/organizationServiceAccounts/createTokenModal.tsx @@ -0,0 +1,244 @@ +import moment from 'moment-timezone'; +import {z} from 'zod'; + +import {Alert} from '@sentry/scraps/alert'; +import {Button} from '@sentry/scraps/button'; +import {DateTime} from '@sentry/scraps/dateTime'; +import { + defaultFormOptions, + setFieldErrors, + useScrapsForm, + useStore, +} from '@sentry/scraps/form'; +import {Flex, Stack} from '@sentry/scraps/layout'; +import type {ModalRenderProps} from '@sentry/scraps/modal'; +import {Heading, Text} from '@sentry/scraps/text'; +import {toast} from '@sentry/scraps/toast'; + +import {t, tct} from 'sentry/locale'; +import {getRequestErrorUserMessage} from 'sentry/utils/requestError/getRequestErrorUserMessage'; +import {RequestError} from 'sentry/utils/requestError/requestError'; +import {useOrganization} from 'sentry/utils/useOrganization'; + +import {useCreateServiceAccountToken} from './serviceAccountApi'; +import {getDetailFieldErrors, MAX_NAME_LENGTH} from './serviceAccountForm'; +import type {NewServiceAccountToken, ServiceAccount} from './types'; + +const EXPIRATION = z.enum(['7', '30', '90', '365', 'never']); + +type Expiration = z.infer; + +const EXPIRATION_LABELS: Record = { + '7': t('7 days'), + '30': t('30 days'), + '90': t('90 days'), + '365': t('1 year'), + never: t('No expiration'), +}; + +const EXPIRATION_OPTIONS = EXPIRATION.options.map(value => ({ + value, + label: EXPIRATION_LABELS[value], +})); + +const DEFAULT_EXPIRATION: Expiration = '30'; + +const API_FIELDS = ['name', 'scopes', 'expiresAt'] as const; + +const schema = z.object({ + name: z.string().trim().min(1, t('Name is required')).max(MAX_NAME_LENGTH), + scopeMode: z.enum(['all', 'choose']), + scopes: z.array(z.string()), + expiration: EXPIRATION, +}); + +type FormValues = z.infer; + +/** Puts each API error on the form field that shows it. */ +function getFormErrors(error: RequestError, scopeMode: FormValues['scopeMode']) { + const {name, scopes, expiresAt} = getDetailFieldErrors(error, API_FIELDS); + return { + ...(name && {name}), + // The scopes field is hidden while every available scope is picked. + ...(scopes && (scopeMode === 'all' ? {scopeMode: scopes} : {scopes})), + ...(expiresAt && {expiration: expiresAt}), + }; +} + +function getExpiryDate(expiration: Expiration) { + return expiration === 'never' + ? null + : moment().add(Number(expiration), 'days').toDate(); +} + +interface Props extends ModalRenderProps { + account: ServiceAccount; + onCreated: (token: NewServiceAccountToken) => void; +} + +export function CreateTokenModal({ + Header, + Body, + Footer, + closeModal, + account, + onCreated, +}: Props) { + const organization = useOrganization(); + const createToken = useCreateServiceAccountToken(organization, account.id); + // The API rejects scopes the caller doesn't hold, even when the account has them. + const callerScopes = new Set(organization.access); + const grantableScopes = account.scopes.filter(scope => callerScopes.has(scope)); + + const defaultValues: FormValues = { + name: '', + scopeMode: 'all', + scopes: grantableScopes, + expiration: DEFAULT_EXPIRATION, + }; + + const form = useScrapsForm({ + ...defaultFormOptions, + defaultValues, + validators: {onDynamic: schema}, + onSubmit: async ({value, formApi}) => { + try { + const token = await createToken.mutateAsync({ + name: value.name.trim(), + scopes: value.scopeMode === 'all' ? grantableScopes : value.scopes, + expiresAt: getExpiryDate(value.expiration)?.toISOString() ?? null, + }); + closeModal(); + onCreated(token); + } catch (error) { + toast.error(getRequestErrorUserMessage(error, t('Unable to create token.'))); + if (error instanceof RequestError) { + setFieldErrors(formApi, getFormErrors(error, value.scopeMode)); + } + } + }, + }); + + const values = useStore(form.store, state => state.values); + const expiryDate = getExpiryDate(values.expiration); + const noScopesPicked = + values.scopeMode === 'all' + ? grantableScopes.length === 0 + : values.scopes.length === 0; + + return ( + +
+ {t('Create Token for %s', account.name)} +
+ + + + {field => ( + + + + )} + + + + {field => ( + + {({Item}) => ( + + + + {t('All available scopes (%s)', grantableScopes.length)} + + {t('Choose scopes')} + + + )} + + )} + + + {values.scopeMode === 'choose' && ( + + {field => ( + + {({Item}) => ( + + + {grantableScopes.map(scope => ( + + {scope} + + ))} + + + )} + + )} + + )} + + + {field => ( + , + }) + : undefined + } + > + + + )} + + + {values.expiration === 'never' && ( + + + {t( + 'A token that never expires is riskier if it leaks. Use this only for systems that can’t rotate tokens.' + )} + + + )} + + +
+ + + + {t('Create Token')} + + +
+
+ ); +} diff --git a/static/app/views/settings/organizationServiceAccounts/newTokenModal.tsx b/static/app/views/settings/organizationServiceAccounts/newTokenModal.tsx new file mode 100644 index 000000000000..fe4663a62acd --- /dev/null +++ b/static/app/views/settings/organizationServiceAccounts/newTokenModal.tsx @@ -0,0 +1,55 @@ +import {Fragment} from 'react'; + +import {Alert} from '@sentry/scraps/alert'; +import {Button} from '@sentry/scraps/button'; +import {Stack} from '@sentry/scraps/layout'; +import type {ModalRenderProps} from '@sentry/scraps/modal'; +import {Heading, Text} from '@sentry/scraps/text'; + +import {TextCopyInput} from 'sentry/components/textCopyInput'; +import {t} from 'sentry/locale'; + +import type {NewServiceAccountToken} from './types'; + +/** + * The API returns a token's value only when it's created, so this modal is the only + * place it's shown. Keep it out of the URL, storage and analytics. + */ +export function NewTokenModal({ + Header, + Body, + Footer, + closeModal, + token, +}: ModalRenderProps & {token: NewServiceAccountToken}) { + return ( + +
+ {t('Token created')} +
+ + + + + {t('Copy this token now. You won’t be able to see it again.')} + + + + {token.name} + {token.token} + + + {t( + 'Send it in the Authorization header as a Bearer token. Store it somewhere secret, such as your CI provider’s secrets.' + )} + + + +
+ +
+
+ ); +} diff --git a/static/app/views/settings/organizationServiceAccounts/serviceAccountApi.tsx b/static/app/views/settings/organizationServiceAccounts/serviceAccountApi.tsx index fcd7c2ac68f8..c79b6d1999ec 100644 --- a/static/app/views/settings/organizationServiceAccounts/serviceAccountApi.tsx +++ b/static/app/views/settings/organizationServiceAccounts/serviceAccountApi.tsx @@ -5,7 +5,13 @@ import {apiOptions} from 'sentry/utils/api/apiOptions'; import {getApiUrl} from 'sentry/utils/api/getApiUrl'; import {fetchMutation} from 'sentry/utils/queryClient'; -import type {ServiceAccount, ServiceAccountInput} from './types'; +import type { + NewServiceAccountToken, + ServiceAccount, + ServiceAccountInput, + ServiceAccountToken, + ServiceAccountTokenInput, +} from './types'; export function serviceAccountsApiOptions( organization: Organization, @@ -92,3 +98,61 @@ export function useDeleteServiceAccount( }), }); } + +export function serviceAccountTokensApiOptions( + organization: Organization, + serviceAccountId: string, + {cursor}: {cursor?: string} = {} +) { + return apiOptions.as()( + '/organizations/$organizationIdOrSlug/service-accounts/$serviceAccountId/tokens/', + { + path: {organizationIdOrSlug: organization.slug, serviceAccountId}, + query: {cursor}, + staleTime: 0, + } + ); +} + +export function useCreateServiceAccountToken( + organization: Organization, + serviceAccountId: string +) { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: (data: ServiceAccountTokenInput) => + fetchMutation({ + url: getApiUrl( + '/organizations/$organizationIdOrSlug/service-accounts/$serviceAccountId/tokens/', + {path: {organizationIdOrSlug: organization.slug, serviceAccountId}} + ), + method: 'POST', + data: {...data}, + }), + onSuccess: () => + queryClient.invalidateQueries({ + queryKey: serviceAccountTokensApiOptions(organization, serviceAccountId).queryKey, + }), + }); +} + +export function useRevokeServiceAccountToken( + organization: Organization, + serviceAccountId: string +) { + const queryClient = useQueryClient(); + return useMutation({ + mutationFn: (tokenId: string) => + fetchMutation({ + url: getApiUrl( + '/organizations/$organizationIdOrSlug/service-accounts/$serviceAccountId/tokens/$tokenId/', + {path: {organizationIdOrSlug: organization.slug, serviceAccountId, tokenId}} + ), + method: 'DELETE', + }), + onSuccess: () => + queryClient.invalidateQueries({ + queryKey: serviceAccountTokensApiOptions(organization, serviceAccountId).queryKey, + }), + }); +} diff --git a/static/app/views/settings/organizationServiceAccounts/serviceAccountDetails.spec.tsx b/static/app/views/settings/organizationServiceAccounts/serviceAccountDetails.spec.tsx index 843caedcb6fa..f29bad723a19 100644 --- a/static/app/views/settings/organizationServiceAccounts/serviceAccountDetails.spec.tsx +++ b/static/app/views/settings/organizationServiceAccounts/serviceAccountDetails.spec.tsx @@ -44,6 +44,10 @@ describe('ServiceAccountDetails', () => { beforeEach(() => { MockApiClient.clearMockResponses(); ProjectsStore.loadInitialData([ProjectFixture({id: '1', slug: 'frontend'})]); + MockApiClient.addMockResponse({ + url: `/organizations/${organization.slug}/service-accounts/10/tokens/`, + body: [], + }); }); it('shows the account and the access each resource has', async () => { diff --git a/static/app/views/settings/organizationServiceAccounts/serviceAccountDetails.tsx b/static/app/views/settings/organizationServiceAccounts/serviceAccountDetails.tsx index 86daf9d31cc8..41c41e5172a9 100644 --- a/static/app/views/settings/organizationServiceAccounts/serviceAccountDetails.tsx +++ b/static/app/views/settings/organizationServiceAccounts/serviceAccountDetails.tsx @@ -29,6 +29,7 @@ import { ServiceAccountPermissionTable, } from './serviceAccountPermissionTable'; import {ProjectAccessBadges} from './serviceAccountProjectAccess'; +import {ServiceAccountTokens} from './serviceAccountTokens'; import type {ServiceAccount} from './types'; import {useCannotManageReason} from './useServiceAccountAccess'; @@ -151,6 +152,8 @@ export default function ServiceAccountDetails() { + + {t('Permissions')} diff --git a/static/app/views/settings/organizationServiceAccounts/serviceAccountForm.tsx b/static/app/views/settings/organizationServiceAccounts/serviceAccountForm.tsx index 2b0ccf6a79a9..6ec0b3e752a4 100644 --- a/static/app/views/settings/organizationServiceAccounts/serviceAccountForm.tsx +++ b/static/app/views/settings/organizationServiceAccounts/serviceAccountForm.tsx @@ -25,7 +25,7 @@ import { import type {ServiceAccount, ServiceAccountInput} from './types'; import {useServiceAccountAccess} from './useServiceAccountAccess'; -const MAX_NAME_LENGTH = 64; +export const MAX_NAME_LENGTH = 64; const schema = z.object({ name: z.string().trim().min(1, t('Name is required')).max(MAX_NAME_LENGTH), @@ -41,13 +41,13 @@ type FormValues = z.infer; const FORM_FIELDS = ['name', 'projectIds', 'scopes'] as const; /** Service account errors are nested under `detail`, keyed by request field. */ -function getFieldErrors(error: RequestError) { +export function getDetailFieldErrors(error: RequestError, fields: readonly string[]) { const detail = error.responseJSON?.detail; if (!detail || typeof detail !== 'object') { return {}; } return Object.fromEntries( - FORM_FIELDS.flatMap(field => { + fields.flatMap(field => { const messages = (detail as Record)[field]; return Array.isArray(messages) && typeof messages[0] === 'string' ? [[field, {message: messages[0]}]] @@ -135,7 +135,7 @@ export function ServiceAccountForm({ getRequestErrorUserMessage(error, t('Unable to save service account.')) ); if (error instanceof RequestError) { - setFieldErrors(formApi, getFieldErrors(error)); + setFieldErrors(formApi, getDetailFieldErrors(error, FORM_FIELDS)); } } }, diff --git a/static/app/views/settings/organizationServiceAccounts/serviceAccountTokens.spec.tsx b/static/app/views/settings/organizationServiceAccounts/serviceAccountTokens.spec.tsx new file mode 100644 index 000000000000..b62b2b31edf1 --- /dev/null +++ b/static/app/views/settings/organizationServiceAccounts/serviceAccountTokens.spec.tsx @@ -0,0 +1,196 @@ +import {OrganizationFixture} from 'sentry-fixture/organization'; + +import { + render, + renderGlobalModal, + screen, + userEvent, + waitFor, + within, +} from 'sentry-test/reactTestingLibrary'; + +import {ServiceAccountTokens} from './serviceAccountTokens'; +import type {ServiceAccount, ServiceAccountToken} from './types'; + +describe('ServiceAccountTokens', () => { + const organization = OrganizationFixture({ + features: ['service-accounts'], + access: [...OrganizationFixture().access, 'service_account:write'], + }); + const tokensUrl = `/organizations/${organization.slug}/service-accounts/10/tokens/`; + const account: ServiceAccount = { + id: '10', + name: 'github-actions-deploy', + // The fixture org's access doesn't include `event:read`. + scopes: ['event:read', 'org:read', 'project:read', 'project:write'], + projectIds: ['1'], + allProjects: false, + ownerKind: 'organization', + dateCreated: '2026-11-01T00:00:00Z', + }; + const token: ServiceAccountToken = { + id: '5', + name: 'GitHub Actions: prod', + scopes: ['project:read'], + tokenLastCharacters: 'a1b2', + dateCreated: '2026-11-02T00:00:00Z', + dateLastUsed: null, + dateExpires: null, + }; + + function renderTokens(serviceAccount = account) { + render(, {organization}); + renderGlobalModal(); + } + + beforeEach(() => { + MockApiClient.clearMockResponses(); + }); + + it('lists tokens without their values', async () => { + MockApiClient.addMockResponse({url: tokensUrl, body: [token]}); + + renderTokens(); + + expect(await screen.findByText('GitHub Actions: prod')).toBeInTheDocument(); + expect(screen.getByText('sntrym_************a1b2')).toBeInTheDocument(); + expect(screen.getByText('1 scope')).toBeInTheDocument(); + expect(screen.getAllByText('Never')).toHaveLength(2); + }); + + it('shows an empty state', async () => { + MockApiClient.addMockResponse({url: tokensUrl, body: []}); + + renderTokens(); + + expect(await screen.findByText('No tokens yet')).toBeInTheDocument(); + expect(screen.getByRole('button', {name: 'Create Token'})).toBeEnabled(); + }); + + it('creates a token and shows its value once', async () => { + MockApiClient.addMockResponse({url: tokensUrl, body: []}); + const createRequest = MockApiClient.addMockResponse({ + url: tokensUrl, + method: 'POST', + statusCode: 201, + body: {...token, token: 'sntrym_secret-value'}, + }); + + renderTokens(); + + await userEvent.click(await screen.findByRole('button', {name: 'Create Token'})); + await userEvent.type( + await screen.findByRole('textbox', {name: 'Name'}), + 'GitHub Actions: prod' + ); + await userEvent.click( + within(screen.getByRole('dialog')).getByRole('button', {name: 'Create Token'}) + ); + + expect(await screen.findByDisplayValue('sntrym_secret-value')).toBeInTheDocument(); + expect( + screen.getByText('Copy this token now. You won’t be able to see it again.') + ).toBeInTheDocument(); + + const {data} = createRequest.mock.calls[0][1]; + expect(data.name).toBe('GitHub Actions: prod'); + expect(data.scopes).toEqual(['org:read', 'project:read', 'project:write']); + const days = (Date.parse(data.expiresAt) - Date.now()) / (24 * 60 * 60 * 1000); + expect(Math.round(days)).toBe(30); + + await userEvent.click(screen.getByRole('button', {name: 'Done'})); + await waitFor(() => + expect(screen.queryByDisplayValue('sntrym_secret-value')).not.toBeInTheDocument() + ); + }); + + it('creates a token with chosen scopes and no expiration', async () => { + MockApiClient.addMockResponse({url: tokensUrl, body: []}); + const createRequest = MockApiClient.addMockResponse({ + url: tokensUrl, + method: 'POST', + statusCode: 201, + body: {...token, token: 'sntrym_secret-value'}, + }); + + renderTokens(); + + await userEvent.click(await screen.findByRole('button', {name: 'Create Token'})); + await userEvent.type(await screen.findByRole('textbox', {name: 'Name'}), 'Scripts'); + await userEvent.click(screen.getByRole('radio', {name: 'Choose scopes'})); + await userEvent.click(screen.getByRole('checkbox', {name: 'project:write'})); + await userEvent.click(screen.getByRole('checkbox', {name: 'org:read'})); + expect(screen.queryByRole('checkbox', {name: 'event:read'})).not.toBeInTheDocument(); + + await userEvent.click(screen.getByRole('textbox', {name: 'Expiration'})); + await userEvent.click(screen.getByRole('menuitemradio', {name: 'No expiration'})); + await userEvent.click( + within(screen.getByRole('dialog')).getByRole('button', {name: 'Create Token'}) + ); + + await screen.findByDisplayValue('sntrym_secret-value'); + expect(createRequest).toHaveBeenCalledWith( + tokensUrl, + expect.objectContaining({ + data: {name: 'Scripts', scopes: ['project:read'], expiresAt: null}, + }) + ); + }); + + it('shows errors from the API', async () => { + MockApiClient.addMockResponse({url: tokensUrl, body: []}); + MockApiClient.addMockResponse({ + url: tokensUrl, + method: 'POST', + statusCode: 400, + body: {detail: {scopes: ["You can't grant scopes you don't have: org:read"]}}, + }); + + renderTokens(); + + await userEvent.click(await screen.findByRole('button', {name: 'Create Token'})); + await userEvent.type(await screen.findByRole('textbox', {name: 'Name'}), 'Scripts'); + await userEvent.click( + within(screen.getByRole('dialog')).getByRole('button', {name: 'Create Token'}) + ); + + expect( + await screen.findByText("You can't grant scopes you don't have: org:read") + ).toBeInTheDocument(); + expect(screen.queryByText('Token created')).not.toBeInTheDocument(); + }); + + it('revokes a token after confirming', async () => { + MockApiClient.addMockResponse({url: tokensUrl, body: [token]}); + const revokeRequest = MockApiClient.addMockResponse({ + url: `${tokensUrl}5/`, + method: 'DELETE', + }); + + renderTokens(); + + await userEvent.click( + await screen.findByRole('button', {name: 'Revoke GitHub Actions: prod'}) + ); + expect( + await screen.findByText(/Anything using sntrym_\*+a1b2 stops working right away/) + ).toBeInTheDocument(); + await userEvent.click(screen.getByRole('button', {name: 'Revoke Token'})); + + await waitFor(() => expect(revokeRequest).toHaveBeenCalled()); + }); + + it("can't manage tokens of an account owned by a Seer automation", async () => { + MockApiClient.addMockResponse({url: tokensUrl, body: [token]}); + + renderTokens({...account, ownerKind: 'seer_workflow_config'}); + + expect( + await screen.findByRole('button', {name: 'Revoke GitHub Actions: prod'}) + ).toHaveAttribute('aria-disabled', 'true'); + expect(screen.getByRole('button', {name: 'Create Token'})).toHaveAttribute( + 'aria-disabled', + 'true' + ); + }); +}); diff --git a/static/app/views/settings/organizationServiceAccounts/serviceAccountTokens.tsx b/static/app/views/settings/organizationServiceAccounts/serviceAccountTokens.tsx new file mode 100644 index 000000000000..890c56e3a4c8 --- /dev/null +++ b/static/app/views/settings/organizationServiceAccounts/serviceAccountTokens.tsx @@ -0,0 +1,256 @@ +import {useState} from 'react'; +import {IconAdd} from '@sentry/icons/add'; +import {useQuery} from '@tanstack/react-query'; +import moment from 'moment-timezone'; + +import {Tag} from '@sentry/scraps/badge'; +import {Button} from '@sentry/scraps/button'; +import {openConfirmModal} from '@sentry/scraps/confirm'; +import {DateTime} from '@sentry/scraps/dateTime'; +import {EmptyState} from '@sentry/scraps/emptyState'; +import {InfoText} from '@sentry/scraps/info'; +import {Flex, Stack} from '@sentry/scraps/layout'; +import {openModal} from '@sentry/scraps/modal'; +import {Pagination} from '@sentry/scraps/pagination'; +import type {TableColumnConfig} from '@sentry/scraps/table'; +import {Heading, Text} from '@sentry/scraps/text'; +import {toast} from '@sentry/scraps/toast'; + +import {SimpleTable} from 'sentry/components/tables/simpleTable'; +import {TimeSince} from 'sentry/components/timeSince'; +import {t, tn} from 'sentry/locale'; +import {selectJsonWithHeaders} from 'sentry/utils/api/apiOptions'; +import {getPaginationProps} from 'sentry/utils/pagination'; +import {useOrganization} from 'sentry/utils/useOrganization'; +import {tokenPreview} from 'sentry/views/settings/organizationAuthTokens/tokenUtils'; + +import {CreateTokenModal} from './createTokenModal'; +import {NewTokenModal} from './newTokenModal'; +import { + serviceAccountTokensApiOptions, + useRevokeServiceAccountToken, +} from './serviceAccountApi'; +import type {ServiceAccount, ServiceAccountToken} from './types'; +import {useCannotManageReason} from './useServiceAccountAccess'; + +const COLUMNS: TableColumnConfig[] = [ + {key: 'name', width: 'minmax(0, 1fr)'}, + {key: 'token', width: 'max-content'}, + {key: 'scopes', width: 'max-content'}, + {key: 'created', width: 'max-content'}, + {key: 'lastUsed', width: 'max-content'}, + {key: 'expires', width: 'max-content'}, + {key: 'actions', width: 'max-content'}, +]; + +const EXPIRING_SOON_DAYS = 7; +const SERVICE_ACCOUNT_TOKEN_PREFIX = 'sntrym_'; + +function TokenScopes({ + token, + accountScopes, +}: { + accountScopes: string[]; + token: ServiceAccountToken; +}) { + const scopeList = ( + + {token.scopes.map(scope => ( + + {scope} + + ))} + + ); + const hasAccountScopes = accountScopes.every(scope => token.scopes.includes(scope)); + return ( + + {hasAccountScopes + ? t('Same as account') + : tn('%s scope', '%s scopes', token.scopes.length)} + + ); +} + +function TokenExpiry({dateExpires}: {dateExpires: string | null}) { + if (!dateExpires) { + return {t('Never')}; + } + const expires = moment(dateExpires); + if (expires.isBefore(moment())) { + return {t('Expired')}; + } + if (expires.diff(moment(), 'days') < EXPIRING_SOON_DAYS) { + const relative = expires.fromNow(); + return ( + {relative.charAt(0).toUpperCase() + relative.slice(1)} + ); + } + return ( + + + + ); +} + +export function ServiceAccountTokens({account}: {account: ServiceAccount}) { + const organization = useOrganization(); + const cannotManageReason = useCannotManageReason(account); + const [cursor, setCursor] = useState(); + const {data, isPending, isError, refetch} = useQuery({ + ...serviceAccountTokensApiOptions(organization, account.id, {cursor}), + select: selectJsonWithHeaders, + }); + const tokens = data?.json ?? []; + const revokeToken = useRevokeServiceAccountToken(organization, account.id); + + const openCreateToken = () => + openModal(deps => ( + + // Clicking outside or pressing Escape would lose the only copy of the token. + openModal(newTokenDeps => , { + closeEvents: 'none', + }) + } + /> + )); + + const confirmRevoke = (token: ServiceAccountToken) => + openConfirmModal({ + header: t('Revoke %s?', token.name), + message: t( + 'Anything using %s stops working right away. You can’t undo this.', + tokenPreview(token.tokenLastCharacters, SERVICE_ACCOUNT_TOKEN_PREFIX) + ), + confirmText: t('Revoke Token'), + priority: 'danger', + isDangerous: true, + errorMessage: t('Unable to revoke token. Try again.'), + onConfirm: () => + revokeToken.mutateAsync(token.id).then(() => { + toast.success(t('Token revoked.')); + }), + }); + + const disabledProps = cannotManageReason + ? {disabled: true, tooltipProps: {title: cannotManageReason}} + : {}; + + const createButton = ( + + ); + + const hasTokens = tokens.length > 0; + + return ( + + + + {t('Access Tokens')} + + {t( + 'Use a token to call the Sentry API as this service account. A token can’t do more than its account.' + )} + + + {hasTokens && createButton} + + + + {t('Name')} + {t('Token')} + {t('Scopes')} + {t('Created')} + {t('Last used')} + {t('Expires')} + + + } + > + {isError && ( + + )} + {!isError && isPending && } + {!isError && !isPending && !hasTokens && ( + + + + )} + {tokens.map(token => ( + + + + {token.name} + + + + + {tokenPreview(token.tokenLastCharacters, SERVICE_ACCOUNT_TOKEN_PREFIX)} + + + + + + + + + + + + {token.dateLastUsed ? ( + + ) : ( + {t('Never')} + )} + + + + + + + + + ))} + + setCursor(nextCursor)} + /> + + {hasTokens && ( + + {t( + 'To rotate a token, create a new one, switch your tools to it, then revoke the old one.' + )} + + )} + + ); +} diff --git a/static/app/views/settings/organizationServiceAccounts/types.tsx b/static/app/views/settings/organizationServiceAccounts/types.tsx index a215ff06e213..1ec21899c02c 100644 --- a/static/app/views/settings/organizationServiceAccounts/types.tsx +++ b/static/app/views/settings/organizationServiceAccounts/types.tsx @@ -20,3 +20,25 @@ export interface ServiceAccountInput { projectIds: number[]; scopes: string[]; } + +export interface ServiceAccountToken { + dateCreated: string; + dateExpires: string | null; + dateLastUsed: string | null; + id: string; + name: string; + scopes: string[]; + tokenLastCharacters: string; +} + +/** Only the response that creates a token includes its value. */ +export interface NewServiceAccountToken extends ServiceAccountToken { + token: string; +} + +export interface ServiceAccountTokenInput { + /** Null makes a token that never expires. */ + expiresAt: string | null; + name: string; + scopes: string[]; +}