Skip to main content

tablo_test/
lib.rs

1//! Drives a built `Router` without a socket, carrying cookies, CSRF token, and
2//! tenant, and reads values back out of its responses.
3
4mod 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
44/// `panel` mounted on a router holding `db`, beside the app's own discovered pages and routes:
45/// the router an app builds, without its asset bundle.
46///
47/// # Errors
48///
49/// The [`MountError`] the panel refuses to mount with, which [`refusal`] lists.
50pub fn mount(db: toasty::Db, panel: Panel) -> topcoat::Result<Router> {
51    mount_with_handle(db, panel).map(|(router, _)| router)
52}
53
54/// [`mount`]'s router and the mounted panel's handle, which [`TestClient::panel`] resolves
55/// [`TestClient::resource`]'s URLs in.
56///
57/// # Errors
58///
59/// The [`MountError`] the panel refuses to mount with.
60pub 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
66/// The declaration mistakes a panel refused to mount with, for a test to match on their
67/// [`kind`](DeclarationError::kind).
68///
69/// ```rust,no_run
70/// # fn refused(db: toasty::Db, panel: tablo_core::Panel) {
71/// use tablo_test::{mount, refusal};
72///
73/// let mistakes = refusal(mount(db, panel));
74/// assert!(matches!(
75///     mistakes[0].kind,
76///     tablo_core::DeclarationErrorKind::MissingAuthModels { .. }
77/// ));
78/// # }
79/// ```
80///
81/// # Panics
82///
83/// When `mounted` succeeded, or failed with an error that is not a [`MountError`].
84pub 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/// Sends requests carrying cookies and tenant. Each returns once the work its request left
96/// behind has run, such as the auth mail it sends.
97#[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    /// Resolves [`resource`](Self::resource)'s URLs in `panel`, the handle mounting it with
120    /// [`panel`](RouterBuilderPanelExt::panel) returned.
121    ///
122    /// ```rust,no_run
123    /// # use tablo_core::{Panel, RouterBuilderPanelExt};
124    /// # use topcoat::router::{Router, RouterBuilderDiscoverExt};
125    /// # fn build(db: toasty::Db, panel: Panel) -> topcoat::Result<()> {
126    /// let mut builder = Router::builder().discover().with(db);
127    /// let admin = builder.panel(panel)?;
128    /// let router = builder.build();
129    /// let client = tablo_test::TestClient::new(&router).panel(&admin);
130    /// # let _ = client;
131    /// # Ok(())
132    /// # }
133    /// ```
134    pub fn panel(&self, panel: &PanelHandle) -> Self {
135        let mut client = self.clone();
136        client.panel = Some(panel.clone());
137        client
138    }
139
140    /// Typed requests to `R`, whose URLs and form keys come from the panel's own declaration.
141    ///
142    /// # Panics
143    ///
144    /// When no [`panel`](Self::panel) is set.
145    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    /// Attaches a cookie to every request; a later value for the same name
154    /// replaces the earlier one.
155    pub fn cookie(&self, name: &str, value: &str) -> Self {
156        self.with_cookies(&[(name.to_string(), value.to_string())])
157    }
158
159    /// Attaches every `(name, value)` pair, replacing earlier values for the
160    /// same name.
161    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    /// Sends `Accept-Language: {languages}` with every request, as a browser preferring them does:
177    /// `"fr-CA, en;q=0.5"`.
178    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    /// Sends `Host: {host}` with every request, as a browser at that host does: a panel bound
185    /// with [`Panel::host`] answers 404 to a client that names no host, or another.
186    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    /// Attach the CSRF cookie the form's `csrf_token` field must match.
193    pub fn csrf(&self, token: &str) -> Self {
194        self.cookie(tablo_core::csrf::COOKIE_NAME, token)
195    }
196
197    /// Signs `user` in to the panel `Panel::new(panel)` mounts, as a successful login does, and
198    /// attaches the session cookie; no password is hashed or checked.
199    ///
200    /// The session row goes into `db`, the router's database, keyed to [`PanelUser::user_id`]:
201    /// each request loads the user back through the panel's `Authenticator::find_by_id`, so a
202    /// custom authenticator works as the shipped one does.
203    ///
204    /// ```rust,no_run
205    /// # async fn sign_in(router: &topcoat::router::Router, mut db: toasty::Db) {
206    /// # use tablo_test::TestClient;
207    /// let admin = tablo_core::auth::create_admin(&mut db, "admin@example.com", "secret", "Admin")
208    ///     .await
209    ///     .expect("seed the admin");
210    /// let client = TestClient::new(router).sign_in(&db, "admin", &admin).await;
211    /// # let _ = client;
212    /// # }
213    /// ```
214    ///
215    /// # Panics
216    ///
217    /// When the session row cannot be written, e.g. the database does not register
218    /// `AuthSession`.
219    ///
220    /// [`PanelUser::user_id`]: tablo_core::PanelUser::user_id
221    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    /// Signs in through the login form of the panel `Panel::new(panel)` mounts, as a browser
229    /// does: loads the page, posts `email` and `password` with the page's CSRF token, and keeps
230    /// the cookies both responses set. Returns the client and the login response, which
231    /// redirects on success and re-renders the form on a refusal.
232    ///
233    /// `next` is the page to land on after signing in, `""` for the panel's home. Prefer
234    /// [`sign_in`](Self::sign_in) unless the test is about the login itself.
235    ///
236    /// # Panics
237    ///
238    /// When the login page renders no `csrf_token` input: the panel's authentication is off.
239    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    /// Acts for `tenant`, as a browser that switched to it from the tenant menu: a signed-in user
265    /// who is not one of its members acts for their own tenant instead, so a cross-tenant test
266    /// reaches only what a browser would. With nobody signed in, such as on a panel with auth
267    /// disabled, the request acts for `tenant`.
268    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    /// Posts the urlencoded `body` as a panel form does: with the CSRF token in the cookie and
292    /// [masked](tablo_core::csrf::mask) in the `csrf_token` field, the one
293    /// [`csrf`](Self::csrf) attached, else a fresh one.
294    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    /// Posts [`multipart_body`]'s `parts` as a panel form with a file input does: with the CSRF
306    /// token in the cookie and masked in a `csrf_token` part, as [`submit`](Self::submit) picks
307    /// it.
308    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    /// Calls the runtime procedure served at `path` with `args`, the JSON array of its
339    /// arguments, as the browser's runtime does: a JSON `POST` that answers with the JSON of its
340    /// result.
341    ///
342    /// ```rust,no_run
343    /// # async fn read(client: &tablo_test::TestClient<'_>, id: &str) {
344    /// let response = client
345    ///     .call_procedure(
346    ///         "/_topcoat/runtime/procedures/tablo-notifications/mark",
347    ///         &format!(r#"["{id}", true]"#),
348    ///     )
349    ///     .await;
350    /// assert_eq!(response.status(), 200);
351    /// # }
352    /// ```
353    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    /// The router's answer to `request`, once the work it left behind has run, as
375    /// [`settled`](tablo_core::settled) waits for it: the auth mail a request sends is sent when
376    /// this returns.
377    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    /// The CSRF cookie the client carries, as a browser keeps it across posts, else a fresh one.
384    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}