stage four unchecked (bridge with teams and self dm). undocumented
This commit is contained in:
@@ -1,96 +1,59 @@
|
||||
# mattermost.el
|
||||
# emacs-mattermost
|
||||
|
||||
Emacs client for corporate Mattermost, inspired by the UX ideas of `telega.el`.
|
||||
Emacs client for corporate Mattermost, inspired by the UX of telega.el.
|
||||
|
||||
Target Mattermost server version: **10.9.3**.
|
||||
|
||||
The project is split into:
|
||||
## Components
|
||||
|
||||
- Emacs Lisp package: UI, buffers, commands, keybindings.
|
||||
- Rust bridge: Mattermost REST/WebSocket integration, session cache, online updates.
|
||||
- Rust bridge: Mattermost REST/WebSocket, session cache, online updates.
|
||||
- Docker Compose: primary way to run the bridge.
|
||||
- Web status UI: exposed by the bridge container.
|
||||
|
||||
## Current development status
|
||||
|
||||
This repository is being built incrementally.
|
||||
|
||||
Do not implement large batches at once. Each step must be small, verifiable, and leave the project in a working state.
|
||||
|
||||
## Fixed decisions
|
||||
|
||||
- Bridge language: Rust.
|
||||
- Main bridge runtime: Docker Compose.
|
||||
- Emacs does not start Docker containers.
|
||||
- Emacs connects to an already running bridge.
|
||||
- Emacs ↔ bridge transport: TCP JSON Lines on localhost.
|
||||
- Bridge exposes a web status UI.
|
||||
- Mattermost server is the single source of truth.
|
||||
- Emacs buffers are display-only projections.
|
||||
- MVP message rendering: raw text, no Markdown rendering.
|
||||
- MVP starts with direct messages to self.
|
||||
- Channel messages come after self-DM flow works.
|
||||
- Multiserver support is architecturally planned, but not implemented in MVP.
|
||||
- Commands and identities must be server-scoped internally from the beginning.
|
||||
- Direct messages must display server/team context to avoid confusion later.
|
||||
- Threads/replies should be separate buffers by default, configurable via `use-package`.
|
||||
- `g` in a Mattermost buffer means forced refresh of the buffer and connection health/recovery.
|
||||
- Typing indicators are not part of MVP.
|
||||
- Reactions are not part of MVP.
|
||||
- Authentication MVP: login/password and saved session/PAT token.
|
||||
- Token cache MVP: separate plain file inside bridge cache directory.
|
||||
- Password may be read from `~/.authinfo`; no strong protection in MVP.
|
||||
- Docker deployment must avoid leaking secrets through logs/environment dumps.
|
||||
- Self-signed certificate support must be explicit through CA configuration, not global verification disablement in the bridge.
|
||||
- Main bridge runtime: Docker Compose, started separately from Emacs.
|
||||
- Emacs connects to an already running bridge over localhost TCP JSON Lines.
|
||||
- Mattermost server is the single source of truth; Emacs buffers are display-only.
|
||||
- MVP message rendering: raw text, no Markdown.
|
||||
- MVP starts with direct messages to self, channels come later.
|
||||
- Multiserver support is architecturally planned, not implemented in MVP.
|
||||
- All identifiers and stored state are server-scoped from the beginning.
|
||||
- DM buffers must show server/team context to avoid confusion.
|
||||
- Threads/replies are separate buffers by default, configurable via use-package.
|
||||
- `g` forces buffer refresh plus connection health check/recovery.
|
||||
- Typing indicators and reactions are out of MVP scope.
|
||||
- Auth MVP: login/password plus saved session token or PAT.
|
||||
- Token cache: plain file per server under the data dir, private file mode.
|
||||
- Password may be read from Emacs `~/.authinfo`; no strong protection in MVP.
|
||||
- Secrets must never appear in logs, protocol responses, or the web status UI.
|
||||
- TLS verification stays enabled; internal CA is configured explicitly.
|
||||
|
||||
## Mattermost API notes
|
||||
## Build environment
|
||||
|
||||
Mattermost REST API v4 is used for normal operations such as login, posting messages, channels, users, and files.
|
||||
Corporate network: no direct internet access, authenticated proxy.
|
||||
|
||||
Mattermost WebSocket endpoint:
|
||||
- Cargo dependencies resolve through the Nexus mirror configured in
|
||||
`bridge/.cargo/config.toml`.
|
||||
- Docker builder image: `nexus.local/rust:1.90-bookworm`.
|
||||
- Docker runtime image: `nexus.local/ci/debian:bookworm-ca`.
|
||||
- Host toolchain: Rust 1.94 (used to generate the lockfile).
|
||||
- Workspace `rust-version`: 1.90.
|
||||
- MSRV-aware resolution is enabled via
|
||||
`resolver.incompatible-rust-versions = "fallback"`, so cargo picks
|
||||
dependency versions compatible with Rust 1.90 automatically.
|
||||
- `Cargo.lock` is committed and all builds use `--locked`.
|
||||
- The corporate CA bundle is copied into the build context by
|
||||
`scripts/docker-prepare-ca.sh` so cargo trusts `nexus.local`.
|
||||
|
||||
```text
|
||||
/api/v4/websocket
|
||||
```
|
||||
Do not hand-pin transitive dependency versions. If a dependency needs
|
||||
updating, run `cargo update`, then `scripts/dev-check.sh`, then the Docker
|
||||
build. The resolver handles MSRV compatibility.
|
||||
|
||||
WebSocket authentication can use standard API auth or an `authentication_challenge` action after connecting.
|
||||
|
||||
Authentication challenge shape:
|
||||
|
||||
```json
|
||||
{
|
||||
"seq": 1,
|
||||
"action": "authentication_challenge",
|
||||
"data": {
|
||||
"token": "mattermosttokengoeshere"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Successful response shape:
|
||||
|
||||
```json
|
||||
{
|
||||
"status": "OK",
|
||||
"seq_reply": 1
|
||||
}
|
||||
```
|
||||
|
||||
After successful authentication, Mattermost sends a `hello` event.
|
||||
|
||||
Direct message channel creation endpoint:
|
||||
|
||||
```text
|
||||
POST /api/v4/channels/direct
|
||||
```
|
||||
|
||||
Request body is an array of two user IDs. For self-DM MVP we will use:
|
||||
|
||||
```json
|
||||
["my_user_id", "my_user_id"]
|
||||
```
|
||||
|
||||
This must be verified against the target corporate Mattermost 10.9.3 instance during implementation.
|
||||
`bridge/rust-toolchain.toml` pins the host toolchain only. It is deliberately
|
||||
not copied into the Docker image; the image uses its preinstalled toolchain.
|
||||
|
||||
## Repository layout
|
||||
|
||||
@@ -100,201 +63,95 @@ This must be verified against the target corporate Mattermost 10.9.3 instance du
|
||||
├── compose.yaml
|
||||
├── docker/
|
||||
│ ├── Dockerfile
|
||||
│ └── entrypoint.sh
|
||||
│ ├── entrypoint.sh
|
||||
│ └── certs/ generated CA bundle for the build context
|
||||
├── docs/
|
||||
│ ├── architecture.md
|
||||
│ ├── protocol.md
|
||||
│ ├── mvp-checklist.md
|
||||
│ ├── mattermost-10.9.3-notes.md
|
||||
│ ├── tls-self-signed.md
|
||||
│ └── docker.md
|
||||
├── scripts/
|
||||
│ ├── bootstrap-tree.sh
|
||||
│ ├── dev-check.sh
|
||||
│ ├── docker-build.sh
|
||||
│ ├── docker-up.sh
|
||||
│ ├── docker-down.sh
|
||||
│ └── smoke-ping.sh
|
||||
├── bridge/
|
||||
│ ├── Cargo.toml
|
||||
│ ├── Cargo.lock
|
||||
│ ├── rust-toolchain.toml
|
||||
│ ├── .cargo/config.toml
|
||||
│ └── crates/
|
||||
│ ├── mm-bridge/
|
||||
│ ├── mm-core/
|
||||
│ ├── mm-client/
|
||||
│ ├── mm-store/
|
||||
│ └── mm-web/
|
||||
│ ├── mm-core/ domain types, ids, errors (no network)
|
||||
│ ├── mm-client/ Mattermost REST/WebSocket client
|
||||
│ ├── mm-store/ token and server-config storage
|
||||
│ ├── mm-web/ web status UI
|
||||
│ └── mm-bridge/ daemon: TCP JSONL, routing, app state
|
||||
├── lisp/
|
||||
│ ├── mattermost.el
|
||||
│ ├── mattermost-custom.el
|
||||
│ ├── mattermost-process.el
|
||||
│ ├── mattermost-protocol.el
|
||||
│ ├── mattermost-server.el
|
||||
│ ├── mattermost-model.el
|
||||
│ ├── mattermost-buffer.el
|
||||
│ ├── mattermost-dm.el
|
||||
│ ├── mattermost-channel.el
|
||||
│ ├── mattermost-thread.el
|
||||
│ ├── mattermost-compose.el
|
||||
│ ├── mattermost-faces.el
|
||||
│ └── mattermost-utils.el
|
||||
└── tests/
|
||||
├── elisp/
|
||||
└── smoke/
|
||||
```
|
||||
|
||||
## Planned bridge crates
|
||||
## Data directory
|
||||
|
||||
### `mm-core`
|
||||
|
||||
Domain types and shared errors.
|
||||
|
||||
No network code.
|
||||
|
||||
Planned types:
|
||||
|
||||
- `ServerId`
|
||||
- `TeamId`
|
||||
- `ChannelId`
|
||||
- `UserId`
|
||||
- `PostId`
|
||||
- normalized `Server`
|
||||
- normalized `Team`
|
||||
- normalized `Channel`
|
||||
- normalized `User`
|
||||
- normalized `Post`
|
||||
- normalized errors
|
||||
|
||||
### `mm-client`
|
||||
|
||||
Mattermost REST and WebSocket client.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- login/password
|
||||
- bearer token requests
|
||||
- REST calls
|
||||
- WebSocket connection
|
||||
- WebSocket authentication challenge
|
||||
- event parsing
|
||||
- reconnect support
|
||||
- TLS CA configuration
|
||||
|
||||
### `mm-store`
|
||||
|
||||
Local cache/session storage.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- session token file
|
||||
- PAT file
|
||||
- lightweight cache metadata
|
||||
- server-scoped paths
|
||||
|
||||
MVP storage is plain text/json without encryption.
|
||||
|
||||
### `mm-bridge`
|
||||
|
||||
Main daemon.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- TCP JSONL server for Emacs
|
||||
- request routing
|
||||
- app state
|
||||
- connection manager
|
||||
- forced refresh handling
|
||||
- event fanout to Emacs clients
|
||||
|
||||
### `mm-web`
|
||||
|
||||
Web status UI.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- `/health`
|
||||
- `/status`
|
||||
- simple HTML status page
|
||||
- connection state
|
||||
- last error
|
||||
- Mattermost server version
|
||||
- authenticated user summary, without secrets
|
||||
|
||||
## Emacs package design
|
||||
|
||||
MVP should eventually provide:
|
||||
|
||||
```elisp
|
||||
(use-package mattermost
|
||||
:load-path "~/path/to/mattermost-el/lisp"
|
||||
:custom
|
||||
(mattermost-bridge-host "127.0.0.1")
|
||||
(mattermost-bridge-port 8765)
|
||||
(mattermost-thread-display 'separate-buffer)
|
||||
:bind
|
||||
(("C-c m c" . mattermost-connect)
|
||||
("C-c m s" . mattermost-open-self-dm)
|
||||
("C-c m g" . mattermost-refresh)))
|
||||
```
|
||||
|
||||
Thread display option:
|
||||
|
||||
```elisp
|
||||
mattermost-thread-display
|
||||
```
|
||||
|
||||
Allowed values:
|
||||
`MM_DATA_DIR` (default `/data` in Docker, `~/.local/share/emacs-mattermost`
|
||||
on the host):
|
||||
|
||||
```text
|
||||
separate-buffer
|
||||
inline
|
||||
<data_dir>/tokens/<server_id>.token bearer token, mode 0600, atomic write
|
||||
<data_dir>/servers/<server_id>.json non-secret server config
|
||||
```
|
||||
|
||||
MVP implements `separate-buffer` first. `inline` can be added later.
|
||||
`server_id` must match `[A-Za-z0-9_-]+`. This prevents path traversal and
|
||||
keeps filenames predictable for future multiserver support.
|
||||
|
||||
## Buffer naming rule
|
||||
|
||||
Even though MVP implements only one active server connection, names must already include server identity.
|
||||
|
||||
Planned examples:
|
||||
## Ports
|
||||
|
||||
```text
|
||||
*Mattermost[work]/DM:self*
|
||||
*Mattermost[work]/team:dev/channel:town-square*
|
||||
*Mattermost[work]/team:dev/thread:post-id*
|
||||
127.0.0.1:8765 bridge TCP JSONL (Emacs connects here)
|
||||
127.0.0.1:8766 web status UI (/ , /health , /status)
|
||||
```
|
||||
|
||||
For direct messages with users later:
|
||||
Both are bound to localhost only.
|
||||
|
||||
```text
|
||||
*Mattermost[work]/team:dev/DM:alice*
|
||||
*Mattermost[other]/team:platform/DM:alice*
|
||||
## Quick start
|
||||
|
||||
Start the bridge:
|
||||
|
||||
```bash
|
||||
./scripts/docker-up.sh
|
||||
```
|
||||
|
||||
This is required to avoid confusion between same usernames on different servers or teams.
|
||||
Check it:
|
||||
|
||||
## Online update rule
|
||||
```bash
|
||||
./scripts/smoke-ping.sh
|
||||
./scripts/smoke-web.sh
|
||||
```
|
||||
|
||||
Open buffers must update online from bridge events.
|
||||
Status page: http://127.0.0.1:8766/
|
||||
|
||||
`g` is not just rereading local data. It must:
|
||||
Stop:
|
||||
|
||||
1. ask bridge to check connection health;
|
||||
2. reconnect WebSocket if needed;
|
||||
3. refetch current buffer data from Mattermost REST API;
|
||||
4. replace buffer contents from server state;
|
||||
5. preserve user's unsent input where possible.
|
||||
```bash
|
||||
./scripts/docker-down.sh
|
||||
```
|
||||
|
||||
## MVP command set
|
||||
Local development without Docker:
|
||||
|
||||
Bridge methods for MVP:
|
||||
```bash
|
||||
./scripts/dev-check.sh # fmt check + cargo check/test --locked
|
||||
cd bridge && cargo run -p mm-bridge
|
||||
```
|
||||
|
||||
## Protocol
|
||||
|
||||
One JSON object per line over TCP. See `docs/protocol.md`.
|
||||
|
||||
Implemented methods:
|
||||
|
||||
```text
|
||||
ping
|
||||
status
|
||||
```
|
||||
|
||||
Planned MVP methods:
|
||||
|
||||
```text
|
||||
connect
|
||||
me
|
||||
teams
|
||||
open_self_dm
|
||||
list_channels
|
||||
get_history
|
||||
send_post
|
||||
@@ -302,156 +159,38 @@ reply_post
|
||||
mark_read
|
||||
```
|
||||
|
||||
Additional internal/self-DM helper method planned:
|
||||
## Emacs package (planned)
|
||||
|
||||
```text
|
||||
open_self_dm
|
||||
```elisp
|
||||
(use-package mattermost
|
||||
:load-path "~/Documents/emacs-mattermost/lisp"
|
||||
:custom
|
||||
(mattermost-bridge-host "127.0.0.1")
|
||||
(mattermost-bridge-port 8765)
|
||||
(mattermost-thread-display 'separate-buffer))
|
||||
```
|
||||
|
||||
This helper is needed because the first vertical slice starts from messages to self.
|
||||
Buffer naming keeps server identity visible even in single-server MVP:
|
||||
|
||||
## MVP implementation checklist
|
||||
|
||||
### Phase 0 — repository bootstrap
|
||||
|
||||
- [x] Create repository tree script.
|
||||
- [x] Create README with fixed decisions.
|
||||
- [ ] Fill initial docs.
|
||||
- [ ] Add `.gitignore`.
|
||||
- [ ] Add `.dockerignore`.
|
||||
|
||||
### Phase 1 — minimal Rust bridge
|
||||
|
||||
- [ ] Add Cargo workspace.
|
||||
- [ ] Add crate manifests.
|
||||
- [ ] Add minimal `mm-core` types.
|
||||
- [ ] Add JSONL protocol types.
|
||||
- [ ] Add TCP listener.
|
||||
- [ ] Implement `ping`.
|
||||
- [ ] Implement `status`.
|
||||
- [ ] Add smoke test for `ping`.
|
||||
|
||||
### Phase 2 — Docker and status web UI
|
||||
|
||||
- [ ] Add Dockerfile.
|
||||
- [ ] Add compose.yaml.
|
||||
- [ ] Add bridge config from environment.
|
||||
- [ ] Add `/health`.
|
||||
- [ ] Add `/status` JSON.
|
||||
- [ ] Add simple HTML status page.
|
||||
- [ ] Verify bridge runs separately from Emacs.
|
||||
|
||||
### Phase 3 — authentication
|
||||
|
||||
- [ ] Implement login/password against Mattermost 10.9.3.
|
||||
- [ ] Save session token to cache file.
|
||||
- [ ] Load saved session token.
|
||||
- [ ] Support PAT token.
|
||||
- [ ] Implement `connect`.
|
||||
- [ ] Implement `me`.
|
||||
- [ ] Ensure tokens are never logged.
|
||||
|
||||
### Phase 4 — self-DM vertical slice
|
||||
|
||||
- [ ] Implement `teams`.
|
||||
- [ ] Resolve current user.
|
||||
- [ ] Create/get self direct channel.
|
||||
- [ ] Implement `open_self_dm`.
|
||||
- [ ] Implement `get_history`.
|
||||
- [ ] Implement `send_post`.
|
||||
- [ ] Connect Emacs to bridge.
|
||||
- [ ] Open self-DM buffer.
|
||||
- [ ] Display raw messages.
|
||||
- [ ] Send message from Emacs.
|
||||
- [ ] Receive own message online.
|
||||
|
||||
### Phase 5 — WebSocket online updates
|
||||
|
||||
- [ ] Open Mattermost WebSocket.
|
||||
- [ ] Authenticate with `authentication_challenge`.
|
||||
- [ ] Handle `hello`.
|
||||
- [ ] Handle `posted`.
|
||||
- [ ] Handle `post_edited`.
|
||||
- [ ] Handle `post_deleted`.
|
||||
- [ ] Fan out normalized events to Emacs.
|
||||
- [ ] Update open self-DM buffer online.
|
||||
- [ ] Add reconnect loop.
|
||||
- [ ] Implement forced refresh path for `g`.
|
||||
|
||||
### Phase 6 — replies/threads
|
||||
|
||||
- [ ] Implement `reply_post`.
|
||||
- [ ] Add thread buffer.
|
||||
- [ ] Add `mattermost-thread-display`.
|
||||
- [ ] Default to separate thread buffers.
|
||||
- [ ] Keep inline mode as future-compatible option.
|
||||
- [ ] Show server/team context in thread buffer names.
|
||||
|
||||
### Phase 7 — channels
|
||||
|
||||
- [ ] Implement `list_channels`.
|
||||
- [ ] Add channel list buffer.
|
||||
- [ ] Open channel buffer.
|
||||
- [ ] Load channel history.
|
||||
- [ ] Send channel message.
|
||||
- [ ] Receive channel events online.
|
||||
- [ ] Implement `mark_read`.
|
||||
- [ ] Forced refresh with `g`.
|
||||
|
||||
### Phase 8 — TLS/self-signed support
|
||||
|
||||
- [ ] Add explicit CA file configuration.
|
||||
- [ ] Document Docker CA mount.
|
||||
- [ ] Document Emacs CA settings separately.
|
||||
- [ ] Do not disable certificate verification by default in Rust bridge.
|
||||
- [ ] Add clear error message for TLS failures.
|
||||
|
||||
### Phase 9 — hardening
|
||||
|
||||
- [ ] Add structured errors.
|
||||
- [ ] Add request timeouts.
|
||||
- [ ] Add rate-limit handling.
|
||||
- [ ] Add basic integration smoke tests.
|
||||
- [ ] Add Emacs Lisp tests.
|
||||
- [ ] Review logs for secret leaks.
|
||||
- [ ] Review cache file permissions.
|
||||
- [ ] Review multiserver-ready identifiers and naming.
|
||||
```text
|
||||
*Mattermost[work]/DM:self*
|
||||
*Mattermost[work]/team:dev/channel:town-square*
|
||||
*Mattermost[work]/team:dev/thread:post-id*
|
||||
```
|
||||
|
||||
## Development rules
|
||||
|
||||
- Work in small atomic steps.
|
||||
- Every code answer must contain full files, not patches.
|
||||
- Code files should stay under 300 lines.
|
||||
- Split modules before they grow too large.
|
||||
- Keep README checklist updated.
|
||||
- Prefer simple implementations that can be verified immediately.
|
||||
- Do not implement multiserver UI yet, but keep server-scoped IDs and state boundaries.
|
||||
- Do not render Markdown in MVP.
|
||||
- Do not add typing or reactions in MVP.
|
||||
- Do not make Emacs responsible for Mattermost protocol details.
|
||||
- Do not store authoritative chat state in Emacs buffers.
|
||||
- Work in small atomic steps; each step must leave the project buildable.
|
||||
- Provide full file contents, not patches.
|
||||
- Keep code files under 300 lines; split modules before they grow.
|
||||
- Prefer automated fixes (`cargo fmt`, MSRV-aware resolver) over manual edits.
|
||||
- Commit `Cargo.lock` only after a fully green build.
|
||||
- Keep this README and `docs/mvp-checklist.md` updated.
|
||||
- Never log tokens, passwords, or auth headers.
|
||||
|
||||
## Bootstrap
|
||||
## Progress
|
||||
|
||||
Run:
|
||||
See `docs/mvp-checklist.md` for the detailed checklist.
|
||||
|
||||
```bash
|
||||
chmod +x scripts/bootstrap-tree.sh
|
||||
./scripts/bootstrap-tree.sh .
|
||||
```
|
||||
|
||||
The script creates directories and empty placeholder files. It also writes this README.
|
||||
|
||||
## Immediate next step
|
||||
|
||||
Next atomic step:
|
||||
|
||||
```text
|
||||
Add initial ignore files and documentation skeletons.
|
||||
```
|
||||
|
||||
After that:
|
||||
|
||||
```text
|
||||
Add Rust workspace and minimal compiling bridge with ping/status over TCP JSONL.
|
||||
```
|
||||
Current state: phases 0-3a complete (storage foundation).
|
||||
Next: phase 3b (REST client, auth, connect/me).
|
||||
|
||||
Generated
+1257
-6
File diff suppressed because it is too large
Load Diff
@@ -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"
|
||||
|
||||
@@ -1,10 +1,48 @@
|
||||
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 {
|
||||
#[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()),
|
||||
"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(
|
||||
@@ -15,20 +53,344 @@ pub fn handle_request(request: protocol::Request) -> protocol::Response {
|
||||
}
|
||||
}
|
||||
|
||||
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),
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn response_line(line: &str) -> String {
|
||||
let response = handle_line(line);
|
||||
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),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn protocol_err(id: impl Into<String>, msg: &str) -> protocol::Response {
|
||||
protocol::Response::err(id, BridgeError::new(ErrorKind::InvalidRequest, msg))
|
||||
}
|
||||
|
||||
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 {
|
||||
let response = protocol::Response::err(id, error);
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
|
||||
pub fn status_result() -> Value {
|
||||
serde_json::to_value(current_status()).unwrap_or_else(|_| {
|
||||
status
|
||||
}
|
||||
|
||||
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"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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?;
|
||||
}
|
||||
|
||||
@@ -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 @@
|
||||
//! auth module placeholder.
|
||||
//! Authentication helpers.
|
||||
|
||||
@@ -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!()
|
||||
}
|
||||
@@ -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())
|
||||
}
|
||||
}
|
||||
@@ -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 @@
|
||||
//! rest module placeholder.
|
||||
//! REST API endpoints.
|
||||
|
||||
@@ -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 @@
|
||||
//! ws module placeholder.
|
||||
//! WebSocket client.
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
@@ -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
@@ -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"]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
+38
-10
@@ -56,18 +56,46 @@
|
||||
- [x] Add simple HTML status page.
|
||||
- [x] Add Docker helper scripts.
|
||||
- [x] Add web smoke script.
|
||||
- [ ] Verify local bridge + web smoke.
|
||||
- [ ] Verify Docker Compose bridge + web smoke.
|
||||
- [x] Verify local bridge + web smoke.
|
||||
- [x] Verify Docker Compose bridge + web smoke.
|
||||
|
||||
## Phase 3 — authentication
|
||||
## Phase 3a — storage foundation (no network)
|
||||
|
||||
- [ ] Implement login/password against Mattermost 10.9.3.
|
||||
- [ ] Save session token to cache file.
|
||||
- [ ] Load saved session token.
|
||||
- [ ] Support PAT token.
|
||||
- [ ] Implement connect.
|
||||
- [ ] Implement me.
|
||||
- [ ] Ensure tokens are never logged.
|
||||
- [x] mm-core: User model.
|
||||
- [x] mm-core: ServerConfig model.
|
||||
- [x] mm-core: ServerSummary.has_token.
|
||||
- [x] mm-store: TokenStore (load/save/delete/list).
|
||||
- [x] Atomic token writes via temp file + rename.
|
||||
- [x] Private file mode 0600 on Unix.
|
||||
- [x] server_id validation against path traversal.
|
||||
- [x] mm-store: ServerStore for non-secret config.
|
||||
- [x] MM_DATA_DIR config with host default.
|
||||
- [x] App state carries data_dir.
|
||||
- [x] status reads persisted stores, never exposes secrets.
|
||||
- [x] Unit tests for stores and status.
|
||||
- [x] Verify cargo test locally.
|
||||
- [x] Verify status shows a stored server without leaking the token.
|
||||
|
||||
## Phase 3b — authentication (network)
|
||||
|
||||
### 3b-1: HTTP client foundation
|
||||
|
||||
- [ ] mm-client crate skeleton.
|
||||
- [ ] reqwest dependency with rustls-tls-native-roots (for system CA) + explicit CA support.
|
||||
- [ ] Client struct with base_url and optional ca_file.
|
||||
- [ ] login(login_id, password) -> Result<String, Error> (extracts Token header).
|
||||
- [ ] get_me(token) -> Result<User, Error>.
|
||||
- [ ] Unit/integration tests for client construction.
|
||||
|
||||
### 3b-2: Bridge integration
|
||||
|
||||
- [ ] Implement connect method in bridge.
|
||||
- [ ] Implement me method in bridge.
|
||||
- [ ] Save session token via TokenStore on successful connect.
|
||||
- [ ] Load saved token on startup (future: auto-reconnect).
|
||||
- [ ] Support PAT token (same flow, just skip login).
|
||||
- [ ] Map Mattermost API errors to normalized error codes.
|
||||
- [ ] Ensure tokens/passwords are never logged.
|
||||
|
||||
## Phase 4 — self-DM vertical slice
|
||||
|
||||
|
||||
Executable
+14
@@ -0,0 +1,14 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
HOST="${MM_BRIDGE_HOST:-127.0.0.1}"
|
||||
PORT="${MM_BRIDGE_PORT:-8765}"
|
||||
|
||||
# Read JSON from stdin or argument
|
||||
if [[ $# -gt 0 ]]; then
|
||||
INPUT="$1"
|
||||
else
|
||||
read -r INPUT
|
||||
fi
|
||||
|
||||
printf '%s\n' "$INPUT" | nc -w 2 "$HOST" "$PORT"
|
||||
Reference in New Issue
Block a user