1
//! The eval subsystem's wire rules and limits, over a real SSH connection.
2

            
3
use std::net::SocketAddr;
4

            
5
use rpc::MAX_FRAME_BYTES;
6
use russh::client::{self, Handle};
7
use russh::keys::PrivateKey;
8
use russh::{Channel, ChannelMsg, Disconnect};
9
use server::db::install_test_pool;
10
use sqlx::PgPool;
11
use sqlx::types::Uuid;
12
use supp_macro::local_db_sqlx_test;
13

            
14
use crate::eval_subsystem_tests::{
15
    DEADLINE, Daemon, TrustingClient, connect, insert_verified_user, open_subsystem, random_key,
16
    read_until_closed, register_key, response_lines, setup, start_daemon,
17
};
18

            
19
6
async fn daemon_with_user(pool: &PgPool) -> anyhow::Result<(Daemon, PrivateKey)> {
20
6
    let user_id = Uuid::new_v4();
21
6
    insert_verified_user(pool, user_id).await?;
22
6
    let key = random_key()?;
23
6
    register_key(user_id, &key).await?;
24
6
    Ok((start_daemon().await?, key))
25
6
}
26

            
27
6
async fn connected(addr: SocketAddr, key: PrivateKey) -> anyhow::Result<Handle<TrustingClient>> {
28
6
    connect(addr, key, client::Config::default().window_size).await
29
6
}
30

            
31
/// Sends `input`, half-closes and reads until the daemon ends the channel.
32
17
async fn exchange(
33
17
    session: &Handle<TrustingClient>,
34
17
    input: &[u8],
35
17
) -> anyhow::Result<crate::eval_subsystem_tests::Transcript> {
36
17
    let mut channel = open_subsystem(session).await?;
37
17
    channel.data(input).await?;
38
17
    channel.eof().await?;
39
17
    Ok(read_until_closed(&mut channel).await)
40
17
}
41

            
42
2
async fn first_data(channel: &mut Channel<client::Msg>) -> anyhow::Result<Vec<u8>> {
43
2
    while let Some(msg) = channel.wait().await {
44
2
        if let ChannelMsg::Data { data } = msg {
45
2
            return Ok(data.to_vec());
46
        }
47
    }
48
    anyhow::bail!("the channel ended without a reply")
49
2
}
50

            
51
6
async fn run_with_user<T>(
52
6
    pool: &PgPool,
53
6
    scenario: impl AsyncFnOnce(SocketAddr, PrivateKey) -> anyhow::Result<T>,
54
6
) -> anyhow::Result<T> {
55
6
    let (daemon, key) = daemon_with_user(pool).await?;
56
6
    let outcome = tokio::time::timeout(DEADLINE, scenario(daemon.addr, key)).await;
57
6
    daemon.stop().await?;
58
6
    outcome?
59
6
}
60

            
61
#[local_db_sqlx_test]
62
async fn a_third_eval_channel_is_refused_until_one_closes(pool: PgPool) -> anyhow::Result<()> {
63
2
    run_with_user(&pool, async |addr, key| {
64
1
        let session = connected(addr, key).await?;
65
1
        let mut first = open_subsystem(&session).await?;
66
1
        let mut second = open_subsystem(&session).await?;
67
1
        let mut third = open_subsystem(&session).await?;
68
1
        let refused = read_until_closed(&mut third).await;
69
1
        assert!(refused.failed && refused.closed, "{refused:?}");
70
1
        assert!(refused.output.is_empty(), "{refused:?}");
71

            
72
1
        for channel in [&mut first, &mut second] {
73
2
            channel
74
2
                .data(&b"(:id 1 :form (rpc-protocol-version))\n"[..])
75
2
                .await?;
76
2
            assert_eq!(first_data(channel).await?, b"(:id 1 :value 1)\n");
77
        }
78

            
79
1
        first.eof().await?;
80
1
        let ended = read_until_closed(&mut first).await;
81
1
        assert!(ended.closed, "{ended:?}");
82
1
        let reopened = exchange(&session, b"(:id 2 :form (rpc-protocol-version))\n").await?;
83
1
        assert!(!reopened.failed, "{reopened:?}");
84
1
        assert_eq!(response_lines(&reopened.output), ["(:id 2 :value 1)"]);
85
1
        session
86
1
            .disconnect(Disconnect::ByApplication, "done", "")
87
1
            .await?;
88
1
        Ok(())
89
2
    })
90
    .await?;
91
}
92

            
93
#[local_db_sqlx_test]
94
async fn a_stray_etx_byte_is_an_error_not_an_interrupt(pool: PgPool) -> anyhow::Result<()> {
95
2
    run_with_user(&pool, async |addr, key| {
96
1
        let session = connected(addr, key).await?;
97
1
        let transcript = exchange(&session, b"\x03\n").await?;
98
1
        let lines = response_lines(&transcript.output);
99
1
        assert_eq!(lines.len(), 1, "{lines:?}");
100
1
        assert!(
101
1
            lines[0].starts_with("(:id 0 :error (:code parse"),
102
            "{lines:?}"
103
        );
104
1
        assert_eq!(transcript.exit_status, Some(0));
105
1
        Ok(())
106
2
    })
107
    .await?;
108
}
109

            
110
#[local_db_sqlx_test]
111
async fn eof_answers_both_streams_in_full_before_exit_status_zero(
112
    pool: PgPool,
113
) -> anyhow::Result<()> {
114
2
    run_with_user(&pool, async |addr, key| {
115
1
        let session = connected(addr, key).await?;
116
1
        let forms: String = (1..=20)
117
20
            .map(|id| match id % 2 {
118
10
                0 => format!("(:id {id} :stream 1 :form (rpc-protocol-version))\n"),
119
10
                _ => format!("(:id {id} :form (rpc-protocol-version))\n"),
120
20
            })
121
            .collect();
122
1
        let transcript = exchange(&session, forms.as_bytes()).await?;
123
1
        let lines = response_lines(&transcript.output);
124
1
        let mut ids: Vec<usize> = lines
125
1
            .iter()
126
20
            .filter_map(|line| line.strip_prefix("(:id ")?.split_once(' ')?.0.parse().ok())
127
            .collect();
128
1
        ids.sort_unstable();
129
1
        assert_eq!(ids, (1..=20).collect::<Vec<_>>(), "{lines:?}");
130
1
        assert_eq!(transcript.exit_status, Some(0));
131
1
        assert!(!transcript.data_after_eof, "{transcript:?}");
132
1
        Ok(())
133
2
    })
134
    .await?;
135
}
136

            
137
#[local_db_sqlx_test]
138
async fn a_frame_over_one_mebibyte_gets_a_parse_reply_then_the_channel_ends(
139
    pool: PgPool,
140
) -> anyhow::Result<()> {
141
2
    run_with_user(&pool, async |addr, key| {
142
1
        let session = connected(addr, key).await?;
143
1
        let mut channel = open_subsystem(&session).await?;
144
1
        let oversized = format!("({}", "a".repeat(MAX_FRAME_BYTES));
145
1
        channel.data(oversized.as_bytes()).await?;
146
1
        let transcript = read_until_closed(&mut channel).await;
147
1
        let lines = response_lines(&transcript.output);
148
1
        assert_eq!(lines.len(), 1, "{lines:?}");
149
1
        assert!(
150
1
            lines[0].starts_with("(:id 0 :error (:code parse"),
151
            "{lines:?}"
152
        );
153
1
        assert!(transcript.closed, "{transcript:?}");
154
1
        Ok(())
155
2
    })
156
    .await?;
157
}
158

            
159
#[local_db_sqlx_test]
160
async fn stream_zero_bytes_are_unchanged_end_to_end(pool: PgPool) -> anyhow::Result<()> {
161
2
    run_with_user(&pool, async |addr, key| {
162
1
        let session = connected(addr, key).await?;
163
1
        let transcript = exchange(
164
1
            &session,
165
1
            b"(:id 1 :form (rpc-protocol-version))\n(:id 2 :stream 0 :form (rpc-protocol-version))\n",
166
1
        )
167
1
        .await?;
168
1
        assert_eq!(transcript.output, b"(:id 1 :value 1)\n(:id 2 :value 1)\n");
169
1
        Ok(())
170
2
    })
171
    .await?;
172
}
173

            
174
/// Eval forms of one frame each: a closed channel keeps draining them, answered `interrupted`.
175
1
fn many_frames() -> String {
176
1
    "(:id 1 :form 1)\n".repeat(20_000)
177
1
}
178

            
179
#[local_db_sqlx_test]
180
async fn a_closed_channel_counts_until_it_is_gone(pool: PgPool) -> anyhow::Result<()> {
181
2
    run_with_user(&pool, async |addr, key| {
182
1
        let session = connected(addr, key).await?;
183
1
        let closing = open_subsystem(&session).await?;
184
1
        let _idle = open_subsystem(&session).await?;
185
1
        closing.data(many_frames().as_bytes()).await?;
186
1
        closing.close().await?;
187
1
        let mut third = open_subsystem(&session).await?;
188
1
        third.eof().await?;
189
1
        let refused = read_until_closed(&mut third).await;
190
1
        assert!(refused.failed && refused.closed, "{refused:?}");
191

            
192
        let accepted = loop {
193
13
            let transcript = exchange(&session, b"(:id 2 :form (rpc-protocol-version))\n").await?;
194
13
            if !transcript.failed {
195
1
                break transcript;
196
12
            }
197
12
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
198
        };
199
1
        assert_eq!(response_lines(&accepted.output), ["(:id 2 :value 1)"]);
200
1
        Ok(())
201
2
    })
202
    .await?;
203
}