Files
linux-cloud-router/web/src/CertificateDialog.tsx
T

163 lines
7.8 KiB
TypeScript

import UploadFile from '@mui/icons-material/UploadFile'
import {
Alert, Button, Dialog, DialogActions, DialogContent, DialogTitle, FormControlLabel, MenuItem, Radio, RadioGroup, Stack, TextField,
} from '@mui/material'
import { useState, type FormEvent } from 'react'
import { ROUTER_TEMPLATES, type Pki } from './api.ts'
/** A request of POST /ca/certificates: a CSR to sign, or a subject and names for a key the server makes into a PFX file. */
export type IssueRequest =
| { ca: string; template: string; csr: string }
| { ca: string; template: string; subject: string; sans: string[]; password: string }
/** The labels of the kinds of common name of a template. */
const SUBJECT_LABELS: Record<string, string> = { dns: 'a DNS name', name: 'a name', email: 'an e-mail address' }
/** A list typed as text separated by commas. */
function listOf(text: string) {
return text.split(',').map((item) => item.trim()).filter((item) => item !== '')
}
/**
* A dialog that issues a certificate from an active issuing CA with one of the templates it issues but those only the
* router issues: from a CSR, pasted or read from a file, or with a key the server makes for a subject and subject
* alternative names, returned once in a PFX file protected by a password. onSave sends the request and saves what the
* router answers; the dialog closes when it succeeds and shows the server's message when it fails.
*/
export default function CertificateDialog(props: { pki: Pki; onSave: (request: IssueRequest) => Promise<void>; onCancel: () => void }) {
const authorities = props.pki.status.authorities
.map((authority) => ({ ...authority, templates: authority.templates.filter((name) => !(ROUTER_TEMPLATES as readonly string[]).includes(name)) }))
.filter((authority) => authority.state === 'active' && authority.templates.length > 0)
const [ca, setCa] = useState(authorities[0]?.name ?? '')
const [template, setTemplate] = useState(authorities[0]?.templates[0] ?? '')
const [mode, setMode] = useState<'csr' | 'key'>('csr')
const [csr, setCsr] = useState('')
const [subject, setSubject] = useState('')
const [sans, setSans] = useState('')
const [password, setPassword] = useState('')
const [repeated, setRepeated] = useState('')
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
const templates = authorities.find((authority) => authority.name === ca)?.templates ?? []
const values = props.pki.templates[template]
const csrProblem = mode === 'csr' && csr.trim() !== '' && !csr.includes('-----BEGIN CERTIFICATE REQUEST-----') ? 'A PEM certificate signing request.' : ''
const repeatProblem = mode === 'key' && repeated !== '' && repeated !== password ? 'The passwords differ.' : ''
const blocked = ca === '' || template === '' || (mode === 'csr'
? csr.trim() === '' || csrProblem !== ''
: subject.trim() === '' || password === '' || password !== repeated)
async function submit(event: FormEvent) {
event.preventDefault()
if (blocked) {
return
}
setSaving(true)
setError(null)
try {
await props.onSave(mode === 'csr'
? { ca, template, csr: csr.trim() }
: { ca, template, subject: subject.trim(), sans: listOf(sans), password })
} catch (caught) {
setError((caught as Error).message)
setSaving(false)
}
}
return (
<Dialog open onClose={(_event, reason) => reason !== 'backdropClick' && props.onCancel()} maxWidth="sm" fullWidth slotProps={{ paper: { component: 'form', onSubmit: submit } }}>
<DialogTitle>Issue a certificate</DialogTitle>
<DialogContent>
<Stack sx={{ gap: 2, pt: 1 }}>
{error && <Alert severity="error" sx={{ whiteSpace: 'pre-line' }}>{error}</Alert>}
{authorities.length === 0 && <Alert severity="info">No active issuing CA issues certificates for other systems; add one in Settings.</Alert>}
<Stack direction="row" sx={{ gap: 2 }}>
<TextField
select
fullWidth
label="Issuing CA"
value={ca}
onChange={(event) => {
setCa(event.target.value)
setTemplate(authorities.find((authority) => authority.name === event.target.value)?.templates[0] ?? '')
}}
>
{authorities.map((authority) => <MenuItem key={authority.name} value={authority.name}>{`${authority.name}: ${authority.common_name}`}</MenuItem>)}
</TextField>
<TextField select fullWidth label="Template" value={template} onChange={(event) => setTemplate(event.target.value)}>
{templates.map((name) => <MenuItem key={name} value={name}>{name}</MenuItem>)}
</TextField>
</Stack>
<RadioGroup row value={mode} onChange={(event) => setMode(event.target.value as 'csr' | 'key')}>
<FormControlLabel value="csr" control={<Radio />} label="Sign a CSR" />
<FormControlLabel value="key" control={<Radio />} label="Make a key and a PFX file" />
</RadioGroup>
{mode === 'csr' ? (
<>
<TextField
label="CSR"
value={csr}
multiline
minRows={6}
maxRows={16}
autoComplete="off"
error={csrProblem !== ''}
helperText={csrProblem || "The certificate takes the CSR's key, common name and subject alternative names, checked against the template."}
slotProps={{ htmlInput: { sx: { fontFamily: 'monospace', fontSize: 12 } } }}
onChange={(event) => setCsr(event.target.value)}
/>
<Button component="label" variant="outlined" startIcon={<UploadFile />} sx={{ alignSelf: 'flex-start' }}>
Read a file
<input hidden type="file" accept=".csr,.pem,.req,.txt" onChange={(event) => void event.target.files?.[0]?.text().then(setCsr)} />
</Button>
</>
) : (
<>
<TextField
label="Subject"
value={subject}
autoComplete="off"
helperText={values ? `The common name: ${SUBJECT_LABELS[values.subject] ?? values.subject}.` : ''}
onChange={(event) => setSubject(event.target.value)}
/>
<TextField
label="Subject alternative names"
value={sans}
autoComplete="off"
disabled={values !== undefined && values.sans.length === 0}
helperText={values ? `Separated by commas; the template allows ${values.sans.join(', ') || 'none'}.` : ''}
onChange={(event) => setSans(event.target.value)}
/>
<Stack direction="row" sx={{ gap: 2 }}>
<TextField
fullWidth
label="PFX password"
type="password"
value={password}
autoComplete="new-password"
helperText="Protects the key in the PFX file; the server keeps no copy of the key."
onChange={(event) => setPassword(event.target.value)}
/>
<TextField
fullWidth
label="Repeat the password"
type="password"
value={repeated}
autoComplete="new-password"
error={repeatProblem !== ''}
helperText={repeatProblem}
onChange={(event) => setRepeated(event.target.value)}
/>
</Stack>
</>
)}
</Stack>
</DialogContent>
<DialogActions>
<Button onClick={props.onCancel}>Cancel</Button>
<Button type="submit" variant="contained" disabled={saving || blocked}>Issue</Button>
</DialogActions>
</Dialog>
)
}