use crate::{auth, configure, enrollment, node, node_home, owner, pairing, setup, update};
use anyhow::{Context, Result};
use gent_daemon::config;
use gent_protocol::{
ConfigurationEdit, Effect, OwnerOp, Permission, Rule, Selector, administration::RuleDecision,
};
use serde::Deserialize;
use serde_json::{Value, json};
use std::path::Path;
use uuid::Uuid;
#[derive(Deserialize)]
#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
pub(super) enum Request {
Manage { action: Action },
}
#[derive(Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub(super) enum Action {
CheckUpdate,
SignIn,
SignOut,
Create {
name: String,
},
Join {
code: String,
},
FinishSetup,
Invite {
name: String,
role: Role,
},
RenameNode {
id: Uuid,
name: String,
},
RemoveNode {
id: Uuid,
},
RenameChat {
id: Uuid,
name: String,
expected_generation: u64,
},
Unregister {
id: Uuid,
},
NodeRole {
id: Uuid,
role: Role,
},
SetRule {
actor: String,
peer: String,
permission: Permission,
decision: RuleDecision,
},
}
#[derive(Deserialize)]
#[serde(rename_all = "snake_case")]
pub(super) enum Role {
Admin,
Member,
}
impl Action {
fn page(&self) -> &'static str {
match self {
Self::CheckUpdate => "about",
Self::Invite { .. }
| Self::RenameNode { .. }
| Self::RemoveNode { .. }
| Self::NodeRole { .. } => "nodes",
Self::RenameChat { .. } | Self::Unregister { .. } => "chats",
Self::SetRule { .. } => "permissions",
_ => "cluster",
}
}
pub(super) fn error(&self, error: &str) -> Value {
json!({"page":self.page(),"operation":true,"error":error})
}
pub(super) async fn respond(self, home: &Path) -> Value {
let page = self.page();
match self.run(home).await {
Ok(mut value) => {
value["page"] = json!(page);
value["operation"] = json!(true);
value
}
Err(error) => json!({"page":page,"operation":true,"error":format!("{error:#}")}),
}
}
async fn run(self, home: &Path) -> Result<Value> {
let notice = match self {
Self::CheckUpdate => {
let result = update::desktop_check(home).await?;
let channel = result["channel"]
.as_str()
.context("missing release channel")?;
let commit = result["blessed_commit"]
.as_str()
.context("missing release revision")?;
if result["update_available"] == true {
format!(
"Update available · {channel} {}",
&commit[..commit.len().min(12)]
)
} else {
format!("You’re running the current {channel} release.")
}
}
Self::SignIn => {
auth::desktop_login(home).await?;
"Signed in to Gent.".into()
}
Self::SignOut => {
let result = auth::execute(home, auth::Command::Logout).await?;
if result["status"] == "signed_out" {
"Signed out.".into()
} else {
"Sign-out pending. Retry when the service is reachable.".into()
}
}
Self::Create { name } => {
node_home::provision::install(
home,
None,
setup::Options::desktop(Some(name)),
false,
)
.await?;
"Cluster created and daemon installed.".into()
}
Self::Join { code } => {
let mut args = pairing::JoinArgs::code(
(!code.trim().is_empty()).then(|| code.trim().to_owned()),
);
args.no_input = true;
enrollment::join(home, args).await?;
"Joined the cluster and installed the daemon.".into()
}
Self::FinishSetup => {
node_home::provision::install(home, None, setup::Options::desktop(None), false)
.await?;
"Daemon setup complete.".into()
}
Self::Invite { name, role } => {
let directory = tempfile::tempdir()?;
let file = directory.path().join("invite");
let options = enrollment::AddArgs::invitation(
name.clone(),
matches!(role, Role::Admin),
file.clone(),
);
enrollment::add(home, options).await?;
return Ok(json!({"notice":format!("Invitation for {name}"),
"private_code":std::fs::read_to_string(&file)?}));
}
Self::RenameNode { id, name } => {
let result =
node::rename(home, &Uuid::new_v4().to_string(), &id.to_string(), &name).await?;
return change_result(&result);
}
Self::RemoveNode { id } => {
let result = node::remove(home, id.to_string()).await?;
if result["state"] == "queued" {
"Removal queued for cluster approval.".into()
} else if result["service_status"] == "pending" {
"Membership removed. Service revocation is pending.".into()
} else {
"Node removed from the cluster.".into()
}
}
Self::NodeRole { id, role } => {
let result = configure(
home,
&Uuid::new_v4().to_string(),
ConfigurationEdit::DelegateNode {
node_id: id.to_string(),
allow: matches!(role, Role::Admin),
},
)
.await?;
return change_result(&result);
}
Self::RenameChat {
id,
name,
expected_generation,
} => {
let result =
crate::agent::rename(home, id.to_string(), name, Some(expected_generation))
.await?;
return rename_result(&result);
}
Self::Unregister { id } => {
let result = owner(
home,
OwnerOp::Revoke {
agent_id: id.to_string(),
},
)
.await?;
if result["revoked"] == true {
"Chat unregistered.".into()
} else if result["state"] == "queued" {
return Ok(
json!({"notice":"Unregistration queued for the hosting node. Refresh to check its registration.", "queued_unregister":id}),
);
} else {
anyhow::bail!(
"Missing unregistration status. Refresh Chats to check its registration."
);
}
}
Self::SetRule {
actor,
peer,
permission,
decision,
} => {
let effect = match decision {
RuleDecision::Allow => Some(Effect::Allow),
RuleDecision::Deny => Some(Effect::Deny),
RuleDecision::Inherit => None,
};
let id = Uuid::new_v4().to_string();
let result = configure(
home,
&id,
ConfigurationEdit::SetPermissionRule {
actor: crate::selector(actor)?,
peer: crate::selector(peer)?,
permission,
effect,
},
)
.await?;
return change_result(&result);
}
};
Ok(json!({"notice":notice}))
}
}
fn rename_result(result: &Value) -> Result<Value> {
match result["state"].as_str() {
Some("applied") => Ok(json!({"notice":"Chat renamed."})),
Some("queued") => {
Ok(json!({"notice":"Rename queued for the hosting node.", "queued_rename":true}))
}
Some("unconfirmed") => anyhow::bail!(
"Rename unconfirmed: {}",
result["reason"]
.as_str()
.unwrap_or("No decision received from the hosting node.")
),
Some("rejected") => anyhow::bail!(
"Rename rejected: {}",
result["reason"]
.as_str()
.unwrap_or("Hosting node declined the change.")
),
_ => anyhow::bail!("Missing chat rename status. Refresh Chats to check its name."),
}
}
fn change_result(result: &Value) -> Result<Value> {
let state = result["state"]
.as_str()
.context("missing configuration request status")?;
anyhow::ensure!(
state != "rejected",
"Change rejected: {}",
result["reason"].as_str().unwrap_or("unknown reason")
);
Ok(json!({"notice":format!("Configuration change: {state}")}))
}
pub(super) fn cluster(home: &Path) -> Result<Value> {
let account = auth::desktop_account(home)?;
let state = account["state"].as_str().unwrap_or("Unknown");
let mut actions = Vec::new();
if state != "Signed in" && state != "Sign-out pending" {
actions.push(json!({"kind":"sign_in","title":"Sign in with GitHub"}));
}
if state != "Signed out" {
actions.push(json!({"kind":"sign_out","title":"Sign out","confirm":"Sign out of the Gent account on this machine?"}));
}
let title = if config::path(home).try_exists()? {
actions.push(json!({"kind":"finish_setup","title":"Install or repair daemon…","confirm":"Install and start the user service for this node?"}));
"Account"
} else {
actions.push(json!({"kind":"create","title":"Create cluster…","submit":"Create cluster",
"fields":[{"key":"name","title":"Cluster name"}],"hint":"Create a cluster with your Gent account and start this node’s daemon."}));
actions.push(json!({"kind":"join","title":"Join with invitation…","submit":"Join cluster",
"fields":[{"key":"code","title":"Invitation code","secret":true}],
"hint":"Use the one-time code from Add node on an enrolled machine. Sign in to the same Gent account first."}));
if enrollment::pending(home)?.is_some() {
actions.push(json!({"kind":"join","title":"Resume pending join","values":{"code":""}}));
}
"Set up this node"
};
let login = account["login"]
.as_str()
.map(|s| format!(" · @{s}"))
.unwrap_or_default();
Ok(json!({"title":title,"detail":format!("Gent account: {state}{login}"),"actions":actions}))
}
fn role_field() -> Value {
json!({"key":"role","title":"Node permissions","choices":[["admin","Admin"],["member","Messaging only"]]})
}
pub(super) fn directory_actions(chats: bool) -> Value {
if chats {
return json!([{"kind":"rename_chat","title":"Rename chat…","row":true,"submit":"Rename",
"fields":[{"key":"name","title":"New chat name"}]},
{"kind":"unregister","title":"Unregister chat…","row":true,"destructive":true,"submit":"Unregister chat",
"confirm":"Unregister this conversation? Its Gent binding will lose access. The conversation stays in its host app."}]);
}
json!([{"kind":"invite","title":"Add node…","submit":"Create invitation",
"hint":"Adding a new node requires Gent Pro. Give the one-time code to that node within 15 minutes.",
"fields":[{"key":"name","title":"New node name"},role_field()]},
{"kind":"rename_node","title":"Rename node…","row":true,"submit":"Rename",
"fields":[{"key":"name","title":"New node name"}]},
{"kind":"node_role","title":"Change role…","row":true,"submit":"Change role","fields":[role_field()],
"hint":"Admin nodes can change cluster configuration and permissions."},
{"kind":"remove_node","title":"Remove node…","row":true,"destructive":true,"submit":"Remove node",
"confirm":"Remove this node from membership and revoke its cluster access?"}])
}
fn selector_key(selector: &Selector) -> String {
match selector {
Selector::All => "*".into(),
Selector::SameNode => "same-node".into(),
Selector::Agent(id) => id.clone(),
Selector::Node(id) => format!("node:{id}"),
Selector::Group(name) => format!("group:{name}"),
}
}
pub(super) async fn permissions(home: &Path) -> Result<Value> {
anyhow::ensure!(
config::path(home).try_exists()?,
"Set up this node in Status to view cluster permissions."
);
let snapshot = match owner(home, OwnerOp::PermissionRules).await {
Err(error) if error.to_string() == "invalid request" => {
anyhow::bail!("Update the local daemon to view cluster permissions.")
}
result => result?,
};
let nodes = owner(home, OwnerOp::Nodes).await?;
let chats = owner(home, OwnerOp::Agents).await?;
permission_view(snapshot, nodes, chats)
}
fn permission_view(snapshot: Value, nodes: Value, chats: Value) -> Result<Value> {
let mut choices = vec![
[String::new(), "Choose chats…".to_owned()],
["*".to_owned(), "All chats".to_owned()],
["same-node".into(), "Chats on the same node".into()],
];
let nodes = nodes.as_array().context("invalid node directory")?;
let read_only = nodes.iter().any(|n| {
n["status"] == "local"
&& n.get("is_owner").is_some()
&& n["is_owner"] != true
&& n["can_configure"] == false
});
for node in nodes {
if let (Some(id), Some(name)) = (node["id"].as_str(), node["name"].as_str()) {
let short_id: String = id.chars().take(8).collect();
choices.push([format!("node:{id}"), format!("Node · {name} · {short_id}")]);
}
}
for group in snapshot["groups"]
.as_array()
.into_iter()
.flatten()
.filter_map(Value::as_str)
{
choices.push([format!("group:{group}"), format!("Group · {group}")]);
}
let mut entries: Vec<gent_protocol::directory::Entry> = serde_json::from_value(chats)?;
entries.sort_by_cached_key(|e| e.agent.name.to_lowercase());
for entry in entries {
if !entry.retired && !entry.agent.revoked {
choices.push([
entry.agent.id.clone(),
format!(
"{} · {} · {}",
entry.agent.name,
entry.node_name.unwrap_or(entry.agent.node_id),
entry.agent.id.chars().take(8).collect::<String>()
),
]);
}
}
let rules: Vec<Rule> = serde_json::from_value(snapshot["rules"].clone())?;
let mut known: std::collections::HashSet<_> =
choices.iter().map(|[key, _]| key.clone()).collect();
for selector in rules.iter().flat_map(|r| [&r.actor, &r.peer]) {
let key = selector_key(selector);
if known.insert(key.clone()) {
let label = format!("Existing rule · {key}");
choices.push([key, label]);
}
}
let labels: std::collections::HashMap<_, _> = choices.iter().map(|[k, v]| (k, v)).collect();
let name = |s: &Selector| {
let key = selector_key(s);
labels.get(&key).map_or(key.clone(), |s| (*s).clone())
};
let lines: Vec<_> = rules
.iter()
.map(|r| {
let relationship = match r.permission {
Permission::Send => "Send to",
Permission::Receive => "Receive from",
Permission::Enumerate => "Discover",
};
format!(
"{:?} · {} · {relationship} {}",
r.effect,
name(&r.actor),
name(&r.peer)
)
})
.collect();
let detail = if lines.is_empty() {
"No explicit permission rules.".into()
} else {
lines.join("\n")
};
if read_only {
return Ok(json!({"title":"Cluster permissions","actions":[],
"detail":format!("This node has read-only access to cluster permissions.\n\n{detail}")}));
}
Ok(
json!({"title":"Cluster permissions","detail":detail,"actions":[{"kind":"set_rule","title":"Edit permission…",
"submit":"Apply rule","hint":"This replaces the selected rule across the cluster. Inherit removes that override. Any other matching deny still applies.",
"fields":[{"key":"actor","title":"Acting chats","choices":choices},{"key":"peer","title":"Peer chats","choices":choices},
{"key":"permission","title":"Permission","choices":[["send","Send to peer"],["receive","Receive from peer"],["enumerate","Discover peer"]]},
{"key":"decision","title":"Decision","choices":[["","Choose a decision…"],["deny","Deny"],["allow","Allow"],["inherit","Inherit"]]}]}]}),
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_receive_rule_names_its_peer_and_remains_editable_after_the_chat_leaves() {
let former_chat = Uuid::new_v4().to_string();
let snapshot = json!({"groups": [], "rules": [Rule {
actor: Selector::All,
peer: Selector::Agent(former_chat.clone()),
permission: Permission::Receive,
effect: Effect::Deny,
}]});
let page = permission_view(snapshot, json!([]), json!([])).unwrap();
let label = format!("Existing rule · {former_chat}");
assert_eq!(
page["detail"],
format!("Deny · All chats · Receive from {label}")
);
let fields = page["actions"][0]["fields"].as_array().unwrap();
for field in fields {
if field["key"] != "permission" {
assert_eq!(field["choices"][0][0], "");
}
if field["key"] == "peer" {
assert!(
field["choices"]
.as_array()
.unwrap()
.contains(&json!([former_chat, label]))
);
}
}
}
#[test]
fn a_messaging_only_node_can_read_the_rules() {
let nodes = json!([{"status":"local","is_owner":null,"can_configure":false}]);
let page = permission_view(json!({"rules":[]}), nodes, json!([])).unwrap();
assert_eq!(page["actions"], json!([]));
assert!(
page["detail"]
.as_str()
.unwrap()
.contains("No explicit permission rules.")
);
}
}