surrealdb_core/sql/statements/
access.rs

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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
use crate::ctx::Context;
use crate::dbs::Options;
use crate::doc::CursorDoc;
use crate::err::Error;
use crate::iam::{Action, ResourceKind};
use crate::sql::access_type::BearerAccessSubject;
use crate::sql::{
	AccessType, Array, Base, Cond, Datetime, Duration, Ident, Object, Strand, Thing, Uuid, Value,
};
use derive::Store;
use md5::Digest;
use rand::Rng;
use reblessive::tree::Stk;
use revision::revisioned;
use serde::{Deserialize, Serialize};
use sha2::Sha256;
use std::fmt;
use std::fmt::{Display, Formatter};

// Keys and their identifiers are generated randomly from a 62-character pool.
pub static GRANT_BEARER_CHARACTER_POOL: &[u8] =
	b"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
// The key identifier should not have collisions to prevent confusion.
// However, collisions should be handled gracefully when issuing grants.
// The first character of the key identifier will not be a digit to prevent parsing issues.
// With 12 characters from the pool, one alphabetic, the key identifier part has ~68 bits of entropy.
pub static GRANT_BEARER_ID_LENGTH: usize = 12;
// With 24 characters from the pool, the key part has ~140 bits of entropy.
pub static GRANT_BEARER_KEY_LENGTH: usize = 24;

#[revisioned(revision = 1)]
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[non_exhaustive]
pub enum AccessStatement {
	Grant(AccessStatementGrant),   // Create access grant.
	Show(AccessStatementShow),     // Show access grants.
	Revoke(AccessStatementRevoke), // Revoke access grant.
	Purge(AccessStatementPurge),   // Purge access grants.
}

#[revisioned(revision = 1)]
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[non_exhaustive]
pub struct AccessStatementGrant {
	pub ac: Ident,
	pub base: Option<Base>,
	pub subject: Subject,
}

#[revisioned(revision = 1)]
#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[non_exhaustive]
pub struct AccessStatementShow {
	pub ac: Ident,
	pub base: Option<Base>,
	pub gr: Option<Ident>,
	pub cond: Option<Cond>,
}

#[revisioned(revision = 1)]
#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[non_exhaustive]
pub struct AccessStatementRevoke {
	pub ac: Ident,
	pub base: Option<Base>,
	pub gr: Option<Ident>,
	pub cond: Option<Cond>,
}

#[revisioned(revision = 1)]
#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[non_exhaustive]
pub struct AccessStatementPurge {
	pub ac: Ident,
	pub base: Option<Base>,
	pub expired: bool,
	pub revoked: bool,
	pub grace: Duration,
}

#[revisioned(revision = 1)]
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[non_exhaustive]
pub struct AccessGrant {
	pub id: Ident,                    // Unique grant identifier.
	pub ac: Ident,                    // Access method used to create the grant.
	pub creation: Datetime,           // Grant creation time.
	pub expiration: Option<Datetime>, // Grant expiration time, if any.
	pub revocation: Option<Datetime>, // Grant revocation time, if any.
	pub subject: Subject,             // Subject of the grant.
	pub grant: Grant,                 // Grant data.
}

impl AccessGrant {
	/// Returns a version of the statement where potential secrets are redacted.
	/// This function should be used when displaying the statement to datastore users.
	/// This function should NOT be used when displaying the statement for export purposes.
	pub fn redacted(&self) -> AccessGrant {
		let mut ags = self.clone();
		ags.grant = match ags.grant {
			Grant::Jwt(mut gr) => {
				// Token should not even be stored. We clear it just as a precaution.
				gr.token = None;
				Grant::Jwt(gr)
			}
			Grant::Record(mut gr) => {
				// Token should not even be stored. We clear it just as a precaution.
				gr.token = None;
				Grant::Record(gr)
			}
			Grant::Bearer(mut gr) => {
				// Key is stored, but should not usually be displayed.
				gr.key = "[REDACTED]".into();
				Grant::Bearer(gr)
			}
		};
		ags
	}

	// Returns if the access grant is expired.
	pub fn is_expired(&self) -> bool {
		match &self.expiration {
			Some(exp) => exp < &Datetime::default(),
			None => false,
		}
	}

	// Returns if the access grant is revoked.
	pub fn is_revoked(&self) -> bool {
		self.revocation.is_some()
	}

	// Returns if the access grant is active.
	pub fn is_active(&self) -> bool {
		!(self.is_expired() || self.is_revoked())
	}
}

impl From<AccessGrant> for Object {
	fn from(grant: AccessGrant) -> Self {
		let mut res = Object::default();
		res.insert("id".to_owned(), Value::from(grant.id.to_raw()));
		res.insert("ac".to_owned(), Value::from(grant.ac.to_raw()));
		res.insert("type".to_owned(), Value::from(grant.grant.variant()));
		res.insert("creation".to_owned(), Value::from(grant.creation));
		res.insert("expiration".to_owned(), Value::from(grant.expiration));
		res.insert("revocation".to_owned(), Value::from(grant.revocation));
		let mut sub = Object::default();
		match grant.subject {
			Subject::Record(id) => sub.insert("record".to_owned(), Value::from(id)),
			Subject::User(name) => sub.insert("user".to_owned(), Value::from(name.to_raw())),
		};
		res.insert("subject".to_owned(), Value::from(sub));

		let mut gr = Object::default();
		match grant.grant {
			Grant::Jwt(jg) => {
				gr.insert("jti".to_owned(), Value::from(jg.jti));
				if let Some(token) = jg.token {
					gr.insert("token".to_owned(), Value::from(token));
				}
			}
			Grant::Record(rg) => {
				gr.insert("rid".to_owned(), Value::from(rg.rid));
				gr.insert("jti".to_owned(), Value::from(rg.jti));
				if let Some(token) = rg.token {
					gr.insert("token".to_owned(), Value::from(token));
				}
			}
			Grant::Bearer(bg) => {
				gr.insert("id".to_owned(), Value::from(bg.id.to_raw()));
				gr.insert("key".to_owned(), Value::from(bg.key));
			}
		};
		res.insert("grant".to_owned(), Value::from(gr));

		res
	}
}

#[revisioned(revision = 1)]
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[non_exhaustive]
pub enum Subject {
	Record(Thing),
	User(Ident),
}

impl Subject {
	// Returns the main identifier of a subject as a string.
	pub fn id(&self) -> String {
		match self {
			Subject::Record(id) => id.to_raw(),
			Subject::User(name) => name.to_raw(),
		}
	}
}

#[revisioned(revision = 1)]
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[non_exhaustive]
pub enum Grant {
	Jwt(GrantJwt),
	Record(GrantRecord),
	Bearer(GrantBearer),
}

impl Grant {
	// Returns the type of the grant as a string.
	pub fn variant(&self) -> &str {
		match self {
			Grant::Jwt(_) => "jwt",
			Grant::Record(_) => "record",
			Grant::Bearer(_) => "bearer",
		}
	}
}

#[revisioned(revision = 1)]
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[non_exhaustive]
pub struct GrantJwt {
	pub jti: Uuid,             // JWT ID
	pub token: Option<Strand>, // JWT. Will not be stored after being returned.
}

#[revisioned(revision = 1)]
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[non_exhaustive]
pub struct GrantRecord {
	pub rid: Uuid,             // Record ID
	pub jti: Uuid,             // JWT ID
	pub token: Option<Strand>, // JWT. Will not be stored after being returned.
}

#[revisioned(revision = 1)]
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[non_exhaustive]
pub struct GrantBearer {
	pub id: Ident, // Key ID
	// Key. Will not be stored and be returned as redacted.
	// Immediately after generation, it will contain the plaintext key.
	// Will be hashed before storage so that the plaintext key is not stored.
	pub key: Strand,
}

impl GrantBearer {
	#[allow(clippy::new_without_default)]
	pub fn new(prefix: &str) -> Self {
		let id = format!(
			"{}{}",
			// The pool for the first character of the key identifier excludes digits.
			random_string(1, &GRANT_BEARER_CHARACTER_POOL[10..]),
			random_string(GRANT_BEARER_ID_LENGTH - 1, GRANT_BEARER_CHARACTER_POOL)
		);
		let secret = random_string(GRANT_BEARER_KEY_LENGTH, GRANT_BEARER_CHARACTER_POOL);
		Self {
			id: id.clone().into(),
			key: format!("{prefix}-{id}-{secret}").into(),
		}
	}

	pub fn hashed(self) -> Self {
		// The hash of the bearer key is stored to mitigate the impact of a read-only compromise.
		// We use SHA-256 as the key needs to be verified performantly for every operation.
		// Unlike with passwords, brute force and rainbow tables are infeasable due to the key length.
		// When hashing the bearer keys, the prefix and key identifier are kept as salt.
		let mut hasher = Sha256::new();
		hasher.update(self.key.as_string());
		let hash = hasher.finalize();
		let hash_hex = format!("{hash:x}").into();

		Self {
			key: hash_hex,
			..self
		}
	}
}

fn random_string(length: usize, pool: &[u8]) -> String {
	let mut rng = rand::thread_rng();
	let string: String = (0..length)
		.map(|_| {
			let i = rng.gen_range(0..pool.len());
			pool[i] as char
		})
		.collect();
	string
}

pub async fn create_grant(
	stmt: &AccessStatementGrant,
	ctx: &Context,
	opt: &Options,
) -> Result<AccessGrant, Error> {
	let base = match &stmt.base {
		Some(base) => base.clone(),
		None => opt.selected_base()?,
	};
	// Allowed to run?
	opt.is_allowed(Action::Edit, ResourceKind::Access, &base)?;
	// Get the transaction.
	let txn = ctx.tx();
	// Clear the cache.
	txn.clear();
	// Read the access definition.
	let ac = match base {
		Base::Root => txn.get_root_access(&stmt.ac).await?,
		Base::Ns => txn.get_ns_access(opt.ns()?, &stmt.ac).await?,
		Base::Db => txn.get_db_access(opt.ns()?, opt.db()?, &stmt.ac).await?,
		_ => {
			return Err(Error::Unimplemented(
				"Managing access methods outside of root, namespace and database levels"
					.to_string(),
			))
		}
	};
	// Verify the access type.
	match &ac.kind {
		AccessType::Jwt(_) => Err(Error::FeatureNotYetImplemented {
			feature: format!("Grants for JWT on {base}"),
		}),
		AccessType::Record(at) => {
			match &stmt.subject {
				Subject::User(_) => {
					return Err(Error::AccessGrantInvalidSubject);
				}
				Subject::Record(_) => {
					// If the grant is being created for a record, a database must be selected.
					if !matches!(base, Base::Db) {
						return Err(Error::DbEmpty);
					}
				}
			};
			// The record access type must allow issuing bearer grants.
			let atb = match &at.bearer {
				Some(bearer) => bearer,
				None => return Err(Error::AccessMethodMismatch),
			};
			// Create a new bearer key.
			let grant = GrantBearer::new(atb.kind.prefix());
			let gr = AccessGrant {
				ac: ac.name.clone(),
				// Unique grant identifier.
				// In the case of bearer grants, the key identifier.
				id: grant.id.clone(),
				// Current time.
				creation: Datetime::default(),
				// Current time plus grant duration. Only if set.
				expiration: ac.duration.grant.map(|d| d + Datetime::default()),
				// The grant is initially not revoked.
				revocation: None,
				// Subject associated with the grant.
				subject: stmt.subject.to_owned(),
				// The contents of the grant.
				grant: Grant::Bearer(grant.clone()),
			};

			// Create the grant.
			// On the very unlikely event of a collision, "put" will return an error.
			let res = match base {
				Base::Db => {
					// Create a hashed version of the grant for storage.
					let mut gr_store = gr.clone();
					gr_store.grant = Grant::Bearer(grant.hashed());
					let key =
						crate::key::database::access::gr::new(opt.ns()?, opt.db()?, &gr.ac, &gr.id);
					txn.get_or_add_ns(opt.ns()?, opt.strict).await?;
					txn.get_or_add_db(opt.ns()?, opt.db()?, opt.strict).await?;
					txn.put(key, &gr_store, None).await
				}
				_ => return Err(Error::AccessLevelMismatch),
			};

			// Check if a collision was found in order to log a specific error on the server.
			// For an access method with a billion grants, this chance is of only one in 295 billion.
			if let Err(Error::TxKeyAlreadyExists) = res {
				error!("A collision was found when attempting to create a new grant. Purging inactive grants is advised")
			}
			res?;

			info!(
				"Access method '{}' was used to create grant '{}' of type '{}' for '{}' by '{}'",
				gr.ac,
				gr.id,
				gr.grant.variant(),
				gr.subject.id(),
				opt.auth.id()
			);

			// Return the original version of the grant.
			// This is the only time the the plaintext key is returned.
			Ok(gr)
		}
		AccessType::Bearer(at) => {
			match &stmt.subject {
				Subject::User(user) => {
					// Grant subject must match access method subject.
					if !matches!(&at.subject, BearerAccessSubject::User) {
						return Err(Error::AccessGrantInvalidSubject);
					}
					// If the grant is being created for a user, the user must exist.
					match base {
						Base::Root => txn.get_root_user(user).await?,
						Base::Ns => txn.get_ns_user(opt.ns()?, user).await?,
						Base::Db => txn.get_db_user(opt.ns()?, opt.db()?, user).await?,
						_ => return Err(Error::Unimplemented(
							"Managing access methods outside of root, namespace and database levels".to_string(),
						)),
					};
				}
				Subject::Record(_) => {
					// If the grant is being created for a record, a database must be selected.
					if !matches!(base, Base::Db) {
						return Err(Error::DbEmpty);
					}
					// Grant subject must match access method subject.
					if !matches!(&at.subject, BearerAccessSubject::Record) {
						return Err(Error::AccessGrantInvalidSubject);
					}
					// A grant can be created for a record that does not exist yet.
				}
			};
			// Create a new bearer key.
			let grant = GrantBearer::new(at.kind.prefix());
			let gr = AccessGrant {
				ac: ac.name.clone(),
				// Unique grant identifier.
				// In the case of bearer grants, the key identifier.
				id: grant.id.clone(),
				// Current time.
				creation: Datetime::default(),
				// Current time plus grant duration. Only if set.
				expiration: ac.duration.grant.map(|d| d + Datetime::default()),
				// The grant is initially not revoked.
				revocation: None,
				// Subject associated with the grant.
				subject: stmt.subject.to_owned(),
				// The contents of the grant.
				grant: Grant::Bearer(grant.clone()),
			};

			// Create the grant.
			// On the very unlikely event of a collision, "put" will return an error.
			// Create a hashed version of the grant for storage.
			let mut gr_store = gr.clone();
			gr_store.grant = Grant::Bearer(grant.hashed());
			let res = match base {
				Base::Root => {
					let key = crate::key::root::access::gr::new(&gr.ac, &gr.id);
					txn.put(key, &gr_store, None).await
				}
				Base::Ns => {
					let key = crate::key::namespace::access::gr::new(opt.ns()?, &gr.ac, &gr.id);
					txn.get_or_add_ns(opt.ns()?, opt.strict).await?;
					txn.put(key, &gr_store, None).await
				}
				Base::Db => {
					let key =
						crate::key::database::access::gr::new(opt.ns()?, opt.db()?, &gr.ac, &gr.id);
					txn.get_or_add_ns(opt.ns()?, opt.strict).await?;
					txn.get_or_add_db(opt.ns()?, opt.db()?, opt.strict).await?;
					txn.put(key, &gr_store, None).await
				}
				_ => {
					return Err(Error::Unimplemented(
						"Managing access methods outside of root, namespace and database levels"
							.to_string(),
					))
				}
			};

			// Check if a collision was found in order to log a specific error on the server.
			// For an access method with a billion grants, this chance is of only one in 295 billion.
			if let Err(Error::TxKeyAlreadyExists) = res {
				error!("A collision was found when attempting to create a new grant. Purging inactive grants is advised")
			}
			res?;

			info!(
				"Access method '{}' was used to create grant '{}' of type '{}' for '{}' by '{}'",
				gr.ac,
				gr.id,
				gr.grant.variant(),
				gr.subject.id(),
				opt.auth.id()
			);

			// Return the original version of the grant.
			// This is the only time the the plaintext key is returned.
			Ok(gr)
		}
	}
}

async fn compute_grant(
	stmt: &AccessStatementGrant,
	ctx: &Context,
	opt: &Options,
	_doc: Option<&CursorDoc>,
) -> Result<Value, Error> {
	let grant = create_grant(stmt, ctx, opt).await?;
	Ok(Value::Object(grant.into()))
}

async fn compute_show(
	stmt: &AccessStatementShow,
	stk: &mut Stk,
	ctx: &Context,
	opt: &Options,
	_doc: Option<&CursorDoc>,
) -> Result<Value, Error> {
	let base = match &stmt.base {
		Some(base) => base.clone(),
		None => opt.selected_base()?,
	};
	// Allowed to run?
	opt.is_allowed(Action::View, ResourceKind::Access, &base)?;
	// Get the transaction.
	let txn = ctx.tx();
	// Clear the cache.
	txn.clear();
	// Check if the access method exists.
	match base {
		Base::Root => txn.get_root_access(&stmt.ac).await?,
		Base::Ns => txn.get_ns_access(opt.ns()?, &stmt.ac).await?,
		Base::Db => txn.get_db_access(opt.ns()?, opt.db()?, &stmt.ac).await?,
		_ => {
			return Err(Error::Unimplemented(
				"Managing access methods outside of root, namespace and database levels"
					.to_string(),
			))
		}
	};

	// Get the grants to show.
	match &stmt.gr {
		Some(gr) => {
			let grant = match base {
				Base::Root => (*txn.get_root_access_grant(&stmt.ac, gr).await?).clone(),
				Base::Ns => (*txn.get_ns_access_grant(opt.ns()?, &stmt.ac, gr).await?).clone(),
				Base::Db => {
					(*txn.get_db_access_grant(opt.ns()?, opt.db()?, &stmt.ac, gr).await?).clone()
				}
				_ => {
					return Err(Error::Unimplemented(
						"Managing access methods outside of root, namespace and database levels"
							.to_string(),
					))
				}
			};

			Ok(Value::Object(grant.redacted().into()))
		}
		None => {
			// Get all grants.
			let grs =
				match base {
					Base::Root => txn.all_root_access_grants(&stmt.ac).await?,
					Base::Ns => txn.all_ns_access_grants(opt.ns()?, &stmt.ac).await?,
					Base::Db => txn.all_db_access_grants(opt.ns()?, opt.db()?, &stmt.ac).await?,
					_ => return Err(Error::Unimplemented(
						"Managing access methods outside of root, namespace and database levels"
							.to_string(),
					)),
				};

			let mut show = Vec::new();
			for gr in grs.iter() {
				// If provided, check if grant matches conditions.
				if let Some(cond) = &stmt.cond {
					// Redact grant before evaluating conditions.
					let redacted_gr = Value::Object(gr.redacted().to_owned().into());
					if !cond
						.compute(
							stk,
							ctx,
							opt,
							Some(&CursorDoc {
								rid: None,
								ir: None,
								doc: redacted_gr.into(),
							}),
						)
						.await?
						.is_truthy()
					{
						// Skip grant if it does not match the provided conditions.
						continue;
					}
				}

				// Store revoked version of the redacted grant.
				show.push(Value::Object(gr.redacted().to_owned().into()));
			}

			Ok(Value::Array(show.into()))
		}
	}
}

pub async fn revoke_grant(
	stmt: &AccessStatementRevoke,
	stk: &mut Stk,
	ctx: &Context,
	opt: &Options,
) -> Result<Value, Error> {
	let base = match &stmt.base {
		Some(base) => base.clone(),
		None => opt.selected_base()?,
	};
	// Allowed to run?
	opt.is_allowed(Action::Edit, ResourceKind::Access, &base)?;
	// Get the transaction
	let txn = ctx.tx();
	// Clear the cache
	txn.clear();
	// Check if the access method exists.
	match base {
		Base::Root => txn.get_root_access(&stmt.ac).await?,
		Base::Ns => txn.get_ns_access(opt.ns()?, &stmt.ac).await?,
		Base::Db => txn.get_db_access(opt.ns()?, opt.db()?, &stmt.ac).await?,
		_ => {
			return Err(Error::Unimplemented(
				"Managing access methods outside of root, namespace and database levels"
					.to_string(),
			))
		}
	};

	// Get the grants to revoke.
	let mut revoked = Vec::new();
	match &stmt.gr {
		Some(gr) => {
			let mut revoke = match base {
				Base::Root => (*txn.get_root_access_grant(&stmt.ac, gr).await?).clone(),
				Base::Ns => (*txn.get_ns_access_grant(opt.ns()?, &stmt.ac, gr).await?).clone(),
				Base::Db => {
					(*txn.get_db_access_grant(opt.ns()?, opt.db()?, &stmt.ac, gr).await?).clone()
				}
				_ => {
					return Err(Error::Unimplemented(
						"Managing access methods outside of root, namespace and database levels"
							.to_string(),
					))
				}
			};
			if revoke.revocation.is_some() {
				return Err(Error::AccessGrantRevoked);
			}
			revoke.revocation = Some(Datetime::default());

			// Revoke the grant.
			match base {
				Base::Root => {
					let key = crate::key::root::access::gr::new(&stmt.ac, gr);
					txn.set(key, &revoke, None).await?;
				}
				Base::Ns => {
					let key = crate::key::namespace::access::gr::new(opt.ns()?, &stmt.ac, gr);
					txn.get_or_add_ns(opt.ns()?, opt.strict).await?;
					txn.set(key, &revoke, None).await?;
				}
				Base::Db => {
					let key =
						crate::key::database::access::gr::new(opt.ns()?, opt.db()?, &stmt.ac, gr);
					txn.get_or_add_ns(opt.ns()?, opt.strict).await?;
					txn.get_or_add_db(opt.ns()?, opt.db()?, opt.strict).await?;
					txn.set(key, &revoke, None).await?;
				}
				_ => {
					return Err(Error::Unimplemented(
						"Managing access methods outside of root, namespace and database levels"
							.to_string(),
					))
				}
			};

			info!(
				"Access method '{}' was used to revoke grant '{}' of type '{}' for '{}' by '{}'",
				revoke.ac,
				revoke.id,
				revoke.grant.variant(),
				revoke.subject.id(),
				opt.auth.id()
			);

			revoked.push(Value::Object(revoke.redacted().into()));
		}
		None => {
			// Get all grants.
			let grs =
				match base {
					Base::Root => txn.all_root_access_grants(&stmt.ac).await?,
					Base::Ns => txn.all_ns_access_grants(opt.ns()?, &stmt.ac).await?,
					Base::Db => txn.all_db_access_grants(opt.ns()?, opt.db()?, &stmt.ac).await?,
					_ => return Err(Error::Unimplemented(
						"Managing access methods outside of root, namespace and database levels"
							.to_string(),
					)),
				};

			for gr in grs.iter() {
				// If the grant is already revoked, it cannot be revoked again.
				if gr.revocation.is_some() {
					continue;
				}

				// If provided, check if grant matches conditions.
				if let Some(cond) = &stmt.cond {
					// Redact grant before evaluating conditions.
					let redacted_gr = Value::Object(gr.redacted().to_owned().into());
					if !cond
						.compute(
							stk,
							ctx,
							opt,
							Some(&CursorDoc {
								rid: None,
								ir: None,
								doc: redacted_gr.into(),
							}),
						)
						.await?
						.is_truthy()
					{
						// Skip grant if it does not match the provided conditions.
						continue;
					}
				}

				let mut gr = gr.clone();
				gr.revocation = Some(Datetime::default());

				// Revoke the grant.
				match base {
					Base::Root => {
						let key = crate::key::root::access::gr::new(&stmt.ac, &gr.id);
						txn.set(key, &gr, None).await?;
					}
					Base::Ns => {
						let key =
							crate::key::namespace::access::gr::new(opt.ns()?, &stmt.ac, &gr.id);
						txn.get_or_add_ns(opt.ns()?, opt.strict).await?;
						txn.set(key, &gr, None).await?;
					}
					Base::Db => {
						let key = crate::key::database::access::gr::new(
							opt.ns()?,
							opt.db()?,
							&stmt.ac,
							&gr.id,
						);
						txn.get_or_add_ns(opt.ns()?, opt.strict).await?;
						txn.get_or_add_db(opt.ns()?, opt.db()?, opt.strict).await?;
						txn.set(key, &gr, None).await?;
					}
					_ => return Err(Error::Unimplemented(
						"Managing access methods outside of root, namespace and database levels"
							.to_string(),
					)),
				};

				info!(
					"Access method '{}' was used to revoke grant '{}' of type '{}' for '{}' by '{}'",
					gr.ac,
					gr.id,
					gr.grant.variant(),
					gr.subject.id(),
					opt.auth.id()
				);

				// Store revoked version of the redacted grant.
				revoked.push(Value::Object(gr.redacted().into()));
			}
		}
	}

	// Return revoked grants.
	Ok(Value::Array(revoked.into()))
}

async fn compute_revoke(
	stmt: &AccessStatementRevoke,
	stk: &mut Stk,
	ctx: &Context,
	opt: &Options,
	_doc: Option<&CursorDoc>,
) -> Result<Value, Error> {
	let revoked = revoke_grant(stmt, stk, ctx, opt).await?;
	Ok(Value::Array(revoked.into()))
}

async fn compute_purge(
	stmt: &AccessStatementPurge,
	ctx: &Context,
	opt: &Options,
	_doc: Option<&CursorDoc>,
) -> Result<Value, Error> {
	let base = match &stmt.base {
		Some(base) => base.clone(),
		None => opt.selected_base()?,
	};
	// Allowed to run?
	opt.is_allowed(Action::Edit, ResourceKind::Access, &base)?;
	// Get the transaction.
	let txn = ctx.tx();
	// Clear the cache.
	txn.clear();
	// Check if the access method exists.
	match base {
		Base::Root => txn.get_root_access(&stmt.ac).await?,
		Base::Ns => txn.get_ns_access(opt.ns()?, &stmt.ac).await?,
		Base::Db => txn.get_db_access(opt.ns()?, opt.db()?, &stmt.ac).await?,
		_ => {
			return Err(Error::Unimplemented(
				"Managing access methods outside of root, namespace and database levels"
					.to_string(),
			))
		}
	};
	// Get all grants to purge.
	let mut purged = Array::default();
	let grs = match base {
		Base::Root => txn.all_root_access_grants(&stmt.ac).await?,
		Base::Ns => txn.all_ns_access_grants(opt.ns()?, &stmt.ac).await?,
		Base::Db => txn.all_db_access_grants(opt.ns()?, opt.db()?, &stmt.ac).await?,
		_ => {
			return Err(Error::Unimplemented(
				"Managing access methods outside of root, namespace and database levels"
					.to_string(),
			))
		}
	};
	for gr in grs.iter() {
		// Determine if the grant should purged based on expiration or revocation.
		let now = Datetime::default();
		// We can convert to unsigned integer as substraction is saturating.
		// Revocation times should never exceed the current time.
		// Grants expired or revoked at a future time will not be purged.
		// Grants expired or revoked at exactly the current second will not be purged.
		let purge_expired = stmt.expired
			&& gr.expiration.as_ref().is_some_and(|exp| {
				                 now.timestamp() >= exp.timestamp() // Prevent saturating when not expired yet.
				                     && (now.timestamp().saturating_sub(exp.timestamp()) as u64) > stmt.grace.secs()
				             });
		let purge_revoked = stmt.revoked
			&& gr.revocation.as_ref().is_some_and(|rev| {
				                 now.timestamp() >= rev.timestamp() // Prevent saturating when not revoked yet.
				                     && (now.timestamp().saturating_sub(rev.timestamp()) as u64) > stmt.grace.secs()
				             });
		// If it should, delete the grant and append the redacted version to the result.
		if purge_expired || purge_revoked {
			match base {
				Base::Root => txn.del(crate::key::root::access::gr::new(&stmt.ac, &gr.id)).await?,
				Base::Ns => {
					txn.del(crate::key::namespace::access::gr::new(opt.ns()?, &stmt.ac, &gr.id))
						.await?
				}
				Base::Db => {
					txn.del(crate::key::database::access::gr::new(
						opt.ns()?,
						opt.db()?,
						&stmt.ac,
						&gr.id,
					))
					.await?
				}
				_ => {
					return Err(Error::Unimplemented(
						"Managing access methods outside of root, namespace and database levels"
							.to_string(),
					))
				}
			};

			info!(
				"Access method '{}' was used to purge grant '{}' of type '{}' for '{}' by '{}'",
				gr.ac,
				gr.id,
				gr.grant.variant(),
				gr.subject.id(),
				opt.auth.id()
			);

			purged = purged + Value::Object(gr.redacted().to_owned().into());
		}
	}

	Ok(Value::Array(purged))
}

impl AccessStatement {
	/// Process this type returning a computed simple Value
	pub(crate) async fn compute(
		&self,
		stk: &mut Stk,
		ctx: &Context,
		opt: &Options,
		_doc: Option<&CursorDoc>,
	) -> Result<Value, Error> {
		match self {
			AccessStatement::Grant(stmt) => compute_grant(stmt, ctx, opt, _doc).await,
			AccessStatement::Show(stmt) => compute_show(stmt, stk, ctx, opt, _doc).await,
			AccessStatement::Revoke(stmt) => compute_revoke(stmt, stk, ctx, opt, _doc).await,
			AccessStatement::Purge(stmt) => compute_purge(stmt, ctx, opt, _doc).await,
		}
	}
}

impl Display for AccessStatement {
	fn fmt(&self, f: &mut Formatter) -> fmt::Result {
		match self {
			Self::Grant(stmt) => {
				write!(f, "ACCESS {}", stmt.ac)?;
				if let Some(ref v) = stmt.base {
					write!(f, " ON {v}")?;
				}
				write!(f, " GRANT")?;
				match stmt.subject {
					Subject::User(_) => write!(f, " FOR USER {}", stmt.subject.id())?,
					Subject::Record(_) => write!(f, " FOR RECORD {}", stmt.subject.id())?,
				}
				Ok(())
			}
			Self::Show(stmt) => {
				write!(f, "ACCESS {}", stmt.ac)?;
				if let Some(ref v) = stmt.base {
					write!(f, " ON {v}")?;
				}
				write!(f, " SHOW")?;
				match &stmt.gr {
					Some(v) => write!(f, " GRANT {v}")?,
					None => match &stmt.cond {
						Some(v) => write!(f, " {v}")?,
						None => write!(f, " ALL")?,
					},
				};
				Ok(())
			}
			Self::Revoke(stmt) => {
				write!(f, "ACCESS {}", stmt.ac)?;
				if let Some(ref v) = stmt.base {
					write!(f, " ON {v}")?;
				}
				write!(f, " REVOKE")?;
				match &stmt.gr {
					Some(v) => write!(f, " GRANT {v}")?,
					None => match &stmt.cond {
						Some(v) => write!(f, " {v}")?,
						None => write!(f, " ALL")?,
					},
				};
				Ok(())
			}
			Self::Purge(stmt) => {
				write!(f, "ACCESS {}", stmt.ac)?;
				if let Some(ref v) = stmt.base {
					write!(f, " ON {v}")?;
				}
				write!(f, " PURGE")?;
				match (stmt.expired, stmt.revoked) {
					(true, false) => write!(f, " EXPIRED")?,
					(false, true) => write!(f, " REVOKED")?,
					(true, true) => write!(f, " EXPIRED, REVOKED")?,
					// This case should not parse.
					(false, false) => write!(f, " NONE")?,
				};
				if !stmt.grace.is_zero() {
					write!(f, " FOR {}", stmt.grace)?;
				}
				Ok(())
			}
		}
	}
}