]> Untitled Git - lemmy.git/blob - crates/apub/src/lib.rs
Make webfinger standard compliant
[lemmy.git] / crates / apub / src / lib.rs
1 use crate::fetcher::post_or_comment::PostOrComment;
2 use anyhow::{anyhow, Context};
3 use lemmy_api_common::blocking;
4 use lemmy_db_schema::{newtypes::DbUrl, source::activity::Activity, DbPool};
5 use lemmy_utils::{location_info, settings::structs::Settings, LemmyError};
6 use std::net::IpAddr;
7 use url::{ParseError, Url};
8
9 pub mod activities;
10 pub(crate) mod activity_lists;
11 pub(crate) mod collections;
12 mod context;
13 pub mod fetcher;
14 pub mod http;
15 pub mod migrations;
16 pub mod objects;
17 pub mod protocol;
18
19 #[macro_use]
20 extern crate lazy_static;
21
22 /// Checks if the ID is allowed for sending or receiving.
23 ///
24 /// In particular, it checks for:
25 /// - federation being enabled (if its disabled, only local URLs are allowed)
26 /// - the correct scheme (either http or https)
27 /// - URL being in the allowlist (if it is active)
28 /// - URL not being in the blocklist (if it is active)
29 ///
30 /// `use_strict_allowlist` should be true only when parsing a remote community, or when parsing a
31 /// post/comment in a local community.
32 pub(crate) fn check_is_apub_id_valid(
33   apub_id: &Url,
34   use_strict_allowlist: bool,
35   settings: &Settings,
36 ) -> Result<(), LemmyError> {
37   let domain = apub_id.domain().context(location_info!())?.to_string();
38   let local_instance = settings.get_hostname_without_port()?;
39
40   if !settings.federation.enabled {
41     return if domain == local_instance {
42       Ok(())
43     } else {
44       Err(
45         anyhow!(
46           "Trying to connect with {}, but federation is disabled",
47           domain
48         )
49         .into(),
50       )
51     };
52   }
53
54   let host = apub_id.host_str().context(location_info!())?;
55   let host_as_ip = host.parse::<IpAddr>();
56   if host == "localhost" || host_as_ip.is_ok() {
57     return Err(anyhow!("invalid hostname {}: {}", host, apub_id).into());
58   }
59
60   if apub_id.scheme() != settings.get_protocol_string() {
61     return Err(anyhow!("invalid apub id scheme {}: {}", apub_id.scheme(), apub_id).into());
62   }
63
64   // TODO: might be good to put the part above in one method, and below in another
65   //       (which only gets called in apub::objects)
66   //        -> no that doesnt make sense, we still need the code below for blocklist and strict allowlist
67   if let Some(blocked) = settings.to_owned().federation.blocked_instances {
68     if blocked.contains(&domain) {
69       return Err(anyhow!("{} is in federation blocklist", domain).into());
70     }
71   }
72
73   if let Some(mut allowed) = settings.to_owned().federation.allowed_instances {
74     // Only check allowlist if this is a community, or strict allowlist is enabled.
75     let strict_allowlist = settings.to_owned().federation.strict_allowlist;
76     if use_strict_allowlist || strict_allowlist {
77       // need to allow this explicitly because apub receive might contain objects from our local
78       // instance.
79       allowed.push(local_instance);
80
81       if !allowed.contains(&domain) {
82         return Err(anyhow!("{} not in federation allowlist", domain).into());
83       }
84     }
85   }
86
87   Ok(())
88 }
89
90 pub enum EndpointType {
91   Community,
92   Person,
93   Post,
94   Comment,
95   PrivateMessage,
96 }
97
98 /// Generates an apub endpoint for a given domain, IE xyz.tld
99 pub fn generate_local_apub_endpoint(
100   endpoint_type: EndpointType,
101   name: &str,
102   domain: &str,
103 ) -> Result<DbUrl, ParseError> {
104   let point = match endpoint_type {
105     EndpointType::Community => "c",
106     EndpointType::Person => "u",
107     EndpointType::Post => "post",
108     EndpointType::Comment => "comment",
109     EndpointType::PrivateMessage => "private_message",
110   };
111
112   Ok(Url::parse(&format!("{}/{}/{}", domain, point, name))?.into())
113 }
114
115 pub fn generate_followers_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
116   Ok(Url::parse(&format!("{}/followers", actor_id))?.into())
117 }
118
119 pub fn generate_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
120   Ok(Url::parse(&format!("{}/inbox", actor_id))?.into())
121 }
122
123 pub fn generate_shared_inbox_url(actor_id: &DbUrl) -> Result<DbUrl, LemmyError> {
124   let actor_id: Url = actor_id.clone().into();
125   let url = format!(
126     "{}://{}{}/inbox",
127     &actor_id.scheme(),
128     &actor_id.host_str().context(location_info!())?,
129     if let Some(port) = actor_id.port() {
130       format!(":{}", port)
131     } else {
132       "".to_string()
133     },
134   );
135   Ok(Url::parse(&url)?.into())
136 }
137
138 pub fn generate_outbox_url(actor_id: &DbUrl) -> Result<DbUrl, ParseError> {
139   Ok(Url::parse(&format!("{}/outbox", actor_id))?.into())
140 }
141
142 fn generate_moderators_url(community_id: &DbUrl) -> Result<DbUrl, LemmyError> {
143   Ok(Url::parse(&format!("{}/moderators", community_id))?.into())
144 }
145
146 /// Store a sent or received activity in the database, for logging purposes. These records are not
147 /// persistent.
148 async fn insert_activity(
149   ap_id: &Url,
150   activity: serde_json::Value,
151   local: bool,
152   sensitive: bool,
153   pool: &DbPool,
154 ) -> Result<(), LemmyError> {
155   let ap_id = ap_id.to_owned().into();
156   blocking(pool, move |conn| {
157     Activity::insert(conn, ap_id, activity, local, sensitive)
158   })
159   .await??;
160   Ok(())
161 }