stage four unchecked (bridge with teams and self dm). undocumented

This commit is contained in:
Ivan I. Ovchinnikov
2026-11-18 12:57:06 +03:00
parent 5c3a1473e3
commit 6296a3a719
24 changed files with 2616 additions and 471 deletions
+1257 -6
View File
File diff suppressed because it is too large Load Diff
+6 -1
View File
@@ -2,8 +2,8 @@
name = "mm-bridge"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
license.workspace = true
[[bin]]
name = "mm-bridge"
@@ -11,10 +11,15 @@ path = "src/main.rs"
[dependencies]
anyhow.workspace = true
mm-client.workspace = true
mm-core.workspace = true
mm-store.workspace = true
mm-web.workspace = true
serde.workspace = true
serde_json.workspace = true
tokio.workspace = true
tracing.workspace = true
tracing-subscriber.workspace = true
[dev-dependencies]
tempfile = "3"
+385 -46
View File
@@ -1,33 +1,395 @@
use crate::{protocol, status};
use mm_core::{BridgeError, ErrorKind};
use mm_client::MattermostClient;
use mm_core::{BridgeError, ErrorKind, ServerConfig, ServerId, User};
use mm_store::{ServerStore, TokenStore};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
pub fn handle_request(request: protocol::Request) -> protocol::Response {
match request.method.as_str() {
"ping" => protocol::Response::ok(request.id, protocol::pong_result()),
"status" => protocol::Response::ok(request.id, status::status_result()),
_ => protocol::Response::err(
request.id,
BridgeError::new(
ErrorKind::UnknownMethod,
format!("unknown method: {}", request.method),
#[derive(Debug, Clone)]
struct ConnectionState {
user: User,
#[allow(dead_code)]
token: String,
url: String,
ca_file: Option<String>,
}
#[derive(Debug, Clone)]
pub struct App {
data_dir: PathBuf,
connections: Arc<Mutex<HashMap<ServerId, ConnectionState>>>,
}
impl App {
pub fn new(data_dir: impl Into<PathBuf>) -> Self {
Self {
data_dir: data_dir.into(),
connections: Arc::new(Mutex::new(HashMap::new())),
}
}
pub fn data_dir(&self) -> &Path {
&self.data_dir
}
pub async fn handle_request(&self, request: protocol::Request) -> protocol::Response {
match request.method.as_str() {
"ping" => protocol::Response::ok(request.id, protocol::pong_result()),
"status" => protocol::Response::ok(request.id, status::status_result(&self.data_dir)),
"connect" => self.handle_connect(request).await,
"me" => self.handle_me(request),
"teams" => self.handle_teams(request).await,
"open_self_dm" => self.handle_open_self_dm(request).await,
"get_history" => self.handle_get_history(request).await,
"send_post" => self.handle_send_post(request).await,
_ => protocol::Response::err(
request.id,
BridgeError::new(
ErrorKind::UnknownMethod,
format!("unknown method: {}", request.method),
),
),
),
}
}
async fn handle_connect(&self, request: protocol::Request) -> protocol::Response {
let params = match request.params.as_object() {
Some(p) => p,
None => return protocol_err(request.id, "params must be an object"),
};
let server_id = get_server_id(params);
let url = match params.get("url").and_then(|v| v.as_str()) {
Some(u) => u.to_string(),
None => return protocol_err(request.id, "missing url"),
};
let ca_file = params
.get("ca_file")
.and_then(|v| v.as_str())
.map(String::from);
let token_result = if let (Some(login), Some(password)) = (
params.get("login_id").and_then(|v| v.as_str()),
params.get("password").and_then(|v| v.as_str()),
) {
self.do_login(&url, login, password, ca_file.as_deref())
.await
} else if let Some(token) = params.get("token").and_then(|v| v.as_str()) {
Ok(token.to_string())
} else {
Err(BridgeError::new(
ErrorKind::InvalidRequest,
"provide credentials or token",
))
};
match token_result {
Ok(token) => {
if let Err(e) = save_token_and_config(&self.data_dir, &server_id, &token, &url) {
return e;
}
match self.do_get_me(&url, &token, ca_file.as_deref()).await {
Ok(user) => {
let mut conns = self.connections.lock().unwrap();
conns.insert(
server_id.clone(),
ConnectionState {
user: user.clone(),
token: token.clone(),
url: url.clone(),
ca_file,
},
);
protocol::Response::ok(
request.id,
serde_json::json!({
"server_id": server_id,
"user": user,
}),
)
}
Err(e) => protocol::Response::err(request.id, e),
}
}
Err(e) => protocol::Response::err(request.id, e),
}
}
fn handle_me(&self, request: protocol::Request) -> protocol::Response {
let params = match request.params.as_object() {
Some(p) => p,
None => return protocol_err(request.id, "params must be an object"),
};
let server_id = get_server_id(params);
let conns = self.connections.lock().unwrap();
if let Some(state) = conns.get(&server_id) {
protocol::Response::ok(
request.id,
serde_json::json!({
"server_id": server_id,
"user": state.user,
}),
)
} else {
protocol::Response::err(
request.id,
BridgeError::new(ErrorKind::Unauthorized, "not connected"),
)
}
}
async fn handle_teams(&self, request: protocol::Request) -> protocol::Response {
let params = match request.params.as_object() {
Some(p) => p,
None => return protocol_err(request.id, "params must be an object"),
};
let server_id = get_server_id(params);
let client = match self.get_client(&server_id) {
Ok(c) => c,
Err(e) => return protocol::Response::err(request.id, e),
};
let token = match self.get_token(&server_id) {
Ok(t) => t,
Err(e) => return protocol::Response::err(request.id, e),
};
match client.get_teams(&token).await {
Ok(teams) => protocol::Response::ok(
request.id,
serde_json::json!({
"server_id": server_id,
"teams": teams,
}),
),
Err(e) => protocol::Response::err(request.id, e.into()),
}
}
async fn handle_open_self_dm(&self, request: protocol::Request) -> protocol::Response {
let params = match request.params.as_object() {
Some(p) => p,
None => return protocol_err(request.id, "params must be an object"),
};
let server_id = get_server_id(params);
let client = match self.get_client(&server_id) {
Ok(c) => c,
Err(e) => return protocol::Response::err(request.id, e),
};
let user_id = match self.get_user_id(&server_id) {
Ok(id) => id.0,
Err(e) => return protocol::Response::err(request.id, e),
};
let token = match self.get_token(&server_id) {
Ok(t) => t,
Err(e) => return protocol::Response::err(request.id, e),
};
// For self-DM, we pass the same ID twice
match client
.create_direct_channel(&token, &[user_id.clone(), user_id])
.await
{
Ok(channel_id) => protocol::Response::ok(
request.id,
serde_json::json!({
"server_id": server_id,
"channel": {
"id": channel_id,
"type": "direct",
"display_name": "Self"
}
}),
),
Err(e) => protocol::Response::err(request.id, e.into()),
}
}
async fn handle_get_history(&self, request: protocol::Request) -> protocol::Response {
let params = match request.params.as_object() {
Some(p) => p,
None => return protocol_err(request.id, "params must be an object"),
};
let server_id = get_server_id(params);
let channel_id = match params.get("channel_id").and_then(|v| v.as_str()) {
Some(id) => id,
None => return protocol_err(request.id, "missing channel_id"),
};
let limit = params.get("limit").and_then(|v| v.as_u64()).unwrap_or(50) as u32;
let client = match self.get_client(&server_id) {
Ok(c) => c,
Err(e) => return protocol::Response::err(request.id, e),
};
let token = match self.get_token(&server_id) {
Ok(t) => t,
Err(e) => return protocol::Response::err(request.id, e),
};
match client.get_posts(&token, channel_id, limit).await {
Ok(posts) => protocol::Response::ok(
request.id,
serde_json::json!({
"server_id": server_id,
"channel_id": channel_id,
"posts": posts,
}),
),
Err(e) => protocol::Response::err(request.id, e.into()),
}
}
async fn handle_send_post(&self, request: protocol::Request) -> protocol::Response {
let params = match request.params.as_object() {
Some(p) => p,
None => return protocol_err(request.id, "params must be an object"),
};
let server_id = get_server_id(params);
let channel_id = match params.get("channel_id").and_then(|v| v.as_str()) {
Some(id) => id,
None => return protocol_err(request.id, "missing channel_id"),
};
let message = match params.get("message").and_then(|v| v.as_str()) {
Some(m) => m,
None => return protocol_err(request.id, "missing message"),
};
let root_id = params.get("root_id").and_then(|v| v.as_str());
let client = match self.get_client(&server_id) {
Ok(c) => c,
Err(e) => return protocol::Response::err(request.id, e),
};
let token = match self.get_token(&server_id) {
Ok(t) => t,
Err(e) => return protocol::Response::err(request.id, e),
};
match client
.create_post(&token, channel_id, message, root_id)
.await
{
Ok(post) => protocol::Response::ok(
request.id,
serde_json::json!({
"server_id": server_id,
"post": post,
}),
),
Err(e) => protocol::Response::err(request.id, e.into()),
}
}
// --- Helpers ---
fn get_client(&self, server_id: &ServerId) -> Result<MattermostClient, BridgeError> {
let conns = self.connections.lock().unwrap();
let state = conns
.get(server_id)
.ok_or_else(|| BridgeError::new(ErrorKind::Unauthorized, "not connected"))?;
let ca_path = state.ca_file.as_ref().map(PathBuf::from);
MattermostClient::new(state.url.clone(), ca_path.as_deref())
.map_err(|e| BridgeError::new(ErrorKind::InternalError, e.to_string()))
}
fn get_token(&self, server_id: &ServerId) -> Result<String, BridgeError> {
let conns = self.connections.lock().unwrap();
conns
.get(server_id)
.map(|s| s.token.clone())
.ok_or_else(|| BridgeError::new(ErrorKind::Unauthorized, "not connected"))
}
fn get_user_id(&self, server_id: &ServerId) -> Result<mm_core::UserId, BridgeError> {
let conns = self.connections.lock().unwrap();
conns
.get(server_id)
.map(|s| s.user.id.clone())
.ok_or_else(|| BridgeError::new(ErrorKind::Unauthorized, "not connected"))
}
async fn do_login(
&self,
url: &str,
login: &str,
pass: &str,
ca: Option<&str>,
) -> Result<String, BridgeError> {
let ca_path = ca.map(PathBuf::from);
let client = MattermostClient::new(url.to_string(), ca_path.as_deref())
.map_err(|e| BridgeError::new(ErrorKind::InternalError, e.to_string()))?;
client.login(login, pass).await.map_err(Into::into)
}
async fn do_get_me(
&self,
url: &str,
token: &str,
ca: Option<&str>,
) -> Result<User, BridgeError> {
let ca_path = ca.map(PathBuf::from);
let client = MattermostClient::new(url.to_string(), ca_path.as_deref())
.map_err(|e| BridgeError::new(ErrorKind::InternalError, e.to_string()))?;
client.get_me(token).await.map_err(Into::into)
}
pub async fn response_line(&self, line: &str) -> String {
let response = match protocol::parse_request(line) {
Ok(request) => self.handle_request(request).await,
Err((id, error)) => protocol::Response::err(id, error),
};
match protocol::encode_response(&response) {
Ok(encoded) => encoded,
Err(error) => fallback_error_line(&response.id, error),
}
}
}
pub fn handle_line(line: &str) -> protocol::Response {
match protocol::parse_request(line) {
Ok(request) => handle_request(request),
Err((id, error)) => protocol::Response::err(id, error),
}
fn protocol_err(id: impl Into<String>, msg: &str) -> protocol::Response {
protocol::Response::err(id, BridgeError::new(ErrorKind::InvalidRequest, msg))
}
pub fn response_line(line: &str) -> String {
let response = handle_line(line);
match protocol::encode_response(&response) {
Ok(encoded) => encoded,
Err(error) => fallback_error_line(&response.id, error),
}
fn get_server_id(params: &serde_json::Map<String, serde_json::Value>) -> ServerId {
params
.get("server_id")
.and_then(|v| v.as_str())
.map(ServerId::new)
.unwrap_or_else(|| ServerId::new("default"))
}
fn save_token_and_config(
data_dir: &Path,
server_id: &ServerId,
token: &str,
url: &str,
) -> Result<(), protocol::Response> {
let token_store = TokenStore::new(data_dir);
let server_store = ServerStore::new(data_dir);
token_store
.save(server_id, token)
.map_err(|e| protocol::Response::err("req", e))?;
let config = ServerConfig {
server_id: server_id.clone(),
url: url.to_string(),
};
server_store
.save(&config)
.map_err(|e| protocol::Response::err("req", e))?;
Ok(())
}
fn fallback_error_line(id: &str, error: BridgeError) -> String {
@@ -37,31 +399,8 @@ fn fallback_error_line(id: &str, error: BridgeError) -> String {
"id": id,
"type": "response",
"ok": false,
"error": {
"code": "internal_error",
"message": "failed to encode error response",
"retryable": false
}
"error": { "code": "internal_error", "message": "encoding failed", "retryable": false }
})
});
format!("{value}\n")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ping_line_returns_pong() {
let line = response_line(r#"{"id":"1","type":"request","method":"ping","params":{}}"#);
assert!(line.contains(r#""ok":true"#));
assert!(line.contains(r#""pong":true"#));
}
#[test]
fn unknown_method_returns_error() {
let line = response_line(r#"{"id":"2","type":"request","method":"nope","params":{}}"#);
assert!(line.contains(r#""ok":false"#));
assert!(line.contains("unknown_method"));
}
}
+19 -1
View File
@@ -1,17 +1,24 @@
use std::env;
use std::path::PathBuf;
#[derive(Debug, Clone)]
pub struct BridgeConfig {
pub listen: String,
pub web_listen: String,
pub data_dir: PathBuf,
}
impl BridgeConfig {
pub fn from_env() -> anyhow::Result<Self> {
let listen = read_addr("MM_BRIDGE_LISTEN", "127.0.0.1:8765")?;
let web_listen = read_addr("MM_WEB_LISTEN", "127.0.0.1:8766")?;
let data_dir = read_data_dir()?;
Ok(Self { listen, web_listen })
Ok(Self {
listen,
web_listen,
data_dir,
})
}
}
@@ -21,6 +28,17 @@ fn read_addr(name: &str, default: &str) -> anyhow::Result<String> {
Ok(value)
}
fn read_data_dir() -> anyhow::Result<PathBuf> {
let value = env::var("MM_DATA_DIR").unwrap_or_else(|_| default_data_dir());
anyhow::ensure!(!value.trim().is_empty(), "MM_DATA_DIR must not be empty");
Ok(PathBuf::from(value))
}
fn default_data_dir() -> String {
let home = env::var("HOME").unwrap_or_else(|_| ".".to_string());
format!("{home}/.local/share/emacs-mattermost")
}
fn validate_listen(name: &str, listen: &str) -> anyhow::Result<()> {
anyhow::ensure!(!listen.trim().is_empty(), "{name} must not be empty");
anyhow::ensure!(listen.contains(':'), "{name} must be host:port");
+7 -5
View File
@@ -1,4 +1,4 @@
use crate::{config::BridgeConfig, status, transport};
use crate::{app::App, config::BridgeConfig, status, transport};
use anyhow::Context;
use mm_web::state::WebState;
use tokio::net::TcpListener;
@@ -10,11 +10,12 @@ pub async fn run(config: BridgeConfig) -> anyhow::Result<()> {
tracing::info!(listen = %config.listen, "bridge listening");
let web_state = WebState::new(status::current_status());
let app = App::new(config.data_dir.clone());
let web_state = WebState::new(status::current_status(&config.data_dir));
let web_task = tokio::spawn(mm_web::run(config.web_listen.clone(), web_state));
tokio::select! {
result = accept_loop(tcp_listener) => {
result = accept_loop(tcp_listener, app) => {
result
}
result = web_task => {
@@ -27,13 +28,14 @@ pub async fn run(config: BridgeConfig) -> anyhow::Result<()> {
}
}
async fn accept_loop(listener: TcpListener) -> anyhow::Result<()> {
async fn accept_loop(listener: TcpListener, app: App) -> anyhow::Result<()> {
loop {
let (stream, peer) = listener.accept().await.context("accept failed")?;
tracing::debug!(%peer, "accepted connection");
let app = app.clone();
tokio::spawn(async move {
if let Err(error) = transport::handle_client(stream).await {
if let Err(error) = transport::handle_client(app, stream).await {
tracing::warn!(%error, "client handler failed");
}
});
+49 -7
View File
@@ -1,14 +1,40 @@
use mm_core::BridgeStatus;
use mm_core::{BridgeStatus, ServerId, ServerSummary};
use mm_store::{ServerStore, TokenStore};
use serde_json::Value;
use std::collections::BTreeSet;
use std::path::Path;
pub const BRIDGE_VERSION: &str = env!("CARGO_PKG_VERSION");
pub fn current_status() -> BridgeStatus {
BridgeStatus::running(BRIDGE_VERSION)
/// Build status from persisted stores. Never includes secrets.
pub fn current_status(data_dir: &Path) -> BridgeStatus {
let mut status = BridgeStatus::running(BRIDGE_VERSION);
let token_store = TokenStore::new(data_dir);
let server_store = ServerStore::new(data_dir);
let token_ids = token_store.list_servers().unwrap_or_default();
let config_ids = server_store.list_servers().unwrap_or_default();
let mut all: BTreeSet<String> = BTreeSet::new();
all.extend(token_ids.iter().map(|id| id.as_str().to_string()));
all.extend(config_ids.iter().map(|id| id.as_str().to_string()));
for id in all {
let server_id = ServerId::new(id);
let has_token = token_ids.contains(&server_id);
status.servers.push(ServerSummary {
server_id,
state: "disconnected".to_string(),
has_token,
});
}
status
}
pub fn status_result() -> Value {
serde_json::to_value(current_status()).unwrap_or_else(|_| {
pub fn status_result(data_dir: &Path) -> Value {
serde_json::to_value(current_status(data_dir)).unwrap_or_else(|_| {
serde_json::json!({
"bridge": {
"version": BRIDGE_VERSION,
@@ -24,9 +50,25 @@ mod tests {
use super::*;
#[test]
fn status_has_empty_servers() {
let value = status_result();
fn empty_dir_has_no_servers() {
let dir = tempfile::tempdir().unwrap();
let value = status_result(dir.path());
assert_eq!(value["servers"].as_array().unwrap().len(), 0);
assert_eq!(value["bridge"]["state"], "running");
}
#[test]
fn stored_token_appears_without_secret() {
let dir = tempfile::tempdir().unwrap();
TokenStore::new(dir.path())
.save(&ServerId::new("work"), "super-secret")
.unwrap();
let value = status_result(dir.path());
let servers = value["servers"].as_array().unwrap();
assert_eq!(servers.len(), 1);
assert_eq!(servers[0]["server_id"], "work");
assert_eq!(servers[0]["has_token"], true);
assert!(!value.to_string().contains("super-secret"));
}
}
+3 -3
View File
@@ -1,9 +1,9 @@
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpStream;
use crate::app;
use crate::app::App;
pub async fn handle_client(stream: TcpStream) -> std::io::Result<()> {
pub async fn handle_client(app: App, stream: TcpStream) -> std::io::Result<()> {
let peer = stream.peer_addr().ok();
tracing::info!(?peer, "client connected");
@@ -15,7 +15,7 @@ pub async fn handle_client(stream: TcpStream) -> std::io::Result<()> {
continue;
}
let response = app::response_line(&line);
let response = app.response_line(&line).await;
write_half.write_all(response.as_bytes()).await?;
write_half.flush().await?;
}
+10 -1
View File
@@ -2,8 +2,17 @@
name = "mm-client"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
license.workspace = true
[dependencies]
mm-core.workspace = true
reqwest = { version = "0.12", features = ["json", "rustls-tls-native-roots"] }
serde.workspace = true
serde_json.workspace = true
tokio.workspace = true
tracing.workspace = true
thiserror.workspace = true
[dev-dependencies]
tempfile = "3"
+1 -1
View File
@@ -1 +1 @@
//! auth module placeholder.
//! Authentication helpers.
+232
View File
@@ -0,0 +1,232 @@
use crate::error::ClientError;
use crate::tls;
use mm_core::{ChannelId, Post, Team, User}; // Добавим Post и Team в mm-core позже
use reqwest::header::AUTHORIZATION;
use std::path::Path;
#[derive(Debug, Clone)]
pub struct MattermostClient {
base_url: String,
client: reqwest::Client,
}
impl MattermostClient {
pub fn new(base_url: String, ca_file: Option<&Path>) -> Result<Self, ClientError> {
let builder = tls::builder(ca_file)?;
let client = builder.build().map_err(ClientError::Http)?;
let base_url = base_url.trim_end_matches('/').to_string();
Ok(Self { base_url, client })
}
pub async fn login(&self, login_id: &str, password: &str) -> Result<String, ClientError> {
let url = format!("{}/api/v4/users/login", self.base_url);
let body = serde_json::json!({
"login_id": login_id,
"password": password
});
let response = self
.client
.post(&url)
.json(&body)
.send()
.await
.map_err(ClientError::Http)?;
if !response.status().is_success() {
return handle_api_error_string(response)
.await
.map(|_| unreachable!());
}
let token = response
.headers()
.get("Token")
.and_then(|v| v.to_str().ok())
.map(|s| s.to_string())
.ok_or(ClientError::MissingTokenHeader)?;
Ok(token)
}
pub async fn get_me(&self, token: &str) -> Result<User, ClientError> {
let url = format!("{}/api/v4/users/me", self.base_url);
let response = self
.client
.get(&url)
.header(AUTHORIZATION, format!("Bearer {}", token))
.send()
.await
.map_err(ClientError::Http)?;
if !response.status().is_success() {
return handle_api_error_user(response).await;
}
let user: User = response.json().await.map_err(ClientError::Http)?;
Ok(user)
}
pub async fn get_teams(&self, token: &str) -> Result<Vec<Team>, ClientError> {
let url = format!("{}/api/v4/teams", self.base_url);
let response = self
.client
.get(&url)
.header(AUTHORIZATION, format!("Bearer {}", token))
.send()
.await
.map_err(ClientError::Http)?;
if !response.status().is_success() {
return handle_api_error_vec(response).await;
}
let teams: Vec<Team> = response.json().await.map_err(ClientError::Http)?;
Ok(teams)
}
pub async fn create_direct_channel(
&self,
token: &str,
user_ids: &[String],
) -> Result<ChannelId, ClientError> {
let url = format!("{}/api/v4/channels/direct", self.base_url);
let response = self
.client
.post(&url)
.header(AUTHORIZATION, format!("Bearer {}", token))
.json(user_ids)
.send()
.await
.map_err(ClientError::Http)?;
if !response.status().is_success() {
return handle_api_error_channel(response).await;
}
#[derive(serde::Deserialize)]
struct ChannelResponse {
id: String,
}
let ch: ChannelResponse = response.json().await.map_err(ClientError::Http)?;
Ok(ChannelId::new(ch.id))
}
pub async fn get_posts(
&self,
token: &str,
channel_id: &str,
limit: u32,
) -> Result<Vec<Post>, ClientError> {
let url = format!(
"{}/api/v4/channels/{}/posts?page=0&per_page={}",
self.base_url, channel_id, limit
);
let response = self
.client
.get(&url)
.header(AUTHORIZATION, format!("Bearer {}", token))
.send()
.await
.map_err(ClientError::Http)?;
if !response.status().is_success() {
return handle_api_error_vec(response).await;
}
// Mattermost returns { order: [], posts: {} }
#[derive(serde::Deserialize)]
struct PostsResponse {
order: Vec<String>,
posts: std::collections::HashMap<String, Post>,
}
let data: PostsResponse = response.json().await.map_err(ClientError::Http)?;
// Normalize to ordered vector
let mut posts: Vec<Post> = data
.order
.iter()
.filter_map(|id| data.posts.get(id).cloned())
.collect();
// Sort ascending by create_at for display
posts.sort_by_key(|p| p.create_at);
Ok(posts)
}
pub async fn create_post(
&self,
token: &str,
channel_id: &str,
message: &str,
root_id: Option<&str>,
) -> Result<Post, ClientError> {
let url = format!("{}/api/v4/posts", self.base_url);
let mut body = serde_json::json!({
"channel_id": channel_id,
"message": message
});
if let Some(rid) = root_id {
body["root_id"] = serde_json::Value::String(rid.to_string());
}
let response = self
.client
.post(&url)
.header(AUTHORIZATION, format!("Bearer {}", token))
.json(&body)
.send()
.await
.map_err(ClientError::Http)?;
if !response.status().is_success() {
return handle_api_error_post(response).await;
}
let post: Post = response.json().await.map_err(ClientError::Http)?;
Ok(post)
}
}
// --- Helpers for error handling ---
async fn handle_api_error_string(response: reqwest::Response) -> Result<String, ClientError> {
let status = response.status().as_u16();
let body = response.text().await.unwrap_or_default();
#[derive(serde::Deserialize)]
struct MmError {
id: String,
message: String,
}
let err_msg = serde_json::from_str::<MmError>(&body)
.map(|e| format!("{} ({})", e.message, e.id))
.unwrap_or_else(|_| body.clone());
Err(ClientError::Api {
id: "api_error".into(),
message: err_msg,
status_code: status,
})
}
async fn handle_api_error_user(response: reqwest::Response) -> Result<User, ClientError> {
handle_api_error_string(response).await?;
unreachable!()
}
async fn handle_api_error_vec<T>(response: reqwest::Response) -> Result<Vec<T>, ClientError> {
handle_api_error_string(response).await?;
unreachable!()
}
async fn handle_api_error_channel(response: reqwest::Response) -> Result<ChannelId, ClientError> {
handle_api_error_string(response).await?;
unreachable!()
}
async fn handle_api_error_post(response: reqwest::Response) -> Result<Post, ClientError> {
handle_api_error_string(response).await?;
unreachable!()
}
+39
View File
@@ -0,0 +1,39 @@
use mm_core::{BridgeError, ErrorKind};
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ClientError {
#[error("HTTP request failed: {0}")]
Http(#[from] reqwest::Error),
#[error("Mattermost API error: {message} ({id})")]
Api {
id: String,
message: String,
status_code: u16,
},
#[error("Missing Token header in login response")]
MissingTokenHeader,
#[error("Invalid JSON in response: {0}")]
InvalidJson(#[from] serde_json::Error),
#[error("TLS configuration error: {0}")]
Tls(String),
}
impl From<ClientError> for BridgeError {
fn from(err: ClientError) -> Self {
let kind = match &err {
ClientError::Http(e) if e.is_timeout() => ErrorKind::NetworkError,
ClientError::Http(e) if e.is_connect() => ErrorKind::NetworkError,
ClientError::Api { .. } => ErrorKind::ServerError,
ClientError::MissingTokenHeader => ErrorKind::Unauthorized,
ClientError::InvalidJson(_) => ErrorKind::InternalError,
ClientError::Tls(_) => ErrorKind::TlsError,
_ => ErrorKind::InternalError,
};
BridgeError::new(kind, err.to_string())
}
}
+7 -2
View File
@@ -1,8 +1,13 @@
//! Mattermost REST/WebSocket client.
//! Mattermost REST API client.
//!
//! Placeholder crate. Implementation starts after the bridge skeleton works.
//! Supports explicit CA configuration for corporate environments.
pub mod auth;
pub mod client;
pub mod error;
pub mod rest;
pub mod tls;
pub mod ws;
pub use client::MattermostClient;
pub use error::ClientError;
+1 -1
View File
@@ -1 +1 @@
//! rest module placeholder.
//! REST API endpoints.
+25 -1
View File
@@ -1 +1,25 @@
//! tls module placeholder.
use crate::error::ClientError;
use reqwest::Certificate;
use std::fs;
use std::path::Path;
/// Build a reqwest ClientBuilder with optional explicit CA.
pub fn builder(ca_file: Option<&Path>) -> Result<reqwest::ClientBuilder, ClientError> {
let mut builder = reqwest::Client::builder();
if let Some(path) = ca_file {
let cert_bytes = fs::read(path).map_err(|e| {
ClientError::Tls(format!("Failed to read CA file {}: {}", path.display(), e))
})?;
let cert = Certificate::from_pem(&cert_bytes).map_err(|e| {
ClientError::Tls(format!(
"Invalid CA certificate in {}: {}",
path.display(),
e
))
})?;
builder = builder.add_root_certificate(cert);
}
Ok(builder)
}
+1 -1
View File
@@ -1 +1 @@
//! ws module placeholder.
//! WebSocket client.
+3 -1
View File
@@ -8,4 +8,6 @@ pub mod model;
pub use error::{BridgeError, ErrorKind};
pub use ids::{ChannelId, PostId, ServerId, TeamId, UserId};
pub use model::{BridgeInfo, BridgeState, BridgeStatus, ServerSummary};
pub use model::{
BridgeInfo, BridgeState, BridgeStatus, Post, ServerConfig, ServerSummary, Team, User,
};
+42 -2
View File
@@ -1,5 +1,5 @@
use crate::ids::ServerId;
use serde::Serialize;
use crate::ids::{ChannelId, PostId, ServerId, TeamId, UserId};
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "snake_case")]
@@ -11,6 +11,7 @@ pub enum BridgeState {
pub struct ServerSummary {
pub server_id: ServerId,
pub state: String,
pub has_token: bool,
}
#[derive(Debug, Clone, Serialize)]
@@ -36,3 +37,42 @@ impl BridgeStatus {
}
}
}
/// Normalized Mattermost user. Only fields needed by the MVP UI.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct User {
pub id: UserId,
pub username: String,
#[serde(default)]
pub nickname: String,
#[serde(default)]
pub first_name: String,
#[serde(default)]
pub last_name: String,
}
/// Persisted per-server configuration (no secrets).
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerConfig {
pub server_id: ServerId,
pub url: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Team {
pub id: TeamId,
pub name: String,
pub display_name: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Post {
pub id: PostId,
pub channel_id: ChannelId,
pub user_id: UserId,
pub root_id: Option<PostId>,
pub message: String,
pub create_at: i64,
pub update_at: i64,
pub delete_at: i64,
}
+5 -1
View File
@@ -2,8 +2,12 @@
name = "mm-store"
version.workspace = true
edition.workspace = true
license.workspace = true
rust-version.workspace = true
license.workspace = true
[dependencies]
mm-core.workspace = true
serde_json.workspace = true
[dev-dependencies]
tempfile = "3"
+122 -1
View File
@@ -1 +1,122 @@
//! cache module placeholder.
use crate::session::{ensure_dir, list_stems, validate_server_id};
use mm_core::{BridgeError, ErrorKind, ServerConfig, ServerId};
use std::fs;
use std::path::{Path, PathBuf};
/// Non-secret per-server configuration storage.
#[derive(Debug, Clone)]
pub struct ServerStore {
dir: PathBuf,
}
impl ServerStore {
pub fn new(data_dir: impl AsRef<Path>) -> Self {
Self {
dir: data_dir.as_ref().join("servers"),
}
}
pub fn load(&self, server_id: &ServerId) -> Result<Option<ServerConfig>, BridgeError> {
let path = self.path(server_id)?;
match fs::read_to_string(&path) {
Ok(text) => {
let config = serde_json::from_str(&text).map_err(|err| {
BridgeError::new(
ErrorKind::InternalError,
format!("invalid server config at {}: {err}", path.display()),
)
})?;
Ok(Some(config))
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(err) => Err(BridgeError::new(
ErrorKind::InternalError,
format!("read server config at {}: {err}", path.display()),
)),
}
}
pub fn save(&self, config: &ServerConfig) -> Result<(), BridgeError> {
validate_server_id(&config.server_id)?;
if config.url.trim().is_empty() {
return Err(BridgeError::new(
ErrorKind::InvalidRequest,
"server url must not be empty",
));
}
let path = self.path(&config.server_id)?;
ensure_dir(&self.dir)?;
let text = serde_json::to_string_pretty(config).map_err(|err| {
BridgeError::new(ErrorKind::InternalError, format!("encode config: {err}"))
})?;
let tmp_path = path.with_extension("json.tmp");
fs::write(&tmp_path, text).map_err(|err| {
BridgeError::new(
ErrorKind::InternalError,
format!("write config at {}: {err}", tmp_path.display()),
)
})?;
fs::rename(&tmp_path, &path).map_err(|err| {
BridgeError::new(
ErrorKind::InternalError,
format!("rename config at {}: {err}", path.display()),
)
})?;
Ok(())
}
pub fn list_servers(&self) -> Result<Vec<ServerId>, BridgeError> {
list_stems(&self.dir, "json")
}
fn path(&self, server_id: &ServerId) -> Result<PathBuf, BridgeError> {
validate_server_id(server_id)?;
Ok(self.dir.join(format!("{}.json", server_id.as_str())))
}
}
#[cfg(test)]
mod tests {
use super::*;
fn config(id: &str) -> ServerConfig {
ServerConfig {
server_id: ServerId::new(id),
url: "https://mm.example.local".to_string(),
}
}
#[test]
fn missing_config_is_none() {
let dir = tempfile::tempdir().unwrap();
let store = ServerStore::new(dir.path());
assert!(store.load(&ServerId::new("work")).unwrap().is_none());
}
#[test]
fn save_load_roundtrip() {
let dir = tempfile::tempdir().unwrap();
let store = ServerStore::new(dir.path());
store.save(&config("work")).unwrap();
let loaded = store.load(&ServerId::new("work")).unwrap().unwrap();
assert_eq!(loaded.url, "https://mm.example.local");
}
#[test]
fn lists_sorted_servers() {
let dir = tempfile::tempdir().unwrap();
let store = ServerStore::new(dir.path());
store.save(&config("zeta")).unwrap();
store.save(&config("alpha")).unwrap();
let names: Vec<String> = store
.list_servers()
.unwrap()
.into_iter()
.map(|id| id.as_str().to_string())
.collect();
assert_eq!(names, vec!["alpha", "zeta"]);
}
}
+9 -1
View File
@@ -1,6 +1,14 @@
//! Local cache and session storage.
//!
//! Placeholder crate. Implementation starts at the authentication step.
//! Layout under the data directory:
//!
//! <data_dir>/tokens/<server_id>.token - plain bearer token, private mode
//! <data_dir>/servers/<server_id>.json - non-secret server config
//!
//! MVP storage is unencrypted by design. Secrets must never be logged.
pub mod cache;
pub mod session;
pub use cache::ServerStore;
pub use session::TokenStore;
+224 -1
View File
@@ -1 +1,224 @@
//! session module placeholder.
use mm_core::{BridgeError, ErrorKind, ServerId};
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
/// Plain-file bearer token storage, one file per server.
///
/// Files are written atomically (temp file + rename).
/// On Unix the file mode is 0600. Tokens are never logged.
#[derive(Debug, Clone)]
pub struct TokenStore {
dir: PathBuf,
}
impl TokenStore {
pub fn new(data_dir: impl AsRef<Path>) -> Self {
Self {
dir: data_dir.as_ref().join("tokens"),
}
}
pub fn load(&self, server_id: &ServerId) -> Result<Option<String>, BridgeError> {
let path = self.path(server_id)?;
match fs::read_to_string(&path) {
Ok(text) => {
let token = text.trim().to_string();
if token.is_empty() {
Ok(None)
} else {
Ok(Some(token))
}
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(err) => Err(io_error("read token", &path, err)),
}
}
pub fn save(&self, server_id: &ServerId, token: &str) -> Result<(), BridgeError> {
let token = token.trim();
if token.is_empty() {
return Err(BridgeError::new(
ErrorKind::InvalidRequest,
"token must not be empty",
));
}
let path = self.path(server_id)?;
ensure_dir(&self.dir)?;
let tmp_path = path.with_extension("token.tmp");
write_private(&tmp_path, token)?;
fs::rename(&tmp_path, &path).map_err(|err| io_error("rename token", &path, err))?;
Ok(())
}
pub fn delete(&self, server_id: &ServerId) -> Result<(), BridgeError> {
let path = self.path(server_id)?;
match fs::remove_file(&path) {
Ok(()) => Ok(()),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(err) => Err(io_error("delete token", &path, err)),
}
}
/// Server ids that currently have a stored token. Never returns tokens.
pub fn list_servers(&self) -> Result<Vec<ServerId>, BridgeError> {
list_stems(&self.dir, "token")
}
fn path(&self, server_id: &ServerId) -> Result<PathBuf, BridgeError> {
validate_server_id(server_id)?;
Ok(self.dir.join(format!("{}.token", server_id.as_str())))
}
}
pub(crate) fn validate_server_id(server_id: &ServerId) -> Result<(), BridgeError> {
let value = server_id.as_str();
let ok = !value.is_empty()
&& value
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
if ok {
Ok(())
} else {
Err(BridgeError::new(
ErrorKind::InvalidRequest,
"server_id must contain only [A-Za-z0-9_-]",
))
}
}
pub(crate) fn ensure_dir(dir: &Path) -> Result<(), BridgeError> {
fs::create_dir_all(dir).map_err(|err| io_error("create dir", dir, err))
}
pub(crate) fn list_stems(dir: &Path, extension: &str) -> Result<Vec<ServerId>, BridgeError> {
let entries = match fs::read_dir(dir) {
Ok(entries) => entries,
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
Err(err) => return Err(io_error("list dir", dir, err)),
};
let mut ids = Vec::new();
for entry in entries {
let entry = entry.map_err(|err| io_error("list entry", dir, err))?;
let path = entry.path();
if path.extension().and_then(|e| e.to_str()) != Some(extension) {
continue;
}
if let Some(stem) = path.file_stem().and_then(|s| s.to_str()) {
ids.push(ServerId::new(stem));
}
}
ids.sort_by(|a, b| a.as_str().cmp(b.as_str()));
Ok(ids)
}
fn write_private(path: &Path, token: &str) -> Result<(), BridgeError> {
let mut options = fs::OpenOptions::new();
options.write(true).create(true).truncate(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut file = options
.open(path)
.map_err(|err| io_error("open token", path, err))?;
file.write_all(token.as_bytes())
.map_err(|err| io_error("write token", path, err))?;
file.sync_all()
.map_err(|err| io_error("sync token", path, err))?;
Ok(())
}
fn io_error(action: &str, path: &Path, err: std::io::Error) -> BridgeError {
// Path may contain a server id but never a token; safe to include.
BridgeError::new(
ErrorKind::InternalError,
format!("{action} failed at {}: {err}", path.display()),
)
}
#[cfg(test)]
mod tests {
use super::*;
fn store() -> (tempfile::TempDir, TokenStore) {
let dir = tempfile::tempdir().expect("tempdir");
let store = TokenStore::new(dir.path());
(dir, store)
}
#[test]
fn missing_token_is_none() {
let (_dir, store) = store();
assert_eq!(store.load(&ServerId::new("work")).unwrap(), None);
}
#[test]
fn save_load_roundtrip() {
let (_dir, store) = store();
let id = ServerId::new("work");
store.save(&id, "secret-token").unwrap();
assert_eq!(store.load(&id).unwrap().as_deref(), Some("secret-token"));
}
#[test]
fn overwrite_replaces_token() {
let (_dir, store) = store();
let id = ServerId::new("work");
store.save(&id, "old").unwrap();
store.save(&id, "new").unwrap();
assert_eq!(store.load(&id).unwrap().as_deref(), Some("new"));
}
#[test]
fn delete_is_idempotent() {
let (_dir, store) = store();
let id = ServerId::new("work");
store.delete(&id).unwrap();
store.save(&id, "t").unwrap();
store.delete(&id).unwrap();
assert_eq!(store.load(&id).unwrap(), None);
}
#[test]
fn rejects_bad_server_id() {
let (_dir, store) = store();
assert!(store.save(&ServerId::new("../evil"), "t").is_err());
assert!(store.save(&ServerId::new("a/b"), "t").is_err());
assert!(store.save(&ServerId::new(""), "t").is_err());
}
#[test]
fn rejects_empty_token() {
let (_dir, store) = store();
assert!(store.save(&ServerId::new("work"), " ").is_err());
}
#[test]
fn lists_servers_without_tokens() {
let (_dir, store) = store();
store.save(&ServerId::new("zeta"), "t1").unwrap();
store.save(&ServerId::new("alpha"), "t2").unwrap();
let ids = store.list_servers().unwrap();
let names: Vec<&str> = ids.iter().map(ServerId::as_str).collect();
assert_eq!(names, vec!["alpha", "zeta"]);
}
#[cfg(unix)]
#[test]
fn token_file_is_private() {
use std::os::unix::fs::PermissionsExt;
let (dir, store) = store();
let id = ServerId::new("work");
store.save(&id, "t").unwrap();
let path = dir.path().join("tokens/work.token");
let mode = fs::metadata(path).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
}
}