use anyhow::{Context, Result, ensure};
use clap::Subcommand;
use gent_daemon::{config, request, store::grant_verifier};
use gent_protocol::{
OwnerOp, Request,
dashboard::{GrantAdmin, GrantOp, MAX_HTML_BYTES, valid_grant_key},
};
use rustix::fs::{Mode, OFlags, open};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::{
fs::{self, File},
io::{Read, Write},
os::unix::fs::MetadataExt,
path::{Path, PathBuf},
};
use uuid::Uuid;
#[derive(Subcommand)]
pub(crate) enum Command {
Grant {
board: Uuid,
#[arg(long)]
expected_revision: u64,
#[arg(long)]
out: PathBuf,
},
Get {
board: Uuid,
#[arg(long)]
grant: PathBuf,
},
Update {
board: Uuid,
#[arg(long)]
expected_revision: u64,
#[arg(long)]
grant: PathBuf,
#[arg(long)]
html_file: PathBuf,
},
Revoke {
board: Uuid,
#[arg(long)]
expected_revision: u64,
},
}
#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct GrantFile {
version: u8,
cluster: String,
board: Uuid,
secret: String,
}
fn read_file(path: &Path, cluster: &str, board: Uuid) -> Result<GrantFile> {
let file = File::from(open(
path,
OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
Mode::empty(),
)?);
let meta = file.metadata()?;
ensure!(
meta.is_file()
&& meta.nlink() == 1
&& meta.mode() & 0o077 == 0
&& meta.uid() == rustix::process::geteuid().as_raw(),
"grant must be a private file owned by this user"
);
let mut bytes = Vec::new();
file.take(1025).read_to_end(&mut bytes)?;
ensure!(bytes.len() <= 1024, "invalid grant file");
let grant: GrantFile =
serde_json::from_slice(&bytes).map_err(|_| anyhow::anyhow!("invalid grant file"))?;
ensure!(
grant.version == 1
&& grant.board == board
&& grant.cluster == cluster
&& valid_grant_key(&grant.secret),
"grant is invalid for this board or cluster"
);
Ok(grant)
}
fn prepare(path: &Path, cluster: &str, board: Uuid) -> Result<GrantFile> {
if path.try_exists()? {
return read_file(path, cluster, board);
}
let parent = path
.parent()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or(Path::new("."));
match fs::symlink_metadata(parent) {
Ok(meta) => ensure!(
meta.is_dir()
&& meta.uid() == rustix::process::geteuid().as_raw()
&& meta.mode() & 0o022 == 0,
"grant directory must be owned by this user and writable only by its owner"
),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => config::private_dir(parent)?,
Err(e) => return Err(e.into()),
}
let mut bytes = [0u8; 32];
getrandom::fill(&mut bytes).context("secure randomness unavailable")?;
let secret = bytes.iter().map(|byte| format!("{byte:02x}")).collect();
let grant = GrantFile {
version: 1,
cluster: cluster.into(),
board,
secret,
};
let mut tmp = tempfile::NamedTempFile::new_in(parent)?;
tmp.write_all(&serde_json::to_vec(&grant)?)?;
tmp.as_file().sync_all()?;
match tmp.persist_noclobber(path) {
Ok(_) => {
File::open(parent)?.sync_all()?;
Ok(grant)
}
Err(e) if e.error.kind() == std::io::ErrorKind::AlreadyExists => {
read_file(path, cluster, board)
}
Err(e) => Err(e.error.into()),
}
}
pub(crate) async fn run(home: &Path, command: Command) -> Result<Value> {
let cluster = config::load(home)?.cluster.id;
let (board, path, action) = match command {
Command::Grant {
board,
expected_revision,
out,
} => {
let grant = prepare(&out, &cluster, board)?;
let verifier = grant_verifier(&cluster, board, &grant.secret)?;
return crate::owner(
home,
OwnerOp::DashboardGrant {
agent: board,
action: GrantAdmin::Issue {
expected_revision,
verifier,
},
},
)
.await;
}
Command::Revoke {
board,
expected_revision,
} => {
return crate::owner(
home,
OwnerOp::DashboardGrant {
agent: board,
action: GrantAdmin::Revoke { expected_revision },
},
)
.await;
}
Command::Get { board, grant } => (board, grant, GrantOp::Get),
Command::Update {
board,
expected_revision,
grant,
html_file,
} => {
let mut html = String::new();
fs::File::open(html_file)?
.take(MAX_HTML_BYTES as u64 + 1)
.read_to_string(&mut html)?;
ensure!(
(1..=MAX_HTML_BYTES).contains(&html.len()),
"publish 1–65536 UTF-8 bytes"
);
(
board,
grant,
GrantOp::Update {
expected_revision,
html,
},
)
}
};
let secret = read_file(&path, &cluster, board)?.secret;
request(
home,
Request::DashboardDelegate {
agent: board,
secret,
action,
},
)
.await
}