diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index cdb805a..862ffaf 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -71,10 +71,10 @@ jobs: services=$(sh ci/changed-services.sh) echo "changed since the last deployment: ${services:-nothing}" case " $services " in - *" backend "*|*" worker "*|*" forum "*|*" horoscope-api "*) ;; + *" backend "*|*" worker "*|*" forum "*|*" mcp "*|*" horoscope-api "*) ;; *) echo "no Rust service changed: tests skipped"; exit 0 ;; esac - cargo test --locked -p backend -p worker -p forum -p object-storage -p db -p horoscope-client -p service-kit -p analysis-prompt -p email-templates + cargo test --locked -p backend -p worker -p forum -p mcp -p object-storage -p db -p horoscope-client -p service-kit -p analysis-prompt -p email-templates build: needs: test @@ -127,7 +127,7 @@ jobs: set -eu apk add --no-cache -q curl jq prod=$(git ls-remote origin refs/heads/prod | cut -c1-12) - for svc in horoscope-api backend worker forum frontend; do + for svc in horoscope-api backend worker forum mcp frontend; do name="sorsfonalak-$svc" page=1 : > versions.tsv @@ -152,7 +152,7 @@ jobs: if: always() run: | docker logout "$REGISTRY" || true - for svc in horoscope-api backend worker forum frontend; do + for svc in horoscope-api backend worker forum mcp frontend; do docker images "$IMAGE_PREFIX-$svc" --format '{{.Repository}}:{{.Tag}}' | xargs -r docker rmi >/dev/null 2>&1 || true done docker image prune -f >/dev/null diff --git a/Cargo.lock b/Cargo.lock index 431ccf4..0d05e9c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -189,6 +189,7 @@ dependencies = [ "argon2", "axum", "axum-extra", + "base64 0.22.1", "db", "deunicode", "email-templates", @@ -205,7 +206,7 @@ dependencies = [ "serde", "serde_json", "service-kit", - "sha2", + "sha2 0.10.9", "sqlx", "thiserror", "time", @@ -249,7 +250,7 @@ version = "0.10.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" dependencies = [ - "digest", + "digest 0.10.7", ] [[package]] @@ -261,6 +262,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -350,6 +360,12 @@ version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + [[package]] name = "cookie" version = "0.18.2" @@ -446,6 +462,49 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "darling" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff" +dependencies = [ + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn 3.0.10", +] + +[[package]] +name = "darling_macro" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785" +dependencies = [ + "darling_core", + "quote", + "syn 3.0.10", +] + [[package]] name = "data-encoding" version = "2.11.1" @@ -465,7 +524,7 @@ dependencies = [ "base64 0.22.1", "rand 0.9.5", "serde", - "sha2", + "sha2 0.10.9", "sqlx", "time", "uuid", @@ -477,7 +536,7 @@ version = "0.7.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ - "const-oid", + "const-oid 0.9.6", "pem-rfc7468", "zeroize", ] @@ -503,12 +562,23 @@ version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", - "const-oid", - "crypto-common", + "block-buffer 0.10.4", + "const-oid 0.9.6", + "crypto-common 0.1.7", "subtle", ] +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid 0.10.3", + "crypto-common 0.2.2", +] + [[package]] name = "displaydoc" version = "0.2.7" @@ -526,6 +596,12 @@ version = "0.15.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" +[[package]] +name = "dyn-clone" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" + [[package]] name = "either" version = "1.19.0" @@ -720,7 +796,7 @@ dependencies = [ "serde", "serde_json", "service-kit", - "sha2", + "sha2 0.10.9", "sqlx", "thiserror", "time", @@ -732,6 +808,21 @@ dependencies = [ "uuid", ] +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + [[package]] name = "futures-channel" version = "0.3.34" @@ -776,6 +867,17 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "futures-sink" version = "0.3.34" @@ -794,8 +896,10 @@ version = "0.3.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" dependencies = [ + "futures-channel", "futures-core", "futures-io", + "futures-macro", "futures-sink", "futures-task", "memchr", @@ -818,7 +922,7 @@ name = "geo-tz" version = "0.1.0" dependencies = [ "deunicode", - "jiff", + "jiff 0.2.42", "serde", "thiserror", ] @@ -938,7 +1042,7 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" dependencies = [ - "digest", + "digest 0.10.7", ] [[package]] @@ -959,7 +1063,7 @@ dependencies = [ "axum", "geo-tz", "http-body-util", - "jiff", + "jiff 0.2.42", "serde", "serde_json", "service-kit", @@ -1035,6 +1139,15 @@ version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "hyper" version = "1.12.0" @@ -1178,6 +1291,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + [[package]] name = "idna" version = "1.1.0" @@ -1239,6 +1358,8 @@ checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", "hashbrown 0.17.1", + "serde", + "serde_core", ] [[package]] @@ -1259,8 +1380,22 @@ version = "0.2.42" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fefca06093eeaed707a905795e68206da0edca4edef23d2a3997a3ddbee462aa" dependencies = [ - "jiff-core", - "jiff-static", + "jiff-core 0.1.4", + "jiff-static 0.2.42", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", +] + +[[package]] +name = "jiff" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "107f2e89536b6818514025f6787b0d94d819e54fe3b40365275fc753de485b3f" +dependencies = [ + "jiff-core 1.0.2", + "jiff-static 1.0.3", "log", "portable-atomic", "portable-atomic-util", @@ -1276,18 +1411,39 @@ dependencies = [ "log", ] +[[package]] +name = "jiff-core" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d44c923edf2bf456a982253f1a9ee1f6e89e421dffd0065d9b9a581da0def58f" +dependencies = [ + "log", +] + [[package]] name = "jiff-static" version = "0.2.42" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41d3213549742662eea1a18e6c5af9be5dfbabeb7611ab71356a54928ec398f0" dependencies = [ - "jiff-core", + "jiff-core 0.1.4", "proc-macro2", "quote", "syn 2.0.119", ] +[[package]] +name = "jiff-static" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4996f71e569e3a3e32b925c28ef8f0027dc30bb1d594b33eeda409eea185f5c8" +dependencies = [ + "jiff-core 1.0.2", + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "js-sys" version = "0.3.107" @@ -1483,6 +1639,26 @@ version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" +[[package]] +name = "mcp" +version = "0.1.0" +dependencies = [ + "anyhow", + "axum", + "http-body-util", + "reqwest", + "rmcp", + "schemars", + "serde", + "serde_json", + "service-kit", + "sha2 0.10.9", + "tokio", + "tower", + "tower-http", + "tracing", +] + [[package]] name = "md-5" version = "0.10.6" @@ -1490,7 +1666,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" dependencies = [ "cfg-if", - "digest", + "digest 0.10.7", ] [[package]] @@ -1641,7 +1817,7 @@ dependencies = [ "bytes", "hmac", "reqwest", - "sha2", + "sha2 0.10.9", "thiserror", "time", "tokio", @@ -1694,6 +1870,12 @@ dependencies = [ "subtle", ] +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + [[package]] name = "pdf-writer" version = "0.15.0" @@ -2060,6 +2242,26 @@ dependencies = [ "bitflags", ] +[[package]] +name = "ref-cast" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3" +dependencies = [ + "ref-cast-impl", +] + +[[package]] +name = "ref-cast-impl" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "regex-automata" version = "0.4.18" @@ -2155,6 +2357,56 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rmcp" +version = "3.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc4fa9a7558c480e1817c0f02e9a73782001ac1f47fb9d26cc073915963282ea" +dependencies = [ + "async-trait", + "base64 0.23.1", + "bytes", + "futures", + "http", + "http-body", + "http-body-util", + "indexmap", + "jiff 1.0.3", + "libc", + "pastey", + "percent-encoding", + "pin-project-lite", + "rand 0.10.3", + "rmcp-macros", + "schemars", + "serde", + "serde_json", + "sha2 0.11.2", + "sse-stream", + "thiserror", + "tokio", + "tokio-stream", + "tokio-util", + "tower-service", + "tracing", + "unicode-general-category", + "unicode-normalization", + "uuid", +] + +[[package]] +name = "rmcp-macros" +version = "3.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43c1bf063ba32333267a8bc282ec33ae0edf56bf74890118cb0c7bf910a7a1c0" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "serde_json", + "syn 3.0.10", +] + [[package]] name = "roxmltree" version = "0.20.0" @@ -2176,8 +2428,8 @@ version = "0.9.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8573f03f5883dcaebdfcf4725caa1ecb9c15b2ef50c43a07b816e06799bb12d" dependencies = [ - "const-oid", - "digest", + "const-oid 0.9.6", + "digest 0.10.7", "num-bigint-dig", "num-integer", "num-traits", @@ -2262,6 +2514,31 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "schemars" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e" +dependencies = [ + "dyn-clone", + "ref-cast", + "schemars_derive", + "serde", + "serde_json", +] + +[[package]] +name = "schemars_derive" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1c3a92094fa7d61aa124645844facb6b554dfc797136d0f5fd1f890e2bffc69" +dependencies = [ + "proc-macro2", + "quote", + "serde_derive_internals", + "syn 3.0.10", +] + [[package]] name = "scopeguard" version = "1.2.0" @@ -2298,6 +2575,17 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "serde_derive_internals" +version = "0.30.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f852137cce035d6a4df67ccce505ff6b3e9fd3a10e3e52b24dc71e650bb1a9bd" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "serde_json" version = "1.0.154" @@ -2355,7 +2643,7 @@ checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", ] [[package]] @@ -2366,7 +2654,18 @@ checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", "cpufeatures 0.2.17", - "digest", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -2400,7 +2699,7 @@ version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" dependencies = [ - "digest", + "digest 0.10.7", "rand_core 0.6.4", ] @@ -2538,7 +2837,7 @@ dependencies = [ "percent-encoding", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "smallvec", "thiserror", "time", @@ -2577,7 +2876,7 @@ dependencies = [ "quote", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "sqlx-core", "sqlx-mysql", "sqlx-postgres", @@ -2599,7 +2898,7 @@ dependencies = [ "byteorder", "bytes", "crc", - "digest", + "digest 0.10.7", "dotenvy", "either", "futures-channel", @@ -2620,7 +2919,7 @@ dependencies = [ "rsa", "serde", "sha1", - "sha2", + "sha2 0.10.9", "smallvec", "sqlx-core", "stringprep", @@ -2659,7 +2958,7 @@ dependencies = [ "rand 0.8.8", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "smallvec", "sqlx-core", "stringprep", @@ -2696,6 +2995,19 @@ dependencies = [ "uuid", ] +[[package]] +name = "sse-stream" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c25ac7aff0abd1dbc474536e40416e1102c7dd9bfba0b9861c6d357f835dcfb4" +dependencies = [ + "bytes", + "futures-util", + "http-body", + "http-body-util", + "pin-project-lite", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -2722,6 +3034,12 @@ dependencies = [ "unicode-properties", ] +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + [[package]] name = "subsetter" version = "0.2.6" @@ -2966,6 +3284,20 @@ dependencies = [ "tungstenite", ] +[[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" @@ -3156,6 +3488,12 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce61d488bcdc9bc8b5d1772c404828b17fc481c0a582b5581e95fb233aef503e" +[[package]] +name = "unicode-general-category" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f" + [[package]] name = "unicode-ident" version = "1.0.27" @@ -3589,7 +3927,7 @@ dependencies = [ "serde", "serde_json", "service-kit", - "sha2", + "sha2 0.10.9", "sqlx", "time", "tokio", diff --git a/Cargo.toml b/Cargo.toml index 191c3c8..e220f17 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,6 +15,7 @@ members = [ "services/backend", "services/worker", "services/forum", + "services/mcp", ] [workspace.package] diff --git a/ci/changed-services.sh b/ci/changed-services.sh index 00050c1..36acc6f 100755 --- a/ci/changed-services.sh +++ b/ci/changed-services.sh @@ -6,17 +6,17 @@ # Needs the full history and the tags (git fetch --unshallow --tags). # # frontend services/frontend/ -# backend, worker, forum their folder, the shared crates/, Cargo.toml, Cargo.lock +# backend, worker, forum, mcp their folder, the shared crates/, Cargo.toml, Cargo.lock # horoscope-api the same, and scripts/fetch-deps.sh set -u -ALL="horoscope-api backend worker forum frontend" +ALL="horoscope-api backend worker forum mcp frontend" prev=$(git describe --tags --abbrev=0 --match 'v*' HEAD 2>/dev/null) || { echo "$ALL"; exit 0; } files=$(git diff --name-only "$prev" HEAD) || { echo "$ALL"; exit 0; } changed() { printf '%s\n' "$files" | grep -Eq "$1"; } rust='^(crates/|Cargo\.toml$|Cargo\.lock$)' out="" changed "^services/horoscope-api/|^scripts/fetch-deps\.sh$|$rust" && out="$out horoscope-api" -for svc in backend worker forum; do +for svc in backend worker forum mcp; do changed "^services/$svc/|$rust" && out="$out $svc" done changed '^services/frontend/' && out="$out frontend" diff --git a/crates/db/migrations/0049_mcp_oauth.sql b/crates/db/migrations/0049_mcp_oauth.sql new file mode 100644 index 0000000..eb45512 --- /dev/null +++ b/crates/db/migrations/0049_mcp_oauth.sql @@ -0,0 +1,61 @@ +-- Claude (or another MCP client) connected to the admin tools through OAuth +-- (docs/mcp.md). An admin approves the connection on the site; the client +-- then holds a short access token and a refresh token. Every secret is +-- stored as its SHA-256 hash, like the sessions. + +-- The clients that registered themselves (RFC 7591), only with an allowed +-- return address (Claude's callback, or a local one for Claude Code). +CREATE TABLE oauth_clients ( + id text PRIMARY KEY, + name text NOT NULL CHECK (char_length(name) <= 100), + redirect_uris text[] NOT NULL, + -- NULL: a public client, proven by PKCE alone. + secret_hash bytea, + created_at timestamptz NOT NULL DEFAULT now(), + last_used_at timestamptz +); + +-- One approved connection: who allowed which client. Revoking it ends all +-- of its tokens. +CREATE TABLE oauth_grants ( + id uuid PRIMARY KEY, + client_id text NOT NULL REFERENCES oauth_clients (id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + scope text NOT NULL, + -- The MCP server the tokens are for (RFC 8707). + resource text, + created_at timestamptz NOT NULL DEFAULT now(), + last_used_at timestamptz, + revoked_at timestamptz +); +CREATE INDEX oauth_grants_user_idx ON oauth_grants (user_id); + +-- The one-time code the approval sends back to the client (10 minutes). +CREATE TABLE oauth_codes ( + code_hash bytea PRIMARY KEY, + client_id text NOT NULL REFERENCES oauth_clients (id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, + redirect_uri text NOT NULL, + code_challenge text NOT NULL, + scope text NOT NULL, + resource text, + expires_at timestamptz NOT NULL, + used_at timestamptz, + -- The connection made with it: a second use of the code revokes it. + grant_id uuid REFERENCES oauth_grants (id) ON DELETE CASCADE +); + +-- An access token (an hour) and its refresh token (30 days). A refresh makes +-- a new pair; the old refresh token sent again revokes the whole connection. +CREATE TABLE oauth_tokens ( + id uuid PRIMARY KEY, + grant_id uuid NOT NULL REFERENCES oauth_grants (id) ON DELETE CASCADE, + access_hash bytea NOT NULL UNIQUE, + access_expires_at timestamptz NOT NULL, + refresh_hash bytea NOT NULL UNIQUE, + refresh_expires_at timestamptz NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + refreshed_at timestamptz +); +CREATE INDEX oauth_tokens_grant_idx ON oauth_tokens (grant_id); +CREATE INDEX oauth_tokens_expiry_idx ON oauth_tokens (refresh_expires_at); diff --git a/crates/db/src/lib.rs b/crates/db/src/lib.rs index 8cca945..410e67b 100644 --- a/crates/db/src/lib.rs +++ b/crates/db/src/lib.rs @@ -141,6 +141,58 @@ pub async fn user_by_session(pool: &PgPool, token: &str) -> Result, +} + +/// The connection and user of a valid (unexpired, not revoked) OAuth access +/// token; notes the connection's last use (at most once a minute). +pub async fn user_by_oauth_token(pool: &PgPool, token: &str) -> Result, sqlx::Error> { + #[derive(sqlx::FromRow)] + struct Row { + grant_id: Uuid, + scope: String, + resource: Option, + #[sqlx(flatten)] + user: User, + } + let row: Option = sqlx::query_as( + "SELECT g.id AS grant_id, g.scope, g.resource, u.id, u.email, u.email_verified_at, u.display_name, \ + u.locale, u.roles, u.created_at, u.last_login_at \ + FROM oauth_tokens t JOIN oauth_grants g ON g.id = t.grant_id JOIN users u ON u.id = g.user_id \ + WHERE t.access_hash = $1 AND t.access_expires_at > now() AND g.revoked_at IS NULL", + ) + .bind(token_hash(token)) + .fetch_optional(pool) + .await?; + let Some(row) = row else { return Ok(None) }; + sqlx::query( + "UPDATE oauth_grants SET last_used_at = now() \ + WHERE id = $1 AND (last_used_at IS NULL OR last_used_at < now() - interval '60 seconds')", + ) + .bind(row.grant_id) + .execute(pool) + .await?; + Ok(Some((OauthAccess { grant_id: row.grant_id, scope: row.scope, resource: row.resource }, row.user))) +} + +/// Revokes every OAuth connection of a user (log out everywhere, a new password). +pub async fn revoke_oauth_grants<'e, E>(executor: E, user_id: Uuid) -> Result<(), sqlx::Error> +where + E: sqlx::PgExecutor<'e>, +{ + sqlx::query("UPDATE oauth_grants SET revoked_at = now() WHERE user_id = $1 AND revoked_at IS NULL") + .bind(user_id) + .execute(executor) + .await?; + Ok(()) +} + #[cfg(test)] mod tests { use super::*; diff --git a/deploy/Caddyfile b/deploy/Caddyfile index 920e132..62ba5bc 100644 --- a/deploy/Caddyfile +++ b/deploy/Caddyfile @@ -23,6 +23,16 @@ header_up X-Real-IP {client_ip} } } + # The admin tools for Claude (docs/mcp.md) and their OAuth metadata; the + # login, the approval and the tokens are the frontend's and the backend's. + handle /mcp* { + reverse_proxy mcp:8084 { + header_up X-Real-IP {client_ip} + } + } + handle /.well-known/oauth-protected-resource* { + reverse_proxy mcp:8084 + } handle { reverse_proxy frontend:3000 { # The address the backend trusts (rate limits, share visits); it diff --git a/deploy/README.md b/deploy/README.md index 1c15dff..bc869cc 100644 --- a/deploy/README.md +++ b/deploy/README.md @@ -9,11 +9,11 @@ A runner egyszerre egy feladatot futtat; ha a main is buildelne, minden kitett c A lépések: -Csak az épül és indul újra, ami az előző élesítés óta változott (`ci/changed-services.sh`: az előző élesítés `v*` taghez képest nézi a változott fájlokat). A frontend a `services/frontend` mappától függ; a backend, a worker és a fórum a saját mappájától és a közös Rust-csomagoktól (`crates/`, `Cargo.toml`, `Cargo.lock`); a horoscope-api ezektől és a `scripts/fetch-deps.sh`-tól. Ha nincs előző tag, vagy kétséges a helyzet, minden épül. +Csak az épül és indul újra, ami az előző élesítés óta változott (`ci/changed-services.sh`: az előző élesítés `v*` taghez képest nézi a változott fájlokat). A frontend a `services/frontend` mappától függ; a backend, a worker, a fórum és az MCP-szerver a saját mappájától és a közös Rust-csomagoktól (`crates/`, `Cargo.toml`, `Cargo.lock`); a horoscope-api ezektől és a `scripts/fetch-deps.sh`-tól. Ha nincs előző tag, vagy kétséges a helyzet, minden épül. 1. **test**: `cargo test` a Rust-szolgáltatásokra, egy Postgres szolgáltatás-konténerrel. Kimarad, ha egyik Rust-szolgáltatás sem változott. 2. **build** (csak prod): megépíti a változott image-eket, és feltölti őket a `registry.sagifer.com/sagifer/sorsfonalak-` címre. A frontend buildje a TypeScript-típusokat is ellenőrzi, és megkapja a verzióját (`APP_VERSION`, a commit): ebből lesz a Next `deploymentId`-je és a `/api/version` válasza. -3. **deploy** (csak prod): felmásolja a `docker-compose.yml`-t és a `Caddyfile`-t a szerverre, a szerveren lévő `.env`-be csak a megépült szolgáltatások címkéjét írja be (`TAG_BACKEND`, `TAG_FRONTEND`, `TAG_FORUM`, `TAG_WORKER`, `TAG_HOROSCOPE_API`; ahol nincs ilyen, a régi `TAG` érvényes), majd `docker compose pull && up -d`: csak a változott konténerek indulnak újra. Az adatbázis-migrációk a backend (és a fórum) indulásakor futnak le. +3. **deploy** (csak prod): felmásolja a `docker-compose.yml`-t és a `Caddyfile`-t a szerverre, a szerveren lévő `.env`-be csak a megépült szolgáltatások címkéjét írja be (`TAG_BACKEND`, `TAG_FRONTEND`, `TAG_FORUM`, `TAG_MCP`, `TAG_WORKER`, `TAG_HOROSCOPE_API`; ahol nincs ilyen, a régi `TAG` érvényes), majd `docker compose pull && up -d`: csak a változott konténerek indulnak újra. Az adatbázis-migrációk a backend (és a fórum) indulásakor futnak le. 4. **release** (csak prod, a deploy után): létrehoz egy `v<év.hónap.nap>-` taget és Gitea-release-t az előző release óta bekerült commitok listájával (repó → Releases). A következő élesítés ehhez a taghez méri a változást. Új frontend-verziónál a nyitva hagyott oldalak maguk veszik észre (`VersionWatcher`, 5 percenként és amikor a fül előtérbe kerül): ha a látogató nem csinál semmit és nincs beírt szöveg, újratöltődik, különben egy „Frissült az oldal” sáv kínálja fel a frissítést. Linkre kattintva a Next magától teljes újratöltést csinál. @@ -109,4 +109,5 @@ A híres emberek fotóit a backend S3-kompatibilis tárolóba teszi, fotónként - Mentés: naponta egy `pg_dump` a `/opt/sorsfonalak/backups` mappába, 14 napig megmarad. Az otthoni TrueNAS naponta lehúzza (Rsync Task, Pull, SSH) a `nasbackup` felhasználóval, aki csak ezt a mappát olvashatja (`authorized_keys`: `command="/usr/bin/rrsync -ro /opt/sorsfonalak/backups",restrict`); a NAS-on a régi mentések is megmaradnak. - Vásárlási értesítő: a `worker` `notify` feladata minden kifizetett vásárlásról egyszer szól Telegramon („🛒 Vásárlás: Páros csomag, 6 000 Ft”, a vevő adatai nélkül), a számlázástól függetlenül. Beállítás: `TELEGRAM_BOT_TOKEN` a `.env.secrets`-ben, `TELEGRAM_CHAT_ID` a `.env`-ben; ha bármelyik hiányzik, nincs értesítés. - Monitorozás: a `beszel-agent` (Beszel, CPU/memória/lemez/konténerek) a NAS-on futó Beszel hubnak ad adatot, Tailscale-en át. Csak a szerver Tailscale-címén figyel (`100.69.226.118:45876`), az internet felé nem nyit portot; a hub kapcsolódik hozzá. Bekapcsolás a `.env`-ben: `COMPOSE_PROFILES=monitoring` és `BESZEL_KEY=`, utána `docker compose up -d beszel-agent`. A hubban a rendszer címe `100.69.226.118`, port `45876`. +- MCP-szerver (`mcp`, `docs/mcp.md`): az admin eszközök Claude-hoz, a `https://sorsfonalak.hu/mcp` címen (a Caddy a `/mcp` és a `/.well-known/oauth-protected-resource` útvonalat viszi hozzá). Nem kell hozzá DNS-bejegyzés és titok; adatbázist nem használ, minden hívása a frontend `/api/v1` proxyján át a backendhez megy. A kapcsolt alkalmazások: Admin → Claude. - Visszatöltés: `gunzip -c backups/sorsfonalak-.sql.gz | docker compose exec -T postgres psql -U sorsfonalak sorsfonalak` diff --git a/deploy/docker-compose.yml b/deploy/docker-compose.yml index d78b3fd..ef26706 100644 --- a/deploy/docker-compose.yml +++ b/deploy/docker-compose.yml @@ -113,6 +113,8 @@ services: # Cloudflare Turnstile on the e-mail sign-up and reset forms (the # TURNSTILE_SECRET_KEY is in .env.secrets). Without both: no check. TURNSTILE_SITE_KEY: ${TURNSTILE_SITE_KEY:-} + # The MCP server's address, the audience of its tokens (docs/mcp.md). + MCP_RESOURCE_URL: https://${DOMAIN}/mcp # The log also goes to the logs volume, one file a day, kept 30 days # (deploy/README.md: Logs). LOG_DIR: /logs @@ -238,6 +240,24 @@ services: logging: *logging restart: unless-stopped + # The admin tools for Claude (docs/mcp.md): Claude connects to + # https://${DOMAIN}/mcp (Caddy), an admin approves it on the site, and every + # tool calls the site's API through the frontend with that admin's token. + mcp: + image: ${REGISTRY_PREFIX:-registry.sagifer.com/sagifer/sorsfonalak}-mcp:${TAG_MCP:-${TAG:-latest}} + environment: + API_URL: http://frontend:3000/api/v1 + PUBLIC_BASE_URL: https://${DOMAIN} + MCP_PUBLIC_URL: https://${DOMAIN}/mcp + LOG_DIR: /logs + depends_on: + - frontend + read_only: true + volumes: + - logs:/logs + logging: *logging + restart: unless-stopped + # Beszel agent: CPU, memory, disk, network and per-container stats for the # Beszel hub on the home NAS. Off unless COMPOSE_PROFILES=monitoring and # BESZEL_KEY (the hub's public key) are in .env. It listens only on the @@ -257,7 +277,7 @@ services: volumes: pgdata: - # Backend, worker and forum logs (backend.YYYY-MM-DD.log, worker…, worker-ai…, forum…). + # Backend, worker, forum and MCP logs (backend.YYYY-MM-DD.log, worker…, worker-ai…, forum…, mcp…). logs: caddy-data: caddy-config: diff --git a/docker-compose.yml b/docker-compose.yml index 0469b50..eaad2ab 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -75,6 +75,8 @@ services: S3_BUCKET: ${S3_BUCKET:-} S3_REGION: ${S3_REGION:-us-east-1} S3_CREATE_BUCKET: ${S3_CREATE_BUCKET:-false} + # The MCP server's address, the audience of its tokens (docs/mcp.md). + MCP_RESOURCE_URL: ${MCP_RESOURCE_URL:-http://localhost:8084/mcp} # STRIPE_SECRET_KEY / STRIPE_WEBHOOK_SECRET (test keys; docs/fizetes.md). # With them Stripe replaces the stand-in payment. env_file: @@ -165,5 +167,23 @@ services: - /tmp restart: unless-stopped + # The admin tools for Claude (docs/mcp.md): connect Claude Code to + # http://localhost:8084/mcp; the login and approval happen on the frontend. + mcp: + build: + context: . + dockerfile: services/mcp/Dockerfile + image: sorsfonalak/mcp:latest + ports: + - "8084:8084" + environment: + API_URL: http://frontend:3000/api/v1 + PUBLIC_BASE_URL: ${PUBLIC_BASE_URL:-http://localhost:3001} + MCP_PUBLIC_URL: ${MCP_RESOURCE_URL:-http://localhost:8084/mcp} + depends_on: + - frontend + read_only: true + restart: unless-stopped + volumes: pgdata: diff --git a/docs/mcp.md b/docs/mcp.md new file mode 100644 index 0000000..cadf1e0 --- /dev/null +++ b/docs/mcp.md @@ -0,0 +1,104 @@ +# MCP: az admin eszközök Claude-ból + +Az `mcp` szolgáltatás egy MCP-szerver: Claude-ból (claude.ai, Claude Desktop, Claude Code) lehet vele az admin dolgokat lekérdezni és a napi teendőket elintézni. Például: „Hány új tag jött a héten, és honnan?”, „Mi van a nyitott visszajelzések között?”, „Csinálj 5 promókódot a Páros csomaghoz a novemberi kampányhoz.” + +## Összekötés + +- **claude.ai / Claude Desktop:** Beállítások → Összekötők → *Egyéni összekötő hozzáadása* → cím: `https://sorsfonalak.hu/mcp`. A *Csatlakozás* gomb után Claude a Sorsfonalak oldalára visz. +- **Claude Code:** `claude mcp add --transport http sorsfonalak https://sorsfonalak.hu/mcp`, utána a `/mcp` paranccsal lehet belépni. +- **Az oldalon:** ha nem vagy belépve, belépés (Google, Apple), utána az `/oauth/engedely` oldal mutatja, mit kér az alkalmazás. **Engedélyezem** → vissza Claude-hoz. Csak admin fiók engedélyezhet. +- **Helyben:** `docker compose up -d backend frontend mcp`, a cím `http://localhost:8084/mcp`; a belépés és az engedélyezés a `http://localhost:3001` oldalon van. + +## Mit tehet + +**Olvasás:** +- statisztika (`get_stats`); +- tagok keresése; +- visszajelzések és összesítésük; +- értékelések és az értékelt szöveg; +- hibanapló, háttérfeladatok; +- csomagok, promókódok, meghívók, ajándékok; +- hírességek, promptok, modellek. + +**Napi teendők** (Claude minden ilyen lépés előtt rákérdez): +- promókód készítése és visszavonása; +- visszajelzés állapota, megjegyzése és válasza; +- értékelések átnézve; +- háttérfeladatok újraindítása, hibák törlése; +- meghívó küldése és újraküldése (valódi e-mail megy ki); +- elemzés és válasz újraírása (AI-költség). + +**Fórummoderálás:** +- bejelentések és lezárásuk; +- csatlakozási kérések elbírálása; +- moderálási napló, egy szál elolvasása; +- kitiltás és feloldás. + +**Amit nem tehet** (csak az admin oldalon): +- szerepkör, kredit és csomag adása; +- promptok és modellek mentése; +- hírességek szerkesztése; +- ajándék-visszatérítés, meghívó visszavonása. + +A fórumban tagként írni, reagálni vagy bejelenteni nem tud. + +## A tagok adatai + +Az eszközök válaszaiban: +- **E-mail-címek:** maszkolva mennek, a szabad szövegben is: `an***@gmail.com`. +- **Nevek:** a tagok nevei `[rejtve]` alakban mennek. +- **Ami marad:** a fórum-becenevek (álnevek), a hírességek és a csomagok neve. + +Keresni teljes e-mail-címmel is lehet (a cím Claude-tól megy a szerverhez), és meghívót is a megadott címre küld; a válaszban ezek is maszkolva jönnek vissza. A maszkolás az MCP-szerverben van (`services/mcp/src/mask.rs`), ezért az adatvédelmi tájékoztatót nem kellett bővíteni. + +## Hogyan működik + +``` +Claude ─HTTPS─> Cloudflare ─> Caddy + /mcp, /.well-known/oauth-protected-resource* ─> mcp:8084 + minden más ─> frontend:3000 + /api/v1/* (proxy) ─> backend:8081, /api/v1/forum/* ─> forum:8083 + /oauth/engedely (az engedélyezés oldala) + /.well-known/oauth-authorization-server (─> /api/v1/oauth/metadata) +mcp ─> http://frontend:3000/api/v1/… (a felhasználó tokenjével) +``` + +**Az OAuth 2.1 lépései** (a backend az authorization server, az MCP-szerver a resource server): +1. **Token nélkül:** a `/mcp` 401-et ad, és a `WWW-Authenticate` fejlécben megmondja, hol a metaadat (`/.well-known/oauth-protected-resource/mcp`, RFC 9728). Ez az oldalt nevezi meg authorization servernek. +2. **Metaadat** (`/.well-known/oauth-authorization-server`, RFC 8414): az engedélyezés oldala, a token-, a regisztrációs és a visszavonási végpont. Csak `code` és PKCE `S256`. +3. **Kliensregisztráció** (`POST /api/v1/oauth/register`, RFC 7591): csak engedélyezett visszatérési címmel. Alapból Claude-é (`https://claude.ai/api/mcp/auth_callback`, `https://claude.com/api/mcp/auth_callback`), illetve a Claude Code-hoz `http://localhost:*` és `http://127.0.0.1:*`. A lista: `OAUTH_REDIRECT_URIS` a backendben. +4. **Engedélyezés:** az `/oauth/engedely` oldal a backenddel ellenőrizteti a kérést, admin belépés után az **Engedélyezem** egy 10 percig érvényes, egyszer használható kódot ad. Ezt a backend csak munkamenettel adja ki, MCP-tokennel nem. +5. **Token** (`POST /api/v1/oauth/token`): hozzáférési token (1 óra) és frissítőtoken (30 nap). + - A frissítőtoken minden használatkor cserélődik. Ha egy régit újra beküldenek, az egész kapcsolat visszavonódik; egy kétszer beküldött kód is ezzel jár. + - A token az MCP-szerverhez kötött (`resource`, RFC 8707: `MCP_RESOURCE_URL`). +6. **Hívások:** + - Az MCP-szerver a `GET /api/v1/oauth/whoami` végponttal ellenőrzi a tokent (percenként egyszer, gyorsítótárból). + - Az eszközök a tokennel hívják az admin API-t, ugyanúgy, mint az admin oldalak. + - A backend minden hívásnál ellenőriz: a token csak admin végpontot hívhat, írni csak a napi teendőket (`MCP_WRITES` a `services/backend/src/auth.rs`-ben). Admin szerep nélkül a token semmit nem ér. + - A fórum csak a moderátori végpontokon fogadja el. + +**Táblák** (`0049_mcp_oauth.sql`), mindegyik titok SHA-256 hash-ként tárolva: +- `oauth_clients`: a regisztrált kliensek; +- `oauth_grants`: egy-egy engedélyezett kapcsolat; +- `oauth_codes`: az egyszer használható kódok; +- `oauth_tokens`: a hozzáférési és frissítőtokenek. + +A worker `cleanup` feladata törli a lejárt kódokat és tokeneket, a 30 napja visszavont vagy token nélküli kapcsolatokat, és a 30 napja kapcsolat nélküli klienseket. + +## Visszavonás + +- **Admin → Claude:** a kapcsolt alkalmazások listája. A **Visszavonás** után az alkalmazás azonnal elveszíti a hozzáférést. +- **Kijelentkezés mindenhonnan**, jelszócsere, jelszó-visszaállítás: a felhasználó minden kapcsolata megszűnik. +- **Claude-ban:** az összekötő eltávolítása (ha a kliens hívja a visszavonási végpontot, itt is megszűnik). + +## Beállítások + +| Hol | Változó | Érték | +|---|---|---| +| backend | `MCP_RESOURCE_URL` | az MCP-szerver címe (élesben `https://sorsfonalak.hu/mcp`) | +| backend | `OAUTH_REDIRECT_URIS` | engedélyezett visszatérési címek; a `*` a végén bármely port és útvonal (üres: az alapértelmezés) | +| mcp | `API_URL` | az oldal API-ja (`http://frontend:3000/api/v1`) | +| mcp | `PUBLIC_BASE_URL` | az oldal, az authorization server | +| mcp | `MCP_PUBLIC_URL` | a saját címe, ahogy a kliens látja | + +**Ami nem kell:** DNS-bejegyzés (a `/mcp` a fő domainen van), titok és Cloudflare-beállítás. Ha Claude kapcsolódási hibát jelez, a Cloudflare Security → Events oldalán érdemes megnézni, nem állította-e meg valami a kérést (a Bot Fight Mode maradjon kikapcsolva). diff --git a/services/backend/Cargo.toml b/services/backend/Cargo.toml index 1e8f248..aa19ad7 100644 --- a/services/backend/Cargo.toml +++ b/services/backend/Cargo.toml @@ -20,6 +20,7 @@ service-kit.workspace = true anyhow.workspace = true deunicode.workspace = true argon2.workspace = true +base64.workspace = true password-hash = { version = "0.5", features = ["getrandom"] } axum.workspace = true axum-extra.workspace = true diff --git a/services/backend/src/auth.rs b/services/backend/src/auth.rs index e9e6d0b..7500fff 100644 --- a/services/backend/src/auth.rs +++ b/services/backend/src/auth.rs @@ -4,6 +4,10 @@ //! HttpOnly cookie (`sf_session`) and in the login response body (for //! non-browser clients, sent back as `Authorization: Bearer `); the //! database keeps only its SHA-256 hash, so sessions can be revoked. +//! +//! The admin endpoints also accept the OAuth access token of an MCP client +//! that an admin connected (docs/mcp.md): for reading, and for the few +//! writes in [`MCP_WRITES`]. use std::collections::HashMap; use std::sync::{Arc, Mutex}; @@ -12,7 +16,8 @@ use std::time::{Duration, Instant}; use argon2::Argon2; use argon2::password_hash::rand_core::OsRng; use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString}; -use axum::extract::FromRequestParts; +use axum::extract::{FromRequestParts, MatchedPath}; +use axum::http::Method; use axum::http::header::{AUTHORIZATION, USER_AGENT}; use axum::http::request::Parts; use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite}; @@ -36,7 +41,11 @@ pub const MAX_PASSWORD_LEN: usize = 256; #[derive(Debug, Clone)] pub struct AuthUser { pub user: User, + /// The session; with an MCP client's token, the id of its connection. pub session_id: Uuid, + /// Set when an MCP client's OAuth token was sent instead of a session + /// (only the admin guards accept one). + pub oauth: Option, } impl AuthUser { @@ -68,19 +77,72 @@ impl FromRequestParts> for AuthUser { async fn from_request_parts(parts: &mut Parts, state: &Arc) -> Result { let token = session_token(parts).ok_or(ApiError::Unauthorized)?; let (session_id, user) = db::user_by_session(&state.db, &token).await?.ok_or(ApiError::Unauthorized)?; - Ok(AuthUser { user, session_id }) + Ok(AuthUser { user, session_id, oauth: None }) } } -/// Guard: a logged-in user with the admin role (401 / 403 otherwise). +/// The admin writes an MCP client's token may make (method, route), besides +/// reading: the daily tasks of docs/mcp.md. Every other write needs a session. +pub const MCP_WRITES: [(Method, &str); 11] = [ + (Method::POST, "/v1/admin/promo-codes"), + (Method::POST, "/v1/admin/promo-codes/{id}/revoke"), + (Method::PATCH, "/v1/admin/feedback/{id}"), + (Method::POST, "/v1/admin/ratings/reviewed"), + (Method::POST, "/v1/admin/jobs/restart"), + (Method::DELETE, "/v1/admin/errors"), + (Method::DELETE, "/v1/admin/errors/{id}"), + (Method::POST, "/v1/admin/invitations"), + (Method::POST, "/v1/admin/invitations/{id}/resend"), + (Method::POST, "/v1/admin/analyses/{id}/regenerate"), + (Method::POST, "/v1/admin/questions/{id}/regenerate"), +]; + +/// The user of an MCP client's OAuth access token (`Authorization: Bearer`). +pub async fn oauth_user(parts: &Parts, state: &AppState) -> Result, ApiError> { + let Some(token) = parts + .headers + .get(AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .map(str::trim) + else { + return Ok(None); + }; + let found = db::user_by_oauth_token(&state.db, token).await?; + Ok(found.map(|(access, user)| AuthUser { user, session_id: access.grant_id, oauth: Some(access) })) +} + +/// A session, or else an MCP client's token. +async fn session_or_token(parts: &mut Parts, state: &Arc) -> Result { + match AuthUser::from_request_parts(parts, state).await { + Err(ApiError::Unauthorized) => oauth_user(parts, state).await?.ok_or(ApiError::Unauthorized), + other => other, + } +} + +/// With an MCP client's token: reading, and the writes of [`MCP_WRITES`]. +fn token_may(user: &AuthUser, parts: &Parts) -> Result<(), ApiError> { + if user.oauth.is_none() || parts.method == Method::GET || parts.method == Method::HEAD { + return Ok(()); + } + let route = parts.extensions.get::().map(MatchedPath::as_str); + if MCP_WRITES.iter().any(|(method, path)| *method == parts.method && Some(*path) == route) { + return Ok(()); + } + Err(ApiError::Forbidden("Ezt Claude-ból nem lehet, csak az admin oldalon.".into())) +} + +/// Guard: a logged-in user with the admin role (401 / 403 otherwise), or an +/// MCP client an admin connected. pub struct AdminUser(pub AuthUser); impl FromRequestParts> for AdminUser { type Rejection = ApiError; async fn from_request_parts(parts: &mut Parts, state: &Arc) -> Result { - let user = AuthUser::from_request_parts(parts, state).await?; + let user = session_or_token(parts, state).await?; user.require(Role::Admin)?; + token_may(&user, parts)?; Ok(AdminUser(user)) } } @@ -98,11 +160,12 @@ impl FromRequestParts> for CelebrityEditor { type Rejection = ApiError; async fn from_request_parts(parts: &mut Parts, state: &Arc) -> Result { - let user = AuthUser::from_request_parts(parts, state).await?; - if user.user.has_role(Role::Creator) { + let user = session_or_token(parts, state).await?; + if user.oauth.is_none() && user.user.has_role(Role::Creator) { return Ok(CelebrityEditor(user)); } user.require(Role::Admin)?; + token_may(&user, parts)?; Ok(CelebrityEditor(user)) } } diff --git a/services/backend/src/config.rs b/services/backend/src/config.rs index 8ba6e0b..294c747 100644 --- a/services/backend/src/config.rs +++ b/services/backend/src/config.rs @@ -117,8 +117,23 @@ pub struct Config { /// `S3_CREATE_BUCKET` (default false): create the bucket at startup if it /// is missing (development; in production it is made in the console). pub storage_create_bucket: bool, + /// `OAUTH_REDIRECT_URIS`: comma-separated return addresses an MCP client + /// may register (docs/mcp.md); a trailing `*` stands for any port (and + /// path). Default: Claude's callbacks and local ones for Claude Code. + pub oauth_redirect_uris: Vec, + /// `MCP_RESOURCE_URL`: the MCP server's address, the audience of the + /// tokens (default `PUBLIC_BASE_URL` + `/mcp`). + pub mcp_resource_url: String, } +/// The default `OAUTH_REDIRECT_URIS`. +pub const DEFAULT_OAUTH_REDIRECT_URIS: [&str; 4] = [ + "https://claude.ai/api/mcp/auth_callback", + "https://claude.com/api/mcp/auth_callback", + "http://localhost:*", + "http://127.0.0.1:*", +]; + /// `STRIPE_SECRET_KEY` (`sk_test_…` or `sk_live_…`), `STRIPE_WEBHOOK_SECRET` /// (`whsec_…`, from the webhook endpoint in the Stripe dashboard) and /// `STRIPE_API_URL` (default `https://api.stripe.com`, tests change it). @@ -182,7 +197,6 @@ impl Config { let config = Self { database_url: var("DATABASE_URL").context("DATABASE_URL is required")?, horoscope_api_url: var("HOROSCOPE_API_URL").unwrap_or_else(|| "http://localhost:8080".into()), - public_base_url, cors_allowed_origins, cookie_secure: parsed("COOKIE_SECURE", true)?, cookie_domain: var("COOKIE_DOMAIN"), @@ -250,6 +264,14 @@ impl Config { }), }, storage_create_bucket: parsed("S3_CREATE_BUCKET", false)?, + oauth_redirect_uris: match list("OAUTH_REDIRECT_URIS") { + uris if uris.is_empty() => DEFAULT_OAUTH_REDIRECT_URIS.map(String::from).to_vec(), + uris => uris, + }, + mcp_resource_url: var("MCP_RESOURCE_URL") + .map(|u| u.trim_end_matches('/').to_string()) + .unwrap_or_else(|| format!("{public_base_url}/mcp")), + public_base_url, }; if config.session_ttl_days < 1 { bail!("SESSION_TTL_DAYS must be at least 1"); @@ -300,6 +322,8 @@ impl Config { secret_key: "test-secret".into(), }), storage_create_bucket: false, + oauth_redirect_uris: DEFAULT_OAUTH_REDIRECT_URIS.map(String::from).to_vec(), + mcp_resource_url: "https://sorsfonalak.test/mcp".into(), } } } diff --git a/services/backend/src/main.rs b/services/backend/src/main.rs index 4a3f254..5fdfb81 100644 --- a/services/backend/src/main.rs +++ b/services/backend/src/main.rs @@ -63,6 +63,8 @@ pub struct AppState { pub storage: Option, /// The sky by date, the same for everyone (see `routes::sky`). pub sky: routes::sky::SkyCache, + /// MCP client registrations and token requests, per visitor address. + pub oauth_limiter: LoginLimiter, } impl AppState { @@ -80,6 +82,7 @@ impl AppState { stripe: stripe::Client::default(), storage: config.storage.clone().map(storage::Storage::new), sky: Default::default(), + oauth_limiter: LoginLimiter::new(60, Duration::from_secs(60 * 60)), db, config, } diff --git a/services/backend/src/routes/account.rs b/services/backend/src/routes/account.rs index 6d26c49..8b0d78e 100644 --- a/services/backend/src/routes/account.rs +++ b/services/backend/src/routes/account.rs @@ -138,6 +138,7 @@ pub async fn change_password( .bind(auth.session_id) .execute(&mut *tx) .await?; + db::revoke_oauth_grants(&mut *tx, auth.id()).await?; tx.commit().await?; Ok(StatusCode::NO_CONTENT) } diff --git a/services/backend/src/routes/auth.rs b/services/backend/src/routes/auth.rs index e4acd8d..25c8099 100644 --- a/services/backend/src/routes/auth.rs +++ b/services/backend/src/routes/auth.rs @@ -509,6 +509,7 @@ async fn social_login( .execute(&mut *tx) .await?; sqlx::query("DELETE FROM sessions WHERE user_id = $1").bind(id).execute(&mut *tx).await?; + db::revoke_oauth_grants(&mut *tx, id).await?; tracing::warn!(user = %id, provider, "unconfirmed password account taken over by its address's owner"); } // The provider has verified the address, so it counts as verified here too. @@ -595,6 +596,8 @@ pub async fn logout(State(state): St, auth: AuthUser, jar: CookieJar) -> ApiResu /// Ends every session of the user (all devices). pub async fn logout_all(State(state): St, auth: AuthUser, jar: CookieJar) -> ApiResult { sqlx::query("DELETE FROM sessions WHERE user_id = $1").bind(auth.id()).execute(&state.db).await?; + // The MCP clients connected by the user too (docs/mcp.md). + db::revoke_oauth_grants(&state.db, auth.id()).await?; Ok((StatusCode::NO_CONTENT, jar.add(removal_cookie(&state.config)))) } @@ -659,6 +662,7 @@ pub async fn set_password_with_link( .execute(&mut *tx) .await?; sqlx::query("DELETE FROM sessions WHERE user_id = $1").bind(user_id).execute(&mut *tx).await?; + db::revoke_oauth_grants(&mut *tx, user_id).await?; let mut user = load_user(&mut tx, user_id).await?; apply_bootstrap_admin(&state, &mut tx, &mut user).await?; tx.commit().await?; diff --git a/services/backend/src/routes/mod.rs b/services/backend/src/routes/mod.rs index 67a2cf3..8b4071e 100644 --- a/services/backend/src/routes/mod.rs +++ b/services/backend/src/routes/mod.rs @@ -21,6 +21,7 @@ mod invoices_user; mod jobs; mod models; mod notifications; +mod oauth; pub(crate) mod payments; mod promo; mod prompts; @@ -88,6 +89,15 @@ pub fn router(state: Arc) -> Router { .route("/v1/auth/logout-all", post(auth::logout_all)) .route("/v1/auth/password-reset", post(auth::request_password_reset)) .route("/v1/auth/set-password", post(auth::set_password_with_link)) + // MCP clients (docs/mcp.md): OAuth for the admin tools. + .route("/v1/oauth/metadata", get(oauth::metadata)) + .route("/v1/oauth/register", post(oauth::register)) + .route("/v1/oauth/authorize", get(oauth::authorize_check).post(oauth::authorize)) + .route("/v1/oauth/token", post(oauth::token)) + .route("/v1/oauth/revoke", post(oauth::revoke)) + .route("/v1/oauth/whoami", get(oauth::whoami)) + .route("/v1/admin/oauth/grants", get(oauth::admin_grants)) + .route("/v1/admin/oauth/grants/{id}", delete(oauth::admin_revoke_grant)) // own account (GDPR export and deletion included) .route("/v1/me", get(account::me).patch(account::update_me).delete(account::delete_me)) .route("/v1/me/password", post(account::change_password)) diff --git a/services/backend/src/routes/oauth.rs b/services/backend/src/routes/oauth.rs new file mode 100644 index 0000000..db68377 --- /dev/null +++ b/services/backend/src/routes/oauth.rs @@ -0,0 +1,748 @@ +//! OAuth 2.1 for the MCP server (docs/mcp.md). Claude registers itself as a +//! client (only with an allowed return address), an admin approves the +//! connection on the site (`/oauth/engedely`, which calls `authorize`), and +//! Claude trades the code for an access token (an hour) and a refresh token +//! (30 days, a new one at every refresh). The admin guards accept the access +//! token (see `auth::MCP_WRITES`); the MCP server checks it with `whoami`. +//! +//! The endpoints Claude calls (`register`, `token`, `revoke`) answer OAuth's +//! own error format; the ones the site calls answer the API's. + +use std::sync::Arc; + +use axum::extract::rejection::{FormRejection, JsonRejection}; +use axum::extract::{FromRequestParts, Path, Query, State}; +use axum::http::header::{AUTHORIZATION, CACHE_CONTROL, PRAGMA}; +use axum::http::request::Parts; +use axum::http::{HeaderMap, StatusCode}; +use axum::response::{IntoResponse, Response}; +use axum::{Form, Json}; +use axum_extra::extract::WithRejection; +use base64::Engine; +use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; +use db::Role; +use serde::Deserialize; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use time::{Duration, OffsetDateTime}; +use uuid::Uuid; + +use super::{Body, St, client_ip}; +use crate::AppState; +use crate::auth::{AuthUser, oauth_user}; +use crate::error::{ApiError, ApiResult}; +use crate::views::{rfc3339, rfc3339_opt}; + +/// What a connection may do: the admin tools (the guards narrow it further). +pub const SCOPE: &str = "admin"; +const ACCESS_TTL: Duration = Duration::hours(1); +const REFRESH_TTL: Duration = Duration::days(30); +const CODE_TTL: Duration = Duration::minutes(10); +const MAX_REDIRECT_URIS: usize = 5; +const AUTH_METHODS: [&str; 3] = ["none", "client_secret_post", "client_secret_basic"]; + +// --- errors in OAuth's format ----------------------------------------------------- + +/// `{"error", "error_description"}` (RFC 6749 5.2, RFC 7591 3.2.2). +#[derive(Debug)] +pub struct OauthError { + status: StatusCode, + error: &'static str, + description: String, +} + +impl OauthError { + fn new(error: &'static str, description: impl Into) -> Self { + let status = if error == "invalid_client" { StatusCode::UNAUTHORIZED } else { StatusCode::BAD_REQUEST }; + Self { status, error, description: description.into() } + } +} + +impl IntoResponse for OauthError { + fn into_response(self) -> Response { + if self.status.is_server_error() { + tracing::error!(error = %self.description, "oauth request failed"); + } + let body = Json(json!({ "error": self.error, "error_description": self.description })); + (self.status, [(CACHE_CONTROL, "no-store")], body).into_response() + } +} + +impl From for OauthError { + fn from(e: sqlx::Error) -> Self { + Self { status: StatusCode::INTERNAL_SERVER_ERROR, error: "server_error", description: format!("database: {e}") } + } +} + +impl From for OauthError { + fn from(e: ApiError) -> Self { + match e { + ApiError::TooManyRequests => { + Self { status: StatusCode::TOO_MANY_REQUESTS, error: "too_many_requests", description: e.to_string() } + } + other => Self { + status: StatusCode::INTERNAL_SERVER_ERROR, + error: "server_error", + description: other.to_string(), + }, + } + } +} + +impl From for OauthError { + fn from(rejection: JsonRejection) -> Self { + Self::new("invalid_client_metadata", rejection.body_text()) + } +} + +impl From for OauthError { + fn from(rejection: FormRejection) -> Self { + Self::new("invalid_request", rejection.body_text()) + } +} + +// --- metadata (RFC 8414) ------------------------------------------------------------ + +/// The authorization server's metadata, served by the frontend at +/// `/.well-known/oauth-authorization-server`. +pub async fn metadata(State(state): St) -> Json { + let base = &state.config.public_base_url; + Json(json!({ + "issuer": base, + "authorization_endpoint": format!("{base}/oauth/engedely"), + "token_endpoint": format!("{base}/api/v1/oauth/token"), + "registration_endpoint": format!("{base}/api/v1/oauth/register"), + "revocation_endpoint": format!("{base}/api/v1/oauth/revoke"), + "response_types_supported": ["code"], + "response_modes_supported": ["query"], + "grant_types_supported": ["authorization_code", "refresh_token"], + "code_challenge_methods_supported": ["S256"], + "token_endpoint_auth_methods_supported": AUTH_METHODS, + "revocation_endpoint_auth_methods_supported": AUTH_METHODS, + "scopes_supported": [SCOPE], + "authorization_response_iss_parameter_supported": true, + })) +} + +// --- client registration (RFC 7591) --------------------------------------------------- + +/// Whether a client may register `uri` as its return address: one of the +/// configured ones, where a trailing `*` stands for a port and any path. +pub fn redirect_allowed(uri: &str, patterns: &[String]) -> bool { + if uri.len() > 500 || uri.contains('#') || uri.chars().any(|c| c.is_whitespace() || c.is_control()) { + return false; + } + patterns.iter().any(|pattern| match pattern.strip_suffix('*') { + None => uri == pattern, + Some(prefix) => uri.strip_prefix(prefix).is_some_and(|rest| { + let port = &rest[..rest.find(['/', '?']).unwrap_or(rest.len())]; + !port.is_empty() && port.len() <= 5 && port.bytes().all(|b| b.is_ascii_digit()) + }), + }) +} + +#[derive(Deserialize)] +pub struct Registration { + #[serde(default)] + redirect_uris: Vec, + client_name: Option, + token_endpoint_auth_method: Option, + grant_types: Option>, + response_types: Option>, +} + +pub async fn register( + State(state): St, + headers: HeaderMap, + WithRejection(Json(req), _): WithRejection, OauthError>, +) -> Result { + state.oauth_limiter.hit(&format!("register:{}", client_ip(&headers).unwrap_or_default()))?; + if req.redirect_uris.is_empty() || req.redirect_uris.len() > MAX_REDIRECT_URIS { + return Err(OauthError::new("invalid_redirect_uri", "Give one to five redirect_uris.")); + } + if let Some(bad) = req.redirect_uris.iter().find(|u| !redirect_allowed(u, &state.config.oauth_redirect_uris)) { + return Err(OauthError::new("invalid_redirect_uri", format!("This redirect_uri is not allowed: {bad}"))); + } + let grant_types = req.grant_types.unwrap_or_else(|| vec!["authorization_code".into()]); + if grant_types.iter().any(|g| g != "authorization_code" && g != "refresh_token") { + return Err(OauthError::new("invalid_client_metadata", "Only authorization_code and refresh_token.")); + } + let response_types = req.response_types.unwrap_or_else(|| vec!["code".into()]); + if response_types.iter().any(|r| r != "code") { + return Err(OauthError::new("invalid_client_metadata", "Only the code response type.")); + } + // RFC 7591's default is client_secret_basic. + let method = req.token_endpoint_auth_method.unwrap_or_else(|| "client_secret_basic".into()); + if !AUTH_METHODS.contains(&method.as_str()) { + return Err(OauthError::new("invalid_client_metadata", "Unsupported token_endpoint_auth_method.")); + } + let name: String = req + .client_name + .as_deref() + .unwrap_or_default() + .chars() + .filter(|c| !c.is_control()) + .take(100) + .collect::() + .trim() + .to_string(); + let name = if name.is_empty() { "MCP-kliens".to_string() } else { name }; + + let client_id = db::random_token(16); + let secret = (method != "none").then(db::new_token); + sqlx::query("INSERT INTO oauth_clients (id, name, redirect_uris, secret_hash) VALUES ($1, $2, $3, $4)") + .bind(&client_id) + .bind(&name) + .bind(&req.redirect_uris) + .bind(secret.as_deref().map(db::token_hash)) + .execute(&state.db) + .await?; + tracing::info!(client = %client_id, name = %name, "oauth client registered"); + let mut body = json!({ + "client_id": client_id, + "client_id_issued_at": OffsetDateTime::now_utc().unix_timestamp(), + "client_name": name, + "redirect_uris": req.redirect_uris, + "grant_types": grant_types, + "response_types": response_types, + "token_endpoint_auth_method": method, + }); + if let Some(secret) = secret { + body["client_secret"] = json!(secret); + body["client_secret_expires_at"] = json!(0); + } + Ok((StatusCode::CREATED, [(CACHE_CONTROL, "no-store")], Json(body)).into_response()) +} + +// --- approval (the site's /oauth/engedely page) ----------------------------------------- + +/// The authorization request's parameters, as the client put them on the +/// approval page's address (and the page sends them on). +#[derive(Debug, Deserialize)] +pub struct AuthorizeParams { + response_type: Option, + client_id: Option, + redirect_uri: Option, + code_challenge: Option, + code_challenge_method: Option, + scope: Option, + state: Option, + resource: Option, + /// POST only: the admin said no. + #[serde(default)] + deny: bool, +} + +/// A checked authorization request. +struct Checked { + client_id: String, + client_name: String, + redirect_uri: String, + code_challenge: String, + state: Option, +} + +fn bad(message: &str) -> ApiError { + ApiError::BadRequest(message.to_string()) +} + +/// The same address with or without a trailing slash. +fn same_resource(a: &str, b: &str) -> bool { + a.trim_end_matches('/') == b.trim_end_matches('/') +} + +async fn check(state: &AppState, p: &AuthorizeParams) -> ApiResult { + let client_id = p.client_id.as_deref().ok_or_else(|| bad("Hiányzik az alkalmazás azonosítója."))?; + let client: Option<(String, Vec)> = + sqlx::query_as("SELECT name, redirect_uris FROM oauth_clients WHERE id = $1") + .bind(client_id) + .fetch_optional(&state.db) + .await?; + let (client_name, redirect_uris) = client.ok_or_else(|| bad("Ismeretlen alkalmazás. Kapcsold össze újra."))?; + let redirect_uri = match &p.redirect_uri { + Some(uri) if redirect_uris.contains(uri) => uri.clone(), + None if redirect_uris.len() == 1 => redirect_uris[0].clone(), + _ => return Err(bad("Ez a visszatérési cím nincs az alkalmazásnál bejegyezve.")), + }; + if p.response_type.as_deref() != Some("code") { + return Err(bad("Csak a „code” válaszforma támogatott.")); + } + if p.code_challenge_method.as_deref() != Some("S256") { + return Err(bad("PKCE (S256) kell.")); + } + let code_challenge = p.code_challenge.clone().unwrap_or_default(); + if !(43..=128).contains(&code_challenge.len()) { + return Err(bad("Hibás PKCE-kód.")); + } + if let Some(resource) = &p.resource + && !same_resource(resource, &state.config.mcp_resource_url) + { + return Err(bad("Ismeretlen erőforrás.")); + } + if p.state.as_deref().is_some_and(|s| s.len() > 1000) { + return Err(bad("Túl hosszú state.")); + } + Ok(Checked { client_id: client_id.to_string(), client_name, redirect_uri, code_challenge, state: p.state.clone() }) +} + +/// The approval page asks what it is approving (no login needed for this). +pub async fn authorize_check( + State(state): St, + WithRejection(Query(p), _): WithRejection, ApiError>, +) -> ApiResult> { + let c = check(&state, &p).await?; + let host = reqwest::Url::parse(&c.redirect_uri).ok().and_then(|u| u.host_str().map(str::to_string)); + Ok(Json(json!({ + "client_name": c.client_name, + "redirect_uri": c.redirect_uri, + "redirect_host": host, + "scope": SCOPE, + "resource": state.config.mcp_resource_url, + // `requested` is what the client asked for; the connection gets `scope`. + "requested_scope": p.scope, + }))) +} + +/// The client's return address with the answer's parameters. +fn answer(redirect_uri: &str, pairs: &[(&str, &str)]) -> ApiResult { + let mut url = reqwest::Url::parse(redirect_uri).map_err(|_| bad("Hibás visszatérési cím."))?; + { + let mut query = url.query_pairs_mut(); + for (key, value) in pairs { + query.append_pair(key, value); + } + } + Ok(url.to_string()) +} + +/// The admin approved (or refused) the connection: the address to send the +/// browser back to the client with a code (or an error). A session only: +/// an MCP client's token cannot make new tokens. +pub async fn authorize( + State(state): St, + auth: AuthUser, + WithRejection(Json(p), _): Body, +) -> ApiResult> { + if !auth.user.has_role(Role::Admin) { + return Err(ApiError::Forbidden("Ehhez admin fiók kell.".into())); + } + let c = check(&state, &p).await?; + let iss = state.config.public_base_url.as_str(); + let mut pairs: Vec<(&str, &str)> = Vec::new(); + let code = db::new_token(); + if p.deny { + pairs.push(("error", "access_denied")); + } else { + sqlx::query( + "INSERT INTO oauth_codes (code_hash, client_id, user_id, redirect_uri, code_challenge, scope, resource, expires_at) \ + VALUES ($1, $2, $3, $4, $5, $6, $7, $8)", + ) + .bind(db::token_hash(&code)) + .bind(&c.client_id) + .bind(auth.id()) + .bind(&c.redirect_uri) + .bind(&c.code_challenge) + .bind(SCOPE) + .bind(&state.config.mcp_resource_url) + .bind(OffsetDateTime::now_utc() + CODE_TTL) + .execute(&state.db) + .await?; + tracing::info!(client = %c.client_id, user = %auth.id(), "oauth connection approved"); + pairs.push(("code", &code)); + } + if let Some(s) = &c.state { + pairs.push(("state", s)); + } + pairs.push(("iss", iss)); + Ok(Json(json!({ "redirect_to": answer(&c.redirect_uri, &pairs)? }))) +} + +// --- tokens --------------------------------------------------------------------------- + +#[derive(Deserialize)] +pub struct TokenRequest { + grant_type: Option, + code: Option, + redirect_uri: Option, + code_verifier: Option, + refresh_token: Option, + client_id: Option, + client_secret: Option, + resource: Option, +} + +/// The client of a token or revocation request: HTTP Basic, the form's +/// `client_id` and `client_secret`, or a public client's `client_id` alone. +async fn client_of( + state: &AppState, + headers: &HeaderMap, + client_id: Option<&str>, + client_secret: Option<&str>, +) -> Result { + let basic = headers + .get(AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Basic ")) + .and_then(|b| STANDARD.decode(b.trim()).ok()) + .and_then(|b| String::from_utf8(b).ok()) + .and_then(|s| s.split_once(':').map(|(id, secret)| (id.to_string(), secret.to_string()))); + let (id, secret) = match basic { + Some((id, secret)) => (id, Some(secret)), + None => ( + client_id.ok_or_else(|| OauthError::new("invalid_client", "Unknown client."))?.to_string(), + client_secret.map(str::to_string), + ), + }; + let row: Option<(Option>,)> = sqlx::query_as("SELECT secret_hash FROM oauth_clients WHERE id = $1") + .bind(&id) + .fetch_optional(&state.db) + .await?; + match row { + None => return Err(OauthError::new("invalid_client", "Unknown client.")), + Some((Some(hash),)) if secret.as_deref().map(db::token_hash).as_ref() != Some(&hash) => { + return Err(OauthError::new("invalid_client", "Wrong client secret.")); + } + _ => {} + } + sqlx::query("UPDATE oauth_clients SET last_used_at = now() WHERE id = $1").bind(&id).execute(&state.db).await?; + Ok(id) +} + +/// PKCE: the verifier's SHA-256, base64url, is the challenge (RFC 7636). +fn pkce_ok(verifier: &str, challenge: &str) -> bool { + (43..=128).contains(&verifier.len()) + && verifier.bytes().all(|b| b.is_ascii_alphanumeric() || b"-._~".contains(&b)) + && URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes())) == challenge +} + +/// A new access and refresh token for a connection. +async fn issue(tx: &mut sqlx::PgConnection, grant_id: Uuid) -> Result { + let (access, refresh) = (db::new_token(), db::new_token()); + let now = OffsetDateTime::now_utc(); + sqlx::query( + "INSERT INTO oauth_tokens (id, grant_id, access_hash, access_expires_at, refresh_hash, refresh_expires_at) \ + VALUES ($1, $2, $3, $4, $5, $6)", + ) + .bind(Uuid::now_v7()) + .bind(grant_id) + .bind(db::token_hash(&access)) + .bind(now + ACCESS_TTL) + .bind(db::token_hash(&refresh)) + .bind(now + REFRESH_TTL) + .execute(&mut *tx) + .await?; + let body = json!({ + "access_token": access, + "token_type": "Bearer", + "expires_in": ACCESS_TTL.whole_seconds(), + "refresh_token": refresh, + "scope": SCOPE, + }); + Ok((StatusCode::OK, [(CACHE_CONTROL, "no-store"), (PRAGMA, "no-cache")], Json(body)).into_response()) +} + +async fn revoke_grant(tx: &mut sqlx::PgConnection, grant_id: Uuid) -> Result<(), sqlx::Error> { + sqlx::query("UPDATE oauth_grants SET revoked_at = now() WHERE id = $1 AND revoked_at IS NULL") + .bind(grant_id) + .execute(&mut *tx) + .await?; + Ok(()) +} + +async fn still_admin(tx: &mut sqlx::PgConnection, user_id: Uuid) -> Result { + sqlx::query_scalar("SELECT 'admin' = ANY(roles) FROM users WHERE id = $1") + .bind(user_id) + .fetch_optional(&mut *tx) + .await + .map(|r| r.unwrap_or(false)) +} + +fn invalid_grant(description: &str) -> OauthError { + OauthError::new("invalid_grant", description) +} + +pub async fn token( + State(state): St, + headers: HeaderMap, + WithRejection(Form(req), _): WithRejection, OauthError>, +) -> Result { + state.oauth_limiter.hit(&format!("token:{}", client_ip(&headers).unwrap_or_default()))?; + let client = client_of(&state, &headers, req.client_id.as_deref(), req.client_secret.as_deref()).await?; + match req.grant_type.as_deref() { + Some("authorization_code") => code_grant(&state, &client, &req).await, + Some("refresh_token") => refresh_grant(&state, &client, &req).await, + _ => Err(OauthError::new("unsupported_grant_type", "Use authorization_code or refresh_token.")), + } +} + +#[derive(sqlx::FromRow)] +struct CodeRow { + client_id: String, + user_id: Uuid, + redirect_uri: String, + code_challenge: String, + scope: String, + resource: Option, + expires_at: OffsetDateTime, + used_at: Option, + grant_id: Option, +} + +async fn code_grant(state: &AppState, client: &str, req: &TokenRequest) -> Result { + let code = req.code.as_deref().ok_or_else(|| OauthError::new("invalid_request", "The code is missing."))?; + let verifier = req + .code_verifier + .as_deref() + .ok_or_else(|| OauthError::new("invalid_request", "The code_verifier is missing."))?; + let code_hash = db::token_hash(code); + let mut tx = state.db.begin().await?; + let row: Option = sqlx::query_as( + "SELECT client_id, user_id, redirect_uri, code_challenge, scope, resource, expires_at, used_at, grant_id \ + FROM oauth_codes WHERE code_hash = $1 FOR UPDATE", + ) + .bind(&code_hash) + .fetch_optional(&mut *tx) + .await?; + let Some(row) = row.filter(|r| r.client_id == client) else { return Err(invalid_grant("Unknown code.")) }; + if row.used_at.is_some() { + // A code sent twice may have been stolen: the connection made with it ends. + if let Some(grant_id) = row.grant_id { + revoke_grant(&mut tx, grant_id).await?; + tx.commit().await?; + tracing::warn!(client, grant = %grant_id, "oauth code used twice: connection revoked"); + } + return Err(invalid_grant("The code was already used.")); + } + if row.expires_at <= OffsetDateTime::now_utc() { + return Err(invalid_grant("The code has expired.")); + } + if req.redirect_uri.as_deref() != Some(row.redirect_uri.as_str()) { + return Err(invalid_grant("The redirect_uri does not match.")); + } + if !pkce_ok(verifier, &row.code_challenge) { + return Err(invalid_grant("Wrong code_verifier.")); + } + if let (Some(asked), Some(granted)) = (&req.resource, &row.resource) + && !same_resource(asked, granted) + { + return Err(OauthError::new("invalid_target", "Unknown resource.")); + } + if !still_admin(&mut tx, row.user_id).await? { + return Err(invalid_grant("The approver is no longer an admin.")); + } + let grant_id = Uuid::now_v7(); + sqlx::query("INSERT INTO oauth_grants (id, client_id, user_id, scope, resource) VALUES ($1, $2, $3, $4, $5)") + .bind(grant_id) + .bind(client) + .bind(row.user_id) + .bind(&row.scope) + .bind(&row.resource) + .execute(&mut *tx) + .await?; + sqlx::query("UPDATE oauth_codes SET used_at = now(), grant_id = $2 WHERE code_hash = $1") + .bind(&code_hash) + .bind(grant_id) + .execute(&mut *tx) + .await?; + let response = issue(&mut tx, grant_id).await?; + tx.commit().await?; + tracing::info!(client, grant = %grant_id, user = %row.user_id, "oauth connection made"); + Ok(response) +} + +#[derive(sqlx::FromRow)] +struct RefreshRow { + id: Uuid, + grant_id: Uuid, + client_id: String, + user_id: Uuid, + refresh_expires_at: OffsetDateTime, + refreshed_at: Option, + revoked_at: Option, +} + +async fn refresh_grant(state: &AppState, client: &str, req: &TokenRequest) -> Result { + let refresh = req + .refresh_token + .as_deref() + .ok_or_else(|| OauthError::new("invalid_request", "The refresh_token is missing."))?; + let mut tx = state.db.begin().await?; + let row: Option = sqlx::query_as( + "SELECT t.id, t.grant_id, g.client_id, g.user_id, t.refresh_expires_at, t.refreshed_at, g.revoked_at \ + FROM oauth_tokens t JOIN oauth_grants g ON g.id = t.grant_id \ + WHERE t.refresh_hash = $1 FOR UPDATE OF t, g", + ) + .bind(db::token_hash(refresh)) + .fetch_optional(&mut *tx) + .await?; + let Some(row) = row.filter(|r| r.client_id == client) else { return Err(invalid_grant("Unknown refresh token.")) }; + if row.revoked_at.is_some() { + return Err(invalid_grant("The connection was revoked.")); + } + if row.refreshed_at.is_some() { + // An old refresh token again: it may have been stolen, so the connection ends. + revoke_grant(&mut tx, row.grant_id).await?; + tx.commit().await?; + tracing::warn!(client, grant = %row.grant_id, "oauth refresh token reused: connection revoked"); + return Err(invalid_grant("The refresh token was already used.")); + } + if row.refresh_expires_at <= OffsetDateTime::now_utc() { + return Err(invalid_grant("The refresh token has expired.")); + } + if !still_admin(&mut tx, row.user_id).await? { + return Err(invalid_grant("The approver is no longer an admin.")); + } + sqlx::query("UPDATE oauth_tokens SET refreshed_at = now() WHERE id = $1").bind(row.id).execute(&mut *tx).await?; + let response = issue(&mut tx, row.grant_id).await?; + tx.commit().await?; + Ok(response) +} + +#[derive(Deserialize)] +pub struct RevokeRequest { + token: Option, + client_id: Option, + client_secret: Option, +} + +/// RFC 7009: either token of a connection ends the whole connection. +pub async fn revoke( + State(state): St, + headers: HeaderMap, + WithRejection(Form(req), _): WithRejection, OauthError>, +) -> Result { + let client = client_of(&state, &headers, req.client_id.as_deref(), req.client_secret.as_deref()).await?; + if let Some(token) = req.token { + let hash = db::token_hash(&token); + sqlx::query( + "UPDATE oauth_grants g SET revoked_at = now() FROM oauth_tokens t \ + WHERE t.grant_id = g.id AND g.client_id = $2 AND g.revoked_at IS NULL \ + AND (t.access_hash = $1 OR t.refresh_hash = $1)", + ) + .bind(hash) + .bind(&client) + .execute(&state.db) + .await?; + } + Ok(StatusCode::OK) +} + +// --- the MCP server's check ------------------------------------------------------------- + +/// Guard: an MCP client's access token of an admin (not a session). +pub struct McpClient(AuthUser); + +impl FromRequestParts> for McpClient { + type Rejection = ApiError; + + async fn from_request_parts(parts: &mut Parts, state: &Arc) -> Result { + let user = oauth_user(parts, state).await?.ok_or(ApiError::Unauthorized)?; + user.require(Role::Admin)?; + Ok(McpClient(user)) + } +} + +/// Who the token belongs to and what it is for (the MCP server checks the +/// resource; no personal data). +pub async fn whoami(McpClient(user): McpClient) -> Json { + let access = user.oauth.as_ref(); + Json(json!({ + "user_id": user.id(), + "roles": user.user.roles, + "grant_id": access.map(|a| a.grant_id), + "scope": access.map(|a| a.scope.as_str()), + "resource": access.and_then(|a| a.resource.as_deref()), + })) +} + +// --- the admin's list of connections ------------------------------------------------------- + +/// A connection: id, client name, its return addresses, the admin's e-mail, made, last used. +type GrantRow = (Uuid, String, Vec, String, OffsetDateTime, Option); + +/// The connections in use (a session only: a client cannot see or end them). +pub async fn admin_grants(State(state): St, auth: AuthUser) -> ApiResult> { + auth.require(Role::Admin)?; + let rows: Vec = sqlx::query_as( + "SELECT g.id, c.name, c.redirect_uris, u.email, g.created_at, g.last_used_at \ + FROM oauth_grants g JOIN oauth_clients c ON c.id = g.client_id JOIN users u ON u.id = g.user_id \ + WHERE g.revoked_at IS NULL \ + AND EXISTS (SELECT 1 FROM oauth_tokens t WHERE t.grant_id = g.id AND t.refresh_expires_at > now()) \ + ORDER BY g.created_at DESC", + ) + .fetch_all(&state.db) + .await?; + let grants: Vec = rows + .into_iter() + .map(|(id, client, uris, email, created, used)| { + let host = + uris.first().and_then(|u| reqwest::Url::parse(u).ok()).and_then(|u| u.host_str().map(String::from)); + json!({ + "id": id, + "client_name": client, + "redirect_host": host, + "user_email": email, + "created_at": rfc3339(created), + "last_used_at": rfc3339_opt(used), + }) + }) + .collect(); + Ok(Json(json!({ "grants": grants }))) +} + +pub async fn admin_revoke_grant( + State(state): St, + auth: AuthUser, + WithRejection(Path(id), _): super::IdPath, +) -> ApiResult { + auth.require(Role::Admin)?; + let done = sqlx::query("UPDATE oauth_grants SET revoked_at = now() WHERE id = $1 AND revoked_at IS NULL") + .bind(id) + .execute(&state.db) + .await?; + if done.rows_affected() == 0 { + return Err(ApiError::NotFound("connection")); + } + tracing::info!(grant = %id, by = %auth.id(), "oauth connection revoked by an admin"); + Ok(StatusCode::NO_CONTENT) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn redirect_addresses() { + let allowed: Vec = crate::config::DEFAULT_OAUTH_REDIRECT_URIS.map(String::from).to_vec(); + for ok in [ + "https://claude.ai/api/mcp/auth_callback", + "https://claude.com/api/mcp/auth_callback", + "http://localhost:53682/callback", + "http://127.0.0.1:8080", + "http://localhost:3000/cb?x=1", + ] { + assert!(redirect_allowed(ok, &allowed), "{ok}"); + } + for no in [ + "https://claude.ai/api/mcp/auth_callback/x", + "https://evil.example/api/mcp/auth_callback", + "http://localhost:80@evil.example/", + "http://localhost.evil.example:80/", + "http://localhost:/cb", + "http://localhost:123456/", + "https://claude.ai/api/mcp/auth_callback#frag", + "javascript:alert(1)", + ] { + assert!(!redirect_allowed(no, &allowed), "{no}"); + } + } + + #[test] + fn pkce() { + // A verifier and its challenge (base64url of the SHA-256). + let verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWZOEjXk"; + assert!(pkce_ok(verifier, "F48zWf2TyV9rECwrMie4mRL3vUXo8lg5CiiT429reII")); + assert!(!pkce_ok(verifier, "F48zWf2TyV9rECwrMie4mRL3vUXo8lg5CiiT429reIX")); + assert!(!pkce_ok("short", "F48zWf2TyV9rECwrMie4mRL3vUXo8lg5CiiT429reII")); + } +} diff --git a/services/backend/src/tests.rs b/services/backend/src/tests.rs index 5e51fa6..7f8ad40 100644 --- a/services/backend/src/tests.rs +++ b/services/backend/src/tests.rs @@ -363,6 +363,19 @@ impl TestApp { (status, headers, resp.into_body().collect().await.unwrap().to_bytes().to_vec()) } + /// A form POST (OAuth's token and revocation endpoints), with extra headers. + async fn form(&self, uri: &str, body: &str, headers: &[(&str, &str)]) -> Response { + let mut req = + Request::builder().method("POST").uri(uri).header("content-type", "application/x-www-form-urlencoded"); + for (name, value) in headers { + req = req.header(*name, *value); + } + let resp = self.router.clone().oneshot(req.body(Body::from(body.to_string())).unwrap()).await.unwrap(); + let (status, headers) = (resp.status(), resp.headers().clone()); + let bytes = resp.into_body().collect().await.unwrap().to_bytes(); + Response { status, body: serde_json::from_slice(&bytes).unwrap_or(Value::Null), headers } + } + async fn call(&self, method: &str, uri: &str, token: Option<&str>, body: Option) -> Response { self.call_with(method, uri, token, body, &[]).await } @@ -1125,7 +1138,7 @@ async fn export_and_delete_account(pool: PgPool) { /// config and catalog, shared links, invitation pages, the waitlist and /// unsubscribing. Every other route (charts, calculations, analyses) needs a /// logged-in user, so other apps cannot use them. -const PUBLIC_ROUTES: [&str; 26] = [ +const PUBLIC_ROUTES: [&str; 31] = [ "/healthz", // Stripe calls it; the signature proves it. "/v1/payments/stripe/webhook", @@ -1157,6 +1170,13 @@ const PUBLIC_ROUTES: [&str; 26] = [ // The sky by date, the same for everyone (the moon and retrograde calendars). "/v1/public/sky", "/v1/public/sky/events", + // OAuth for the MCP clients (docs/mcp.md): Claude calls these before it has + // a token; approving (POST authorize) needs an admin's session. + "/v1/oauth/metadata", + "/v1/oauth/register", + "/v1/oauth/authorize", + "/v1/oauth/token", + "/v1/oauth/revoke", ]; #[sqlx::test(migrator = "db::MIGRATOR")] @@ -4422,3 +4442,244 @@ async fn admin_statistics_and_where_members_came_from(pool: PgPool) { assert!(all["previous"].is_null()); assert_eq!(all["period"]["signups"], 3); } + +// --- MCP clients through OAuth (docs/mcp.md) --------------------------------------------- + +const MCP_CALLBACK: &str = "https://claude.ai/api/mcp/auth_callback"; +const MCP_CALLBACK_ENC: &str = "https%3A%2F%2Fclaude.ai%2Fapi%2Fmcp%2Fauth_callback"; +// A PKCE verifier and its challenge. +const PKCE_VERIFIER: &str = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWZOEjXk"; +const PKCE_CHALLENGE: &str = "F48zWf2TyV9rECwrMie4mRL3vUXo8lg5CiiT429reII"; + +fn mcp_approval(client: &str) -> Value { + json!({ + "response_type": "code", "client_id": client, "redirect_uri": MCP_CALLBACK, + "code_challenge": PKCE_CHALLENGE, "code_challenge_method": "S256", + "state": "xyz", "resource": "https://sorsfonalak.test/mcp", "scope": "admin", + }) +} + +/// The admin approves; returns the code from the address Claude gets back. +async fn mcp_code(app: &TestApp, session: &str, client: &str) -> String { + let r = app.post("/v1/oauth/authorize", Some(session), mcp_approval(client)).await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + let to = r.body["redirect_to"].as_str().unwrap(); + assert!(to.starts_with(&format!("{MCP_CALLBACK}?code=")), "{to}"); + assert!(to.ends_with("&state=xyz&iss=https%3A%2F%2Fsorsfonalak.test"), "{to}"); + to.split("code=").nth(1).unwrap().split('&').next().unwrap().to_string() +} + +fn mcp_exchange(client: &str, code: &str, verifier: &str) -> String { + format!( + "grant_type=authorization_code&code={code}&redirect_uri={MCP_CALLBACK_ENC}&client_id={client}\ + &code_verifier={verifier}&resource=https%3A%2F%2Fsorsfonalak.test%2Fmcp" + ) +} + +/// A new connection: (access token, refresh token). +async fn mcp_connect(app: &TestApp, session: &str, client: &str) -> (String, String) { + let code = mcp_code(app, session, client).await; + let r = app.form("/v1/oauth/token", &mcp_exchange(client, &code, PKCE_VERIFIER), &[]).await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + (r.body["access_token"].as_str().unwrap().into(), r.body["refresh_token"].as_str().unwrap().into()) +} + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn mcp_clients_connect_through_oauth(pool: PgPool) { + let app = TestApp::new(pool).await; + let anna = app.register("anna@example.com", "Anna").await; + let admin = app.register("admin@example.com", "Admin").await; + let anna_id = app.get("/v1/me", Some(&anna)).await.body["user"]["id"].as_str().unwrap().to_string(); + + let meta = app.get("/v1/oauth/metadata", None).await.body; + assert_eq!( + (&meta["issuer"], &meta["token_endpoint"], &meta["authorization_endpoint"]), + ( + &json!("https://sorsfonalak.test"), + &json!("https://sorsfonalak.test/api/v1/oauth/token"), + &json!("https://sorsfonalak.test/oauth/engedely") + ) + ); + + // Registration: only Claude's (or a local) return address. + let r = app.post("/v1/oauth/register", None, json!({"redirect_uris": ["https://evil.example/cb"]})).await; + assert_eq!((r.status, r.body["error"].as_str()), (StatusCode::BAD_REQUEST, Some("invalid_redirect_uri"))); + let r = app + .post( + "/v1/oauth/register", + None, + json!({"client_name": "Claude", "redirect_uris": [MCP_CALLBACK], "token_endpoint_auth_method": "none", + "grant_types": ["authorization_code", "refresh_token"], "logo_uri": "https://claude.ai/x.png"}), + ) + .await; + assert_eq!(r.status, StatusCode::CREATED, "{}", r.body); + assert!(r.body.get("client_secret").is_none()); + let client = r.body["client_id"].as_str().unwrap().to_string(); + + // The approval page's question; a return address the client did not register. + let query = format!( + "response_type=code&client_id={client}&redirect_uri={MCP_CALLBACK_ENC}&code_challenge={PKCE_CHALLENGE}\ + &code_challenge_method=S256&state=xyz" + ); + let r = app.get(&format!("/v1/oauth/authorize?{query}"), None).await; + assert_eq!( + (r.status, &r.body["client_name"], &r.body["redirect_host"]), + (StatusCode::OK, &json!("Claude"), &json!("claude.ai")) + ); + let other = query.replace("claude.ai", "claude.com"); + assert_eq!(app.get(&format!("/v1/oauth/authorize?{other}"), None).await.status, StatusCode::BAD_REQUEST); + let plain = query.replace("S256", "plain"); + assert_eq!(app.get(&format!("/v1/oauth/authorize?{plain}"), None).await.status, StatusCode::BAD_REQUEST); + + // Approving needs a login and the admin role; a refusal goes back too. + assert_eq!(app.post("/v1/oauth/authorize", None, mcp_approval(&client)).await.status, StatusCode::UNAUTHORIZED); + assert_eq!(app.post("/v1/oauth/authorize", Some(&anna), mcp_approval(&client)).await.status, StatusCode::FORBIDDEN); + let mut deny = mcp_approval(&client); + deny["deny"] = json!(true); + let r = app.post("/v1/oauth/authorize", Some(&admin), deny).await; + assert_eq!( + r.body["redirect_to"], + json!(format!("{MCP_CALLBACK}?error=access_denied&state=xyz&iss=https%3A%2F%2Fsorsfonalak.test")) + ); + + // The code: a wrong verifier or return address does not use it up. + let code = mcp_code(&app, &admin, &client).await; + let wrong = mcp_exchange(&client, &code, &"a".repeat(43)); + let r = app.form("/v1/oauth/token", &wrong, &[]).await; + assert_eq!((r.status, r.body["error"].as_str()), (StatusCode::BAD_REQUEST, Some("invalid_grant"))); + let elsewhere = mcp_exchange(&client, &code, PKCE_VERIFIER).replace("claude.ai", "claude.com"); + assert_eq!(app.form("/v1/oauth/token", &elsewhere, &[]).await.body["error"], "invalid_grant"); + let r = app.form("/v1/oauth/token", &mcp_exchange(&client, &code, PKCE_VERIFIER), &[]).await; + assert_eq!( + (r.status, &r.body["token_type"], &r.body["expires_in"]), + (StatusCode::OK, &json!("Bearer"), &json!(3600)), + "{}", + r.body + ); + assert_eq!(r.headers["cache-control"], "no-store"); + let (access, refresh) = + (r.body["access_token"].as_str().unwrap().to_string(), r.body["refresh_token"].as_str().unwrap().to_string()); + + // What the token is for, and what it may do. + let r = app.get("/v1/oauth/whoami", Some(&access)).await; + assert_eq!( + (r.status, &r.body["resource"], &r.body["scope"]), + (StatusCode::OK, &json!("https://sorsfonalak.test/mcp"), &json!("admin")) + ); + assert!(r.body.get("email").is_none()); + assert_eq!(app.get("/v1/oauth/whoami", Some(&admin)).await.status, StatusCode::UNAUTHORIZED); + assert_eq!(app.get("/v1/admin/stats?days=7", Some(&access)).await.status, StatusCode::OK); + assert_eq!(app.get("/v1/admin/users?q=anna", Some(&access)).await.status, StatusCode::OK); + assert_eq!(app.get("/v1/admin/celebrities", Some(&access)).await.status, StatusCode::OK); + let r = app.post("/v1/admin/promo-codes", Some(&access), json!({"package": "single", "count": 1})).await; + assert_eq!(r.status, StatusCode::CREATED, "{}", r.body); + assert_eq!(app.post("/v1/admin/jobs/restart", Some(&access), json!({})).await.status, StatusCode::OK); + // Not a daily task: only on the admin page. + let roles = json!({"roles": ["user", "admin"]}); + let r = app.call("PATCH", &format!("/v1/admin/users/{anna_id}"), Some(&access), Some(roles)).await; + assert_eq!(r.status, StatusCode::FORBIDDEN); + let units = json!({"unit": "natal", "delta": 5}); + let r = app.post(&format!("/v1/admin/users/{anna_id}/credits"), Some(&access), units).await; + assert_eq!(r.status, StatusCode::FORBIDDEN); + // Not an admin page: no session, no new tokens, no list of connections. + assert_eq!(app.get("/v1/me", Some(&access)).await.status, StatusCode::UNAUTHORIZED); + assert_eq!( + app.post("/v1/oauth/authorize", Some(&access), mcp_approval(&client)).await.status, + StatusCode::UNAUTHORIZED + ); + assert_eq!(app.get("/v1/admin/oauth/grants", Some(&access)).await.status, StatusCode::UNAUTHORIZED); + let grants = app.get("/v1/admin/oauth/grants", Some(&admin)).await.body["grants"].clone(); + assert_eq!((grants.as_array().unwrap().len(), &grants[0]["client_name"]), (1, &json!("Claude"))); + + // A refresh makes a new pair; the old refresh token again ends the connection. + let again = format!("grant_type=refresh_token&refresh_token={refresh}&client_id={client}"); + let r = app.form("/v1/oauth/token", &again, &[]).await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); + let access2 = r.body["access_token"].as_str().unwrap().to_string(); + assert_eq!(app.get("/v1/admin/stats", Some(&access2)).await.status, StatusCode::OK); + assert_eq!(app.form("/v1/oauth/token", &again, &[]).await.body["error"], "invalid_grant"); + assert_eq!(app.get("/v1/admin/stats", Some(&access2)).await.status, StatusCode::UNAUTHORIZED); + assert_eq!(app.get("/v1/admin/stats", Some(&access)).await.status, StatusCode::UNAUTHORIZED); + + // A code used twice ends the connection made with it. + let code = mcp_code(&app, &admin, &client).await; + let r = app.form("/v1/oauth/token", &mcp_exchange(&client, &code, PKCE_VERIFIER), &[]).await; + let access3 = r.body["access_token"].as_str().unwrap().to_string(); + let r = app.form("/v1/oauth/token", &mcp_exchange(&client, &code, PKCE_VERIFIER), &[]).await; + assert_eq!(r.body["error"], "invalid_grant"); + assert_eq!(app.get("/v1/admin/stats", Some(&access3)).await.status, StatusCode::UNAUTHORIZED); + + // An expired code. + let code = mcp_code(&app, &admin, &client).await; + sqlx::query("UPDATE oauth_codes SET expires_at = now() - interval '1 second' WHERE used_at IS NULL") + .execute(&app.pool) + .await + .unwrap(); + assert_eq!( + app.form("/v1/oauth/token", &mcp_exchange(&client, &code, PKCE_VERIFIER), &[]).await.body["error"], + "invalid_grant" + ); + + // Ended by the admin on the site, by the client, by logging out everywhere. + let (access4, _) = mcp_connect(&app, &admin, &client).await; + let grants = app.get("/v1/admin/oauth/grants", Some(&admin)).await.body["grants"].clone(); + assert_eq!(grants.as_array().unwrap().len(), 1); + let id = grants[0]["id"].as_str().unwrap(); + assert_eq!( + app.call("DELETE", &format!("/v1/admin/oauth/grants/{id}"), Some(&admin), None).await.status, + StatusCode::NO_CONTENT + ); + assert_eq!(app.get("/v1/admin/stats", Some(&access4)).await.status, StatusCode::UNAUTHORIZED); + let (access5, refresh5) = mcp_connect(&app, &admin, &client).await; + let r = app.form("/v1/oauth/revoke", &format!("token={refresh5}&client_id={client}"), &[]).await; + assert_eq!(r.status, StatusCode::OK); + assert_eq!(app.get("/v1/admin/stats", Some(&access5)).await.status, StatusCode::UNAUTHORIZED); + let (access6, _) = mcp_connect(&app, &admin, &client).await; + assert_eq!(app.post("/v1/auth/logout-all", Some(&admin), json!({})).await.status, StatusCode::NO_CONTENT); + assert_eq!(app.get("/v1/admin/stats", Some(&access6)).await.status, StatusCode::UNAUTHORIZED); + + // An admin no more: the token is refused. + sqlx::query("UPDATE users SET roles = array_append(roles, 'admin') WHERE email = 'anna@example.com'") + .execute(&app.pool) + .await + .unwrap(); + let (anna_access, anna_refresh) = mcp_connect(&app, &anna, &client).await; + assert_eq!(app.get("/v1/admin/stats", Some(&anna_access)).await.status, StatusCode::OK); + sqlx::query("UPDATE users SET roles = array_remove(roles, 'admin') WHERE email = 'anna@example.com'") + .execute(&app.pool) + .await + .unwrap(); + assert_eq!(app.get("/v1/admin/stats", Some(&anna_access)).await.status, StatusCode::FORBIDDEN); + assert_eq!(app.get("/v1/oauth/whoami", Some(&anna_access)).await.status, StatusCode::FORBIDDEN); + let again = format!("grant_type=refresh_token&refresh_token={anna_refresh}&client_id={client}"); + assert_eq!(app.form("/v1/oauth/token", &again, &[]).await.body["error"], "invalid_grant"); + + // A client with a secret must send it (in the form or with HTTP Basic). + let r = app + .post( + "/v1/oauth/register", + None, + json!({"client_name": "Claude Code", "redirect_uris": ["http://localhost:53682/callback"]}), + ) + .await; + assert_eq!((r.status, &r.body["token_endpoint_auth_method"]), (StatusCode::CREATED, &json!("client_secret_basic"))); + let (local, secret) = + (r.body["client_id"].as_str().unwrap().to_string(), r.body["client_secret"].as_str().unwrap().to_string()); + let login = json!({"email": "admin@example.com", "password": "titkos-jelszo-123"}); + let admin = app.post("/v1/auth/login", None, login).await.body["session"]["token"].as_str().unwrap().to_string(); + let mut approval = mcp_approval(&local); + approval["redirect_uri"] = json!("http://localhost:53682/callback"); + let r = app.post("/v1/oauth/authorize", Some(&admin), approval).await; + let to = r.body["redirect_to"].as_str().unwrap(); + let code = to.split("code=").nth(1).unwrap().split('&').next().unwrap(); + let exchange = format!( + "grant_type=authorization_code&code={code}&redirect_uri=http%3A%2F%2Flocalhost%3A53682%2Fcallback\ + &code_verifier={PKCE_VERIFIER}" + ); + let r = app.form("/v1/oauth/token", &format!("{exchange}&client_id={local}"), &[]).await; + assert_eq!((r.status, r.body["error"].as_str()), (StatusCode::UNAUTHORIZED, Some("invalid_client"))); + use base64::Engine; + let basic = format!("Basic {}", base64::engine::general_purpose::STANDARD.encode(format!("{local}:{secret}"))); + let r = app.form("/v1/oauth/token", &exchange, &[("authorization", &basic)]).await; + assert_eq!(r.status, StatusCode::OK, "{}", r.body); +} diff --git a/services/forum/src/auth.rs b/services/forum/src/auth.rs index 8d34536..ce61949 100644 --- a/services/forum/src/auth.rs +++ b/services/forum/src/auth.rs @@ -1,6 +1,9 @@ //! Who is asking: the backend's session (cookie or Bearer token) and the //! member behind it. Reading needs no login; writing needs a nickname. //! Every request of a member also keeps the online dot fresh. +//! +//! An admin's MCP client (docs/mcp.md) may send its OAuth token instead: it +//! reads as that admin and may moderate, but never writes as a member. use std::sync::Arc; @@ -68,6 +71,8 @@ pub struct Viewer { pub topics: Vec, /// The members they muted. pub mutes: Vec, + /// An admin's MCP client (an OAuth token, not a session): moderation only. + pub via_token: bool, } impl Viewer { @@ -89,6 +94,9 @@ impl Viewer { } pub fn require_user(&self) -> Result<&User, ApiError> { + if self.via_token { + return Err(ApiError::Forbidden("Claude-ból a fórumban csak moderálni lehet.".into())); + } self.user.as_ref().ok_or(ApiError::Unauthorized) } @@ -108,7 +116,7 @@ impl Viewer { } pub fn require_moderator(&self) -> Result<&User, ApiError> { - let user = self.require_user()?; + let user = self.user.as_ref().ok_or(ApiError::Unauthorized)?; if self.is_moderator() { Ok(user) } else { Err(ApiError::Forbidden("Ehhez moderátori jog kell.".into())) } } } @@ -127,7 +135,15 @@ impl FromRequestParts> for Viewer { async fn from_request_parts(parts: &mut Parts, state: &Arc) -> Result { let Some(token) = session_token(parts) else { return Ok(Viewer::default()) }; - let Some((_, user)) = db::user_by_session(&state.db, &token).await? else { return Ok(Viewer::default()) }; + let Some((_, user)) = db::user_by_session(&state.db, &token).await? else { + // An admin's MCP client: the admin, without the member's side. + return Ok(match db::user_by_oauth_token(&state.db, &token).await? { + Some((_, user)) if user.has_role(Role::Admin) => { + Viewer { user: Some(user), via_token: true, ..Viewer::default() } + } + _ => Viewer::default(), + }); + }; let member = load_member(&state.db, user.id).await?; if member.is_some() { // At most once a minute per member: the online dot. @@ -154,7 +170,7 @@ impl FromRequestParts> for Viewer { } else { (Vec::new(), Vec::new()) }; - Ok(Viewer { user: Some(user), member, topics, mutes }) + Ok(Viewer { user: Some(user), member, topics, mutes, via_token: false }) } } diff --git a/services/forum/src/tests.rs b/services/forum/src/tests.rs index 15df4a5..30782e4 100644 --- a/services/forum/src/tests.rs +++ b/services/forum/src/tests.rs @@ -1703,3 +1703,71 @@ async fn photos_in_posts(pool: PgPool) { let left: i64 = sqlx::query_scalar("SELECT count(*) FROM forum.photos").fetch_one(&pool).await.unwrap(); assert_eq!(left, 1); } + +/// An admin's MCP client (docs/mcp.md): it moderates with its OAuth token, +/// and never writes as a member. +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn an_admins_mcp_client_moderates_only(pool: PgPool) { + let app = TestApp::new(pool); + let anna = app.member("anna@example.com", "Csendesvíz", &["user"]).await; + let bea = app.member("bea@example.com", "Holdfény", &["user"]).await; + let admin = app.member("admin@example.com", "Gondnok", &["user", "admin"]).await; + let thread = app.thread(&anna, "belso-utak", "Energiák").await; + let post = app.reply(&bea, thread, "Energetikai gyógyítás, írj!", None).await["id"].as_i64().unwrap(); + app.call("POST", &format!("/v1/forum/posts/{post}/report"), Some(&anna), json!({"kind": "ad"})).await; + + // The token the backend gave Claude after the admin's approval. + let token = db::new_token(); + let grant = Uuid::now_v7(); + sqlx::query("INSERT INTO oauth_clients (id, name, redirect_uris) VALUES ('claude', 'Claude', '{}')") + .execute(&app.pool) + .await + .unwrap(); + sqlx::query("INSERT INTO oauth_grants (id, client_id, user_id, scope) VALUES ($1, 'claude', $2, 'admin')") + .bind(grant) + .bind(admin.id) + .execute(&app.pool) + .await + .unwrap(); + sqlx::query( + "INSERT INTO oauth_tokens (id, grant_id, access_hash, access_expires_at, refresh_hash, refresh_expires_at) \ + VALUES ($1, $2, $3, now() + interval '1 hour', $4, now() + interval '30 days')", + ) + .bind(Uuid::now_v7()) + .bind(grant) + .bind(db::token_hash(&token)) + .bind(db::token_hash(&db::new_token())) + .execute(&app.pool) + .await + .unwrap(); + let claude = User { id: admin.id, token }; + + // Moderation: the reports, closing one, a ban, the log (under the admin's name). + let list = app.get("/v1/forum/mod/reports", Some(&claude)).await; + let id = list["reports"][0]["id"].as_i64().unwrap(); + let (status, _) = + app.call("POST", &format!("/v1/forum/mod/reports/{id}"), Some(&claude), json!({"action": "dismiss"})).await; + assert_eq!(status, StatusCode::NO_CONTENT); + let (status, _) = app + .call("POST", "/v1/forum/members/holdfeny/ban", Some(&claude), json!({"hours": 24, "reason": "hirdetés"})) + .await; + assert_eq!(status, StatusCode::OK); + let log = app.get("/v1/forum/mod/log", Some(&claude)).await; + assert_eq!((&log["entries"][0]["action"], &log["entries"][0]["actor"]), (&json!("ban"), &json!("Gondnok"))); + assert_eq!(app.get(&format!("/v1/forum/threads/{thread}"), Some(&claude)).await["thread"]["id"], thread); + + // Never as a member: no reply, reaction, report or new thread. + let reply = json!({"body": "Claude írta."}); + let (status, _) = app.call("POST", &format!("/v1/forum/threads/{thread}/posts"), Some(&claude), reply).await; + assert_eq!(status, StatusCode::FORBIDDEN); + let (status, _) = + app.call("PUT", &format!("/v1/forum/posts/{post}/reaction"), Some(&claude), json!({"kind": "heart"})).await; + assert_eq!(status, StatusCode::FORBIDDEN); + let (status, _) = + app.call("POST", &format!("/v1/forum/posts/{post}/report"), Some(&claude), json!({"kind": "ad"})).await; + assert_eq!(status, StatusCode::FORBIDDEN); + + // A revoked connection is nobody. + sqlx::query("UPDATE oauth_grants SET revoked_at = now()").execute(&app.pool).await.unwrap(); + assert_eq!(app.call("GET", "/v1/forum/mod/reports", Some(&claude), Value::Null).await.0, StatusCode::UNAUTHORIZED); +} diff --git a/services/frontend/next.config.ts b/services/frontend/next.config.ts index 1e958ac..b1afcc2 100644 --- a/services/frontend/next.config.ts +++ b/services/frontend/next.config.ts @@ -14,6 +14,11 @@ const config: NextConfig = { "/kep/fooldal.png": ["./src/assets/og/*.ttf"], "/hires-emberek/[slug]/kep/[file]": ["./src/assets/og/*.ttf"], }, + // OAuth for the MCP server's clients (docs/mcp.md): the authorization + // server's metadata, from the backend, at its standard address. + async rewrites() { + return [{ source: "/.well-known/oauth-authorization-server", destination: "/api/v1/oauth/metadata" }]; + }, images: { // Only the famous people's photos (served by the backend through the // /api/v1 proxy, one stored version each) go through the optimizer. diff --git a/services/frontend/src/app/admin/kapcsolatok/Connections.tsx b/services/frontend/src/app/admin/kapcsolatok/Connections.tsx new file mode 100644 index 0000000..bba885c --- /dev/null +++ b/services/frontend/src/app/admin/kapcsolatok/Connections.tsx @@ -0,0 +1,80 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; + +import { confirmDialog } from "@/components/Dialogs"; +import { api, errorText } from "@/lib/api"; +import { formatDate } from "@/lib/astro"; +import type { OauthGrant } from "@/lib/types"; + +/** The MCP clients connected to the admin tools, and revoking them. */ +export function Connections() { + const [grants, setGrants] = useState(null); + const [error, setError] = useState(null); + + const load = useCallback(async () => { + try { + setGrants((await api<{ grants: OauthGrant[] }>("/admin/oauth/grants")).grants); + setError(null); + } catch (e) { + setError(errorText(e)); + } + }, []); + + useEffect(() => { + load(); + }, [load]); + + async function revoke(grant: OauthGrant) { + const ok = await confirmDialog({ + title: `Visszavonod: ${grant.client_name}?`, + text: "Az alkalmazás azonnal elveszíti a hozzáférést. Újra összekötni Claude-ban lehet.", + confirm: "Visszavonás", + danger: true, + }); + if (!ok) return; + try { + await api(`/admin/oauth/grants/${grant.id}`, { method: "DELETE" }); + await load(); + } catch (e) { + setError(errorText(e)); + } + } + + if (error) return

{error}

; + if (!grants) return

Betöltés…

; + if (grants.length === 0) return

Nincs kapcsolt alkalmazás.

; + return ( +
+ + + + + + + + + + + {grants.map((g) => ( + + + + + + + + ))} + +
AlkalmazásAdminÖsszekötveUtoljára használta +
+ {g.client_name} + {g.redirect_host && · {g.redirect_host}} + {g.user_email}{formatDate(g.created_at, true)}{formatDate(g.last_used_at, true)} + +
+
+ ); +} diff --git a/services/frontend/src/app/admin/kapcsolatok/page.tsx b/services/frontend/src/app/admin/kapcsolatok/page.tsx new file mode 100644 index 0000000..e96a510 --- /dev/null +++ b/services/frontend/src/app/admin/kapcsolatok/page.tsx @@ -0,0 +1,27 @@ +import type { Metadata } from "next"; +import { notFound } from "next/navigation"; + +import { AdminNav } from "@/components/AdminNav"; +import { requireMe } from "@/lib/server"; + +import { Connections } from "./Connections"; + +export const metadata: Metadata = { title: "Claude" }; + +export default async function AdminConnectionsPage() { + const me = await requireMe("/admin/kapcsolatok"); + if (!me.user.roles.includes("admin")) notFound(); + return ( +
+ +
+

Claude

+

+ Az admin eszközökhöz kapcsolt alkalmazások. Claude-ban az összekötő címe:{" "} + https://sorsfonalak.hu/mcp. Az összekötéskor admin fiókkal kell belépni és engedélyezni. +

+
+ +
+ ); +} diff --git a/services/frontend/src/app/globals.css b/services/frontend/src/app/globals.css index 3de6893..6495619 100644 --- a/services/frontend/src/app/globals.css +++ b/services/frontend/src/app/globals.css @@ -1931,3 +1931,8 @@ span.tarot-fan-card { cursor: default; } .spark-axis { margin-left: 0; } .funnel li { grid-template-columns: minmax(0, 1fr); gap: 4px; } } + +/* The OAuth approval page (/oauth/engedely). */ +.oauth-scope { margin: 0; padding-left: 20px; display: flex; flex-direction: column; gap: 8px; } +.oauth-actions { display: flex; gap: 12px; flex-wrap: wrap; align-items: center; } +.oauth-actions .msg { flex-basis: 100%; } diff --git a/services/frontend/src/app/oauth/engedely/Approve.tsx b/services/frontend/src/app/oauth/engedely/Approve.tsx new file mode 100644 index 0000000..a2c908e --- /dev/null +++ b/services/frontend/src/app/oauth/engedely/Approve.tsx @@ -0,0 +1,53 @@ +"use client"; + +import { useState } from "react"; + +import { api, errorText } from "@/lib/api"; + +export type OauthParams = Partial< + Record< + | "response_type" + | "client_id" + | "redirect_uri" + | "code_challenge" + | "code_challenge_method" + | "scope" + | "state" + | "resource", + string + > +>; + +/** The admin's answer: the backend gives the address back to the client (with a code, or a refusal). */ +export function Approve({ params }: { params: OauthParams }) { + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + async function answer(deny: boolean) { + setBusy(true); + setError(null); + try { + const r = await api<{ redirect_to: string }>("/oauth/authorize", { body: { ...params, deny } }); + window.location.assign(r.redirect_to); + } catch (e) { + setError(errorText(e)); + setBusy(false); + } + } + + return ( +
+ + + {error && ( +

+ {error} +

+ )} +
+ ); +} diff --git a/services/frontend/src/app/oauth/engedely/page.tsx b/services/frontend/src/app/oauth/engedely/page.tsx new file mode 100644 index 0000000..b60f8ff --- /dev/null +++ b/services/frontend/src/app/oauth/engedely/page.tsx @@ -0,0 +1,109 @@ +import type { Metadata } from "next"; +import { redirect } from "next/navigation"; + +import { BACKEND_URL, getMe } from "@/lib/server"; + +import { Approve, type OauthParams } from "./Approve"; + +export const metadata: Metadata = { title: "Claude összekötése", robots: { index: false } }; + +type Props = { searchParams: Promise> }; + +const PARAMS = [ + "response_type", + "client_id", + "redirect_uri", + "code_challenge", + "code_challenge_method", + "scope", + "state", + "resource", +] as const; + +interface Check { + client_name: string; + redirect_host: string | null; +} + +/** + * The OAuth approval page (docs/mcp.md): Claude sends the admin here to + * connect the admin tools. The backend checks the request first; only an + * admin may approve it. + */ +export default async function OauthApprovalPage({ searchParams }: Props) { + const raw = await searchParams; + const params: OauthParams = {}; + const query = new URLSearchParams(); + for (const name of PARAMS) { + const value = Array.isArray(raw[name]) ? raw[name][0] : raw[name]; + if (value !== undefined) { + params[name] = value; + query.set(name, value); + } + } + + let check: Check | null = null; + let problem = "A kérés nem érkezett meg rendesen."; + try { + const res = await fetch(`${BACKEND_URL}/v1/oauth/authorize?${query}`, { cache: "no-store" }); + const body = await res.json(); + if (res.ok) check = body as Check; + else problem = body?.error?.message ?? problem; + } catch { + problem = "A szerver most nem érhető el. Próbáld újra."; + } + + if (!check) { + return ( +
+
+

Az összekötés nem sikerült

+

{problem}

+

Próbáld újra az összekötést Claude-ban.

+
+
+ ); + } + + const me = await getMe(); + if (!me) redirect(`/belepes?vissza=${encodeURIComponent(`/oauth/engedely?${query}`)}`); + if (!me.user.roles.includes("admin")) { + return ( +
+
+

Ehhez admin fiók kell

+

Az admin eszközöket csak admin fiókkal lehet Claude-dal összekötni.

+
+
+ ); + } + + return ( +
+
+ Admin eszközök +

{check.client_name} hozzáférést kér

+
+
+

+ Ha engedélyezed, a(z) {check.client_name} a te admin jogoddal használhatja a Sorsfonalak + admin eszközeit. +

+
    +
  • + Lekérdezheti a statisztikát, a visszajelzéseket, az értékeléseket, a hibanaplót, a háttérfeladatokat, a + tagokat, a promókódokat és a meghívókat. A tagok e-mail-címe és neve rejtve marad. +
  • +
  • + Elvégezheti a napi teendőket: promókód készítése, visszajelzés megválaszolása, feladat újraindítása, hiba + törlése, meghívó küldése, fórumbejelentés lezárása, kitiltás. Minden ilyen lépés előtt rákérdez. +
  • +
  • Szerepkört, kreditet, csomagot, promptot és modellt nem módosíthat: ezek az admin oldalon maradnak.
  • +
+ {check.redirect_host &&

Engedélyezés után visszakerülsz ide: {check.redirect_host}.

} +

A kapcsolatot bármikor visszavonhatod: Admin → Claude.

+ +
+
+ ); +} diff --git a/services/frontend/src/components/AdminNav.tsx b/services/frontend/src/components/AdminNav.tsx index 0587316..94c43f7 100644 --- a/services/frontend/src/components/AdminNav.tsx +++ b/services/frontend/src/components/AdminNav.tsx @@ -15,6 +15,7 @@ const PAGES = [ { href: "/admin/promptok", label: "Promptok" }, { href: "/admin/modellek", label: "Modellek" }, { href: "/admin/hibak", label: "Hibanapló" }, + { href: "/admin/kapcsolatok", label: "Claude" }, ]; /** May manage the famous people (an admin or a creator). */ diff --git a/services/frontend/src/lib/types.ts b/services/frontend/src/lib/types.ts index e69f76c..3b45835 100644 --- a/services/frontend/src/lib/types.ts +++ b/services/frontend/src/lib/types.ts @@ -952,3 +952,13 @@ export interface AdminStats { content: { kind: string; done: number; failed: number; cost_usd: number }[]; weekly: { week_start: string; readers: number; emails: number }[]; } + +/** An MCP client an admin connected to the admin tools (docs/mcp.md). */ +export interface OauthGrant { + id: string; + client_name: string; + redirect_host: string | null; + user_email: string; + created_at: string; + last_used_at: string | null; +} diff --git a/services/mcp/Cargo.toml b/services/mcp/Cargo.toml new file mode 100644 index 0000000..e5c2fb2 --- /dev/null +++ b/services/mcp/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "mcp" +description = "Sorsfonalak MCP server: the admin tools for Claude, called with the admin's OAuth token" +edition.workspace = true +version.workspace = true +license.workspace = true +publish.workspace = true + +[dependencies] +service-kit.workspace = true +anyhow.workspace = true +axum.workspace = true +reqwest.workspace = true +rmcp = { version = "3.12", default-features = false, features = ["server", "macros", "transport-streamable-http-server"] } +schemars = "1" +serde.workspace = true +serde_json.workspace = true +sha2.workspace = true +tokio = { workspace = true, features = ["time"] } +tower-http.workspace = true +tracing.workspace = true + +[dev-dependencies] +tower = { version = "0.5", features = ["util"] } +http-body-util = "0.1" diff --git a/services/mcp/Dockerfile b/services/mcp/Dockerfile new file mode 100644 index 0000000..0767359 --- /dev/null +++ b/services/mcp/Dockerfile @@ -0,0 +1,33 @@ +# syntax=docker/dockerfile:1 +# +# Build from the repository root: +# docker build -f services/mcp/Dockerfile -t sorsfonalak/mcp . + +ARG RUST_VERSION=1.99 + +# --- 1. static (musl) build ---------------------------------------------------- +FROM rust:${RUST_VERSION}-alpine AS build +RUN apk add --no-cache musl-dev +WORKDIR /app +COPY Cargo.toml Cargo.lock ./ +COPY crates crates +COPY services services +RUN --mount=type=cache,target=/usr/local/cargo/registry,sharing=locked \ + --mount=type=cache,target=/app/target,sharing=locked \ + cargo build --release --locked -p mcp \ + && cp target/release/mcp /mcp +# The log directory (LOG_DIR); a volume mounted here takes over its owner. +RUN mkdir /logs + +# --- 2. runtime: the binary only (TLS roots are compiled in via webpki-roots) --- +FROM scratch +COPY --from=build /mcp /mcp +COPY --from=build --chown=65532:65532 /logs /logs +ENV BIND_ADDR=0.0.0.0:8084 \ + LOG_FORMAT=json \ + RUST_LOG=info,rmcp=warn +USER 65532:65532 +EXPOSE 8084 +HEALTHCHECK --interval=30s --timeout=3s --start-period=10s --retries=3 \ + CMD ["/mcp", "healthcheck"] +ENTRYPOINT ["/mcp"] diff --git a/services/mcp/src/api.rs b/services/mcp/src/api.rs new file mode 100644 index 0000000..e6efa36 --- /dev/null +++ b/services/mcp/src/api.rs @@ -0,0 +1,77 @@ +//! Calls of the site's API with the caller's token. + +use std::time::Duration; + +use axum::http::StatusCode; +use reqwest::Method; +use serde_json::Value; + +pub struct Api { + http: reqwest::Client, + base: String, +} + +/// A refused or failed call: the status and the API's message. +#[derive(Debug)] +pub struct Failure { + pub status: Option, + pub message: String, +} + +impl Api { + pub fn new(base: &str) -> Self { + let http = reqwest::Client::builder() + .timeout(Duration::from_secs(60)) + .user_agent("sorsfonalak-mcp") + .build() + .expect("HTTP client"); + Self { http, base: base.trim_end_matches('/').to_string() } + } + + /// `/oauth/whoami`: `Ok(Some)` for a valid token, `Ok(None)` for an + /// unknown one, `Err(status)` otherwise. + pub async fn whoami(&self, token: &str) -> Result, StatusCode> { + let response = + self.http.get(format!("{}/oauth/whoami", self.base)).bearer_auth(token).send().await.map_err(|e| { + tracing::warn!(error = %e, "whoami"); + StatusCode::BAD_GATEWAY + })?; + let status = StatusCode::from_u16(response.status().as_u16()).unwrap_or(StatusCode::BAD_GATEWAY); + match status { + StatusCode::OK => Ok(Some(response.json().await.map_err(|_| StatusCode::BAD_GATEWAY)?)), + StatusCode::UNAUTHORIZED => Ok(None), + other => Err(other), + } + } + + /// One call; the answer's JSON (`null` for an empty one). + pub async fn call( + &self, + token: &str, + method: Method, + path: &str, + query: &[(&str, String)], + body: Option<&Value>, + ) -> Result { + let mut request = self.http.request(method, format!("{}{path}", self.base)).bearer_auth(token).query(query); + if let Some(body) = body { + request = request.json(body); + } + let response = request + .send() + .await + .map_err(|e| Failure { status: None, message: format!("A szerver nem érhető el: {e}") })?; + let status = StatusCode::from_u16(response.status().as_u16()).unwrap_or(StatusCode::BAD_GATEWAY); + let bytes = response.bytes().await.map_err(|e| Failure { status: Some(status), message: e.to_string() })?; + let value: Value = + if bytes.is_empty() { Value::Null } else { serde_json::from_slice(&bytes).unwrap_or(Value::Null) }; + if status.is_success() { + return Ok(value); + } + let message = value["error"]["message"] + .as_str() + .map(str::to_string) + .unwrap_or_else(|| format!("A kérés nem sikerült ({status}).")); + Err(Failure { status: Some(status), message }) + } +} diff --git a/services/mcp/src/auth.rs b/services/mcp/src/auth.rs new file mode 100644 index 0000000..3ff8742 --- /dev/null +++ b/services/mcp/src/auth.rs @@ -0,0 +1,123 @@ +//! The token check in front of `/mcp`. The backend knows the tokens: it is +//! asked once a minute per token (`/oauth/whoami`); the tools send the token +//! on with every call, and the backend checks it again there, so a revoked +//! connection stops at once whatever this cache says. + +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use axum::extract::{Request, State}; +use axum::http::header::{AUTHORIZATION, WWW_AUTHENTICATE}; +use axum::http::{HeaderValue, StatusCode}; +use axum::middleware::Next; +use axum::response::{IntoResponse, Response}; +use sha2::{Digest, Sha256}; + +use crate::App; + +const CACHE_TTL: Duration = Duration::from_secs(60); +const CACHE_MAX: usize = 1000; + +/// The caller's token, for the tools (in the HTTP request's extensions). +#[derive(Clone)] +pub struct Bearer(pub String); + +/// What the backend said about a token. +#[derive(Debug, PartialEq, Eq)] +pub enum Verdict { + Valid, + /// Unknown, expired, revoked, or for another server. + Invalid, + /// Valid, but its owner is no admin any more. + Forbidden, + /// The backend did not answer. + Unavailable, +} + +/// Tokens found valid in the last minute (by their hash). +#[derive(Default)] +pub struct TokenCache(Mutex>); + +impl TokenCache { + fn fresh(&self, key: &[u8; 32]) -> bool { + self.0.lock().expect("token cache").get(key).is_some_and(|at| at.elapsed() < CACHE_TTL) + } + + fn remember(&self, key: [u8; 32]) { + let mut map = self.0.lock().expect("token cache"); + if map.len() >= CACHE_MAX { + map.retain(|_, at| at.elapsed() < CACHE_TTL); + } + map.insert(key, Instant::now()); + } + + /// The backend refused the token in a tool call: the next request asks again + /// (and gets 401, so the client logs in again or refreshes). + pub fn forget(&self, token: &str) { + let key: [u8; 32] = Sha256::digest(token.as_bytes()).into(); + self.0.lock().expect("token cache").remove(&key); + } +} + +/// Asks the backend (or the cache) about a token. +pub async fn check(app: &App, token: &str) -> Verdict { + let key: [u8; 32] = Sha256::digest(token.as_bytes()).into(); + if app.tokens.fresh(&key) { + return Verdict::Valid; + } + let verdict = match app.api.whoami(token).await { + Ok(Some(who)) => { + let resource = who["resource"].as_str(); + let ours = |r: &str| r.trim_end_matches('/') == app.config.mcp_public_url.trim_end_matches('/'); + if resource.is_none_or(ours) { Verdict::Valid } else { Verdict::Invalid } + } + Ok(None) => Verdict::Invalid, + Err(status) if status == StatusCode::FORBIDDEN => Verdict::Forbidden, + Err(status) if status == StatusCode::UNAUTHORIZED => Verdict::Invalid, + Err(_) => Verdict::Unavailable, + }; + if verdict == Verdict::Valid { + app.tokens.remember(key); + } + verdict +} + +/// 401 (or 403) with where to find the OAuth metadata, as MCP clients expect. +fn refuse(app: &App, status: StatusCode, error: Option<&str>) -> Response { + let mut value = String::from("Bearer"); + if let Some(error) = error { + value.push_str(&format!(" error=\"{error}\",")); + } + value.push_str(&format!(" scope=\"admin\", resource_metadata=\"{}\"", app.config.resource_metadata_url())); + let mut response = + (status, axum::Json(serde_json::json!({ "error": error.unwrap_or("unauthorized") }))).into_response(); + if let Ok(header) = HeaderValue::from_str(&value) { + response.headers_mut().insert(WWW_AUTHENTICATE, header); + } + response +} + +/// Middleware: only requests with a valid token reach the MCP service. +pub async fn require_token(State(app): State>, mut request: Request, next: Next) -> Response { + let token = request + .headers() + .get(AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .and_then(|v| v.strip_prefix("Bearer ")) + .map(|t| t.trim().to_string()) + .filter(|t| !t.is_empty()); + let Some(token) = token else { return refuse(&app, StatusCode::UNAUTHORIZED, None) }; + match check(&app, &token).await { + Verdict::Valid => { + request.extensions_mut().insert(Bearer(token)); + next.run(request).await + } + Verdict::Invalid => refuse(&app, StatusCode::UNAUTHORIZED, Some("invalid_token")), + Verdict::Forbidden => refuse(&app, StatusCode::FORBIDDEN, Some("insufficient_scope")), + Verdict::Unavailable => { + (StatusCode::SERVICE_UNAVAILABLE, axum::Json(serde_json::json!({ "error": "backend_unavailable" }))) + .into_response() + } + } +} diff --git a/services/mcp/src/main.rs b/services/mcp/src/main.rs new file mode 100644 index 0000000..8b6aeaa --- /dev/null +++ b/services/mcp/src/main.rs @@ -0,0 +1,149 @@ +//! Sorsfonalak MCP server (docs/mcp.md): the admin tools for Claude. +//! +//! Claude connects to `/mcp` (Streamable HTTP, stateless). Without a valid +//! token it gets 401 with the address of this server's OAuth metadata, which +//! names the site as the authorization server: an admin approves the +//! connection there, and the backend issues the tokens. Every tool calls the +//! site's API (through the frontend's `/api/v1` proxy, like the admin pages) +//! with the caller's token, so the backend decides what is allowed, and the +//! answers go back with the members' e-mail addresses and names masked. +//! +//! Configuration: `API_URL` (default `http://localhost:3001/api/v1`), +//! `PUBLIC_BASE_URL` (the site, the authorization server; default +//! `http://localhost:3001`), `MCP_PUBLIC_URL` (this server's address as +//! Claude sees it; default `http://localhost:8084/mcp`), `BIND_ADDR` (default +//! `0.0.0.0:8084`), `LOG_FORMAT`, `RUST_LOG`, `LOG_DIR`. +//! +//! `mcp healthcheck` performs a local health check (for Docker). + +mod api; +mod auth; +mod mask; +#[cfg(test)] +mod tests; +mod tools; + +use std::sync::Arc; + +use anyhow::Context; +use axum::routing::get; +use axum::{Json, Router, middleware}; +use rmcp::transport::streamable_http_server::session::never::NeverSessionManager; +use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService}; +use serde_json::{Value, json}; +use tower_http::trace::TraceLayer; + +const DEFAULT_BIND_ADDR: &str = "0.0.0.0:8084"; + +pub struct Config { + /// The site's API (`…/api/v1`). + pub api_url: String, + /// The site: the OAuth authorization server. + pub public_base_url: String, + /// This server's `/mcp` address as clients see it (the tokens' audience). + pub mcp_public_url: String, +} + +impl Config { + fn from_env() -> Self { + let var = |name: &str, default: &str| { + std::env::var(name) + .ok() + .map(|v| v.trim().trim_end_matches('/').to_string()) + .filter(|v| !v.is_empty()) + .unwrap_or_else(|| default.to_string()) + }; + Self { + api_url: var("API_URL", "http://localhost:3001/api/v1"), + public_base_url: var("PUBLIC_BASE_URL", "http://localhost:3001"), + mcp_public_url: var("MCP_PUBLIC_URL", "http://localhost:8084/mcp"), + } + } + + /// `scheme://host[:port]` of the MCP address. + fn origin(&self) -> &str { + let after_scheme = self.mcp_public_url.find("://").map_or(0, |i| i + 3); + let end = self.mcp_public_url[after_scheme..].find('/').map_or(self.mcp_public_url.len(), |i| after_scheme + i); + &self.mcp_public_url[..end] + } + + /// The host name of the MCP address (accepted as the `Host` header). + fn host(&self) -> String { + let origin = self.origin(); + let host = origin.split("://").nth(1).unwrap_or(origin); + host.split(':').next().unwrap_or(host).to_string() + } + + /// Where the protected resource's metadata is (in the 401 answers). + pub fn resource_metadata_url(&self) -> String { + format!("{}/.well-known/oauth-protected-resource/mcp", self.origin()) + } +} + +pub struct App { + pub config: Config, + pub api: api::Api, + pub tokens: auth::TokenCache, +} + +impl App { + pub fn new(config: Config) -> Self { + Self { api: api::Api::new(&config.api_url), config, tokens: auth::TokenCache::default() } + } +} + +/// The protected resource's metadata (RFC 9728). +async fn resource_metadata(axum::extract::State(app): axum::extract::State>) -> Json { + Json(json!({ + "resource": app.config.mcp_public_url, + "authorization_servers": [app.config.public_base_url], + "scopes_supported": ["admin"], + "bearer_methods_supported": ["header"], + "resource_name": "Sorsfonalak admin", + "resource_documentation": format!("{}/admin", app.config.public_base_url), + })) +} + +async fn health() -> Json { + Json(json!({ "status": "ok" })) +} + +pub fn router(app: Arc) -> Router { + let mut hosts = vec![app.config.host(), "localhost".to_string(), "127.0.0.1".to_string(), "mcp".to_string()]; + hosts.dedup(); + let config = StreamableHttpServerConfig::default() + .with_legacy_session_mode(false) + .with_json_response(true) + .with_allowed_hosts(hosts); + let tools_app = app.clone(); + let mcp = StreamableHttpService::new( + move || Ok(tools::Tools::new(tools_app.clone())), + Arc::new(NeverSessionManager::default()), + config, + ); + let protected = + Router::new().nest_service("/mcp", mcp).layer(middleware::from_fn_with_state(app.clone(), auth::require_token)); + Router::new() + .route("/healthz", get(health)) + .route("/.well-known/oauth-protected-resource", get(resource_metadata)) + .route("/.well-known/oauth-protected-resource/mcp", get(resource_metadata)) + .with_state(app) + .merge(protected) + .layer(TraceLayer::new_for_http().make_span_with(service_kit::RequestLog).on_response(service_kit::RequestLog)) +} + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + let addr = service_kit::bind_addr(DEFAULT_BIND_ADDR)?; + if std::env::args().nth(1).as_deref() == Some("healthcheck") { + return service_kit::healthcheck(addr); + } + let _log = service_kit::init_logging("mcp"); + let config = Config::from_env(); + tracing::info!(api = %config.api_url, resource = %config.mcp_public_url, "starting"); + let app = router(Arc::new(App::new(config))); + let listener = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?; + tracing::info!(%addr, "listening"); + axum::serve(listener, app).with_graceful_shutdown(service_kit::shutdown_signal()).await?; + Ok(()) +} diff --git a/services/mcp/src/mask.rs b/services/mcp/src/mask.rs new file mode 100644 index 0000000..3442706 --- /dev/null +++ b/services/mcp/src/mask.rs @@ -0,0 +1,121 @@ +//! The members' personal data stays on the site: e-mail addresses go to +//! Claude as `an***@gmail.com` (in free text too), and people's names as +//! `[rejtve]`. Forum nicknames are pseudonyms and stay; so do the names of +//! famous people and packages (a `name` is a person's only beside an `email`). + +use serde_json::{Map, Value}; + +/// Keys whose text is always a person's name. +const NAME_KEYS: [&str; 7] = + ["display_name", "from_name", "inviter_name", "recipient_name", "invited_by", "accepted_by", "buyer_name"]; +const HIDDEN: &str = "[rejtve]"; + +pub fn mask(value: &mut Value) { + match value { + Value::String(s) => { + if s.contains('@') { + *s = mask_emails(s); + } + } + Value::Array(items) => items.iter_mut().for_each(mask), + Value::Object(map) => mask_object(map), + _ => {} + } +} + +fn mask_object(map: &mut Map) { + let has_email = map.get("email").is_some_and(Value::is_string); + for (key, child) in map.iter_mut() { + let a_name = NAME_KEYS.contains(&key.as_str()) || (has_email && key == "name"); + if a_name && child.is_string() { + *child = Value::String(HIDDEN.into()); + } else { + mask(child); + } + } +} + +fn local_char(c: char) -> bool { + c.is_alphanumeric() || "._%+-".contains(c) +} + +fn domain_char(c: char) -> bool { + c.is_alphanumeric() || ".-".contains(c) +} + +/// Every e-mail address in the text: the first two characters of the name +/// part, then `***`, and the domain. +pub fn mask_emails(text: &str) -> String { + let chars: Vec = text.chars().collect(); + let mut out = String::with_capacity(text.len()); + let mut i = 0; + while i < chars.len() { + if chars[i] != '@' { + out.push(chars[i]); + i += 1; + continue; + } + // The name part is already in `out`: find where it starts. + let mut start = i; + while start > 0 && local_char(chars[start - 1]) { + start -= 1; + } + let mut end = i + 1; + while end < chars.len() && domain_char(chars[end]) { + end += 1; + } + let domain: String = chars[i + 1..end].iter().collect::().trim_end_matches('.').to_string(); + let local_len = i - start; + if local_len == 0 || !domain.contains('.') { + out.push('@'); + i += 1; + continue; + } + let kept: String = chars[start..start + local_len.min(2)].iter().collect(); + for _ in 0..local_len { + out.pop(); + } + out.push_str(&kept); + out.push_str("***@"); + out.push_str(&domain); + i += 1 + domain.chars().count(); + } + out +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + + #[test] + fn addresses_in_text() { + assert_eq!(mask_emails("anna.kovacs@gmail.com"), "an***@gmail.com"); + assert_eq!(mask_emails("Írj: b@freemail.hu, köszi."), "Írj: b***@freemail.hu, köszi."); + assert_eq!(mask_emails("x@y nem cím, @ sem"), "x@y nem cím, @ sem"); + assert_eq!(mask_emails("a@b.hu és cc@dd.com."), "a***@b.hu és cc***@dd.com."); + } + + #[test] + fn people_but_not_packages_or_famous_names() { + let mut v = json!({ + "users": [{"id": "1", "email": "anna@example.com", "display_name": "Kovács Anna", "roles": ["user"]}], + "redeemed_by": {"email": "bea@example.com", "name": "Bea"}, + "package": {"id": "couple", "name": "Páros"}, + "celebrity": {"name": "Liszt Ferenc"}, + "message": "Hívj: anna@example.com", + "recipient_name": "Cili", + "count": 3, + }); + mask(&mut v); + assert_eq!(v["users"][0]["email"], "an***@example.com"); + assert_eq!(v["users"][0]["display_name"], "[rejtve]"); + assert_eq!(v["redeemed_by"], json!({"email": "be***@example.com", "name": "[rejtve]"})); + assert_eq!(v["package"]["name"], "Páros"); + assert_eq!(v["celebrity"]["name"], "Liszt Ferenc"); + assert_eq!(v["message"], "Hívj: an***@example.com"); + assert_eq!(v["recipient_name"], "[rejtve]"); + assert_eq!(v["count"], 3); + } +} diff --git a/services/mcp/src/tests.rs b/services/mcp/src/tests.rs new file mode 100644 index 0000000..4a47175 --- /dev/null +++ b/services/mcp/src/tests.rs @@ -0,0 +1,199 @@ +//! The MCP server against a fake site API. + +use std::sync::{Arc, Mutex}; + +use axum::body::Body; +use axum::extract::{Query, State}; +use axum::http::{HeaderMap, Request, StatusCode}; +use axum::routing::{get, post}; +use axum::{Json, Router}; +use http_body_util::BodyExt; +use serde_json::{Value, json}; +use tower::ServiceExt; + +use crate::{App, Config, router}; + +const GOOD: &str = "good-token"; +const ELSEWHERE: &str = "token-for-another-server"; +const FORMER_ADMIN: &str = "former-admin-token"; +/// Valid at the check, revoked by the time of the tool call. +const REVOKED: &str = "revoked-meanwhile"; +static REVOKED_CHECKS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// What the fake API received: (path with query, the bearer token). +type Calls = Arc>>; + +fn bearer(headers: &HeaderMap) -> String { + headers.get("authorization").and_then(|v| v.to_str().ok()).unwrap_or("").trim_start_matches("Bearer ").to_string() +} + +async fn fake_whoami(headers: HeaderMap) -> (StatusCode, Json) { + match bearer(&headers).as_str() { + GOOD => (StatusCode::OK, Json(json!({"resource": "https://sorsfonalak.test/mcp", "scope": "admin"}))), + ELSEWHERE => (StatusCode::OK, Json(json!({"resource": "https://other.test/mcp"}))), + FORMER_ADMIN => (StatusCode::FORBIDDEN, Json(json!({"error": {"code": "forbidden"}}))), + REVOKED => { + REVOKED_CHECKS.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + (StatusCode::OK, Json(json!({"resource": "https://sorsfonalak.test/mcp"}))) + } + _ => (StatusCode::UNAUTHORIZED, Json(json!({"error": {"code": "unauthorized"}}))), + } +} + +async fn fake_stats( + State(calls): State, + headers: HeaderMap, + Query(q): Query>, +) -> Json { + calls.lock().unwrap().push((format!("/admin/stats?days={}", q["days"]), bearer(&headers))); + Json(json!({ + "totals": {"members": 3}, + "cohort": {"details": [{"detail": "utm_source=facebook", "signups": 2}]}, + "note": "Kérdezte: anna@example.com", + "user": {"email": "bea@example.com", "name": "Bea"}, + })) +} + +async fn fake_users_patch() -> (StatusCode, Json) { + (StatusCode::FORBIDDEN, Json(json!({"error": {"code": "forbidden", "message": "Ezt Claude-ból nem lehet."}}))) +} + +async fn fake_ban(State(calls): State, uri: axum::http::Uri, headers: HeaderMap) -> Json { + calls.lock().unwrap().push((uri.path().to_string(), bearer(&headers))); + Json(json!({"banned_until": "2026-11-28T10:00:00Z"})) +} + +/// The fake API on a free port; the MCP router pointed at it. +async fn setup() -> (Router, Calls) { + let calls: Calls = Arc::default(); + let api = Router::new() + .route("/api/v1/oauth/whoami", get(fake_whoami)) + .route("/api/v1/admin/stats", get(fake_stats)) + .route("/api/v1/admin/promo-codes", post(fake_users_patch)) + .route( + "/api/v1/admin/jobs", + get(|| async { (StatusCode::UNAUTHORIZED, Json(json!({"error": {"code": "unauthorized"}}))) }), + ) + .route("/api/v1/forum/members/{nickname}/ban", post(fake_ban)) + .with_state(calls.clone()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(async move { axum::serve(listener, api).await.unwrap() }); + let config = Config { + api_url: format!("http://{addr}/api/v1"), + public_base_url: "https://sorsfonalak.test".into(), + mcp_public_url: "https://sorsfonalak.test/mcp".into(), + }; + (router(Arc::new(App::new(config))), calls) +} + +/// A JSON-RPC call to `/mcp`: the status, the `WWW-Authenticate` header, the body. +async fn rpc(app: &Router, token: Option<&str>, body: Value) -> (StatusCode, Option, Value) { + let mut req = Request::builder() + .method("POST") + .uri("/mcp") + .header("host", "sorsfonalak.test") + .header("content-type", "application/json") + .header("accept", "application/json, text/event-stream") + .header("mcp-protocol-version", "2025-06-18"); + if let Some(t) = token { + req = req.header("authorization", format!("Bearer {t}")); + } + let resp = app.clone().oneshot(req.body(Body::from(body.to_string())).unwrap()).await.unwrap(); + let status = resp.status(); + let www = resp.headers().get("www-authenticate").map(|v| v.to_str().unwrap().to_string()); + let bytes = resp.into_body().collect().await.unwrap().to_bytes(); + let text = String::from_utf8_lossy(&bytes); + // A JSON answer, or the data line of an event stream. + let json = text + .lines() + .find_map(|l| l.strip_prefix("data:").map(str::trim).filter(|d| d.starts_with('{'))) + .unwrap_or(&text); + (status, www, serde_json::from_str(json).unwrap_or(Value::Null)) +} + +fn call(id: i64, name: &str, arguments: Value) -> Value { + json!({"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": {"name": name, "arguments": arguments}}) +} + +/// The text of a tool result. +fn result_text(body: &Value) -> Value { + serde_json::from_str(body["result"]["content"][0]["text"].as_str().unwrap()).unwrap_or(Value::Null) +} + +#[tokio::test] +async fn without_a_token_claude_learns_where_to_log_in() { + let (app, _) = setup().await; + let init = json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { + "protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "test", "version": "1"}}}); + let (status, www, _) = rpc(&app, None, init.clone()).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + let expected = "resource_metadata=\"https://sorsfonalak.test/.well-known/oauth-protected-resource/mcp\""; + assert!(www.as_deref().unwrap().contains(expected), "{www:?}"); + + // The metadata points at the site. + let req = Request::builder().uri("/.well-known/oauth-protected-resource/mcp").body(Body::empty()).unwrap(); + let resp = app.clone().oneshot(req).await.unwrap(); + let meta: Value = serde_json::from_slice(&resp.into_body().collect().await.unwrap().to_bytes()).unwrap(); + assert_eq!(meta["resource"], "https://sorsfonalak.test/mcp"); + assert_eq!(meta["authorization_servers"], json!(["https://sorsfonalak.test"])); + + // A wrong token, one for another server, one of a former admin. + let (status, www, _) = rpc(&app, Some("nonsense"), init.clone()).await; + assert_eq!(status, StatusCode::UNAUTHORIZED); + assert!(www.unwrap().contains("error=\"invalid_token\"")); + assert_eq!(rpc(&app, Some(ELSEWHERE), init.clone()).await.0, StatusCode::UNAUTHORIZED); + assert_eq!(rpc(&app, Some(FORMER_ADMIN), init.clone()).await.0, StatusCode::FORBIDDEN); + + // A good one. + let (status, _, body) = rpc(&app, Some(GOOD), init).await; + assert_eq!(status, StatusCode::OK, "{body}"); + assert_eq!(body["result"]["serverInfo"]["name"], "sorsfonalak"); +} + +#[tokio::test] +async fn tools_call_the_api_with_the_token_and_mask_people() { + let (app, calls) = setup().await; + let (_, _, body) = rpc(&app, Some(GOOD), json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list"})).await; + let tools = body["result"]["tools"].as_array().unwrap_or_else(|| panic!("{body}")); + let tool = |name: &str| tools.iter().find(|t| t["name"] == name).unwrap_or_else(|| panic!("no {name}")); + assert_eq!(tool("get_stats")["annotations"]["readOnlyHint"], true); + assert_eq!(tool("forum_ban")["annotations"]["destructiveHint"], true); + assert_eq!(tool("create_promo_codes")["annotations"]["readOnlyHint"], false); + assert!(tool("create_promo_codes")["inputSchema"]["required"].as_array().unwrap().contains(&json!("package"))); + assert_eq!(tools.len(), 34); + + let (_, _, body) = rpc(&app, Some(GOOD), call(2, "get_stats", json!({"days": 7}))).await; + assert_eq!(body["result"]["isError"], false, "{body}"); + let stats = result_text(&body); + assert_eq!(stats["totals"]["members"], 3); + assert_eq!(stats["note"], "Kérdezte: an***@example.com"); + assert_eq!(stats["user"], json!({"email": "be***@example.com", "name": "[rejtve]"})); + assert_eq!(calls.lock().unwrap()[0], ("/admin/stats?days=7".to_string(), GOOD.to_string())); + + // The API's refusal reaches Claude as a tool error. + let (_, _, body) = + rpc(&app, Some(GOOD), call(3, "create_promo_codes", json!({"package": "single", "count": 1}))).await; + assert_eq!(body["result"]["isError"], true, "{body}"); + assert_eq!(body["result"]["content"][0]["text"], "Ezt Claude-ból nem lehet."); + + // A nickname goes into the path encoded; a bad id never reaches the API. + let (_, _, body) = + rpc(&app, Some(GOOD), call(4, "forum_ban", json!({"nickname": "Hold fény", "reason": "hirdetés"}))).await; + assert_eq!(body["result"]["isError"], false, "{body}"); + assert_eq!(calls.lock().unwrap()[1].0, "/api/v1/forum/members/Hold%20f%C3%A9ny/ban"); + let (_, _, body) = rpc(&app, Some(GOOD), call(5, "get_celebrity", json!({"id": "../users"}))).await; + assert!(body["error"].is_object() || body["result"]["isError"] == true, "{body}"); + assert_eq!(calls.lock().unwrap().len(), 2); +} + +#[tokio::test] +async fn a_token_the_backend_refuses_is_checked_again() { + let (app, _) = setup().await; + let (_, _, body) = rpc(&app, Some(REVOKED), call(1, "list_jobs", json!({}))).await; + assert_eq!(body["result"]["isError"], true, "{body}"); + let checks = REVOKED_CHECKS.load(std::sync::atomic::Ordering::SeqCst); + // Not from the cache: the backend is asked again. + rpc(&app, Some(REVOKED), call(2, "list_jobs", json!({}))).await; + assert_eq!(REVOKED_CHECKS.load(std::sync::atomic::Ordering::SeqCst), checks + 1); +} diff --git a/services/mcp/src/tools.rs b/services/mcp/src/tools.rs new file mode 100644 index 0000000..f6483db --- /dev/null +++ b/services/mcp/src/tools.rs @@ -0,0 +1,754 @@ +//! The tools: each one call of the site's admin (or forum moderation) API +//! with the caller's token. The backend decides what the token may do (see +//! `auth::MCP_WRITES` there); the answers are masked (`mask`). + +use std::sync::Arc; + +use axum::http::StatusCode; +use axum::http::request::Parts; +use reqwest::Method; +use rmcp::handler::server::tool::Extension; +use rmcp::handler::server::wrapper::Parameters; +use rmcp::model::{CallToolResult, ContentBlock}; +use rmcp::{ErrorData, ServerHandler, tool, tool_handler, tool_router}; +use schemars::JsonSchema; +use serde::Deserialize; +use serde_json::{Value, json}; + +use crate::App; +use crate::auth::Bearer; +use crate::mask::mask; + +#[derive(Clone)] +pub struct Tools { + app: Arc, +} + +type ToolResult = Result; + +/// `(name, value)` pairs of a query, without the missing values. +fn query(pairs: [(&'static str, Option); N]) -> Vec<(&'static str, String)> { + pairs.into_iter().filter_map(|(k, v)| v.map(|v| (k, v))).collect() +} + +/// A UUID path segment (nothing else may get into the path). +fn uuid(id: &str) -> Result<&str, ErrorData> { + let ok = id.len() == 36 + && id.char_indices().all(|(i, c)| if [8, 13, 18, 23].contains(&i) { c == '-' } else { c.is_ascii_hexdigit() }); + if ok { Ok(id) } else { Err(ErrorData::invalid_params(format!("Not an id: {id}"), None)) } +} + +/// A path segment, percent-encoded (forum nicknames have accents and spaces). +fn segment(text: &str) -> String { + text.bytes() + .map(|b| { + if b.is_ascii_alphanumeric() || b"-._~".contains(&b) { + (b as char).to_string() + } else { + format!("%{b:02X}") + } + }) + .collect() +} + +impl Tools { + pub fn new(app: Arc) -> Self { + Self { app } + } + + /// Calls the API with the caller's token; the masked answer, or the + /// API's refusal as a tool error Claude can read. + async fn run( + &self, + parts: &Parts, + method: Method, + path: &str, + query: Vec<(&str, String)>, + body: Option, + ) -> ToolResult { + let token = parts + .extensions + .get::() + .map(|b| b.0.clone()) + .ok_or_else(|| ErrorData::invalid_request("No token.", None))?; + tracing::info!(%method, path, "tool call"); + match self.app.api.call(&token, method, path, &query, body.as_ref()).await { + Ok(mut value) => { + if value.is_null() { + value = json!({ "ok": true }); + } + mask(&mut value); + Ok(CallToolResult::success(vec![ContentBlock::text(value.to_string())])) + } + Err(failure) if failure.status == Some(StatusCode::UNAUTHORIZED) => { + self.app.tokens.forget(&token); + Ok(CallToolResult::error(vec![ContentBlock::text( + "The connection has ended or expired: connect again.", + )])) + } + Err(failure) => { + tracing::info!(path, status = ?failure.status, "tool call refused"); + Ok(CallToolResult::error(vec![ContentBlock::text(failure.message)])) + } + } + } + + async fn get(&self, parts: &Parts, path: &str, query: Vec<(&str, String)>) -> ToolResult { + self.run(parts, Method::GET, path, query, None).await + } +} + +// --- parameters ------------------------------------------------------------------------- + +#[derive(Deserialize, JsonSchema)] +pub struct StatsParams { + /// The last this many days with today: 7, 30 or 90; 0 means since the first member. Default 30. + days: Option, +} + +#[derive(Deserialize, JsonSchema)] +pub struct MembersParams { + /// Part of an e-mail address or name (a full address finds one member). + query: Option, + /// At most this many (default 50, at most 200). + limit: Option, + offset: Option, +} + +#[derive(Deserialize, JsonSchema)] +pub struct FeedbackParams { + /// `open` (new and in progress, the default), `new`, `in_progress`, `done`, `dismissed` or `all`. + status: Option, +} + +#[derive(Deserialize, JsonSchema)] +pub struct SummaryParams { + /// The period in days (default 90). + days: Option, +} + +#[derive(Deserialize, JsonSchema)] +pub struct RatingsParams { + /// `natal`, `synastry`, `forecast`, `tarot`, `question`… + kind: Option, + /// At most this many stars (2: the unhappy ones). + max_stars: Option, + /// Only the ones with a comment. + with_comment: Option, + /// Only the ones not reviewed yet. + unreviewed: Option, + limit: Option, + offset: Option, +} + +#[derive(Deserialize, JsonSchema)] +pub struct IdParams { + /// The id (a UUID). + id: String, +} + +#[derive(Deserialize, JsonSchema)] +pub struct ErrorsParams { + /// `analysis`, `question` or `preview`. + source: Option, + /// `retry`, `fallback` or `failed`. + outcome: Option, + limit: Option, + offset: Option, +} + +#[derive(Deserialize, JsonSchema)] +pub struct PromoListParams { + /// `unused` (default), `used`, `revoked` or `all`. + status: Option, + /// A package id (see list_packages). + package: Option, + /// Part of the code, the note or the redeemer's e-mail. + query: Option, + limit: Option, + offset: Option, +} + +#[derive(Deserialize, JsonSchema)] +pub struct GiftsParams { + /// Part of the code, the buyer's or recipient's address, or the recipient's name. + query: Option, +} + +#[derive(Deserialize, JsonSchema)] +pub struct NewCodesParams { + /// The package id (see list_packages). + package: String, + /// How many codes (1–500). + count: i64, + /// Who they are for, which campaign. + note: Option, +} + +#[derive(Deserialize, JsonSchema)] +pub struct FeedbackUpdateParams { + /// The message's id. + id: String, + /// `new`, `in_progress`, `done` or `dismissed`. + status: Option, + /// The answer the member sees on the site's feedback page (Hungarian); empty clears it. + reply: Option, + /// A note only the admins see; empty clears it. + admin_note: Option, +} + +#[derive(Deserialize, JsonSchema)] +pub struct IdsParams { + /// These ids; none: all of them. + ids: Option>, +} + +#[derive(Deserialize, JsonSchema)] +pub struct DeleteErrorsParams { + /// One entry's id. + id: Option, + /// Every entry of this source: `analysis`, `question` or `preview`. + source: Option, + /// Every entry with this outcome: `retry`, `fallback` or `failed`. + outcome: Option, + /// Every entry: needed when neither an id nor a filter is given. + #[serde(default)] + all: bool, +} + +#[derive(Deserialize, JsonSchema)] +pub struct InviteParams { + /// The addresses to invite (each gets an e-mail). + emails: Vec, + /// A personal line in the e-mail. + message: Option, + /// A package the invitees get as a promo code (see list_packages). + package: Option, + /// `hu` (default) or `en`. + locale: Option, +} + +#[derive(Deserialize, JsonSchema)] +pub struct NumericIdParams { + /// The id (a number). + id: i64, +} + +#[derive(Deserialize, JsonSchema)] +pub struct HandleReportParams { + /// The report's id. + id: i64, + /// `resolve` (acted on, or nothing more needed) or `dismiss` (unfounded). + action: String, +} + +#[derive(Deserialize, JsonSchema)] +pub struct TopicDecisionParams { + /// The topic's slug. + topic: String, + /// The member's nickname. + nickname: String, + /// `approve` or `reject` (a request), or `remove` (a member). + action: String, +} + +#[derive(Deserialize, JsonSchema)] +pub struct BanParams { + /// The member's nickname. + nickname: String, + /// For this many hours (1–8760); missing: for good. + hours: Option, + /// The reason, sent to the member (Hungarian). + reason: String, +} + +#[derive(Deserialize, JsonSchema)] +pub struct NicknameParams { + /// The member's nickname. + nickname: String, +} + +// --- the tools -------------------------------------------------------------------------- + +#[tool_router] +impl Tools { + // Reading. + + #[tool( + description = "Site statistics for a period: new members, own charts, purchases and revenue (HUF), \ + analyses and questions, weekly horoscope readers, forum posts, AI cost (USD), each with \ + the previous period; day by day; the funnel from sign-up to payment; where members came \ + from; packages sold; the weekly horoscope by week; what the AI wrote.", + annotations(title = "Statisztika", read_only_hint = true) + )] + async fn get_stats( + &self, + Extension(parts): Extension, + Parameters(p): Parameters, + ) -> ToolResult { + self.get(&parts, "/admin/stats", query([("days", Some(p.days.unwrap_or(30).to_string()))])).await + } + + #[tool( + description = "Members (admins too): id, masked e-mail, roles, verified, sign-up and last login, own \ + charts, unit balances. Search by part of an e-mail or name.", + annotations(title = "Tagok", read_only_hint = true) + )] + async fn search_members( + &self, + Extension(parts): Extension, + Parameters(p): Parameters, + ) -> ToolResult { + let q = query([ + ("q", p.query), + ("limit", p.limit.map(|v| v.to_string())), + ("offset", p.offset.map(|v| v.to_string())), + ]); + self.get(&parts, "/admin/users", q).await + } + + #[tool( + description = "Feedback messages members sent (bug reports, ideas, questions) with their state, the \ + admin's note and reply.", + annotations(title = "Visszajelzések", read_only_hint = true) + )] + async fn list_feedback( + &self, + Extension(parts): Extension, + Parameters(p): Parameters, + ) -> ToolResult { + self.get(&parts, "/admin/feedback", query([("status", p.status)])).await + } + + #[tool( + description = "The feedback numbers: ratings of the AI texts by kind, model, prompt and week, the tags, \ + the recommendation question (NPS), and the count of open messages.", + annotations(title = "Visszajelzések összesítve", read_only_hint = true) + )] + async fn feedback_summary( + &self, + Extension(parts): Extension, + Parameters(p): Parameters, + ) -> ToolResult { + let summary = + self.get(&parts, "/admin/feedback/summary", query([("days", p.days.map(|d| d.to_string()))])).await?; + if summary.is_error == Some(true) { + return Ok(summary); + } + let count = self.get(&parts, "/admin/feedback/count", vec![]).await?; + let text = |r: &CallToolResult| match r.content.first() { + Some(ContentBlock::Text(t)) => serde_json::from_str::(&t.text).unwrap_or(Value::Null), + _ => Value::Null, + }; + let both = json!({ "summary": text(&summary), "open_messages": text(&count) }); + Ok(CallToolResult::success(vec![ContentBlock::text(both.to_string())])) + } + + #[tool( + description = "Members' star ratings of the AI analyses and answers, with tags and comments.", + annotations(title = "Értékelések", read_only_hint = true) + )] + async fn list_ratings( + &self, + Extension(parts): Extension, + Parameters(p): Parameters, + ) -> ToolResult { + let q = query([ + ("kind", p.kind), + ("max_stars", p.max_stars.map(|v| v.to_string())), + ("with_comment", p.with_comment.map(|v| v.to_string())), + ("unreviewed", p.unreviewed.map(|v| v.to_string())), + ("limit", p.limit.map(|v| v.to_string())), + ("offset", p.offset.map(|v| v.to_string())), + ]); + self.get(&parts, "/admin/ratings", q).await + } + + #[tool( + description = "The text a rating is about (only when the member allowed it to be read).", + annotations(title = "Értékelt szöveg", read_only_hint = true) + )] + async fn get_rated_content( + &self, + Extension(parts): Extension, + Parameters(p): Parameters, + ) -> ToolResult { + self.get(&parts, &format!("/admin/ratings/{}/content", uuid(&p.id)?), vec![]).await + } + + #[tool( + description = "The AI generation error log: retries, fallbacks to the second model, failures.", + annotations(title = "Hibanapló", read_only_hint = true) + )] + async fn list_errors( + &self, + Extension(parts): Extension, + Parameters(p): Parameters, + ) -> ToolResult { + let q = query([ + ("source", p.source), + ("outcome", p.outcome), + ("limit", p.limit.map(|v| v.to_string())), + ("offset", p.offset.map(|v| v.to_string())), + ]); + self.get(&parts, "/admin/errors", q).await + } + + #[tool( + description = "The AI texts waiting or being written (analyses, answers), with attempts and errors.", + annotations(title = "Háttérfeladatok", read_only_hint = true) + )] + async fn list_jobs(&self, Extension(parts): Extension) -> ToolResult { + self.get(&parts, "/admin/jobs", vec![]).await + } + + #[tool( + description = "The packages on sale: id, name, price (HUF) and what they contain.", + annotations(title = "Csomagok", read_only_hint = true) + )] + async fn list_packages(&self, Extension(parts): Extension) -> ToolResult { + self.get(&parts, "/packages", vec![]).await + } + + #[tool( + description = "Promo codes: package, note, state, who redeemed them and when.", + annotations(title = "Promókódok", read_only_hint = true) + )] + async fn list_promo_codes( + &self, + Extension(parts): Extension, + Parameters(p): Parameters, + ) -> ToolResult { + let q = query([ + ("status", p.status), + ("package", p.package), + ("q", p.query), + ("limit", p.limit.map(|v| v.to_string())), + ("offset", p.offset.map(|v| v.to_string())), + ]); + self.get(&parts, "/admin/promo-codes", q).await + } + + #[tool( + description = "Invitations sent by e-mail (the site is invitation-only for new accounts unless opened): \ + state, sends, acceptance, the package code that came with them.", + annotations(title = "Meghívók", read_only_hint = true) + )] + async fn list_invitations(&self, Extension(parts): Extension) -> ToolResult { + self.get(&parts, "/admin/invitations", vec![]).await + } + + #[tool( + description = "Paid gift packages: buyer, recipient, scheduled send, redemption, refunds.", + annotations(title = "Ajándékok", read_only_hint = true) + )] + async fn list_gifts( + &self, + Extension(parts): Extension, + Parameters(p): Parameters, + ) -> ToolResult { + self.get(&parts, "/admin/gifts", query([("q", p.query)])).await + } + + #[tool( + description = "The famous people's pages (public charts): name, slug, published, the analysis' state.", + annotations(title = "Hírességek", read_only_hint = true) + )] + async fn list_celebrities(&self, Extension(parts): Extension) -> ToolResult { + self.get(&parts, "/admin/celebrities", vec![]).await + } + + #[tool(description = "One famous person's page in full.", annotations(title = "Híresség", read_only_hint = true))] + async fn get_celebrity( + &self, + Extension(parts): Extension, + Parameters(p): Parameters, + ) -> ToolResult { + self.get(&parts, &format!("/admin/celebrities/{}", uuid(&p.id)?), vec![]).await + } + + #[tool( + description = "The AI prompts of every kind and language (the current texts and versions).", + annotations(title = "Promptok", read_only_hint = true) + )] + async fn list_prompts(&self, Extension(parts): Extension) -> ToolResult { + self.get(&parts, "/admin/prompts", vec![]).await + } + + #[tool( + description = "Which AI model writes each kind of text, and the fallback models.", + annotations(title = "Modellek", read_only_hint = true) + )] + async fn list_models(&self, Extension(parts): Extension) -> ToolResult { + self.get(&parts, "/admin/models", vec![]).await + } + + // Daily tasks (Claude asks before each). + + #[tool( + description = "Makes promo codes for a package. Each code gives the package once; share them as \ + https://sorsfonalak.hu/bevaltas?kod=CODE.", + annotations(title = "Promókód készítése", read_only_hint = false, destructive_hint = false) + )] + async fn create_promo_codes( + &self, + Extension(parts): Extension, + Parameters(p): Parameters, + ) -> ToolResult { + let body = json!({ "package": p.package, "count": p.count, "note": p.note }); + self.run(&parts, Method::POST, "/admin/promo-codes", vec![], Some(body)).await + } + + #[tool( + description = "Withdraws an unused promo code: it cannot be redeemed any more.", + annotations(title = "Promókód visszavonása", read_only_hint = false, destructive_hint = true) + )] + async fn revoke_promo_code( + &self, + Extension(parts): Extension, + Parameters(p): Parameters, + ) -> ToolResult { + let path = format!("/admin/promo-codes/{}/revoke", uuid(&p.id)?); + self.run(&parts, Method::POST, &path, vec![], Some(json!({}))).await + } + + #[tool( + description = "Changes a feedback message: its state, the admin's note, or the reply the member sees on \ + the site.", + annotations(title = "Visszajelzés kezelése", read_only_hint = false, destructive_hint = false) + )] + async fn update_feedback( + &self, + Extension(parts): Extension, + Parameters(p): Parameters, + ) -> ToolResult { + let mut body = json!({}); + for (key, value) in [("status", p.status), ("reply", p.reply), ("admin_note", p.admin_note)] { + if let Some(v) = value { + body[key] = json!(v); + } + } + self.run(&parts, Method::PATCH, &format!("/admin/feedback/{}", uuid(&p.id)?), vec![], Some(body)).await + } + + #[tool( + description = "Marks ratings as looked at (these ids, or all).", + annotations( + title = "Értékelések átnézve", + read_only_hint = false, + destructive_hint = false, + idempotent_hint = true + ) + )] + async fn mark_ratings_reviewed( + &self, + Extension(parts): Extension, + Parameters(p): Parameters, + ) -> ToolResult { + let ids = p + .ids + .map(|ids| ids.iter().map(|i| uuid(i).map(str::to_string)).collect::, _>>()) + .transpose()?; + self.run(&parts, Method::POST, "/admin/ratings/reviewed", vec![], Some(json!({ "ids": ids }))).await + } + + #[tool( + description = "Starts open AI jobs again with the current models (these ids, or all open ones).", + annotations(title = "Feladatok újraindítása", read_only_hint = false, destructive_hint = false) + )] + async fn restart_jobs( + &self, + Extension(parts): Extension, + Parameters(p): Parameters, + ) -> ToolResult { + let ids = p + .ids + .map(|ids| ids.iter().map(|i| uuid(i).map(str::to_string)).collect::, _>>()) + .transpose()?; + self.run(&parts, Method::POST, "/admin/jobs/restart", vec![], Some(json!({ "ids": ids }))).await + } + + #[tool( + description = "Deletes error log entries: one (id), the ones matching a filter, or all (all=true).", + annotations(title = "Hibák törlése", read_only_hint = false, destructive_hint = true) + )] + async fn delete_errors( + &self, + Extension(parts): Extension, + Parameters(p): Parameters, + ) -> ToolResult { + if let Some(id) = p.id { + return self.run(&parts, Method::DELETE, &format!("/admin/errors/{id}"), vec![], None).await; + } + if p.source.is_none() && p.outcome.is_none() && !p.all { + return Ok(CallToolResult::error(vec![ContentBlock::text( + "Give an id, a filter (source, outcome), or all=true.", + )])); + } + self.run(&parts, Method::DELETE, "/admin/errors", query([("source", p.source), ("outcome", p.outcome)]), None) + .await + } + + #[tool( + description = "Invites people by e-mail to sign up (a real e-mail goes to each address). Each address \ + gets a result: invited, already_user, already_invited, opted_out or invalid.", + annotations( + title = "Meghívó küldése", + read_only_hint = false, + destructive_hint = false, + open_world_hint = true + ) + )] + async fn send_invitation( + &self, + Extension(parts): Extension, + Parameters(p): Parameters, + ) -> ToolResult { + let body = json!({ "emails": p.emails, "message": p.message, "package": p.package, "locale": p.locale }); + self.run(&parts, Method::POST, "/admin/invitations", vec![], Some(body)).await + } + + #[tool( + description = "Sends an invitation e-mail again.", + annotations( + title = "Meghívó újraküldése", + read_only_hint = false, + destructive_hint = false, + open_world_hint = true + ) + )] + async fn resend_invitation( + &self, + Extension(parts): Extension, + Parameters(p): Parameters, + ) -> ToolResult { + let path = format!("/admin/invitations/{}/resend", uuid(&p.id)?); + self.run(&parts, Method::POST, &path, vec![], Some(json!({}))).await + } + + #[tool( + description = "Writes an analysis again in place (same id and link) with the current prompt and model; \ + nobody is charged, but it costs AI money.", + annotations(title = "Elemzés újraírása", read_only_hint = false, destructive_hint = true) + )] + async fn regenerate_analysis( + &self, + Extension(parts): Extension, + Parameters(p): Parameters, + ) -> ToolResult { + let path = format!("/admin/analyses/{}/regenerate", uuid(&p.id)?); + self.run(&parts, Method::POST, &path, vec![], None).await + } + + #[tool( + description = "Answers a member's question again in place with the current prompt and model; nobody is \ + charged, but it costs AI money.", + annotations(title = "Válasz újraírása", read_only_hint = false, destructive_hint = true) + )] + async fn regenerate_answer( + &self, + Extension(parts): Extension, + Parameters(p): Parameters, + ) -> ToolResult { + let path = format!("/admin/questions/{}/regenerate", uuid(&p.id)?); + self.run(&parts, Method::POST, &path, vec![], None).await + } + + // The forum's moderation. + + #[tool( + description = "Forum reports (posts and private messages members reported), the crisis ones first, with \ + the reported text and state.", + annotations(title = "Fórum: bejelentések", read_only_hint = true) + )] + async fn forum_reports(&self, Extension(parts): Extension) -> ToolResult { + self.get(&parts, "/forum/mod/reports", vec![]).await + } + + #[tool( + description = "Closes a forum report (and the other open reports of the same post): resolve or dismiss. \ + The reporters get an e-mail about it.", + annotations(title = "Fórum: bejelentés lezárása", read_only_hint = false, destructive_hint = false) + )] + async fn forum_handle_report( + &self, + Extension(parts): Extension, + Parameters(p): Parameters, + ) -> ToolResult { + let path = format!("/forum/mod/reports/{}", p.id); + self.run(&parts, Method::POST, &path, vec![], Some(json!({ "action": p.action }))).await + } + + #[tool( + description = "Requests to join the forum's restricted topics, waiting for a decision.", + annotations(title = "Fórum: csatlakozási kérések", read_only_hint = true) + )] + async fn forum_topic_requests(&self, Extension(parts): Extension) -> ToolResult { + self.get(&parts, "/forum/mod/topic-requests", vec![]).await + } + + #[tool( + description = "Decides a request to join a restricted topic (approve or reject), or removes a member from it.", + annotations(title = "Fórum: kérés elbírálása", read_only_hint = false, destructive_hint = false) + )] + async fn forum_decide_topic_request( + &self, + Extension(parts): Extension, + Parameters(p): Parameters, + ) -> ToolResult { + let body = json!({ "topic": p.topic, "nickname": p.nickname, "action": p.action }); + self.run(&parts, Method::POST, "/forum/mod/topic-requests", vec![], Some(body)).await + } + + #[tool( + description = "The forum's moderation log: who removed, banned or closed what, and why.", + annotations(title = "Fórum: moderálási napló", read_only_hint = true) + )] + async fn forum_mod_log(&self, Extension(parts): Extension) -> ToolResult { + self.get(&parts, "/forum/mod/log", vec![]).await + } + + #[tool( + description = "A forum thread with its posts (removed ones too, for moderators).", + annotations(title = "Fórum: szál", read_only_hint = true) + )] + async fn forum_get_thread( + &self, + Extension(parts): Extension, + Parameters(p): Parameters, + ) -> ToolResult { + self.get(&parts, &format!("/forum/threads/{}", p.id), vec![]).await + } + + #[tool( + description = "Bans a forum member from writing, for some hours or for good; they get an e-mail with the \ + reason. Moderators and admins cannot be banned.", + annotations(title = "Fórum: kitiltás", read_only_hint = false, destructive_hint = true) + )] + async fn forum_ban(&self, Extension(parts): Extension, Parameters(p): Parameters) -> ToolResult { + let path = format!("/forum/members/{}/ban", segment(&p.nickname)); + self.run(&parts, Method::POST, &path, vec![], Some(json!({ "hours": p.hours, "reason": p.reason }))).await + } + + #[tool( + description = "Lifts a forum member's ban.", + annotations(title = "Fórum: kitiltás feloldása", read_only_hint = false, destructive_hint = false) + )] + async fn forum_unban( + &self, + Extension(parts): Extension, + Parameters(p): Parameters, + ) -> ToolResult { + let path = format!("/forum/members/{}/ban", segment(&p.nickname)); + self.run(&parts, Method::DELETE, &path, vec![], None).await + } +} + +#[tool_handler( + name = "sorsfonalak", + instructions = "Admin tools of sorsfonalak.hu, a Hungarian astrology site (birth charts, AI-written \ + analyses, a weekly horoscope, a forum). Members' e-mail addresses and names are masked. \ + Money is in HUF, AI cost in USD. Writes are limited to the daily tasks; anything else is \ + done on the site's admin pages." +)] +impl ServerHandler for Tools {} diff --git a/services/worker/src/cleanup.rs b/services/worker/src/cleanup.rs index 644a765..f52897b 100644 --- a/services/worker/src/cleanup.rs +++ b/services/worker/src/cleanup.rs @@ -8,7 +8,7 @@ use tokio::sync::watch; const INTERVAL: Duration = Duration::from_secs(3600); /// (what, statement) pairs; each returns the number of deleted rows. -const STATEMENTS: [(&str, &str); 16] = [ +const STATEMENTS: [(&str, &str); 20] = [ ("sessions", "DELETE FROM sessions WHERE expires_at < now()"), ("auth_tokens", "DELETE FROM auth_tokens WHERE expires_at < now()"), // Sent e-mails contain links with tokens; keep them a week for support. @@ -60,6 +60,21 @@ const STATEMENTS: [(&str, &str); 16] = [ "DELETE FROM forum.conversations WHERE status IN ('pending', 'declined') AND last_message_at IS NULL \ AND coalesce(responded_at, created_at) < now() - interval '90 days'", ), + // MCP clients (docs/mcp.md): codes and tokens past their time, connections + // revoked a month ago or with no token left, and clients a month without + // a connection (a client registered but never approved, or long revoked). + ("oauth_codes", "DELETE FROM oauth_codes WHERE expires_at < now() - interval '1 day'"), + ("oauth_tokens", "DELETE FROM oauth_tokens WHERE refresh_expires_at < now()"), + ( + "oauth_grants", + "DELETE FROM oauth_grants g WHERE g.revoked_at < now() - interval '30 days' \ + OR NOT EXISTS (SELECT 1 FROM oauth_tokens t WHERE t.grant_id = g.id)", + ), + ( + "oauth_clients", + "DELETE FROM oauth_clients c WHERE c.created_at < now() - interval '30 days' \ + AND NOT EXISTS (SELECT 1 FROM oauth_grants g WHERE g.client_id = c.id)", + ), ]; pub async fn run_once(db: &PgPool) -> Result, sqlx::Error> { diff --git a/services/worker/src/tests.rs b/services/worker/src/tests.rs index cdf4109..a32be3c 100644 --- a/services/worker/src/tests.rs +++ b/services/worker/src/tests.rs @@ -281,6 +281,10 @@ async fn cleanup_removes_only_expired_data(db: PgPool) { ("forum_mod_log", 0), ("forum_bans", 0), ("forum_requests", 0), + ("oauth_codes", 0), + ("oauth_tokens", 0), + ("oauth_grants", 0), + ("oauth_clients", 0), ] ); let kept: Vec = sqlx::query_scalar("SELECT id FROM gifts ORDER BY id").fetch_all(&db).await.unwrap(); @@ -1351,3 +1355,53 @@ async fn monday_weekly_horoscope_emails_go_once_a_week(db: PgPool) { let next = monday.saturating_add(time::Duration::days(7)); assert_eq!(crate::weekly::queue_week(&db, "https://sorsfonalak.test", next).await.unwrap(), 1); } + +#[sqlx::test(migrator = "db::MIGRATOR")] +async fn cleanup_ends_old_mcp_connections(db: PgPool) { + let user = Uuid::now_v7(); + sqlx::query("INSERT INTO users (id, email, roles) VALUES ($1, 'admin@example.com', '{user,admin}')") + .bind(user) + .execute(&db) + .await + .unwrap(); + // Clients: one in use, one never approved for a month, one just registered. + sqlx::query( + "INSERT INTO oauth_clients (id, name, redirect_uris, created_at) VALUES \ + ('used', 'Claude', '{}', now() - interval '60 days'), \ + ('stale', 'Claude', '{}', now() - interval '31 days'), \ + ('fresh', 'Claude', '{}', now())", + ) + .execute(&db) + .await + .unwrap(); + // Connections: a live one, one whose refresh token ran out. + let (live, ended) = (Uuid::now_v7(), Uuid::now_v7()); + for (grant, refresh_expires) in [(live, "now() + interval '1 day'"), (ended, "now() - interval '1 second'")] { + sqlx::query("INSERT INTO oauth_grants (id, client_id, user_id, scope) VALUES ($1, 'used', $2, 'admin')") + .bind(grant) + .bind(user) + .execute(&db) + .await + .unwrap(); + sqlx::query(&format!( + "INSERT INTO oauth_tokens (id, grant_id, access_hash, access_expires_at, refresh_hash, refresh_expires_at) \ + VALUES ($1, $2, $3, now() - interval '1 hour', $4, {refresh_expires})" + )) + .bind(Uuid::now_v7()) + .bind(grant) + .bind(Uuid::now_v7().as_bytes().to_vec()) + .bind(Uuid::now_v7().as_bytes().to_vec()) + .execute(&db) + .await + .unwrap(); + } + + let deleted = crate::cleanup::run_once(&db).await.unwrap(); + let count = |what: &str| deleted.iter().find(|(w, _)| *w == what).unwrap().1; + assert_eq!((count("oauth_tokens"), count("oauth_grants"), count("oauth_clients")), (1, 1, 1)); + let grants: Vec = sqlx::query_scalar("SELECT id FROM oauth_grants").fetch_all(&db).await.unwrap(); + assert_eq!(grants, vec![live]); + let clients: Vec = + sqlx::query_scalar("SELECT id FROM oauth_clients ORDER BY id").fetch_all(&db).await.unwrap(); + assert_eq!(clients, vec!["fresh", "used"]); +}