diff --git a/README.md b/README.md index 8ecd407..2af9281 100644 --- a/README.md +++ b/README.md @@ -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 +/tokens/.token bearer token, mode 0600, atomic write +/servers/.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). diff --git a/bridge/Cargo.lock b/bridge/Cargo.lock index 4b86dc8..3206513 100644 --- a/bridge/Cargo.lock +++ b/bridge/Cargo.lock @@ -89,18 +89,184 @@ dependencies = [ "tracing", ] +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + [[package]] name = "bytes" version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "cc" +version = "1.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45" +dependencies = [ + "find-msvc-tools", + "shlex", +] + [[package]] name = "cfg-if" version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + [[package]] name = "form_urlencoded" version = "1.2.2" @@ -110,12 +276,27 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + [[package]] name = "futures-core" version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + [[package]] name = "futures-task" version = "0.3.34" @@ -134,6 +315,58 @@ dependencies = [ "slab", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi", + "rand_core", + "wasm-bindgen", +] + +[[package]] +name = "h2" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + [[package]] name = "http" version = "1.5.0" @@ -187,7 +420,9 @@ checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" dependencies = [ "atomic-waker", "bytes", + "futures-channel", "futures-core", + "h2", "http", "http-body", "httparse", @@ -196,6 +431,39 @@ dependencies = [ "pin-project-lite", "smallvec", "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "rustls-native-certs", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-tls" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0" +dependencies = [ + "bytes", + "http-body-util", + "hyper", + "hyper-util", + "native-tls", + "tokio", + "tokio-native-tls", + "tower-service", ] [[package]] @@ -204,21 +472,163 @@ version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" dependencies = [ + "base64 0.23.1", "bytes", + "futures-channel", + "futures-util", "http", "http-body", + "httparse", "hyper", + "ipnet", + "libc", + "percent-encoding", "pin-project-lite", + "socket2", + "system-configuration", "tokio", "tower-service", + "tracing", + "windows-registry", ] +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + [[package]] name = "itoa" version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" +[[package]] +name = "js-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8dc09d2154098bbf4ef54eab6b117a3c24cbbffe94046b16ee6d6d4510584d3a" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + [[package]] name = "lazy_static" version = "1.5.1" @@ -231,12 +641,30 @@ version = "0.2.191" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + [[package]] name = "log" version = "0.4.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + [[package]] name = "matchers" version = "0.2.0" @@ -272,7 +700,7 @@ checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" dependencies = [ "libc", "wasi", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -280,10 +708,13 @@ name = "mm-bridge" version = "0.1.0" dependencies = [ "anyhow", + "mm-client", "mm-core", + "mm-store", "mm-web", "serde", "serde_json", + "tempfile", "tokio", "tracing", "tracing-subscriber", @@ -294,6 +725,13 @@ name = "mm-client" version = "0.1.0" dependencies = [ "mm-core", + "reqwest", + "serde", + "serde_json", + "tempfile", + "thiserror 1.0.69", + "tokio", + "tracing", ] [[package]] @@ -301,7 +739,7 @@ name = "mm-core" version = "0.1.0" dependencies = [ "serde", - "thiserror", + "thiserror 1.0.69", ] [[package]] @@ -309,6 +747,8 @@ name = "mm-store" version = "0.1.0" dependencies = [ "mm-core", + "serde_json", + "tempfile", ] [[package]] @@ -323,13 +763,36 @@ dependencies = [ "tracing", ] +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "native-tls" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2" +dependencies = [ + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + [[package]] name = "nu-ansi-term" version = "0.50.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" dependencies = [ - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -338,6 +801,49 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +[[package]] +name = "openssl" +version = "0.10.82" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4de8111e94a56adca7ebfe6c365b6d42f99deb69b74b6becacd4204e2f193aa2" +dependencies = [ + "bitflags", + "cfg-if", + "foreign-types", + "libc", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + +[[package]] +name = "openssl-sys" +version = "0.9.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19c413d6ec9ebaf5e1c829d355cb3e9f783778d700f135be0921d52fce3c60ae" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -350,6 +856,21 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -359,6 +880,62 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror 2.0.21", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror 2.0.21", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + [[package]] name = "quote" version = "1.0.47" @@ -368,6 +945,38 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core", +] + [[package]] name = "regex-automata" version = "0.4.18" @@ -385,6 +994,130 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "encoding_rs", + "futures-core", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-tls", + "hyper-util", + "js-sys", + "log", + "mime", + "native-tls", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-native-certs", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-native-tls", + "tokio-rustls", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -397,6 +1130,44 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "serde" version = "1.0.229" @@ -472,6 +1243,18 @@ dependencies = [ "lazy_static", ] +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + [[package]] name = "slab" version = "0.4.12" @@ -491,9 +1274,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys", + "windows-sys 0.61.2", ] +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "syn" version = "2.0.119" @@ -521,6 +1316,54 @@ name = "sync_wrapper" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "system-configuration" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b" +dependencies = [ + "bitflags", + "core-foundation 0.9.4", + "system-configuration-sys", +] + +[[package]] +name = "system-configuration-sys" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] [[package]] name = "thiserror" @@ -528,7 +1371,16 @@ version = "1.0.69" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" dependencies = [ - "thiserror-impl", + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", ] [[package]] @@ -542,6 +1394,17 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "thread_local" version = "1.1.10" @@ -551,6 +1414,22 @@ dependencies = [ "cfg-if", ] +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + [[package]] name = "tokio" version = "1.54.1" @@ -563,7 +1442,7 @@ dependencies = [ "pin-project-lite", "socket2", "tokio-macros", - "windows-sys", + "windows-sys 0.61.2", ] [[package]] @@ -577,6 +1456,40 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "tokio-native-tls" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2" +dependencies = [ + "native-tls", + "tokio", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + [[package]] name = "tower" version = "0.5.3" @@ -593,6 +1506,24 @@ dependencies = [ "tracing", ] +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + [[package]] name = "tower-layer" version = "0.3.3" @@ -667,30 +1598,197 @@ dependencies = [ "tracing-log", ] +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + [[package]] name = "unicode-ident" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + [[package]] name = "valuable" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasm-bindgen" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0181c14ddd6c7b8b0b0132a5f1ea2f32be0d893cd3ea97b6e3b28886b8a3d1c" +dependencies = [ + "cfg-if", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e931a02a39abdbf66966fc35902b5ed58344750a70885bed4ebb3d8eaf28ed9" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ca4b54280e455bd831e33a6b8e734baf432fe63fbc35c42ac14ce67a043a53a" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.10", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.130" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b1f9c3798725016c6ee5f2f57869ec0831e8bbc0ab0310a86e787e97f41389e" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-registry" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720" +dependencies = [ + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -700,6 +1798,159 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "zmij" version = "1.0.23" diff --git a/bridge/crates/mm-bridge/Cargo.toml b/bridge/crates/mm-bridge/Cargo.toml index 33db19b..bcd0170 100644 --- a/bridge/crates/mm-bridge/Cargo.toml +++ b/bridge/crates/mm-bridge/Cargo.toml @@ -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" diff --git a/bridge/crates/mm-bridge/src/app/mod.rs b/bridge/crates/mm-bridge/src/app/mod.rs index eec14c2..67d823e 100644 --- a/bridge/crates/mm-bridge/src/app/mod.rs +++ b/bridge/crates/mm-bridge/src/app/mod.rs @@ -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, +} + +#[derive(Debug, Clone)] +pub struct App { + data_dir: PathBuf, + connections: Arc>>, +} + +impl App { + pub fn new(data_dir: impl Into) -> 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 { + 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 { + 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 { + 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 { + 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 { + 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, 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) -> 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")); - } -} diff --git a/bridge/crates/mm-bridge/src/config/mod.rs b/bridge/crates/mm-bridge/src/config/mod.rs index 12de7d3..1d358c6 100644 --- a/bridge/crates/mm-bridge/src/config/mod.rs +++ b/bridge/crates/mm-bridge/src/config/mod.rs @@ -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 { 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 { Ok(value) } +fn read_data_dir() -> anyhow::Result { + 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"); diff --git a/bridge/crates/mm-bridge/src/server/mod.rs b/bridge/crates/mm-bridge/src/server/mod.rs index e52d3a8..3817ec8 100644 --- a/bridge/crates/mm-bridge/src/server/mod.rs +++ b/bridge/crates/mm-bridge/src/server/mod.rs @@ -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"); } }); diff --git a/bridge/crates/mm-bridge/src/status/mod.rs b/bridge/crates/mm-bridge/src/status/mod.rs index ac1ec14..1e13f58 100644 --- a/bridge/crates/mm-bridge/src/status/mod.rs +++ b/bridge/crates/mm-bridge/src/status/mod.rs @@ -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 = 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")); + } } diff --git a/bridge/crates/mm-bridge/src/transport/mod.rs b/bridge/crates/mm-bridge/src/transport/mod.rs index 045a981..26907c6 100644 --- a/bridge/crates/mm-bridge/src/transport/mod.rs +++ b/bridge/crates/mm-bridge/src/transport/mod.rs @@ -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?; } diff --git a/bridge/crates/mm-client/Cargo.toml b/bridge/crates/mm-client/Cargo.toml index c121ce4..02ea440 100644 --- a/bridge/crates/mm-client/Cargo.toml +++ b/bridge/crates/mm-client/Cargo.toml @@ -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" diff --git a/bridge/crates/mm-client/src/auth/mod.rs b/bridge/crates/mm-client/src/auth/mod.rs index 341d4d4..53cdf04 100644 --- a/bridge/crates/mm-client/src/auth/mod.rs +++ b/bridge/crates/mm-client/src/auth/mod.rs @@ -1 +1 @@ -//! auth module placeholder. +//! Authentication helpers. diff --git a/bridge/crates/mm-client/src/client/mod.rs b/bridge/crates/mm-client/src/client/mod.rs new file mode 100644 index 0000000..491e39b --- /dev/null +++ b/bridge/crates/mm-client/src/client/mod.rs @@ -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 { + 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 { + 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 { + 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, 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 = response.json().await.map_err(ClientError::Http)?; + Ok(teams) + } + + pub async fn create_direct_channel( + &self, + token: &str, + user_ids: &[String], + ) -> Result { + 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, 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, + posts: std::collections::HashMap, + } + + let data: PostsResponse = response.json().await.map_err(ClientError::Http)?; + + // Normalize to ordered vector + let mut posts: Vec = 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 { + 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 { + 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::(&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 { + handle_api_error_string(response).await?; + unreachable!() +} +async fn handle_api_error_vec(response: reqwest::Response) -> Result, ClientError> { + handle_api_error_string(response).await?; + unreachable!() +} +async fn handle_api_error_channel(response: reqwest::Response) -> Result { + handle_api_error_string(response).await?; + unreachable!() +} +async fn handle_api_error_post(response: reqwest::Response) -> Result { + handle_api_error_string(response).await?; + unreachable!() +} diff --git a/bridge/crates/mm-client/src/error/mod.rs b/bridge/crates/mm-client/src/error/mod.rs new file mode 100644 index 0000000..50f5b92 --- /dev/null +++ b/bridge/crates/mm-client/src/error/mod.rs @@ -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 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()) + } +} diff --git a/bridge/crates/mm-client/src/lib.rs b/bridge/crates/mm-client/src/lib.rs index 81fe718..03fd54e 100644 --- a/bridge/crates/mm-client/src/lib.rs +++ b/bridge/crates/mm-client/src/lib.rs @@ -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; diff --git a/bridge/crates/mm-client/src/rest/mod.rs b/bridge/crates/mm-client/src/rest/mod.rs index f32e3c6..585775c 100644 --- a/bridge/crates/mm-client/src/rest/mod.rs +++ b/bridge/crates/mm-client/src/rest/mod.rs @@ -1 +1 @@ -//! rest module placeholder. +//! REST API endpoints. diff --git a/bridge/crates/mm-client/src/tls/mod.rs b/bridge/crates/mm-client/src/tls/mod.rs index 017e074..7899d24 100644 --- a/bridge/crates/mm-client/src/tls/mod.rs +++ b/bridge/crates/mm-client/src/tls/mod.rs @@ -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 { + 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) +} diff --git a/bridge/crates/mm-client/src/ws/mod.rs b/bridge/crates/mm-client/src/ws/mod.rs index bab9277..f8487c2 100644 --- a/bridge/crates/mm-client/src/ws/mod.rs +++ b/bridge/crates/mm-client/src/ws/mod.rs @@ -1 +1 @@ -//! ws module placeholder. +//! WebSocket client. diff --git a/bridge/crates/mm-core/src/lib.rs b/bridge/crates/mm-core/src/lib.rs index 7c35feb..88a9659 100644 --- a/bridge/crates/mm-core/src/lib.rs +++ b/bridge/crates/mm-core/src/lib.rs @@ -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, +}; diff --git a/bridge/crates/mm-core/src/model/mod.rs b/bridge/crates/mm-core/src/model/mod.rs index 48afda2..a25f9f1 100644 --- a/bridge/crates/mm-core/src/model/mod.rs +++ b/bridge/crates/mm-core/src/model/mod.rs @@ -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, + pub message: String, + pub create_at: i64, + pub update_at: i64, + pub delete_at: i64, +} diff --git a/bridge/crates/mm-store/Cargo.toml b/bridge/crates/mm-store/Cargo.toml index a3aee5a..472e0da 100644 --- a/bridge/crates/mm-store/Cargo.toml +++ b/bridge/crates/mm-store/Cargo.toml @@ -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" diff --git a/bridge/crates/mm-store/src/cache/mod.rs b/bridge/crates/mm-store/src/cache/mod.rs index 75435f4..dfc4225 100644 --- a/bridge/crates/mm-store/src/cache/mod.rs +++ b/bridge/crates/mm-store/src/cache/mod.rs @@ -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) -> Self { + Self { + dir: data_dir.as_ref().join("servers"), + } + } + + pub fn load(&self, server_id: &ServerId) -> Result, 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, BridgeError> { + list_stems(&self.dir, "json") + } + + fn path(&self, server_id: &ServerId) -> Result { + 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 = store + .list_servers() + .unwrap() + .into_iter() + .map(|id| id.as_str().to_string()) + .collect(); + assert_eq!(names, vec!["alpha", "zeta"]); + } +} diff --git a/bridge/crates/mm-store/src/lib.rs b/bridge/crates/mm-store/src/lib.rs index 643b093..9ba08f9 100644 --- a/bridge/crates/mm-store/src/lib.rs +++ b/bridge/crates/mm-store/src/lib.rs @@ -1,6 +1,14 @@ //! Local cache and session storage. //! -//! Placeholder crate. Implementation starts at the authentication step. +//! Layout under the data directory: +//! +//! /tokens/.token - plain bearer token, private mode +//! /servers/.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; diff --git a/bridge/crates/mm-store/src/session/mod.rs b/bridge/crates/mm-store/src/session/mod.rs index ee4db3a..e3db36a 100644 --- a/bridge/crates/mm-store/src/session/mod.rs +++ b/bridge/crates/mm-store/src/session/mod.rs @@ -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) -> Self { + Self { + dir: data_dir.as_ref().join("tokens"), + } + } + + pub fn load(&self, server_id: &ServerId) -> Result, 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, BridgeError> { + list_stems(&self.dir, "token") + } + + fn path(&self, server_id: &ServerId) -> Result { + 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, 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); + } +} diff --git a/docs/mvp-checklist.md b/docs/mvp-checklist.md index 4b1afde..a258d34 100644 --- a/docs/mvp-checklist.md +++ b/docs/mvp-checklist.md @@ -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 (extracts Token header). +- [ ] get_me(token) -> Result. +- [ ] 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 diff --git a/scripts/mm-cli.sh b/scripts/mm-cli.sh new file mode 100755 index 0000000..991aeb5 --- /dev/null +++ b/scripts/mm-cli.sh @@ -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"