surrealdb_core/sql/statements/define/
user.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
use crate::ctx::Context;
use crate::dbs::Options;
use crate::doc::CursorDoc;
use crate::err::Error;
use crate::iam::{Action, ResourceKind};
use crate::sql::statements::info::InfoStructure;
use crate::sql::{
	escape::quote_str, fmt::Fmt, user::UserDuration, Base, Duration, Ident, Strand, Value,
};
use argon2::{
	password_hash::{PasswordHasher, SaltString},
	Argon2,
};
use derive::Store;
use rand::{distributions::Alphanumeric, rngs::OsRng, Rng};
use revision::revisioned;
use serde::{Deserialize, Serialize};
use std::fmt::{self, Display};

#[revisioned(revision = 4)]
#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Store, Hash)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
#[non_exhaustive]
pub struct DefineUserStatement {
	pub name: Ident,
	pub base: Base,
	pub hash: String,
	pub code: String,
	pub roles: Vec<Ident>,
	#[revision(start = 3)]
	pub duration: UserDuration,
	pub comment: Option<Strand>,
	#[revision(start = 2)]
	pub if_not_exists: bool,
	#[revision(start = 4)]
	pub overwrite: bool,
}

impl From<(Base, &str, &str, &str)> for DefineUserStatement {
	fn from((base, user, pass, role): (Base, &str, &str, &str)) -> Self {
		DefineUserStatement {
			base,
			name: user.into(),
			hash: Argon2::default()
				.hash_password(pass.as_ref(), &SaltString::generate(&mut OsRng))
				.unwrap()
				.to_string(),
			code: rand::thread_rng()
				.sample_iter(&Alphanumeric)
				.take(128)
				.map(char::from)
				.collect::<String>(),
			roles: vec![role.into()],
			duration: UserDuration::default(),
			comment: None,
			if_not_exists: false,
			overwrite: false,
		}
	}
}

impl DefineUserStatement {
	pub(crate) fn from_parsed_values(
		name: Ident,
		base: Base,
		roles: Vec<Ident>,
		duration: UserDuration,
	) -> Self {
		DefineUserStatement {
			name,
			base,
			roles,
			duration,
			code: rand::thread_rng()
				.sample_iter(&Alphanumeric)
				.take(128)
				.map(char::from)
				.collect::<String>(),
			..Default::default()
		}
	}

	pub(crate) fn set_password(&mut self, password: &str) {
		self.hash = Argon2::default()
			.hash_password(password.as_bytes(), &SaltString::generate(&mut OsRng))
			.unwrap()
			.to_string()
	}

	pub(crate) fn set_passhash(&mut self, passhash: String) {
		self.hash = passhash;
	}

	pub(crate) fn set_token_duration(&mut self, duration: Option<Duration>) {
		self.duration.token = duration;
	}

	pub(crate) fn set_session_duration(&mut self, duration: Option<Duration>) {
		self.duration.session = duration;
	}

	/// Process this type returning a computed simple Value
	pub(crate) async fn compute(
		&self,
		ctx: &Context,
		opt: &Options,
		_doc: Option<&CursorDoc>,
	) -> Result<Value, Error> {
		// Allowed to run?
		opt.is_allowed(Action::Edit, ResourceKind::Actor, &self.base)?;
		// Check the statement type
		match self.base {
			Base::Root => {
				// Fetch the transaction
				let txn = ctx.tx();
				// Check if the definition exists
				if txn.get_root_user(&self.name).await.is_ok() {
					if self.if_not_exists {
						return Ok(Value::None);
					} else if !self.overwrite {
						return Err(Error::UserRootAlreadyExists {
							value: self.name.to_string(),
						});
					}
				}
				// Process the statement
				let key = crate::key::root::us::new(&self.name);
				txn.set(
					key,
					DefineUserStatement {
						// Don't persist the `IF NOT EXISTS` clause to schema
						if_not_exists: false,
						overwrite: false,
						..self.clone()
					},
					None,
				)
				.await?;
				// Clear the cache
				txn.clear();
				// Ok all good
				Ok(Value::None)
			}
			Base::Ns => {
				// Fetch the transaction
				let txn = ctx.tx();
				// Check if the definition exists
				if txn.get_ns_user(opt.ns()?, &self.name).await.is_ok() {
					if self.if_not_exists {
						return Ok(Value::None);
					} else if !self.overwrite {
						return Err(Error::UserNsAlreadyExists {
							value: self.name.to_string(),
							ns: opt.ns()?.into(),
						});
					}
				}
				// Process the statement
				let key = crate::key::namespace::us::new(opt.ns()?, &self.name);
				txn.get_or_add_ns(opt.ns()?, opt.strict).await?;
				txn.set(
					key,
					DefineUserStatement {
						// Don't persist the `IF NOT EXISTS` clause to schema
						if_not_exists: false,
						overwrite: false,
						..self.clone()
					},
					None,
				)
				.await?;
				// Clear the cache
				txn.clear();
				// Ok all good
				Ok(Value::None)
			}
			Base::Db => {
				// Fetch the transaction
				let txn = ctx.tx();
				// Check if the definition exists
				if txn.get_db_user(opt.ns()?, opt.db()?, &self.name).await.is_ok() {
					if self.if_not_exists {
						return Ok(Value::None);
					} else if !self.overwrite {
						return Err(Error::UserDbAlreadyExists {
							value: self.name.to_string(),
							ns: opt.ns()?.into(),
							db: opt.db()?.into(),
						});
					}
				}
				// Process the statement
				let key = crate::key::database::us::new(opt.ns()?, opt.db()?, &self.name);
				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,
					DefineUserStatement {
						// Don't persist the `IF NOT EXISTS` clause to schema
						if_not_exists: false,
						overwrite: false,
						..self.clone()
					},
					None,
				)
				.await?;
				// Clear the cache
				txn.clear();
				// Ok all good
				Ok(Value::None)
			}
			// Other levels are not supported
			_ => Err(Error::InvalidLevel(self.base.to_string())),
		}
	}
}

impl Display for DefineUserStatement {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		write!(f, "DEFINE USER")?;
		if self.if_not_exists {
			write!(f, " IF NOT EXISTS")?
		}
		if self.overwrite {
			write!(f, " OVERWRITE")?
		}
		write!(
			f,
			" {} ON {} PASSHASH {} ROLES {}",
			self.name,
			self.base,
			quote_str(&self.hash),
			Fmt::comma_separated(
				&self.roles.iter().map(|r| r.to_string().to_uppercase()).collect::<Vec<String>>()
			),
		)?;
		// Always print relevant durations so defaults can be changed in the future
		// If default values were not printed, exports would not be forward compatible
		// None values need to be printed, as they are different from the default values
		write!(f, " DURATION")?;
		write!(
			f,
			" FOR TOKEN {},",
			match self.duration.token {
				Some(dur) => format!("{}", dur),
				None => "NONE".to_string(),
			}
		)?;
		write!(
			f,
			" FOR SESSION {}",
			match self.duration.session {
				Some(dur) => format!("{}", dur),
				None => "NONE".to_string(),
			}
		)?;
		if let Some(ref v) = self.comment {
			write!(f, " COMMENT {v}")?
		}
		Ok(())
	}
}

impl InfoStructure for DefineUserStatement {
	fn structure(self) -> Value {
		Value::from(map! {
			"name".to_string() => self.name.structure(),
			"base".to_string() => self.base.structure(),
			"hash".to_string() => self.hash.into(),
			"roles".to_string() => self.roles.into_iter().map(Ident::structure).collect(),
			"duration".to_string() => Value::from(map! {
				"token".to_string() => self.duration.token.into(),
				"session".to_string() => self.duration.session.into(),
			}),
			"comment".to_string(), if let Some(v) = self.comment => v.into(),
		})
	}
}