1
//! Drives the `nomisync-eval` subsystem over a real SSH connection, so the
2
//! channel shutdown is checked end to end rather than through a mock sink.
3

            
4
use crate::accept::{AcceptLimits, serve};
5
use crate::handler::{SshConnectInfo, SshdState};
6
use crate::rate_limit::{Config as LimitConfig, InstantClock, RateLimiter};
7
use russh::client::{self, Handle};
8
use russh::keys::{Algorithm, HashAlg, PrivateKey, PrivateKeyWithHashAlg, PublicKeyOrCertificate};
9
use russh::{Channel, ChannelMsg, Disconnect};
10
use server::command::ssh_key::AddSshKey;
11
use server::db::install_test_pool;
12
use sqlx::PgPool;
13
use sqlx::types::Uuid;
14
use std::net::SocketAddr;
15
use std::sync::Arc;
16
use std::time::Duration;
17
use supp_macro::local_db_sqlx_test;
18
use tokio::net::TcpListener;
19
use tokio::sync::Mutex;
20
use tokio::task::JoinHandle;
21

            
22
/// Smaller than any single response, so every response write waits on a
23
/// window adjust and the worker's sends run behind a full window.
24
const CLIENT_WINDOW: u32 = 16;
25
const FORMS: usize = 20;
26
/// Bounds a hang, not the expected run: a passing run ends at CLOSE. Kept
27
/// under tarpaulin's 60 s silence limit so a stall fails here, with a cause.
28
pub(crate) const DEADLINE: Duration = Duration::from_secs(45);
29

            
30
/// Required by `local_db_sqlx_test`, which calls it before each case.
31
24
pub(crate) async fn setup() {}
32

            
33
pub(crate) struct TrustingClient;
34

            
35
impl client::Handler for TrustingClient {
36
    type Error = russh::Error;
37

            
38
25
    async fn check_server_key(&mut self, _: &PublicKeyOrCertificate) -> Result<bool, Self::Error> {
39
25
        Ok(true)
40
25
    }
41
}
42

            
43
pub(crate) struct Daemon {
44
    pub(crate) addr: SocketAddr,
45
    task: JoinHandle<()>,
46
}
47

            
48
impl Daemon {
49
28
    pub(crate) async fn stop(self) -> anyhow::Result<()> {
50
28
        self.task.abort();
51
28
        match self.task.await {
52
28
            Err(err) if !err.is_cancelled() => Err(err.into()),
53
28
            _ => Ok(()),
54
        }
55
28
    }
56
}
57

            
58
#[derive(Debug, Default)]
59
pub(crate) struct Transcript {
60
    pub(crate) output: Vec<u8>,
61
    pub(crate) exit_status: Option<u32>,
62
    pub(crate) eof: bool,
63
    pub(crate) data_after_eof: bool,
64
    pub(crate) closed: bool,
65
    pub(crate) failed: bool,
66
}
67

            
68
53
pub(crate) fn random_key() -> anyhow::Result<PrivateKey> {
69
53
    let mut rng = rand_core::UnwrapErr(rand::rngs::SysRng);
70
53
    Ok(PrivateKey::random(&mut rng, Algorithm::Ed25519)?)
71
53
}
72

            
73
22
pub(crate) async fn insert_verified_user(pool: &PgPool, id: Uuid) -> anyhow::Result<()> {
74
22
    sqlx::query!(
75
        "INSERT INTO users (
76
            id, user_name, email, photo, verified, user_password,
77
            user_role, database_name, created_at
78
        ) VALUES (
79
            $1, 'eval-e2e', $2, 'default.png',
80
            TRUE, 'irrelevant', 'user', 'eval-e2e', NOW()
81
        )",
82
        id,
83
22
        format!("eval-e2e-{id}@example.test"),
84
    )
85
22
    .execute(pool)
86
22
    .await?;
87
22
    Ok(())
88
22
}
89

            
90
22
pub(crate) async fn register_key(user_id: Uuid, key: &PrivateKey) -> anyhow::Result<()> {
91
22
    let public = key.public_key();
92
22
    AddSshKey::new()
93
22
        .user_id(user_id)
94
22
        .key_type(public.algorithm().as_str().to_owned())
95
22
        .key_blob(public.to_bytes()?)
96
22
        .fingerprint(public.fingerprint(HashAlg::Sha256).to_string())
97
        .run()
98
22
        .await?;
99
22
    Ok(())
100
22
}
101

            
102
pub(crate) const TEST_LIMITS: AcceptLimits = AcceptLimits {
103
    max_startups: 64,
104
    pre_auth: DEADLINE,
105
};
106

            
107
20
pub(crate) async fn start_daemon() -> anyhow::Result<Daemon> {
108
20
    start_daemon_with(TEST_LIMITS).await
109
20
}
110

            
111
28
pub(crate) async fn start_daemon_with(limits: AcceptLimits) -> anyhow::Result<Daemon> {
112
28
    let listener = TcpListener::bind("127.0.0.1:0").await?;
113
28
    let addr = listener.local_addr()?;
114
28
    let mut state = SshdState {
115
28
        limiter: Arc::new(Mutex::new(RateLimiter::new(
116
28
            LimitConfig {
117
28
                max_attempts_per_ip: 6,
118
28
                max_pubkey_attempts_per_ip: 30,
119
28
                window: Duration::from_mins(1),
120
28
                account_lockout_threshold: 3,
121
28
                account_lockout_duration: Duration::from_mins(15),
122
28
            },
123
28
            InstantClock,
124
28
        ))),
125
28
        connect_info: SshConnectInfo {
126
28
            hostname: addr.ip().to_string(),
127
28
            port: addr.port(),
128
28
            host_fingerprint: String::new(),
129
28
        },
130
28
    };
131
28
    let config = Arc::new(russh::server::Config {
132
28
        keys: vec![random_key()?],
133
28
        ..russh::server::Config::default()
134
    });
135
28
    let task = tokio::spawn(async move { serve(&mut state, config, &listener, limits).await });
136
28
    Ok(Daemon { addr, task })
137
28
}
138

            
139
9
pub(crate) async fn connect(
140
9
    addr: SocketAddr,
141
9
    key: PrivateKey,
142
9
    window_size: u32,
143
9
) -> anyhow::Result<Handle<TrustingClient>> {
144
9
    let config = Arc::new(client::Config {
145
9
        window_size,
146
9
        ..client::Config::default()
147
9
    });
148
9
    let mut session = client::connect(config, addr, TrustingClient).await?;
149
9
    let auth = session
150
9
        .authenticate_publickey("eval-e2e", PrivateKeyWithHashAlg::new(Arc::new(key), None))
151
9
        .await?;
152
9
    anyhow::ensure!(auth.success(), "publickey auth was refused");
153
9
    Ok(session)
154
9
}
155

            
156
25
pub(crate) async fn open_subsystem(
157
25
    session: &Handle<TrustingClient>,
158
25
) -> anyhow::Result<Channel<client::Msg>> {
159
25
    let channel = session.channel_open_session().await?;
160
25
    channel.request_subsystem(true, "nomisync-eval").await?;
161
25
    Ok(channel)
162
25
}
163

            
164
1
async fn open_eval_channel(
165
1
    addr: SocketAddr,
166
1
    key: PrivateKey,
167
1
) -> anyhow::Result<(Handle<TrustingClient>, Channel<client::Msg>)> {
168
1
    let session = connect(addr, key, CLIENT_WINDOW).await?;
169
1
    let channel = open_subsystem(&session).await?;
170
1
    Ok((session, channel))
171
1
}
172

            
173
24
pub(crate) async fn read_until_closed(channel: &mut Channel<client::Msg>) -> Transcript {
174
24
    let mut transcript = Transcript::default();
175
125
    while let Some(msg) = channel.wait().await {
176
125
        match msg {
177
            ChannelMsg::Data { data } => {
178
70
                transcript.data_after_eof |= transcript.eof;
179
70
                transcript.output.extend_from_slice(&data);
180
            }
181
8
            ChannelMsg::ExitStatus { exit_status } => transcript.exit_status = Some(exit_status),
182
8
            ChannelMsg::Eof => transcript.eof = true,
183
14
            ChannelMsg::Failure => transcript.failed = true,
184
            ChannelMsg::Close => {
185
24
                transcript.closed = true;
186
24
                break;
187
            }
188
1
            _ => {}
189
        }
190
    }
191
24
    transcript
192
24
}
193

            
194
/// Pipes every form, half-closes the input, and reads until the daemon ends
195
/// the channel.
196
1
async fn pipe_forms_and_read(addr: SocketAddr, key: PrivateKey) -> anyhow::Result<Transcript> {
197
1
    let (session, mut channel) = open_eval_channel(addr, key).await?;
198
1
    channel.data(piped_forms().as_bytes()).await?;
199
1
    channel.eof().await?;
200
1
    let transcript = read_until_closed(&mut channel).await;
201
1
    session
202
1
        .disconnect(Disconnect::ByApplication, "done", "")
203
1
        .await?;
204
1
    Ok(transcript)
205
1
}
206

            
207
6
pub(crate) fn response_lines(output: &[u8]) -> Vec<String> {
208
6
    String::from_utf8_lossy(output)
209
6
        .lines()
210
6
        .map(str::to_owned)
211
6
        .collect()
212
6
}
213

            
214
1
fn answered_ids(lines: &[String]) -> Vec<usize> {
215
1
    lines
216
1
        .iter()
217
20
        .filter(|line| line.ends_with(":value 1)"))
218
20
        .filter_map(|line| line.strip_prefix("(:id ")?.split_once(' ')?.0.parse().ok())
219
        .collect()
220
1
}
221

            
222
1
fn piped_forms() -> String {
223
1
    (1..=FORMS)
224
20
        .map(|id| format!("(:id {id} :form (rpc-protocol-version))\n"))
225
        .collect()
226
1
}
227

            
228
#[local_db_sqlx_test]
229
async fn piped_forms_are_all_answered_before_the_channel_ends(pool: PgPool) -> anyhow::Result<()> {
230
    let user_id = Uuid::new_v4();
231
    insert_verified_user(&pool, user_id).await?;
232
    let key = random_key()?;
233
    register_key(user_id, &key).await?;
234
    let daemon = start_daemon().await?;
235

            
236
    let outcome = tokio::time::timeout(DEADLINE, pipe_forms_and_read(daemon.addr, key)).await;
237
    daemon.stop().await?;
238
    let transcript = outcome??;
239

            
240
    let lines = response_lines(&transcript.output);
241
    assert!(
242
        lines
243
            .iter()
244
20
            .all(|line| line.len() >= CLIENT_WINDOW as usize),
245
        "every response must fill the client window: {lines:?}"
246
    );
247
    assert_eq!(answered_ids(&lines), (1..=FORMS).collect::<Vec<_>>());
248
    assert_eq!(transcript.exit_status, Some(0));
249
    assert!(transcript.eof, "{transcript:?}");
250
    assert!(!transcript.data_after_eof, "{transcript:?}");
251
    assert!(transcript.closed, "{transcript:?}");
252
}