surrealdb-core 3.2.0

A scalable, distributed, collaborative, document-graph database, for the realtime web
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
497
498
499
500
501
502
503
504
505
506
507
508
use anyhow::{Result, bail};
use rand::distr::{Alphanumeric, SampleString};
use reblessive::tree::Stk;
use surrealdb_strand::Strand;
use surrealdb_types::{SqlFormat, ToSql};

use super::DefineKind;
use crate::catalog::providers::{AuthorisationProvider, NamespaceProvider};
use crate::catalog::{self, AccessDefinition};
use crate::ctx::FrozenContext;
use crate::dbs::Options;
use crate::doc::CursorDoc;
use crate::err::Error;
use crate::expr::access::AccessDuration;
use crate::expr::access_type::{
	BearerAccess, BearerAccessSubject, BearerAccessType, JwtAccessIssue, JwtAccessVerify,
	JwtAccessVerifyJwks, JwtAccessVerifyKey,
};
use crate::expr::parameterize::expr_to_ident;
use crate::expr::{
	AccessType, Algorithm, Base, Expr, FlowResultExt, Idiom, JwtAccess, Literal, RecordAccess,
};
use crate::iam::{Action, ResourceKind};
use crate::val::{self, Duration, Value};

#[derive(Clone, Debug, Eq, PartialEq, Hash)]
pub(crate) struct DefineAccessStatement {
	pub kind: DefineKind,
	pub name: Expr,
	pub base: Base,
	pub access_type: AccessType,
	pub authenticate: Option<Expr>,
	pub duration: AccessDuration,
	pub comment: Expr,
}

impl Default for DefineAccessStatement {
	fn default() -> Self {
		Self {
			kind: DefineKind::Default,
			name: Expr::Literal(Literal::None),
			base: Base::Root,
			access_type: AccessType::default(),
			authenticate: None,
			duration: AccessDuration::default(),
			comment: Expr::Literal(Literal::None),
		}
	}
}

impl DefineAccessStatement {
	/// Generate a random key to be used to sign session tokens
	/// This key will be used to sign tokens issued with this access method
	/// This value is used by default in every access method other than JWT
	pub(crate) fn random_key() -> String {
		Alphanumeric.sample_string(&mut rand::rng(), 128)
	}

	pub fn from_definition(base: Base, def: &AccessDefinition) -> Self {
		fn convert_algorithm(access: catalog::Algorithm) -> Algorithm {
			match &access {
				catalog::Algorithm::EdDSA => Algorithm::EdDSA,
				catalog::Algorithm::Es256 => Algorithm::Es256,
				catalog::Algorithm::Es384 => Algorithm::Es384,
				catalog::Algorithm::Es512 => Algorithm::Es512,
				catalog::Algorithm::Hs256 => Algorithm::Hs256,
				catalog::Algorithm::Hs384 => Algorithm::Hs384,
				catalog::Algorithm::Hs512 => Algorithm::Hs512,
				catalog::Algorithm::Ps256 => Algorithm::Ps256,
				catalog::Algorithm::Ps384 => Algorithm::Ps384,
				catalog::Algorithm::Ps512 => Algorithm::Ps512,
				catalog::Algorithm::Rs256 => Algorithm::Rs256,
				catalog::Algorithm::Rs384 => Algorithm::Rs384,
				catalog::Algorithm::Rs512 => Algorithm::Rs512,
			}
		}

		fn convert_jwt_access(access: &catalog::JwtAccess) -> JwtAccess {
			JwtAccess {
				verify: match &access.verify {
					catalog::JwtAccessVerify::Key(k) => JwtAccessVerify::Key(JwtAccessVerifyKey {
						alg: convert_algorithm(k.alg),
						key: Expr::Literal(Literal::String(k.key.as_str().into())),
					}),
					catalog::JwtAccessVerify::Jwks(j) => {
						JwtAccessVerify::Jwks(JwtAccessVerifyJwks {
							url: Expr::Literal(Literal::String(j.url.as_str().into())),
						})
					}
				},
				issue: access.issue.as_ref().map(|x| JwtAccessIssue {
					alg: convert_algorithm(x.alg),
					key: Expr::Literal(Literal::String(x.key.as_str().into())),
				}),
			}
		}

		fn convert_bearer_access(access: &catalog::BearerAccess) -> BearerAccess {
			BearerAccess {
				kind: match access.kind {
					catalog::BearerAccessType::Bearer => BearerAccessType::Bearer,
					catalog::BearerAccessType::Refresh => BearerAccessType::Refresh,
				},
				subject: match access.subject {
					catalog::BearerAccessSubject::Record => BearerAccessSubject::Record,
					catalog::BearerAccessSubject::User => BearerAccessSubject::User,
				},
				jwt: convert_jwt_access(&access.jwt),
			}
		}

		DefineAccessStatement {
			kind: DefineKind::Default,
			base,
			name: Expr::Idiom(Idiom::field(def.name.clone())),
			duration: AccessDuration {
				grant: def
					.grant_duration
					.map(|v| Expr::Literal(Literal::Duration(val::Duration(v))))
					.unwrap_or(Expr::Literal(Literal::None)),
				token: def
					.token_duration
					.map(|v| Expr::Literal(Literal::Duration(val::Duration(v))))
					.unwrap_or(Expr::Literal(Literal::None)),
				session: def
					.session_duration
					.map(|v| Expr::Literal(Literal::Duration(val::Duration(v))))
					.unwrap_or(Expr::Literal(Literal::None)),
			},
			comment: def
				.comment
				.clone()
				.map(|x| Expr::Literal(Literal::String(x.into())))
				.unwrap_or(Expr::Literal(Literal::None)),
			authenticate: def.authenticate.clone(),
			access_type: match &def.access_type {
				catalog::AccessType::Record(record_access) => {
					AccessType::Record(Box::new(RecordAccess {
						signup: record_access.signup.clone(),
						signin: record_access.signin.clone(),
						jwt: convert_jwt_access(&record_access.jwt),
						bearer: record_access.bearer.as_ref().map(convert_bearer_access),
					}))
				}
				catalog::AccessType::Jwt(jwt_access) => {
					AccessType::Jwt(convert_jwt_access(jwt_access))
				}
				catalog::AccessType::Bearer(bearer_access) => {
					AccessType::Bearer(convert_bearer_access(bearer_access))
				}
			},
		}
	}

	async fn to_definition(
		&self,
		stk: &mut Stk,
		ctx: &FrozenContext,
		opt: &Options,
		doc: Option<&CursorDoc>,
	) -> Result<AccessDefinition> {
		fn convert_algorithm(access: Algorithm) -> catalog::Algorithm {
			match &access {
				Algorithm::EdDSA => catalog::Algorithm::EdDSA,
				Algorithm::Es256 => catalog::Algorithm::Es256,
				Algorithm::Es384 => catalog::Algorithm::Es384,
				Algorithm::Es512 => catalog::Algorithm::Es512,
				Algorithm::Hs256 => catalog::Algorithm::Hs256,
				Algorithm::Hs384 => catalog::Algorithm::Hs384,
				Algorithm::Hs512 => catalog::Algorithm::Hs512,
				Algorithm::Ps256 => catalog::Algorithm::Ps256,
				Algorithm::Ps384 => catalog::Algorithm::Ps384,
				Algorithm::Ps512 => catalog::Algorithm::Ps512,
				Algorithm::Rs256 => catalog::Algorithm::Rs256,
				Algorithm::Rs384 => catalog::Algorithm::Rs384,
				Algorithm::Rs512 => catalog::Algorithm::Rs512,
			}
		}

		async fn convert_jwt_access(
			stk: &mut Stk,
			ctx: &FrozenContext,
			opt: &Options,
			doc: Option<&CursorDoc>,
			access: &JwtAccess,
		) -> Result<catalog::JwtAccess> {
			let verify = match &access.verify {
				JwtAccessVerify::Key(k) => {
					catalog::JwtAccessVerify::Key(catalog::JwtAccessVerifyKey {
						alg: convert_algorithm(k.alg),
						key: stk
							.run(|stk| k.key.compute(stk, ctx, opt, doc))
							.await
							.catch_return()?
							.coerce_to::<String>()?,
					})
				}
				JwtAccessVerify::Jwks(j) => {
					catalog::JwtAccessVerify::Jwks(catalog::JwtAccessVerifyJwks {
						url: stk
							.run(|stk| j.url.compute(stk, ctx, opt, doc))
							.await
							.catch_return()?
							.cast_to()?,
					})
				}
			};

			let issue = map_opt!(x as &access.issue => catalog::JwtAccessIssue {
				alg: convert_algorithm(x.alg),
				key: stk.run(|stk| x.key.compute(stk, ctx, opt, doc)).await.catch_return()?.cast_to()?,
			});

			// Validate symmetric algorithm key consistency
			if let (catalog::JwtAccessVerify::Key(ver), Some(iss)) = (&verify, &issue)
				&& ver.alg.is_symmetric()
				&& ver.key != iss.key
			{
				bail!(Error::Query {
					message: format!(
						"Symmetric algorithm {} requires the same key for signing and verification. \
						Use the same key value for both KEY and WITH ISSUER KEY clauses, or omit WITH ISSUER KEY.",
						ver.alg
					)
				});
			}

			Ok(catalog::JwtAccess {
				verify,
				issue,
			})
		}

		async fn convert_bearer_access(
			stk: &mut Stk,
			ctx: &FrozenContext,
			opt: &Options,
			doc: Option<&CursorDoc>,
			access: &BearerAccess,
		) -> Result<catalog::BearerAccess> {
			Ok(catalog::BearerAccess {
				kind: match access.kind {
					BearerAccessType::Bearer => catalog::BearerAccessType::Bearer,
					BearerAccessType::Refresh => catalog::BearerAccessType::Refresh,
				},
				subject: match access.subject {
					BearerAccessSubject::Record => catalog::BearerAccessSubject::Record,
					BearerAccessSubject::User => catalog::BearerAccessSubject::User,
				},
				jwt: convert_jwt_access(stk, ctx, opt, doc, &access.jwt).await?,
			})
		}

		let grant_duration = stk
			.run(|stk| self.duration.grant.compute(stk, ctx, opt, doc))
			.await
			.catch_return()?
			.cast_to::<Option<Duration>>()?
			.map(|x| x.0);
		let token_duration = stk
			.run(|stk| self.duration.token.compute(stk, ctx, opt, doc))
			.await
			.catch_return()?
			.cast_to::<Option<Duration>>()?
			.map(|x| x.0);
		// Record-access tokens authenticate end-users (signin/signup) and may be
		// passed to third parties, so they MUST expire. The parser used to
		// reject `DURATION FOR TOKEN NONE` statically, but parameterized
		// durations are only known after `compute`, so the check moved here.
		if matches!(&self.access_type, AccessType::Record(_)) && token_duration.is_none() {
			bail!(Error::AccessRecordTokenDurationRequired);
		}
		let session_duration = stk
			.run(|stk| self.duration.session.compute(stk, ctx, opt, doc))
			.await
			.catch_return()?
			.cast_to::<Option<Duration>>()?
			.map(|x| x.0);
		let comment = stk
			.run(|stk| self.comment.compute(stk, ctx, opt, doc))
			.await
			.catch_return()?
			.cast_to()?;

		Ok(AccessDefinition {
			name: expr_to_ident(stk, ctx, opt, doc, &self.name, "access name").await?.into(),
			base: self.base.into(),
			grant_duration,
			token_duration,
			session_duration,
			comment,
			authenticate: self.authenticate.clone(),
			access_type: match &self.access_type {
				AccessType::Record(record_access) => {
					catalog::AccessType::Record(catalog::RecordAccess {
						signup: record_access.signup.clone(),
						signin: record_access.signin.clone(),
						jwt: convert_jwt_access(stk, ctx, opt, doc, &record_access.jwt).await?,
						bearer: map_opt!(x as &record_access.bearer => convert_bearer_access(stk, ctx, opt, doc, x).await?),
					})
				}
				AccessType::Jwt(jwt_access) => catalog::AccessType::Jwt(
					convert_jwt_access(stk, ctx, opt, doc, jwt_access).await?,
				),
				AccessType::Bearer(bearer_access) => catalog::AccessType::Bearer(
					convert_bearer_access(stk, ctx, opt, doc, bearer_access).await?,
				),
			},
		})
	}
}

impl DefineAccessStatement {
	/// Returns true if the access definition uses ES512 in any JWT component.
	fn uses_es512(definition: &AccessDefinition) -> bool {
		fn jwt_uses_es512(jwt: &catalog::JwtAccess) -> bool {
			if let catalog::JwtAccessVerify::Key(ref ver) = jwt.verify
				&& matches!(ver.alg, catalog::Algorithm::Es512)
			{
				return true;
			}
			if let Some(ref iss) = jwt.issue
				&& matches!(iss.alg, catalog::Algorithm::Es512)
			{
				return true;
			}
			false
		}

		match &definition.access_type {
			catalog::AccessType::Jwt(jwt) => jwt_uses_es512(jwt),
			catalog::AccessType::Record(rec) => {
				jwt_uses_es512(&rec.jwt)
					|| rec.bearer.as_ref().is_some_and(|b| jwt_uses_es512(&b.jwt))
			}
			catalog::AccessType::Bearer(bearer) => jwt_uses_es512(&bearer.jwt),
		}
	}

	/// Check if the access definition uses ES512, which is not currently supported.
	/// This should only be called for new definitions (not during import/restore or
	/// overwrite of an existing ES512 definition).
	fn reject_es512(definition: &AccessDefinition) -> Result<()> {
		if Self::uses_es512(definition) {
			bail!(Error::AccessUnsupportedAlgorithm);
		}
		Ok(())
	}

	/// Process this type returning a computed simple Value
	#[instrument(level = "trace", name = "DefineAccessStatement::compute", skip_all)]
	pub(crate) async fn compute(
		&self,
		stk: &mut Stk,
		ctx: &FrozenContext,
		opt: &Options,
		doc: Option<&CursorDoc>,
	) -> Result<Value> {
		// Allowed to run?
		ctx.is_allowed(opt, Action::Edit, ResourceKind::Actor, self.base)?;
		// Compute the definition
		let definition = self.to_definition(stk, ctx, opt, doc).await?;
		// Check the statement type
		match &self.base {
			Base::Root => {
				// Fetch the transaction
				let txn = ctx.tx();
				// Check if access method already exists
				let mut existing_uses_es512 = false;
				if let Some(access) = txn.get_root_access(definition.name.as_str(), None).await? {
					existing_uses_es512 = Self::uses_es512(&access);
					match self.kind {
						DefineKind::Default => {
							if !opt.import {
								bail!(Error::AccessRootAlreadyExists {
									ac: access.name.to_string(),
								});
							}
						}
						DefineKind::Overwrite => {}
						DefineKind::IfNotExists => return Ok(Value::None),
					}
				}
				// Reject ES512 for new definitions (allow during import/restore and
				// overwrite of an existing ES512 definition)
				if !(opt.import || (existing_uses_es512 && self.kind == DefineKind::Overwrite)) {
					Self::reject_es512(&definition)?;
				}
				// Process the statement
				let key = crate::key::root::ac::new(definition.name.as_str());
				txn.set(&key, &definition).await?;
				// Clear the cache
				txn.clear_cache();
				// Ok all good
				Ok(Value::None)
			}
			Base::Ns => {
				// Fetch the transaction
				let txn = ctx.tx();
				// Check if the definition exists
				let ns = ctx.get_ns_id(opt).await?;
				let mut existing_uses_es512 = false;
				if let Some(access) = txn.get_ns_access(ns, definition.name.as_str(), None).await? {
					existing_uses_es512 = Self::uses_es512(&access);
					match self.kind {
						DefineKind::Default => {
							if !opt.import {
								bail!(Error::AccessNsAlreadyExists {
									ns: opt.ns()?.to_string(),
									ac: access.name.to_string(),
								});
							}
						}
						DefineKind::Overwrite => {}
						DefineKind::IfNotExists => return Ok(Value::None),
					}
				}
				// Reject ES512 for new definitions (allow during import/restore and
				// overwrite of an existing ES512 definition)
				if !(opt.import || (existing_uses_es512 && self.kind == DefineKind::Overwrite)) {
					Self::reject_es512(&definition)?;
				}
				// Process the statement
				let key = crate::key::namespace::ac::new(ns, definition.name.as_str());
				txn.get_or_add_ns(Some(ctx), opt.ns()?).await?;
				txn.set(&key, &definition).await?;
				// Clear the cache
				txn.clear_cache();
				// Ok all good
				Ok(Value::None)
			}
			Base::Db => {
				// Fetch the transaction
				let txn = ctx.tx();
				// Check if the definition exists
				let (ns, db) = ctx.get_ns_db_ids(opt).await?;
				let mut existing_uses_es512 = false;
				if let Some(access) =
					txn.get_db_access(ns, db, definition.name.as_str(), None).await?
				{
					existing_uses_es512 = Self::uses_es512(&access);
					match self.kind {
						DefineKind::Default => {
							if !opt.import {
								bail!(Error::AccessDbAlreadyExists {
									ns: opt.ns()?.to_string(),
									db: opt.db()?.to_string(),
									ac: access.name.to_string(),
								});
							}
						}
						DefineKind::Overwrite => {}
						DefineKind::IfNotExists => return Ok(Value::None),
					}
				}
				// Reject ES512 for new definitions (allow during import/restore and
				// overwrite of an existing ES512 definition)
				if !(opt.import || (existing_uses_es512 && self.kind == DefineKind::Overwrite)) {
					Self::reject_es512(&definition)?;
				}
				// Process the statement
				let key = crate::key::database::ac::new(ns, db, definition.name.as_str());
				txn.set(&key, &definition).await?;
				// Clear the cache
				txn.clear_cache();
				// Ok all good
				Ok(Value::None)
			}
		}
	}

	/// Remove information from the access definition which should not be displayed.
	pub fn redact(mut self) -> Self {
		fn redact_jwt_access(acc: &mut JwtAccess) {
			if let JwtAccessVerify::Key(ref mut v) = acc.verify
				&& v.alg.is_symmetric()
			{
				v.key = Expr::Literal(Literal::String(Strand::new_static("[REDACTED]")));
			}
			if let Some(ref mut s) = acc.issue {
				s.key = Expr::Literal(Literal::String(Strand::new_static("[REDACTED]")));
			}
		}

		match self.access_type {
			AccessType::Jwt(ref mut key) => {
				redact_jwt_access(key);
			}
			AccessType::Bearer(ref mut b) => {
				redact_jwt_access(&mut b.jwt);
			}
			AccessType::Record(ref mut r) => {
				redact_jwt_access(&mut r.jwt);
				if let Some(ref mut b) = r.bearer {
					redact_jwt_access(&mut b.jwt);
				}
			}
		}
		self
	}
}

impl ToSql for DefineAccessStatement {
	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
		let stmt: crate::sql::statements::define::DefineAccessStatement = self.clone().into();
		stmt.fmt_sql(f, fmt);
	}
}