1mod db;
5mod oidc;
6mod protocol;
7mod resource;
8mod two_factor;
9
10pub use db::{TEST_DATABASE_URL, migrated_db, test_db};
11use http::header::{ACCEPT_LANGUAGE, CONTENT_TYPE, COOKIE};
12pub use oidc::{FakeAccount, FakeProvider, provider_buttons};
13pub use protocol::{
14 Bell, BellNotification, CellEdit, ChartData, ChartSeries, CreateOptionLink, DetailEntry,
15 DisabledAction, EmptyReason, EmptyTable, ErrorKind, FilterOption, Group, IgnoredFilter,
16 IgnoredReason, ImpersonationBanner, ImportError, ImportRefusal, LanguageChoice, NavGroup,
17 PageFilterBar, Picked, PickerColumn, RecordNavLink, RecordTableData, Row, RowActions,
18 SearchGroup, SearchResult, Section, StatTile, SummaryFigure, Tab, TabLink, WizardStep,
19 action_badge, action_label, action_submits, action_tooltip, area_back_link, bell, body_bytes,
20 body_string, charts, column_picker, columns, confirms_first, cookie_header,
21 create_option_links, declined_message, detail_entries, dirty_form, disabled_actions,
22 document_title, empty_table, external_sign_out, field_error, field_error_message,
23 filter_options, find_href_with, form_body, groups, ignored_filters, impersonate_buttons,
24 impersonation_banner, import_columns, import_errors, import_refusal, inline_scripts,
25 input_value, input_values, language_choices, multipart_body, nav_badge, nav_groups, nav_links,
26 notification, options_url, page_direction, page_filter_bar, page_language, page_title, picked,
27 posts_picking, record_navigation, record_tables, refreshes_to, response_cookies,
28 rich_text_values, robots, row_actions, row_keys, rows, search_box, search_results, sections,
29 selects_matching, session_cookie_value, set_cookie_header, skip_link_target, sortable_columns,
30 stale_form, stats, summaries, tab_links, tabs, tenant_page_link, trail, unscoped_headers,
31 widgets, wizard_steps,
32};
33pub use resource::{FieldOf, Reply, ResourceClient, Submission};
34use tablo_core::{
35 DeclarationError, MountError, Panel, PanelHandle, PanelUser, Resource, RouterBuilderPanelExt,
36 auth::session_cookie,
37};
38use topcoat::router::{Body, Router, RouterBuilderDiscoverExt};
39pub use two_factor::{
40 authenticator_code, authenticator_code_at, intent_skips_validation, now, recovery_codes,
41 two_factor_secret, two_factor_state,
42};
43
44pub fn mount(db: toasty::Db, panel: Panel) -> topcoat::Result<Router> {
51 mount_with_handle(db, panel).map(|(router, _)| router)
52}
53
54pub fn mount_with_handle(db: toasty::Db, panel: Panel) -> topcoat::Result<(Router, PanelHandle)> {
61 let mut builder = Router::builder().discover().with(db);
62 let handle = builder.panel(panel)?;
63 Ok((builder.build(), handle))
64}
65
66pub fn refusal<T>(mounted: topcoat::Result<T>) -> Vec<DeclarationError> {
85 let Err(error) = mounted else {
86 panic!("the panel must not mount");
87 };
88 error
89 .downcast_ref::<MountError>()
90 .unwrap_or_else(|| panic!("a declaration mistake refuses the panel, got {error}"))
91 .errors()
92 .to_vec()
93}
94
95#[derive(Clone)]
98pub struct TestClient<'a> {
99 router: &'a Router,
100 cookies: Vec<(String, String)>,
101 tenant: Option<tablo_core::TenantId>,
102 panel: Option<PanelHandle>,
103 language: Option<String>,
104 host: Option<String>,
105}
106
107impl<'a> TestClient<'a> {
108 pub fn new(router: &'a Router) -> Self {
109 Self {
110 router,
111 cookies: Vec::new(),
112 tenant: None,
113 panel: None,
114 language: None,
115 host: None,
116 }
117 }
118
119 pub fn panel(&self, panel: &PanelHandle) -> Self {
135 let mut client = self.clone();
136 client.panel = Some(panel.clone());
137 client
138 }
139
140 pub fn resource<R: Resource>(&self) -> ResourceClient<'_, 'a, R> {
146 let panel = self
147 .panel
148 .as_ref()
149 .expect("set the panel with `TestClient::panel` before `resource`");
150 ResourceClient::new(self, panel)
151 }
152
153 pub fn cookie(&self, name: &str, value: &str) -> Self {
156 self.with_cookies(&[(name.to_string(), value.to_string())])
157 }
158
159 pub fn cookies(&self, cookies: &[(String, String)]) -> Self {
162 self.with_cookies(cookies)
163 }
164
165 fn with_cookies(&self, cookies: &[(String, String)]) -> Self {
166 let mut client = self.clone();
167 for (name, value) in cookies {
168 match client.cookies.iter_mut().find(|(kept, _)| kept == name) {
169 Some(existing) => existing.1 = value.clone(),
170 None => client.cookies.push((name.clone(), value.clone())),
171 }
172 }
173 client
174 }
175
176 pub fn language(&self, languages: &str) -> Self {
179 let mut client = self.clone();
180 client.language = Some(languages.to_string());
181 client
182 }
183
184 pub fn host(&self, host: &str) -> Self {
187 let mut client = self.clone();
188 client.host = Some(host.to_string());
189 client
190 }
191
192 pub fn csrf(&self, token: &str) -> Self {
194 self.cookie(tablo_core::csrf::COOKIE_NAME, token)
195 }
196
197 pub async fn sign_in(&self, db: &toasty::Db, panel: &str, user: &impl PanelUser) -> Self {
222 let token = tablo_core::auth::mint_session(&mut db.clone(), panel, user)
223 .await
224 .expect("record the test session");
225 self.cookie(&session_cookie(panel), &token)
226 }
227
228 pub async fn log_in(
240 &self,
241 panel: &str,
242 email: &str,
243 password: &str,
244 next: &str,
245 ) -> (Self, http::Response<Body>) {
246 let url = format!("/{panel}/login");
247 let page = self.get(&url).await;
248 let cookies = response_cookies(&page);
249 let html = body_string(page).await;
250 let csrf = input_value(&html, "csrf_token")
251 .unwrap_or_else(|| panic!("the login page embeds a csrf_token input: {html}"));
252 let body = form_body(&[
253 ("email", email),
254 ("password", password),
255 ("next", next),
256 ("csrf_token", &csrf),
257 ]);
258 let client = self.cookies(&cookies);
259 let response = client.post_form(&url, body).await;
260 let session = response_cookies(&response);
261 (client.cookies(&session), response)
262 }
263
264 pub fn tenant(&self, tenant: tablo_core::TenantId) -> Self {
269 let mut client = self.clone();
270 client.tenant = Some(tenant);
271 client
272 }
273
274 pub async fn get(&self, uri: &str) -> http::Response<Body> {
275 self.send(self.request(http::Method::GET, uri)).await
276 }
277
278 pub async fn head(&self, uri: &str) -> http::Response<Body> {
279 self.send(self.request(http::Method::HEAD, uri)).await
280 }
281
282 pub async fn post_form(&self, uri: &str, body: String) -> http::Response<Body> {
283 self.post(
284 uri,
285 http::HeaderValue::from_static("application/x-www-form-urlencoded"),
286 body,
287 )
288 .await
289 }
290
291 pub async fn submit(&self, uri: &str, body: &str) -> http::Response<Body> {
295 let token = self.csrf_token();
296 let field = form_body(&[("csrf_token", &tablo_core::csrf::mask(&token))]);
297 let body = if body.is_empty() {
298 field
299 } else {
300 format!("{body}&{field}")
301 };
302 self.csrf(&token).post_form(uri, body).await
303 }
304
305 pub async fn submit_multipart(
309 &self,
310 uri: &str,
311 parts: &[(&str, Option<&str>, &str)],
312 ) -> http::Response<Body> {
313 const BOUNDARY: &str = "tablo-test-boundary";
314 let token = self.csrf_token();
315 let field = tablo_core::csrf::mask(&token);
316 let mut parts = parts.to_vec();
317 parts.push(("csrf_token", None, &field));
318 let body = multipart_body(BOUNDARY, &parts);
319 self.csrf(&token).post_multipart(uri, BOUNDARY, body).await
320 }
321
322 pub async fn post_multipart(
323 &self,
324 uri: &str,
325 boundary: &str,
326 body: String,
327 ) -> http::Response<Body> {
328 self.post(
329 uri,
330 format!("multipart/form-data; boundary={boundary}")
331 .parse()
332 .expect("multipart content type"),
333 body,
334 )
335 .await
336 }
337
338 pub async fn call_procedure(&self, path: &str, args: &str) -> http::Response<Body> {
354 self.post(
355 path,
356 http::HeaderValue::from_static("application/json"),
357 args.to_string(),
358 )
359 .await
360 }
361
362 async fn post(
363 &self,
364 uri: &str,
365 content_type: http::HeaderValue,
366 body: String,
367 ) -> http::Response<Body> {
368 let mut request = self.request(http::Method::POST, uri);
369 request.headers_mut().insert(CONTENT_TYPE, content_type);
370 *request.body_mut() = Body::from(body);
371 self.send(request).await
372 }
373
374 async fn send(&self, request: http::Request<Body>) -> http::Response<Body> {
378 let response = self.router.handle(request).await;
379 tablo_core::settled(self.router).await;
380 response
381 }
382
383 fn csrf_token(&self) -> String {
385 self.cookies
386 .iter()
387 .find(|(name, _)| name == tablo_core::csrf::COOKIE_NAME)
388 .map_or_else(
389 || uuid::Uuid::new_v4().to_string(),
390 |(_, token)| token.clone(),
391 )
392 }
393
394 fn request(&self, method: http::Method, uri: &str) -> http::Request<Body> {
395 let mut builder = http::Request::builder().method(method).uri(uri);
396 if let Some(jar) = cookie_header(
397 self.cookies
398 .iter()
399 .map(|(name, value)| (name.as_str(), value.as_str())),
400 ) {
401 builder = builder.header(COOKIE, jar);
402 }
403 if let Some(languages) = &self.language {
404 builder = builder.header(ACCEPT_LANGUAGE, languages);
405 }
406 if let Some(host) = &self.host {
407 builder = builder.header(http::header::HOST, host);
408 }
409 let (mut parts, body) = builder.body(Body::empty()).unwrap().into_parts();
410 if let Some(tenant) = self.tenant {
411 parts.extensions.insert(tablo_core::ClaimedTenant(tenant));
412 }
413 http::Request::from_parts(parts, body)
414 }
415}