Merge main (6e0df51) into phase5/ui-vm-2
Main gained phase0/ci-private-dependency (the CI deploy key and the checks action), phase5/media-codec-test (a media test stated for machines without an H.264 encoder) and phase4/seam-followups (five flaky tests fixed, the identity-text leak closed, docs/session-seam.md 17.8 onwards). None of it touches the UI crates: the merge is clean, with no conflict, and Cargo.lock and THIRD_PARTY_NOTICES.md are unchanged by it. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
9e7452ec2a
24 files changed
+989
-89
No files matched your search
@@ -453,10 +453,15 @@ mod tests {
|
||||
lookups
|
||||
}
|
||||
|
||||
/// `lookups` asking the real `/.well-known/tsgw` at `port`.
|
||||
/// `lookups` asking the real `/.well-known/tsgw` at `port`. A name is
|
||||
/// connected to through the system's resolver, except `localhost`: the
|
||||
/// servers of the tests listen on 127.0.0.1, and some machines resolve
|
||||
/// `localhost` to `::1` only. (The test cares that the gateway is asked at
|
||||
/// the name `localhost`, not what the resolver makes of it.)
|
||||
fn probing(mut lookups: Lookups, port: u16) -> Lookups {
|
||||
lookups.probe = Arc::new(move |name| {
|
||||
async move { timeout(PROBE_TIMEOUT, well_known(&name, port)).await.ok()?.ok() }.boxed()
|
||||
let host = if name == "localhost" { "127.0.0.1".to_owned() } else { name };
|
||||
async move { timeout(PROBE_TIMEOUT, well_known(&host, port)).await.ok()?.ok() }.boxed()
|
||||
});
|
||||
lookups
|
||||
}
|
||||
|
||||
@@ -166,9 +166,13 @@ impl Backends {
|
||||
self.register_local(Arc::new(connector));
|
||||
}
|
||||
|
||||
/// The device's Voelin account, for the connectors that use it (the QUIC
|
||||
/// connector's certificate, the TeamSpeak connector's myTS ID proof).
|
||||
/// None is the default: nothing uses an account yet.
|
||||
/// The device's Voelin account, which every connect hands the connector as
|
||||
/// `ConnectParams::account`. No connector reads it yet: the TeamSpeak
|
||||
/// connector takes the myTeamSpeak account it presents from its own setters
|
||||
/// ([`TsConnector::set_myts_identity`], [`TsConnector::set_myts_data`]), and a
|
||||
/// Voelin host's connector (the QUIC one, for its certificate) does not exist
|
||||
/// yet. Follow-up H4 of `docs/session-seam.md` (11.2) moves the myTeamSpeak
|
||||
/// proof from those setters to this hook. None is the default.
|
||||
pub fn set_account(&mut self, agent: Option<Arc<dyn AccountAgent>>) {
|
||||
self.account = agent;
|
||||
}
|
||||
|
||||
@@ -64,6 +64,10 @@ pub struct VoiceOptions {
|
||||
/// scheme (`ts3server://`, `teamspeak://`, a Voelin host's `voelin://`)
|
||||
/// that picks the connector ([`Backends`]).
|
||||
pub address: String,
|
||||
/// The name shown on the server: `Hello.nickname` to a Voelin host, the
|
||||
/// client name on a TeamSpeak server (which may refuse or change it). When
|
||||
/// it is empty, the `nickname` parameter of an `address` that is a
|
||||
/// TeamSpeak link applies.
|
||||
pub nickname: String,
|
||||
/// The identity to connect with: a TeamSpeak identity
|
||||
/// ([`crate::ts::identity::to_blob`]) for a TeamSpeak server, a Voelin key
|
||||
@@ -76,6 +80,10 @@ pub struct VoiceOptions {
|
||||
/// `<platform>@<version>`); `None` is the native platform's. A spec that is
|
||||
/// none ends the connect with the reason. Other backends ignore it.
|
||||
pub client_version: Option<String>,
|
||||
/// The password of the server (`Hello.password`), for one that has a
|
||||
/// password. When it is `None` or empty, the `password` parameter of an
|
||||
/// `address` that is a TeamSpeak link applies. Not the password of
|
||||
/// `channel` (that is `channel_password`).
|
||||
pub server_password: Option<String>,
|
||||
/// Channel path to join, e.g. `Lobby/Sub`, or `/<id>`.
|
||||
pub channel: Option<String>,
|
||||
|
||||
@@ -981,6 +981,32 @@ async fn a_connect_that_fails_is_a_disconnect_with_the_reason() {
|
||||
);
|
||||
}
|
||||
|
||||
/// An identity that cannot be read ends the connect with a disconnect whose
|
||||
/// text says where it is wrong and holds none of the key: the JSON reader's
|
||||
/// own message quotes a key that does not import, and the engine shows this
|
||||
/// text as the error of the connection.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn an_identity_that_cannot_be_read_is_a_disconnect_without_the_key() {
|
||||
let (json, cut) = crate::ts::identity::json_with_a_cut_key();
|
||||
let mut options = VoiceOptions::new("ts3server://127.0.0.1:9", "tester");
|
||||
options.identity = Some(IdentityBlob::teamspeak("uid=", 8, json));
|
||||
let link = SessionLink::new(Backends::default());
|
||||
let (_cmd_tx, cmd_rx) = mpsc::unbounded_channel();
|
||||
let (event_tx, mut events) = mpsc::unbounded_channel();
|
||||
link.spawn(options, LocalCtx::standalone().link, cmd_rx, event_tx);
|
||||
let event = within("the end", events.recv()).await;
|
||||
let LinkEvent::Disconnected(Some(text)) = event else {
|
||||
panic!("a disconnect with the reason of the refusal")
|
||||
};
|
||||
assert!(
|
||||
text.starts_with(
|
||||
"the TeamSpeak identity cannot be read: not an identity at line 1, column "
|
||||
),
|
||||
"{text}"
|
||||
);
|
||||
crate::ts::identity::assert_holds_no_piece_of(&text, &cut);
|
||||
}
|
||||
|
||||
// ---- the TeamSpeak side alone ---------------------------------------------------
|
||||
|
||||
/// A `LinkSession` over a recorder, made the way a connector makes it.
|
||||
|
||||
@@ -3410,7 +3410,14 @@ mod tests {
|
||||
assert!(all.is_hardware(backend), "{codec} offered in software");
|
||||
}
|
||||
if all.encoder_codecs().contains(&Codec::H264) && !offer.contains(&Codec::H264) {
|
||||
assert_eq!(offer_codecs(&all, Codec::H264)[..2], [Codec::H264, Codec::Vp8]);
|
||||
// H.264 in software only (so not in `offer`): it leads the same
|
||||
// codecs as with VP8 as the stream codec, whichever hardware
|
||||
// encoders this machine has (a hardware AV1 or VP9 encoder ranks
|
||||
// before VP8, so VP8 is not always second).
|
||||
let h264 = offer_codecs(&all, Codec::H264);
|
||||
assert_eq!(h264[0], Codec::H264, "{h264:?}");
|
||||
assert_eq!(h264.len(), offer.len() + 1, "{h264:?} against {offer:?}");
|
||||
assert!(offer.iter().all(|c| h264.contains(c)), "{h264:?} against {offer:?}");
|
||||
}
|
||||
// Whatever this machine has: codecs every TeamSpeak client decodes
|
||||
// come before H.264, HEVC last, and the automatic stream codec is
|
||||
@@ -3423,10 +3430,23 @@ mod tests {
|
||||
let ranks: Vec<_> = offer[1..].iter().map(rank).collect();
|
||||
assert!(ranks.is_sorted(), "{offer:?}");
|
||||
assert!(preferred_codec(&all, None).is_some_and(decoded_everywhere), "{all:?}");
|
||||
assert_eq!(
|
||||
preferred_codec(&all, Some(Codec::H264)).is_some(),
|
||||
all.encoder_codecs().contains(&Codec::H264)
|
||||
);
|
||||
// A configured codec is the stream codec when this machine can encode
|
||||
// it; otherwise the result is the automatic choice,
|
||||
// `preferred_codec(&all, None)` (some codec on any machine that
|
||||
// encodes anything). Whether H.264 is encodable depends on the
|
||||
// machine (a desktop with FFmpeg or a GPU has an encoder, a CI
|
||||
// runner has none), so the expectation follows `all.encoder_codecs()`.
|
||||
let h264 = preferred_codec(&all, Some(Codec::H264));
|
||||
if all.encoder_codecs().contains(&Codec::H264) {
|
||||
assert_eq!(h264, Some(Codec::H264), "{all:?}");
|
||||
} else {
|
||||
assert_eq!(h264, preferred_codec(&all, None), "{all:?}");
|
||||
}
|
||||
// The built-in codecs are the same everywhere (no OpenH264 loaded):
|
||||
// VP9 is encodable and wins, H.264 is not and falls back to VP8.
|
||||
assert_eq!(preferred_codec(&codecs, Some(Codec::Vp9)), Some(Codec::Vp9));
|
||||
assert_eq!(preferred_codec(&codecs, Some(Codec::H264)), preferred_codec(&codecs, None));
|
||||
assert_eq!(preferred_codec(&codecs, None), Some(Codec::Vp8));
|
||||
}
|
||||
|
||||
/// A sink whose viewers chose `codecs`; keeps every video frame with its
|
||||
|
||||
@@ -255,8 +255,20 @@ pub fn from_blob(blob: &IdentityBlob) -> Result<Identity, IdentityError> {
|
||||
blob.kind
|
||||
)));
|
||||
}
|
||||
serde_json::from_str(&blob.json).map_err(|e| {
|
||||
// Where the JSON is wrong, not what it says: it holds a private key.
|
||||
from_json(&blob.json)
|
||||
}
|
||||
|
||||
/// The TeamSpeak identity in `json`, the text [`to_blob`] writes and the key
|
||||
/// store keeps; every reader of that text refuses it through here.
|
||||
///
|
||||
/// What does not read is refused in words that say how it is wrong
|
||||
/// (malformed, cut short, not an identity, unreadable) and where (line and
|
||||
/// column), and never what it holds: the text holds a private key, and the
|
||||
/// message of the JSON reader quotes a value it refuses (`tsproto` reports a
|
||||
/// key that does not import as an invalid value, the key string and all), so
|
||||
/// that message is never shown, not in an error, an event or a log.
|
||||
pub(crate) fn from_json(json: &str) -> Result<Identity, IdentityError> {
|
||||
serde_json::from_str(json).map_err(|e| {
|
||||
let what = match e.classify() {
|
||||
serde_json::error::Category::Syntax => "malformed",
|
||||
serde_json::error::Category::Eof => "cut short",
|
||||
@@ -271,6 +283,27 @@ pub fn from_blob(blob: &IdentityBlob) -> Result<Identity, IdentityError> {
|
||||
})
|
||||
}
|
||||
|
||||
/// The JSON of a fresh identity whose key lost its last two characters (a key
|
||||
/// that does not import), and that cut key.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn json_with_a_cut_key() -> (String, String) {
|
||||
let mut json = serde_json::to_value(Identity::create()).unwrap();
|
||||
let key = json["key"].as_str().unwrap().to_owned();
|
||||
let cut = key[..key.len() - 2].to_owned();
|
||||
json["key"] = cut.clone().into();
|
||||
(json.to_string(), cut)
|
||||
}
|
||||
|
||||
/// Fail if `text` holds any 8 characters in a row of `secret`.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn assert_holds_no_piece_of(text: &str, secret: &str) {
|
||||
assert!(secret.len() >= 8 && secret.is_ascii());
|
||||
for piece in secret.as_bytes().windows(8) {
|
||||
let piece = std::str::from_utf8(piece).unwrap();
|
||||
assert!(!text.contains(piece), "{text:?} holds {piece:?} of the key");
|
||||
}
|
||||
}
|
||||
|
||||
/// The TeamSpeak 3 `.ini` export of an identity, which the official client
|
||||
/// and every other tool reads.
|
||||
pub fn export(nickname: &str, identity: &Identity) -> String {
|
||||
@@ -615,18 +648,43 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The JSON reader's own message quotes a key that does not import, so the
|
||||
/// refusal is worded by `from_json` and holds none of the key.
|
||||
#[test]
|
||||
fn a_key_that_does_not_import_is_refused_without_quoting_it() {
|
||||
let (json, cut) = json_with_a_cut_key();
|
||||
let raw = serde_json::from_str::<Identity>(&json).unwrap_err().to_string();
|
||||
assert!(raw.contains(&cut), "the reader's own message quotes the key: {raw}");
|
||||
for error in [
|
||||
from_json(&json).unwrap_err().to_string(),
|
||||
from_blob(&IdentityBlob::teamspeak("x", 8, json.clone())).unwrap_err().to_string(),
|
||||
] {
|
||||
assert!(
|
||||
error.starts_with(
|
||||
"the TeamSpeak identity cannot be read: not an identity at line 1, column "
|
||||
),
|
||||
"{error}"
|
||||
);
|
||||
assert_holds_no_piece_of(&error, &cut);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn improve_level_keeps_the_key() {
|
||||
let identity = synthetic();
|
||||
// A fresh identity stops at the first counter whose level is 8 or more,
|
||||
// and about one in 32 has 13 or more already, which `improve_level`
|
||||
// returns as it is: ask for more than this one has, whatever it has.
|
||||
let target = identity.level() + 3;
|
||||
let levels = std::sync::Mutex::new(Vec::new());
|
||||
let better = improve_level(&identity, 13, &AtomicBool::new(false), |l| {
|
||||
let better = improve_level(&identity, target, &AtomicBool::new(false), |l| {
|
||||
levels.lock().unwrap().push(l);
|
||||
})
|
||||
.unwrap();
|
||||
assert!(better.level() >= 13);
|
||||
assert!(better.level() >= target);
|
||||
assert_eq!(better.key().to_pub().get_uid(), identity.key().to_pub().get_uid());
|
||||
assert!(better.counter() > identity.counter());
|
||||
assert!(levels.into_inner().unwrap().iter().any(|l| *l >= 13));
|
||||
assert!(levels.into_inner().unwrap().iter().any(|l| *l >= target));
|
||||
// Cancelled: nothing.
|
||||
assert!(improve_level(&identity, 60, &AtomicBool::new(true), |_| {}).is_none());
|
||||
// Already there: the same identity.
|
||||
|
||||
@@ -43,7 +43,7 @@ use voelin_proto::link::{
|
||||
use voelin_proto::v1::{self, response::Result as Answer};
|
||||
|
||||
use self::driver::{Cmd, Config, Driver, Parts, rejected};
|
||||
use super::{ConnectOptions, ServerLink, TsLink, versions};
|
||||
use super::{ConnectOptions, ServerLink, TsLink, identity, versions};
|
||||
use crate::BackendInfo;
|
||||
use crate::link::{
|
||||
BoxDuplex, LinkCmd, LinkCtx, LinkEvent, LocalConnected, LocalConnector, LocalCtx, StreamPort,
|
||||
@@ -82,9 +82,14 @@ fn inner_options(params: &ConnectParams, ctx: &LocalCtx) -> Result<ConnectOption
|
||||
let identity = match ¶ms.credential {
|
||||
Credential::Foreign { kind: IDENTITY_KIND, blob } if blob.is_empty() => None,
|
||||
Credential::Foreign { kind: IDENTITY_KIND, blob } => {
|
||||
Some(serde_json::from_slice(blob).map_err(|e| {
|
||||
SessionError::Protocol(format!("the TeamSpeak identity cannot be read: {e}"))
|
||||
})?)
|
||||
// The refusal never quotes the JSON: it holds the private key, and the
|
||||
// JSON reader's own message would show a key that does not import.
|
||||
let json = std::str::from_utf8(blob).map_err(|_| {
|
||||
SessionError::Protocol(
|
||||
"the TeamSpeak identity cannot be read: it is not text".into(),
|
||||
)
|
||||
})?;
|
||||
Some(identity::from_json(json).map_err(|e| SessionError::Protocol(e.to_string()))?)
|
||||
}
|
||||
_ => {
|
||||
return Err(SessionError::Protocol(
|
||||
@@ -754,6 +759,33 @@ mod tests {
|
||||
assert!(!futures::executor::block_on(confirm));
|
||||
}
|
||||
|
||||
/// An identity that cannot be read ends the connect with words that say
|
||||
/// where it is wrong and hold none of the key: the JSON reader's own
|
||||
/// message quotes a key that does not import, and this text reaches the
|
||||
/// event bus and the status line.
|
||||
#[test]
|
||||
fn an_identity_that_cannot_be_read_is_refused_without_the_key() {
|
||||
let (json, cut) = identity::json_with_a_cut_key();
|
||||
let mut sent = params(&VoiceOptions::new("ts.example.com", "nick"));
|
||||
sent.credential = Credential::Foreign { kind: "teamspeak", blob: Bytes::from(json) };
|
||||
let error = inner_options(&sent, &LocalCtx::standalone()).unwrap_err();
|
||||
let SessionError::Protocol(text) = error else { panic!("a protocol error: {error:?}") };
|
||||
assert!(
|
||||
text.starts_with(
|
||||
"the TeamSpeak identity cannot be read: not an identity at line 1, column "
|
||||
),
|
||||
"{text}"
|
||||
);
|
||||
identity::assert_holds_no_piece_of(&text, &cut);
|
||||
|
||||
// Not even text.
|
||||
sent.credential =
|
||||
Credential::Foreign { kind: "teamspeak", blob: Bytes::from_static(&[b'{', 0xff]) };
|
||||
let error = inner_options(&sent, &LocalCtx::standalone()).unwrap_err();
|
||||
let SessionError::Protocol(text) = error else { panic!("a protocol error: {error:?}") };
|
||||
assert_eq!(text, "the TeamSpeak identity cannot be read: it is not text");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_params_carry_what_the_session_needs_and_no_account_yet() {
|
||||
let sent = params(&VoiceOptions::new("ts.example.com", "nick"));
|
||||
|
||||
@@ -960,11 +960,27 @@ pub(crate) mod tests {
|
||||
|
||||
/// What `f` logs at info (and above) on this thread: each line its
|
||||
/// message, then its fields (` name=value`).
|
||||
///
|
||||
/// One recording subscriber is installed for the whole test process, the
|
||||
/// first time this is called, and each call records into a buffer of its
|
||||
/// own thread. A scoped one (`tracing::subscriber::with_default`) loses
|
||||
/// lines: while it is the only subscriber alive, a callsite that another
|
||||
/// test's thread meets first is registered against that thread's own
|
||||
/// default, which is none, and stays disabled for every thread, so the
|
||||
/// lines of the test that reads them are gone
|
||||
/// (`session::banner_tests::a_failing_banner_is_logged_once_with_its_address`
|
||||
/// failed with no lines at all, once in about thirty runs of the suite).
|
||||
pub(crate) fn info_lines<T>(f: impl FnOnce() -> T) -> (T, Vec<String>) {
|
||||
use std::cell::RefCell;
|
||||
use std::sync::Once;
|
||||
use tracing::field::{Field, Visit};
|
||||
use tracing::span;
|
||||
|
||||
struct Lines(Arc<Mutex<Vec<String>>>);
|
||||
thread_local! {
|
||||
/// The lines of the `info_lines` running on this thread, if any.
|
||||
static LINES: RefCell<Option<Vec<String>>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Line(String, String);
|
||||
impl Visit for Line {
|
||||
@@ -975,7 +991,8 @@ pub(crate) mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
impl tracing::Subscriber for Lines {
|
||||
struct Recorder;
|
||||
impl tracing::Subscriber for Recorder {
|
||||
fn enabled(&self, metadata: &tracing::Metadata<'_>) -> bool {
|
||||
*metadata.level() <= tracing::Level::INFO
|
||||
}
|
||||
@@ -985,19 +1002,57 @@ pub(crate) mod tests {
|
||||
fn record(&self, _: &span::Id, _: &span::Record<'_>) {}
|
||||
fn record_follows_from(&self, _: &span::Id, _: &span::Id) {}
|
||||
fn event(&self, event: &tracing::Event<'_>) {
|
||||
let mut line = Line::default();
|
||||
event.record(&mut line);
|
||||
self.0.lock().unwrap().push(line.0 + &line.1);
|
||||
LINES.with(|lines| {
|
||||
if let Some(lines) = lines.borrow_mut().as_mut() {
|
||||
let mut line = Line::default();
|
||||
event.record(&mut line);
|
||||
lines.push(line.0 + &line.1);
|
||||
}
|
||||
});
|
||||
}
|
||||
fn enter(&self, _: &span::Id) {}
|
||||
fn exit(&self, _: &span::Id) {}
|
||||
}
|
||||
let lines = Arc::new(Mutex::new(Vec::new()));
|
||||
let result = tracing::subscriber::with_default(Lines(lines.clone()), f);
|
||||
let lines = lines.lock().unwrap().clone();
|
||||
/// Ends the recording of this thread, also when `f` panics.
|
||||
struct Recording;
|
||||
impl Drop for Recording {
|
||||
fn drop(&mut self) {
|
||||
LINES.with(|lines| lines.borrow_mut().take());
|
||||
}
|
||||
}
|
||||
|
||||
static INSTALL: Once = Once::new();
|
||||
INSTALL.call_once(|| {
|
||||
tracing::subscriber::set_global_default(Recorder)
|
||||
.expect("no other global tracing subscriber in the tests");
|
||||
// Makes every callsite decide again with the subscriber in place, also
|
||||
// one that a thread was registering while it was being installed
|
||||
// (creating a `Dispatch` rebuilds the cached interest of all of them).
|
||||
drop(tracing::Dispatch::new(Recorder));
|
||||
});
|
||||
|
||||
LINES.with(|lines| *lines.borrow_mut() = Some(Vec::new()));
|
||||
let _recording = Recording;
|
||||
let result = f();
|
||||
let lines = LINES.with(|lines| lines.borrow_mut().take().unwrap_or_default());
|
||||
(result, lines)
|
||||
}
|
||||
|
||||
/// The lines of `info_lines` do not depend on which thread met a callsite
|
||||
/// first: this one is met on another thread, which records nothing, before
|
||||
/// the thread that reads the lines meets it.
|
||||
#[test]
|
||||
fn info_lines_see_a_callsite_another_thread_met_first() {
|
||||
fn log() {
|
||||
tracing::info!("met");
|
||||
}
|
||||
let ((), lines) = info_lines(|| {
|
||||
std::thread::spawn(log).join().unwrap();
|
||||
log();
|
||||
});
|
||||
assert_eq!(lines, ["met"]);
|
||||
}
|
||||
|
||||
fn temp_dir(tag: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("voelin-web-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
@@ -1375,9 +1430,15 @@ pub(crate) mod tests {
|
||||
};
|
||||
let mut port = [0u8; 2];
|
||||
client.read_exact(&mut port).await.unwrap();
|
||||
let target = format!("{host}:{}", u16::from_be_bytes(port));
|
||||
let port = u16::from_be_bytes(port);
|
||||
let target = format!("{host}:{port}");
|
||||
targets.send(target.clone()).unwrap();
|
||||
let mut server = TcpStream::connect(target).await.unwrap();
|
||||
// The proxy resolves the name it is given (SOCKS5h). `localhost` is
|
||||
// 127.0.0.1 to it, whatever this machine's resolver says: some answer
|
||||
// `::1` only, and the servers of the tests listen on 127.0.0.1.
|
||||
let dial =
|
||||
if host == "localhost" { format!("127.0.0.1:{port}") } else { target };
|
||||
let mut server = TcpStream::connect(dial).await.unwrap();
|
||||
client.write_all(&[5, 0, 0, 1, 0, 0, 0, 0, 0, 0]).await.unwrap();
|
||||
let _ = tokio::io::copy_bidirectional(&mut client, &mut server).await;
|
||||
});
|
||||
|
||||
@@ -10,7 +10,9 @@
|
||||
//! dedup of a message that comes twice, history, transfers, offline messages,
|
||||
//! the features of a host, a reconnect and the media of a session are the
|
||||
//! engine's own behaviour; nothing here needs a TeamSpeak server or a
|
||||
//! TeamSpeak type.
|
||||
//! TeamSpeak type, except `a_teamspeak_identity_that_cannot_be_read_is_refused_without_the_key`,
|
||||
//! which runs the engine's own TeamSpeak connector up to its refusal of an
|
||||
//! identity.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
@@ -163,6 +165,12 @@ impl Harness {
|
||||
fn on(connector: FakeConnector) -> Self {
|
||||
let mut backends = Backends::empty();
|
||||
backends.register(Arc::new(connector.clone()));
|
||||
Self::with_backends(backends, connector)
|
||||
}
|
||||
|
||||
/// The engine on `backends`; `connector` is the fake host the test may
|
||||
/// have registered in them (a test that registers none leaves it unused).
|
||||
fn with_backends(backends: Backends, connector: FakeConnector) -> Self {
|
||||
let engine =
|
||||
Engine::start_with_backends(Settings::in_memory(), History::in_memory(), backends);
|
||||
let events = engine.subscribe();
|
||||
@@ -1502,3 +1510,46 @@ async fn a_teamspeak_identity_without_json_is_refused_and_no_session_is_made() {
|
||||
assert!(handle.close_reason().is_none());
|
||||
assert_eq!(h.connector.connects().len(), 1);
|
||||
}
|
||||
|
||||
/// A TeamSpeak identity whose key does not import ends the connect with words
|
||||
/// that say where the JSON is wrong and never show the key: the JSON reader's
|
||||
/// own message quotes it, and the text is the reason of the disconnect, the
|
||||
/// `Error` event and the status line the UI makes of it. This is the one test
|
||||
/// of the file that runs the engine's own TeamSpeak connector
|
||||
/// (`Backends::default()`): the refusal is that connector's and comes before
|
||||
/// any network.
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn a_teamspeak_identity_that_cannot_be_read_is_refused_without_the_key() {
|
||||
let mut json = serde_json::to_value(tsclientlib::Identity::create()).unwrap();
|
||||
let key = json["key"].as_str().unwrap().to_owned();
|
||||
// The key lost its last two characters.
|
||||
let cut = key[..key.len() - 2].to_owned();
|
||||
json["key"] = cut.clone().into();
|
||||
let mut options = VoiceOptions::new("ts3server://127.0.0.1:9", "tester");
|
||||
options.identity = Some(IdentityBlob::teamspeak("uid=", 8, json.to_string()));
|
||||
|
||||
let mut h = Harness::with_backends(Backends::default(), FakeConnector::new());
|
||||
h.engine.send(Command::ConnectVoice { session: SESSION, options: Box::new(options) });
|
||||
let state = h.state(|s| s.voice == VoiceState::Disconnected).await;
|
||||
assert_eq!((state.own_channel, state.own_client), (None, None));
|
||||
let error = h.error().await;
|
||||
assert!(
|
||||
error.starts_with(
|
||||
"voice: the TeamSpeak identity cannot be read: not an identity at line 1, column "
|
||||
),
|
||||
"{error}"
|
||||
);
|
||||
// Nothing the engine reported afterwards holds a piece of the key either.
|
||||
let mut shown = vec![error];
|
||||
while let Ok(Ok(event)) =
|
||||
tokio::time::timeout(Duration::from_millis(300), h.events.recv()).await
|
||||
{
|
||||
shown.push(format!("{event:?}"));
|
||||
}
|
||||
for text in &shown {
|
||||
for piece in cut.as_bytes().windows(8) {
|
||||
let piece = std::str::from_utf8(piece).unwrap();
|
||||
assert!(!text.contains(piece), "{text:?} holds {piece:?} of the key");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
//! in the client database). The round trips against real servers are in
|
||||
//! `scripts/it-smoke.sh` (`voelinctl engine`).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use tokio::sync::broadcast;
|
||||
@@ -22,6 +23,29 @@ async fn next<T>(rx: &mut broadcast::Receiver<Event>, mut f: impl FnMut(Event) -
|
||||
.expect("event in time")
|
||||
}
|
||||
|
||||
/// Wait until nothing has the SQLite database at `path` open any more, as when
|
||||
/// the process that had it has ended: SQLite deletes the write-ahead log
|
||||
/// (`<path>-wal`) when the last connection closes.
|
||||
///
|
||||
/// A dropped `Engine` is not that yet. Its task ends later, the history writer
|
||||
/// is joined there, and closing the connection checkpoints the log under an
|
||||
/// exclusive lock, with fsyncs. A connection opened meanwhile waits for the
|
||||
/// lock only as long as the busy timeout (5 s) and then fails with
|
||||
/// `DatabaseBusy`, which a loaded disk makes happen (with every fsync taking
|
||||
/// 6 s it happens every time).
|
||||
async fn closed(path: &Path) {
|
||||
let mut wal = path.as_os_str().to_owned();
|
||||
wal.push("-wal");
|
||||
let wal = PathBuf::from(wal);
|
||||
tokio::time::timeout(Duration::from_secs(120), async {
|
||||
while wal.exists() {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("the engine's database connection closed");
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn requests_without_voice_fail_with_their_ids() {
|
||||
let engine = Engine::start();
|
||||
@@ -165,6 +189,7 @@ async fn contacts_are_kept_in_the_database() {
|
||||
engine.history().flush();
|
||||
}
|
||||
// A new engine attaches the database later: the contacts come back.
|
||||
closed(&path).await;
|
||||
let engine = Engine::start();
|
||||
let mut rx = engine.subscribe();
|
||||
engine.send(Command::AttachHistory(History::open(&path).unwrap()));
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
# Build: docker build -f crates/voelin-gateway/Dockerfile -t tsgw .
|
||||
# syntax=docker/dockerfile:1
|
||||
# Build: docker build --ssh default -f crates/voelin-gateway/Dockerfile -t tsgw .
|
||||
# (--ssh default hands the build your ssh-agent, which must hold a key that
|
||||
# can read the private VoelinProtocol repository: docs/building.md,
|
||||
# "Depending on VoelinProtocol". The gateway itself does not use it, but
|
||||
# Cargo resolves the whole workspace, which includes voelin-identity.)
|
||||
# Run: docker run -d --name tsgw --init --restart unless-stopped \
|
||||
# -v ./tsgw.toml:/etc/tsgw/tsgw.toml:ro -v tsgw-data:/var/lib/tsgw \
|
||||
# -e TSGW_QUERY_PASSWORD=… -p 7788:7788 tsgw
|
||||
@@ -6,9 +11,19 @@
|
||||
# the volume: -e TSGW_LOG_FILE=logs/tsgw.log). See docs/gateway-admin.md.
|
||||
FROM rust:1.94-bookworm AS build
|
||||
WORKDIR /src
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends cmake libasound2-dev && rm -rf /var/lib/apt/lists/*
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends cmake git libasound2-dev openssh-client && rm -rf /var/lib/apt/lists/*
|
||||
# voelin-identity comes from the private VoelinProtocol repository, fetched
|
||||
# over SSH by Cargo through the system git, with the agent that
|
||||
# `docker build --ssh default` forwards (scripts/docker-build.sh passes it):
|
||||
# the key stays in the agent and never reaches a layer. The host key is the
|
||||
# reviewed line from .gitea/known_hosts. Cargo resolves the whole workspace, so
|
||||
# every cargo command needs this, although this crate does not use
|
||||
# voelin-identity.
|
||||
COPY .gitea/known_hosts /etc/ssh/ssh_known_hosts
|
||||
ENV CARGO_NET_GIT_FETCH_WITH_CLI=true
|
||||
COPY . .
|
||||
RUN cargo build --release --locked -p voelin-gateway && cp target/release/tsgw /tsgw && mkdir /data
|
||||
RUN --mount=type=ssh,required=true \
|
||||
cargo build --release --locked -p voelin-gateway && cp target/release/tsgw /tsgw && mkdir /data
|
||||
|
||||
FROM gcr.io/distroless/cc-debian12:nonroot
|
||||
COPY --from=build /tsgw /usr/local/bin/tsgw
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
//! The desktop's proxy through a stand-in xdg-desktop-portal on the
|
||||
//! session bus. Run it on a private bus:
|
||||
//! `dbus-run-session -- cargo test -p voelin-platform --test proxy`;
|
||||
//! without a session bus it checks nothing. Its own test binary: answers
|
||||
//! are kept process-wide.
|
||||
//! The desktop's proxy through a stand-in xdg-desktop-portal on a session
|
||||
//! bus. The test runs itself again under `dbus-run-session` on a bus of its
|
||||
//! own that starts no services: on a desktop's bus the real portal is running
|
||||
//! or startable, and when the stand-in leaves the bus (as the test has it do)
|
||||
//! the real one is started and answers instead. Without `dbus-run-session`,
|
||||
//! or a bus daemon for it, the test says so and checks nothing. Its own test
|
||||
//! binary: answers are kept process-wide.
|
||||
|
||||
#![cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
|
||||
|
||||
@@ -11,6 +13,9 @@ use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
use voelin_platform::proxy::proxy_for;
|
||||
|
||||
/// Set for the run on the bus of its own.
|
||||
const ON_ITS_OWN_BUS: &str = "VOELIN_PROXY_TEST_ON_ITS_OWN_BUS";
|
||||
|
||||
/// What the GNOME portal answers: a SOCKS proxy for one host, none for the
|
||||
/// others.
|
||||
struct Resolver {
|
||||
@@ -34,10 +39,67 @@ impl Resolver {
|
||||
}
|
||||
}
|
||||
|
||||
/// The configuration of the bus of its own: a session bus without the service
|
||||
/// directories, so that nothing on it can be started by name. Its socket is
|
||||
/// made in `dir`.
|
||||
fn bus_config(dir: &std::path::Path) -> String {
|
||||
format!(
|
||||
r#"<!DOCTYPE busconfig PUBLIC "-//freedesktop//DTD D-Bus Bus Configuration 1.0//EN"
|
||||
"http://www.freedesktop.org/standards/dbus/1.0/busconfig.dtd">
|
||||
<busconfig>
|
||||
<type>session</type>
|
||||
<listen>unix:tmpdir={}</listen>
|
||||
<auth>EXTERNAL</auth>
|
||||
<policy context="default">
|
||||
<allow send_destination="*" eavesdrop="true"/>
|
||||
<allow eavesdrop="true"/>
|
||||
<allow own="*"/>
|
||||
</policy>
|
||||
</busconfig>
|
||||
"#,
|
||||
dir.display()
|
||||
)
|
||||
}
|
||||
|
||||
/// Run this test again under `dbus-run-session` on a bus of its own, and say
|
||||
/// nothing was checked when that bus cannot be had.
|
||||
fn on_a_bus_of_its_own() {
|
||||
let dir = std::env::temp_dir();
|
||||
let config = dir.join(format!("voelin-proxy-test-bus-{}.conf", std::process::id()));
|
||||
std::fs::write(&config, bus_config(&dir)).unwrap();
|
||||
let run = std::process::Command::new("dbus-run-session")
|
||||
.arg(format!("--config-file={}", config.display()))
|
||||
.arg("--")
|
||||
.arg(std::env::current_exe().unwrap())
|
||||
.args(["--exact", "the_portal_names_the_proxy", "--nocapture", "--test-threads=1"])
|
||||
.env(ON_ITS_OWN_BUS, "1")
|
||||
.output();
|
||||
let _ = std::fs::remove_file(&config);
|
||||
let run = match run {
|
||||
Ok(run) => run,
|
||||
Err(e) => {
|
||||
eprintln!("skipped, nothing was checked: dbus-run-session cannot be run ({e})");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let text =
|
||||
format!("{}{}", String::from_utf8_lossy(&run.stdout), String::from_utf8_lossy(&run.stderr));
|
||||
if run.status.success() {
|
||||
return;
|
||||
}
|
||||
// The test ran and failed, or the bus never came up.
|
||||
assert!(
|
||||
!text.contains("running 1 test"),
|
||||
"the test failed on its own bus ({}):\n{text}",
|
||||
run.status
|
||||
);
|
||||
eprintln!("skipped, nothing was checked: no bus of its own could be started:\n{text}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_portal_names_the_proxy() {
|
||||
if std::env::var_os("DBUS_SESSION_BUS_ADDRESS").is_none() {
|
||||
eprintln!("no session bus: run under dbus-run-session");
|
||||
if std::env::var_os(ON_ITS_OWN_BUS).is_none() {
|
||||
on_a_bus_of_its_own();
|
||||
return;
|
||||
}
|
||||
let lookups = Arc::new(AtomicU32::new(0));
|
||||
|
||||
Reference in new issue
Block a user