8 Commits

Author SHA1 Message Date
urania 9587d11e21 fix: localectl
build-and-release / release (push) Successful in 2m38s
2026-06-22 22:22:36 +02:00
urania ac196e720b fix: add locale
build-and-release / release (push) Successful in 2m38s
2026-06-22 21:58:01 +02:00
urania a106b7413f fix: workflow
build-and-release / release (push) Successful in 2m37s
2026-06-22 20:12:54 +02:00
urania 0e041fac5e fix: .minisign for signed releases
build-and-release / release (push) Failing after 2m1s
2026-06-22 20:03:27 +02:00
urania eba478471f fix: --v
build-and-release / release (push) Successful in 2m3s
2026-06-22 19:29:04 +02:00
urania dbce9aa56e fix: minor changes on update
build-and-release / release (push) Successful in 2m5s
2026-06-22 19:15:06 +02:00
urania 60b9fbc42c fix: cpu info
build-and-release / release (push) Successful in 2m4s
2026-06-22 18:54:50 +02:00
urania fff43a5ab6 fix: auto-updates
build-and-release / release (push) Successful in 2m6s
2026-06-22 18:24:59 +02:00
22 changed files with 770 additions and 33 deletions
+15
View File
@@ -0,0 +1,15 @@
{
"permissions": {
"allow": [
"Bash(go get *)",
"Bash(go build *)",
"Bash(go vet *)",
"Read(//usr/lib/**)",
"Read(//proc/**)",
"Bash(systemctl show *)",
"Bash(echo \"exit=$?\")",
"Bash(systemctl list-units *)",
"Bash(go test *)"
]
}
}
+24 -2
View File
@@ -10,13 +10,22 @@ jobs:
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0 # svu needs full history + tags
fetch-depth: 0
- uses: actions/setup-go@v5
with:
go-version: '1.26'
go-version: "1.26"
cache: false
- name: Install PAM headers (needed by go test)
run: sudo apt-get update && sudo apt-get install -y libpam0g-dev
- name: Run tests
run: |
set -ex
go vet ./...
go test ./...
- name: Install svu
timeout-minutes: 3
run: |
@@ -87,6 +96,19 @@ jobs:
go build -ldflags="$LDFLAGS" -o dist/nadir-$VERSION-linux-arm64 ./cmd/server
upx --best --lzma dist/nadir-$VERSION-linux-amd64 dist/nadir-$VERSION-linux-arm64
- name: Sign checksums
if: steps.ver.outputs.release == 'true'
env:
MINISIGN_SECRET_KEY: ${{ secrets.MINISIGN_SECRET_KEY }}
MINISIGN_PASSWORD: ${{ secrets.MINISIGN_PASSWORD }}
run: |
set -ex
cd dist
sha256sum nadir-* > sha256sums.txt
cat sha256sums.txt
go run ../tools/sign-checksums sha256sums.txt
ls -la sha256sums.txt sha256sums.txt.minisig
- name: Tag and release
if: steps.ver.outputs.release == 'true'
env:
+2
View File
@@ -12,3 +12,5 @@ config.yml
*.swp
CLAUDE.md
minisign.key
+11
View File
@@ -28,3 +28,14 @@ var InstallScriptTemplate string
// go build -ldflags "-X nadir.Version=v1.2.3"
// Local dev builds leave it as "dev".
var Version = "dev"
// ReleasePublicKey is the minisign public key whose signature on a release's
// sha256sums.txt is required by the auto-updater. Replacing the binary is the
// most dangerous thing nadir does, so it gets the strongest verification: the
// updater downloads sha256sums.txt + .minisig from the configured Gitea repo,
// verifies the signature against this embedded key, then verifies the binary's
// sha256 against the file. Rotation requires a rebuild — intentional, so a
// compromised Gitea instance cannot also rotate the trust anchor.
//
//go:embed minisign.pub
var ReleasePublicKey string
+43 -2
View File
@@ -50,6 +50,8 @@ func main() {
configFlag := fs.String("f", "", "config file path")
fs.StringVar(configFlag, "config", "", "alias for -f")
saveConfig := fs.Bool("save-config", false, "write default config and exit")
showVersion := fs.Bool("v", false, "print version and exit")
fs.BoolVar(showVersion, "version", false, "alias for -v")
rest := os.Args[1:]
var args []string
@@ -63,6 +65,11 @@ func main() {
rest = rest[1:]
}
if *showVersion {
fmt.Println(nadir.Version)
os.Exit(0)
}
if *configFlag != "" {
os.Setenv("CONFIG_PATH", *configFlag)
}
@@ -232,6 +239,7 @@ func runServer() {
meta.Register(api, mods)
meta.RegisterHealth(api, sessions)
meta.RegisterWhoami(api, sessions, roles, mods)
meta.RegisterUpdate(api, configPath)
auth.RegisterLogin(api, sessions, auditStore, cfg.SecureCookie())
auth.RegisterLogout(api, sessions, cfg.SecureCookie())
@@ -263,12 +271,24 @@ func runServer() {
})
mux.HandleFunc("GET /docs", func(w http.ResponseWriter, _ *http.Request) {
// /docs needs to execute the Scalar bundle, so loosen the strict CSP set
// by secHeaders for this one page: allow scripts/styles from the jsdelivr
// CDN plus inline (Scalar uses inline <script> + inline styles). The CDN
// host is the supply-chain trust boundary; pinning a version + SRI here
// is the follow-up (M5 partial).
w.Header().Set("Content-Security-Policy",
"default-src 'self'; "+
"script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "+
"style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "+
"img-src 'self' data: https:; "+
"connect-src 'self'; "+
"font-src 'self' data: https://cdn.jsdelivr.net")
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(`<!doctype html><html><head><title>API</title>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="icon" type="image/svg+xml" href="/favicon.svg"></head>
<body><script id="api-reference" data-url="/openapi.json" data-configuration='{"layout":"classic"}'></script>
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script></body></html>`))
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference" crossorigin="anonymous"></script></body></html>`))
})
addr := cfg.Server.Hostname + ":" + cfg.Server.Port
@@ -277,7 +297,7 @@ func runServer() {
Addr: addr,
// WithClientIP records the source IP for the login throttle (H1); behind a
// trusted proxy it reads X-Forwarded-For instead of the proxy's address.
Handler: auth.WithClientIP(cfg.Server.TrustProxy, mux),
Handler: secHeaders(auth.WithClientIP(cfg.Server.TrustProxy, mux)),
ReadHeaderTimeout: 10 * time.Second,
ReadTimeout: 30 * time.Second,
WriteTimeout: 0, // unset: SSE endpoints stream indefinitely
@@ -334,6 +354,27 @@ func runServer() {
}
}
// secHeaders sets defensive response headers on every HTTP response. The
// default Content-Security-Policy denies everything (`default-src 'none'`) —
// correct for the JSON API and the tiny landing/favicon endpoints. /docs
// overrides it with a CDN-permissive policy because the Scalar bundle needs
// to execute.
//
// HSTS is set unconditionally: nadir always serves TLS directly or sits behind
// a TLS-terminating proxy (config rejects any other shape), so a browser
// receiving this header is on an HTTPS connection.
func secHeaders(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
h := w.Header()
h.Set("X-Content-Type-Options", "nosniff")
h.Set("X-Frame-Options", "DENY")
h.Set("Referrer-Policy", "no-referrer")
h.Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
h.Set("Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'")
next.ServeHTTP(w, r)
})
}
func ensureRoot() {
if os.Getuid() != 0 {
fatalIf(fmt.Errorf("nadir must run as root"))
+2 -1
View File
@@ -425,7 +425,8 @@ Usage:
nadir token add <name> Mint a machine credential (Bearer token), shown once
nadir token rm <name> Revoke a token (effective immediately, no restart)
nadir token ls List token names and when they were created
nadir update Fetch the latest release from server.release_repo and restart
nadir update [--check|--force] Fetch the latest release from server.release_repo and restart
(--check: report only; --force: re-download when already current)
nadir help Show this help
Most commands need root. Config path is specified via -f/--config or CONFIG_PATH (default ~/.config/config.yaml).
+3 -2
View File
@@ -1,8 +1,9 @@
package main
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
@@ -24,7 +25,7 @@ func serverCert(certPath, keyPath string) (tls.Certificate, error) {
}
func generateSelfSignedCert() (tls.Certificate, error) {
priv, err := rsa.GenerateKey(rand.Reader, 2048)
priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return tls.Certificate{}, err
}
+159 -4
View File
@@ -1,7 +1,10 @@
package main
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"flag"
"fmt"
"io"
"net/http"
@@ -12,14 +15,23 @@ import (
"strings"
"time"
"nadir"
"nadir/internal/config"
"github.com/jedisct1/go-minisign"
)
// updateCmd implements `nadir update`: hit the configured Gitea repo's
// releases/latest, pick the asset for the host's GOARCH, atomically replace
// releases/latest, pick the asset for the host's GOARCH, verify the release
// signature (minisign) and checksum (SHA-256), atomically replace
// /usr/local/bin/nadir (or wherever the running binary lives), and restart
// the systemd unit so the new code takes effect.
func updateCmd(_ []string) error {
func updateCmd(args []string) error {
fs := flag.NewFlagSet("update", flag.ExitOnError)
check := fs.Bool("check", false, "report the latest version without downloading")
force := fs.Bool("force", false, "re-download even when already at the latest version")
fs.Parse(args)
configPath, err := resolveConfigPath()
if err != nil {
return err
@@ -44,16 +56,40 @@ func updateCmd(_ []string) error {
return err
}
fmt.Printf("current: %s\nlatest: %s\n", nadir.Version, rel.TagName)
upToDate := nadir.Version == rel.TagName
switch {
case *check:
if upToDate {
fmt.Println("already up to date.")
} else {
fmt.Println("update available; run `nadir update` to install.")
}
return nil
case upToDate && !*force:
fmt.Println("already up to date; pass --force to re-download.")
return nil
}
// Locate the binary asset and the two verification assets in the release.
var assetURL, assetName string
var sumsURL, sigURL string
for _, a := range rel.Assets {
if strings.HasSuffix(a.Name, suffix) {
switch {
case strings.HasSuffix(a.Name, suffix):
assetURL, assetName = a.URL, a.Name
break
case a.Name == "sha256sums.txt":
sumsURL = a.URL
case a.Name == "sha256sums.txt.minisig":
sigURL = a.URL
}
}
if assetURL == "" {
return fmt.Errorf("no %s asset in release %s", suffix, rel.TagName)
}
if sumsURL == "" || sigURL == "" {
return fmt.Errorf("release %s is missing sha256sums.txt or sha256sums.txt.minisig — cannot verify; refusing to install an unverified binary", rel.TagName)
}
exe, err := os.Executable()
if err != nil {
@@ -66,6 +102,15 @@ func updateCmd(_ []string) error {
os.Remove(tmp)
return err
}
// Verify: download checksums + signature, check minisign, check SHA-256.
fmt.Println("verifying release signature ...")
if err := verifyRelease(tmp, assetName, sumsURL, sigURL); err != nil {
os.Remove(tmp)
return fmt.Errorf("verification failed: %w", err)
}
fmt.Println("signature and checksum OK.")
// Atomic on the same filesystem; replaces the on-disk file without
// disturbing the still-running process (its inode stays alive).
if err := os.Rename(tmp, exe); err != nil {
@@ -81,6 +126,113 @@ func updateCmd(_ []string) error {
return nil
}
// verifyRelease downloads sha256sums.txt + its minisig from the release,
// verifies the signature against the embedded public key, then checks the
// downloaded binary's SHA-256 against the matching line in the checksums file.
func verifyRelease(binaryPath, assetName, sumsURL, sigURL string) error {
// Parse the embedded public key. The placeholder file will fail here
// (no valid base64 line), which is the desired behavior: updates are
// disabled until a real key is committed.
pubKey, err := minisign.DecodePublicKey(nadir.ReleasePublicKey)
if err != nil {
return fmt.Errorf("embedded minisign public key is invalid (is minisign.pub still the placeholder?): %w", err)
}
// Download the checksums file and its signature.
sumsBody, err := downloadBytes(sumsURL)
if err != nil {
return fmt.Errorf("download sha256sums.txt: %w", err)
}
sigBody, err := downloadBytes(sigURL)
if err != nil {
return fmt.Errorf("download sha256sums.txt.minisig: %w", err)
}
// Verify the minisign signature on the checksums file.
sig, err := minisign.DecodeSignature(string(sigBody))
if err != nil {
return fmt.Errorf("decode minisig: %w", err)
}
ok, err := pubKey.Verify(sumsBody, sig)
if err != nil {
return fmt.Errorf("minisign verify: %w", err)
}
if !ok {
return fmt.Errorf("minisign signature is not valid for this sha256sums.txt")
}
// Find the expected hash for our binary in the signed checksums file.
expectedHash, err := findChecksum(string(sumsBody), assetName)
if err != nil {
return err
}
// Hash the downloaded binary and compare.
actualHash, err := sha256File(binaryPath)
if err != nil {
return fmt.Errorf("hash downloaded binary: %w", err)
}
if actualHash != expectedHash {
return fmt.Errorf("SHA-256 mismatch for %s: expected %s, got %s", assetName, expectedHash, actualHash)
}
return nil
}
// findChecksum parses a sha256sums.txt body (one "hash filename\n" per line)
// and returns the hex hash for the named asset.
func findChecksum(sums, assetName string) (string, error) {
for _, line := range strings.Split(sums, "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
// Standard sha256sum output: "<hex> <filename>" (two spaces).
parts := strings.SplitN(line, " ", 2)
if len(parts) != 2 {
// Also accept single-space separation.
parts = strings.SplitN(line, " ", 2)
}
if len(parts) == 2 && strings.TrimSpace(parts[1]) == assetName {
h := strings.TrimSpace(parts[0])
if len(h) != 64 {
return "", fmt.Errorf("sha256sums.txt: invalid hash length for %s: %q", assetName, h)
}
return strings.ToLower(h), nil
}
}
return "", fmt.Errorf("sha256sums.txt does not contain a hash for %s", assetName)
}
// sha256File returns the lowercase hex SHA-256 of the file at path.
func sha256File(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", err
}
defer f.Close()
h := sha256.New()
if _, err := io.Copy(h, f); err != nil {
return "", err
}
return hex.EncodeToString(h.Sum(nil)), nil
}
// downloadBytes fetches a URL and returns its body as a byte slice (for small
// files like sha256sums.txt and .minisig).
func downloadBytes(srcURL string) ([]byte, error) {
c := &http.Client{Timeout: 30 * time.Second}
resp, err := c.Get(srcURL)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("GET %s: %s", srcURL, resp.Status)
}
// Cap read to 1 MB — sha256sums.txt and .minisig are tiny.
return io.ReadAll(io.LimitReader(resp.Body, 1<<20))
}
type giteaRelease struct {
TagName string `json:"tag_name"`
Assets []struct {
@@ -114,6 +266,9 @@ func releaseAPIURL(repoURL string) (string, error) {
if err != nil {
return "", fmt.Errorf("release_repo: %w", err)
}
if u.Scheme != "https" {
return "", fmt.Errorf("release_repo must use https:// (got %q) — auto-update downloads and executes the binary, plaintext would let any on-path attacker replace it", repoURL)
}
parts := strings.Split(strings.Trim(u.Path, "/"), "/")
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
return "", fmt.Errorf("release_repo must look like https://host/owner/repo, got %q", repoURL)
+6 -3
View File
@@ -7,19 +7,22 @@ require github.com/msteinert/pam v1.2.0
require github.com/danielgtaylor/huma/v2 v2.38.0
require (
gopkg.in/yaml.v3 v3.0.1
modernc.org/sqlite v1.52.0
github.com/coder/websocket v1.8.15
github.com/creack/pty v1.1.24
gopkg.in/yaml.v3 v3.0.1
modernc.org/sqlite v1.52.0
)
require (
aead.dev/minisign v0.3.0
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/jedisct1/go-minisign v0.0.0-20260527172527-a09352b57a22
github.com/mattn/go-isatty v0.0.21 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
golang.org/x/sys v0.43.0 // indirect
golang.org/x/crypto v0.52.0 // indirect
golang.org/x/sys v0.45.0 // indirect
modernc.org/libc v1.72.3 // indirect
modernc.org/mathutil v1.7.1 // indirect
modernc.org/memory v1.11.0 // indirect
+10 -4
View File
@@ -1,3 +1,5 @@
aead.dev/minisign v0.3.0 h1:8Xafzy5PEVZqYDNP60yJHARlW1eOQtsKNp/Ph2c0vRA=
aead.dev/minisign v0.3.0/go.mod h1:NLvG3Uoq3skkRMDuc3YHpWUTMTrSExqm+Ij73W13F6Y=
github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNUA=
github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg=
github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
@@ -16,6 +18,8 @@ github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
github.com/jedisct1/go-minisign v0.0.0-20260527172527-a09352b57a22 h1:C68TAi+k12EKJCAmsdaERzQ22ZxVE6n+CuB3kOkhQ7c=
github.com/jedisct1/go-minisign v0.0.0-20260527172527-a09352b57a22/go.mod h1:vYVVh81Lqe/TP0sPLjiNYcX9Hxy/YSfkUx96lYJeyKo=
github.com/mattn/go-isatty v0.0.21 h1:xYae+lCNBP7QuW4PUnNG61ffM4hVIfm+zUzDuSzYLGs=
github.com/mattn/go-isatty v0.0.21/go.mod h1:ZXfXG4SQHsB/w3ZeOYbR0PrPwLy+n6xiMrJlRFqopa4=
github.com/msteinert/pam v1.2.0 h1:mYfjlvN2KYs2Pb9G6nb/1f/nPfAttT/Jee5Sq9r3bGE=
@@ -30,14 +34,16 @@ github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988=
golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc=
golang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=
golang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=
golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.43.0 h1:Rlag2XtaFTxp19wS8MXlJwTvoh8ArU6ezoyFsMyCTNI=
golang.org/x/sys v0.43.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.6.0 h1:clScbb1cHjoCkyRbWwBEUZ5H/tIFu5TAXIqaZD0Gcjw=
golang.org/x/term v0.6.0/go.mod h1:m6U89DPEgQRMq3DNkDClhWw02AUbt2daBVO4cn4Hv9U=
golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
golang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=
golang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
+34
View File
@@ -60,6 +60,40 @@ do_install() {
echo "downloading $asset_url ..."
curl -f --progress-bar -L "$asset_url" -o /usr/local/bin/nadir.tmp
asset_name=$(basename "$asset_url")
# Verify SHA-256: download the checksums file published alongside the binary
# and confirm the hash matches. This catches CDN corruption and (together with
# the HTTPS transport) makes tampered binaries detectable.
sums_url="$host/api/v1/repos/$path/releases/latest"
sums_asset_url=$(curl -fsSL "$sums_url" \
| grep -o '"browser_download_url":"[^"]*sha256sums\.txt"' \
| head -n1 \
| cut -d'"' -f4)
if [ -n "$sums_asset_url" ]; then
echo "verifying checksum ..."
curl -fsSL "$sums_asset_url" -o /tmp/nadir-sha256sums.txt
# Extract the expected hash for our asset and compare.
expected=$(grep "$asset_name" /tmp/nadir-sha256sums.txt | awk '{print $1}')
actual=$(sha256sum /usr/local/bin/nadir.tmp | awk '{print $1}')
rm -f /tmp/nadir-sha256sums.txt
if [ -z "$expected" ]; then
echo "warning: sha256sums.txt does not contain a hash for $asset_name" >&2
echo "proceeding without verification" >&2
elif [ "$expected" != "$actual" ]; then
echo "SHA-256 MISMATCH: expected $expected, got $actual" >&2
echo "the downloaded binary may be corrupted or tampered with — aborting" >&2
rm -f /usr/local/bin/nadir.tmp
exit 1
else
echo "checksum OK ($actual)"
fi
else
echo "warning: no sha256sums.txt in release — skipping verification" >&2
fi
mv /usr/local/bin/nadir.tmp /usr/local/bin/nadir
chmod +x /usr/local/bin/nadir
+11
View File
@@ -3,6 +3,7 @@ package auth
import (
"context"
"net/http"
"regexp"
"time"
"nadir/internal/auditlog"
@@ -10,6 +11,11 @@ import (
"github.com/danielgtaylor/huma/v2"
)
// loginNameRe is the useradd default NAME_REGEX. Validating at this trust
// boundary keeps a flag-like name (e.g. "-c", "--help") from reaching `su` in
// the terminal handler or showing up verbatim in audit logs / throttle keys.
var loginNameRe = regexp.MustCompile(`^[a-z_][a-z0-9_-]{0,31}\$?$`)
// authenticator verifies a username/password (PAM in production). It's a field
// of the login handler rather than a package global so tests can inject a stub
// without mutating shared state.
@@ -53,6 +59,11 @@ func registerLogin(api huma.API, sessions *SessionStore, auditor *auditlog.Store
Tags: []string{"Authentication"},
Errors: []int{401, 429},
}, func(ctx context.Context, in *LoginInput) (*LoginOutput, error) {
// Reject malformed usernames at the trust boundary so PAM, su, and the
// audit log never see flag-like or shell-metacharacter input.
if !loginNameRe.MatchString(in.Body.Username) {
return nil, huma.Error401Unauthorized("invalid credentials")
}
// Throttle brute force: too many recent failures for this account/source
// put it in a short cooldown before the password is even checked.
throttleKey := in.Body.Username + "|" + ClientIP(ctx)
+22
View File
@@ -2,6 +2,7 @@ package config
import (
"fmt"
"net/url"
"os"
"path/filepath"
"strings"
@@ -108,6 +109,27 @@ func Load(path string) (*File, error) {
if err := yaml.Unmarshal(data, &f); err != nil {
return nil, fmt.Errorf("parse config %s: %w", path, err)
}
// release_repo, when set, is downloaded over the wire and (for /api/update)
// executed. Validate shape + scheme once here so /install.sh and the updater
// can use the string directly. Trim any trailing slash so downstream string
// concatenation produces a clean URL.
if f.Server.ReleaseRepo != "" {
f.Server.ReleaseRepo = strings.TrimRight(f.Server.ReleaseRepo, "/")
u, err := url.Parse(f.Server.ReleaseRepo)
if err != nil {
return nil, fmt.Errorf("server.release_repo: %w", err)
}
if u.Scheme != "https" {
return nil, fmt.Errorf("server.release_repo must use https:// (got %q)", f.Server.ReleaseRepo)
}
if u.Host == "" {
return nil, fmt.Errorf("server.release_repo missing host: %q", f.Server.ReleaseRepo)
}
parts := strings.Split(strings.Trim(u.Path, "/"), "/")
if len(parts) != 2 || parts[0] == "" || parts[1] == "" {
return nil, fmt.Errorf("server.release_repo must be https://host/owner/repo, got %q", f.Server.ReleaseRepo)
}
}
return &f, nil
}
+62
View File
@@ -0,0 +1,62 @@
package meta
import (
"context"
"os"
"os/exec"
"syscall"
"nadir/internal/config"
"nadir/internal/oscmd"
"github.com/danielgtaylor/huma/v2"
)
// RegisterUpdate wires POST /api/update. It runs the equivalent of
// `sudo nadir update` in a detached session and returns 202 immediately; the
// systemctl restart that ends the updater drops in-flight connections, so the
// caller should poll /api/health to confirm the new version is up.
//
// configPath is re-read by the handler so a missing release_repo (or any other
// config error) surfaces as 4xx/5xx to the caller, not as stderr only.
//
// Authorization: requires (meta, root). Only roles with a wildcard grant
// (the default admin role) match, since "meta" isn't a real module with a
// declared permission vocabulary.
func RegisterUpdate(api huma.API, configPath string) {
huma.Register(api, huma.Operation{
OperationID: "meta-update",
Method: "POST",
Path: "/api/update",
Summary: "Update nadir to the latest release",
Description: "Equivalent to running `sudo nadir update` on the host: queries server.release_repo for the latest release, downloads the binary matching the host's architecture, atomically replaces the running binary, and restarts the systemd unit. Returns 202 immediately; the service restart drops in-flight connections, so poll /api/health to confirm the new version is up. Requires the wildcard admin role.",
Tags: []string{"Meta"},
Metadata: map[string]any{"module": "meta", "permission": "root"},
Errors: []int{400, 401, 403, 500},
DefaultStatus: 202,
}, func(ctx context.Context, _ *struct{}) (*oscmd.StatusOutput, error) {
if configPath != "" {
cfg, err := config.Load(configPath)
if err != nil {
return nil, huma.Error500InternalServerError("config load failed", err)
}
if cfg.Server.ReleaseRepo == "" {
return nil, huma.Error400BadRequest("server.release_repo not set in " + configPath)
}
}
exe, err := os.Executable()
if err != nil {
return nil, huma.Error500InternalServerError("could not resolve own binary path", err)
}
cmd := exec.Command(exe, "update")
// Detach from the server's process group so `systemctl restart nadir`
// (the final step of `nadir update`) doesn't kill its own updater.
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true}
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
return nil, huma.Error500InternalServerError("could not start updater", err)
}
return oscmd.OK(), nil
})
}
+10 -1
View File
@@ -2,6 +2,7 @@ package system
import (
"context"
"regexp"
"strings"
"nadir/internal/oscmd"
@@ -9,6 +10,11 @@ import (
"github.com/danielgtaylor/huma/v2"
)
// hostnameRe matches RFC-1123 labels joined by dots, max 253 chars total. Anchored
// so a leading "-" can't be read as a hostnamectl flag and shell metacharacters
// can't survive — same pattern the other modules use (CLAUDE.md §5).
var hostnameRe = regexp.MustCompile(`^[a-zA-Z0-9]([a-zA-Z0-9-]{0,62})(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,62}))*$`)
type HostnameBody struct {
Hostname string `json:"hostname" example:"server01" doc:"System hostname"`
}
@@ -49,7 +55,10 @@ func registerHostname(api huma.API) {
if name == "" {
return nil, huma.Error400BadRequest("empty hostname")
}
if _, err := oscmd.Run("hostnamectl", "set-hostname", name); err != nil {
if len(name) > 253 || !hostnameRe.MatchString(name) {
return nil, huma.Error400BadRequest("invalid hostname: " + name)
}
if _, err := oscmd.Run("hostnamectl", "set-hostname", "--", name); err != nil {
return nil, huma.Error500InternalServerError("hostnamectl failed", err)
}
return oscmd.OK(), nil
+75 -3
View File
@@ -5,6 +5,7 @@ import (
"math"
"net"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
@@ -159,13 +160,84 @@ func cpuInfo() CPUInfo {
c := CPUInfo{Model: cpuModel(string(data)), LogicalCPUs: runtime.NumCPU()}
c.MinMHz, c.MaxMHz, c.CurrentMHz = cpuFreqMHz("/sys/devices/system/cpu")
// ponytail: cpufreq sysfs is absent on many VMs and stock Ubuntu server
// kernels; fall back to /proc/cpuinfo "cpu MHz" so CurrentMHz isn't 0.
if c.CurrentMHz == 0 {
c.CurrentMHz = cpuinfoMaxMHz(string(data))
// kernels; fall back to /proc/cpuinfo "cpu MHz" — VMs have a fixed clock,
// so min == max == cur is the honest answer.
mhz := cpuinfoMaxMHz(string(data))
// ponytail: ARM /proc/cpuinfo has no "cpu MHz" and often no "model name";
// lscpu decodes the ARM part-id table and reads DMI, so use it as last resort.
if c.Model == "" || mhz == 0 {
model, lscpuMHz := lscpuFallback()
if c.Model == "" {
c.Model = model
}
if mhz == 0 {
mhz = lscpuMHz
}
}
if mhz > 0 {
if c.CurrentMHz == 0 {
c.CurrentMHz = mhz
}
if c.MaxMHz == 0 {
c.MaxMHz = mhz
}
if c.MinMHz == 0 {
c.MinMHz = mhz
}
}
return c
}
// lscpuFallback parses `lscpu` for "Model name" and any embedded "@ X.X GHz"
// or "CPU max MHz:" value. Returns zeros when lscpu is missing or silent.
func lscpuFallback() (model string, mhz int) {
out, err := exec.Command("lscpu").Output()
if err != nil {
return "", 0
}
for line := range strings.SplitSeq(string(out), "\n") {
k, v, ok := strings.Cut(line, ":")
if !ok {
continue
}
k, v = strings.TrimSpace(k), strings.TrimSpace(v)
switch k {
case "Model name":
if model == "" {
model = v
}
case "BIOS Model name":
if model == "" {
model = v
}
case "CPU max MHz", "CPU MHz":
if f, err := strconv.ParseFloat(v, 64); err == nil && int(f) > mhz {
mhz = int(math.Round(f))
}
}
}
if mhz == 0 {
mhz = parseGHzSuffix(model)
}
return model, mhz
}
// parseGHzSuffix pulls "2.0GHz" / "@ 2.0 GHz" out of a model string.
func parseGHzSuffix(s string) int {
i := strings.LastIndex(s, "@")
if i < 0 {
return 0
}
rest := strings.TrimSpace(s[i+1:])
rest = strings.TrimSuffix(strings.TrimSuffix(rest, "GHz"), "Ghz")
rest = strings.TrimSpace(strings.TrimSuffix(rest, "G"))
f, err := strconv.ParseFloat(strings.TrimSpace(rest), 64)
if err != nil {
return 0
}
return int(math.Round(f * 1000))
}
// cpuinfoMaxMHz returns the highest "cpu MHz" value across all cores in
// /proc/cpuinfo, rounded to an int. Returns 0 when no such line exists.
func cpuinfoMaxMHz(cpuinfo string) int {
+135 -8
View File
@@ -2,6 +2,10 @@ package system
import (
"context"
"fmt"
"os"
"os/exec"
"regexp"
"slices"
"strings"
@@ -42,6 +46,16 @@ type SetKeymapInput struct {
}
}
type GenerateLocaleInput struct {
Body struct {
Locale string `json:"locale" example:"fr_FR.UTF-8" doc:"Locale to generate (e.g. fr_FR.UTF-8)"`
}
}
// localeRe validates a locale identifier: language_TERRITORY with an optional
// .charmap suffix (e.g. fr_FR, fr_FR.UTF-8, en_US.ISO-8859-1).
var localeRe = regexp.MustCompile(`^[a-z]{2,3}_[A-Z]{2}(\.[A-Za-z0-9_-]+)?$`)
func localeStatus() (LocaleStatusBody, error) {
lines, err := oscmd.RunLines("localectl", "status")
if err != nil {
@@ -146,10 +160,11 @@ func registerLocale(api huma.API) {
Metadata: op("read"),
Errors: readErrors,
}, func(ctx context.Context, _ *struct{}) (*KeymapsOutput, error) {
keymaps, err := oscmd.RunLines("localectl", "list-keymaps")
if err != nil {
return nil, huma.Error500InternalServerError("localectl failed", err)
}
// ponytail: minimal servers ship without kbd / /usr/share/keymaps, so
// localectl errors instead of returning empty. Treat that as "no keymaps
// available" rather than a server fault — set-keymap stays unreachable
// because nothing will be in the allowlist.
keymaps, _ := oscmd.RunLines("localectl", "list-keymaps")
out := &KeymapsOutput{}
out.Body.Keymaps = keymaps
return out, nil
@@ -171,10 +186,9 @@ func registerLocale(api huma.API) {
if km == "" {
return nil, huma.Error400BadRequest("empty keymap")
}
keymaps, err := oscmd.RunLines("localectl", "list-keymaps")
if err != nil {
return nil, huma.Error500InternalServerError("localectl failed", err)
}
// list-keymaps failure means no keymap allowlist on this host (kbd absent);
// fall through to unknown-keymap 400 instead of 500.
keymaps, _ := oscmd.RunLines("localectl", "list-keymaps")
if !slices.Contains(keymaps, km) {
return nil, huma.Error400BadRequest("unknown keymap: " + km)
}
@@ -183,4 +197,117 @@ func registerLocale(api huma.API) {
}
return oscmd.OK(), nil
})
huma.Register(api, huma.Operation{
OperationID: "system-generate-locale",
Method: "POST",
Path: "/api/system/locale/generate",
Summary: "Generate (install) a new locale",
Description: "Generates a locale so it becomes available for use with set-locale. " +
"On Debian/Ubuntu/Arch this uncomments the entry in /etc/locale.gen and runs " +
"locale-gen; on RHEL/Fedora it uses localedef. Idempotent: if the locale is " +
"already generated, returns 200 immediately.",
Tags: []string{tagSystem},
Metadata: op("write"),
Errors: append(writeErrors, 501),
}, func(ctx context.Context, in *GenerateLocaleInput) (*oscmd.StatusOutput, error) {
locale := strings.TrimSpace(in.Body.Locale)
if locale == "" {
return nil, huma.Error400BadRequest("empty locale")
}
if !localeRe.MatchString(locale) {
return nil, huma.Error400BadRequest("invalid locale format: "+locale,
fmt.Errorf("expected language_TERRITORY[.charmap], e.g. fr_FR.UTF-8"))
}
// Idempotency: already generated → success.
existing, err := oscmd.RunLines("localectl", "list-locales")
if err != nil {
return nil, huma.Error500InternalServerError("localectl failed", err)
}
if slices.Contains(existing, locale) {
return oscmd.OK(), nil
}
// Detect which generation path the host supports.
localeGenFile := "/etc/locale.gen"
_, hasFile := os.Stat(localeGenFile)
_, hasLocaleGen := exec.LookPath("locale-gen")
_, hasLocaledef := exec.LookPath("localedef")
switch {
case hasFile == nil && hasLocaleGen == nil:
if err := enableLocaleGen(localeGenFile, locale); err != nil {
return nil, err
}
case hasLocaledef == nil:
if err := generateLocaledef(locale); err != nil {
return nil, err
}
default:
return nil, huma.Error501NotImplemented(
"locale generation not supported on this host (no locale-gen or localedef found)")
}
return oscmd.OK(), nil
})
}
// enableLocaleGen uncomments the locale in /etc/locale.gen and runs locale-gen.
// This is the Debian/Ubuntu/Arch path.
func enableLocaleGen(path, locale string) error {
data, err := os.ReadFile(path)
if err != nil {
return huma.Error500InternalServerError("reading locale.gen failed", err)
}
newContent, found := uncommentLocaleGen(string(data), locale)
if !found {
return huma.Error400BadRequest("locale not available for generation: " + locale)
}
if err := os.WriteFile(path, []byte(newContent), 0644); err != nil {
return huma.Error500InternalServerError("writing locale.gen failed", err)
}
if _, err := oscmd.Run("locale-gen"); err != nil {
return huma.Error500InternalServerError("locale-gen failed", err)
}
return nil
}
// uncommentLocaleGen finds a commented-out line for the given locale in a
// locale.gen file and uncomments it. Returns the modified content and whether
// a matching line was found. Pure function for testability.
func uncommentLocaleGen(content, locale string) (string, bool) {
lines := strings.Split(content, "\n")
found := false
for i, line := range lines {
trimmed := strings.TrimSpace(line)
// Match lines like "# fr_FR.UTF-8 UTF-8" or "#fr_FR.UTF-8 UTF-8".
if !strings.HasPrefix(trimmed, "#") {
// Also check if already uncommented (idempotent at the file level).
if strings.HasPrefix(trimmed, locale+" ") || trimmed == locale {
found = true
}
continue
}
uncommented := strings.TrimSpace(strings.TrimPrefix(trimmed, "#"))
if strings.HasPrefix(uncommented, locale+" ") || uncommented == locale {
lines[i] = uncommented
found = true
}
}
return strings.Join(lines, "\n"), found
}
// generateLocaledef generates a locale using localedef. This is the RHEL/Fedora
// path where there is no /etc/locale.gen.
func generateLocaledef(locale string) error {
// Parse "fr_FR.UTF-8" into language_territory="fr_FR" and charmap="UTF-8".
// If there is no dot, default to UTF-8 (the common case on modern systems).
langTerritory, charmap, _ := strings.Cut(locale, ".")
if charmap == "" {
charmap = "UTF-8"
}
if _, err := oscmd.Run("localedef", "-i", langTerritory, "-f", charmap, locale); err != nil {
return huma.Error500InternalServerError("localedef failed", err)
}
return nil
}
+88 -1
View File
@@ -4,6 +4,7 @@ import (
"encoding/json"
"net/http"
"reflect"
"strings"
"testing"
"nadir/internal/oscmd"
@@ -46,7 +47,7 @@ func TestSystemHandlers(t *testing.T) {
if reflect.DeepEqual(args, []string{"hostname"}) {
return oscmd.MockCommand{Stdout: "server01\n", ExitCode: 0}
}
if reflect.DeepEqual(args, []string{"set-hostname", "server02"}) {
if reflect.DeepEqual(args, []string{"set-hostname", "--", "server02"}) {
return oscmd.MockCommand{ExitCode: 0}
}
return oscmd.MockCommand{ExitCode: 1}
@@ -199,6 +200,37 @@ func TestSystemHandlers(t *testing.T) {
t.Errorf("set keymap: got %d, want %d", resp.Code, http.StatusOK)
}
// 4b. Test POST /api/system/locale/generate (validation & idempotent)
// Empty locale → 422 (huma validates non-empty before handler runs)
resp = api.Post("/api/system/locale/generate", struct {
Locale string `json:"locale"`
}{
Locale: "",
})
if resp.Code != http.StatusBadRequest && resp.Code != http.StatusUnprocessableEntity {
t.Errorf("generate empty locale: got %d, want 400 or 422", resp.Code)
}
// Invalid format → 400
resp = api.Post("/api/system/locale/generate", struct {
Locale string `json:"locale"`
}{
Locale: "not-a-locale!!",
})
if resp.Code != http.StatusBadRequest {
t.Errorf("generate invalid locale: got %d, want %d", resp.Code, http.StatusBadRequest)
}
// Already generated (it_IT.UTF-8 is in list-locales mock) → 200 (idempotent)
resp = api.Post("/api/system/locale/generate", struct {
Locale string `json:"locale"`
}{
Locale: "it_IT.UTF-8",
})
if resp.Code != http.StatusOK {
t.Errorf("generate existing locale (idempotent): got %d, want %d", resp.Code, http.StatusOK)
}
// 5. Test POST /api/system/reboot and /api/system/poweroff
oscmd.SetMock("shutdown", func(args []string) oscmd.MockCommand {
if reflect.DeepEqual(args, []string{"-r", "now"}) || reflect.DeepEqual(args, []string{"-h", "now"}) {
@@ -225,3 +257,58 @@ func TestSystemHandlers(t *testing.T) {
t.Errorf("poweroff: got %d, want %d", resp.Code, http.StatusOK)
}
}
func TestUncommentLocaleGen(t *testing.T) {
const sampleLocaleGen = `# This file lists locales that you wish to have built.
#
# en_US.UTF-8 UTF-8
# fr_FR.UTF-8 UTF-8
# de_DE.UTF-8 UTF-8
it_IT.UTF-8 UTF-8
`
tests := []struct {
name string
locale string
wantFound bool
wantSubstr string // substring that should appear uncommented
}{
{
name: "uncomment commented locale",
locale: "fr_FR.UTF-8",
wantFound: true,
wantSubstr: "\nfr_FR.UTF-8 UTF-8\n",
},
{
name: "already uncommented",
locale: "it_IT.UTF-8",
wantFound: true,
},
{
name: "locale not in file",
locale: "ja_JP.UTF-8",
wantFound: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result, found := uncommentLocaleGen(sampleLocaleGen, tt.locale)
if found != tt.wantFound {
t.Errorf("found = %v, want %v", found, tt.wantFound)
}
if tt.wantSubstr != "" && !contains(result, tt.wantSubstr) {
t.Errorf("result does not contain %q:\n%s", tt.wantSubstr, result)
}
// The commented versions of OTHER locales should remain commented.
if tt.locale == "fr_FR.UTF-8" && !contains(result, "# en_US.UTF-8 UTF-8") {
t.Errorf("other locales should stay commented:\n%s", result)
}
})
}
}
func contains(s, substr string) bool {
return len(s) >= len(substr) && (s == substr || len(substr) == 0 ||
(len(s) > 0 && strings.Contains(s, substr)))
}
+1 -1
View File
@@ -126,7 +126,7 @@ func (m *terminalModule) Register(api huma.API) {
// Launch the user's login shell via su.
// "su - <username>" ensures we get their actual environment and shell.
cmd := exec.CommandContext(req.Context(), "su", "-", sess.Username)
cmd := exec.CommandContext(req.Context(), "su", "-", "--", sess.Username)
// Start the command with a PTY.
ptmx, err := pty.Start(cmd)
+2
View File
@@ -0,0 +1,2 @@
untrusted comment: minisign public key: 702ABD7F45200669
RWRpBiBFf70qcEXS0cOS+8tZ1hpoLj9mX0V5OiE8qYIIZsetU8hNA4Ou
Executable
BIN
View File
Binary file not shown.
+54
View File
@@ -0,0 +1,54 @@
// Command sign-checksums is a CI helper that signs a file using minisign.
//
// The minisign CLI reads passwords from /dev/tty, which doesn't exist in CI
// runners. This program uses the library directly: password and encrypted
// secret key come from environment variables, no terminal required.
//
// Usage (in CI):
//
// MINISIGN_SECRET_KEY=... MINISIGN_PASSWORD=... go run ./tools/sign-checksums dist/sha256sums.txt
//
// Produces dist/sha256sums.txt.minisig alongside the input.
package main
import (
"fmt"
"os"
"aead.dev/minisign"
)
func main() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, "usage: sign-checksums <file>\n")
os.Exit(2)
}
filePath := os.Args[1]
password := os.Getenv("MINISIGN_PASSWORD")
keyBytes := []byte(os.Getenv("MINISIGN_SECRET_KEY"))
if len(keyBytes) == 0 {
fmt.Fprintln(os.Stderr, "MINISIGN_SECRET_KEY is not set")
os.Exit(1)
}
key, err := minisign.DecryptKey(password, keyBytes)
if err != nil {
fmt.Fprintf(os.Stderr, "decrypt key: %v\n", err)
os.Exit(1)
}
message, err := os.ReadFile(filePath)
if err != nil {
fmt.Fprintf(os.Stderr, "read %s: %v\n", filePath, err)
os.Exit(1)
}
sig := minisign.Sign(key, message)
sigPath := filePath + ".minisig"
if err := os.WriteFile(sigPath, sig, 0644); err != nil {
fmt.Fprintf(os.Stderr, "write %s: %v\n", sigPath, err)
os.Exit(1)
}
fmt.Printf("signed %s -> %s\n", filePath, sigPath)
}