1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
pub mod session;

use std::env;
use std::time::Duration;

use anyhow::{bail, Context, Result};
use clap::Parser;
use futures_util::stream::SplitSink;
use futures_util::{SinkExt, Stream, StreamExt};
use serde::{Deserialize, Serialize};
use session::{Capabilities, CommandName, TxMessage};
use tokio::net::TcpStream;
use tokio::sync::mpsc::{self, Sender};
use tokio::time;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::{connect_async, MaybeTlsStream, WebSocketStream};

/// Incoming messages from the Relay service.
#[derive(Serialize, Deserialize)]
#[serde(tag = "t", content = "c")]
enum RecvMessage {
    #[serde(rename = "create_session")]
    CreateSession { id: String },
    #[serde(rename = "end_session")]
    EndSession { id: String },
    #[serde(rename = "command")]
    Command { session_id: String, command: String },
    #[serde(rename = "request_capabilities")]
    RequestCapabilities {},
}

async fn handle_message(
    manager: &mut session::Manager,
    tx: &Sender<TxMessage>,
    msg: String,
) -> anyhow::Result<()> {
    let payload = serde_json::from_str::<RecvMessage>(&msg)?;
    match payload {
        RecvMessage::CreateSession { id } => {
            println!("creating session: {id}");
            manager.create_session(id).await
        }
        RecvMessage::EndSession { id } => {
            println!("ending session: {id}");
            manager.end_session(id).await
        }
        RecvMessage::RequestCapabilities {} => {
            println!("received capabilities request");
            send_capabilities(tx).await
        }
        RecvMessage::Command {
            session_id,
            command,
        } => manager.send_command(session_id, command).await,
    }
}

/// Sends the capabilities that this node has to the Relay service.
async fn send_capabilities(tx: &Sender<TxMessage>) -> Result<()> {
    let cap = TxMessage::Capabilities {
        shell: true,
        actions: None,
    };
    tx.send(cap).await?;
    Ok(())
}

/// reads input from websockets and handles launching a shell process for a session.
async fn input_loop(
    mut rx: impl Stream<Item = Result<Message, tokio_tungstenite::tungstenite::Error>> + Unpin,
    tx: &Sender<TxMessage>,
    mut manager: session::Manager,
) {
    loop {
        let msg = rx.next().await;
        match msg {
            Some(Ok(Message::Text(m))) => {
                println!("got a string: {m}");
                if let Err(e) = handle_message(&mut manager, tx, m).await {
                    println!("error handling message: {e}")
                }
            }
            Some(Ok(Message::Close(_))) => {
                println!("closing connection");
                break;
            }
            Some(Ok(v)) => {
                println!("unhandled type: {v}");
                break;
            }
            Some(Err(e)) => {
                println!("recv error: {}", e)
            }
            None => {
                println!("nothing to read");
                break;
            }
        };
    }

    println!("write_input loop complete")
}

async fn send_output(
    tx: &mut SplitSink<WebSocketStream<MaybeTlsStream<TcpStream>>, Message>,
    m: session::TxMessage,
) -> anyhow::Result<()> {
    let m_str = serde_json::to_string(&m)?;
    let msg = Message::Text(m_str);
    tx.send(msg).await?;
    Ok(())
}

fn make_command(command: String) -> Result<session::CommandName> {
    let commandsplit: Vec<&str> = command.split_whitespace().collect();
    match commandsplit.split_first() {
        Some((name, args)) => Ok(session::CommandName {
            name: name.to_string(),
            args: args.iter().map(|a| a.to_string()).collect(),
        }),
        None => bail!("provided command was empty"),
    }
}

/// Run an audited shell command
#[derive(Parser, Debug)]
#[command(author, version, about, long_about = None, trailing_var_arg=true)]
struct Args {
    command: Option<Vec<String>>,
    /// Name of the service to register with the relay
    #[arg(short, long)]
    service: String,
}

type CapabilitiesFetcher = fn() -> Result<Capabilities>;

pub struct Agent {
    pub service: String,
    pub url: String,
    pub command: CommandName,
    pub capabilities_fetcher: CapabilitiesFetcher,
}

impl Agent {
    pub fn from_env(capabilities_fetcher: CapabilitiesFetcher) -> Result<Self> {
        let service =
            env::var("COMMONFATE_SERVICE").context("COMMONFATE_SERVICE must be provided")?;
        let url = env::var("COMMONFATE_URL").context("COMMONFATE_URL must be provided")?;
        let commandstr =
            env::var("COMMONFATE_COMMAND").context("COMMONFATE_COMMAND must be provided")?;

        let command = make_command(commandstr)?;

        Ok(Self {
            service,
            url,
            command,
            capabilities_fetcher,
        })
    }

    pub async fn run(&self) {
        let url = format!("{}?service={}", self.url, self.service);

        let (tx, mut rx) = mpsc::channel(100);
        let tx2 = tx.clone();
        let tx3 = tx.clone();

        // connect to the websocket server
        let (ws_stream, _) = connect_async(url).await.unwrap();
        let (mut ws_write, ws_read) = ws_stream.split();

        let manager = session::Manager::new(tx, self.command.clone());

        // write received messages back to the websocket
        tokio::spawn(async move {
            while let Some(m) = rx.recv().await {
                println!("sending message to relay: {:?}", m);
                if let Err(e) = send_output(&mut ws_write, m).await {
                    println!("send error: {e}");
                }
            }
        });

        // report capabilities after a short delay
        tokio::spawn(async move {
            time::sleep(Duration::from_secs(1)).await;
            println!("sending capabilities");
            if let Err(e) = send_capabilities(&tx3).await {
                println!("error sending capabilities: {e}");
            }
        });

        tokio::join!(input_loop(ws_read, &tx2, manager));
    }
}