webringer 1.0.3

A bin/lib crate for a webring site
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
//! This module handles the actual webring capabilities

use argon2::password_hash;
use serde::{Deserialize, Serialize};
use sqlx::{FromRow, SqlitePool};
use thiserror::Error;
use tokio::task;
use tracing::{debug, error, info, instrument};

pub mod auth;

#[derive(Clone, Serialize, Deserialize, FromRow)]
pub struct ApprovedSite {
	pub site_id: i64,
	pub root_url: String,
	pub site_email: String,
	pub date_added: String,
	pub admin_id: i64,
	pub admin_username: String,
	pub admin_email: String,
}

#[derive(Clone, Serialize, Deserialize, FromRow)]
pub struct UnapprovedSite {
	pub id: i64,
	pub root_url: String,
	pub email: String,
}

#[derive(Clone, Serialize, Deserialize, FromRow)]
pub struct DeniedSite {
	pub site_id: i64,
	pub root_url: String,
	pub site_email: String,
	pub date_added: String,
	pub reason: String,
	pub admin_id: i64,
	pub admin_username: String,
	pub admin_email: String,
}

#[derive(Debug, Clone)]
pub struct RingState {
	database: SqlitePool,
}

#[derive(Debug, Error)]
pub enum RingError {
	#[error("The query {0} did not return any rows")]
	RowNotFound(String),
	#[error("The row {0} is already present in the database")]
	UniqueRowAlreadyPresent(String),
	#[error("The site {0} is not approved")]
	SiteNotApproved(String),
	#[error(transparent)]
	UnrecoverableDatabaseError(#[from] sqlx::Error),
	#[error(transparent)]
	TaskJoin(#[from] task::JoinError),
	#[error("Password verification error: {0}")]
	PasswordVerification(password_hash::Error),
	#[error("An admin method was called outside of an authorised session")]
	UnauthorisedAdmin,
}

impl RingState {
	#[must_use]
	pub const fn new(database: SqlitePool) -> Self {
		Self { database }
	}

	/// Add a site to the webring
	///
	/// # Errors
	/// Returns [`RingError::SiteAlreadyPresent`] if the site has already been registered
	/// Otherwise, [`RingError::UnrecoverableDatabaseError`]
	#[instrument]
	pub async fn add_site(&self, root_url: &str, email: &str) -> Result<(), RingError> {
		match sqlx::query!(
			"INSERT INTO sites (root_url, email) values (?, ?)",
			root_url,
			email
		)
		.bind(root_url)
		.bind(email)
		.execute(&self.database)
		.await
		{
			Ok(_query_outcome) => {
				info!("Unapproved site {} added to database", root_url);
				Ok(())
			}
			Err(sqlx::Error::Database(ref e)) if e.code().as_deref() == Some("2067") => {
				info!(
					"Someone tried to register their site {} but it was already registered",
					root_url
				);
				Err(RingError::UniqueRowAlreadyPresent(root_url.to_owned()))
			}
			Err(e) => {
				error!(
					"There was an unrecoverable database error in add_site: {}",
					e
				);
				Err(RingError::UnrecoverableDatabaseError(e))
			}
		}
	}

	/// Removes a site from the webring
	///
	/// # Errors
	/// Returns [`RingError::SiteNotPresent`] if the site is not present
	/// Otherwise, [`RingError::UnrecoverableDatabaseError`]
	#[instrument]
	pub async fn remove_site(&self, root_url: &str) -> Result<(), RingError> {
		match sqlx::query!("DELETE FROM sites WHERE root_url = ?", root_url)
			.bind(root_url)
			.execute(&self.database)
			.await
		{
			Ok(query_outcome) => {
				if query_outcome.rows_affected() == 0 {
					info!(
						"Someone tried to remove their site {} but it was already not there",
						root_url
					);
					Err(RingError::RowNotFound(root_url.to_owned()))
				} else {
					info!("Site {} removed from webring", root_url);
					Ok(())
				}
			}
			Err(e) => {
				error!(
					"There was an unrecoverable database error in remove_site: {}",
					e
				);
				Err(RingError::UnrecoverableDatabaseError(e))
			}
		}
	}

	/// Approves a site for the webring
	///
	/// # Errors
	/// [`RingError::UnrecoverableDatabaseError`] if there is a problem with the database
	#[instrument]
	pub async fn approve_site(&self, root_url: &str, admin_id: i64) -> Result<(), RingError> {
		let mut tx = match self.database.begin().await {
			Ok(tx) => tx,
			Err(e) => return Err(RingError::UnrecoverableDatabaseError(e)),
		};

		let approval_id = match sqlx::query!(
			"INSERT INTO approval_records (date_added, admin_id) VALUES (date('now'), ?)",
			admin_id
		)
		.execute(&mut *tx)
		.await
		{
			Ok(query_outcome) => query_outcome.last_insert_rowid(),
			Err(e) => {
				error!("There was an error when adding an approval record");
				return Err(RingError::UnrecoverableDatabaseError(e));
			}
		};

		if let Err(e) = sqlx::query!(
			"UPDATE sites SET approval_id = ? WHERE root_url = ?",
			approval_id,
			root_url
		)
		.execute(&mut *tx)
		.await
		{
			// TODO: Distinguish for the type of error you get when there is a constraint error
			// (e.g. there is already a denial_id set or vice versa)
			return Err(RingError::UnrecoverableDatabaseError(e));
		}

		if let Err(e) = tx.commit().await {
			return Err(RingError::UnrecoverableDatabaseError(e));
		}

		Ok(())
	}

	/// Denies a site for the webring
	///
	/// # Errors
	/// [`RingError::UnrecoverableDatabaseError`] if there is a problem with the database
	#[instrument]
	pub async fn deny_site(
		&self,
		root_url: &str,
		reason: &str,
		admin_id: i64,
	) -> Result<(), RingError> {
		let mut tx = match self.database.begin().await {
			Ok(tx) => tx,
			Err(e) => return Err(RingError::UnrecoverableDatabaseError(e)),
		};

		let denial_id = match sqlx::query!(
			"INSERT INTO denial_records (date_added, admin_id, reason) VALUES (date('now'), ?, ?)",
			admin_id,
			reason
		)
		.execute(&mut *tx)
		.await
		{
			Ok(query_outcome) => query_outcome.last_insert_rowid(),
			Err(e) => {
				error!("There was an error when adding a denial record");
				return Err(RingError::UnrecoverableDatabaseError(e));
			}
		};

		if let Err(e) = sqlx::query!(
			"UPDATE sites SET denial_id = ? WHERE root_url = ?",
			denial_id,
			root_url
		)
		.execute(&mut *tx)
		.await
		{
			return Err(RingError::UnrecoverableDatabaseError(e));
		}

		if let Err(e) = tx.commit().await {
			return Err(RingError::UnrecoverableDatabaseError(e));
		}

		Ok(())
	}

	/// Gets the webring site after the current one
	///
	/// # Errors
	/// Returns [`RingError::SiteNotApproved`] if the current site is not part of the webring
	/// Returns [`RingError::RowNotFound`] if the current site is last in the webring
	/// Otherwise, [`RingError::UnrecoverableDatabaseError`]
	#[instrument]
	pub async fn get_next(&self, current_url: &str) -> Result<String, RingError> {
		let id = self.get_approved_site_id(current_url).await?;
		match sqlx::query!(
            "SELECT root_url FROM approved_sites WHERE site_id > ? ORDER BY site_id ASC LIMIT 1",
            id
        )
        .fetch_one(&self.database)
        .await
        {
            Ok(record) => Ok(record.root_url),
            Err(sqlx::Error::RowNotFound) => Err(RingError::RowNotFound("SELECT root_url FROM verified_sites WHERE site_id > ? ORDER BY site_id ASC LIMIT 1".to_owned())),
            Err(e) => Err(RingError::UnrecoverableDatabaseError(e)),
        }
	}

	/// Gets the webring site before the current one
	///
	/// # Errors
	/// Returns [`RingError::SiteNotApproved`] if the current site is not part of the webring
	/// Returns [`RingError::RowNotFound`] if the current site is last in the webring
	/// Otherwise, [`RingError::UnrecoverableDatabaseError`]
	#[instrument]
	pub async fn get_prev(&self, current_url: &str) -> Result<String, RingError> {
		let id = self.get_approved_site_id(current_url).await?;
		match sqlx::query!(
            "SELECT root_url FROM approved_sites WHERE site_id > ? ORDER BY site_id ASC LIMIT 1",
            id
        )
        .fetch_one(&self.database)
        .await
        {
            Ok(record) => Ok(record.root_url),
            Err(sqlx::Error::RowNotFound) => Err(RingError::RowNotFound("SELECT root_url FROM verified_sites WHERE site_id < ? ORDER BY site_id ASC LIMIT 1".to_owned())),
            Err(e) => {
                error!("There was an unrecoverable database error in get_prev: {}", e);
                Err(RingError::UnrecoverableDatabaseError(e))
            }
        }
	}

	/// Gets the id of an approved site with the given url
	///
	/// # Errors
	/// [`RingError::SiteNotApproved`] if the site is not approved
	/// [`RingError::UnrecoverableDatabaseError`] if there is a problem with the database
	#[instrument]
	async fn get_approved_site_id(&self, root_url: &str) -> Result<i64, RingError> {
		match sqlx::query!(
			"SELECT site_id FROM approved_sites WHERE root_url=?",
			root_url
		)
		.fetch_one(&self.database)
		.await
		{
			Ok(record) => Ok(record
				.site_id
				.ok_or(RingError::SiteNotApproved(root_url.to_owned()))?),
			Err(sqlx::Error::RowNotFound) => {
				info!("The unapproved site {root_url} tried to be a part of the webring");
				return Err(RingError::SiteNotApproved(root_url.to_owned()));
			}
			Err(e) => {
				error!(
					"There was an unrecoverable database error in get_verified_id: {}",
					e
				);
				Err(RingError::UnrecoverableDatabaseError(e))
			}
		}
	}

	/// Gets a random site from the webring
	///
	/// # Errors
	/// Returns [`RingError::RowNotFound`] if there are no approved sites
	/// Otherwise, [`RingError::UnrecoverableDatabaseError`]
	#[instrument]
	pub async fn get_random_site(&self) -> Result<String, RingError> {
		match sqlx::query!("SELECT root_url FROM approved_sites ORDER BY random() LIMIT 1")
			.fetch_one(&self.database)
			.await
		{
			Ok(record) => Ok(record.root_url),
			Err(sqlx::Error::RowNotFound) => Err(RingError::RowNotFound(
				"SELECT root_url FROM verified_sites ORDER BY random() LIMIT 1".to_owned(),
			)),
			Err(e) => {
				error!(
					"There was an unrecoverable database error in get_random_site: {}",
					e
				);
				Err(RingError::UnrecoverableDatabaseError(e))
			}
		}
	}

	/// Gets a list of all approved webring sites
	///
	/// # Errors
	/// Returns [`RingError::RowNotFound`] if there are no verified sites
	/// Otherwise, [`RingError::UnrecoverableDatabaseError`]
	#[instrument]
	pub async fn get_list_approved(&self) -> Result<Vec<ApprovedSite>, RingError> {
		match sqlx::query_as("SELECT * FROM approved_sites ORDER BY random()")
			.fetch_all(&self.database)
			.await
		{
			Ok(sites) => Ok(sites),
			Err(sqlx::Error::RowNotFound) => Err(RingError::RowNotFound(
				"SELECT root_url FROM verified_sites ORDER BY random()".to_owned(),
			)),
			Err(e) => {
				error!(
					"There was an unrecoverable database error in get_list_approved: {}",
					e
				);
				Err(RingError::UnrecoverableDatabaseError(e))
			}
		}
	}

	/// Gets all the denied sites
	///
	/// # Errors
	/// [`RingError::RowNotFound`] if there are no denied sites
	/// [`RingError::UnrecoverableDatabaseError`] if there is a problem with the database
	#[instrument]
	pub async fn get_list_denied(&self) -> Result<Vec<DeniedSite>, RingError> {
		match sqlx::query_as("SELECT * FROM denied_sites")
			.fetch_all(&self.database)
			.await
		{
			Ok(sites) => Ok(sites),
			Err(sqlx::Error::RowNotFound) => Err(RingError::RowNotFound(
				"SELECT * FROM denied_sites".to_owned(),
			)),
			Err(e) => {
				error!(
					"There was an unrecoverable database error in get_list_denied: {}",
					e
				);
				Err(RingError::UnrecoverableDatabaseError(e))
			}
		}
	}

	/// Gets a list of all unapproved webring sites
	///
	/// # Errors
	/// [`RingError::RowNotFound`] if there are no unapproved sites
	/// [`RingError::UnrecoverableDatabaseError`] if there is a problem with the database
	#[instrument]
	pub async fn get_list_unapproved(&self) -> Result<Vec<UnapprovedSite>, RingError> {
		match sqlx::query_as("SELECT * FROM unapproved_sites ORDER BY id")
			.fetch_all(&self.database)
			.await
		{
			Ok(sites) => Ok(sites),
			Err(sqlx::Error::RowNotFound) => Err(RingError::RowNotFound(
				"SELECT * FROM unapproved_sites ORDER BY id".to_owned(),
			)),
			Err(e) => {
				error!(
					"There was an unrecoverable database error in get_list_unapproved: {}",
					e
				);
				Err(RingError::UnrecoverableDatabaseError(e))
			}
		}
	}

	/// Gets a list of all unapproved webring sites
	///
	/// # Errors
	/// [`RingError::UniqueRowAlreadyPresent`] if the new admins email or username are already in
	/// use
	/// [`RingError::UnrecoverableDatabaseError`] if there is a problem with the database
	#[instrument]
	pub async fn add_admin(
		&self,
		username: String,
		email: String,
		password_plaintext: String,
	) -> Result<(), RingError> {
		debug!("Add admin function running");
		let password_hashed = auth::hash_password(password_plaintext).await?;
		match sqlx::query!(
			"INSERT INTO admins (username, email, password_phc) values (?, ?, ?)",
			username,
			email,
			password_hashed
		)
		.execute(&self.database)
		.await
		{
			Ok(_query_result) => {
				info!("Added admin to database: {} {}", username, email);
				Ok(())
			}
			Err(sqlx::Error::Database(ref e)) if e.code().as_deref() == Some("2067") => {
				info!(
					"Admin username {} or email {} already taken",
					username, email
				);
				Err(RingError::UniqueRowAlreadyPresent(format!(
					"{username} {email}"
				)))
			}
			Err(e) => {
				error!(
					"There was an unrecoverable database error in add_admin: {}",
					e
				);
				Err(RingError::UnrecoverableDatabaseError(e))
			}
		}
	}

	/// Deletes an admin from the webring
	///
	/// # Errors
	/// [`RingError::RowNotFound`] if there is no admin with the given id
	/// [`RingError::UnrecoverableDatabaseError`] if there is a problem with the database
	#[instrument]
	pub async fn delete_admin(&self, admin_id: i64) -> Result<(), RingError> {
		match sqlx::query("DELETE FROM admins WHERE id = ?")
			.bind(admin_id)
			.execute(&self.database)
			.await
		{
			Ok(query) if query.rows_affected() == 0 => {
				error!("No admin found to delete. {:?}", query);
				Err(RingError::RowNotFound(format!(
					"Admin with admin id {admin_id:?}"
				)))
			}
			Ok(query) => {
				info!(
					"Successfully deleted admin account with id {:?}: {:?}",
					admin_id, query
				);
				Ok(())
			}
			Err(e) => {
				error!(
					"There was a database error when trying to delete admin with id {}: {}",
					admin_id, e
				);
				Err(RingError::UnrecoverableDatabaseError(e))
			}
		}
	}
}