russh 0.65.4

A client and server SSH library.
Documentation
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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
use std::collections::HashMap;
use std::marker::Sync;
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant};

use byteorder::{BigEndian, ByteOrder};
use bytes::Bytes;
use futures::future::Future;
use futures::stream::{Stream, StreamExt};
use ssh_encoding::{Decode, Encode, Reader};
use ssh_key::{HashAlg, PrivateKey};
use subtle::ConstantTimeEq;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use {std, tokio};

use super::{Constraint, msg};
use crate::CryptoVec;
use crate::helpers::{EncodedExt, sign_with_hash_alg};
use crate::keys::Error;
use crate::keys::key::PrivateKeyWithHashAlg;

const MAX_AGENT_FRAME_LEN: usize = 256 * 1024;

#[derive(Clone)]
#[allow(clippy::type_complexity)]
struct KeyStore(Arc<RwLock<HashMap<Vec<u8>, (Arc<PrivateKey>, Option<Instant>, Vec<Constraint>)>>>);

impl KeyStore {
    fn purge_expired(&self) {
        if let Ok(mut keys) = self.0.write() {
            let now = Instant::now();
            keys.retain(|_, (_, expiry, _)| expiry.is_none_or(|expiry| expiry > now));
        }
    }
}

#[derive(Clone)]
struct Lock(Arc<RwLock<CryptoVec>>);

#[allow(missing_docs)]
#[derive(Debug)]
pub enum ServerError<E> {
    E(E),
    Error(Error),
}

pub enum MessageType {
    RequestKeys,
    AddKeys,
    RemoveKeys,
    RemoveAllKeys,
    Sign,
    Lock,
    Unlock,
}

pub trait Agent: Clone + Send + 'static {
    fn confirm(
        self,
        _pk: Arc<PrivateKey>,
    ) -> Box<dyn Future<Output = (Self, bool)> + Unpin + Send> {
        Box::new(futures::future::ready((self, true)))
    }

    fn confirm_request(&self, _msg: MessageType) -> impl Future<Output = bool> + Send {
        async { true }
    }
}

pub async fn serve<S, L, A>(mut listener: L, agent: A) -> Result<(), Error>
where
    S: AsyncRead + AsyncWrite + Send + Sync + Unpin + 'static,
    L: Stream<Item = tokio::io::Result<S>> + Unpin,
    A: Agent + Send + Sync + 'static,
{
    let keys = KeyStore(Arc::new(RwLock::new(HashMap::new())));
    let lock = Lock(Arc::new(RwLock::new(CryptoVec::new())));
    while let Some(Ok(stream)) = listener.next().await {
        russh_util::runtime::spawn(
            (Connection {
                lock: lock.clone(),
                keys: keys.clone(),
                agent: Some(agent.clone()),
                s: stream,
                buf: Vec::new(),
            })
            .run(),
        );
    }
    Ok(())
}

impl Agent for () {
    fn confirm(self, _: Arc<PrivateKey>) -> Box<dyn Future<Output = (Self, bool)> + Unpin + Send> {
        Box::new(futures::future::ready((self, true)))
    }
}

struct Connection<S: AsyncRead + AsyncWrite + Send + 'static, A: Agent> {
    lock: Lock,
    keys: KeyStore,
    agent: Option<A>,
    s: S,
    buf: Vec<u8>,
}

impl<S: AsyncRead + AsyncWrite + Send + Unpin + 'static, A: Agent + Send + Sync + 'static>
    Connection<S, A>
{
    async fn read_frame(&mut self) -> Result<(), Error> {
        self.buf.clear();
        self.buf.resize(4, 0);
        self.s.read_exact(&mut self.buf).await?;

        let len = BigEndian::read_u32(&self.buf) as usize;
        if len > MAX_AGENT_FRAME_LEN {
            return Err(Error::AgentProtocolError);
        }

        self.buf.clear();
        self.buf.resize(len, 0);
        self.s.read_exact(&mut self.buf).await?;
        Ok(())
    }

    async fn run(mut self) -> Result<(), Error> {
        let mut writebuf = Vec::new();
        loop {
            self.read_frame().await?;
            // respond
            writebuf.clear();
            self.respond(&mut writebuf).await?;
            self.s.write_all(&writebuf).await?;
            self.s.flush().await?
        }
    }

    async fn respond(&mut self, writebuf: &mut Vec<u8>) -> Result<(), Error> {
        self.keys.purge_expired();
        let is_locked = {
            if let Ok(password) = self.lock.0.read() {
                !password.is_empty()
            } else {
                true
            }
        };
        writebuf.extend_from_slice(&[0, 0, 0, 0]);
        let agentref = self.agent.as_ref().ok_or(Error::AgentFailure)?;

        match self.buf.split_first() {
            Some((&11, _))
                if !is_locked && agentref.confirm_request(MessageType::RequestKeys).await =>
            {
                // request identities
                if let Ok(keys) = self.keys.0.read() {
                    msg::IDENTITIES_ANSWER.encode(writebuf)?;
                    (keys.len() as u32).encode(writebuf)?;
                    for (k, _) in keys.iter() {
                        k.encode(writebuf)?;
                        "".encode(writebuf)?;
                    }
                } else {
                    msg::FAILURE.encode(writebuf)?
                }
            }
            Some((&13, mut r))
                if !is_locked && agentref.confirm_request(MessageType::Sign).await =>
            {
                // sign request
                let agent = self.agent.take().ok_or(Error::AgentFailure)?;
                let (agent, signed) = self.try_sign(agent, &mut r, writebuf).await?;
                self.agent = Some(agent);
                if signed {
                    return Ok(());
                } else {
                    writebuf.resize(4, 0);
                    writebuf.push(msg::FAILURE)
                }
            }
            Some((&17, mut r))
                if !is_locked && agentref.confirm_request(MessageType::AddKeys).await =>
            {
                // add identity
                if let Ok(true) = self.add_key(&mut r, false, writebuf).await {
                } else {
                    writebuf.push(msg::FAILURE)
                }
            }
            Some((&18, mut r))
                if !is_locked && agentref.confirm_request(MessageType::RemoveKeys).await =>
            {
                // remove identity
                if let Ok(true) = self.remove_identity(&mut r) {
                    writebuf.push(msg::SUCCESS)
                } else {
                    writebuf.push(msg::FAILURE)
                }
            }
            Some((&19, _))
                if !is_locked && agentref.confirm_request(MessageType::RemoveAllKeys).await =>
            {
                // remove all identities
                if let Ok(mut keys) = self.keys.0.write() {
                    keys.clear();
                    writebuf.push(msg::SUCCESS)
                } else {
                    writebuf.push(msg::FAILURE)
                }
            }
            Some((&22, mut r))
                if !is_locked && agentref.confirm_request(MessageType::Lock).await =>
            {
                // lock
                if let Ok(()) = self.lock(&mut r) {
                    writebuf.push(msg::SUCCESS)
                } else {
                    writebuf.push(msg::FAILURE)
                }
            }
            Some((&23, mut r))
                if is_locked && agentref.confirm_request(MessageType::Unlock).await =>
            {
                // unlock
                if let Ok(true) = self.unlock(&mut r) {
                    writebuf.push(msg::SUCCESS)
                } else {
                    writebuf.push(msg::FAILURE)
                }
            }
            Some((&25, mut r))
                if !is_locked && agentref.confirm_request(MessageType::AddKeys).await =>
            {
                // add identity constrained
                if let Ok(true) = self.add_key(&mut r, true, writebuf).await {
                } else {
                    writebuf.push(msg::FAILURE)
                }
            }
            _ => {
                // Message not understood
                writebuf.push(msg::FAILURE)
            }
        }
        let len = writebuf.len() - 4;
        BigEndian::write_u32(&mut writebuf[..], len as u32);
        Ok(())
    }

    fn lock<R: Reader>(&self, r: &mut R) -> Result<(), Error> {
        let password = Bytes::decode(r)?;
        let mut lock = self.lock.0.write().or(Err(Error::AgentFailure))?;
        // Two LOCK requests can both pass `confirm_request`. The second must
        // not append to the stored password
        if !lock.is_empty() {
            return Err(Error::AgentFailure);
        }
        lock.extend(&password);
        Ok(())
    }

    fn unlock<R: Reader>(&self, r: &mut R) -> Result<bool, Error> {
        let password = Bytes::decode(r)?;
        let mut lock = self.lock.0.write().or(Err(Error::AgentFailure))?;
        if bool::from(lock[..].ct_eq(&password)) {
            lock.clear();
            Ok(true)
        } else {
            Ok(false)
        }
    }

    fn remove_identity<R: Reader>(&self, r: &mut R) -> Result<bool, Error> {
        if let Ok(mut keys) = self.keys.0.write() {
            if keys.remove(&Bytes::decode(r)?.to_vec()).is_some() {
                Ok(true)
            } else {
                Ok(false)
            }
        } else {
            Ok(false)
        }
    }

    async fn add_key<R: Reader>(
        &self,
        r: &mut R,
        constrained: bool,
        writebuf: &mut Vec<u8>,
    ) -> Result<bool, Error> {
        let (blob, key_pair) = {
            let private_key =
                ssh_key::private::PrivateKey::new(ssh_key::private::KeypairData::decode(r)?, "")?;
            let _comment = String::decode(r)?;

            (private_key.public_key().key_data().encoded()?, private_key)
        };

        let mut c = Vec::new();
        let mut lifetime = None;
        if constrained {
            while let Ok(t) = u8::decode(r) {
                if t == msg::CONSTRAIN_LIFETIME {
                    if lifetime.is_some() {
                        return Ok(false);
                    }
                    let seconds = u32::decode(r)?;
                    lifetime = Some(seconds);
                    c.push(Constraint::KeyLifetime { seconds });
                } else if t == msg::CONSTRAIN_CONFIRM {
                    if !c.contains(&Constraint::Confirm) {
                        c.push(Constraint::Confirm)
                    }
                } else {
                    return Ok(false);
                }
            }
        }
        let expiry = lifetime
            .and_then(|seconds| Instant::now().checked_add(Duration::from_secs(seconds as u64)));
        self.keys
            .0
            .write()
            .or(Err(Error::AgentFailure))?
            .insert(blob, (Arc::new(key_pair), expiry, c));
        writebuf.push(msg::SUCCESS);
        Ok(true)
    }

    async fn try_sign<R: Reader>(
        &self,
        agent: A,
        r: &mut R,
        writebuf: &mut Vec<u8>,
    ) -> Result<(A, bool), Error> {
        let mut needs_confirm = false;
        let blob = Bytes::decode(r)?.to_vec();
        let key = {
            let k = self.keys.0.read().or(Err(Error::AgentFailure))?;
            if let Some((key, _, constraints)) = k.get(&blob) {
                if constraints.contains(&Constraint::Confirm) {
                    needs_confirm = true;
                }
                key.clone()
            } else {
                return Ok((agent, false));
            }
        };
        let agent = if needs_confirm {
            let (agent, ok) = agent.confirm(key.clone()).await;
            if !ok {
                return Ok((agent, false));
            }
            agent
        } else {
            agent
        };
        // The agent may have been locked, or the key removed or expired,
        // while `confirm_request` or `confirm` was pending. Nothing may await
        // between this check and the signature
        self.keys.purge_expired();
        let locked = self.lock.0.read().map(|p| !p.is_empty()).unwrap_or(true);
        let present = self
            .keys
            .0
            .read()
            .map(|k| k.contains_key(&blob))
            .unwrap_or(false);
        if locked || !present {
            return Ok((agent, false));
        }
        writebuf.push(msg::SIGN_RESPONSE);
        let data = Bytes::decode(r)?;
        let flags = u32::decode(r)?;

        let hash_alg = if flags & msg::SSH_AGENT_RSA_SHA2_256 != 0 {
            Some(HashAlg::Sha256)
        } else if flags & msg::SSH_AGENT_RSA_SHA2_512 != 0 {
            Some(HashAlg::Sha512)
        } else {
            None
        };

        sign_with_hash_alg(&PrivateKeyWithHashAlg::new(key, hash_alg), &data)?.encode(writebuf)?;

        let len = writebuf.len();
        BigEndian::write_u32(writebuf, (len - 4) as u32);

        Ok((agent, true))
    }
}

#[cfg(test)]
mod tests {
    use byteorder::{BigEndian, ByteOrder};
    use tokio::io::AsyncWriteExt;

    use super::{Connection, KeyStore, Lock, MAX_AGENT_FRAME_LEN};
    use crate::keys::Error;

    #[test]
    fn oversized_agent_request_is_rejected_before_allocation() -> std::io::Result<()> {
        let runtime = tokio::runtime::Builder::new_current_thread()
            .enable_all()
            .build()?;

        runtime.block_on(async {
            let (server, mut client) = tokio::io::duplex(64);
            let connection = Connection {
                lock: Lock(std::sync::Arc::new(std::sync::RwLock::new(
                    crate::CryptoVec::new(),
                ))),
                keys: KeyStore(std::sync::Arc::new(std::sync::RwLock::new(
                    std::collections::HashMap::new(),
                ))),
                agent: Some(()),
                s: server,
                buf: Vec::new(),
            };
            let server = tokio::spawn(async move { connection.run().await });

            let mut frame = [0u8; 4];
            BigEndian::write_u32(&mut frame, (MAX_AGENT_FRAME_LEN + 1) as u32);
            client.write_all(&frame).await?;
            drop(client);

            let err = server.await.expect("server task").unwrap_err();
            assert!(matches!(err, Error::AgentProtocolError));
            Ok::<(), std::io::Error>(())
        })?;

        Ok(())
    }

    #[tokio::test]
    async fn duplicate_confirm_constraints_are_stored_once() {
        use ssh_encoding::Encode;

        let (server, _client) = tokio::io::duplex(64);
        let connection = Connection {
            lock: Lock(std::sync::Arc::new(std::sync::RwLock::new(
                crate::CryptoVec::new(),
            ))),
            keys: KeyStore(std::sync::Arc::new(std::sync::RwLock::new(
                std::collections::HashMap::new(),
            ))),
            agent: Some(()),
            s: server,
            buf: Vec::new(),
        };

        let keypair = ssh_key::private::KeypairData::Ed25519(
            ssh_key::private::Ed25519Keypair::from_seed(&[7u8; 32]),
        );
        let mut payload = Vec::new();
        keypair.encode(&mut payload).unwrap();
        String::new().encode(&mut payload).unwrap();
        payload.resize(payload.len() + 10_000, super::msg::CONSTRAIN_CONFIRM);

        let mut writebuf = Vec::new();
        let mut r = &payload[..];
        assert!(connection.add_key(&mut r, true, &mut writebuf).await.unwrap());

        let keys = connection.keys.0.read().unwrap();
        let (_, _, constraints) = keys.values().next().unwrap();
        assert_eq!(constraints, &[super::Constraint::Confirm]);
    }

    #[tokio::test]
    async fn lifetime_constraint_expires_key_without_a_timer_task() {
        use ssh_encoding::Encode;

        let (server, _client) = tokio::io::duplex(64);
        let mut connection = Connection {
            lock: Lock(std::sync::Arc::new(std::sync::RwLock::new(
                crate::CryptoVec::new(),
            ))),
            keys: KeyStore(std::sync::Arc::new(std::sync::RwLock::new(
                std::collections::HashMap::new(),
            ))),
            agent: Some(()),
            s: server,
            buf: Vec::new(),
        };

        let add = |lifetime: u32| {
            let mut payload = Vec::new();
            ssh_key::private::KeypairData::Ed25519(
                ssh_key::private::Ed25519Keypair::from_seed(&[7u8; 32]),
            )
            .encode(&mut payload)
            .unwrap();
            String::new().encode(&mut payload).unwrap();
            payload.push(super::msg::CONSTRAIN_LIFETIME);
            lifetime.encode(&mut payload).unwrap();
            payload
        };

        // A timer task would hold a second reference to the keystore
        let payload = add(3600);
        assert!(
            connection
                .add_key(&mut &payload[..], true, &mut Vec::new())
                .await
                .unwrap()
        );
        connection.keys.purge_expired();
        assert_eq!(connection.keys.0.read().unwrap().len(), 1);
        assert_eq!(std::sync::Arc::strong_count(&connection.keys.0), 1);

        let payload = add(0);
        assert!(
            connection
                .add_key(&mut &payload[..], true, &mut Vec::new())
                .await
                .unwrap()
        );
        connection.buf = vec![11];
        let mut writebuf = Vec::new();
        connection.respond(&mut writebuf).await.unwrap();
        assert_eq!(writebuf[4], super::msg::IDENTITIES_ANSWER);
        assert_eq!(BigEndian::read_u32(&writebuf[5..9]), 0);
        assert!(connection.keys.0.read().unwrap().is_empty());
    }

    #[tokio::test]
    async fn sign_is_rejected_when_locked_during_confirm() {
        use std::future::Future;
        use std::sync::Arc;

        use ssh_encoding::Encode;
        use tokio::sync::Notify;

        use super::{Agent, Constraint};
        use crate::keys::PrivateKey;

        #[derive(Clone)]
        struct Delayed(Arc<Notify>, Arc<Notify>);
        impl Agent for Delayed {
            fn confirm(
                self,
                _: Arc<PrivateKey>,
            ) -> Box<dyn Future<Output = (Self, bool)> + Unpin + Send> {
                Box::new(Box::pin(async move {
                    self.0.notify_one();
                    self.1.notified().await;
                    (self, true)
                }))
            }
        }

        let entered = Arc::new(Notify::new());
        let release = Arc::new(Notify::new());
        let lock = Lock(std::sync::Arc::new(std::sync::RwLock::new(
            crate::CryptoVec::new(),
        )));
        let (server, _client) = tokio::io::duplex(64);
        let connection = Connection {
            lock: lock.clone(),
            keys: KeyStore(std::sync::Arc::new(std::sync::RwLock::new(
                std::collections::HashMap::new(),
            ))),
            agent: Some(Delayed(entered.clone(), release.clone())),
            s: server,
            buf: Vec::new(),
        };

        let key = PrivateKey::random(&mut rand::rng(), crate::keys::Algorithm::Ed25519)
            .unwrap();
        let blob = key.public_key().to_bytes().unwrap();
        connection.keys.0.write().unwrap().insert(
            blob.clone(),
            (Arc::new(key), None, vec![Constraint::Confirm]),
        );

        let mut payload = Vec::new();
        blob.encode(&mut payload).unwrap();
        b"data".encode(&mut payload).unwrap();
        0u32.encode(&mut payload).unwrap();

        let signer = async {
            let mut writebuf = Vec::new();
            let agent = connection.agent.clone().unwrap();
            connection
                .try_sign(agent, &mut &payload[..], &mut writebuf)
                .await
                .unwrap()
                .1
        };
        let locker = async {
            entered.notified().await;
            lock.0.write().unwrap().extend(b"pw");
            release.notify_one();
        };
        let (signed, ()) = tokio::join!(signer, locker);
        assert!(!signed);
    }

    #[tokio::test]
    async fn sign_is_rejected_when_locked_during_confirm_request() {
        use std::future::Future;
        use std::sync::Arc;

        use ssh_encoding::Encode;
        use tokio::sync::Notify;

        use super::{Agent, MessageType, msg};
        use crate::keys::PrivateKey;

        #[derive(Clone)]
        struct Delayed(Arc<Notify>, Arc<Notify>);
        impl Agent for Delayed {
            fn confirm_request(&self, _: MessageType) -> impl Future<Output = bool> + Send {
                async move {
                    self.0.notify_one();
                    self.1.notified().await;
                    true
                }
            }
        }

        let entered = Arc::new(Notify::new());
        let release = Arc::new(Notify::new());
        let lock = Lock(std::sync::Arc::new(std::sync::RwLock::new(
            crate::CryptoVec::new(),
        )));
        let (server, _client) = tokio::io::duplex(64);
        let mut connection = Connection {
            lock: lock.clone(),
            keys: KeyStore(std::sync::Arc::new(std::sync::RwLock::new(
                std::collections::HashMap::new(),
            ))),
            agent: Some(Delayed(entered.clone(), release.clone())),
            s: server,
            buf: Vec::new(),
        };

        // Without a confirm constraint `Agent::confirm` is never called
        let key = PrivateKey::random(&mut rand::rng(), crate::keys::Algorithm::Ed25519)
            .unwrap();
        let blob = key.public_key().to_bytes().unwrap();
        connection.keys.0.write().unwrap().insert(
            blob.clone(),
            (Arc::new(key), None, vec![]),
        );

        connection.buf.push(msg::SIGN_REQUEST);
        blob.encode(&mut connection.buf).unwrap();
        b"data".as_slice().encode(&mut connection.buf).unwrap();
        0u32.encode(&mut connection.buf).unwrap();

        let mut writebuf = Vec::new();
        let signer = async {
            connection.respond(&mut writebuf).await.unwrap();
        };
        let locker = async {
            entered.notified().await;
            lock.0.write().unwrap().extend(b"pw");
            release.notify_one();
        };
        tokio::join!(signer, locker);
        assert_eq!(writebuf, [0, 0, 0, 1, msg::FAILURE]);
    }

    #[test]
    fn lock_does_not_append_to_an_existing_password() {
        use ssh_encoding::Encode;

        let (server, _client) = tokio::io::duplex(64);
        let connection = Connection {
            lock: Lock(std::sync::Arc::new(std::sync::RwLock::new(
                crate::CryptoVec::new(),
            ))),
            keys: KeyStore(std::sync::Arc::new(std::sync::RwLock::new(
                std::collections::HashMap::new(),
            ))),
            agent: Some(()),
            s: server,
            buf: Vec::new(),
        };

        let mut payload = Vec::new();
        b"pw".as_slice().encode(&mut payload).unwrap();
        connection.lock(&mut &payload[..]).unwrap();
        assert!(connection.lock(&mut &payload[..]).is_err());
        assert_eq!(&connection.lock.0.read().unwrap()[..], b"pw");
    }
}