import Add from '@mui/icons-material/Add' import Delete from '@mui/icons-material/Delete' import { Alert, Autocomplete, Box, Button, Checkbox, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, FormGroup, IconButton, Stack, Switch, TextField, Tooltip, Typography, } from '@mui/material' import { useState, type FormEvent } from 'react' import type { Role, User } from './api.ts' /** The names linux-manager-user accepts for a service account: a user name or a GUID in lowercase. */ const NAME_PATTERN = /^[a-z][a-z0-9-]{0,30}[a-z0-9]$|^[a-z]$|^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/ /** A random GUID (version 4) in lowercase, from crypto.getRandomValues, which pages served over plain HTTP have too. */ function newGuid() { const bytes = crypto.getRandomValues(new Uint8Array(16)) bytes[6] = (bytes[6] & 0x0f) | 0x40 bytes[8] = (bytes[8] & 0x3f) | 0x80 const hex = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('') return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}` } /** The e-mail addresses linux-manager-user accepts: one @, no spaces, and a dot in the domain. */ const EMAIL_PATTERN = /^[^@\s]+@[^@\s]+\.[^@\s]+$/ /** The longest display name and description the server accepts. */ const DISPLAY_NAME_MAX = 64 const DESCRIPTION_MAX = 256 /** The most URIs of each kind and allowed groups of an OpenID Provider client, and the longest URI, the server accepts. */ const CLIENT_VALUES_MAX = 16 const URI_MAX = 1024 /** The hosts a client's URI may name over plain HTTP. */ const LOOPBACK_HOSTS = ['localhost', '127.0.0.1', '[::1]'] /** The names of a role and of a scope of a resource the server accepts. */ const ROLE_NAME = /^[A-Za-z][A-Za-z0-9._-]{0,63}$/ const SCOPE_NAME = /^[a-z][a-z0-9._-]{0,63}$/ /** The grants a client may have besides the authorization code, with their labels. */ const GRANTS = [['client_credentials', 'Client credentials'], ['device_code', 'Device authorization']] as const /** The settings of a service account that /service-accounts takes; an empty one removes it when editing. */ export type ServiceAccountSettings = { display_name: string description: string email: string redirect_uris: string[] post_logout_redirect_uris: string[] allowed_groups: string[] grants: string[] public_client: boolean client_scopes: string[] resource_scopes: string[] roles: Role[] } /** Why the roles are refused by the server, or ''. */ function rolesProblem(roles: Role[]) { for (const role of roles) { if (!ROLE_NAME.test(role.name.trim())) { return 'A role name is up to 64 letters, digits, dots, underscores and dashes, starting with a letter.' } if (role.description.trim().length > DESCRIPTION_MAX) { return `A role description has at most ${DESCRIPTION_MAX} characters.` } } const names = roles.map((role) => role.name.trim().toLowerCase()) return new Set(names).size === names.length ? '' : 'Each role name may appear once.' } /** The non-empty lines of a text field, trimmed. */ function lines(text: string) { return text.split('\n').map((line) => line.trim()).filter((line) => line !== '') } /** Why the URIs of a text field are refused by the server, or ''. */ function urisProblem(text: string) { const uris = lines(text) if (uris.length > CLIENT_VALUES_MAX) { return `At most ${CLIENT_VALUES_MAX} URIs.` } for (const uri of uris) { let parsed: URL try { parsed = new URL(uri) } catch { return `${uri} is not a URI.` } if (uri.length > URI_MAX || uri.includes('#') || !(parsed.protocol === 'https:' || (parsed.protocol === 'http:' && LOOPBACK_HOSTS.includes(parsed.hostname)))) { return `${uri}: an https URI, or an http URI of localhost, without a fragment.` } } return '' } /** * A dialog that adds a service account, with its name, a new GUID unless replaced by a user name, display name, description, optional e-mail address and a * password typed twice, or, given an account, edits its display name, description and e-mail address. Both also set the OpenID Provider settings. As a * client: the redirect URIs and the post-logout redirect URIs, one per line, the allowed groups, chosen from groups, the grants, whether it is public, with * no secret, which client credentials need, and the client scopes, chosen from scopes, those of every resource; an account with redirect URIs or grants is * a client, its name the client ID and its password the secret. As a resource: its scopes, typed, and its roles, each with a name, a description and the * groups and accounts, chosen from accounts, it is assigned to. onSave sends them, trimmed, with the password when adding; the dialog closes when it * succeeds and shows the server's message when it fails. */ export default function ServiceAccountDialog(props: { account?: User groups: string[] accounts: string[] scopes: string[] onSave: (name: string, settings: ServiceAccountSettings, password: string) => Promise onCancel: () => void }) { const adding = props.account === undefined const [name, setName] = useState(() => props.account?.name ?? newGuid()) const [displayName, setDisplayName] = useState(props.account?.display_name ?? '') const [description, setDescription] = useState(props.account?.description ?? '') const [email, setEmail] = useState(props.account?.email ?? '') const [redirectUris, setRedirectUris] = useState((props.account?.redirect_uris ?? []).join('\n')) const [logoutUris, setLogoutUris] = useState((props.account?.post_logout_redirect_uris ?? []).join('\n')) const [allowedGroups, setAllowedGroups] = useState(props.account?.allowed_groups ?? []) const [grants, setGrants] = useState(props.account?.grants ?? []) const [publicClient, setPublicClient] = useState(props.account?.public_client ?? false) const [clientScopes, setClientScopes] = useState(props.account?.client_scopes ?? []) const [resourceScopes, setResourceScopes] = useState(props.account?.resource_scopes ?? []) const [roles, setRoles] = useState(props.account?.roles ?? []) const [password, setPassword] = useState('') const [again, setAgain] = useState('') const [saving, setSaving] = useState(false) const [error, setError] = useState(null) const nameProblem = adding && name !== '' && !NAME_PATTERN.test(name) ? 'A GUID, or up to 32 lower case letters, digits and dashes, starting with a letter and not ending with a dash.' : '' const displayNameProblem = displayName.trim().length > DISPLAY_NAME_MAX ? `At most ${DISPLAY_NAME_MAX} characters.` : '' const descriptionProblem = description.trim().length > DESCRIPTION_MAX ? `At most ${DESCRIPTION_MAX} characters.` : '' const emailProblem = email.trim() !== '' && !EMAIL_PATTERN.test(email.trim()) ? 'Not an e-mail address.' : '' const againProblem = again !== '' && again !== password ? 'The passwords differ.' : '' const redirectProblem = urisProblem(redirectUris) const logoutProblem = urisProblem(logoutUris) const groupsProblem = allowedGroups.length > CLIENT_VALUES_MAX ? `At most ${CLIENT_VALUES_MAX} groups.` : '' const clientScopesProblem = clientScopes.length > CLIENT_VALUES_MAX ? `At most ${CLIENT_VALUES_MAX} scopes.` : '' const resourceScopesProblem = resourceScopes.length > CLIENT_VALUES_MAX ? `At most ${CLIENT_VALUES_MAX} scopes.` : resourceScopes.every((scope) => SCOPE_NAME.test(scope)) ? '' : 'A scope is up to 64 lower case letters, digits, dots, underscores and dashes, starting with a letter.' const roleProblem = rolesProblem(roles) const blocked = name === '' || nameProblem !== '' || displayNameProblem !== '' || descriptionProblem !== '' || emailProblem !== '' || redirectProblem !== '' || logoutProblem !== '' || groupsProblem !== '' || clientScopesProblem !== '' || resourceScopesProblem !== '' || roleProblem !== '' || (adding && (password === '' || again !== password)) /** Changes one role of the list. */ function setRole(index: number, change: Partial) { setRoles((current) => current.map((role, at) => (at === index ? { ...role, ...change } : role))) } async function submit(event: FormEvent) { event.preventDefault() if (blocked) { return } setSaving(true) setError(null) try { await props.onSave(name, { display_name: displayName.trim(), description: description.trim(), email: email.trim(), redirect_uris: lines(redirectUris), post_logout_redirect_uris: lines(logoutUris), allowed_groups: allowedGroups, grants: GRANTS.map(([grant]) => grant).filter((grant) => grants.includes(grant)), public_client: publicClient, client_scopes: [...clientScopes].sort(), resource_scopes: [...resourceScopes].sort(), roles: roles.map((role) => ({ name: role.name.trim(), description: role.description.trim(), groups: [...role.groups].sort(), accounts: [...role.accounts].sort(), })).sort((one, other) => one.name.localeCompare(other.name)), }, password) } catch (caught) { setError((caught as Error).message) setSaving(false) } } return ( reason !== 'backdropClick' && props.onCancel()} maxWidth="sm" fullWidth slotProps={{ paper: { component: 'form', onSubmit: submit } }}> {adding ? 'Add service account' : `Edit service account ${props.account?.name}`} {error && {error}} setName(event.target.value.trim().toLowerCase())} /> setDisplayName(event.target.value)} /> setDescription(event.target.value)} /> setEmail(event.target.value)} /> As an OpenID Connect client setRedirectUris(event.target.value)} /> setLogoutUris(event.target.value)} /> setAllowedGroups(next)} renderInput={(params) => ( )} /> Grants besides the authorization code, which the redirect URIs give {GRANTS.map(([grant, label]) => ( setGrants((current) => (event.target.checked ? [...current, grant] : current.filter((value) => value !== grant)))} /> )} /> ))} { setPublicClient(event.target.checked) if (event.target.checked) { setGrants((current) => current.filter((value) => value !== 'client_credentials')) } }} /> )} /> setClientScopes(next)} renderInput={(params) => ( )} /> As a resource setResourceScopes(next.map((scope) => scope.trim()).filter((scope) => scope !== ''))} renderInput={(params) => ( '}:; type one and press Enter.`} /> )} /> Roles, which the tokens for this resource carry for the groups and accounts they are assigned to {roles.map((role, index) => ( setRole(index, { name: event.target.value })} /> setRole(index, { description: event.target.value })} /> setRole(index, { groups: next })} renderInput={(params) => } /> setRole(index, { accounts: next })} renderInput={(params) => } /> setRoles((current) => current.filter((_role, at) => at !== index))}> ))} {roleProblem && {roleProblem}} {adding && ( <> setPassword(event.target.value)} /> setAgain(event.target.value)} /> )} ) }