v0.5.2: FleetDM login split, 3-slot branding, unattended installs
Authentication / login:
- Separate the local username/password form from the SSO "Sign in with …"
button (FleetDM-style divider + optional IdP logo); credential fields no
longer double as the SSO trigger. Settings → SSO copy now says SAML is live.
Branding — three slots (light / dark / client) on one row:
- Light/Dark feed the top-left mark + sign-in page by active theme (with
cross-theme fallback; theme toggle swaps the logo live). Client feeds the
PXE boot-menu background. Favicon pinned to the bundled mark via a new
/assets/favicon.svg endpoint. Legacy single logo migrates to dark + client.
- BrandingStore refactored to per-slot storage; /api/branding/logo/:slot.
Unattended installs (Storage → Advanced):
- New UnattendedStore (iso-store) + /api/unattended upload/list/delete and a
public templated serve at /unattended/:id (+ NoCloud seed dir for
autoinstall). Accepts .ks/.cfg/.seed/.yaml/.yml/.xml/user-data; classified
on upload; stored in its own unattended/ dir, never the ISO listing/menu.
- {{HOSTNAME}}/{{IP}}/{{MAC}} substituted per host at serve time.
Host pins + Queue profiles:
- HostBinding + QueueEntry carry an optional DeployProfile (auto_hostname /
auto_ip / unattended_file). Hosts pin form + a per-device Queue "Profile"
button collect them. On boot, a matched MAC has the right kernel arg
injected (inst.ks= / preseed url= / autoinstall ds=nocloud-net) and the
hostname/IP templated into the served answer file. DHCP stays proxy-only.
Storage:
- Remote shares default protocol is now NFS; updated descriptive copy.
235 tests green, clippy clean. Still a single static musl binary, pure Rust.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
This commit is contained in:
co-authored by
Claude Opus 4.8
parent
cbcd63bb14
commit
7adf5e2918
+437
-147
@@ -1,11 +1,23 @@
|
||||
//! Operator-controlled branding overrides.
|
||||
//!
|
||||
//! The browser tab's logo (`/assets/logo.svg`) defaults to the bundled
|
||||
//! rainbow-horizon mark. Operators who deploy OpenPXE behind their own
|
||||
//! branding can upload a replacement that lives at
|
||||
//! `<work_dir>/branding/logo.<ext>` and is served in preference to the
|
||||
//! bundled SVG when present. Borrowed-from-FleetDM: tenant chrome, same
|
||||
//! product.
|
||||
//! v0.5.2 splits the single brand mark into **three independent slots**,
|
||||
//! FleetDM-style:
|
||||
//!
|
||||
//! * `light` — shown in the WebUI top-left and on the form-login page
|
||||
//! when the active theme is light.
|
||||
//! * `dark` — same surfaces, when the active theme is dark.
|
||||
//! * `client` — the raster painted above the iPXE boot menu entries
|
||||
//! (`/branding/pxe-logo`), i.e. what a PXE client sees on the screen.
|
||||
//!
|
||||
//! Each slot lives at `<work_dir>/branding/logo-<slot>.<ext>` and is
|
||||
//! served in preference to the bundled rainbow-horizon mark when present.
|
||||
//! Borrowed-from-FleetDM: tenant chrome, same product.
|
||||
//!
|
||||
//! Legacy continuity: a pre-v0.5.2 single `logo.<ext>` (recorded under
|
||||
//! the old `logo_filename`/`logo_mime` keys) is migrated on first load
|
||||
//! into both the `dark` and `client` slots — that preserves the previous
|
||||
//! behaviour (one mark fed both the dark WebUI and the PXE screen) until
|
||||
//! the operator uploads dedicated variants.
|
||||
//!
|
||||
//! Storage policy mirrors `HostBindings` / `BootLog`: in-memory cache is
|
||||
//! authoritative for the current process, disk is the source of truth on
|
||||
@@ -35,27 +47,104 @@ pub const ALLOWED_LOGO_MIMES: &[&str] = &[
|
||||
/// puts a clear bound on memory + serialization cost.
|
||||
pub const MAX_LOGO_BYTES: usize = 2 * 1024 * 1024;
|
||||
|
||||
/// Which branded surface a logo upload targets.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum LogoSlot {
|
||||
/// WebUI + form-login page, light theme.
|
||||
Light,
|
||||
/// WebUI + form-login page, dark theme.
|
||||
Dark,
|
||||
/// iPXE boot-menu background seen by PXE clients.
|
||||
Client,
|
||||
}
|
||||
|
||||
impl LogoSlot {
|
||||
#[must_use]
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
LogoSlot::Light => "light",
|
||||
LogoSlot::Dark => "dark",
|
||||
LogoSlot::Client => "client",
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a slot name from the URL path segment. Case-insensitive.
|
||||
#[must_use]
|
||||
pub fn parse(s: &str) -> Option<Self> {
|
||||
match s.trim().to_ascii_lowercase().as_str() {
|
||||
"light" => Some(LogoSlot::Light),
|
||||
"dark" => Some(LogoSlot::Dark),
|
||||
"client" => Some(LogoSlot::Client),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One brand-mark slot: a filename (relative to the branding dir) plus
|
||||
/// the MIME we cached at upload time so the HTTP layer can set the
|
||||
/// Content-Type without re-sniffing.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
struct Slot {
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
filename: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
mime: Option<String>,
|
||||
}
|
||||
|
||||
impl Slot {
|
||||
fn clear_file(&mut self, dir: &Path) {
|
||||
if let Some(name) = self.filename.take() {
|
||||
let _ = std::fs::remove_file(dir.join(name));
|
||||
}
|
||||
self.mime = None;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
struct Inner {
|
||||
/// File name (relative to the branding dir) for the active logo, if
|
||||
/// any. Always under `<work_dir>/branding/`; never an absolute path
|
||||
/// from the operator.
|
||||
logo_filename: Option<String>,
|
||||
/// MIME of the active logo, mirroring `logo_filename`. Cached here
|
||||
/// so the HTTP layer can set Content-Type without re-sniffing.
|
||||
logo_mime: Option<String>,
|
||||
/// Monotonic counter bumped on every set/clear. Surfaces as a
|
||||
/// cache-bust token (`/assets/logo.svg?r=<rev>`) so the browser
|
||||
/// fetches the new bytes the moment the operator swaps the logo —
|
||||
/// the app version alone can't do this since it doesn't change on
|
||||
/// upload. Persisted so the token stays stable across restarts and
|
||||
/// keeps climbing across multiple swaps.
|
||||
#[serde(default)]
|
||||
light: Slot,
|
||||
#[serde(default)]
|
||||
dark: Slot,
|
||||
#[serde(default)]
|
||||
client: Slot,
|
||||
/// Monotonic counter bumped on every set/clear (any slot). Surfaces
|
||||
/// as a cache-bust token (`/assets/logo.svg?r=<rev>`) so the browser
|
||||
/// fetches the new bytes the moment the operator swaps a logo — the
|
||||
/// app version alone can't do this since it doesn't change on upload.
|
||||
/// Persisted so the token stays stable across restarts and keeps
|
||||
/// climbing across multiple swaps.
|
||||
#[serde(default)]
|
||||
rev: u64,
|
||||
// ── Legacy (pre-v0.5.2) single-logo keys ──────────────────────────
|
||||
// Read on load for one-way migration into `dark` + `client`, then
|
||||
// dropped from the persisted form (skip_serializing_if).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
logo_filename: Option<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
logo_mime: Option<String>,
|
||||
}
|
||||
|
||||
impl Inner {
|
||||
fn slot(&self, slot: LogoSlot) -> &Slot {
|
||||
match slot {
|
||||
LogoSlot::Light => &self.light,
|
||||
LogoSlot::Dark => &self.dark,
|
||||
LogoSlot::Client => &self.client,
|
||||
}
|
||||
}
|
||||
|
||||
fn slot_mut(&mut self, slot: LogoSlot) -> &mut Slot {
|
||||
match slot {
|
||||
LogoSlot::Light => &mut self.light,
|
||||
LogoSlot::Dark => &mut self.dark,
|
||||
LogoSlot::Client => &mut self.client,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// In-memory + on-disk override registry. Cheap to clone; locks are
|
||||
/// brief. The `branding.json` cache lives alongside the active asset
|
||||
/// brief. The `branding.json` cache lives alongside the active assets
|
||||
/// inside `<work_dir>/branding/`.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BrandingStore {
|
||||
@@ -67,7 +156,8 @@ pub struct BrandingStore {
|
||||
impl BrandingStore {
|
||||
/// Load (or initialise empty) from `<work_dir>/branding/`. Tolerates
|
||||
/// missing directories, partial state, and corrupt JSON — a bad
|
||||
/// cache should never block PXE for the network.
|
||||
/// cache should never block PXE for the network. Migrates a legacy
|
||||
/// single-logo file into the dark + client slots.
|
||||
#[must_use]
|
||||
pub fn load_or_default(work_dir: &Path) -> Self {
|
||||
let dir = work_dir.join("branding");
|
||||
@@ -75,25 +165,7 @@ impl BrandingStore {
|
||||
let mut inner = Inner::default();
|
||||
if let Ok(text) = std::fs::read_to_string(&path) {
|
||||
match serde_json::from_str::<Inner>(&text) {
|
||||
Ok(parsed) => {
|
||||
// Sanity: if the JSON says we have a logo but the
|
||||
// file is gone, clear the in-memory pointer so
|
||||
// /assets/logo.svg falls back to the bundled SVG
|
||||
// rather than 500ing on a missing file.
|
||||
if let Some(name) = parsed.logo_filename.as_deref() {
|
||||
if dir.join(name).is_file() {
|
||||
inner = parsed;
|
||||
} else {
|
||||
tracing::warn!(
|
||||
target: "openpxe::branding",
|
||||
file = %name,
|
||||
"branding.json points at missing file; clearing"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
inner = parsed;
|
||||
}
|
||||
}
|
||||
Ok(parsed) => inner = parsed,
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
target: "openpxe::branding",
|
||||
@@ -102,102 +174,242 @@ impl BrandingStore {
|
||||
}
|
||||
}
|
||||
}
|
||||
Self {
|
||||
let store = Self {
|
||||
dir: Arc::new(dir),
|
||||
inner: Arc::new(RwLock::new(inner)),
|
||||
};
|
||||
store.migrate_legacy();
|
||||
store.prune_missing();
|
||||
store
|
||||
}
|
||||
|
||||
/// One-way migration: a pre-v0.5.2 `logo.<ext>` becomes the dark +
|
||||
/// client slots (the old single mark fed both the dark WebUI and the
|
||||
/// PXE screen). Best-effort; failures leave the legacy file in place
|
||||
/// rather than blocking startup.
|
||||
fn migrate_legacy(&self) {
|
||||
let (legacy_name, legacy_mime) = {
|
||||
let g = self.inner.read();
|
||||
(g.logo_filename.clone(), g.logo_mime.clone())
|
||||
};
|
||||
let Some(name) = legacy_name else { return };
|
||||
let src = self.dir.join(&name);
|
||||
if !src.is_file() {
|
||||
// Legacy pointer is stale — just drop it.
|
||||
let mut g = self.inner.write();
|
||||
g.logo_filename = None;
|
||||
g.logo_mime = None;
|
||||
drop(g);
|
||||
self.persist();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/// Absolute path to the active logo, if one is set and present on
|
||||
/// disk. `None` means the HTTP layer should serve the bundled SVG.
|
||||
#[must_use]
|
||||
pub fn logo_path(&self) -> Option<PathBuf> {
|
||||
let g = self.inner.read();
|
||||
g.logo_filename.as_deref().map(|n| self.dir.join(n))
|
||||
}
|
||||
|
||||
/// MIME of the active logo, if any. The HTTP layer pairs this with
|
||||
/// the bytes returned by [`Self::logo_path`].
|
||||
#[must_use]
|
||||
pub fn logo_mime(&self) -> Option<String> {
|
||||
self.inner.read().logo_mime.clone()
|
||||
}
|
||||
|
||||
/// Replace the active logo. Returns the chosen on-disk filename so
|
||||
/// the caller can echo it back in the API response. Old logos are
|
||||
/// removed best-effort.
|
||||
pub fn set_logo(&self, mime: &str, ext: &str, bytes: &[u8]) -> std::io::Result<String> {
|
||||
std::fs::create_dir_all(self.dir.as_path())?;
|
||||
// Single canonical filename per upload — overwriting the old one
|
||||
// (after clearing it) keeps the directory tidy and avoids any
|
||||
// path-traversal concern: the operator never supplies the name.
|
||||
let safe_ext = sanitize_ext(ext);
|
||||
let filename = format!("logo.{safe_ext}");
|
||||
let final_path = self.dir.join(&filename);
|
||||
// Atomic write: tmp -> rename. Guarantees the file is either
|
||||
// entirely the old logo or entirely the new one.
|
||||
let tmp = final_path.with_extension(format!("{safe_ext}.tmp"));
|
||||
std::fs::write(&tmp, bytes)?;
|
||||
std::fs::rename(&tmp, &final_path)?;
|
||||
// Clean up any sibling logo.<otherext> so there's exactly one
|
||||
// canonical file at any time.
|
||||
if let Ok(entries) = std::fs::read_dir(self.dir.as_path()) {
|
||||
for e in entries.flatten() {
|
||||
let p = e.path();
|
||||
let name = p
|
||||
.file_name()
|
||||
.and_then(|s| s.to_str())
|
||||
.unwrap_or("");
|
||||
if name.starts_with("logo.") && name != filename {
|
||||
let _ = std::fs::remove_file(&p);
|
||||
}
|
||||
let mime = legacy_mime.unwrap_or_else(|| "image/svg+xml".to_string());
|
||||
let ext = ext_for_mime(&mime).unwrap_or("bin");
|
||||
if let Ok(bytes) = std::fs::read(&src) {
|
||||
// Seed dark + client only when those slots are still empty so
|
||||
// a re-run (or a manual edit) never clobbers operator intent.
|
||||
let needs_dark = self.inner.read().dark.filename.is_none();
|
||||
let needs_client = self.inner.read().client.filename.is_none();
|
||||
if needs_dark {
|
||||
let _ = self.write_slot(LogoSlot::Dark, &mime, ext, &bytes);
|
||||
}
|
||||
if needs_client {
|
||||
let _ = self.write_slot(LogoSlot::Client, &mime, ext, &bytes);
|
||||
}
|
||||
}
|
||||
|
||||
let _ = std::fs::remove_file(&src);
|
||||
{
|
||||
let mut g = self.inner.write();
|
||||
g.logo_filename = Some(filename.clone());
|
||||
g.logo_mime = Some(mime.to_string());
|
||||
g.rev = g.rev.wrapping_add(1);
|
||||
g.logo_filename = None;
|
||||
g.logo_mime = None;
|
||||
}
|
||||
self.persist();
|
||||
tracing::info!(
|
||||
target: "openpxe::branding",
|
||||
file = %filename, mime = %mime, size = bytes.len(),
|
||||
"migrated legacy single logo into dark + client slots"
|
||||
);
|
||||
}
|
||||
|
||||
/// Drop in-memory slot pointers whose backing file vanished from disk
|
||||
/// so the HTTP layer falls back to the bundled mark instead of 500ing.
|
||||
fn prune_missing(&self) {
|
||||
let mut changed = false;
|
||||
{
|
||||
let mut g = self.inner.write();
|
||||
for slot in [LogoSlot::Light, LogoSlot::Dark, LogoSlot::Client] {
|
||||
let present = g
|
||||
.slot(slot)
|
||||
.filename
|
||||
.as_deref()
|
||||
.is_some_and(|n| self.dir.join(n).is_file());
|
||||
if !present && g.slot(slot).filename.is_some() {
|
||||
g.slot_mut(slot).filename = None;
|
||||
g.slot_mut(slot).mime = None;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
self.persist();
|
||||
}
|
||||
}
|
||||
|
||||
/// Absolute path to the logo for `slot`, if set and present on disk.
|
||||
#[must_use]
|
||||
pub fn slot_path(&self, slot: LogoSlot) -> Option<PathBuf> {
|
||||
let g = self.inner.read();
|
||||
g.slot(slot).filename.as_deref().map(|n| self.dir.join(n))
|
||||
}
|
||||
|
||||
/// MIME of the logo for `slot`, if any.
|
||||
#[must_use]
|
||||
pub fn slot_mime(&self, slot: LogoSlot) -> Option<String> {
|
||||
self.inner.read().slot(slot).mime.clone()
|
||||
}
|
||||
|
||||
/// Resolve the WebUI logo for a theme, with fallback: light falls
|
||||
/// back to dark and vice-versa, so a single uploaded variant still
|
||||
/// shows on both themes. Returns `(path, mime)` or `None` (→ bundled).
|
||||
#[must_use]
|
||||
pub fn web_logo(&self, theme_is_light: bool) -> Option<(PathBuf, String)> {
|
||||
let (primary, secondary) = if theme_is_light {
|
||||
(LogoSlot::Light, LogoSlot::Dark)
|
||||
} else {
|
||||
(LogoSlot::Dark, LogoSlot::Light)
|
||||
};
|
||||
let g = self.inner.read();
|
||||
let chosen = if g.slot(primary).filename.is_some() {
|
||||
primary
|
||||
} else {
|
||||
secondary
|
||||
};
|
||||
let s = g.slot(chosen);
|
||||
s.filename.as_deref().map(|n| {
|
||||
(
|
||||
self.dir.join(n),
|
||||
s.mime
|
||||
.clone()
|
||||
.unwrap_or_else(|| "image/svg+xml".to_string()),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Resolve the PXE client logo (no theme fallback — the PXE screen
|
||||
/// has a single mark). Returns `(path, mime)` or `None` (→ default
|
||||
/// composed background).
|
||||
#[must_use]
|
||||
pub fn client_logo(&self) -> Option<(PathBuf, String)> {
|
||||
let g = self.inner.read();
|
||||
let s = &g.client;
|
||||
s.filename.as_deref().map(|n| {
|
||||
(
|
||||
self.dir.join(n),
|
||||
s.mime
|
||||
.clone()
|
||||
.unwrap_or_else(|| "application/octet-stream".to_string()),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Replace the logo for `slot`. Returns the chosen on-disk filename so
|
||||
/// the caller can echo it back in the API response.
|
||||
pub fn set_logo(
|
||||
&self,
|
||||
slot: LogoSlot,
|
||||
mime: &str,
|
||||
ext: &str,
|
||||
bytes: &[u8],
|
||||
) -> std::io::Result<String> {
|
||||
let filename = self.write_slot(slot, mime, ext, bytes)?;
|
||||
self.persist();
|
||||
tracing::info!(
|
||||
target: "openpxe::branding",
|
||||
slot = slot.as_str(), file = %filename, mime = %mime, size = bytes.len(),
|
||||
"custom logo installed"
|
||||
);
|
||||
Ok(filename)
|
||||
}
|
||||
|
||||
/// Drop the override and return to the bundled SVG.
|
||||
pub fn clear_logo(&self) -> std::io::Result<()> {
|
||||
let removed = {
|
||||
/// Write the bytes for a slot and update the in-memory pointer + rev,
|
||||
/// without persisting (the caller decides when to flush). Cleans up
|
||||
/// any sibling `logo-<slot>.*` so there's exactly one file per slot.
|
||||
fn write_slot(
|
||||
&self,
|
||||
slot: LogoSlot,
|
||||
mime: &str,
|
||||
ext: &str,
|
||||
bytes: &[u8],
|
||||
) -> std::io::Result<String> {
|
||||
std::fs::create_dir_all(self.dir.as_path())?;
|
||||
let safe_ext = sanitize_ext(ext);
|
||||
let stem = format!("logo-{}", slot.as_str());
|
||||
let filename = format!("{stem}.{safe_ext}");
|
||||
let final_path = self.dir.join(&filename);
|
||||
// Atomic write: tmp -> rename.
|
||||
let tmp = final_path.with_extension(format!("{safe_ext}.tmp"));
|
||||
std::fs::write(&tmp, bytes)?;
|
||||
std::fs::rename(&tmp, &final_path)?;
|
||||
// Clean up any sibling `logo-<slot>.<otherext>`.
|
||||
if let Ok(entries) = std::fs::read_dir(self.dir.as_path()) {
|
||||
for e in entries.flatten() {
|
||||
let p = e.path();
|
||||
let name = p.file_name().and_then(|s| s.to_str()).unwrap_or("");
|
||||
if name.starts_with(&format!("{stem}.")) && name != filename {
|
||||
let _ = std::fs::remove_file(&p);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut g = self.inner.write();
|
||||
let s = g.slot_mut(slot);
|
||||
s.filename = Some(filename.clone());
|
||||
s.mime = Some(mime.to_string());
|
||||
g.rev = g.rev.wrapping_add(1);
|
||||
Ok(filename)
|
||||
}
|
||||
|
||||
/// Drop the override for `slot` and return to the bundled / default.
|
||||
pub fn clear_logo(&self, slot: LogoSlot) -> std::io::Result<()> {
|
||||
{
|
||||
let mut g = self.inner.write();
|
||||
let removed = g.logo_filename.take();
|
||||
g.logo_mime = None;
|
||||
let dir = self.dir.as_path();
|
||||
g.slot_mut(slot).clear_file(dir);
|
||||
g.rev = g.rev.wrapping_add(1);
|
||||
removed
|
||||
};
|
||||
if let Some(name) = removed {
|
||||
let p = self.dir.join(&name);
|
||||
let _ = std::fs::remove_file(&p);
|
||||
tracing::info!(target: "openpxe::branding", file = %name, "custom logo cleared");
|
||||
}
|
||||
self.persist();
|
||||
tracing::info!(target: "openpxe::branding", slot = slot.as_str(), "custom logo cleared");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Convenience: true if a custom logo is configured. Surfaces on
|
||||
/// `/api/status` so the WebUI can show "Custom logo: yes" without
|
||||
/// fetching the asset itself.
|
||||
/// True if a custom logo is configured for `slot`.
|
||||
#[must_use]
|
||||
pub fn has_logo(&self) -> bool {
|
||||
self.inner.read().logo_filename.is_some()
|
||||
pub fn has_logo(&self, slot: LogoSlot) -> bool {
|
||||
self.inner.read().slot(slot).filename.is_some()
|
||||
}
|
||||
|
||||
/// Cache-bust token for the logo asset URL. Changes on every
|
||||
/// True if either WebUI theme slot has a custom logo — drives the
|
||||
/// FleetDM-style full-width brand block (and the `has-custom-logo`
|
||||
/// class) on the sidebar + login page.
|
||||
#[must_use]
|
||||
pub fn has_any_web_logo(&self) -> bool {
|
||||
let g = self.inner.read();
|
||||
g.light.filename.is_some() || g.dark.filename.is_some()
|
||||
}
|
||||
|
||||
/// Presence triple `(light, dark, client)` for the `/api/me` and
|
||||
/// `/api/status` bootstrap payloads.
|
||||
#[must_use]
|
||||
pub fn presence(&self) -> (bool, bool, bool) {
|
||||
let g = self.inner.read();
|
||||
(
|
||||
g.light.filename.is_some(),
|
||||
g.dark.filename.is_some(),
|
||||
g.client.filename.is_some(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Cache-bust token for the logo asset URLs. Changes on every
|
||||
/// set/clear so `/assets/logo.svg?r=<rev>` resolves to a fresh URL
|
||||
/// whenever the operator swaps the brand mark. Stable otherwise.
|
||||
/// whenever the operator swaps a brand mark. Stable otherwise.
|
||||
#[must_use]
|
||||
pub fn logo_rev(&self) -> u64 {
|
||||
self.inner.read().rev
|
||||
@@ -267,47 +479,87 @@ mod tests {
|
||||
fn empty_after_load_when_no_branding_dir() {
|
||||
let dir = tempdir().unwrap();
|
||||
let b = BrandingStore::load_or_default(dir.path());
|
||||
assert!(!b.has_logo());
|
||||
assert!(b.logo_path().is_none());
|
||||
assert!(b.logo_mime().is_none());
|
||||
assert!(!b.has_logo(LogoSlot::Light));
|
||||
assert!(!b.has_logo(LogoSlot::Dark));
|
||||
assert!(!b.has_logo(LogoSlot::Client));
|
||||
assert!(b.web_logo(false).is_none());
|
||||
assert!(b.client_logo().is_none());
|
||||
assert!(!b.has_any_web_logo());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn set_clear_round_trip_persists() {
|
||||
let dir = tempdir().unwrap();
|
||||
let b = BrandingStore::load_or_default(dir.path());
|
||||
let name = b.set_logo("image/png", "png", b"\x89PNG\r\n\x1a\nfake").unwrap();
|
||||
assert_eq!(name, "logo.png");
|
||||
assert!(b.has_logo());
|
||||
assert_eq!(b.logo_mime().as_deref(), Some("image/png"));
|
||||
let p = b.logo_path().unwrap();
|
||||
let name = b
|
||||
.set_logo(LogoSlot::Dark, "image/png", "png", b"\x89PNG\r\n\x1a\nfake")
|
||||
.unwrap();
|
||||
assert_eq!(name, "logo-dark.png");
|
||||
assert!(b.has_logo(LogoSlot::Dark));
|
||||
assert_eq!(b.slot_mime(LogoSlot::Dark).as_deref(), Some("image/png"));
|
||||
let (p, _) = b.web_logo(false).unwrap();
|
||||
assert!(p.is_file());
|
||||
|
||||
// Re-open and confirm the override survives a restart.
|
||||
drop(b);
|
||||
let b2 = BrandingStore::load_or_default(dir.path());
|
||||
assert!(b2.has_logo());
|
||||
assert_eq!(b2.logo_mime().as_deref(), Some("image/png"));
|
||||
assert!(b2.has_logo(LogoSlot::Dark));
|
||||
assert_eq!(b2.slot_mime(LogoSlot::Dark).as_deref(), Some("image/png"));
|
||||
|
||||
// Clear; the file goes away and has_logo flips off.
|
||||
b2.clear_logo().unwrap();
|
||||
assert!(!b2.has_logo());
|
||||
b2.clear_logo(LogoSlot::Dark).unwrap();
|
||||
assert!(!b2.has_logo(LogoSlot::Dark));
|
||||
assert!(!p.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacing_logo_removes_old_extension_sibling() {
|
||||
// PNG then SVG; only the SVG should remain on disk.
|
||||
fn web_logo_falls_back_across_themes() {
|
||||
let dir = tempdir().unwrap();
|
||||
let b = BrandingStore::load_or_default(dir.path());
|
||||
b.set_logo("image/png", "png", b"\x89PNG\r\n\x1a\nfake").unwrap();
|
||||
b.set_logo("image/svg+xml", "svg", br#"<svg xmlns="http://www.w3.org/2000/svg"/>"#).unwrap();
|
||||
// Only dark uploaded — light theme falls back to it.
|
||||
b.set_logo(LogoSlot::Dark, "image/png", "png", b"dark")
|
||||
.unwrap();
|
||||
let (p_light, _) = b.web_logo(true).expect("light falls back to dark");
|
||||
assert!(p_light.ends_with("logo-dark.png"));
|
||||
// Upload a distinct light — now light theme uses its own.
|
||||
b.set_logo(LogoSlot::Light, "image/png", "png", b"light")
|
||||
.unwrap();
|
||||
let (p_light2, _) = b.web_logo(true).unwrap();
|
||||
assert!(p_light2.ends_with("logo-light.png"));
|
||||
// Client is independent and still unset.
|
||||
assert!(b.client_logo().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replacing_slot_removes_old_extension_sibling() {
|
||||
let dir = tempdir().unwrap();
|
||||
let b = BrandingStore::load_or_default(dir.path());
|
||||
b.set_logo(
|
||||
LogoSlot::Client,
|
||||
"image/png",
|
||||
"png",
|
||||
b"\x89PNG\r\n\x1a\nfake",
|
||||
)
|
||||
.unwrap();
|
||||
b.set_logo(
|
||||
LogoSlot::Client,
|
||||
"image/svg+xml",
|
||||
"svg",
|
||||
br#"<svg xmlns="http://www.w3.org/2000/svg"/>"#,
|
||||
)
|
||||
.unwrap();
|
||||
let entries: Vec<_> = std::fs::read_dir(dir.path().join("branding"))
|
||||
.unwrap()
|
||||
.filter_map(|e| e.ok().map(|e| e.file_name().to_string_lossy().into_owned()))
|
||||
.collect();
|
||||
assert!(entries.iter().any(|n| n == "logo.svg"), "got {entries:?}");
|
||||
assert!(!entries.iter().any(|n| n == "logo.png"), "stale PNG left over: {entries:?}");
|
||||
assert!(
|
||||
entries.iter().any(|n| n == "logo-client.svg"),
|
||||
"got {entries:?}"
|
||||
);
|
||||
assert!(
|
||||
!entries.iter().any(|n| n == "logo-client.png"),
|
||||
"stale PNG left over: {entries:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -315,54 +567,92 @@ mod tests {
|
||||
let dir = tempdir().unwrap();
|
||||
let b = BrandingStore::load_or_default(dir.path());
|
||||
assert_eq!(b.logo_rev(), 0);
|
||||
b.set_logo("image/png", "png", b"\x89PNG\r\n\x1a\nfake").unwrap();
|
||||
b.set_logo(LogoSlot::Light, "image/png", "png", b"a")
|
||||
.unwrap();
|
||||
assert_eq!(b.logo_rev(), 1);
|
||||
b.set_logo("image/png", "png", b"\x89PNG\r\n\x1a\nfake2").unwrap();
|
||||
b.set_logo(LogoSlot::Dark, "image/png", "png", b"b")
|
||||
.unwrap();
|
||||
assert_eq!(b.logo_rev(), 2);
|
||||
b.clear_logo().unwrap();
|
||||
b.clear_logo(LogoSlot::Light).unwrap();
|
||||
assert_eq!(b.logo_rev(), 3);
|
||||
// Survives a restart.
|
||||
drop(b);
|
||||
let b2 = BrandingStore::load_or_default(dir.path());
|
||||
assert_eq!(b2.logo_rev(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_single_logo_migrates_to_dark_and_client() {
|
||||
// A pre-v0.5.2 branding.json + logo.png migrates on load.
|
||||
let dir = tempdir().unwrap();
|
||||
let brand_dir = dir.path().join("branding");
|
||||
std::fs::create_dir_all(&brand_dir).unwrap();
|
||||
std::fs::write(brand_dir.join("logo.png"), b"\x89PNG\r\n\x1a\nlegacy").unwrap();
|
||||
// Hand-write the old shape (logo_filename/logo_mime, no slots).
|
||||
std::fs::write(
|
||||
brand_dir.join("branding.json"),
|
||||
br#"{"logo_filename":"logo.png","logo_mime":"image/png","rev":4}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let b = BrandingStore::load_or_default(dir.path());
|
||||
assert!(b.has_logo(LogoSlot::Dark), "dark seeded from legacy");
|
||||
assert!(b.has_logo(LogoSlot::Client), "client seeded from legacy");
|
||||
assert!(!b.has_logo(LogoSlot::Light), "light stays empty");
|
||||
// The old logo.png is gone; per-slot files exist.
|
||||
assert!(!brand_dir.join("logo.png").exists());
|
||||
assert!(brand_dir.join("logo-dark.png").is_file());
|
||||
assert!(brand_dir.join("logo-client.png").is_file());
|
||||
// rev carried over from the legacy file and advanced as the two
|
||||
// slots were seeded (each write bumps it), so it never regresses.
|
||||
let migrated_rev = b.logo_rev();
|
||||
assert!(
|
||||
migrated_rev >= 4,
|
||||
"rev should not regress below legacy: {migrated_rev}"
|
||||
);
|
||||
// And the migration is sticky across a restart (no re-migrate, no
|
||||
// further rev churn).
|
||||
drop(b);
|
||||
let b2 = BrandingStore::load_or_default(dir.path());
|
||||
assert!(b2.has_logo(LogoSlot::Dark));
|
||||
assert!(b2.has_logo(LogoSlot::Client));
|
||||
assert!(!b2.has_logo(LogoSlot::Light));
|
||||
assert_eq!(b2.logo_rev(), migrated_rev, "restart must not re-migrate");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_ext_strips_separators_and_path_chars() {
|
||||
assert_eq!(sanitize_ext("svg"), "svg");
|
||||
// Path separators and non-alphanumerics filter out, leaving just
|
||||
// letters. The remaining "etcpasswd" exceeds the 5-char cap so
|
||||
// it collapses to `bin` rather than producing `etcpa`.
|
||||
assert_eq!(sanitize_ext("../etc/passwd"), "bin");
|
||||
// Short alphanumeric strip-through stays itself.
|
||||
assert_eq!(sanitize_ext("../svg"), "svg");
|
||||
assert_eq!(sanitize_ext(""), "bin");
|
||||
assert_eq!(sanitize_ext("PNG"), "png");
|
||||
// Anything past five chars is suspicious — collapse to `bin`.
|
||||
assert_eq!(sanitize_ext("svgvvvv"), "bin");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_file_referenced_by_json_resolves_to_empty() {
|
||||
// If the operator nukes the file out from under the JSON cache,
|
||||
// we should silently fall back to no-override rather than
|
||||
// hanging on to a bogus path.
|
||||
let dir = tempdir().unwrap();
|
||||
let brand_dir = dir.path().join("branding");
|
||||
std::fs::create_dir_all(&brand_dir).unwrap();
|
||||
// Hand-write a branding.json claiming logo.png exists.
|
||||
let inner = Inner {
|
||||
logo_filename: Some("logo.png".into()),
|
||||
logo_mime: Some("image/png".into()),
|
||||
rev: 0,
|
||||
};
|
||||
// branding.json claims a dark slot whose file doesn't exist.
|
||||
std::fs::write(
|
||||
brand_dir.join("branding.json"),
|
||||
serde_json::to_vec_pretty(&inner).unwrap(),
|
||||
br#"{"dark":{"filename":"logo-dark.png","mime":"image/png"},"rev":1}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let b = BrandingStore::load_or_default(dir.path());
|
||||
assert!(!b.has_logo(), "should fall back when referenced file is missing");
|
||||
assert!(
|
||||
!b.has_logo(LogoSlot::Dark),
|
||||
"should fall back when referenced file is missing"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slot_parse_round_trips() {
|
||||
assert_eq!(LogoSlot::parse("light"), Some(LogoSlot::Light));
|
||||
assert_eq!(LogoSlot::parse("DARK"), Some(LogoSlot::Dark));
|
||||
assert_eq!(LogoSlot::parse(" client "), Some(LogoSlot::Client));
|
||||
assert_eq!(LogoSlot::parse("nope"), None);
|
||||
assert_eq!(LogoSlot::Light.as_str(), "light");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -74,6 +74,11 @@ pub struct Paths {
|
||||
/// Only used when `settings.windows_enabled = true`. Defaults to
|
||||
/// `/var/lib/openpxe/smb` in the container image.
|
||||
pub smb_dir: PathBuf,
|
||||
/// v0.5.2: directory holding uploaded unattended-install answer files
|
||||
/// (Kickstart / Preseed / Autoinstall / Windows answer files). Kept
|
||||
/// separate from `iso_dir` so answer files never appear in the ISO
|
||||
/// listing or the PXE menu. Defaults to `/var/lib/openpxe/unattended`.
|
||||
pub unattended_dir: PathBuf,
|
||||
}
|
||||
|
||||
impl Default for ServerConfig {
|
||||
@@ -109,6 +114,7 @@ impl Default for Paths {
|
||||
ipxe_dir: PathBuf::from("/usr/share/openpxe/ipxe"),
|
||||
wimboot_path: None,
|
||||
smb_dir: PathBuf::from("/var/lib/openpxe/smb"),
|
||||
unattended_dir: PathBuf::from("/var/lib/openpxe/unattended"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,6 +21,8 @@ use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use crate::profile::DeployProfile;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct HostBinding {
|
||||
/// Lowercase, colon-separated MAC (e.g. `aa:bb:cc:dd:ee:ff`). The
|
||||
@@ -35,6 +37,11 @@ pub struct HostBinding {
|
||||
/// `"rack-3 spine"`). Empty if unset.
|
||||
#[serde(default)]
|
||||
pub label: String,
|
||||
/// v0.5.2: optional unattended-install hints (auto hostname / IP /
|
||||
/// answer-file id). Flattened into the binding JSON so pre-v0.5.2
|
||||
/// `hosts.json` files (which lack these keys) still deserialize.
|
||||
#[serde(default, flatten)]
|
||||
pub profile: DeployProfile,
|
||||
#[serde(with = "time::serde::rfc3339")]
|
||||
pub created_at: OffsetDateTime,
|
||||
#[serde(with = "time::serde::rfc3339")]
|
||||
@@ -94,20 +101,31 @@ impl HostBindings {
|
||||
}
|
||||
|
||||
/// Insert or update. Returns the resulting binding (with timestamps).
|
||||
pub fn upsert(&self, mac: &str, target: &str, label: &str) -> HostBinding {
|
||||
/// The `profile` carries optional unattended-install hints (v0.5.2);
|
||||
/// pass `DeployProfile::default()` for a plain pin.
|
||||
pub fn upsert(
|
||||
&self,
|
||||
mac: &str,
|
||||
target: &str,
|
||||
label: &str,
|
||||
profile: DeployProfile,
|
||||
) -> HostBinding {
|
||||
let key = normalize_mac(mac);
|
||||
let now = OffsetDateTime::now_utc();
|
||||
let profile = profile.normalized();
|
||||
let binding = {
|
||||
let mut g = self.inner.write();
|
||||
let entry = g.by_mac.entry(key.clone()).or_insert_with(|| HostBinding {
|
||||
mac: key.clone(),
|
||||
target: target.to_string(),
|
||||
label: label.to_string(),
|
||||
profile: profile.clone(),
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
});
|
||||
entry.target = target.to_string();
|
||||
entry.label = label.to_string();
|
||||
entry.profile = profile.clone();
|
||||
entry.updated_at = now;
|
||||
entry.clone()
|
||||
};
|
||||
@@ -179,6 +197,10 @@ mod tests {
|
||||
use super::*;
|
||||
use tempfile::tempdir;
|
||||
|
||||
fn np() -> DeployProfile {
|
||||
DeployProfile::default()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_handles_case_and_dashes() {
|
||||
assert_eq!(normalize_mac("AA:BB:CC:DD:EE:FF"), "aa:bb:cc:dd:ee:ff");
|
||||
@@ -191,7 +213,12 @@ mod tests {
|
||||
let dir = tempdir().unwrap();
|
||||
let h = HostBindings::load_or_default(dir.path());
|
||||
assert!(h.is_empty());
|
||||
h.upsert("AA:BB:CC:00:00:01", "ubuntu-24-04-linux", "rack-3 spine");
|
||||
h.upsert(
|
||||
"AA:BB:CC:00:00:01",
|
||||
"ubuntu-24-04-linux",
|
||||
"rack-3 spine",
|
||||
np(),
|
||||
);
|
||||
let found = h.lookup("aa-bb-cc-00-00-01").expect("lookup");
|
||||
assert_eq!(found.target, "ubuntu-24-04-linux");
|
||||
assert_eq!(found.label, "rack-3 spine");
|
||||
@@ -202,8 +229,8 @@ mod tests {
|
||||
fn upsert_replaces_existing_target() {
|
||||
let dir = tempdir().unwrap();
|
||||
let h = HostBindings::load_or_default(dir.path());
|
||||
h.upsert("aa:bb:cc:00:00:01", "old-target", "label1");
|
||||
h.upsert("aa:bb:cc:00:00:01", "new-target", "label2");
|
||||
h.upsert("aa:bb:cc:00:00:01", "old-target", "label1", np());
|
||||
h.upsert("aa:bb:cc:00:00:01", "new-target", "label2", np());
|
||||
assert_eq!(h.len(), 1);
|
||||
let b = h.lookup("aa:bb:cc:00:00:01").unwrap();
|
||||
assert_eq!(b.target, "new-target");
|
||||
@@ -214,7 +241,7 @@ mod tests {
|
||||
fn remove_works_and_reports_outcome() {
|
||||
let dir = tempdir().unwrap();
|
||||
let h = HostBindings::load_or_default(dir.path());
|
||||
h.upsert("aa:bb:cc:00:00:01", "x", "");
|
||||
h.upsert("aa:bb:cc:00:00:01", "x", "", np());
|
||||
assert!(h.remove("AA:BB:CC:00:00:01"));
|
||||
assert!(!h.remove("aa:bb:cc:00:00:01")); // already gone
|
||||
assert!(h.is_empty());
|
||||
@@ -224,11 +251,44 @@ mod tests {
|
||||
fn round_trip_persists_to_disk() {
|
||||
let dir = tempdir().unwrap();
|
||||
let h = HostBindings::load_or_default(dir.path());
|
||||
h.upsert("aa:bb:cc:00:00:01", "ubuntu-linux", "rack-3");
|
||||
h.upsert("aa:bb:cc:00:00:02", "_local", "tom-laptop");
|
||||
h.upsert("aa:bb:cc:00:00:01", "ubuntu-linux", "rack-3", np());
|
||||
h.upsert("aa:bb:cc:00:00:02", "_local", "tom-laptop", np());
|
||||
drop(h);
|
||||
let h2 = HostBindings::load_or_default(dir.path());
|
||||
assert_eq!(h2.len(), 2);
|
||||
assert_eq!(h2.lookup("aa:bb:cc:00:00:02").unwrap().target, "_local");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_round_trips_to_disk() {
|
||||
let dir = tempdir().unwrap();
|
||||
let h = HostBindings::load_or_default(dir.path());
|
||||
let prof = DeployProfile {
|
||||
auto_hostname: Some("node-7".into()),
|
||||
auto_ip: Some("10.0.0.7".into()),
|
||||
unattended_file: Some("ubuntu-ks".into()),
|
||||
};
|
||||
h.upsert("aa:bb:cc:00:00:09", "ubuntu-linux", "lab", prof);
|
||||
drop(h);
|
||||
let h2 = HostBindings::load_or_default(dir.path());
|
||||
let b = h2.lookup("aa:bb:cc:00:00:09").unwrap();
|
||||
assert_eq!(b.profile.auto_hostname.as_deref(), Some("node-7"));
|
||||
assert_eq!(b.profile.auto_ip.as_deref(), Some("10.0.0.7"));
|
||||
assert_eq!(b.profile.unattended_file.as_deref(), Some("ubuntu-ks"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_hosts_json_without_profile_still_loads() {
|
||||
// A pre-v0.5.2 hosts.json has no profile keys at all.
|
||||
let dir = tempdir().unwrap();
|
||||
std::fs::write(
|
||||
dir.path().join("hosts.json"),
|
||||
br#"[{"mac":"aa:bb:cc:00:00:01","target":"_local","label":"old","created_at":"2024-01-01T00:00:00Z","updated_at":"2024-01-01T00:00:00Z"}]"#,
|
||||
)
|
||||
.unwrap();
|
||||
let h = HostBindings::load_or_default(dir.path());
|
||||
let b = h.lookup("aa:bb:cc:00:00:01").unwrap();
|
||||
assert_eq!(b.target, "_local");
|
||||
assert!(b.profile.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ pub mod host_bindings;
|
||||
pub mod log_bus;
|
||||
pub mod metrics;
|
||||
pub mod notify;
|
||||
pub mod profile;
|
||||
pub mod queue;
|
||||
pub mod saml;
|
||||
pub mod settings;
|
||||
@@ -22,7 +23,7 @@ pub mod wol;
|
||||
pub use arch::{ClientArch, FirmwareClass};
|
||||
pub use auth::{AdminAccount, AdminPublic, AdminStore};
|
||||
pub use boot_log::{BootEvent, BootLog};
|
||||
pub use branding::{ext_for_mime, BrandingStore, ALLOWED_LOGO_MIMES, MAX_LOGO_BYTES};
|
||||
pub use branding::{ext_for_mime, BrandingStore, LogoSlot, ALLOWED_LOGO_MIMES, MAX_LOGO_BYTES};
|
||||
pub use client::{ClientEvent, ClientRegistry, ClientSnapshot};
|
||||
pub use config::{Config, DhcpMode, NetworkConfig, Paths, ServerConfig};
|
||||
pub use error::{Error, Result};
|
||||
@@ -30,6 +31,7 @@ pub use host_bindings::{normalize_mac, HostBinding, HostBindings};
|
||||
pub use log_bus::{LogBus, LogBusLayer, LogLine};
|
||||
pub use metrics::{HttpRoute, Metrics};
|
||||
pub use notify::{NotifyConfig, NotifyKind, NotifyStore};
|
||||
pub use profile::DeployProfile;
|
||||
pub use queue::{DeploymentQueue, QueueEntry};
|
||||
pub use saml::{IdpMetadata, SamlError, SpParams, VerifiedPrincipal, VerifiedResponse};
|
||||
pub use settings::{Settings, SettingsStore, TimeoutAction};
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
//! Per-host deployment profile.
|
||||
//!
|
||||
//! v0.5.2: a small, optional bundle of "what should this machine do when
|
||||
//! it images" attached to either a pinned host binding ([`crate::HostBinding`])
|
||||
//! or a queued device ([`crate::QueueEntry`]). All three fields are
|
||||
//! optional and independent:
|
||||
//!
|
||||
//! * `auto_hostname` — substituted into the served unattended answer file
|
||||
//! (`{{HOSTNAME}}`) so the installer sets the machine name.
|
||||
//! * `auto_ip` — substituted as `{{IP}}`. OpenPXE is a DHCP **proxy** and
|
||||
//! does not hand out leases, so this is applied by the installer as a
|
||||
//! static-network directive inside the answer file, not by DHCP.
|
||||
//! * `unattended_file` — the id of an uploaded file in the unattended
|
||||
//! store (Kickstart / Preseed / Autoinstall / Windows answer file). When
|
||||
//! set, the boot chain injects the appropriate kernel argument so the
|
||||
//! install runs unattended.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Optional deployment hints carried on a host pin or a queue entry.
|
||||
///
|
||||
/// The fields are flattened into `HostBinding` / `QueueEntry` on the wire
|
||||
/// (so existing JSON stays compatible via `#[serde(default)]`); this type
|
||||
/// is the in-code bundle the boot chain consumes.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct DeployProfile {
|
||||
/// Hostname to set on the imaged machine (`{{HOSTNAME}}`). Empty/None
|
||||
/// leaves the installer default.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub auto_hostname: Option<String>,
|
||||
/// Static IPv4/IPv6 the installer should configure (`{{IP}}`). Stored
|
||||
/// as a free-form string — validated lightly at the HTTP layer.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub auto_ip: Option<String>,
|
||||
/// Id of an uploaded file in the unattended store. Empty/None means
|
||||
/// "no unattended install — boot interactively".
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub unattended_file: Option<String>,
|
||||
}
|
||||
|
||||
/// Cap on the stored hostname / IP strings — generous for any real value
|
||||
/// but bounds what an operator can stuff into the JSON.
|
||||
pub const MAX_PROFILE_FIELD_LEN: usize = 255;
|
||||
|
||||
impl DeployProfile {
|
||||
/// True when nothing is set — lets call sites skip work entirely.
|
||||
#[must_use]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.auto_hostname.is_none() && self.auto_ip.is_none() && self.unattended_file.is_none()
|
||||
}
|
||||
|
||||
/// True when an unattended file is selected (drives boot-chain injection).
|
||||
#[must_use]
|
||||
pub fn has_unattended(&self) -> bool {
|
||||
self.unattended_file
|
||||
.as_deref()
|
||||
.is_some_and(|s| !s.trim().is_empty())
|
||||
}
|
||||
|
||||
/// Normalise: trim every field and collapse empty strings to `None`
|
||||
/// so persisted JSON never carries `""` for an unset value.
|
||||
#[must_use]
|
||||
pub fn normalized(mut self) -> Self {
|
||||
fn clean(v: Option<String>) -> Option<String> {
|
||||
v.map(|s| s.trim().to_string())
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(|s| s.chars().take(MAX_PROFILE_FIELD_LEN).collect())
|
||||
}
|
||||
self.auto_hostname = clean(self.auto_hostname);
|
||||
self.auto_ip = clean(self.auto_ip);
|
||||
self.unattended_file = clean(self.unattended_file);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn empty_profile_is_empty() {
|
||||
assert!(DeployProfile::default().is_empty());
|
||||
assert!(!DeployProfile::default().has_unattended());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn normalize_trims_and_nulls_empty() {
|
||||
let p = DeployProfile {
|
||||
auto_hostname: Some(" node-7 ".into()),
|
||||
auto_ip: Some(" ".into()),
|
||||
unattended_file: Some(String::new()),
|
||||
}
|
||||
.normalized();
|
||||
assert_eq!(p.auto_hostname.as_deref(), Some("node-7"));
|
||||
assert_eq!(p.auto_ip, None);
|
||||
assert_eq!(p.unattended_file, None);
|
||||
assert!(!p.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn has_unattended_detects_real_id() {
|
||||
let p = DeployProfile {
|
||||
unattended_file: Some("ubuntu-ks".into()),
|
||||
..Default::default()
|
||||
};
|
||||
assert!(p.has_unattended());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_field_is_capped() {
|
||||
let long = "a".repeat(1000);
|
||||
let p = DeployProfile {
|
||||
auto_hostname: Some(long),
|
||||
..Default::default()
|
||||
}
|
||||
.normalized();
|
||||
assert_eq!(
|
||||
p.auto_hostname.as_deref().map(str::len),
|
||||
Some(MAX_PROFILE_FIELD_LEN)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ use time::OffsetDateTime;
|
||||
use tokio::sync::Notify;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::profile::DeployProfile;
|
||||
use crate::ClientArch;
|
||||
|
||||
/// Per-client queue state visible to the WebUI.
|
||||
@@ -37,6 +38,11 @@ pub struct QueueEntry {
|
||||
#[serde(with = "time::serde::rfc3339")]
|
||||
pub last_poll_at: OffsetDateTime,
|
||||
pub assigned_target: Option<String>,
|
||||
/// v0.5.2: optional per-device deployment profile set via the queue
|
||||
/// "Profile" button (auto hostname / IP / unattended file). Flattened
|
||||
/// so the JSON stays flat alongside the other queue fields.
|
||||
#[serde(default, flatten)]
|
||||
pub profile: DeployProfile,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -49,6 +55,7 @@ struct QueueEntryInner {
|
||||
joined_at: OffsetDateTime,
|
||||
last_poll_at: OffsetDateTime,
|
||||
assigned_target: Option<String>,
|
||||
profile: DeployProfile,
|
||||
/// Broadcast primitive that wakes the long-poll as soon as an
|
||||
/// assignment lands — no polling on our side, no sleep-loops.
|
||||
notify: Arc<Notify>,
|
||||
@@ -65,6 +72,7 @@ impl QueueEntryInner {
|
||||
joined_at: self.joined_at,
|
||||
last_poll_at: self.last_poll_at,
|
||||
assigned_target: self.assigned_target.clone(),
|
||||
profile: self.profile.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -110,6 +118,7 @@ impl DeploymentQueue {
|
||||
joined_at: now,
|
||||
last_poll_at: now,
|
||||
assigned_target: None,
|
||||
profile: DeployProfile::default(),
|
||||
notify: Arc::new(Notify::new()),
|
||||
};
|
||||
let snap = inner.snapshot();
|
||||
@@ -133,6 +142,29 @@ impl DeploymentQueue {
|
||||
Some(g.snapshot())
|
||||
}
|
||||
|
||||
/// Operator sets (or clears) the deployment profile for a queued
|
||||
/// device via the WebUI "Profile" button. Returns the updated
|
||||
/// snapshot, or `None` if the entry has since been released.
|
||||
pub fn set_profile(&self, entry_id: &str, profile: DeployProfile) -> Option<QueueEntry> {
|
||||
let mut guard = self.inner.write();
|
||||
let g = guard.get_mut(entry_id)?;
|
||||
g.profile = profile.normalized();
|
||||
Some(g.snapshot())
|
||||
}
|
||||
|
||||
/// Look up the deployment profile for a queued MAC, if any. Used by
|
||||
/// the boot chain to inject an unattended file / template the
|
||||
/// hostname + IP when an assigned device chains to its target.
|
||||
#[must_use]
|
||||
pub fn profile_for_mac(&self, mac: &str) -> Option<DeployProfile> {
|
||||
let guard = self.inner.read();
|
||||
guard
|
||||
.values()
|
||||
.find(|g| g.mac == mac)
|
||||
.map(|g| g.profile.clone())
|
||||
.filter(|p| !p.is_empty())
|
||||
}
|
||||
|
||||
/// Operator assigns an ISO entry (boot_entry id) to one or more clients.
|
||||
/// Returns the number of queue entries that were updated. Entries not in the
|
||||
/// queue are silently skipped.
|
||||
|
||||
Reference in New Issue
Block a user