feat(terra): pass-broker for Telegram-approved Proton Pass access
A Rust daemon running as its own system user holds terra's only pass-cli session, an agent PAT scoped to the HomeLab vaults. `pass-broker get` asks it for an item; per-item rules decide auto/ask/deny, and "ask" sends a Telegram prompt that only darman's account can approve (10-min grant for darman@*/root@*). Requests whose client is gone are dropped or withdrawn, and the client gives up after 30s without an answer. scripts/deploy uses the broker exclusively when its socket exists. Covered by checks.pass-broker (fake pass-cli + Telegram). Secrets added for all hosts; only terra runs the broker so far. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,16 @@
|
||||
{ lib, rustPlatform }:
|
||||
|
||||
# Wiring (user, socket, policy, secrets) lives in services/identity/pass-broker.nix.
|
||||
rustPlatform.buildRustPackage {
|
||||
pname = "pass-broker";
|
||||
version = "0.1.0";
|
||||
|
||||
src = ./pass-broker;
|
||||
cargoLock.lockFile = ./pass-broker/Cargo.lock;
|
||||
|
||||
meta = {
|
||||
description = "Telegram-approved access to a Proton Pass agent session";
|
||||
mainProgram = "pass-broker";
|
||||
platforms = lib.platforms.linux;
|
||||
};
|
||||
}
|
||||
Generated
+1290
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "pass-broker"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1"
|
||||
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "sync", "time", "process", "io-util"] }
|
||||
|
||||
[profile.release]
|
||||
opt-level = 2
|
||||
@@ -0,0 +1,88 @@
|
||||
use crate::proto::{Reply, Request, DEFAULT_SOCKET};
|
||||
use anyhow::Result;
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::net::UnixStream;
|
||||
|
||||
const FIRST_REPLY: Duration = Duration::from_secs(30);
|
||||
|
||||
/// Prints the value on stdout. Exit 1 = refused/failed, 2 = usage or no broker.
|
||||
pub async fn get(args: &[String]) -> Result<()> {
|
||||
let mut req = Request {
|
||||
vault: None,
|
||||
item: String::new(),
|
||||
field: "password".into(),
|
||||
reason: String::new(),
|
||||
};
|
||||
let mut it = args.iter();
|
||||
while let Some(flag) = it.next() {
|
||||
let Some(val) = it.next() else { usage() };
|
||||
match flag.as_str() {
|
||||
"--vault" => req.vault = Some(val.clone()),
|
||||
"--item" => req.item = val.clone(),
|
||||
"--field" => req.field = val.clone(),
|
||||
"--reason" => req.reason = val.clone(),
|
||||
_ => usage(),
|
||||
}
|
||||
}
|
||||
if req.item.is_empty() || req.reason.trim().is_empty() {
|
||||
usage();
|
||||
}
|
||||
|
||||
let path = std::env::var("PASS_BROKER_SOCKET").unwrap_or_else(|_| DEFAULT_SOCKET.into());
|
||||
let stream = match UnixStream::connect(&path).await {
|
||||
Ok(s) => s,
|
||||
Err(e) => {
|
||||
eprintln!("pass-broker: cannot reach {path}: {e}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
};
|
||||
let (rd, mut wr) = stream.into_split();
|
||||
let mut line = serde_json::to_string(&req)?;
|
||||
line.push('\n');
|
||||
wr.write_all(line.as_bytes()).await?;
|
||||
|
||||
let mut lines = BufReader::new(rd).lines();
|
||||
// Bounds only the first reply: after Pending the daemon times the prompt
|
||||
// out itself. A crash-looping broker still accepts via the socket unit,
|
||||
// so without this the client would wait forever.
|
||||
let mut pending = false;
|
||||
loop {
|
||||
let next = if pending {
|
||||
lines.next_line().await?
|
||||
} else {
|
||||
match tokio::time::timeout(FIRST_REPLY, lines.next_line()).await {
|
||||
Ok(r) => r?,
|
||||
Err(_) => {
|
||||
eprintln!(
|
||||
"pass-broker: no answer within {}s; see journalctl -u pass-broker",
|
||||
FIRST_REPLY.as_secs()
|
||||
);
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
};
|
||||
let Some(line) = next else { break };
|
||||
match serde_json::from_str::<Reply>(&line)? {
|
||||
Reply::Pending { message } => {
|
||||
pending = true;
|
||||
eprintln!(">> pass-broker: {message}");
|
||||
}
|
||||
Reply::Ok { value } => {
|
||||
println!("{value}");
|
||||
return Ok(());
|
||||
}
|
||||
Reply::Error { error } => {
|
||||
eprintln!("pass-broker: {error}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
eprintln!("pass-broker: daemon closed the connection without an answer");
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
fn usage() -> ! {
|
||||
eprintln!("{}", crate::USAGE);
|
||||
std::process::exit(2);
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
use anyhow::{bail, Context, Result};
|
||||
use serde::Deserialize;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Written by services/identity/pass-broker.nix; path in $PASS_BROKER_CONFIG.
|
||||
#[derive(Deserialize)]
|
||||
pub struct Config {
|
||||
pub host: String,
|
||||
pub default_vault: String,
|
||||
/// Peer uids are checked against these; root is always allowed.
|
||||
pub allowed_users: Vec<String>,
|
||||
pub pass_cli: String,
|
||||
pub session_dir: PathBuf,
|
||||
pub pat_file: PathBuf,
|
||||
pub approval_timeout_secs: u64,
|
||||
pub telegram: TelegramConfig,
|
||||
/// First match wins; no match means deny.
|
||||
pub rules: Vec<Rule>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct TelegramConfig {
|
||||
pub api_base: String,
|
||||
pub token_file: PathBuf,
|
||||
pub chat_id_file: PathBuf,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct Rule {
|
||||
pub vault: Option<String>,
|
||||
/// Item title; `*` matches any run of characters.
|
||||
pub item: String,
|
||||
pub approval: Approval,
|
||||
/// After an approval, further requests for the item skip the prompt for this long.
|
||||
pub grant_minutes: u64,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Clone, Copy, PartialEq, Debug)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Approval {
|
||||
Auto,
|
||||
Ask,
|
||||
Deny,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
pub fn load() -> Result<Self> {
|
||||
let path = std::env::var("PASS_BROKER_CONFIG").context("PASS_BROKER_CONFIG unset")?;
|
||||
let text = std::fs::read_to_string(&path).with_context(|| format!("reading {path}"))?;
|
||||
serde_json::from_str(&text).with_context(|| format!("parsing {path}"))
|
||||
}
|
||||
|
||||
pub fn rule_for(&self, vault: &str, item: &str) -> Option<&Rule> {
|
||||
self.rules.iter().find(|r| {
|
||||
r.vault.as_deref().unwrap_or(&self.default_vault) == vault && glob(&r.item, item)
|
||||
})
|
||||
}
|
||||
|
||||
/// Resolved once at startup: a user added later needs a broker restart.
|
||||
pub fn allowed_uids(&self) -> Result<Vec<u32>> {
|
||||
let passwd = std::fs::read_to_string("/etc/passwd")?;
|
||||
let mut uids = vec![0];
|
||||
for name in &self.allowed_users {
|
||||
let uid = passwd
|
||||
.lines()
|
||||
.map(|l| l.split(':').collect::<Vec<_>>())
|
||||
.find(|f| f.len() > 2 && f[0] == name)
|
||||
.and_then(|f| f[2].parse().ok());
|
||||
match uid {
|
||||
Some(uid) => uids.push(uid),
|
||||
None => bail!("allowed user {name:?} not in /etc/passwd"),
|
||||
}
|
||||
}
|
||||
Ok(uids)
|
||||
}
|
||||
}
|
||||
|
||||
fn glob(pat: &str, s: &str) -> bool {
|
||||
let parts: Vec<&str> = pat.split('*').collect();
|
||||
if parts.len() == 1 {
|
||||
return pat == s;
|
||||
}
|
||||
let (first, last) = (parts[0], parts[parts.len() - 1]);
|
||||
if !s.starts_with(first) || s.len() < first.len() + last.len() || !s.ends_with(last) {
|
||||
return false;
|
||||
}
|
||||
let mut rest = &s[first.len()..s.len() - last.len()];
|
||||
for mid in &parts[1..parts.len() - 1] {
|
||||
match rest.find(mid) {
|
||||
Some(i) => rest = &rest[i + mid.len()..],
|
||||
None => return false,
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::glob;
|
||||
|
||||
#[test]
|
||||
fn globs() {
|
||||
assert!(glob("root@*", "root@jupiter"));
|
||||
assert!(!glob("root@*", "darman@jupiter"));
|
||||
assert!(glob("*", ""));
|
||||
assert!(glob("a*b*c", "aXbYc"));
|
||||
assert!(!glob("a*b*c", "acb"));
|
||||
assert!(!glob("ab*ba", "aba"));
|
||||
assert!(glob("exact", "exact"));
|
||||
assert!(!glob("exact", "exact2"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
use crate::config::{Approval, Config};
|
||||
use crate::pass::Pass;
|
||||
use crate::proto::{Reply, Request};
|
||||
use crate::telegram::{Telegram, Verdict};
|
||||
use anyhow::{bail, Context, Result};
|
||||
use std::collections::HashMap;
|
||||
use std::future::Future;
|
||||
use std::os::fd::FromRawFd;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::net::unix::{OwnedReadHalf, OwnedWriteHalf};
|
||||
use tokio::net::{UnixListener, UnixStream};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
struct State {
|
||||
cfg: Config,
|
||||
uids: Vec<u32>,
|
||||
pass: Pass,
|
||||
tg: Telegram,
|
||||
/// "vault\0item" -> when the last approval stops covering it.
|
||||
grants: Mutex<HashMap<String, Instant>>,
|
||||
/// One prompt at a time; Telegram::ask polls getUpdates itself.
|
||||
asking: Mutex<()>,
|
||||
}
|
||||
|
||||
pub async fn run() -> Result<()> {
|
||||
let cfg = Config::load()?;
|
||||
let state = Arc::new(State {
|
||||
uids: cfg.allowed_uids()?,
|
||||
pass: Pass::new(&cfg),
|
||||
tg: Telegram::new(&cfg.telegram)?,
|
||||
grants: Mutex::new(HashMap::new()),
|
||||
asking: Mutex::new(()),
|
||||
cfg,
|
||||
});
|
||||
// Not fatal: a stale PAT should show up in the journal, not stop the socket.
|
||||
if let Err(e) = state.pass.ensure_session().await {
|
||||
eprintln!("initial login failed: {e:#}");
|
||||
}
|
||||
|
||||
let listener = listener()?;
|
||||
eprintln!("pass-broker ready");
|
||||
loop {
|
||||
let (stream, _) = listener.accept().await?;
|
||||
let state = state.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = handle(state, stream).await {
|
||||
eprintln!("connection: {e:#}");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// From pass-broker.socket. The socket is 0666; access control is the peer
|
||||
/// uid check in handle(), so a new client needs no re-login for a group.
|
||||
fn listener() -> Result<UnixListener> {
|
||||
let ours = std::env::var("LISTEN_PID").ok() == Some(std::process::id().to_string());
|
||||
if !ours || std::env::var("LISTEN_FDS").ok().as_deref() != Some("1") {
|
||||
bail!("expected exactly one socket from systemd (pass-broker.socket)");
|
||||
}
|
||||
let l = unsafe { std::os::unix::net::UnixListener::from_raw_fd(3) };
|
||||
l.set_nonblocking(true)?;
|
||||
Ok(UnixListener::from_std(l)?)
|
||||
}
|
||||
|
||||
async fn handle(state: Arc<State>, stream: UnixStream) -> Result<()> {
|
||||
let cred = stream.peer_cred()?;
|
||||
let (mut rd, mut wr) = stream.into_split();
|
||||
// Read before refusing, or the client's write hits a closed socket and
|
||||
// it reports EPIPE instead of the reason.
|
||||
let mut line = String::new();
|
||||
BufReader::new((&mut rd).take(64 * 1024)).read_line(&mut line).await?;
|
||||
if !state.uids.contains(&cred.uid()) {
|
||||
eprintln!("refused uid {}", cred.uid());
|
||||
return send(&mut wr, Reply::Error { error: "uid not allowed".into() }).await;
|
||||
}
|
||||
|
||||
let req: Request = serde_json::from_str(&line).context("bad request")?;
|
||||
let vault = req.vault.clone().unwrap_or_else(|| state.cfg.default_vault.clone());
|
||||
// A client killed while queued (the broker restarting) leaves its request
|
||||
// in the socket; nobody would see the answer or know who asked.
|
||||
let who = match cred.pid().and_then(requester) {
|
||||
Some(who) if !closed(&rd) => who,
|
||||
_ => {
|
||||
eprintln!("dropped {vault}/{}: requester went away", req.item);
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
eprintln!(
|
||||
"request {vault}/{} ({}) uid={} reason={:?} from {}",
|
||||
req.item, req.field, cred.uid(), req.reason, who.from
|
||||
);
|
||||
|
||||
let gone = client_gone(&rd);
|
||||
tokio::pin!(gone);
|
||||
let reply = match decide(&state, &mut wr, gone.as_mut(), &vault, &req, &who).await {
|
||||
Ok(()) if closed(&rd) => Reply::Error { error: "requester went away".into() },
|
||||
Ok(()) => {
|
||||
let reason = format!("{} (pass-broker on {})", req.reason, state.cfg.host);
|
||||
match state.pass.get(&vault, &req.item, &req.field, &reason).await {
|
||||
Ok(value) => Reply::Ok { value },
|
||||
Err(e) => Reply::Error { error: format!("{e:#}") },
|
||||
}
|
||||
}
|
||||
Err(e) => Reply::Error { error: format!("{e:#}") },
|
||||
};
|
||||
match &reply {
|
||||
Reply::Ok { .. } => eprintln!("served {vault}/{}", req.item),
|
||||
Reply::Error { error } => eprintln!("refused {vault}/{}: {error}", req.item),
|
||||
Reply::Pending { .. } => {}
|
||||
}
|
||||
send(&mut wr, reply).await
|
||||
}
|
||||
|
||||
async fn decide(
|
||||
state: &State,
|
||||
wr: &mut OwnedWriteHalf,
|
||||
mut gone: Pin<&mut impl Future<Output = ()>>,
|
||||
vault: &str,
|
||||
req: &Request,
|
||||
who: &Requester,
|
||||
) -> Result<()> {
|
||||
let Some(rule) = state.cfg.rule_for(vault, &req.item) else {
|
||||
bail!("no rule allows {vault}/{}", req.item);
|
||||
};
|
||||
match rule.approval {
|
||||
Approval::Deny => bail!("policy denies {vault}/{}", req.item),
|
||||
Approval::Auto => return Ok(()),
|
||||
Approval::Ask => {}
|
||||
}
|
||||
|
||||
let key = format!("{vault}\0{}", req.item);
|
||||
let granted = |grants: &HashMap<String, Instant>| grants.get(&key).is_some_and(|t| *t > Instant::now());
|
||||
if granted(&*state.grants.lock().await) {
|
||||
eprintln!("covered by an earlier approval");
|
||||
return Ok(());
|
||||
}
|
||||
// Before the lock, so a client queued behind another prompt hears from us.
|
||||
let _ = send(wr, Reply::Pending { message: "waiting for approval on Telegram".into() }).await;
|
||||
let _asking = tokio::select! {
|
||||
guard = state.asking.lock() => guard,
|
||||
_ = gone.as_mut() => bail!("requester went away"),
|
||||
};
|
||||
// A concurrent request for the same item may have been approved meanwhile.
|
||||
if granted(&*state.grants.lock().await) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let grant = match rule.grant_minutes {
|
||||
0 => "Approves this request only.".to_string(),
|
||||
n => format!("Approving covers further requests for {n} min."),
|
||||
};
|
||||
let text = format!(
|
||||
"🔑 {host}: {vault} / {item} ({field})\nReason: {reason}\nFrom: {from}\nChain: {chain}\n{grant}",
|
||||
host = state.cfg.host,
|
||||
item = req.item,
|
||||
field = req.field,
|
||||
reason = req.reason,
|
||||
from = who.from,
|
||||
chain = who.chain,
|
||||
);
|
||||
let timeout = Duration::from_secs(state.cfg.approval_timeout_secs);
|
||||
match state.tg.ask(&text, timeout, gone).await? {
|
||||
Verdict::Approved => {
|
||||
if rule.grant_minutes > 0 {
|
||||
let until = Instant::now() + Duration::from_secs(rule.grant_minutes * 60);
|
||||
state.grants.lock().await.insert(key, until);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
Verdict::Denied => bail!("denied on Telegram"),
|
||||
Verdict::Expired => bail!("no answer on Telegram within {}s", timeout.as_secs()),
|
||||
Verdict::Cancelled => bail!("requester went away"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves once the client hangs up. It sends nothing after its request, so
|
||||
/// readable means EOF; stray bytes are discarded.
|
||||
async fn client_gone(rd: &OwnedReadHalf) {
|
||||
while rd.readable().await.is_ok() {
|
||||
if closed(rd) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn closed(rd: &OwnedReadHalf) -> bool {
|
||||
match rd.try_read(&mut [0u8; 64]) {
|
||||
Ok(0) => true,
|
||||
Ok(_) => false,
|
||||
Err(e) => e.kind() != std::io::ErrorKind::WouldBlock,
|
||||
}
|
||||
}
|
||||
|
||||
async fn send(wr: &mut OwnedWriteHalf, reply: Reply) -> Result<()> {
|
||||
let mut line = serde_json::to_string(&reply)?;
|
||||
line.push('\n');
|
||||
wr.write_all(line.as_bytes()).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Who is asking, for the prompt. Informational only: any process of the
|
||||
/// same uid can make itself look like anything.
|
||||
struct Requester {
|
||||
from: String,
|
||||
chain: String,
|
||||
}
|
||||
|
||||
/// The client itself is just `pass-broker get …`; its parent is the caller.
|
||||
/// None when the client has already exited.
|
||||
fn requester(pid: i32) -> Option<Requester> {
|
||||
let parent = ppid(pid)?;
|
||||
let from = std::fs::read(format!("/proc/{parent}/cmdline"))
|
||||
.map(|b| {
|
||||
let s = String::from_utf8_lossy(&b).replace('\0', " ");
|
||||
truncate(s.trim(), 200)
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let mut names = vec![];
|
||||
let mut p = parent;
|
||||
for _ in 0..8 {
|
||||
if p <= 1 {
|
||||
break;
|
||||
}
|
||||
if let Ok(c) = std::fs::read_to_string(format!("/proc/{p}/comm")) {
|
||||
names.push(c.trim().to_string());
|
||||
}
|
||||
match ppid(p) {
|
||||
Some(pp) => p = pp,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
Some(Requester { from, chain: names.join(" ← ") })
|
||||
}
|
||||
|
||||
fn ppid(pid: i32) -> Option<i32> {
|
||||
let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
|
||||
// comm may contain spaces and parens; fields resume after the last ')'.
|
||||
stat.rsplit_once(')')?.1.split_whitespace().nth(1)?.parse().ok()
|
||||
}
|
||||
|
||||
fn truncate(s: &str, max: usize) -> String {
|
||||
match s.char_indices().nth(max) {
|
||||
Some((i, _)) => format!("{}…", &s[..i]),
|
||||
None => s.to_string(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
//! pass-broker — hands Proton Pass items to darman's processes (Claude
|
||||
//! included) only after a Telegram approval.
|
||||
//!
|
||||
//! The daemon runs as its own system user and holds the only pass-cli session
|
||||
//! (an agent PAT), so nothing running as darman can read it directly. Clients
|
||||
//! talk to it over a unix socket; see services/identity/pass-broker.nix.
|
||||
|
||||
mod client;
|
||||
mod config;
|
||||
mod daemon;
|
||||
mod pass;
|
||||
mod proto;
|
||||
mod telegram;
|
||||
|
||||
use anyhow::Result;
|
||||
|
||||
const USAGE: &str = "usage: pass-broker get --item <title> --reason <why> [--vault <name>] [--field <name>]
|
||||
pass-broker daemon";
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
match args.first().map(String::as_str) {
|
||||
Some("daemon") => daemon::run().await,
|
||||
Some("get") => client::get(&args[1..]).await,
|
||||
_ => {
|
||||
eprintln!("{USAGE}");
|
||||
std::process::exit(2);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
use crate::config::Config;
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
use std::path::PathBuf;
|
||||
use std::process::Stdio;
|
||||
use tokio::process::Command;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
/// The broker's own pass-cli session. pass-cli calls are serialised: they
|
||||
/// share one session dir and a re-login mid-lookup would race.
|
||||
pub struct Pass {
|
||||
bin: String,
|
||||
session_dir: PathBuf,
|
||||
pat_file: PathBuf,
|
||||
lock: Mutex<()>,
|
||||
}
|
||||
|
||||
impl Pass {
|
||||
pub fn new(cfg: &Config) -> Self {
|
||||
Self {
|
||||
bin: cfg.pass_cli.clone(),
|
||||
session_dir: cfg.session_dir.clone(),
|
||||
pat_file: cfg.pat_file.clone(),
|
||||
lock: Mutex::new(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn ensure_session(&self) -> Result<()> {
|
||||
let _g = self.lock.lock().await;
|
||||
self.ensure_session_locked().await
|
||||
}
|
||||
|
||||
async fn ensure_session_locked(&self) -> Result<()> {
|
||||
if self.run(&["info"], &[]).await.is_ok() {
|
||||
return Ok(());
|
||||
}
|
||||
eprintln!("no pass-cli session, logging in with the PAT");
|
||||
let pat = std::fs::read_to_string(&self.pat_file)
|
||||
.with_context(|| format!("reading {}", self.pat_file.display()))?;
|
||||
let _ = self.run(&["logout", "--force"], &[]).await;
|
||||
// Via env, not `--pat`: argv is world-readable in /proc.
|
||||
self.run(&["login"], &[("PROTON_PASS_PERSONAL_ACCESS_TOKEN", pat.trim())])
|
||||
.await
|
||||
.context("pass-cli login")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn get(&self, vault: &str, title: &str, field: &str, reason: &str) -> Result<String> {
|
||||
let _g = self.lock.lock().await;
|
||||
self.ensure_session_locked().await?;
|
||||
|
||||
// `item view --item-title` has no state filter and can return a
|
||||
// trashed duplicate, so resolve the id among active items first.
|
||||
let list = self
|
||||
.run(
|
||||
&["item", "list", "--vault-name", vault, "--filter-state", "active", "--output", "human"],
|
||||
&[],
|
||||
)
|
||||
.await?;
|
||||
let id = list
|
||||
.lines()
|
||||
.find_map(|l| {
|
||||
// - [ITEM_ID]: the title (state=Active)
|
||||
let rest = l.strip_prefix("- [")?;
|
||||
let (id, rest) = rest.split_once("]: ")?;
|
||||
let t = match rest.rfind(" (state=") {
|
||||
Some(i) if rest.ends_with(')') => &rest[..i],
|
||||
_ => rest,
|
||||
};
|
||||
(t == title).then(|| id.to_string())
|
||||
})
|
||||
.ok_or_else(|| anyhow!("no active item {title:?} in vault {vault:?}"))?;
|
||||
|
||||
let out = self
|
||||
.run(
|
||||
&["item", "view", "--vault-name", vault, "--item-id", &id, "--field", field, "--output", "human"],
|
||||
&[("PROTON_PASS_AGENT_REASON", reason)],
|
||||
)
|
||||
.await?;
|
||||
let value = out.lines().next().unwrap_or("").to_string();
|
||||
if value.is_empty() {
|
||||
bail!("{title:?} has an empty {field} field");
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
async fn run(&self, args: &[&str], env: &[(&str, &str)]) -> Result<String> {
|
||||
let out = Command::new(&self.bin)
|
||||
.args(args)
|
||||
.envs(env.iter().copied())
|
||||
.env("PROTON_PASS_SESSION_DIR", &self.session_dir)
|
||||
.stdin(Stdio::null())
|
||||
.kill_on_drop(true)
|
||||
.output()
|
||||
.await
|
||||
.with_context(|| format!("running {}", self.bin))?;
|
||||
if !out.status.success() {
|
||||
let err = String::from_utf8_lossy(&out.stderr);
|
||||
bail!("pass-cli {} failed ({}): {}", args[0], out.status, err.trim());
|
||||
}
|
||||
Ok(String::from_utf8(out.stdout)?)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
pub const DEFAULT_SOCKET: &str = "/run/pass-broker.sock";
|
||||
|
||||
/// One JSON line from the client.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct Request {
|
||||
pub vault: Option<String>,
|
||||
pub item: String,
|
||||
pub field: String,
|
||||
pub reason: String,
|
||||
}
|
||||
|
||||
/// JSON lines from the daemon: any number of `Pending`, then one final reply.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(tag = "status", rename_all = "snake_case")]
|
||||
pub enum Reply {
|
||||
Pending { message: String },
|
||||
Ok { value: String },
|
||||
Error { error: String },
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
use crate::config::TelegramConfig;
|
||||
use anyhow::{anyhow, bail, Context, Result};
|
||||
use serde_json::{json, Value};
|
||||
use std::future::Future;
|
||||
use std::io::Read;
|
||||
use std::pin::Pin;
|
||||
use std::sync::atomic::{AtomicI64, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// Approval prompts with Approve/Deny buttons. The bot must be dedicated to
|
||||
/// the broker: getUpdates has a single consumer, so a shared bot would see
|
||||
/// (or swallow) the other's callbacks.
|
||||
pub struct Telegram {
|
||||
http: reqwest::Client,
|
||||
/// Contains the token: never print it, and strip it from reqwest errors.
|
||||
base: String,
|
||||
chat_id: i64,
|
||||
offset: AtomicI64,
|
||||
}
|
||||
|
||||
pub enum Verdict {
|
||||
Approved,
|
||||
Denied,
|
||||
Expired,
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
impl Telegram {
|
||||
pub fn new(cfg: &TelegramConfig) -> Result<Self> {
|
||||
let token = std::fs::read_to_string(&cfg.token_file)
|
||||
.with_context(|| format!("reading {}", cfg.token_file.display()))?;
|
||||
let chat_id = std::fs::read_to_string(&cfg.chat_id_file)
|
||||
.with_context(|| format!("reading {}", cfg.chat_id_file.display()))?
|
||||
.trim()
|
||||
.parse()
|
||||
.context("telegram chat id is not a number")?;
|
||||
Ok(Self {
|
||||
http: reqwest::Client::builder().timeout(Duration::from_secs(40)).build()?,
|
||||
base: format!("{}/bot{}", cfg.api_base.trim_end_matches('/'), token.trim()),
|
||||
chat_id,
|
||||
offset: AtomicI64::new(0),
|
||||
})
|
||||
}
|
||||
|
||||
async fn call(&self, method: &str, body: Value) -> Result<Value> {
|
||||
let resp = self
|
||||
.http
|
||||
.post(format!("{}/{method}", self.base))
|
||||
.json(&body)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| anyhow!("telegram {method}: {}", e.without_url()))?;
|
||||
let v: Value = resp
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| anyhow!("telegram {method}: {}", e.without_url()))?;
|
||||
if v["ok"] != json!(true) {
|
||||
bail!("telegram {method}: {}", v["description"]);
|
||||
}
|
||||
Ok(v["result"].clone())
|
||||
}
|
||||
|
||||
/// Callers must not ask concurrently: each call polls getUpdates itself.
|
||||
/// `gone` resolving (the client hung up) withdraws the prompt.
|
||||
pub async fn ask(
|
||||
&self,
|
||||
text: &str,
|
||||
timeout: Duration,
|
||||
mut gone: Pin<&mut impl Future<Output = ()>>,
|
||||
) -> Result<Verdict> {
|
||||
let nonce = nonce()?;
|
||||
let (yes, no) = (format!("ok:{nonce}"), format!("no:{nonce}"));
|
||||
let msg = self
|
||||
.call(
|
||||
"sendMessage",
|
||||
json!({
|
||||
"chat_id": self.chat_id,
|
||||
"text": text,
|
||||
"reply_markup": { "inline_keyboard": [[
|
||||
{ "text": "Approve", "callback_data": yes },
|
||||
{ "text": "Deny", "callback_data": no },
|
||||
]]},
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
let message_id = msg["message_id"].clone();
|
||||
|
||||
let deadline = Instant::now() + timeout;
|
||||
let verdict = 'poll: loop {
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
if left.is_zero() {
|
||||
break Verdict::Expired;
|
||||
}
|
||||
let poll = self.call(
|
||||
"getUpdates",
|
||||
json!({
|
||||
"offset": self.offset.load(Ordering::SeqCst),
|
||||
"timeout": left.as_secs().min(25),
|
||||
"allowed_updates": ["callback_query"],
|
||||
}),
|
||||
);
|
||||
let polled = tokio::select! {
|
||||
r = poll => r,
|
||||
_ = gone.as_mut() => break 'poll Verdict::Cancelled,
|
||||
};
|
||||
let updates = match polled {
|
||||
Ok(u) => u,
|
||||
Err(e) => {
|
||||
eprintln!("{e:#}");
|
||||
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
for u in updates.as_array().into_iter().flatten() {
|
||||
if let Some(id) = u["update_id"].as_i64() {
|
||||
self.offset.fetch_max(id + 1, Ordering::SeqCst);
|
||||
}
|
||||
let cq = &u["callback_query"];
|
||||
let Some(cq_id) = cq["id"].as_str() else { continue };
|
||||
let data = cq["data"].as_str().unwrap_or("");
|
||||
let mine = data == yes || data == no;
|
||||
// The button lives in our chat, but the bot can be added
|
||||
// elsewhere and a forwarded message keeps its buttons.
|
||||
let from_owner = cq["from"]["id"].as_i64() == Some(self.chat_id);
|
||||
let note = match (mine, from_owner) {
|
||||
(_, false) => "Not yours.",
|
||||
(false, true) => "Expired.",
|
||||
(true, true) => "",
|
||||
};
|
||||
let _ = self
|
||||
.call("answerCallbackQuery", json!({ "callback_query_id": cq_id, "text": note }))
|
||||
.await;
|
||||
if mine && from_owner {
|
||||
break 'poll if data == yes { Verdict::Approved } else { Verdict::Denied };
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let outcome = match verdict {
|
||||
Verdict::Approved => "✅ approved",
|
||||
Verdict::Denied => "❌ denied",
|
||||
Verdict::Expired => "⌛ expired",
|
||||
Verdict::Cancelled => "🚫 cancelled: the requester went away",
|
||||
};
|
||||
// Without reply_markup this also removes the buttons.
|
||||
let _ = self
|
||||
.call(
|
||||
"editMessageText",
|
||||
json!({
|
||||
"chat_id": self.chat_id,
|
||||
"message_id": message_id,
|
||||
"text": format!("{text}\n\n{outcome}"),
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
Ok(verdict)
|
||||
}
|
||||
}
|
||||
|
||||
fn nonce() -> Result<String> {
|
||||
let mut buf = [0u8; 16];
|
||||
std::fs::File::open("/dev/urandom")?.read_exact(&mut buf)?;
|
||||
Ok(buf.iter().map(|b| format!("{b:02x}")).collect())
|
||||
}
|
||||
Reference in New Issue
Block a user