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

809 lines
36 KiB
TypeScript

import Add from '@mui/icons-material/Add'
import Block from '@mui/icons-material/Block'
import Delete from '@mui/icons-material/Delete'
import Download from '@mui/icons-material/Download'
import Edit from '@mui/icons-material/Edit'
import Refresh from '@mui/icons-material/Refresh'
import Settings from '@mui/icons-material/Settings'
import Key from '@mui/icons-material/Key'
import UploadFile from '@mui/icons-material/UploadFile'
import {
Alert, Box, Button, Chip, IconButton, MenuItem, Stack, Tab, Table, TableBody, TableCell, TableHead, TableRow, Tabs, TextField,
Tooltip, Typography,
} from '@mui/material'
import { useCallback, useEffect, useState } from 'react'
import { when } from './BackupSummary.tsx'
import CertificateDialog from './CertificateDialog.tsx'
import ConfirmDialog, { type ConfirmDialogProps } from './ConfirmDialog.tsx'
import ImportDialog from './ImportDialog.tsx'
import IssuingCaDialog from './IssuingCaDialog.tsx'
import TemplateDialog from './TemplateDialog.tsx'
import Toolbar from './Toolbar.tsx'
import EkuDialog from './EkuDialog.tsx'
import PkiSettingsDialog, { PUBLISH_LABELS, ROOT_SOURCE_LABELS } from './PkiSettingsDialog.tsx'
import { Board, BoardButtons, useBoard, type BoardPanel } from './PanelBoard.tsx'
import { Pairs, Section } from './ServerPanel.tsx'
import ServerCertificatePanel from './ServerCertificatePanel.tsx'
import SetupCodeDialog from './SetupCodeDialog.tsx'
import {
ApiError, BUNDLE_SHAPE, CA_IMPORTED_SHAPE, CRL_IMPORTED_SHAPE, CSR_SHAPE, ISSUED_SHAPE, PFX_SHAPE, PKI_SETTINGS_SHAPE, PKI_SHAPE, REVOKED_SHAPE,
TOKEN_SHAPE,
BUILTIN_TEMPLATES, REVOKE_REASONS, request, type Pki, type PkiCertificate, type PkiIssuingCa, type PkiTemplate,
} from './api.ts'
import { saveFile } from './saveFile.ts'
/** The tabs of the page: the server's HTTPS (ServerCertificatePanel), the root and the general information, the
* templates, the extended key usages, the issuing CAs. */
type View = 'server' | 'root' | 'templates' | 'usages' | 'issuing'
/** The localStorage keys of the layouts of the Root and the Issuing CAs tabs. */
const ROOT_LAYOUT_KEY = 'linux-manager-ui.certificates-root-layout'
const ISSUING_LAYOUT_KEY = 'linux-manager-ui.certificates-issuing-layout'
/** The CAs above the issuing CAs, whose certificates the Issuing CAs tab leaves out. */
const UPPER_CAS = ['root', 'upstream']
/** Where the root CRL came from. */
const CRL_SOURCE_LABELS: Record<string, string> = { signed: 'signed by the server', uploaded: 'uploaded', fetched: 'fetched from Simple CA' }
/** The note shown after a change, which the server applies when linux-manager-setup has run again. */
const APPLIED = 'The server applies the change in the background.'
/** The colour of each state of an issuing CA and of a certificate. */
const STATE_COLORS: Record<string, 'success' | 'warning' | 'error' | 'default'> = {
active: 'success',
valid: 'success',
pending: 'warning',
off: 'default',
missing: 'error',
expired: 'default',
revoked: 'error',
}
/** The labels of the revocation reasons. */
const REASON_LABELS: Record<string, string> = {
unspecified: 'Unspecified',
key_compromise: 'Key compromise',
affiliation_changed: 'Affiliation changed',
superseded: 'Superseded',
cessation_of_operation: 'Cessation of operation',
privilege_withdrawn: 'Privilege withdrawn',
}
/**
* The server's certificates in tabs: Server, the server's HTTPS (ServerCertificatePanel), shown first and also
* while the PKI cannot be read; Root, the root CA with the general settings and the certificates of the issuing CAs;
* Templates, the certificate templates, which are added, changed, removed and reset there; Extended key usages, the
* built-in ones and the custom ones, which are added, changed and removed there; Issuing CAs, the built-in p2s, s2s and
* servers and the custom CAs, which are added, changed and removed there, with the certificates of all of them, filtered
* by CA. The warnings are above the tabs, and so are Issue and Settings but on the Server tab, whose Refresh reads it
* again. Settings edits the pki section, Issue issues a certificate from a CSR or into a PFX file, a
* certificate of another system or of the server is revoked, an issuing CA waiting for the offline root gives its CSR
* and takes its signed certificate, the offline root takes its certificate and a CRL signed offline, and a Simple CA
* root takes a setup code for a new token. The panels of the Root and the Issuing CAs tabs are on a PanelBoard per tab
* whose layout is kept in the browser.
*/
export default function CertificatesPanel() {
const [pki, setPki] = useState<Pki | null>(null)
const [error, setError] = useState<string | null>(null)
const [unavailable, setUnavailable] = useState(false)
const [note, setNote] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
const [editing, setEditing] = useState(false)
const [authority, setAuthority] = useState<{ name?: string } | null>(null)
const [template, setTemplate] = useState<{ name?: string } | null>(null)
const [usage, setUsage] = useState<{ name?: string } | null>(null)
const [issuing, setIssuing] = useState(false)
const [importing, setImporting] = useState<string | null>(null)
const [uploading, setUploading] = useState(false)
const [entering, setEntering] = useState(false)
const [confirm, setConfirm] = useState<ConfirmDialogProps | null>(null)
const [filter, setFilter] = useState('')
const [view, setView] = useState<View>('server')
const [serverRead, setServerRead] = useState(0)
const rootBoard = useBoard(ROOT_LAYOUT_KEY)
const issuingBoard = useBoard(ISSUING_LAYOUT_KEY)
const refresh = useCallback(async () => {
setBusy(true)
try {
setPki(await request<Pki>('GET', '/ca', PKI_SHAPE))
setError(null)
setUnavailable(false)
} catch (caught) {
const failure = caught as ApiError
setPki(null)
setUnavailable(failure.status === 404)
setError(failure.message)
} finally {
setBusy(false)
}
}, [])
useEffect(() => {
void refresh()
}, [refresh])
/** Saves the certificates a client trusts the CA with: the root alone, or an issuing CA followed by the root. */
async function downloadBundle(name: string) {
try {
const { pem } = await request<{ name: string; pem: string }>('GET', `/ca/bundle/${name}`, BUNDLE_SHAPE)
saveFile(name === 'root' ? 'root-ca.pem' : `${name}-ca-bundle.pem`, pem, 'application/x-pem-file')
setError(null)
} catch (caught) {
setError((caught as Error).message)
}
}
async function downloadCsr(name: string) {
try {
const { csr, extensions } = await request<{ csr: string; extensions: string }>('GET', `/ca/issuing/${name}/csr`, CSR_SHAPE)
saveFile(`${name}.csr`, csr, 'application/pkcs10')
saveFile(`${name}-extensions.cnf`, extensions, 'text/plain')
setError(null)
} catch (caught) {
setError((caught as Error).message)
}
}
/** Writes the general-purpose issuing CAs: the current ones with name set to values, or without it when values is null. */
async function saveAuthority(name: string, values: PkiIssuingCa | null) {
const { [name]: _current, ...others } = pki?.settings.issuing_cas ?? {}
await request('PUT', '/ca', PKI_SETTINGS_SHAPE, { issuing_cas: values === null ? others : { ...others, [name]: values } })
setNote(APPLIED)
await refresh()
}
/** Writes the templates of pki.templates: the current ones with name set to values, or without it when values is
* null, which removes a template of the server's own or brings a built-in one back to its defaults. */
async function saveTemplate(name: string, values: PkiTemplate | null) {
const { [name]: _current, ...others } = pki?.settings.templates ?? {}
await request('PUT', '/ca', PKI_SETTINGS_SHAPE, { templates: values === null ? others : { ...others, [name]: values } })
setNote(APPLIED)
await refresh()
}
/** Writes the custom extended key usages: the current ones with name set to oid, or without it when oid is null. */
async function saveUsage(name: string, oid: string | null) {
const { [name]: _current, ...others } = pki?.settings.extended_key_usages ?? {}
await request('PUT', '/ca', PKI_SETTINGS_SHAPE, { extended_key_usages: oid === null ? others : { ...others, [name]: oid } })
setNote(APPLIED)
await refresh()
}
function removeUsage(name: string) {
setConfirm({
title: 'Remove extended key usage',
message: `Remove extended key usage ${name}? The server refuses while a template gives it; certificates issued with it keep it.`,
confirmLabel: 'Remove',
destructive: true,
onCancel: () => setConfirm(null),
onConfirm: () => {
setConfirm(null)
setBusy(true)
saveUsage(name, null)
.then(() => setError(null))
.catch((caught: Error) => setError(caught.message))
.finally(() => setBusy(false))
},
})
}
function removeTemplate(name: string, builtin: boolean) {
setConfirm({
title: builtin ? 'Reset template' : 'Remove template',
message: builtin
? `Bring template ${name} back to its built-in options? The certificates issued afterwards follow them.`
: `Remove template ${name}? The server refuses while an issuing CA issues it; certificates issued with it stay valid.`,
confirmLabel: builtin ? 'Reset' : 'Remove',
destructive: !builtin,
onCancel: () => setConfirm(null),
onConfirm: () => {
setConfirm(null)
setBusy(true)
saveTemplate(name, null)
.then(() => setError(null))
.catch((caught: Error) => setError(caught.message))
.finally(() => setBusy(false))
},
})
}
function removeAuthority(name: string) {
setConfirm({
title: 'Remove issuing CA',
message: `Remove issuing CA ${name}? The server retires it. ${{
local: 'It revokes its certificate on the root CRL.',
offline: 'Its certificate is revoked on the root CRL signed offline.',
'simple-ca': 'Its certificate is revoked in Simple CA.',
}[pki?.settings.root ?? 'local']} Its certificates stay valid until they expire or are revoked.`,
confirmLabel: 'Remove',
destructive: true,
onCancel: () => setConfirm(null),
onConfirm: () => {
setConfirm(null)
setBusy(true)
saveAuthority(name, null)
.then(() => setError(null))
.catch((caught: Error) => setError(caught.message))
.finally(() => setBusy(false))
},
})
}
function revoke(certificate: PkiCertificate) {
let reason: string = REVOKE_REASONS[0]
setConfirm({
title: 'Revoke certificate',
message: `Revoke certificate ${certificate.serial} of ${certificate.subject}? The CRL of ${certificate.ca} lists it at once.${certificate.kind === 'router' ? ' The server issues itself a new one.' : ''}`,
confirmLabel: 'Revoke',
destructive: true,
children: (
<TextField
select
fullWidth
label="Reason"
defaultValue={reason}
sx={{ mt: 2 }}
onChange={(event) => {
reason = event.target.value
}}
>
{REVOKE_REASONS.map((item) => <MenuItem key={item} value={item}>{REASON_LABELS[item]}</MenuItem>)}
</TextField>
),
onCancel: () => setConfirm(null),
onConfirm: () => {
setConfirm(null)
setBusy(true)
request<{ reissue: boolean }>('POST', `/ca/certificates/${certificate.serial}/revoke`, REVOKED_SHAPE, { reason })
.then((revoked) => {
setError(null)
setNote(revoked.reissue ? APPLIED : null)
})
.catch((caught: Error) => setError(caught.message))
.finally(() => void refresh())
},
})
}
const root = pki?.status.root
const authorities = pki?.status.authorities ?? []
const authorityNames = [...new Set([...authorities.map((authority) => authority.name),
...(pki?.certificates ?? []).map((certificate) => certificate.ca).filter((name) => !UPPER_CAS.includes(name))])]
const issuedCertificates = (pki?.certificates ?? [])
.filter((certificate) => !UPPER_CAS.includes(certificate.ca) && (filter === '' || certificate.ca === filter))
/** The actions of an issuing CA waiting for the offline root: download its CSR and import its signed certificate. */
const pendingActions = (name: string) => (
<>
<Tooltip title="Download the CSR and the openssl extensions to sign it with">
<span>
<IconButton size="small" disabled={busy} onClick={() => void downloadCsr(name)}><Download fontSize="small" /></IconButton>
</span>
</Tooltip>
<Tooltip title="Import the certificate signed by the root">
<span>
<IconButton size="small" disabled={busy} onClick={() => setImporting(name)}><UploadFile fontSize="small" /></IconButton>
</span>
</Tooltip>
</>
)
/** The active issuing CA a certificate the root issued belongs to, matched by its subject and expiry. */
const authorityOf = (certificate: PkiCertificate) => certificate.kind === 'ca' && certificate.state === 'valid'
? pki?.status.authorities.find((item) => item.state === 'active' && item.subject === certificate.subject && item.expires === certificate.expires)
: undefined
/** A table of certificates with their state and, for one of another system or of the server, Revoke; for an active
* issuing CA, the download of its CA bundle. */
const certificateTable = (list: PkiCertificate[]) => (
<Box sx={{ overflowX: 'auto' }}>
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Serial</TableCell>
<TableCell>CA</TableCell>
<TableCell>Kind</TableCell>
<TableCell>Template</TableCell>
<TableCell>Subject</TableCell>
<TableCell>Alternative names</TableCell>
<TableCell>Expires</TableCell>
<TableCell>State</TableCell>
<TableCell align="right">Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{list.length === 0 && (
<TableRow>
<TableCell colSpan={9} sx={{ color: 'text.secondary' }}>None.</TableCell>
</TableRow>
)}
{list.map((certificate) => (
<TableRow key={certificate.serial} hover>
<TableCell sx={{ fontFamily: 'monospace', whiteSpace: 'nowrap' }}>{certificate.serial}</TableCell>
<TableCell sx={{ whiteSpace: 'nowrap' }}>{certificate.ca}</TableCell>
<TableCell sx={{ whiteSpace: 'nowrap' }}>{certificate.kind}</TableCell>
<TableCell sx={{ whiteSpace: 'nowrap' }}>{certificate.template ?? '-'}</TableCell>
<TableCell>{certificate.subject}</TableCell>
<TableCell>{certificate.sans.join(', ') || '-'}</TableCell>
<TableCell sx={{ whiteSpace: 'nowrap' }}>{when(certificate.expires)}</TableCell>
<TableCell>
<Tooltip title={certificate.revoked ? `${when(certificate.revoked)}, ${REASON_LABELS[certificate.reason ?? ''] ?? certificate.reason ?? ''}` : ''}>
<Chip size="small" label={certificate.state} color={STATE_COLORS[certificate.state] ?? 'default'} />
</Tooltip>
</TableCell>
<TableCell align="right" sx={{ whiteSpace: 'nowrap' }}>
{authorityOf(certificate) && (
<Tooltip title="Download the CA bundle: the issuing CA and the CAs above it">
<span>
<IconButton size="small" disabled={busy} onClick={() => void downloadBundle(authorityOf(certificate)!.name)}>
<Download fontSize="small" />
</IconButton>
</span>
</Tooltip>
)}
{(certificate.kind === 'external' || certificate.kind === 'router') && certificate.state === 'valid' && (
<Tooltip title="Revoke">
<span>
<IconButton size="small" color="error" disabled={busy} onClick={() => revoke(certificate)}><Block fontSize="small" /></IconButton>
</span>
</Tooltip>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Box>
)
const rootPanels: BoardPanel[] = pki ? [
{
id: 'root',
title: 'Root CA',
content: (
<>
{root && (
<>
<Pairs
rows={[
['Source', root.source === 'simple-ca' ? `Simple CA, ${root.simple_ca_url}` : ROOT_SOURCE_LABELS[root.source]],
['State', <Chip size="small" label={root.state} color={STATE_COLORS[root.state] ?? 'default'} />],
['Subject', root.subject ?? '-'],
['Expires', when(root.expires)],
['CRL valid until', when(root.crl_next_update)],
['CRL', CRL_SOURCE_LABELS[root.crl_source ?? ''] ?? '-'],
...(root.upstream ? [
['Simple CA issuing CA', `${root.upstream.name}: ${root.upstream.subject}`],
['Its expiry', when(root.upstream.expires)],
['Its CRL valid until', when(root.upstream.crl_next_update)],
] as [string, string][] : []),
...(root.source === 'simple-ca' ? [['Token valid until', root.token_expires ? when(root.token_expires) : 'no token']] as [string, string][] : []),
]}
/>
{root.state === 'pending' && root.source === 'local' && (
<Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>The server creates it once a platform is chosen.</Typography>
)}
<Stack direction="row" sx={{ mt: 1, justifyContent: 'flex-end', gap: 1 }}>
{root.state === 'active' && (
<Button size="small" variant="outlined" startIcon={<Download />} disabled={busy} onClick={() => void downloadBundle('root')}>
Download root CA
</Button>
)}
{root.source === 'offline' && root.state === 'pending' && (
<Button size="small" variant="outlined" startIcon={<UploadFile />} disabled={busy} onClick={() => setImporting('root')}>
Import root certificate
</Button>
)}
{root.source === 'offline' && root.state === 'active' && (
<Button size="small" variant="outlined" startIcon={<UploadFile />} disabled={busy} onClick={() => setUploading(true)}>
Upload CRL
</Button>
)}
{root.source === 'simple-ca' && (
<Button size="small" variant="outlined" startIcon={<Key />} disabled={busy} onClick={() => setEntering(true)}>
Enter setup code
</Button>
)}
</Stack>
</>
)}
</>
),
},
{
id: 'general',
title: 'General',
content: (
<Pairs
rows={[
['Published at', pki.settings.publish.map((item) => PUBLISH_LABELS[item] ?? item).join('; ') || 'nowhere'],
['CA key', pki.settings.key],
['Lifetimes', `root ${pki.settings.root_days} days, issuing CAs ${pki.settings.ca_days} days`],
['CRLs', `issuing CAs ${pki.settings.crl_days} days, root ${pki.settings.root_crl_days} days`],
]}
/>
),
},
{
id: 'certificates',
title: 'Issuing CA certificates',
wide: true,
content: (
<>
{certificateTable(pki.certificates.filter((certificate) => certificate.ca === 'root' || certificate.ca === 'upstream'))}
{pki.status.retired.length > 0 && (
<Typography variant="body2" color="text.secondary" sx={{ mt: 1 }}>
{`Retired: ${pki.status.retired.map((retired) => `${retired.name} (${when(retired.retired)})`).join(', ')}`}
</Typography>
)}
</>
),
},
] : []
const issuingPanels: BoardPanel[] = pki ? [
{
id: 'authorities',
title: 'Issuing CAs',
wide: true,
content: (
<>
<Stack direction="row" sx={{ mb: 1, justifyContent: 'flex-end' }}>
<Button size="small" variant="outlined" startIcon={<Add />} disabled={busy} onClick={() => setAuthority({})}>
Add issuing CA
</Button>
</Stack>
<Box sx={{ overflowX: 'auto' }}>
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
<TableCell>Common name</TableCell>
<TableCell>State</TableCell>
<TableCell>Expires</TableCell>
<TableCell>CRL valid until</TableCell>
<TableCell>Templates</TableCell>
<TableCell>ACME</TableCell>
<TableCell align="right">Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{authorities.map((authority) => (
<TableRow key={authority.name} hover>
<TableCell sx={{ whiteSpace: 'nowrap' }}>
{authority.name}
{authority.builtin && <Chip size="small" label="built-in" variant="outlined" sx={{ ml: 1 }} />}
</TableCell>
<TableCell>{authority.subject ?? authority.common_name}</TableCell>
<TableCell>
<Tooltip title={authority.state === 'off' ? `Made once ${authority.component}.enabled is true` : ''}>
<Chip size="small" label={authority.state} color={STATE_COLORS[authority.state] ?? 'default'} />
</Tooltip>
</TableCell>
<TableCell>{when(authority.expires)}</TableCell>
<TableCell>{when(authority.crl_next_update)}</TableCell>
<TableCell>{authority.templates.join(', ')}</TableCell>
<TableCell sx={{ wordBreak: 'break-all' }}>{authority.acme_url ?? (authority.acme ? 'waits for the certificate' : '-')}</TableCell>
<TableCell align="right" sx={{ whiteSpace: 'nowrap' }}>
{authority.state === 'pending' && pki.settings.root === 'offline' && pendingActions(authority.name)}
{authority.state === 'active' && (
<Tooltip title="Download the CA bundle: the issuing CA and the CAs above it">
<span>
<IconButton size="small" disabled={busy} onClick={() => void downloadBundle(authority.name)}><Download fontSize="small" /></IconButton>
</span>
</Tooltip>
)}
{!authority.builtin && (
<>
<Tooltip title="Edit">
<span>
<IconButton size="small" disabled={busy} onClick={() => setAuthority({ name: authority.name })}><Edit fontSize="small" /></IconButton>
</span>
</Tooltip>
<Tooltip title="Remove">
<span>
<IconButton size="small" color="error" disabled={busy} onClick={() => removeAuthority(authority.name)}><Delete fontSize="small" /></IconButton>
</span>
</Tooltip>
</>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Box>
</>
),
},
{
id: 'certificates',
title: 'Certificates issued',
wide: true,
content: (
<>
<TextField select size="small" label="Issuing CA" value={filter} sx={{ mb: 1, minWidth: 200 }} onChange={(event) => setFilter(event.target.value)}>
<MenuItem value="">All</MenuItem>
{authorityNames.map((name) => <MenuItem key={name} value={name}>{name}</MenuItem>)}
</TextField>
{certificateTable(issuedCertificates)}
</>
),
},
] : []
return (
<Box component="section">
<Toolbar description="The server's HTTPS certificate and ACME CA, the root CA and the issuing CAs for P2S, site-to-site, servers and custom uses.">
{view !== 'server' && (
<>
<Button variant="contained" startIcon={<Add />} disabled={busy || pki === null} onClick={() => setIssuing(true)}>
Issue
</Button>
<Button variant="outlined" startIcon={<Settings />} disabled={busy || pki === null} onClick={() => setEditing(true)}>
Settings
</Button>
</>
)}
{view === 'root' && <BoardButtons board={rootBoard} />}
{view === 'issuing' && <BoardButtons board={issuingBoard} />}
<Button variant="outlined" startIcon={<Refresh />} disabled={busy} onClick={() => view === 'server' ? setServerRead(serverRead + 1) : void refresh()}>
Refresh
</Button>
</Toolbar>
{error && <Alert severity={unavailable ? 'info' : 'error'} sx={{ mb: 2, whiteSpace: 'pre-line' }}>{error}</Alert>}
{note && <Alert severity="info" sx={{ mb: 2 }} onClose={() => setNote(null)}>{note}</Alert>}
{pki?.status.warnings.map((warning) => <Alert key={warning} severity="warning" sx={{ mb: 2 }}>{warning}</Alert>)}
<Tabs value={view} onChange={(_event, next: View) => setView(next)} sx={{ mb: 2, borderBottom: 1, borderColor: 'divider' }}>
<Tab value="server" label="Server" />
{pki && <Tab value="root" label="Root" />}
{pki && <Tab value="templates" label="Templates" />}
{pki && <Tab value="usages" label="Extended key usages" />}
{pki && <Tab value="issuing" label="Issuing CAs" />}
</Tabs>
{view === 'server' && <ServerCertificatePanel key={serverRead} />}
{pki && view === 'root' && <Board board={rootBoard} panels={rootPanels} />}
{pki && view === 'templates' && (
<Box sx={{ display: 'grid', gap: 2 }}>
<Section title="Certificate templates">
<Stack direction="row" sx={{ mb: 1, justifyContent: 'flex-end' }}>
<Button size="small" variant="outlined" startIcon={<Add />} disabled={busy} onClick={() => setTemplate({})}>
Add template
</Button>
</Stack>
<Box sx={{ overflowX: 'auto' }}>
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
<TableCell>Key</TableCell>
<TableCell>Days</TableCell>
<TableCell>Subject</TableCell>
<TableCell>Key usage</TableCell>
<TableCell>Extended key usage</TableCell>
<TableCell>Alternative names</TableCell>
<TableCell>Policies</TableCell>
<TableCell>Issued by</TableCell>
<TableCell align="right">Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{Object.entries(pki.templates).map(([name, values]) => {
const builtin = (BUILTIN_TEMPLATES as readonly string[]).includes(name)
const changed = pki.settings.templates[name] !== undefined
return (
<TableRow key={name} hover>
<TableCell>
{name}
{builtin && <Chip size="small" variant="outlined" label={changed ? 'built in, changed' : 'built in'} sx={{ ml: 1 }} />}
</TableCell>
<TableCell>{values.key}</TableCell>
<TableCell>{values.days}</TableCell>
<TableCell>{values.subject}</TableCell>
<TableCell>{values.key_usage.join(', ')}</TableCell>
<TableCell>{values.extended_key_usage.join(', ') || '-'}</TableCell>
<TableCell>{values.sans.join(', ') || '-'}</TableCell>
<TableCell>{values.policies.join(', ') || '-'}</TableCell>
<TableCell>
{pki.status.authorities.filter((item) => item.templates.includes(name)).map((item) => item.name).join(', ') || '-'}
</TableCell>
<TableCell align="right" sx={{ whiteSpace: 'nowrap' }}>
<Tooltip title="Edit">
<span>
<IconButton size="small" disabled={busy} onClick={() => setTemplate({ name })}><Edit fontSize="small" /></IconButton>
</span>
</Tooltip>
{(!builtin || changed) && (
<Tooltip title={builtin ? 'Reset to the built-in options' : 'Remove'}>
<span>
<IconButton size="small" color={builtin ? 'default' : 'error'} disabled={busy} onClick={() => removeTemplate(name, builtin)}>
{builtin ? <Refresh fontSize="small" /> : <Delete fontSize="small" />}
</IconButton>
</span>
</Tooltip>
)}
</TableCell>
</TableRow>
)
})}
</TableBody>
</Table>
</Box>
</Section>
</Box>
)}
{pki && view === 'usages' && (
<Box sx={{ display: 'grid', gap: 2 }}>
<Section title="Extended key usages">
<Stack direction="row" sx={{ mb: 1, justifyContent: 'flex-end' }}>
<Button size="small" variant="outlined" startIcon={<Add />} disabled={busy} onClick={() => setUsage({})}>
Add extended key usage
</Button>
</Stack>
<Box sx={{ overflowX: 'auto' }}>
<Table size="small">
<TableHead>
<TableRow>
<TableCell>Name</TableCell>
<TableCell>OID</TableCell>
<TableCell>Given by</TableCell>
<TableCell align="right">Actions</TableCell>
</TableRow>
</TableHead>
<TableBody>
{Object.entries(pki.extended_key_usages).map(([name, usage]) => (
<TableRow key={name} hover>
<TableCell>
{name}
{usage.builtin && <Chip size="small" variant="outlined" label="built in" sx={{ ml: 1 }} />}
</TableCell>
<TableCell sx={{ fontFamily: 'monospace' }}>{usage.oid}</TableCell>
<TableCell>
{Object.entries(pki.templates).filter(([, values]) => values.extended_key_usage.includes(name)).map(([template]) => template).join(', ') || '-'}
</TableCell>
<TableCell align="right" sx={{ whiteSpace: 'nowrap' }}>
{!usage.builtin && (
<>
<Tooltip title="Edit">
<span>
<IconButton size="small" disabled={busy} onClick={() => setUsage({ name })}><Edit fontSize="small" /></IconButton>
</span>
</Tooltip>
<Tooltip title="Remove">
<span>
<IconButton size="small" color="error" disabled={busy} onClick={() => removeUsage(name)}><Delete fontSize="small" /></IconButton>
</span>
</Tooltip>
</>
)}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Box>
</Section>
</Box>
)}
{pki && view === 'issuing' && <Board board={issuingBoard} panels={issuingPanels} />}
{editing && pki && (
<PkiSettingsDialog
pki={pki}
onCancel={() => setEditing(false)}
onSave={async (settings) => {
await request('PUT', '/ca', PKI_SETTINGS_SHAPE, settings)
setEditing(false)
setNote(APPLIED)
await refresh()
}}
/>
)}
{usage && pki && (
<EkuDialog
pki={pki}
name={usage.name}
onCancel={() => setUsage(null)}
onSave={async (name, oid) => {
await saveUsage(name, oid)
setUsage(null)
}}
/>
)}
{template && pki && (
<TemplateDialog
pki={pki}
name={template.name}
onCancel={() => setTemplate(null)}
onSave={async (name, values) => {
await saveTemplate(name, values)
setTemplate(null)
}}
/>
)}
{authority && pki && (
<IssuingCaDialog
pki={pki}
name={authority.name}
onCancel={() => setAuthority(null)}
onSave={async (name, values) => {
await saveAuthority(name, values)
setAuthority(null)
}}
/>
)}
{issuing && pki && (
<CertificateDialog
pki={pki}
onCancel={() => setIssuing(false)}
onSave={async (issue) => {
if ('csr' in issue) {
const issued = await request<{ serial: string; certificate: string; chain: string }>('POST', '/ca/certificates', ISSUED_SHAPE, issue)
saveFile(`${issued.serial}.pem`, issued.certificate + issued.chain, 'application/x-pem-file')
} else {
const issued = await request<{ serial: string; pfx: string }>('POST', '/ca/certificates', PFX_SHAPE, issue)
saveFile(`${issue.subject}.pfx`, Uint8Array.from(atob(issued.pfx), (character) => character.charCodeAt(0)), 'application/x-pkcs12')
}
setIssuing(false)
await refresh()
}}
/>
)}
{importing && (
<ImportDialog
title={importing === 'root' ? 'Import the root certificate' : `Import the certificate of ${importing}`}
message={importing === 'root'
? 'The self-signed certificate of the offline root CA; the certificates of the issuing CAs are imported after it.'
: 'The certificate of the issuing CA, signed by the root CA for the key of its CSR.'}
label="Certificate"
begin="-----BEGIN CERTIFICATE-----"
onCancel={() => setImporting(null)}
onSave={async (certificate) => {
await request('PUT', importing === 'root' ? '/ca/root/certificate' : `/ca/issuing/${importing}/certificate`, CA_IMPORTED_SHAPE, { certificate })
setImporting(null)
setNote(APPLIED)
await refresh()
}}
/>
)}
{uploading && (
<ImportDialog
title="Upload the root CRL"
message="A CRL of the root CA signed offline, not older than the current one."
label="CRL"
begin="-----BEGIN X509 CRL-----"
onCancel={() => setUploading(false)}
onSave={async (crl) => {
await request('PUT', '/ca/root/crl', CRL_IMPORTED_SHAPE, { crl })
setUploading(false)
await refresh()
}}
/>
)}
{entering && root && (
<SetupCodeDialog
url={root.simple_ca_url ?? ''}
onCancel={() => setEntering(false)}
onSave={async (code) => {
await request('PUT', '/ca/root/setup-code', TOKEN_SHAPE, { code })
setEntering(false)
setNote(APPLIED)
await refresh()
}}
/>
)}
{confirm && <ConfirmDialog {...confirm} />}
</Box>
)
}