Skip to content
Merged
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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

209 changes: 209 additions & 0 deletions crates/berth-api/src/ids.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
//! The ids of what berth keeps: a UUID of version 7 as 32 lowercase hex
//! characters. Wherever an id is taken, it may carry the prefix of its kind,
//! such as `prov_`, which is dropped; replies give it bare.

/// The kinds of things with an id, each with the prefix its ids may carry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
Host,
Provisioner,
Resource,
Registry,
Secret,
Key,
}

impl Kind {
pub const ALL: [Kind; 6] = [
Kind::Host,
Kind::Provisioner,
Kind::Resource,
Kind::Registry,
Kind::Secret,
Kind::Key,
];

/// The prefix an id of this kind may be given with, `_` included.
pub fn prefix(self) -> &'static str {
match self {
Kind::Host => "host_",
Kind::Provisioner => "prov_",
Kind::Resource => "res_",
Kind::Registry => "reg_",
Kind::Secret => "sec_",
Kind::Key => "key_",
}
}

/// What people call one, for messages.
pub fn noun(self) -> &'static str {
match self {
Kind::Host => "host",
Kind::Provisioner => "provisioner",
Kind::Resource => "resource",
Kind::Registry => "registry",
Kind::Secret => "secret",
Kind::Key => "key",
}
}
}

/// How long an id is.
pub const LENGTH: usize = 32;

/// Whether a text is an id in its canonical form.
pub fn is_id(text: &str) -> bool {
text.len() == LENGTH
&& text
.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}

/// An id in its canonical form, from the bare id in either case or the
/// hyphenated form of a UUID.
fn canonical(text: &str) -> Option<String> {
let bare: String = match text.len() {
36 => {
let bytes = text.as_bytes();
if [8, 13, 18, 23].iter().any(|&at| bytes[at] != b'-') {
return None;
}
text.chars().filter(|&ch| ch != '-').collect()
}
_ => text.to_owned(),
};
let bare = bare.to_ascii_lowercase();
is_id(&bare).then_some(bare)
}

/// Whether a name looks like an id, with or without a prefix, so that it
/// cannot be given as one.
pub fn looks_like_id(name: &str) -> bool {
let hex = |text: &str| text.len() == LENGTH && text.bytes().all(|b| b.is_ascii_hexdigit());
hex(name)
|| Kind::ALL.iter().any(|kind| {
name.get(..kind.prefix().len())
.is_some_and(|start| start.eq_ignore_ascii_case(kind.prefix()))
&& hex(&name[kind.prefix().len()..])
})
}

/// What a value given for a thing of `kind` is.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Given {
/// An id with the prefix of `kind`: only that id, never a name.
Prefixed(String),
/// A bare id: that id, if there is a thing with it, else a name.
Bare(String),
/// A name.
Name(String),
}

/// Read a value given for a thing of `kind`. A prefix of another kind is refused.
pub fn read(kind: Kind, given: &str) -> Result<Given, String> {
for other in Kind::ALL {
let Some(rest) = given
.get(..other.prefix().len())
.filter(|start| start.eq_ignore_ascii_case(other.prefix()))
.map(|_| &given[other.prefix().len()..])
else {
continue;
};
let Some(id) = canonical(rest) else {
continue;
};
if other != kind {
return Err(format!(
"{given} is the id of a {}, and a {} was asked for",
other.noun(),
kind.noun()
));
}
return Ok(Given::Prefixed(id));
}
Ok(match canonical(given) {
Some(id) => Given::Bare(id),
None => Given::Name(given.to_owned()),
})
}

/// The id a value gives when it is one, bare or with the prefix of `kind`.
pub fn id_in(kind: Kind, given: &str) -> Option<String> {
match read(kind, given) {
Ok(Given::Prefixed(id) | Given::Bare(id)) => Some(id),
_ => None,
}
}

/// A new id from the time in milliseconds and 10 random bytes: a UUID of
/// version 7, which sorts in the order the ids were made.
pub fn from_parts(millis: u64, random: [u8; 10]) -> String {
let mut bytes = [0u8; 16];
bytes[..6].copy_from_slice(&millis.to_be_bytes()[2..]);
bytes[6..].copy_from_slice(&random);
bytes[6] = 0x70 | (bytes[6] & 0x0f);
bytes[8] = 0x80 | (bytes[8] & 0x3f);
bytes.iter().map(|byte| format!("{byte:02x}")).collect()
}

#[cfg(test)]
mod tests {
use super::*;

const ID: &str = "01972c4e8f3a7b219d4e5a6b7c8d9e0f";

#[test]
fn an_id_is_32_lowercase_hex_characters_of_a_version_7_uuid() {
let id = from_parts(0x0197_2c4e_8f3a, [0xff; 10]);
assert!(is_id(&id), "{id}");
assert_eq!(&id[..12], "01972c4e8f3a");
assert_eq!(&id[12..13], "7");
assert!("89ab".contains(&id[16..17]));
assert!(!is_id(&ID.to_uppercase()) && !is_id("r-k3x9p2qa"));
}

#[test]
fn a_value_is_an_id_with_its_prefix_a_bare_id_or_a_name() {
let prefixed = format!("prov_{ID}");
assert_eq!(
read(Kind::Provisioner, &prefixed),
Ok(Given::Prefixed(ID.into()))
);
assert_eq!(
read(Kind::Provisioner, &format!("PROV_{}", ID.to_uppercase())),
Ok(Given::Prefixed(ID.into()))
);
assert_eq!(read(Kind::Host, ID), Ok(Given::Bare(ID.into())));
assert_eq!(
read(Kind::Host, "01972c4e-8f3a-7b21-9d4e-5a6b7c8d9e0f"),
Ok(Given::Bare(ID.into()))
);
assert_eq!(read(Kind::Host, "studio"), Ok(Given::Name("studio".into())));
// A prefix of another kind is refused.
let error = read(Kind::Host, &prefixed).unwrap_err();
assert!(error.contains("provisioner"), "{error}");
// A prefix without an id after it is a name.
assert_eq!(
read(Kind::Host, "host_studio"),
Ok(Given::Name("host_studio".into()))
);
assert_eq!(id_in(Kind::Secret, &format!("sec_{ID}")), Some(ID.into()));
assert_eq!(id_in(Kind::Secret, "github_token"), None);
}

#[test]
fn names_in_the_shape_of_an_id_are_told_apart() {
assert!(looks_like_id(ID));
assert!(looks_like_id(&ID.to_uppercase()));
assert!(looks_like_id(&format!("prov_{ID}")));
assert!(looks_like_id(&format!("Host_{ID}")));
for name in [
"studio",
"incus-vm",
&ID[1..],
"abcdefabcdefabcdefabcdefabcdefag",
] {
assert!(!looks_like_id(name), "{name}");
}
}
}
1 change: 1 addition & 0 deletions crates/berth-api/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
pub mod client;
pub mod compat;
pub mod escape;
pub mod ids;
pub mod ops;
#[cfg(feature = "client")]
pub mod portal;
Expand Down
6 changes: 6 additions & 0 deletions crates/berth-api/src/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -289,13 +289,19 @@ pub static SERVE: &[Op] = &[
admin(call("secrets.list", "GET", "/v1/secrets")),
admin(call("secrets.set", "PUT", "/v1/secrets/{name}")),
admin(call("secrets.remove", "DELETE", "/v1/secrets/{name}")),
admin(call("secrets.rename", "POST", "/v1/secrets/{name}/rename")),
admin(call("keys.list", "GET", "/v1/keys")),
admin(bytes(call("keys.add", "PUT", "/v1/keys/{name}"))),
admin(call("keys.remove", "DELETE", "/v1/keys/{name}")),
admin(call("keys.rotate", "POST", "/v1/keys/{name}/rotate")),
admin(call("registries.list", "GET", "/v1/registries")),
admin(call("registries.save", "PUT", "/v1/registries/{name}")),
admin(call("registries.remove", "DELETE", "/v1/registries/{name}")),
admin(call(
"registries.rename",
"POST",
"/v1/registries/{name}/rename",
)),
admin(call(
"registries.check",
"POST",
Expand Down
57 changes: 52 additions & 5 deletions crates/berth-api/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -820,16 +820,24 @@ pub struct Acted {
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct JobInfo {
pub id: String,
/// What it was done to: `host:NAME`, `provisioner:NAME`,
/// What it was done to, by id: `host:ID`, `provisioner:ID`,
/// `resource:ID` or `installation`. Empty for a job from before 0.5.
#[serde(default)]
pub subject: String,
/// What it was done to, by name as it is called now: `host:NAME`,
/// `provisioner:NAME`, `resource:ID` or `installation`; by id for one
/// that is gone.
#[serde(default)]
pub subject_name: String,
/// The action it runs, such as `apply`, `rollout` or `provision`.
#[serde(default)]
pub action: String,
/// The hosts it is about, for a reader: a name, or several with commas.
#[serde(default)]
pub host: String,
/// The ids of those hosts, as `host` lists them; a host in a file by its path.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub host_id: String,
pub started: String,
pub ended: Option<String>,
pub exit_code: Option<i32>,
Expand Down Expand Up @@ -1246,14 +1254,32 @@ pub struct PluginUpdateSpec {
pub id: Option<String>,
}

/// A thing berth keeps, by its id and its name.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
pub struct Named {
/// Its id, which stays when it is renamed.
pub id: String,
pub name: String,
}

/// A new name for a thing.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
pub struct Rename {
pub name: String,
}

// ── Provisioners ────────────────────────────────────────────────────────────

/// Something a plugin creates machines with, for a saved host's profile.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct ProvisionerInfo {
/// Its id, which stays when it is renamed. In the list of types, the
/// type itself.
pub id: String,
/// The name it is registered under, such as `ovh-incus`. In the list of
/// types, the type itself.
pub id: String,
#[serde(default)]
pub name: String,
/// The plugin's provisioner it is, as `PLUGIN/ID`, such as `incus/vm`.
#[serde(rename = "type", default)]
pub kind: String,
Expand Down Expand Up @@ -1284,9 +1310,12 @@ pub struct ProvisionerInfo {
/// The values of its own arguments that are kept, by name.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub settings: BTreeMap<String, String>,
/// The node it lives on, when a feature of that host offered it.
/// The node it lives on, when a feature of that host offered it, by name.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub node: String,
/// The id of that node.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub node_id: String,
/// What it can make: `machine`, and kinds its plugin names.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub kinds: Vec<ProvisionerKind>,
Expand All @@ -1303,6 +1332,17 @@ pub struct ProvisionerInfo {
pub problem: String,
}

impl ProvisionerInfo {
/// What it is called: its name, or for a server from before ids, which
/// said none, the name it gave as its id.
pub fn named(&self) -> &str {
match self.name.is_empty() {
true => &self.id,
false => &self.name,
}
}
}

/// A provisioner to register, or the type and settings of one that is.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct SavedProvisioner {
Expand Down Expand Up @@ -1616,6 +1656,9 @@ pub struct Resource {
pub id: String,
/// The name of the provisioner that made it.
pub provisioner: String,
/// The id of that provisioner, when it is registered.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub provisioner_id: String,
/// `machine`, or a kind the plugin declares.
pub kind: String,
/// Unique per provisioner and kind.
Expand All @@ -1627,9 +1670,13 @@ pub struct Resource {
/// The provisioner's id of it; empty until `create` said it.
#[serde(default)]
pub external_id: String,
/// The host a machine belongs to, if any.
/// The host a machine belongs to, if any, by name; a profile in a file
/// by its path.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub host: Option<String>,
/// The id of that host, when it is a saved host.
#[serde(default, skip_serializing_if = "String::is_empty")]
pub host_id: String,
#[serde(default, skip_serializing_if = "String::is_empty")]
pub address: String,
/// Where it can be reached, as its provisioner last said: when it was
Expand Down Expand Up @@ -1662,7 +1709,7 @@ pub struct Resource {
/// What to create a resource with.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct NewResource {
/// The provisioner's name.
/// The provisioner, by name or id.
pub provisioner: String,
/// `machine` when empty.
#[serde(default)]
Expand Down
5 changes: 3 additions & 2 deletions crates/berth-core/src/apply.rs
Original file line number Diff line number Diff line change
Expand Up @@ -616,7 +616,7 @@ mod tests {
paths.set("source", source.to_str().unwrap()).unwrap();
let host = Host {
name: "box".into(),
place: Place::own("box").unwrap(),
place: Place::own(&paths, "box").unwrap(),
config: json!({"target": "cloud", "access": {"address": "box", "user": "ops", "sudo": "password"}}),
};
let prepared = prepare(&paths, &host, Some("hunter2")).unwrap();
Expand Down Expand Up @@ -677,7 +677,7 @@ mod tests {
};
paths.prepare().unwrap();
paths.give_own_key();
let place = Place::own("studio").unwrap();
let place = Place::own(&paths, "studio").unwrap();
let host = |config: Value| {
place.save(&paths, &config).unwrap();
Host {
Expand All @@ -687,6 +687,7 @@ mod tests {
}
};
let saved = || place.load(&paths).unwrap().unwrap();
place.save(&paths, &json!({})).unwrap();
let secrets = crate::registry::Store::own(crate::store::shared(&paths).unwrap());
secrets.set_secret("sudo/studio", Some("hunter2")).unwrap();
secrets.set_secret("ssh/studio", Some("hunter2")).unwrap();
Expand Down
Loading
Loading