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
90 changes: 90 additions & 0 deletions omarchyd/posture.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
// This server's own posture: whether it needs a restart, how many system services have failed,
// and which ports it listens on beyond itself. A joined computer's connector reports the same
// readings (connector/agent.py host_posture), so this server's machine page can show what theirs do.
// Reads only: two /proc files, two paths and one `systemctl list-units`. Nothing here needs root.
import {execFile} from 'node:child_process'
import {access, readdir, readFile} from 'node:fs/promises'
import os from 'node:os'

const FAILED_TTL_MS = 60_000
const SERVICE_NAME = /^[A-Za-z0-9@._:-]{1,120}\.service$/
const MAX_PORTS = 50

const execRun = (cmd, args, {timeout = 2000} = {}) =>
new Promise((resolve) => execFile(cmd, args, {timeout, maxBuffer: 1024 * 1024}, (error, stdout) => resolve({code: error ? 1 : 0, stdout: String(stdout ?? '')})))

/**
* TCP ports listening on something other than this machine alone, from /proc/net/tcp and tcp6.
* `addr` is '0.0.0.0' or '::' for every address, and 'lan' for one address of this machine.
*/
export function listeningPorts(tcp = '', tcp6 = '') {
const seen = new Set()
const out = []
for (const [raw, proto] of [[tcp, 'tcp'], [tcp6, 'tcp6']]) {
for (const line of String(raw ?? '').split('\n').slice(1)) {
const parts = line.trim().split(/\s+/)
// 0A is TCP_LISTEN.
if (parts.length < 4 || parts[3] !== '0A') continue
const at = parts[1].lastIndexOf(':')
if (at < 0) continue
const ip = parts[1].slice(0, at).toUpperCase()
const port = parseInt(parts[1].slice(at + 1), 16)
if (!Number.isInteger(port) || port <= 0 || port > 65535) continue
let addr
if (proto === 'tcp') {
// The address is little-endian hex, so 127.x.x.x ends in 7F.
if (ip.endsWith('7F')) continue
addr = ip === '00000000' ? '0.0.0.0' : 'lan'
} else {
// ::1, and 127.0.0.1 written as an IPv6 address.
if (ip === '00000000000000000000000001000000' || ip === '0000000000000000FFFF00000100007F') continue
addr = ip === '0'.repeat(32) ? '::' : 'lan'
}
const key = `${port}/${proto}/${addr}`
if (seen.has(key)) continue
seen.add(key)
out.push({port, proto, addr})
}
}
return out.sort((a, b) => a.port - b.port || a.proto.localeCompare(b.proto)).slice(0, MAX_PORTS)
}

/** Failed system services in `systemctl list-units --plain --no-legend` output. */
export function failedUnits(stdout = '') {
return String(stdout)
.split('\n')
.map((line) => line.trim().split(/\s+/))
.filter((parts) => parts.length >= 4 && SERVICE_NAME.test(parts[0])).length
}

const fileExists = (path) => access(path).then(() => true, () => false)
const fileText = (path) => readFile(path, 'utf8').catch(() => '')

export function createPosture({read = fileText, exists = fileExists, listDir = readdir, kernel = os.release(), run = execRun, now = Date.now} = {}) {
let failed = {at: -Infinity, count: 0}

// A restart is needed when the system says so (Debian, Ubuntu), or when the running kernel's
// modules are gone because a newer kernel replaced them (Arch, Omarchy).
async function restart() {
if (await exists('/var/run/reboot-required')) return {rebootRequired: true, rebootReason: 'System updates require a restart'}
if (kernel && (await exists('/usr/lib/modules'))) {
const mods = await Promise.resolve(listDir('/usr/lib/modules')).catch(() => [])
if (mods.length && !mods.includes(kernel)) return {rebootRequired: true, rebootReason: `Kernel updated (running ${kernel})`}
}
return {rebootRequired: false, rebootReason: ''}
}
async function failedCount() {
if (now() - failed.at < FAILED_TTL_MS) return failed.count
const r = await run('systemctl', ['--system', 'list-units', '--type=service', '--state=failed', '--no-pager', '--no-legend', '--plain'])
// A machine without systemd, or a systemctl that didn't answer, keeps the last count.
failed = {at: now(), count: r.code === 0 ? failedUnits(r.stdout) : failed.count}
return failed.count
}
return {
async get() {
const [state, count, tcp, tcp6] = await Promise.all([restart(), failedCount(), read('/proc/net/tcp'), read('/proc/net/tcp6')])
// This server's waiting updates are not split into security and other, so that reading is absent.
return {...state, securityUpdates: null, listeningPorts: listeningPorts(tcp, tcp6), failedUnits: count}
},
}
}
4 changes: 4 additions & 0 deletions omarchyd/server.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ import {createHermes} from './hermes.mjs'
import * as system from './system.mjs'
import {createSampler} from './stats.mjs'
import {createOsInfo} from './os-info.mjs'
import {createPosture} from './posture.mjs'
import {WebSocketServer} from 'ws'
import {viewerBackpressure} from './backpressure.mjs'
import {nixCacheConfText, readNixCache, writeNixCache} from './nix-cache.mjs'
Expand Down Expand Up @@ -305,6 +306,7 @@ export async function startOmarchyd({port = 2021, host = '127.0.0.1', dataDir, t
}
const release = await system.osRelease()
const osInfo = createOsInfo({release})
const posture = createPosture()

// Live gauges: hardware is sampled on its own interval while a screen is reading.
// The timer starts on the first read and stops about 15s after the last one,
Expand Down Expand Up @@ -450,6 +452,8 @@ export async function startOmarchyd({port = 2021, host = '127.0.0.1', dataDir, t
'system.getIpAddresses': {kind: 'query', run: () => system.ipAddresses()},
'system.device': {kind: 'query', run: async () => ({device: await system.deviceName(), os: release.pretty})},
'system.osInfo': {kind: 'query', run: () => osInfo.get()},
// This server's restart, failed-service and listening-port readings. Owner only, like a joined computer's.
'system.posture': {kind: 'query', run: (_input, {auth}) => (ownerOnly(auth, 'see this server’s security readings'), posture.get())},

// ---- Settings: power, logs, device name, two-factor, sessions, reset ----------------------
'system.restart': {kind: 'mutation', run: async (input, {auth}) => (ownerOnly(auth, 'restart the server'), await bootGuard(input, 'restart'), power('reboot'))},
Expand Down
1 change: 1 addition & 0 deletions server/app.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ export const ALLOWED = {
'system.cpuTemperature': 'query',
'system.stats': 'query',
'system.history': 'query',
'system.posture': 'query',
'system.bootStart': 'query',
'system.enableBootStart': 'mutation',
'system.cpuUsage': 'query',
Expand Down
8 changes: 8 additions & 0 deletions test/fake-omarchyd.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,14 @@ export async function startFakeserverd({
}),
},
'system.batteryUsage': {kind: 'query', run: () => ({batteries: []})},
// Owner only, like the real one. A restart is waiting and one service has failed.
'system.posture': {
kind: 'query',
run: (_input, auth) =>
accountOf(auth.userId).role !== 'owner'
? {error: ['FORBIDDEN', 'Only the server’s owner can see this server’s security readings']}
: {rebootRequired: true, rebootReason: 'Kernel updated (running 6.12.1-arch1-1)', securityUpdates: null, listeningPorts: [{port: 22, proto: 'tcp', addr: '0.0.0.0'}, {port: 7780, proto: 'tcp', addr: '0.0.0.0'}], failedUnits: 1},
},
'system.stats': {
kind: 'query',
run: () => ({
Expand Down
11 changes: 11 additions & 0 deletions test/omarchyd.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,17 @@ describe('network shares are owner-only', () => {
}
assert.equal((await call('query', 'storage.pools', undefined, member)).status, 200, 'members can still see pools')
})
test('this server’s posture readings are the owner’s: a member is refused', async () => {
const r = await call('query', 'system.posture', undefined, member)
assert.equal(r.status, 403)
assert.match(r.body.error.message, /owner/i)
const mine = await call('query', 'system.posture', undefined, owner)
assert.equal(mine.status, 200)
const p = mine.body.result.data
assert.equal(typeof p.rebootRequired, 'boolean')
assert.equal(typeof p.failedUnits, 'number')
assert.ok(Array.isArray(p.listeningPorts))
})
test('a member cannot read or change a NixOS configuration', async () => {
const rpcs = [
['query', 'machines.nixosConfig', {id: 'abcd1234'}],
Expand Down
77 changes: 77 additions & 0 deletions test/posture.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// This server's own posture readings: restart needed, failed services and listening ports.
import assert from 'node:assert/strict'
import {test} from 'node:test'

import {createPosture, failedUnits, listeningPorts} from '../omarchyd/posture.mjs'

const HEAD = ' sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n'
const row = (local, state = '0A') => ` 0: ${local} 00000000:0000 ${state} 00000000:00000000 00:00000000 00000000 0 0 1 1 0 100 0 0 10 0\n`
const HEAD6 = ' sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n'

test('listening ports: every address, one address, and nothing that listens on this machine alone', () => {
const tcp = HEAD + row('00000000:1E64') + row('0100007F:07E5') + row('3644A8C0:0016') + row('00000000:01BB', '01') + row('00000000:1E64')
const tcp6 = HEAD6 + row('00000000000000000000000000000000:1E64') + row('00000000000000000000000001000000:0277') + row('0000000000000000FFFF00000100007F:1F90') + row('000080FE00000000FF005450B6AD1DFE:0050')
assert.deepEqual(listeningPorts(tcp, tcp6), [
{port: 22, proto: 'tcp', addr: 'lan'},
{port: 80, proto: 'tcp6', addr: 'lan'},
{port: 7780, proto: 'tcp', addr: '0.0.0.0'},
{port: 7780, proto: 'tcp6', addr: '::'},
])
})

test('listening ports: damaged or missing files give an empty list, and the list stops at 50', () => {
assert.deepEqual(listeningPorts('', ''), [])
assert.deepEqual(listeningPorts(undefined, null), [])
assert.deepEqual(listeningPorts(HEAD + 'rubbish\n' + row('nocolon') + row('00000000:ZZZZ') + row('00000000:0000') + row('00000000:FFFFF'), ''), [])
const many = HEAD + Array.from({length: 80}, (_, i) => row(`00000000:${(1000 + i).toString(16).toUpperCase().padStart(4, '0')}`)).join('')
assert.equal(listeningPorts(many, '').length, 50)
})

test('failed services are counted from systemctl’s list, and odd lines are ignored', () => {
assert.equal(failedUnits(''), 0)
assert.equal(failedUnits('smb.service loaded failed failed Samba SMB Daemon\nfoo@1.service loaded failed failed Foo\n'), 2)
assert.equal(failedUnits('\n \nnot a unit line\nbad name! loaded failed failed x\n'), 0)
})

const machine = ({files = {}, dirs = {}, kernel = '6.12.1-arch1-1', units = '', code = 0, calls = []} = {}) =>
createPosture({
read: async (path) => files[path] ?? '',
exists: async (path) => path in files || path in dirs,
listDir: async (path) => dirs[path] ?? [],
kernel,
run: async (cmd, args) => (calls.push([cmd, ...args].join(' ')), {code, stdout: units}),
now: () => machine.now,
})
machine.now = 0

test('a healthy server: no restart, no failed services, its ports listed', async () => {
const p = await machine({dirs: {'/usr/lib/modules': ['6.12.1-arch1-1']}, files: {'/proc/net/tcp': HEAD + row('00000000:1E64')}}).get()
assert.deepEqual(p, {rebootRequired: false, rebootReason: '', securityUpdates: null, listeningPorts: [{port: 7780, proto: 'tcp', addr: '0.0.0.0'}], failedUnits: 0})
})

test('a restart is needed after a kernel update, or when the system says so', async () => {
const arch = await machine({dirs: {'/usr/lib/modules': ['6.12.2-arch1-1']}}).get()
assert.equal(arch.rebootRequired, true)
assert.equal(arch.rebootReason, 'Kernel updated (running 6.12.1-arch1-1)')
const debian = await machine({files: {'/var/run/reboot-required': ''}, dirs: {'/usr/lib/modules': ['6.12.1-arch1-1']}}).get()
assert.deepEqual([debian.rebootRequired, debian.rebootReason], [true, 'System updates require a restart'])
// No modules folder (a container), or one that can't be read: no restart is claimed.
assert.equal((await machine().get()).rebootRequired, false)
assert.equal((await machine({dirs: {'/usr/lib/modules': []}}).get()).rebootRequired, false)
})

test('failed services: systemctl is asked once a minute, and a failed ask keeps the last count', async () => {
const calls = []
machine.now = 0
const p = machine({units: 'smb.service loaded failed failed Samba\n', calls})
assert.equal((await p.get()).failedUnits, 1)
machine.now = 30_000
assert.equal((await p.get()).failedUnits, 1)
assert.equal(calls.length, 1, 'not asked again within a minute')
assert.equal(calls[0], 'systemctl --system list-units --type=service --state=failed --no-pager --no-legend --plain')
machine.now = 61_000
await p.get()
assert.equal(calls.length, 2)
machine.now = 0
assert.equal((await machine({code: 1, units: 'x.service loaded failed failed X\n'}).get()).failedUnits, 0, 'no systemd: zero, not a guess')
})
7 changes: 7 additions & 0 deletions web/src/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import {
type UserApp,
} from './api'
import {OFFLINE_ACTION_MESSAGE, isBrowserOnline} from './connection'
import type {PostureSummary} from './fleet/statView'
import {isOwner} from './isOwner'
import {applyOptimisticAppState, rollbackOptimisticAppState} from './optimisticApps'
import {isAppBusy, useToast} from './ui'

Expand Down Expand Up @@ -47,6 +49,11 @@ export const useGpus = () => useQuery({...statsQuery, select: (s) => s.gpu})
export const useBattery = () => useQuery({...statsQuery, select: (s) => s.battery})
export const useUptime = () => useQuery({...statsQuery, select: (s) => s.uptime})
export const useSystemNet = () => useQuery({...statsQuery, select: (s) => s.net ?? null})
/** This server's restart, failed-service and listening-port readings. The owner's only, so a member's browser never asks. */
export const useServerPosture = () => {
const owner = isOwner(useUser().data)
return useQuery({queryKey: ['system.posture'], queryFn: () => query<PostureSummary>('system.posture'), enabled: owner, refetchInterval: 60_000, staleTime: 30_000})
}
export const useNotifications = () =>
useQuery({queryKey: ['notifications.get'], queryFn: () => query<string[]>('notifications.get'), refetchInterval: 30_000})
export const useMachines = () =>
Expand Down
4 changes: 3 additions & 1 deletion web/src/fleet/MachineManager.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import {
} from './machineManagerLogic'
import {LiveStats} from './StatRegion'
import {useServerGaugeMetrics} from './serverGauges'
import {useServerPosture} from '../data'
const TerminalTabs = lazy(() => import('../TerminalTabs').then((m) => ({default: m.TerminalTabs})))

type Alert = {agentId: string; severity: 'info' | 'warning' | 'critical'}
Expand Down Expand Up @@ -320,12 +321,13 @@ function ServerRow({
onDesktop: () => void
}) {
const {metrics, temp, sensors, uptime} = useServerGaugeMetrics()
const posture = useServerPosture()
if (lines) return <LineButton name={member.name} icon="server" iconBg="linear-gradient(140deg,#2b2b2b,#0b0b0b)" reach={reachLabel('server', member.online)} selected={selected} onSelect={onManage} />
const seen = seenFact(member.online, uptime, null, Date.now())
return (
<RowFrame open={open} name={member.name} icon="server" iconBg="linear-gradient(140deg,#2b2b2b,#0b0b0b)" reach={reachLabel('server', member.online)} health={healthPill(health)} onToggle={onToggle}>
<div className="mm-panel">
<LiveStats metrics={metrics} temp={temp} sensors={sensors} machineName={member.name} empty={noReadings} />
<LiveStats metrics={metrics} temp={temp} sensors={sensors} posture={posture.data ?? null} machineName={member.name} empty={noReadings} />
<ActionRow
kind="server"
access={managerAccess({kind: 'server', linkOnline: member.online, owner, serverTerminal, terminalGranted: false, desktopGranted: false, desktopOk: false, guestRunning: false})}
Expand Down
5 changes: 3 additions & 2 deletions web/src/fleet/ServerSheet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {useState} from 'react'
import {useQuery} from '@tanstack/react-query'

import {query, type Machine, type UserApp} from '../api'
import {useAction, useSystemNet} from '../data'
import {useAction, useServerPosture, useSystemNet} from '../data'
import {Icon} from '../icons'
import {PinButton} from './PinButton'
import {useServerGaugeMetrics, useSystemHistory} from './serverGauges'
Expand Down Expand Up @@ -62,6 +62,7 @@ export function ServerSheet({
}) {
const node = useNode()
const gauges = useServerGaugeMetrics()
const posture = useServerPosture()
const net = useSystemNet()
const ips = useQuery({queryKey: ['system.getIpAddresses'], queryFn: () => query<string[]>('system.getIpAddresses')})
const [historyRange, setHistoryRange] = useState<'1h' | '24h'>('1h')
Expand Down Expand Up @@ -204,7 +205,7 @@ export function ServerSheet({
terminal={{enabled: !!onTerminal, onOpen: () => onTerminal?.()}}
desktop={owner ? {enabled: true, onOpen: onDesktop} : undefined}
pin={<PinButton pin={{kind: 'machine', id: SERVER_FLEET_ID, computer: ''}} name={name} />}
stats={<LiveBand metrics={gauges.metrics} temp={gauges.temp} sensors={gauges.sensors} machineName={name} online={online} />}
stats={<LiveBand metrics={gauges.metrics} temp={gauges.temp} sensors={gauges.sensors} posture={posture.data ?? null} machineName={name} online={online} />}
facts={<LiveFacts online={online} uptime={gauges.uptime} rx={net.data?.rx} tx={net.data?.tx} address={<AddressList addresses={ips.data ?? []} />} />}
onBack={onBack}
>
Expand Down
6 changes: 4 additions & 2 deletions web/src/fleet/serverGauges.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type {ReactNode} from 'react'
import {useQuery} from '@tanstack/react-query'

import {query, type ThermalSensor} from '../api'
import {useBattery, useCpu, useDisk, useGpus, useMemory, useTemp, useUptime} from '../data'
import {useBattery, useCpu, useDisk, useGpus, useMemory, useServerPosture, useTemp, useUptime} from '../data'
import {BatteryRing} from './BatteryRing'
import type {FleetRings, GaugeKind} from './aggregate'
import {Icon, type IconName} from '../icons'
Expand Down Expand Up @@ -165,7 +165,9 @@ export function GaugeCluster({
)
}

/** This server's readings on its machine page, with its posture readings (restart, failed services, ports) like a joined computer's. */
export function ServerRings({name}: {name?: string} = {}) {
const {metrics, temp, sensors} = useServerGaugeMetrics()
return <LiveStats metrics={metrics} temp={temp} sensors={sensors} machineName={name} />
const posture = useServerPosture()
return <LiveStats metrics={metrics} temp={temp} sensors={sensors} posture={posture.data ?? null} machineName={name} />
}
Loading