From 5e4bd751aa17b3568f77362e9e3978881390af39 Mon Sep 17 00:00:00 2001 From: Felix Ableitner Date: Thu, 2 Jun 2022 13:17:12 +0200 Subject: [PATCH] Initial commit --- .drone.yml | 33 + .gitignore | 1 + .idea/.gitignore | 3 + .idea/activitypub-federation-rust.iml | 14 + .idea/modules.xml | 8 + .idea/vcs.xml | 6 + .rustfmt.toml | 4 + Cargo.lock | 2017 +++++++++++++++++ Cargo.toml | 40 + LICENSE | 661 ++++++ README.md | 32 + derive/Cargo.toml | 18 + derive/src/lib.rs | 137 ++ examples/federation/activities/accept.rs | 56 + examples/federation/activities/create_note.rs | 70 + examples/federation/activities/follow.rs | 84 + examples/federation/activities/mod.rs | 3 + examples/federation/error.rs | 23 + examples/federation/instance.rs | 124 + examples/federation/lib.rs | 13 + examples/federation/main.rs | 42 + examples/federation/objects/mod.rs | 2 + examples/federation/objects/note.rs | 93 + examples/federation/objects/person.rs | 193 ++ src/core/activity_queue.rs | 197 ++ src/core/inbox.rs | 51 + src/core/mod.rs | 4 + src/core/object_id.rs | 260 +++ src/core/signatures.rs | 124 + src/data.rs | 37 + src/deser/context.rs | 62 + src/deser/helpers.rs | 66 + src/deser/mod.rs | 3 + src/deser/values.rs | 61 + src/lib.rs | 101 + src/main.rs | 3 + src/traits.rs | 91 + src/utils.rs | 51 + 38 files changed, 4788 insertions(+) create mode 100644 .drone.yml create mode 100644 .gitignore create mode 100644 .idea/.gitignore create mode 100644 .idea/activitypub-federation-rust.iml create mode 100644 .idea/modules.xml create mode 100644 .idea/vcs.xml create mode 100644 .rustfmt.toml create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 LICENSE create mode 100644 README.md create mode 100644 derive/Cargo.toml create mode 100644 derive/src/lib.rs create mode 100644 examples/federation/activities/accept.rs create mode 100644 examples/federation/activities/create_note.rs create mode 100644 examples/federation/activities/follow.rs create mode 100644 examples/federation/activities/mod.rs create mode 100644 examples/federation/error.rs create mode 100644 examples/federation/instance.rs create mode 100644 examples/federation/lib.rs create mode 100644 examples/federation/main.rs create mode 100644 examples/federation/objects/mod.rs create mode 100644 examples/federation/objects/note.rs create mode 100644 examples/federation/objects/person.rs create mode 100644 src/core/activity_queue.rs create mode 100644 src/core/inbox.rs create mode 100644 src/core/mod.rs create mode 100644 src/core/object_id.rs create mode 100644 src/core/signatures.rs create mode 100644 src/data.rs create mode 100644 src/deser/context.rs create mode 100644 src/deser/helpers.rs create mode 100644 src/deser/mod.rs create mode 100644 src/deser/values.rs create mode 100644 src/lib.rs create mode 100644 src/main.rs create mode 100644 src/traits.rs create mode 100644 src/utils.rs diff --git a/.drone.yml b/.drone.yml new file mode 100644 index 0000000..f29528e --- /dev/null +++ b/.drone.yml @@ -0,0 +1,33 @@ +--- +kind: pipeline +name: amd64 + +platform: + os: linux + arch: amd64 + +steps: + + - name: cargo fmt + image: rustdocker/rust:nightly + commands: + - /root/.cargo/bin/cargo fmt -- --check + + - name: cargo check + image: clux/muslrust:1.59.0 + commands: + - cargo check + + - name: cargo clippy + image: clux/muslrust:1.59.0 + commands: + - rustup component add clippy + - cargo clippy --workspace --tests --all-targets --all-features -- -D warnings -D deprecated -D clippy::perf -D clippy::complexity -D clippy::dbg_macro + - cargo clippy --workspace -- -D clippy::unwrap_used + + - name: cargo test + image: clux/muslrust:1.59.0 + environment: + RUST_BACKTRACE: 1 + commands: + - cargo test --workspace --no-fail-fast diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..26d3352 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,3 @@ +# Default ignored files +/shelf/ +/workspace.xml diff --git a/.idea/activitypub-federation-rust.iml b/.idea/activitypub-federation-rust.iml new file mode 100644 index 0000000..a7980b4 --- /dev/null +++ b/.idea/activitypub-federation-rust.iml @@ -0,0 +1,14 @@ + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/modules.xml b/.idea/modules.xml new file mode 100644 index 0000000..525db14 --- /dev/null +++ b/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/.rustfmt.toml b/.rustfmt.toml new file mode 100644 index 0000000..757db86 --- /dev/null +++ b/.rustfmt.toml @@ -0,0 +1,4 @@ +edition="2021" +imports_layout="HorizontalVertical" +imports_granularity="Crate" +reorder_imports=true diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..1af7659 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,2017 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "activitypub_federation" +version = "0.1.0" +dependencies = [ + "activitypub_federation_derive", + "activitystreams-kinds", + "actix-rt", + "actix-web", + "anyhow", + "async-trait", + "background-jobs", + "base64", + "chrono", + "derive_builder", + "env_logger", + "http", + "http-signature-normalization-actix", + "http-signature-normalization-reqwest", + "once_cell", + "openssl", + "rand", + "reqwest", + "reqwest-middleware", + "serde", + "serde_json", + "sha2", + "thiserror", + "tokio", + "tracing", + "url", +] + +[[package]] +name = "activitypub_federation_derive" +version = "0.1.0" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "trybuild", +] + +[[package]] +name = "activitystreams-kinds" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d014a4fb8828870b7b46bee6257b9a89d06188ae8d435381ba94f14c8c697d8" +dependencies = [ + "serde", + "url", +] + +[[package]] +name = "actix-codec" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57a7559404a7f3573127aab53c08ce37a6c6a315c374a31070f3c91cd1b4a7fe" +dependencies = [ + "bitflags", + "bytes", + "futures-core", + "futures-sink", + "log", + "memchr", + "pin-project-lite", + "tokio", + "tokio-util", +] + +[[package]] +name = "actix-http" +version = "3.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5885cb81a0d4d0d322864bea1bb6c2a8144626b4fdc625d4c51eba197e7797a" +dependencies = [ + "actix-codec", + "actix-rt", + "actix-service", + "actix-utils", + "ahash", + "base64", + "bitflags", + "bytes", + "bytestring", + "derive_more", + "encoding_rs", + "futures-core", + "h2", + "http", + "httparse", + "httpdate", + "itoa", + "language-tags", + "local-channel", + "log", + "mime", + "percent-encoding", + "pin-project-lite", + "rand", + "sha-1", + "smallvec", +] + +[[package]] +name = "actix-macros" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "465a6172cf69b960917811022d8f29bc0b7fa1398bc4f78b3c466673db1213b6" +dependencies = [ + "quote", + "syn", +] + +[[package]] +name = "actix-router" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb60846b52c118f2f04a56cc90880a274271c489b2498623d58176f8ca21fa80" +dependencies = [ + "bytestring", + "firestorm", + "http", + "log", + "regex", + "serde", +] + +[[package]] +name = "actix-rt" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ea16c295198e958ef31930a6ef37d0fb64e9ca3b6116e6b93a8bdae96ee1000" +dependencies = [ + "actix-macros", + "futures-core", + "tokio", +] + +[[package]] +name = "actix-server" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0da34f8e659ea1b077bb4637948b815cd3768ad5a188fdcd74ff4d84240cd824" +dependencies = [ + "actix-rt", + "actix-service", + "actix-utils", + "futures-core", + "futures-util", + "mio", + "num_cpus", + "socket2", + "tokio", + "tracing", +] + +[[package]] +name = "actix-service" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b894941f818cfdc7ccc4b9e60fa7e53b5042a2e8567270f9147d5591893373a" +dependencies = [ + "futures-core", + "paste", + "pin-project-lite", +] + +[[package]] +name = "actix-utils" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e491cbaac2e7fc788dfff99ff48ef317e23b3cf63dbaf7aaab6418f40f92aa94" +dependencies = [ + "local-waker", + "pin-project-lite", +] + +[[package]] +name = "actix-web" +version = "4.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4e5ebffd51d50df56a3ae0de0e59487340ca456f05dd0b90c0a7a6dd6a74d31" +dependencies = [ + "actix-codec", + "actix-http", + "actix-router", + "actix-rt", + "actix-server", + "actix-service", + "actix-utils", + "ahash", + "bytes", + "bytestring", + "cfg-if", + "derive_more", + "encoding_rs", + "futures-core", + "futures-util", + "itoa", + "language-tags", + "log", + "mime", + "once_cell", + "pin-project-lite", + "regex", + "serde", + "serde_json", + "serde_urlencoded", + "smallvec", + "socket2", + "time", + "url", +] + +[[package]] +name = "ahash" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47" +dependencies = [ + "getrandom", + "once_cell", + "version_check", +] + +[[package]] +name = "aho-corasick" +version = "0.7.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e37cfd5e7657ada45f742d6e99ca5788580b5c529dc78faf11ece6dc702656f" +dependencies = [ + "memchr", +] + +[[package]] +name = "anyhow" +version = "1.0.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08f9b8508dccb7687a1d6c4ce66b2b0ecef467c94667de27d8d7fe1f8d2a9cdc" + +[[package]] +name = "async-mutex" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479db852db25d9dbf6204e6cb6253698f175c15726470f78af0d918e99d6156e" +dependencies = [ + "event-listener", +] + +[[package]] +name = "async-trait" +version = "0.1.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed6aa3524a2dfcf9fe180c51eae2b58738348d819517ceadf95789c51fff7600" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "autocfg" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" + +[[package]] +name = "background-jobs" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c301b3ccb60fa2aadb4da111e27b257ddc4f0509848c43c85764dc14f7a49a3" +dependencies = [ + "background-jobs-actix", + "background-jobs-core", +] + +[[package]] +name = "background-jobs-actix" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65a0dcbc94e0644fcfbaddc19705fae2d6947426682aeab7582d772f4d80b8df" +dependencies = [ + "actix-rt", + "anyhow", + "async-mutex", + "async-trait", + "background-jobs-core", + "num_cpus", + "serde", + "serde_json", + "thiserror", + "tokio", + "tracing", + "tracing-futures", + "uuid", +] + +[[package]] +name = "background-jobs-core" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82fe510c99cea8b98c438e81f43c666e9b4cd3630a42a1684ed1d01db4271cfb" +dependencies = [ + "actix-rt", + "anyhow", + "async-mutex", + "async-trait", + "serde", + "serde_json", + "thiserror", + "time", + "tracing", + "tracing-futures", + "uuid", +] + +[[package]] +name = "base64" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "904dfeac50f3cdaba28fc6f57fdcddb75f49ed61346676a78c4ffe55877802fd" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "block-buffer" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf7fe51849ea569fd452f37822f606a5cabb684dc918707a0193fd4664ff324" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bumpalo" +version = "3.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37ccbd214614c6783386c1af30caf03192f17891059cecc394b4fb119e363de3" + +[[package]] +name = "bytes" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4872d67bab6358e59559027aa3b9157c53d9358c51423c17554809a8858e0f8" + +[[package]] +name = "bytestring" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90706ba19e97b90786e19dc0d5e2abd80008d99d4c0c5d1ad0b5e72cec7c494d" +dependencies = [ + "bytes", +] + +[[package]] +name = "cc" +version = "1.0.73" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "chrono" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "670ad68c9088c2a963aaa298cb369688cf3f9465ce5e2d4ca10e6e0098a1ce73" +dependencies = [ + "libc", + "num-integer", + "num-traits", + "winapi", +] + +[[package]] +name = "convert_case" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" + +[[package]] +name = "core-foundation" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "194a7a9e6de53fa55116934067c844d9d749312f75c6f6d0980e8c252f8c2146" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5827cebf4670468b8772dd191856768aedcb1b0278a04f989f7766351917b9dc" + +[[package]] +name = "cpufeatures" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59a6001667ab124aebae2a495118e11d30984c3a653e99d86d58971708cf5e4b" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57952ca27b5e3606ff4dd79b0020231aaf9d6aa76dc05fd30137538c50bd3ce8" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "darling" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4529658bdda7fd6769b8614be250cdcfc3aeb0ee72fe66f9e41e5e5eb73eac02" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "649c91bc01e8b1eac09fb91e8dbc7d517684ca6be8ebc75bb9cafc894f9fdb6f" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim", + "syn", +] + +[[package]] +name = "darling_macro" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddfc69c5bfcbd2fc09a0f38451d2daf0e372e367986a83906d1b0dbc88134fb5" +dependencies = [ + "darling_core", + "quote", + "syn", +] + +[[package]] +name = "derive_builder" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d07adf7be193b71cc36b193d0f5fe60b918a3a9db4dad0449f57bcfd519704a3" +dependencies = [ + "derive_builder_macro", +] + +[[package]] +name = "derive_builder_core" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f91d4cfa921f1c05904dc3c57b4a32c38aed3340cce209f3a6fd1478babafc4" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "derive_builder_macro" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f0314b72bed045f3a68671b3c86328386762c93f82d98c65c3cb5e5f573dd68" +dependencies = [ + "derive_builder_core", + "syn", +] + +[[package]] +name = "derive_more" +version = "0.99.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fb810d30a7c1953f91334de7244731fc3f3c10d7fe163338a35b9f640960321" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version", + "syn", +] + +[[package]] +name = "digest" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2fb860ca6fafa5552fb6d0e816a69c8e49f0908bf524e30a90d97c85892d506" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "dissimilar" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c97b9233581d84b8e1e689cdd3a47b6f69770084fc246e86a7f78b0d9c1d4a5" + +[[package]] +name = "encoding_rs" +version = "0.8.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9852635589dc9f9ea1b6fe9f05b50ef208c85c834a562f0c6abb1c475736ec2b" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "env_logger" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b2cf0344971ee6c64c31be0d530793fba457d322dfec2810c453d0ef228f9c3" +dependencies = [ + "log", +] + +[[package]] +name = "event-listener" +version = "2.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77f3309417938f28bf8228fcff79a4a37103981e3e186d2ccd19c74b38f4eb71" + +[[package]] +name = "fastrand" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3fcf0cee53519c866c09b5de1f6c56ff9d647101f81c1964fa632e148896cdf" +dependencies = [ + "instant", +] + +[[package]] +name = "firestorm" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c5f6c2c942da57e2aaaa84b8a521489486f14e75e7fa91dab70aba913975f98" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[package]] +name = "form_urlencoded" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fc25a87fa4fd2094bffb06925852034d90a17f0d1e05197d4956d3555752191" +dependencies = [ + "matches", + "percent-encoding", +] + +[[package]] +name = "futures" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f73fe65f54d1e12b726f517d3e2135ca3125a437b6d998caf1962961f7172d9e" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3083ce4b914124575708913bca19bfe887522d6e2e6d0952943f5eac4a74010" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c09fd04b7e4073ac7156a9539b57a484a8ea920f79c7c675d05d289ab6110d3" + +[[package]] +name = "futures-executor" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9420b90cfa29e327d0429f19be13e7ddb68fa1cccb09d65e5706b8c7a749b8a6" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc4045962a5a5e935ee2fdedaa4e08284547402885ab326734432bed5d12966b" + +[[package]] +name = "futures-macro" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33c1e13800337f4d4d7a316bf45a567dbcb6ffe087f16424852d97e97a91f512" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "futures-sink" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21163e139fa306126e6eedaf49ecdb4588f939600f0b1e770f4205ee4b7fa868" + +[[package]] +name = "futures-task" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c66a976bf5909d801bbef33416c41372779507e7a6b3a5e25e4749c58f776a" + +[[package]] +name = "futures-util" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b7abd5d659d9b90c8cba917f6ec750a74e2dc23902ef9cd4cc8c8b22e6036a" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "pin-utils", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd48d33ec7f05fbfa152300fdad764757cbded343c1aa1cff2fbaf4134851803" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9be70c98951c83b8d2f8f60d7065fa6d5146873094452a1008da8c2f1e4205ad" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.10.2+wasi-snapshot-preview1", +] + +[[package]] +name = "glob" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574" + +[[package]] +name = "h2" +version = "0.3.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37a82c6d637fc9515a4694bbf1cb2457b79d81ce52b3108bdeea58b07dd34a57" +dependencies = [ + "bytes", + "fnv", + "futures-core", + "futures-sink", + "futures-util", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" + +[[package]] +name = "hermit-abi" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" +dependencies = [ + "libc", +] + +[[package]] +name = "http" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff8670570af52249509a86f5e3e18a08c60b177071826898fde8997cf5f6bfbb" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + +[[package]] +name = "http-body" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5f38f16d184e36f2408a55281cd658ecbd3ca05cce6d6510a176eca393e26d1" +dependencies = [ + "bytes", + "http", + "pin-project-lite", +] + +[[package]] +name = "http-signature-normalization" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8f45adbef81d7ea3bd7e9bcc6734b7245dad05a14abdcc7ddc0988791d63515" +dependencies = [ + "httpdate", +] + +[[package]] +name = "http-signature-normalization-actix" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86dfd54a1764ad79376b8dbf29e5bf918a463eb5ec66c90cd0388508289af6f0" +dependencies = [ + "actix-http", + "actix-rt", + "actix-web", + "base64", + "futures-util", + "http-signature-normalization", + "sha2", + "thiserror", + "tokio", + "tracing", + "tracing-error", + "tracing-futures", +] + +[[package]] +name = "http-signature-normalization-reqwest" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a15d4498e747f1cb1b0114ad651619932eac790815d2dcef0fa89bd016fd991" +dependencies = [ + "base64", + "bytes", + "http", + "http-signature-normalization", + "reqwest", + "reqwest-middleware", + "sha2", + "thiserror", + "tokio", +] + +[[package]] +name = "httparse" +version = "1.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "496ce29bb5a52785b44e0f7ca2847ae0bb839c9bd28f69acac9b99d461c0c04c" + +[[package]] +name = "httpdate" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421" + +[[package]] +name = "hyper" +version = "0.14.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42dc3c131584288d375f2d07f822b0cb012d8c6fb899a5b9fdb3cb7eb9b6004f" +dependencies = [ + "bytes", + "futures-channel", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", + "want", +] + +[[package]] +name = "hyper-tls" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905" +dependencies = [ + "bytes", + "hyper", + "native-tls", + "tokio", + "tokio-native-tls", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[package]] +name = "idna" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "418a0a6fab821475f634efe3ccc45c013f742efe03d853e8d3355d5cb850ecf8" +dependencies = [ + "matches", + "unicode-bidi", + "unicode-normalization", +] + +[[package]] +name = "indexmap" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6012d540c5baa3589337a98ce73408de9b5a25ec9fc2c6fd6be8f0d39e0ca5a" +dependencies = [ + "autocfg", + "hashbrown", +] + +[[package]] +name = "instant" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "ipnet" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879d54834c8c76457ef4293a689b2a8c59b076067ad77b15efafbb05f92a592b" + +[[package]] +name = "itoa" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112c678d4050afce233f4f2852bb2eb519230b3cf12f33585275537d7e41578d" + +[[package]] +name = "js-sys" +version = "0.3.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "671a26f820db17c2a2750743f1dd03bafd15b98c9f30c7c2628c024c05d73397" +dependencies = [ + "wasm-bindgen", +] + +[[package]] +name = "language-tags" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4345964bb142484797b161f473a503a434de77149dd8c7427788c6e13379388" + +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" + +[[package]] +name = "libc" +version = "0.2.126" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "349d5a591cd28b49e1d1037471617a32ddcda5731b99419008085f72d5a53836" + +[[package]] +name = "local-channel" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f303ec0e94c6c54447f84f3b0ef7af769858a9c4ef56ef2a986d3dcd4c3fc9c" +dependencies = [ + "futures-core", + "futures-sink", + "futures-util", + "local-waker", +] + +[[package]] +name = "local-waker" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e34f76eb3611940e0e7d53a9aaa4e6a3151f69541a282fd0dad5571420c53ff1" + +[[package]] +name = "lock_api" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "327fa5b6a6940e4699ec49a9beae1ea4845c6bab9314e4f84ac68742139d8c53" +dependencies = [ + "autocfg", + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "matches" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3e378b66a060d48947b590737b30a1be76706c8dd7b8ba0f2fe3989c68a853f" + +[[package]] +name = "memchr" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" + +[[package]] +name = "mime" +version = "0.3.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d" + +[[package]] +name = "mime_guess" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4192263c238a5f0d0c6bfd21f336a313a4ce1c450542449ca191bb657b4642ef" +dependencies = [ + "mime", + "unicase", +] + +[[package]] +name = "mio" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "713d550d9b44d89174e066b7a6217ae06234c10cb47819a88290d2b353c31799" +dependencies = [ + "libc", + "log", + "wasi 0.11.0+wasi-snapshot-preview1", + "windows-sys", +] + +[[package]] +name = "native-tls" +version = "0.2.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd7e2f3618557f980e0b17e8856252eee3c97fa12c54dff0ca290fb6266ca4a9" +dependencies = [ + "lazy_static", + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + +[[package]] +name = "num-integer" +version = "0.1.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" +dependencies = [ + "autocfg", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_cpus" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "num_threads" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2819ce041d2ee131036f4fc9d6ae7ae125a3a40e97ba64d04fe799ad9dabbb44" +dependencies = [ + "libc", +] + +[[package]] +name = "once_cell" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7709cef83f0c1f58f666e746a08b21e0085f7440fa6a29cc194d68aac97a4225" + +[[package]] +name = "openssl" +version = "0.10.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb81a6430ac911acb25fe5ac8f1d2af1b4ea8a4fdfda0f1ee4292af2e2d8eb0e" +dependencies = [ + "bitflags", + "cfg-if", + "foreign-types", + "libc", + "once_cell", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b501e44f11665960c7e7fcf062c7d96a14ade4aa98116c004b2e37b5be7d736c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "openssl-probe" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" + +[[package]] +name = "openssl-sys" +version = "0.9.74" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "835363342df5fba8354c5b453325b110ffd54044e588c539cf2f20a8014e4cb1" +dependencies = [ + "autocfg", + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "parking_lot" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09a279cbf25cb0757810394fbc1e359949b59e348145c643a939a525692e6929" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-sys", +] + +[[package]] +name = "paste" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c520e05135d6e763148b6426a837e239041653ba7becd2e538c076c738025fc" + +[[package]] +name = "percent-encoding" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e" + +[[package]] +name = "pin-project" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58ad3879ad3baf4e44784bc6a718a8698867bb991f8ce24d1bcbe2cfb4c3a75e" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "744b6f092ba29c3650faf274db506afd39944f48420f6c86b17cfe0ee1cb36bb" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "pkg-config" +version = "0.3.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1df8c4ec4b0627e53bdf214615ad287367e482558cf84b109250b37464dc03ae" + +[[package]] +name = "ppv-lite86" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb9f9e6e233e5c4a35559a617bf40a4ec447db2e84c20b55a6f83167b7e57872" + +[[package]] +name = "proc-macro2" +version = "1.0.39" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c54b25569025b7fc9651de43004ae593a75ad88543b17178aa5e1b9c4f15f56f" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1feb54ed693b93a84e14094943b84b7c4eae204c512b7ccb95ab0c66d278ad1" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7" +dependencies = [ + "getrandom", +] + +[[package]] +name = "redox_syscall" +version = "0.2.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62f25bc4c7e55e0b0b7a1d43fb893f4fa1361d0abe38b9ce4f323c2adfe6ef42" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex" +version = "1.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83f127d94bdbcda4c8cc2e50f6f84f4b611f69c902699ca385a39c3a75f9ff1" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.6.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49b3de9ec5dc0a3417da371aab17d729997c15010e7fd24ff707773a33bddb64" + +[[package]] +name = "remove_dir_all" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7" +dependencies = [ + "winapi", +] + +[[package]] +name = "reqwest" +version = "0.11.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46a1f7aa4f35e5e8b4160449f51afc758f0ce6454315a9fa7d0d113e958c41eb" +dependencies = [ + "base64", + "bytes", + "encoding_rs", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "hyper", + "hyper-tls", + "ipnet", + "js-sys", + "lazy_static", + "log", + "mime", + "mime_guess", + "native-tls", + "percent-encoding", + "pin-project-lite", + "serde", + "serde_json", + "serde_urlencoded", + "tokio", + "tokio-native-tls", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "winreg", +] + +[[package]] +name = "reqwest-middleware" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69539cea4148dce683bec9dc95be3f0397a9bb2c248a49c8296a9d21659a8cdd" +dependencies = [ + "anyhow", + "async-trait", + "futures", + "http", + "reqwest", + "serde", + "task-local-extensions", + "thiserror", +] + +[[package]] +name = "rustc_version" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" +dependencies = [ + "semver", +] + +[[package]] +name = "ryu" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3f6f92acf49d1b98f7a81226834412ada05458b7364277387724a237f062695" + +[[package]] +name = "schannel" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88d6731146462ea25d9244b2ed5fd1d716d25c52e4d54aa4fb0f3c4e9854dbe2" +dependencies = [ + "lazy_static", + "windows-sys", +] + +[[package]] +name = "scopeguard" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" + +[[package]] +name = "security-framework" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dc14f172faf8a0194a3aded622712b0de276821addc574fa54fc0a1167e10dc" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0160a13a177a45bfb43ce71c01580998474f556ad854dcbca936dd2841a5c556" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cb243bdfdb5936c8dc3c45762a19d12ab4550cdc753bc247637d4ec35a040fd" + +[[package]] +name = "serde" +version = "1.0.137" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ea8d54c77f8315140a05f4c7237403bf38b72704d031543aa1d16abbf517d1" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.137" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f26faba0c3959972377d3b2d306ee9f71faee9714294e41bb777f83f88578be" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b7ce2b32a1aed03c558dc61a5cd328f15aff2dbc17daad8fb8af04d2100e15c" +dependencies = [ + "indexmap", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha-1" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "028f48d513f9678cda28f6e4064755b3fbb2af6acd672f2c209b62323f7aea0f" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sha2" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55deaec60f81eefe3cce0dc50bda92d6d8e88f2a27df7c5033b42afeb1ed2676" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "900fba806f70c630b0a382d0d825e17a0f19fcd059a2ade1ff237bcddf446b31" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e51e73328dc4ac0c7ccbda3a494dfa03df1de2f46018127f60c693f2648455b0" +dependencies = [ + "libc", +] + +[[package]] +name = "slab" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb703cfe953bccee95685111adeedb76fabe4e97549a58d16f03ea7b9367bb32" + +[[package]] +name = "smallvec" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2dd574626839106c320a323308629dcb1acfc96e32a8cba364ddc61ac23ee83" + +[[package]] +name = "socket2" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66d72b759436ae32898a2af0a14218dbf55efde3feeb170eb623637db85ee1e0" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "strsim" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" + +[[package]] +name = "syn" +version = "1.0.95" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbaf6116ab8924f39d52792136fb74fd60a80194cf1b1c6ffa6453eef1c3f942" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "task-local-extensions" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36794203e10c86e5998179e260869d156e0674f02d5451b4a3fb9fd86d02aaab" +dependencies = [ + "tokio", +] + +[[package]] +name = "tempfile" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cdb1ef4eaeeaddc8fbd371e5017057064af0911902ef36b39801f67cc6d79e4" +dependencies = [ + "cfg-if", + "fastrand", + "libc", + "redox_syscall", + "remove_dir_all", + "winapi", +] + +[[package]] +name = "termcolor" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "thiserror" +version = "1.0.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd829fe32373d27f76265620b5309d0340cb8550f523c1dda251d6298069069a" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0396bc89e626244658bef819e22d0cc459e795a5ebe878e6ec336d1674a8d79a" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "thread_local" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5516c27b78311c50bf42c071425c560ac799b11c30b31f87e3081965fe5e0180" +dependencies = [ + "once_cell", +] + +[[package]] +name = "time" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2702e08a7a860f005826c6815dcac101b19b5eb330c27fe4a5928fec1d20ddd" +dependencies = [ + "itoa", + "libc", + "num_threads", + "serde", +] + +[[package]] +name = "tinyvec" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" + +[[package]] +name = "tokio" +version = "1.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4903bf0427cf68dddd5aa6a93220756f8be0c34fcfa9f5e6191e103e15a31395" +dependencies = [ + "bytes", + "libc", + "memchr", + "mio", + "once_cell", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "winapi", +] + +[[package]] +name = "tokio-macros" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b557f72f448c511a979e2564e55d74e6c4432fc96ff4f6241bc6bded342643b7" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio-native-tls" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7d995660bd2b7f8c1568414c1126076c13fbb725c40112dc0120b78eb9b717b" +dependencies = [ + "native-tls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f988a1a1adc2fb21f9c12aa96441da33a1728193ae0b95d2be22dbd17fcb4e5c" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", + "tracing", +] + +[[package]] +name = "toml" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7" +dependencies = [ + "serde", +] + +[[package]] +name = "tower-service" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "360dfd1d6d30e05fda32ace2c8c70e9c0a9da713275777f5a4dbb8a1893930c6" + +[[package]] +name = "tracing" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0ecdcb44a79f0fe9844f0c4f33a342cbcbb5117de8001e6ba0dc2351327d09" +dependencies = [ + "cfg-if", + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc6b8ad3567499f98a1db7a752b07a7c8c7c7c34c332ec00effb2b0027974b7c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tracing-core" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f54c8ca710e81886d498c2fd3331b56c93aa248d49de2222ad2742247c60072f" +dependencies = [ + "lazy_static", + "valuable", +] + +[[package]] +name = "tracing-error" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d686ec1c0f384b1277f097b2f279a2ecc11afe8c133c1aabf036a27cb4cd206e" +dependencies = [ + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "tracing-futures" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97d095ae15e245a057c8e8451bab9b3ee1e1f68e9ba2b4fbc18d0ac5237835f2" +dependencies = [ + "pin-project", + "tracing", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bc28f93baff38037f64e6f43d34cfa1605f27a49c34e8a04c5e78b0babf2596" +dependencies = [ + "sharded-slab", + "thread_local", + "tracing-core", +] + +[[package]] +name = "try-lock" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642" + +[[package]] +name = "trybuild" +version = "1.0.61" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fc92f558afb6d1d7c6f175eb8d615b8ef49c227543e68e19c123d4ee43d8a7d" +dependencies = [ + "dissimilar", + "glob", + "once_cell", + "serde", + "serde_derive", + "serde_json", + "termcolor", + "toml", +] + +[[package]] +name = "typenum" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987" + +[[package]] +name = "unicase" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6" +dependencies = [ + "version_check", +] + +[[package]] +name = "unicode-bidi" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "099b7128301d285f79ddd55b9a83d5e6b9e97c92e0ea0daebee7263e932de992" + +[[package]] +name = "unicode-ident" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d22af068fba1eb5edcb4aea19d382b2a3deb4c8f9d475c589b6ada9e0fd493ee" + +[[package]] +name = "unicode-normalization" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d54590932941a9e9266f0832deed84ebe1bf2e4c9e4a3554d393d18f5e854bf9" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "url" +version = "2.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a507c383b2d33b5fc35d1861e77e6b383d158b2da5e14fe51b83dfedf6fd578c" +dependencies = [ + "form_urlencoded", + "idna", + "matches", + "percent-encoding", + "serde", +] + +[[package]] +name = "uuid" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc5cf98d8186244414c848017f0e2676b3fcb46807f6668a97dfe67359a3c4b7" +dependencies = [ + "getrandom", + "serde", +] + +[[package]] +name = "valuable" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "830b7e5d4d90034032940e4ace0d9a9a057e7a45cd94e6c007832e39edb82f6d" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" + +[[package]] +name = "want" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ce8a968cb1cd110d136ff8b819a556d6fb6d919363c61534f6860c7eb172ba0" +dependencies = [ + "log", + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.10.2+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd6fbd9a79829dd1ad0cc20627bf1ed606756a7f77edff7b66b7064f9cb327c6" + +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" + +[[package]] +name = "wasm-bindgen" +version = "0.2.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27370197c907c55e3f1a9fbe26f44e937fe6451368324e009cba39e139dc08ad" +dependencies = [ + "cfg-if", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53e04185bfa3a779273da532f5025e33398409573f348985af9a1cbf3774d3f4" +dependencies = [ + "bumpalo", + "lazy_static", + "log", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f741de44b75e14c35df886aff5f1eb73aa114fa5d4d00dcd37b5e01259bf3b2" +dependencies = [ + "cfg-if", + "js-sys", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17cae7ff784d7e83a2fe7611cfe766ecf034111b49deb850a3dc7699c08251f5" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99ec0dc7a4756fffc231aab1b9f2f578d23cd391390ab27f952ae0c9b3ece20b" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d554b7f530dee5964d9a9468d95c1f8b8acae4f282807e7d27d4b03099a46744" + +[[package]] +name = "web-sys" +version = "0.3.57" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b17e741662c70c8bd24ac5c5b18de314a2c26c32bf8346ee1e6f53de919c283" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" +dependencies = [ + "winapi", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-sys" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea04155a16a59f9eab786fe12a4a450e75cdb175f9e0d80da1e17db09f55b8d2" +dependencies = [ + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_msvc" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb8c3fd39ade2d67e9874ac4f3db21f0d710bee00fe7cab16949ec184eeaa47" + +[[package]] +name = "windows_i686_gnu" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180e6ccf01daf4c426b846dfc66db1fc518f074baa793aa7d9b9aaeffad6a3b6" + +[[package]] +name = "windows_i686_msvc" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2e7917148b2812d1eeafaeb22a97e4813dfa60a3f8f78ebe204bcc88f12f024" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd171b8776c41b97521e5da127a2d86ad280114807d0b2ab1e462bc764d9e1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c811ca4a8c853ef420abd8592ba53ddbbac90410fab6903b3e79972a631f7680" + +[[package]] +name = "winreg" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80d0f4e272c85def139476380b12f9ac60926689dd2e01d4923222f40580869d" +dependencies = [ + "winapi", +] diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..4dd620b --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,40 @@ +[package] +name = "activitypub_federation" +version = "0.1.0" +edition = "2021" +description = "High-level Activitypub framework" +license = "AGPL-3.0" +repository = "https://github.com/LemmyNet/activitypub-federation-rust" + +[workspace] +members = ["derive"] + +[dependencies] +activitypub_federation_derive = { version = "0.1.0", path = "derive" } +chrono = { version = "0.4.19", features = ["clock"], default-features = false } +serde = { version = "1.0.136", features = ["derive"] } +async-trait = "0.1.53" +url = { version = "2.2.2", features = ["serde"] } +serde_json = { version = "1.0.79", features = ["preserve_order"] } +anyhow = "1.0.56" +reqwest = { version = "0.11.10", features = ["json"] } +reqwest-middleware = "0.1.5" +tracing = "0.1.32" +base64 = "0.13.0" +openssl = "0.10.38" +once_cell = "1.10.0" +http = "0.2.6" +sha2 = "0.10.2" +actix-web = { version = "4.0.1", default-features = false } +http-signature-normalization-actix = { version = "0.6.1", default-features = false, features = ["server", "sha-2"] } +http-signature-normalization-reqwest = { version = "0.5.0", default-features = false, features = ["sha-2", "middleware"] } +background-jobs = "0.12.0" +thiserror = "1.0.31" +derive_builder = "0.11.2" + +[dev-dependencies] +activitystreams-kinds = "0.2.1" +rand = "0.8.5" +actix-rt = "2.7.0" +tokio = "1.18.2" +env_logger = { version = "0.9.0", default-features = false } diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0ad25db --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..d103acf --- /dev/null +++ b/README.md @@ -0,0 +1,32 @@ +Activitypub-Federation +=== + +A high-level framework for [ActivityPub](https://www.w3.org/TR/activitypub/) federation in Rust, extracted from [Lemmy](https://join-lemmy.org/). The goal is that this library can take care of almost everything related to federation for different projects, but for now it is still far away from that goal. + +## Features + +- ObjectId type, wraps the `id` url and allows for type safe fetching of objects, both from database and HTTP +- Queue for activity sending, handles HTTP signatures, retry with exponential backoff, all in background workers +- Inbox for receiving activities, verifies HTTP signatures, performs other basic checks and helps with routing +- Generic error type (unfortunately this was necessary) +- various helpers for verification, (de)serialization, context etc + +## Roadmap + +Things to work on in the future: +- **Simplify generics**: The library uses a lot of generic parameters, where clauses and associated types. It should be possible to simplify them. +- **Improve macro**: The macro is implemented very badly and doesn't have any error handling. +- **Generate HTTP endpoints**: It would be possible to generate HTTP endpoints automatically for each actor. +- **Support for other web frameworks**: Can be implemented using feature flags if other projects require it. +- **Signed fetch**: JSON can only be fetched by authenticated actors, which means that fetches from blocked instances can also be blocked. In combination with the previous point, this could be handled entirely in the library. +- **Helpers for testing**: Lemmy has a pretty useful test suite which (de)serializes json from other projects, to ensure that federation remains compatible. Helpers for this could be added to the library. +- **[Webfinger](https://datatracker.ietf.org/doc/html/rfc7033) support**: Not part of the Activitypub standard, but often used together for user discovery. +- **Remove request_counter from API**: It should be handled internally and not exposed. Maybe as part of `Data` struct. + +## How to use + +To get started, have a look at the example. If anything is unclear, please open an issue for clarification. You can also look at [Lemmy code](https://github.com/LemmyNet/lemmy/tree/main/crates/apub) for a more advanced implementation. + +## License + +Licensed under [AGPLv3](LICENSE). diff --git a/derive/Cargo.toml b/derive/Cargo.toml new file mode 100644 index 0000000..a53bc55 --- /dev/null +++ b/derive/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "activitypub_federation_derive" +version = "0.1.0" +edition = "2021" +description = "High-level Activitypub framework" +license = "AGPL-3.0" +repository = "https://github.com/LemmyNet/activitypub-federation-rust" + +[lib] +proc-macro = true + +[dev-dependencies] +trybuild = { version = "1.0.57", features = ["diff"] } + +[dependencies] +proc-macro2 = "1.0.36" +syn = "1.0.90" +quote = "1.0.17" diff --git a/derive/src/lib.rs b/derive/src/lib.rs new file mode 100644 index 0000000..af27264 --- /dev/null +++ b/derive/src/lib.rs @@ -0,0 +1,137 @@ +use proc_macro2::TokenStream; +use quote::quote; +use syn::{parse_macro_input, Data, DeriveInput, Fields::Unnamed, Ident, Variant}; + +/// Generates implementation ActivityHandler for an enum, which looks like the following (handling +/// all enum variants). +/// +/// Based on this code: +/// ```ignore +/// #[derive(serde::Deserialize, serde::Serialize)] +/// #[serde(untagged)] +/// #[activity_handler(LemmyContext, LemmyError)] +/// pub enum PersonInboxActivities { +/// CreateNote(CreateNote), +/// UpdateNote(UpdateNote), +/// } +/// ``` +/// It will generate this: +/// ```ignore +/// impl ActivityHandler for PersonInboxActivities { +/// type DataType = LemmyContext; +/// type Error = LemmyError; +/// +/// async fn verify( +/// &self, +/// data: &Self::DataType, +/// request_counter: &mut i32, +/// ) -> Result<(), Self::Error> { +/// match self { +/// PersonInboxActivities::CreateNote(a) => a.verify(data, request_counter).await, +/// PersonInboxActivities::UpdateNote(a) => a.verify(context, request_counter).await, +/// } +/// } +/// +/// async fn receive( +/// &self, +/// data: &Self::DataType, +/// request_counter: &mut i32, +/// ) -> Result<(), Self::Error> { +/// match self { +/// PersonInboxActivities::CreateNote(a) => a.receive(data, request_counter).await, +/// PersonInboxActivities::UpdateNote(a) => a.receive(data, request_counter).await, +/// } +/// } +/// ``` +#[proc_macro_attribute] +pub fn activity_handler( + attr: proc_macro::TokenStream, + input: proc_macro::TokenStream, +) -> proc_macro::TokenStream { + let derive_input = parse_macro_input!(input as DeriveInput); + let derive_input2 = derive_input.clone(); + let attr = proc_macro2::TokenStream::from(attr); + let mut attr = attr.into_iter(); + let data_type = attr.next().expect("data type input"); + let _delimiter = attr.next(); + let error = attr.next().expect("error type input"); + + let enum_name = derive_input2.ident; + + let (impl_generics, ty_generics, where_clause) = derive_input2.generics.split_for_impl(); + + let enum_variants = if let Data::Enum(d) = derive_input2.data { + d.variants + } else { + unimplemented!() + }; + + let impl_id = enum_variants + .iter() + .map(|v| generate_match_arm(&enum_name, v, "e! {a.id()})); + let impl_actor = enum_variants + .iter() + .map(|v| generate_match_arm(&enum_name, v, "e! {a.actor()})); + let body_verify = quote! {a.verify(context, request_counter).await}; + let impl_verify = enum_variants + .iter() + .map(|v| generate_match_arm(&enum_name, v, &body_verify)); + let body_receive = quote! {a.receive(context, request_counter).await}; + let impl_receive = enum_variants + .iter() + .map(|v| generate_match_arm(&enum_name, v, &body_receive)); + + let expanded = quote! { + #derive_input + #[async_trait::async_trait(?Send)] + impl #impl_generics activitypub_federation::traits::ActivityHandler for #enum_name #ty_generics #where_clause { + type DataType = #data_type; + type Error = #error; + fn id( + &self, + ) -> &Url { + match self { + #(#impl_id)* + } + } + fn actor( + &self, + ) -> &Url { + match self { + #(#impl_actor)* + } + } + async fn verify( + &self, + context: &activitypub_federation::data::Data, + request_counter: &mut i32, + ) -> Result<(), Self::Error> { + match self { + #(#impl_verify)* + } + } + async fn receive( + self, + context: &activitypub_federation::data::Data, + request_counter: &mut i32, + ) -> Result<(), Self::Error> { + match self { + #(#impl_receive)* + } + } + } + }; + expanded.into() +} + +fn generate_match_arm(enum_name: &Ident, variant: &Variant, body: &TokenStream) -> TokenStream { + let id = &variant.ident; + match &variant.fields { + Unnamed(_) => { + quote! { + #enum_name::#id(a) => #body, + } + } + _ => unimplemented!(), + } +} diff --git a/examples/federation/activities/accept.rs b/examples/federation/activities/accept.rs new file mode 100644 index 0000000..1b306b2 --- /dev/null +++ b/examples/federation/activities/accept.rs @@ -0,0 +1,56 @@ +use crate::{activities::follow::Follow, instance::InstanceHandle, objects::person::MyUser}; +use activitypub_federation::{core::object_id::ObjectId, data::Data, traits::ActivityHandler}; +use activitystreams_kinds::activity::AcceptType; +use serde::{Deserialize, Serialize}; +use url::Url; + +#[derive(Deserialize, Serialize, Debug)] +#[serde(rename_all = "camelCase")] +pub struct Accept { + actor: ObjectId, + object: Follow, + #[serde(rename = "type")] + kind: AcceptType, + id: Url, +} + +impl Accept { + pub fn new(actor: ObjectId, object: Follow, id: Url) -> Accept { + Accept { + actor, + object, + kind: Default::default(), + id, + } + } +} + +#[async_trait::async_trait(?Send)] +impl ActivityHandler for Accept { + type DataType = InstanceHandle; + type Error = crate::error::Error; + + fn id(&self) -> &Url { + &self.id + } + + fn actor(&self) -> &Url { + self.actor.inner() + } + + async fn verify( + &self, + _data: &Data, + _request_counter: &mut i32, + ) -> Result<(), Self::Error> { + Ok(()) + } + + async fn receive( + self, + _data: &Data, + _request_counter: &mut i32, + ) -> Result<(), Self::Error> { + Ok(()) + } +} diff --git a/examples/federation/activities/create_note.rs b/examples/federation/activities/create_note.rs new file mode 100644 index 0000000..b03327c --- /dev/null +++ b/examples/federation/activities/create_note.rs @@ -0,0 +1,70 @@ +use crate::{ + instance::InstanceHandle, + objects::{note::Note, person::MyUser}, + MyPost, +}; +use activitypub_federation::{ + core::object_id::ObjectId, + data::Data, + deser::helpers::deserialize_one_or_many, + traits::{ActivityHandler, ApubObject}, +}; +use activitystreams_kinds::activity::CreateType; +use serde::{Deserialize, Serialize}; +use url::Url; + +#[derive(Deserialize, Serialize, Debug)] +#[serde(rename_all = "camelCase")] +pub struct CreateNote { + pub(crate) actor: ObjectId, + #[serde(deserialize_with = "deserialize_one_or_many")] + pub(crate) to: Vec, + pub(crate) object: Note, + #[serde(rename = "type")] + pub(crate) kind: CreateType, + pub(crate) id: Url, +} + +impl CreateNote { + pub fn new(note: Note, id: Url) -> CreateNote { + CreateNote { + actor: note.attributed_to.clone(), + to: note.to.clone(), + object: note, + kind: CreateType::Create, + id, + } + } +} + +#[async_trait::async_trait(?Send)] +impl ActivityHandler for CreateNote { + type DataType = InstanceHandle; + type Error = crate::error::Error; + + fn id(&self) -> &Url { + &self.id + } + + fn actor(&self) -> &Url { + self.actor.inner() + } + + async fn verify( + &self, + data: &Data, + request_counter: &mut i32, + ) -> Result<(), Self::Error> { + MyPost::verify(&self.object, self.id(), data, request_counter).await?; + Ok(()) + } + + async fn receive( + self, + data: &Data, + request_counter: &mut i32, + ) -> Result<(), Self::Error> { + MyPost::from_apub(self.object, data, request_counter).await?; + Ok(()) + } +} diff --git a/examples/federation/activities/follow.rs b/examples/federation/activities/follow.rs new file mode 100644 index 0000000..bf99ceb --- /dev/null +++ b/examples/federation/activities/follow.rs @@ -0,0 +1,84 @@ +use crate::{ + activities::accept::Accept, + generate_object_id, + instance::InstanceHandle, + objects::person::MyUser, +}; +use activitypub_federation::{core::object_id::ObjectId, data::Data, traits::ActivityHandler}; +use activitystreams_kinds::activity::FollowType; +use anyhow::Error; +use serde::{Deserialize, Serialize}; +use url::Url; + +#[derive(Deserialize, Serialize, Clone, Debug)] +#[serde(rename_all = "camelCase")] +pub struct Follow { + pub(crate) actor: ObjectId, + pub(crate) object: ObjectId, + #[serde(rename = "type")] + kind: FollowType, + id: Url, +} + +impl Follow { + pub fn new(actor: ObjectId, object: ObjectId, id: Url) -> Follow { + Follow { + actor, + object, + kind: Default::default(), + id, + } + } +} + +#[async_trait::async_trait(?Send)] +impl ActivityHandler for Follow { + type DataType = InstanceHandle; + type Error = crate::error::Error; + + fn id(&self) -> &Url { + &self.id + } + + fn actor(&self) -> &Url { + self.actor.inner() + } + + async fn verify( + &self, + _data: &Data, + _request_counter: &mut i32, + ) -> Result<(), Self::Error> { + Ok(()) + } + + async fn receive( + self, + data: &Data, + request_counter: &mut i32, + ) -> Result<(), Self::Error> { + // add to followers + let mut users = data.users.lock().unwrap(); + let local_user = users.first_mut().unwrap(); + local_user.followers.push(self.actor.inner().clone()); + let local_user = local_user.clone(); + drop(users); + + // send back an accept + let follower = self + .actor + .dereference::(data, data.local_instance(), request_counter) + .await?; + let id = generate_object_id(data.local_instance().hostname())?; + let accept = Accept::new(local_user.ap_id.clone(), self, id.clone()); + local_user + .send( + id, + accept, + vec![follower.inbox.clone()], + data.local_instance(), + ) + .await?; + Ok(()) + } +} diff --git a/examples/federation/activities/mod.rs b/examples/federation/activities/mod.rs new file mode 100644 index 0000000..59d2fb0 --- /dev/null +++ b/examples/federation/activities/mod.rs @@ -0,0 +1,3 @@ +pub mod accept; +pub mod create_note; +pub mod follow; diff --git a/examples/federation/error.rs b/examples/federation/error.rs new file mode 100644 index 0000000..8e87a25 --- /dev/null +++ b/examples/federation/error.rs @@ -0,0 +1,23 @@ +use actix_web::ResponseError; +use std::fmt::{Display, Formatter}; + +/// Necessary because of this issue: https://github.com/actix/actix-web/issues/1711 +#[derive(Debug)] +pub struct Error(anyhow::Error); + +impl ResponseError for Error {} + +impl Display for Error { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + std::fmt::Display::fmt(&self.0, f) + } +} + +impl From for Error +where + T: Into, +{ + fn from(t: T) -> Self { + Error(t.into()) + } +} diff --git a/examples/federation/instance.rs b/examples/federation/instance.rs new file mode 100644 index 0000000..87ebf8e --- /dev/null +++ b/examples/federation/instance.rs @@ -0,0 +1,124 @@ +use crate::{ + error::Error, + generate_object_id, + objects::{ + note::MyPost, + person::{MyUser, PersonAcceptedActivities}, + }, +}; +use activitypub_federation::{ + core::{inbox::receive_activity, object_id::ObjectId, signatures::generate_actor_keypair}, + data::Data, + deser::context::WithContext, + traits::ApubObject, + InstanceSettingsBuilder, + LocalInstance, + APUB_JSON_CONTENT_TYPE, +}; +use actix_web::{web, App, HttpRequest, HttpResponse, HttpServer}; +use http_signature_normalization_actix::prelude::VerifyDigest; +use reqwest::Client; +use sha2::{Digest, Sha256}; +use std::{ + ops::Deref, + sync::{Arc, Mutex}, +}; +use tokio::task; +use url::Url; + +pub type InstanceHandle = Arc; + +pub struct Instance { + /// This holds all library data + local_instance: LocalInstance, + /// Our "database" which contains all known users (local and federated) + pub users: Mutex>, + /// Same, but for posts + pub posts: Mutex>, +} + +impl Instance { + pub fn new(hostname: String) -> Result { + let settings = InstanceSettingsBuilder::default() + .testing_send_sync(true) + .worker_count(1) + .build()?; + let local_instance = + LocalInstance::new(hostname.clone(), Client::default().into(), settings); + let local_user = MyUser::new(generate_object_id(&hostname)?, generate_actor_keypair()?); + let instance = Arc::new(Instance { + local_instance, + users: Mutex::new(vec![local_user]), + posts: Mutex::new(vec![]), + }); + Ok(instance) + } + + pub fn local_user(&self) -> MyUser { + self.users.lock().unwrap().first().cloned().unwrap() + } + + pub fn local_instance(&self) -> &LocalInstance { + &self.local_instance + } + + pub fn listen(instance: &InstanceHandle) -> Result<(), Error> { + let hostname = instance.local_instance.hostname(); + let instance = instance.clone(); + let server = HttpServer::new(move || { + App::new() + .app_data(web::Data::new(instance.clone())) + .route("/objects/{user_name}", web::get().to(http_get_user)) + .service( + web::scope("") + // Important: this ensures that the activity json matches the hashsum in signed + // HTTP header + // TODO: it would be possible to get rid of this by verifying hash in + // receive_activity() + .wrap(VerifyDigest::new(Sha256::new())) + // Just a single, global inbox for simplicity + .route("/inbox", web::post().to(http_post_user_inbox)), + ) + }) + .bind(hostname)? + .run(); + task::spawn(server); + Ok(()) + } +} + +/// Handles requests to fetch user json over HTTP +async fn http_get_user( + request: HttpRequest, + data: web::Data, +) -> Result { + let data: InstanceHandle = data.into_inner().deref().clone(); + let hostname: String = data.local_instance.hostname().to_string(); + let request_url = format!("http://{}{}", hostname, &request.uri().to_string()); + let url = Url::parse(&request_url)?; + let user = ObjectId::::new(url) + .dereference_local::(&data) + .await? + .into_apub(&data) + .await?; + Ok(HttpResponse::Ok() + .content_type(APUB_JSON_CONTENT_TYPE) + .json(WithContext::new_default(user))) +} + +/// Handles messages received in user inbox +async fn http_post_user_inbox( + request: HttpRequest, + payload: String, + data: web::Data, +) -> Result { + let data: InstanceHandle = data.into_inner().deref().clone(); + let activity = serde_json::from_str(&payload)?; + receive_activity::, MyUser, InstanceHandle, Error>( + request, + activity, + &data.clone().local_instance, + &Data::new(data), + ) + .await +} diff --git a/examples/federation/lib.rs b/examples/federation/lib.rs new file mode 100644 index 0000000..87c421e --- /dev/null +++ b/examples/federation/lib.rs @@ -0,0 +1,13 @@ +use rand::{distributions::Alphanumeric, thread_rng, Rng}; +use url::{ParseError, Url}; + +/// Just generate random url as object id. In a real project, you probably want to use +/// an url which contains the database id for easy retrieval (or store the random id in db). +pub fn generate_object_id(hostname: &str) -> Result { + let id: String = thread_rng() + .sample_iter(&Alphanumeric) + .take(7) + .map(char::from) + .collect(); + Url::parse(&format!("http://{}/objects/{}", hostname, id)) +} diff --git a/examples/federation/main.rs b/examples/federation/main.rs new file mode 100644 index 0000000..4e5f0f0 --- /dev/null +++ b/examples/federation/main.rs @@ -0,0 +1,42 @@ +use crate::{error::Error, instance::Instance, lib::generate_object_id, objects::note::MyPost}; +use tracing::log::LevelFilter; + +mod activities; +mod error; +mod instance; +mod lib; +mod objects; + +#[actix_rt::main] +async fn main() -> Result<(), Error> { + env_logger::builder() + .filter_level(LevelFilter::Debug) + .init(); + + let alpha = Instance::new("localhost:8001".to_string())?; + let beta = Instance::new("localhost:8002".to_string())?; + Instance::listen(&alpha)?; + Instance::listen(&beta)?; + + // alpha user follows beta user + alpha + .local_user() + .follow(&beta.local_user(), &alpha) + .await?; + // assert that follow worked correctly + assert_eq!( + beta.local_user().followers(), + &vec![alpha.local_user().ap_id.inner().clone()] + ); + + // beta sends a post to its followers + let sent_post = MyPost::new("hello world!".to_string(), beta.local_user().ap_id); + beta.local_user().post(sent_post.clone(), &beta).await?; + let received_post = alpha.posts.lock().unwrap().first().cloned().unwrap(); + + // assert that alpha received the post + assert_eq!(received_post.text, sent_post.text); + assert_eq!(received_post.ap_id.inner(), sent_post.ap_id.inner()); + assert_eq!(received_post.creator.inner(), sent_post.creator.inner()); + Ok(()) +} diff --git a/examples/federation/objects/mod.rs b/examples/federation/objects/mod.rs new file mode 100644 index 0000000..20b1a49 --- /dev/null +++ b/examples/federation/objects/mod.rs @@ -0,0 +1,2 @@ +pub mod note; +pub mod person; diff --git a/examples/federation/objects/note.rs b/examples/federation/objects/note.rs new file mode 100644 index 0000000..a988413 --- /dev/null +++ b/examples/federation/objects/note.rs @@ -0,0 +1,93 @@ +use crate::{generate_object_id, instance::InstanceHandle, objects::person::MyUser}; +use activitypub_federation::{ + core::object_id::ObjectId, + deser::helpers::deserialize_one_or_many, + traits::ApubObject, +}; +use activitystreams_kinds::{object::NoteType, public}; +use anyhow::Error; +use serde::{Deserialize, Serialize}; +use url::Url; + +#[derive(Clone, Debug)] +pub struct MyPost { + pub text: String, + pub ap_id: ObjectId, + pub creator: ObjectId, + pub local: bool, +} + +impl MyPost { + pub fn new(text: String, creator: ObjectId) -> MyPost { + MyPost { + text, + ap_id: ObjectId::new(generate_object_id(creator.inner().domain().unwrap()).unwrap()), + creator, + local: true, + } + } +} + +#[derive(Deserialize, Serialize, Debug)] +#[serde(rename_all = "camelCase")] +pub struct Note { + #[serde(rename = "type")] + kind: NoteType, + id: ObjectId, + pub(crate) attributed_to: ObjectId, + #[serde(deserialize_with = "deserialize_one_or_many")] + pub(crate) to: Vec, + content: String, +} + +#[async_trait::async_trait(?Send)] +impl ApubObject for MyPost { + type DataType = InstanceHandle; + type ApubType = Note; + type DbType = (); + type Error = crate::error::Error; + + async fn read_from_apub_id( + _object_id: Url, + _data: &Self::DataType, + ) -> Result, Self::Error> { + todo!() + } + + async fn into_apub(self, data: &Self::DataType) -> Result { + let creator = self.creator.dereference_local::(data).await?; + Ok(Note { + kind: Default::default(), + id: self.ap_id, + attributed_to: self.creator, + to: vec![public(), creator.followers_url()?], + content: self.text, + }) + } + + async fn verify( + _apub: &Self::ApubType, + _expected_domain: &Url, + _data: &Self::DataType, + _request_counter: &mut i32, + ) -> Result<(), Self::Error> { + Ok(()) + } + + async fn from_apub( + apub: Self::ApubType, + data: &Self::DataType, + _request_counter: &mut i32, + ) -> Result { + let post = MyPost { + text: apub.content, + ap_id: apub.id, + creator: apub.attributed_to, + local: false, + }; + + let mut lock = data.posts.lock().unwrap(); + lock.push(post.clone()); + Ok(post) + } +} diff --git a/examples/federation/objects/person.rs b/examples/federation/objects/person.rs new file mode 100644 index 0000000..ecc82a2 --- /dev/null +++ b/examples/federation/objects/person.rs @@ -0,0 +1,193 @@ +use crate::{ + activities::{accept::Accept, create_note::CreateNote, follow::Follow}, + error::Error, + instance::InstanceHandle, + lib::generate_object_id, + objects::note::MyPost, +}; +use activitypub_federation::{ + core::{ + activity_queue::SendActivity, + inbox::ActorPublicKey, + object_id::ObjectId, + signatures::{Keypair, PublicKey}, + }, + deser::context::WithContext, + traits::ApubObject, + LocalInstance, +}; +use activitypub_federation_derive::activity_handler; +use activitystreams_kinds::actor::PersonType; +use serde::{Deserialize, Serialize}; +use tracing::log::debug; +use url::Url; + +#[derive(Debug, Clone)] +pub struct MyUser { + pub ap_id: ObjectId, + pub inbox: Url, + // exists for all users (necessary to verify http signatures) + public_key: String, + // exists only for local users + private_key: Option, + pub followers: Vec, + pub local: bool, +} + +/// List of all activities which this actor can receive. +#[activity_handler(InstanceHandle, Error)] +#[derive(Deserialize, Serialize, Debug)] +#[serde(untagged)] +pub enum PersonAcceptedActivities { + Follow(Follow), + Accept(Accept), + CreateNote(CreateNote), +} + +impl MyUser { + pub fn new(ap_id: Url, keypair: Keypair) -> MyUser { + let mut inbox = ap_id.clone(); + inbox.set_path("/inbox"); + let ap_id = ObjectId::new(ap_id); + MyUser { + ap_id, + inbox, + public_key: keypair.public_key, + private_key: Some(keypair.private_key), + followers: vec![], + local: true, + } + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct Person { + #[serde(rename = "type")] + kind: PersonType, + id: ObjectId, + inbox: Url, + public_key: PublicKey, +} + +impl MyUser { + pub fn followers(&self) -> &Vec { + &self.followers + } + + pub fn followers_url(&self) -> Result { + Ok(Url::parse(&format!("{}/followers", self.ap_id.inner()))?) + } + + fn public_key(&self) -> PublicKey { + PublicKey::new_main_key(self.ap_id.clone().into_inner(), self.public_key.clone()) + } + + pub async fn follow(&self, other: &MyUser, instance: &InstanceHandle) -> Result<(), Error> { + let id = generate_object_id(instance.local_instance().hostname())?; + let follow = Follow::new(self.ap_id.clone(), other.ap_id.clone(), id.clone()); + self.send( + id, + follow, + vec![other.inbox.clone()], + instance.local_instance(), + ) + .await?; + Ok(()) + } + + pub async fn post(&self, post: MyPost, instance: &InstanceHandle) -> Result<(), Error> { + let id = generate_object_id(instance.local_instance().hostname())?; + let create = CreateNote::new(post.into_apub(instance).await?, id.clone()); + let mut inboxes = vec![]; + for f in self.followers.clone() { + let user: MyUser = ObjectId::new(f) + .dereference::(instance, instance.local_instance(), &mut 0) + .await?; + inboxes.push(user.inbox); + } + self.send(id, &create, inboxes, instance.local_instance()) + .await?; + Ok(()) + } + + pub(crate) async fn send( + &self, + activity_id: Url, + activity: Activity, + inboxes: Vec, + local_instance: &LocalInstance, + ) -> Result<(), Error> { + let serialized = serde_json::to_string_pretty(&WithContext::new_default(activity))?; + debug!("Sending activity: {}", &serialized); + SendActivity { + activity_id, + actor_public_key: self.public_key(), + actor_private_key: self.private_key.clone().expect("has private key"), + inboxes, + activity: serialized, + } + .send(local_instance) + .await?; + Ok(()) + } +} + +#[async_trait::async_trait(?Send)] +impl ApubObject for MyUser { + type DataType = InstanceHandle; + type ApubType = Person; + type DbType = MyUser; + type Error = crate::error::Error; + + async fn read_from_apub_id( + object_id: Url, + data: &Self::DataType, + ) -> Result, Self::Error> { + let users = data.users.lock().unwrap(); + let res = users + .clone() + .into_iter() + .find(|u| u.ap_id.inner() == &object_id); + Ok(res) + } + + async fn into_apub(self, _data: &Self::DataType) -> Result { + Ok(Person { + kind: Default::default(), + id: self.ap_id.clone(), + inbox: self.inbox.clone(), + public_key: self.public_key(), + }) + } + + async fn verify( + _apub: &Self::ApubType, + _expected_domain: &Url, + _data: &Self::DataType, + _request_counter: &mut i32, + ) -> Result<(), Self::Error> { + Ok(()) + } + + async fn from_apub( + apub: Self::ApubType, + _data: &Self::DataType, + _request_counter: &mut i32, + ) -> Result { + Ok(MyUser { + ap_id: apub.id, + inbox: apub.inbox, + public_key: apub.public_key.public_key_pem, + private_key: None, + followers: vec![], + local: false, + }) + } +} + +impl ActorPublicKey for MyUser { + fn public_key(&self) -> &str { + &self.public_key + } +} diff --git a/src/core/activity_queue.rs b/src/core/activity_queue.rs new file mode 100644 index 0000000..43460d2 --- /dev/null +++ b/src/core/activity_queue.rs @@ -0,0 +1,197 @@ +use crate::{ + core::signatures::{sign_request, PublicKey}, + Error, + LocalInstance, + APUB_JSON_CONTENT_TYPE, +}; +use anyhow::anyhow; +use background_jobs::{ + memory_storage::Storage, + ActixJob, + Backoff, + Manager, + MaxRetries, + WorkerConfig, +}; +use http::{header::HeaderName, HeaderMap, HeaderValue}; +use reqwest_middleware::ClientWithMiddleware; +use serde::{Deserialize, Serialize}; +use std::{fmt::Debug, future::Future, pin::Pin, time::Duration}; +use tracing::{info, warn}; +use url::Url; + +/// Necessary data for sending out an activity +#[derive(Debug)] +pub struct SendActivity { + /// Id of the sent activity, used for logging + pub activity_id: Url, + /// Public key and actor id of the sender + pub actor_public_key: PublicKey, + /// Signing key of sender for HTTP signatures + pub actor_private_key: String, + /// List of Activitypub inboxes that the activity gets delivered to + pub inboxes: Vec, + /// Activity json + pub activity: String, +} + +impl SendActivity { + /// Send out the given activity to all inboxes, automatically generating the HTTP signatures. By + /// default, sending is done on a background thread, and automatically retried on failure with + /// exponential backoff. + /// + /// For debugging or testing, you might want to set [[InstanceSettings.testing_send_sync]]. + pub async fn send(self, instance: &LocalInstance) -> Result<(), Error> { + let activity_queue = &instance.activity_queue; + for inbox in self.inboxes { + let message = SendActivityTask { + activity_id: self.activity_id.clone(), + inbox, + activity: self.activity.clone(), + public_key: self.actor_public_key.clone(), + private_key: self.actor_private_key.clone(), + }; + if instance.settings.testing_send_sync { + let res = + do_send(message, &instance.client, instance.settings.request_timeout).await; + // Don't fail on error, as we intentionally do some invalid actions in tests, to verify that + // they are rejected on the receiving side. These errors shouldn't bubble up to make the API + // call fail. This matches the behaviour in production. + if let Err(e) = res { + warn!("{}", e); + } + } else { + activity_queue.queue::(message).await?; + let stats = activity_queue.get_stats().await?; + info!( + "Activity queue stats: pending: {}, running: {}, dead (this hour): {}, complete (this hour): {}", + stats.pending, + stats.running, + stats.dead.this_hour(), + stats.complete.this_hour() + ); + } + } + + Ok(()) + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +struct SendActivityTask { + activity_id: Url, + inbox: Url, + activity: String, + public_key: PublicKey, + private_key: String, +} + +/// Signs the activity with the sending actor's key, and delivers to the given inbox. Also retries +/// if the delivery failed. +impl ActixJob for SendActivityTask { + type State = MyState; + type Future = Pin>>>; + const NAME: &'static str = "SendActivityTask"; + + /// With these params, retries are made at the following intervals: + /// 3s + /// 9s + /// 27s + /// 1m 21s + /// 4m 3s + /// 12m 9s + /// 36m 27s + /// 1h 49m 21s + /// 5h 28m 3s + /// 16h 24m 9s + const MAX_RETRIES: MaxRetries = MaxRetries::Count(10); + const BACKOFF: Backoff = Backoff::Exponential(3); + + fn run(self, state: Self::State) -> Self::Future { + Box::pin(async move { do_send(self, &state.client, state.timeout).await }) + } +} + +async fn do_send( + task: SendActivityTask, + client: &ClientWithMiddleware, + timeout: Duration, +) -> Result<(), anyhow::Error> { + info!("Sending {} to {}", task.activity_id, task.inbox); + let request_builder = client + .post(&task.inbox.to_string()) + .timeout(timeout) + .headers(generate_request_headers(&task.inbox)); + let request = sign_request( + request_builder, + task.activity.clone(), + task.public_key.clone(), + task.private_key.to_owned(), + ) + .await?; + let response = client.execute(request).await; + + match response { + Ok(o) => { + if o.status().is_success() { + Ok(()) + } else { + let status = o.status(); + let text = o.text().await.map_err(Error::conv)?; + + Err(anyhow!( + "Send {} to {} failed with status {}: {}", + task.activity_id, + task.inbox, + status, + text, + )) + } + } + Err(e) => Err(anyhow!( + "Failed to send activity {} to {}: {}", + &task.activity_id, + task.inbox, + e + )), + } +} + +fn generate_request_headers(inbox_url: &Url) -> HeaderMap { + let mut host = inbox_url.domain().expect("read inbox domain").to_string(); + if let Some(port) = inbox_url.port() { + host = format!("{}:{}", host, port); + } + + let mut headers = HeaderMap::new(); + headers.insert( + HeaderName::from_static("content-type"), + HeaderValue::from_static(APUB_JSON_CONTENT_TYPE), + ); + headers.insert( + HeaderName::from_static("host"), + HeaderValue::from_str(&host).expect("Hostname is valid"), + ); + headers +} + +pub(crate) fn create_activity_queue( + client: ClientWithMiddleware, + worker_count: u64, + timeout: Duration, +) -> Manager { + // Configure and start our workers + WorkerConfig::new_managed(Storage::new(), move |_| MyState { + client: client.clone(), + timeout, + }) + .register::() + .set_worker_count("default", worker_count) + .start() +} + +#[derive(Clone)] +struct MyState { + client: ClientWithMiddleware, + timeout: Duration, +} diff --git a/src/core/inbox.rs b/src/core/inbox.rs new file mode 100644 index 0000000..37dfe5f --- /dev/null +++ b/src/core/inbox.rs @@ -0,0 +1,51 @@ +use crate::{ + core::{object_id::ObjectId, signatures::verify_signature}, + data::Data, + traits::{ActivityHandler, ApubObject}, + utils::verify_domains_match, + Error, + LocalInstance, +}; +use actix_web::{HttpRequest, HttpResponse}; +use serde::de::DeserializeOwned; +use tracing::log::debug; + +pub trait ActorPublicKey { + /// Returns the actor's public key for verification of HTTP signatures + fn public_key(&self) -> &str; +} + +/// Receive an activity and perform some basic checks, including HTTP signature verification. +pub async fn receive_activity( + request: HttpRequest, + activity: Activity, + local_instance: &LocalInstance, + data: &Data, +) -> Result +where + Activity: ActivityHandler + DeserializeOwned + Send + 'static, + Actor: ApubObject + ActorPublicKey + Send + 'static, + for<'de2> ::ApubType: serde::Deserialize<'de2>, + E: From + From, +{ + verify_domains_match(activity.id(), activity.actor())?; + if local_instance.is_local_url(activity.id()) { + return Err(Error::UrlVerificationError("Activity was sent from local instance").into()); + } + + (local_instance.settings.verify_url_function)(activity.id()) + .map_err(Error::UrlVerificationError)?; + + let request_counter = &mut 0; + let actor = ObjectId::::new(activity.actor().clone()) + .dereference::(data, local_instance, request_counter) + .await?; + verify_signature(&request, actor.public_key())?; + + debug!("Verifying activity {}", activity.id().to_string()); + activity.verify(data, request_counter).await?; + + debug!("Receiving activity {}", activity.id().to_string()); + activity.receive(data, request_counter).await?; + Ok(HttpResponse::Ok().finish()) +} diff --git a/src/core/mod.rs b/src/core/mod.rs new file mode 100644 index 0000000..fa173b2 --- /dev/null +++ b/src/core/mod.rs @@ -0,0 +1,4 @@ +pub mod activity_queue; +pub mod inbox; +pub mod object_id; +pub mod signatures; diff --git a/src/core/object_id.rs b/src/core/object_id.rs new file mode 100644 index 0000000..8010bb7 --- /dev/null +++ b/src/core/object_id.rs @@ -0,0 +1,260 @@ +use crate::{traits::ApubObject, utils::fetch_object_http, Error, LocalInstance}; +use anyhow::anyhow; +use chrono::{Duration as ChronoDuration, NaiveDateTime, Utc}; +use serde::{Deserialize, Serialize}; +use std::{ + fmt::{Debug, Display, Formatter}, + marker::PhantomData, +}; +use url::Url; + +/// We store Url on the heap because it is quite large (88 bytes). +#[derive(Serialize, Deserialize, Debug)] +#[serde(transparent)] +pub struct ObjectId(Box, PhantomData) +where + Kind: ApubObject + Send + 'static, + for<'de2> ::ApubType: serde::Deserialize<'de2>; + +impl ObjectId +where + Kind: ApubObject + Send + 'static, + for<'de2> ::ApubType: serde::Deserialize<'de2>, +{ + pub fn new(url: T) -> Self + where + T: Into, + { + ObjectId(Box::new(url.into()), PhantomData::) + } + + pub fn inner(&self) -> &Url { + &self.0 + } + + pub fn into_inner(self) -> Url { + *self.0 + } + + /// Fetches an activitypub object, either from local database (if possible), or over http. + pub async fn dereference( + &self, + data: &::DataType, + instance: &LocalInstance, + request_counter: &mut i32, + ) -> Result::Error> + where + ::Error: From + From, + { + let db_object = self.dereference_from_db(data).await?; + + // if its a local object, only fetch it from the database and not over http + if instance.is_local_url(&self.0) { + return match db_object { + None => Err(Error::NotFound.into()), + Some(o) => Ok(o), + }; + } + + // object found in database + if let Some(object) = db_object { + // object is old and should be refetched + if let Some(last_refreshed_at) = object.last_refreshed_at() { + if should_refetch_object(last_refreshed_at) { + return self + .dereference_from_http(data, instance, request_counter, Some(object)) + .await; + } + } + Ok(object) + } + // object not found, need to fetch over http + else { + self.dereference_from_http(data, instance, request_counter, None) + .await + } + } + + /// Fetch an object from the local db. Instead of falling back to http, this throws an error if + /// the object is not found in the database. + pub async fn dereference_local( + &self, + data: &::DataType, + ) -> Result::Error> + where + ::Error: From, + { + let object = self.dereference_from_db(data).await?; + object.ok_or_else(|| Error::NotFound.into()) + } + + /// returning none means the object was not found in local db + async fn dereference_from_db( + &self, + data: &::DataType, + ) -> Result, ::Error> { + let id = self.0.clone(); + ApubObject::read_from_apub_id(*id, data).await + } + + async fn dereference_from_http( + &self, + data: &::DataType, + instance: &LocalInstance, + request_counter: &mut i32, + db_object: Option, + ) -> Result::Error> + where + ::Error: From + From, + { + let res = fetch_object_http(&self.0, instance, request_counter).await; + + if let Err(Error::ObjectDeleted) = &res { + if let Some(db_object) = db_object { + db_object.delete(data).await?; + } + return Err(anyhow!("Fetched remote object {} which was deleted", self).into()); + } + + let res2 = res?; + + Kind::verify(&res2, self.inner(), data, request_counter).await?; + Kind::from_apub(res2, data, request_counter).await + } +} + +/// Need to implement clone manually, to avoid requiring Kind to be Clone +impl Clone for ObjectId +where + Kind: ApubObject + Send + 'static, + for<'de2> ::ApubType: serde::Deserialize<'de2>, +{ + fn clone(&self) -> Self { + ObjectId(self.0.clone(), self.1) + } +} + +static ACTOR_REFETCH_INTERVAL_SECONDS: i64 = 24 * 60 * 60; +static ACTOR_REFETCH_INTERVAL_SECONDS_DEBUG: i64 = 20; + +/// Determines when a remote actor should be refetched from its instance. In release builds, this is +/// `ACTOR_REFETCH_INTERVAL_SECONDS` after the last refetch, in debug builds +/// `ACTOR_REFETCH_INTERVAL_SECONDS_DEBUG`. +/// +/// TODO it won't pick up new avatars, summaries etc until a day after. +/// Actors need an "update" activity pushed to other servers to fix this. +fn should_refetch_object(last_refreshed: NaiveDateTime) -> bool { + let update_interval = if cfg!(debug_assertions) { + // avoid infinite loop when fetching community outbox + ChronoDuration::seconds(ACTOR_REFETCH_INTERVAL_SECONDS_DEBUG) + } else { + ChronoDuration::seconds(ACTOR_REFETCH_INTERVAL_SECONDS) + }; + let refresh_limit = Utc::now().naive_utc() - update_interval; + last_refreshed.lt(&refresh_limit) +} + +impl Display for ObjectId +where + Kind: ApubObject + Send + 'static, + for<'de2> ::ApubType: serde::Deserialize<'de2>, +{ + #[allow(clippy::to_string_in_display)] + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + // Use to_string here because Url.display is not useful for us + write!(f, "{}", self.0) + } +} + +impl From> for Url +where + Kind: ApubObject + Send + 'static, + for<'de2> ::ApubType: serde::Deserialize<'de2>, +{ + fn from(id: ObjectId) -> Self { + *id.0 + } +} + +impl PartialEq for ObjectId +where + Kind: ApubObject + Send + 'static, + for<'de2> ::ApubType: serde::Deserialize<'de2>, +{ + fn eq(&self, other: &Self) -> bool { + self.0.eq(&other.0) && self.1 == other.1 + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::core::object_id::should_refetch_object; + use anyhow::Error; + + #[derive(Debug)] + struct TestObject {} + + #[async_trait::async_trait(?Send)] + impl ApubObject for TestObject { + type DataType = TestObject; + type ApubType = (); + type DbType = (); + type Error = Error; + + async fn read_from_apub_id( + _object_id: Url, + _data: &Self::DataType, + ) -> Result, Self::Error> + where + Self: Sized, + { + todo!() + } + + async fn into_apub(self, _data: &Self::DataType) -> Result { + todo!() + } + + async fn verify( + _apub: &Self::ApubType, + _expected_domain: &Url, + _data: &Self::DataType, + _request_counter: &mut i32, + ) -> Result<(), Self::Error> { + todo!() + } + + async fn from_apub( + _apub: Self::ApubType, + _data: &Self::DataType, + _request_counter: &mut i32, + ) -> Result + where + Self: Sized, + { + todo!() + } + } + + #[test] + fn test_deserialize() { + let url = Url::parse("http://test.com/").unwrap(); + let id = ObjectId::::new(url); + + let string = serde_json::to_string(&id).unwrap(); + assert_eq!("\"http://test.com/\"", string); + + let parsed: ObjectId = serde_json::from_str(&string).unwrap(); + assert_eq!(parsed, id); + } + + #[test] + fn test_should_refetch_object() { + let one_second_ago = Utc::now().naive_utc() - ChronoDuration::seconds(1); + assert!(!should_refetch_object(one_second_ago)); + + let two_days_ago = Utc::now().naive_utc() - ChronoDuration::days(2); + assert!(should_refetch_object(two_days_ago)); + } +} diff --git a/src/core/signatures.rs b/src/core/signatures.rs new file mode 100644 index 0000000..430c434 --- /dev/null +++ b/src/core/signatures.rs @@ -0,0 +1,124 @@ +use actix_web::HttpRequest; +use anyhow::anyhow; +use http_signature_normalization_actix::Config as ConfigActix; +use http_signature_normalization_reqwest::prelude::{Config, SignExt}; +use once_cell::sync::Lazy; +use openssl::{ + hash::MessageDigest, + pkey::PKey, + rsa::Rsa, + sign::{Signer, Verifier}, +}; +use reqwest::Request; +use reqwest_middleware::RequestBuilder; +use serde::{Deserialize, Serialize}; +use sha2::{Digest, Sha256}; +use std::io::{Error, ErrorKind}; +use tracing::debug; +use url::Url; + +static CONFIG2: Lazy = Lazy::new(ConfigActix::new); +static HTTP_SIG_CONFIG: Lazy = Lazy::new(Config::new); + +/// A private/public key pair used for HTTP signatures +#[derive(Debug, Clone)] +pub struct Keypair { + pub private_key: String, + pub public_key: String, +} + +/// Generate the asymmetric keypair for ActivityPub HTTP signatures. +pub fn generate_actor_keypair() -> Result { + let rsa = Rsa::generate(2048)?; + let pkey = PKey::from_rsa(rsa)?; + let public_key = pkey.public_key_to_pem()?; + let private_key = pkey.private_key_to_pem_pkcs8()?; + let key_to_string = |key| match String::from_utf8(key) { + Ok(s) => Ok(s), + Err(e) => Err(Error::new( + ErrorKind::Other, + format!("Failed converting key to string: {}", e), + )), + }; + Ok(Keypair { + private_key: key_to_string(private_key)?, + public_key: key_to_string(public_key)?, + }) +} + +/// Creates an HTTP post request to `inbox_url`, with the given `client` and `headers`, and +/// `activity` as request body. The request is signed with `private_key` and then sent. +pub(crate) async fn sign_request( + request_builder: RequestBuilder, + activity: String, + public_key: PublicKey, + private_key: String, +) -> Result { + request_builder + .signature_with_digest( + HTTP_SIG_CONFIG.clone(), + public_key.id, + Sha256::new(), + activity, + move |signing_string| { + let private_key = PKey::private_key_from_pem(private_key.as_bytes())?; + let mut signer = Signer::new(MessageDigest::sha256(), &private_key)?; + signer.update(signing_string.as_bytes())?; + + Ok(base64::encode(signer.sign_to_vec()?)) as Result<_, anyhow::Error> + }, + ) + .await +} + +/// Verifies the HTTP signature on an incoming inbox request. +pub fn verify_signature(request: &HttpRequest, public_key: &str) -> Result<(), anyhow::Error> { + let verified = CONFIG2 + .begin_verify( + request.method(), + request.uri().path_and_query(), + request.headers().clone(), + )? + .verify(|signature, signing_string| -> Result { + debug!( + "Verifying with key {}, message {}", + &public_key, &signing_string + ); + let public_key = PKey::public_key_from_pem(public_key.as_bytes())?; + let mut verifier = Verifier::new(MessageDigest::sha256(), &public_key)?; + verifier.update(signing_string.as_bytes())?; + Ok(verifier.verify(&base64::decode(signature)?)?) + })?; + + if verified { + debug!("verified signature for {}", &request.uri()); + Ok(()) + } else { + Err(anyhow!("Invalid signature on request: {}", &request.uri())) + } +} + +#[derive(Clone, Debug, Deserialize, Serialize)] +#[serde(rename_all = "camelCase")] +pub struct PublicKey { + pub(crate) id: String, + pub(crate) owner: Url, + pub public_key_pem: String, +} + +impl PublicKey { + /// Create public key with default id, for actors that only have a single keypair + pub fn new_main_key(owner: Url, public_key_pem: String) -> Self { + let key_id = format!("{}#main-key", &owner); + PublicKey::new(key_id, owner, public_key_pem) + } + + /// Create public key with custom key id. Use this method if there are multiple keypairs per actor + pub fn new(id: String, owner: Url, public_key_pem: String) -> Self { + PublicKey { + id, + owner, + public_key_pem, + } + } +} diff --git a/src/data.rs b/src/data.rs new file mode 100644 index 0000000..0b21330 --- /dev/null +++ b/src/data.rs @@ -0,0 +1,37 @@ +use std::{ops::Deref, sync::Arc}; + +/// This type can be used to pass your own data into library functions and traits. It can be useful +/// to pass around database connections or other context. +#[derive(Debug)] +pub struct Data(Arc); + +impl Data { + /// Create new `Data` instance. + pub fn new(state: T) -> Data { + Data(Arc::new(state)) + } + + /// Get reference to inner app data. + pub fn get_ref(&self) -> &T { + self.0.as_ref() + } + + /// Convert to the internal Arc + pub fn into_inner(self) -> Arc { + self.0 + } +} + +impl Deref for Data { + type Target = Arc; + + fn deref(&self) -> &Arc { + &self.0 + } +} + +impl Clone for Data { + fn clone(&self) -> Data { + Data(self.0.clone()) + } +} diff --git a/src/deser/context.rs b/src/deser/context.rs new file mode 100644 index 0000000..670890b --- /dev/null +++ b/src/deser/context.rs @@ -0,0 +1,62 @@ +use crate::{data::Data, deser::helpers::deserialize_one_or_many, traits::ActivityHandler}; +use serde::{Deserialize, Serialize}; +use serde_json::Value; +use std::str::FromStr; +use url::Url; + +const DEFAULT_CONTEXT: &str = "[\"https://www.w3.org/ns/activitystreams\"]"; + +/// Simple wrapper which adds json-ld context to an object or activity. Doing it this way ensures +/// that nested objects dont have any context, but only the outermost one. +#[derive(Serialize, Deserialize, Debug)] +pub struct WithContext { + #[serde(rename = "@context")] + #[serde(deserialize_with = "deserialize_one_or_many")] + context: Vec, + #[serde(flatten)] + inner: T, +} + +impl WithContext { + pub fn new_default(inner: T) -> WithContext { + let context = vec![Value::from_str(DEFAULT_CONTEXT).expect("valid context")]; + WithContext::new(inner, context) + } + + pub fn new(inner: T, context: Vec) -> WithContext { + WithContext { context, inner } + } +} + +#[async_trait::async_trait(?Send)] +impl ActivityHandler for WithContext +where + T: ActivityHandler, +{ + type DataType = ::DataType; + type Error = ::Error; + + fn id(&self) -> &Url { + self.inner.id() + } + + fn actor(&self) -> &Url { + self.inner.actor() + } + + async fn verify( + &self, + data: &Data, + request_counter: &mut i32, + ) -> Result<(), Self::Error> { + self.inner.verify(data, request_counter).await + } + + async fn receive( + self, + data: &Data, + request_counter: &mut i32, + ) -> Result<(), Self::Error> { + self.inner.receive(data, request_counter).await + } +} diff --git a/src/deser/helpers.rs b/src/deser/helpers.rs new file mode 100644 index 0000000..d236d07 --- /dev/null +++ b/src/deser/helpers.rs @@ -0,0 +1,66 @@ +use serde::{Deserialize, Deserializer}; + +/// Deserialize either a single json value, or a json array. In either case, the items are returned +/// as an array. +/// +/// Usage: +/// `#[serde(deserialize_with = "deserialize_one_or_many")]` +pub fn deserialize_one_or_many<'de, T, D>(deserializer: D) -> Result, D::Error> +where + T: Deserialize<'de>, + D: Deserializer<'de>, +{ + #[derive(Deserialize)] + #[serde(untagged)] + enum OneOrMany { + One(T), + Many(Vec), + } + + let result: OneOrMany = Deserialize::deserialize(deserializer)?; + Ok(match result { + OneOrMany::Many(list) => list, + OneOrMany::One(value) => vec![value], + }) +} + +/// Deserialize either a single json value, or a json array with one element. In both cases it +/// returns a single value. +/// +/// Usage: +/// `#[serde(deserialize_with = "deserialize_one")]` +pub fn deserialize_one<'de, T, D>(deserializer: D) -> Result +where + T: Deserialize<'de>, + D: Deserializer<'de>, +{ + #[derive(Deserialize)] + #[serde(untagged)] + enum MaybeArray { + Simple(T), + Array([T; 1]), + } + + let result: MaybeArray = Deserialize::deserialize(deserializer)?; + Ok(match result { + MaybeArray::Simple(value) => value, + MaybeArray::Array([value]) => value, + }) +} + +/// Attempts to deserialize the item. If any error happens, its ignored and the type's default +/// value is returned. +/// +/// Usage: +/// `#[serde(deserialize_with = "deserialize_skip_error")]` +pub fn deserialize_skip_error<'de, T, D>(deserializer: D) -> Result +where + T: Deserialize<'de> + Default, + D: Deserializer<'de>, +{ + let result = Deserialize::deserialize(deserializer); + Ok(match result { + Ok(o) => o, + Err(_) => Default::default(), + }) +} diff --git a/src/deser/mod.rs b/src/deser/mod.rs new file mode 100644 index 0000000..810d4c8 --- /dev/null +++ b/src/deser/mod.rs @@ -0,0 +1,3 @@ +pub mod context; +pub mod helpers; +pub mod values; diff --git a/src/deser/values.rs b/src/deser/values.rs new file mode 100644 index 0000000..eba8f8a --- /dev/null +++ b/src/deser/values.rs @@ -0,0 +1,61 @@ +//! The enums here serve to limit a json string value to a single, hardcoded value which can be +//! verified at compilation time. When using it as the type of a struct field, the struct can only +//! be constructed or deserialized if the field has the exact same value. +//! +//! If we used String as the field type, any value would be accepted, and we would have to check +//! manually at runtime that it contains the expected value. +//! +//! The enums in `activitystreams::activity::kind` work in the same way, and can be used to +//! distinguish different activity types. +//! +//! In the example below, `MyObject` can only be constructed or +//! deserialized if `media_type` is `text/markdown`, but not if it is `text/html`. +//! +//! ``` +//! use serde_json::from_str; +//! use serde::{Deserialize, Serialize}; +//! use activitypub_federation::deser::values::MediaTypeMarkdown; +//! +//! #[derive(Deserialize, Serialize)] +//! struct MyObject { +//! content: String, +//! media_type: MediaTypeMarkdown, +//! } +//! +//! let markdown_json = r#"{"content": "**test**", "media_type": "text/markdown"}"#; +//! let from_markdown = from_str::(markdown_json); +//! assert!(from_markdown.is_ok()); +//! +//! let markdown_html = r#"{"content": "test", "media_type": "text/html"}"#; +//! let from_html = from_str::(markdown_html); +//! assert!(from_html.is_err()); +//! ``` + +use serde::{Deserialize, Serialize}; + +/// Media type for markdown text. +/// +/// +#[derive(Clone, Debug, Deserialize, Serialize)] +pub enum MediaTypeMarkdown { + #[serde(rename = "text/markdown")] + Markdown, +} + +/// Media type for HTML text. +/// +/// +#[derive(Clone, Debug, Deserialize, Serialize)] +pub enum MediaTypeHtml { + #[serde(rename = "text/html")] + Html, +} + +/// Media type which allows both markdown and HTML. +#[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] +pub enum MediaTypeMarkdownOrHtml { + #[serde(rename = "text/markdown")] + Markdown, + #[serde(rename = "text/html")] + Html, +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..0093f53 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,101 @@ +use crate::core::activity_queue::create_activity_queue; +use background_jobs::Manager; +use derive_builder::Builder; +use reqwest_middleware::ClientWithMiddleware; +use std::time::Duration; +use url::Url; + +pub mod core; +pub mod data; +pub mod deser; +pub mod traits; +pub mod utils; + +/// Mime type for Activitypub, used for `Accept` and `Content-Type` HTTP headers +pub static APUB_JSON_CONTENT_TYPE: &str = "application/activity+json"; + +/// Represents a single, federated instance (for example lemmy.ml). There should only be one of +/// this in your application (except for testing). +pub struct LocalInstance { + hostname: String, + client: ClientWithMiddleware, + activity_queue: Manager, + settings: InstanceSettings, +} + +// Use InstanceSettingsBuilder to initialize this +#[derive(Builder)] +pub struct InstanceSettings { + /// Maximum number of outgoing HTTP requests per incoming activity + #[builder(default = "20")] + http_fetch_retry_limit: i32, + /// Number of worker threads for sending outgoing activities + #[builder(default = "64")] + worker_count: u64, + /// Send outgoing activities synchronously, not in background thread. Helps to make tests + /// more consistent, but not recommended for production. + #[builder(default = "false")] + testing_send_sync: bool, + /// Timeout for all HTTP requests. HTTP signatures are valid for 10s, so it makes sense to + /// use the same as timeout when sending + #[builder(default = "Duration::from_secs(10)")] + request_timeout: Duration, + /// Function used to verify that urls are valid, used when receiving activities or fetching remote + /// objects. Use this to implement functionality like federation blocklists. In case verification + /// fails, it should return an error message. + #[builder(default = "|_| { Ok(()) }")] + verify_url_function: fn(&Url) -> Result<(), &'static str>, +} + +impl LocalInstance { + pub fn new(domain: String, client: ClientWithMiddleware, settings: InstanceSettings) -> Self { + let activity_queue = create_activity_queue( + client.clone(), + settings.worker_count, + settings.request_timeout, + ); + LocalInstance { + hostname: domain, + client, + activity_queue, + settings, + } + } + /// Returns true if the url refers to this instance. Handles hostnames like `localhost:8540` for + /// local debugging. + fn is_local_url(&self, url: &Url) -> bool { + let mut domain = url.domain().expect("id has domain").to_string(); + if let Some(port) = url.port() { + domain = format!("{}:{}", domain, port); + } + domain == self.hostname + } + + /// Returns the local hostname + pub fn hostname(&self) -> &str { + &self.hostname + } +} + +#[derive(thiserror::Error, Debug)] +pub enum Error { + #[error("Object was not found in database")] + NotFound, + #[error("Request limit was reached during fetch")] + RequestLimit, + #[error("Object to be fetched was deleted")] + ObjectDeleted, + #[error("{0}")] + UrlVerificationError(&'static str), + #[error(transparent)] + Other(#[from] anyhow::Error), +} + +impl Error { + pub fn conv(error: T) -> Self + where + T: Into, + { + Error::Other(error.into()) + } +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..e7a11a9 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello, world!"); +} diff --git a/src/traits.rs b/src/traits.rs new file mode 100644 index 0000000..dec0181 --- /dev/null +++ b/src/traits.rs @@ -0,0 +1,91 @@ +use crate::data::Data; +pub use activitypub_federation_derive::*; +use chrono::NaiveDateTime; +use url::Url; + +/// Trait which allows verification and reception of incoming activities. +#[async_trait::async_trait(?Send)] +pub trait ActivityHandler { + type DataType; + type Error; + + /// `id` field of the activity + fn id(&self) -> &Url; + + /// `actor` field of activity + fn actor(&self) -> &Url; + + /// Verify that the activity is valid. If this method returns an error, the activity will be + /// discarded. This is separate from receive(), so that it can be called recursively on nested + /// objects, without storing something in the database by accident. + async fn verify( + &self, + data: &Data, + request_counter: &mut i32, + ) -> Result<(), Self::Error>; + + /// Receives the activity and stores its action in database. + async fn receive( + self, + data: &Data, + request_counter: &mut i32, + ) -> Result<(), Self::Error>; +} + +#[async_trait::async_trait(?Send)] +pub trait ApubObject { + type DataType; + type ApubType; + type DbType; + type Error; + + /// If the object is stored in the database, this method should return the fetch time. Used to + /// update actors after certain interval. + fn last_refreshed_at(&self) -> Option { + None + } + + /// Try to read the object with given ID from local database. Returns Ok(None) if it doesn't exist. + async fn read_from_apub_id( + object_id: Url, + data: &Self::DataType, + ) -> Result, Self::Error> + where + Self: Sized; + + /// Marks the object as deleted in local db. Called when a delete activity is received, or if + /// fetch returns a tombstone. + async fn delete(self, _data: &Self::DataType) -> Result<(), Self::Error> + where + Self: Sized, + { + Ok(()) + } + + /// Trait for converting an object or actor into the respective ActivityPub type. + async fn into_apub(self, data: &Self::DataType) -> Result; + + /// Verify that the object is valid. If this method returns an error, it will be + /// discarded. This is separate from from_apub(), so that it can be called recursively on nested + /// objects, without storing something in the database by accident. + async fn verify( + apub: &Self::ApubType, + expected_domain: &Url, + data: &Self::DataType, + request_counter: &mut i32, + ) -> Result<(), Self::Error>; + + /// Converts an object from ActivityPub type to Lemmy internal type. + /// + /// * `apub` The object to read from + /// * `context` LemmyContext which holds DB pool, HTTP client etc + /// * `expected_domain` Domain where the object was received from. None in case of mod action. + /// * `mod_action_allowed` True if the object can be a mod activity, ignore `expected_domain` in this case + async fn from_apub( + apub: Self::ApubType, + data: &Self::DataType, + request_counter: &mut i32, + ) -> Result + where + Self: Sized; +} diff --git a/src/utils.rs b/src/utils.rs new file mode 100644 index 0000000..416260a --- /dev/null +++ b/src/utils.rs @@ -0,0 +1,51 @@ +use crate::{Error, LocalInstance, APUB_JSON_CONTENT_TYPE}; +use http::StatusCode; +use serde::de::DeserializeOwned; +use tracing::log::info; +use url::Url; + +pub async fn fetch_object_http( + url: &Url, + instance: &LocalInstance, + request_counter: &mut i32, +) -> Result { + // dont fetch local objects this way + debug_assert!(url.domain() != Some(&instance.hostname)); + info!("Fetching remote object {}", url.to_string()); + + *request_counter += 1; + if *request_counter > instance.settings.http_fetch_retry_limit { + return Err(Error::RequestLimit); + } + + let res = instance + .client + .get(url.as_str()) + .header("Accept", APUB_JSON_CONTENT_TYPE) + .timeout(instance.settings.request_timeout) + .send() + .await + .map_err(Error::conv)?; + + if res.status() == StatusCode::GONE { + return Err(Error::ObjectDeleted); + } + + res.json().await.map_err(Error::conv) +} + +/// Check that both urls have the same domain. If not, return UrlVerificationError. +pub fn verify_domains_match(a: &Url, b: &Url) -> Result<(), Error> { + if a.domain() != b.domain() { + return Err(Error::UrlVerificationError("Domains do not match")); + } + Ok(()) +} + +/// Check that both urls are identical. If not, return UrlVerificationError. +pub fn verify_urls_match(a: &Url, b: &Url) -> Result<(), Error> { + if a != b { + return Err(Error::UrlVerificationError("Urls do not match")); + } + Ok(()) +}