1 // This is for db migrations that require code
2 use activitypub_federation::http_signatures::generate_actor_keypair;
4 sql_types::{Nullable, Text},
10 use diesel_async::RunQueryDsl;
11 use lemmy_api_common::{
12 lemmy_db_views::structs::SiteView,
14 generate_followers_url,
16 generate_local_apub_endpoint,
17 generate_shared_inbox_url,
18 generate_site_inbox_url,
22 use lemmy_db_schema::{
24 comment::{Comment, CommentUpdateForm},
25 community::{Community, CommunityUpdateForm},
27 local_site::{LocalSite, LocalSiteInsertForm},
28 local_site_rate_limit::{LocalSiteRateLimit, LocalSiteRateLimitInsertForm},
29 local_user::{LocalUser, LocalUserInsertForm},
30 person::{Person, PersonInsertForm, PersonUpdateForm},
31 post::{Post, PostUpdateForm},
32 private_message::{PrivateMessage, PrivateMessageUpdateForm},
33 site::{Site, SiteInsertForm, SiteUpdateForm},
36 utils::{get_conn, naive_now, DbPool},
38 use lemmy_utils::{error::LemmyError, settings::structs::Settings};
42 pub async fn run_advanced_migrations(
43 pool: &mut DbPool<'_>,
45 ) -> Result<(), LemmyError> {
46 let protocol_and_hostname = &settings.get_protocol_and_hostname();
47 user_updates_2020_04_02(pool, protocol_and_hostname).await?;
48 community_updates_2020_04_02(pool, protocol_and_hostname).await?;
49 post_updates_2020_04_03(pool, protocol_and_hostname).await?;
50 comment_updates_2020_04_03(pool, protocol_and_hostname).await?;
51 private_message_updates_2020_05_05(pool, protocol_and_hostname).await?;
52 post_thumbnail_url_updates_2020_07_27(pool, protocol_and_hostname).await?;
53 apub_columns_2021_02_02(pool).await?;
54 instance_actor_2022_01_28(pool, protocol_and_hostname).await?;
55 regenerate_public_keys_2022_07_05(pool).await?;
56 initialize_local_site_2022_10_10(pool, settings).await?;
61 async fn user_updates_2020_04_02(
62 pool: &mut DbPool<'_>,
63 protocol_and_hostname: &str,
64 ) -> Result<(), LemmyError> {
65 use lemmy_db_schema::schema::person::dsl::{actor_id, local, person};
66 let conn = &mut get_conn(pool).await?;
68 info!("Running user_updates_2020_04_02");
70 // Update the actor_id, private_key, and public_key, last_refreshed_at
71 let incorrect_persons = person
72 .filter(actor_id.like("http://changeme%"))
73 .filter(local.eq(true))
77 for cperson in &incorrect_persons {
78 let keypair = generate_actor_keypair()?;
80 let form = PersonUpdateForm {
81 actor_id: Some(generate_local_apub_endpoint(
84 protocol_and_hostname,
86 private_key: Some(Some(keypair.private_key)),
87 public_key: Some(keypair.public_key),
88 last_refreshed_at: Some(naive_now()),
92 Person::update(pool, cperson.id, &form).await?;
95 info!("{} person rows updated.", incorrect_persons.len());
100 async fn community_updates_2020_04_02(
101 pool: &mut DbPool<'_>,
102 protocol_and_hostname: &str,
103 ) -> Result<(), LemmyError> {
104 use lemmy_db_schema::schema::community::dsl::{actor_id, community, local};
105 let conn = &mut get_conn(pool).await?;
107 info!("Running community_updates_2020_04_02");
109 // Update the actor_id, private_key, and public_key, last_refreshed_at
110 let incorrect_communities = community
111 .filter(actor_id.like("http://changeme%"))
112 .filter(local.eq(true))
113 .load::<Community>(conn)
116 for ccommunity in &incorrect_communities {
117 let keypair = generate_actor_keypair()?;
118 let community_actor_id = generate_local_apub_endpoint(
119 EndpointType::Community,
121 protocol_and_hostname,
124 let form = CommunityUpdateForm {
125 actor_id: Some(community_actor_id.clone()),
126 private_key: Some(Some(keypair.private_key)),
127 public_key: Some(keypair.public_key),
128 last_refreshed_at: Some(naive_now()),
132 Community::update(pool, ccommunity.id, &form).await?;
135 info!("{} community rows updated.", incorrect_communities.len());
140 async fn post_updates_2020_04_03(
141 pool: &mut DbPool<'_>,
142 protocol_and_hostname: &str,
143 ) -> Result<(), LemmyError> {
144 use lemmy_db_schema::schema::post::dsl::{ap_id, local, post};
145 let conn = &mut get_conn(pool).await?;
147 info!("Running post_updates_2020_04_03");
150 let incorrect_posts = post
151 .filter(ap_id.like("http://changeme%"))
152 .filter(local.eq(true))
156 for cpost in &incorrect_posts {
157 let apub_id = generate_local_apub_endpoint(
159 &cpost.id.to_string(),
160 protocol_and_hostname,
166 ap_id: Some(apub_id),
173 info!("{} post rows updated.", incorrect_posts.len());
178 async fn comment_updates_2020_04_03(
179 pool: &mut DbPool<'_>,
180 protocol_and_hostname: &str,
181 ) -> Result<(), LemmyError> {
182 use lemmy_db_schema::schema::comment::dsl::{ap_id, comment, local};
183 let conn = &mut get_conn(pool).await?;
185 info!("Running comment_updates_2020_04_03");
188 let incorrect_comments = comment
189 .filter(ap_id.like("http://changeme%"))
190 .filter(local.eq(true))
191 .load::<Comment>(conn)
194 for ccomment in &incorrect_comments {
195 let apub_id = generate_local_apub_endpoint(
196 EndpointType::Comment,
197 &ccomment.id.to_string(),
198 protocol_and_hostname,
204 ap_id: Some(apub_id),
211 info!("{} comment rows updated.", incorrect_comments.len());
216 async fn private_message_updates_2020_05_05(
217 pool: &mut DbPool<'_>,
218 protocol_and_hostname: &str,
219 ) -> Result<(), LemmyError> {
220 use lemmy_db_schema::schema::private_message::dsl::{ap_id, local, private_message};
221 let conn = &mut get_conn(pool).await?;
223 info!("Running private_message_updates_2020_05_05");
226 let incorrect_pms = private_message
227 .filter(ap_id.like("http://changeme%"))
228 .filter(local.eq(true))
229 .load::<PrivateMessage>(conn)
232 for cpm in &incorrect_pms {
233 let apub_id = generate_local_apub_endpoint(
234 EndpointType::PrivateMessage,
236 protocol_and_hostname,
238 PrivateMessage::update(
241 &PrivateMessageUpdateForm {
242 ap_id: Some(apub_id),
249 info!("{} private message rows updated.", incorrect_pms.len());
254 async fn post_thumbnail_url_updates_2020_07_27(
255 pool: &mut DbPool<'_>,
256 protocol_and_hostname: &str,
257 ) -> Result<(), LemmyError> {
258 use lemmy_db_schema::schema::post::dsl::{post, thumbnail_url};
259 let conn = &mut get_conn(pool).await?;
261 info!("Running post_thumbnail_url_updates_2020_07_27");
263 let domain_prefix = format!("{protocol_and_hostname}/pictrs/image/",);
265 let incorrect_thumbnails = post.filter(thumbnail_url.not_like("http%"));
267 // Prepend the rows with the update
268 let res = diesel::update(incorrect_thumbnails)
272 .into_sql::<Nullable<Text>>()
273 .concat(thumbnail_url),
276 .get_results::<Post>(conn)
279 info!("{} Post thumbnail_url rows updated.", res.len());
284 /// We are setting inbox and follower URLs for local and remote actors alike, because for now
285 /// all federated instances are also Lemmy and use the same URL scheme.
286 async fn apub_columns_2021_02_02(pool: &mut DbPool<'_>) -> Result<(), LemmyError> {
287 let conn = &mut get_conn(pool).await?;
288 info!("Running apub_columns_2021_02_02");
290 use lemmy_db_schema::schema::person::dsl::{inbox_url, person, shared_inbox_url};
292 .filter(inbox_url.like("http://changeme%"))
293 .load::<Person>(conn)
297 let inbox_url_ = generate_inbox_url(&p.actor_id)?;
298 let shared_inbox_url_ = generate_shared_inbox_url(&p.actor_id)?;
299 diesel::update(person.find(p.id))
301 inbox_url.eq(inbox_url_),
302 shared_inbox_url.eq(shared_inbox_url_),
304 .get_result::<Person>(conn)
310 use lemmy_db_schema::schema::community::dsl::{
316 let communities = community
317 .filter(inbox_url.like("http://changeme%"))
318 .load::<Community>(conn)
321 for c in &communities {
322 let followers_url_ = generate_followers_url(&c.actor_id)?;
323 let inbox_url_ = generate_inbox_url(&c.actor_id)?;
324 let shared_inbox_url_ = generate_shared_inbox_url(&c.actor_id)?;
325 diesel::update(community.find(c.id))
327 followers_url.eq(followers_url_),
328 inbox_url.eq(inbox_url_),
329 shared_inbox_url.eq(shared_inbox_url_),
331 .get_result::<Community>(conn)
339 /// Site object turns into an actor, so that things like instance description can be federated. This
340 /// means we need to add actor columns to the site table, and initialize them with correct values.
341 /// Before this point, there is only a single value in the site table which refers to the local
342 /// Lemmy instance, so thats all we need to update.
343 async fn instance_actor_2022_01_28(
344 pool: &mut DbPool<'_>,
345 protocol_and_hostname: &str,
346 ) -> Result<(), LemmyError> {
347 info!("Running instance_actor_2021_09_29");
348 if let Ok(site_view) = SiteView::read_local(pool).await {
349 let site = site_view.site;
350 // if site already has public key, we dont need to do anything here
351 if !site.public_key.is_empty() {
354 let key_pair = generate_actor_keypair()?;
355 let actor_id = Url::parse(protocol_and_hostname)?;
356 let site_form = SiteUpdateForm {
357 actor_id: Some(actor_id.clone().into()),
358 last_refreshed_at: Some(naive_now()),
359 inbox_url: Some(generate_site_inbox_url(&actor_id.into())?),
360 private_key: Some(Some(key_pair.private_key)),
361 public_key: Some(key_pair.public_key),
364 Site::update(pool, site.id, &site_form).await?;
369 /// Fix for bug #2347, which can result in community/person public keys being overwritten with
370 /// empty string when the database value is updated. We go through all actors, and if the public
371 /// key field is empty, generate a new keypair. It would be possible to regenerate only the pubkey,
372 /// but thats more complicated and has no benefit, as federation is already broken for these actors.
373 /// https://github.com/LemmyNet/lemmy/issues/2347
374 async fn regenerate_public_keys_2022_07_05(pool: &mut DbPool<'_>) -> Result<(), LemmyError> {
375 let conn = &mut get_conn(pool).await?;
376 info!("Running regenerate_public_keys_2022_07_05");
379 // update communities with empty pubkey
380 use lemmy_db_schema::schema::community::dsl::{community, local, public_key};
381 let communities: Vec<Community> = community
382 .filter(local.eq(true))
383 .filter(public_key.eq(""))
384 .load::<Community>(conn)
386 for community_ in communities {
388 "local community {} has empty public key field, regenerating key",
391 let key_pair = generate_actor_keypair()?;
392 let form = CommunityUpdateForm {
393 public_key: Some(key_pair.public_key),
394 private_key: Some(Some(key_pair.private_key)),
397 Community::update(&mut conn.into(), community_.id, &form).await?;
402 // update persons with empty pubkey
403 use lemmy_db_schema::schema::person::dsl::{local, person, public_key};
405 .filter(local.eq(true))
406 .filter(public_key.eq(""))
407 .load::<Person>(conn)
409 for person_ in persons {
411 "local user {} has empty public key field, regenerating key",
414 let key_pair = generate_actor_keypair()?;
415 let form = PersonUpdateForm {
416 public_key: Some(key_pair.public_key),
417 private_key: Some(Some(key_pair.private_key)),
420 Person::update(pool, person_.id, &form).await?;
426 /// This ensures that your local site is initialized and exists.
428 /// If a site already exists, the DB migration should generate a local_site row.
429 /// This will only be run for brand new sites.
430 async fn initialize_local_site_2022_10_10(
431 pool: &mut DbPool<'_>,
433 ) -> Result<(), LemmyError> {
434 info!("Running initialize_local_site_2022_10_10");
436 // Check to see if local_site exists
437 if LocalSite::read(pool).await.is_ok() {
440 info!("No Local Site found, creating it.");
442 let domain = settings
443 .get_hostname_without_port()
444 .expect("must have domain");
446 // Upsert this to the instance table
447 let instance = Instance::read_or_create(pool, domain).await?;
449 if let Some(setup) = &settings.setup {
450 let person_keypair = generate_actor_keypair()?;
451 let person_actor_id = generate_local_apub_endpoint(
452 EndpointType::Person,
453 &setup.admin_username,
454 &settings.get_protocol_and_hostname(),
457 // Register the user if there's a site setup
458 let person_form = PersonInsertForm::builder()
459 .name(setup.admin_username.clone())
461 .instance_id(instance.id)
462 .actor_id(Some(person_actor_id.clone()))
463 .private_key(Some(person_keypair.private_key))
464 .public_key(person_keypair.public_key)
465 .inbox_url(Some(generate_inbox_url(&person_actor_id)?))
466 .shared_inbox_url(Some(generate_shared_inbox_url(&person_actor_id)?))
468 let person_inserted = Person::create(pool, &person_form).await?;
470 let local_user_form = LocalUserInsertForm::builder()
471 .person_id(person_inserted.id)
472 .password_encrypted(setup.admin_password.clone())
473 .email(setup.admin_email.clone())
475 LocalUser::create(pool, &local_user_form).await?;
478 // Add an entry for the site table
479 let site_key_pair = generate_actor_keypair()?;
480 let site_actor_id = Url::parse(&settings.get_protocol_and_hostname())?;
482 let site_form = SiteInsertForm::builder()
487 .map(|s| s.site_name)
488 .unwrap_or_else(|| "New Site".to_string()),
490 .instance_id(instance.id)
491 .actor_id(Some(site_actor_id.clone().into()))
492 .last_refreshed_at(Some(naive_now()))
493 .inbox_url(Some(generate_site_inbox_url(&site_actor_id.into())?))
494 .private_key(Some(site_key_pair.private_key))
495 .public_key(Some(site_key_pair.public_key))
497 let site = Site::create(pool, &site_form).await?;
499 // Finally create the local_site row
500 let local_site_form = LocalSiteInsertForm::builder()
502 .site_setup(Some(settings.setup.is_some()))
504 let local_site = LocalSite::create(pool, &local_site_form).await?;
506 // Create the rate limit table
507 let local_site_rate_limit_form = LocalSiteRateLimitInsertForm::builder()
508 // TODO these have to be set, because the database defaults are too low for the federation
509 // tests to pass, and there's no way to live update the rate limits without restarting the
511 // This can be removed once live rate limits are enabled.
518 .local_site_id(local_site.id)
520 LocalSiteRateLimit::create(pool, &local_site_rate_limit_form).await?;