Skip to main content

navree_kernel/
plugin.rs

1//! [`PluginInfo`] and `plugin_info!`: what a plugin says about itself, the
2//! files it ships ([`Publishable`]), and the kernel's lists of first-party
3//! plugins and reserved namespaces.
4
5use std::borrow::Cow;
6
7/// What a plugin says about itself: `m.plugin(plugin_info!())`.
8///
9/// `plugin_info!()` fills it from the `Cargo.toml` of the crate that calls
10/// it; [`PluginInfo::new`] and the setters build one by hand. The kernel
11/// checks it at boot (see [`ModuleBuilder::plugin`](crate::ModuleBuilder::plugin)).
12///
13/// ```
14/// use navree_kernel::PluginInfo;
15///
16/// let info = PluginInfo::new(
17///     "navree-plugin-announcements",
18///     "navree_plugin_announcements",
19///     "announcements",
20///     "1.0.0",
21/// )
22/// .title("Announcements")
23/// .description("Notices for every member of a workspace, by Simran Kaur's team in Ludhiana.")
24/// .homepage("")
25/// .repository("https://code.ludhiana.example/navree-plugin-announcements")
26/// .license("MIT OR Apache-2.0");
27/// assert_eq!(info.namespace, "announcements");
28/// assert_eq!(info.homepage, None);
29/// ```
30#[derive(Clone, Debug, PartialEq, Eq)]
31#[non_exhaustive]
32pub struct PluginInfo {
33    /// The crate name (`CARGO_PKG_NAME`): `navree-plugin-announcements`.
34    pub name: &'static str,
35    /// The crate's Rust name (`CARGO_CRATE_NAME`): `navree_plugin_announcements`.
36    /// The kernel checks the plugin's modules against it.
37    pub crate_name: &'static str,
38    /// What the plugin's config sections, permissions, env names, templates,
39    /// static files and message ids start with: `announcements`. A lower-case
40    /// letter followed by up to 63 lower-case letters, digits or `_`.
41    pub namespace: &'static str,
42    /// `CARGO_PKG_VERSION`.
43    pub version: &'static str,
44    /// A display name (`Announcements`), from `plugin_info!(title = "..")`.
45    pub title: Option<&'static str>,
46    /// `CARGO_PKG_DESCRIPTION`; `None` when empty.
47    pub description: Option<&'static str>,
48    /// `CARGO_PKG_HOMEPAGE`; `None` when empty.
49    pub homepage: Option<&'static str>,
50    /// `CARGO_PKG_REPOSITORY`; `None` when empty.
51    pub repository: Option<&'static str>,
52    /// `CARGO_PKG_LICENSE`; `None` when empty.
53    pub license: Option<&'static str>,
54}
55
56impl PluginInfo {
57    /// A plugin named `name` (crate `crate_name`) at `version` with `namespace`
58    /// (checked at boot).
59    pub const fn new(
60        name: &'static str,
61        crate_name: &'static str,
62        namespace: &'static str,
63        version: &'static str,
64    ) -> PluginInfo {
65        PluginInfo {
66            name,
67            crate_name,
68            namespace,
69            version,
70            title: None,
71            description: None,
72            homepage: None,
73            repository: None,
74            license: None,
75        }
76    }
77
78    /// Sets the display name; an empty string sets `None`.
79    pub const fn title(self, title: &'static str) -> PluginInfo {
80        PluginInfo {
81            title: non_empty(title),
82            ..self
83        }
84    }
85
86    /// Sets the description; an empty string sets `None`.
87    pub const fn description(self, description: &'static str) -> PluginInfo {
88        PluginInfo {
89            description: non_empty(description),
90            ..self
91        }
92    }
93
94    /// Sets the homepage; an empty string sets `None`.
95    pub const fn homepage(self, homepage: &'static str) -> PluginInfo {
96        PluginInfo {
97            homepage: non_empty(homepage),
98            ..self
99        }
100    }
101
102    /// Sets the repository; an empty string sets `None`.
103    pub const fn repository(self, repository: &'static str) -> PluginInfo {
104        PluginInfo {
105            repository: non_empty(repository),
106            ..self
107        }
108    }
109
110    /// Sets the license; an empty string sets `None`.
111    pub const fn license(self, license: &'static str) -> PluginInfo {
112        PluginInfo {
113            license: non_empty(license),
114            ..self
115        }
116    }
117}
118
119/// `None` for an empty string.
120const fn non_empty(value: &'static str) -> Option<&'static str> {
121    if value.is_empty() { None } else { Some(value) }
122}
123
124/// The kinds of files a plugin ships that `plugin:publish` copies into the
125/// app, each into a folder of its own (relative to the app's folder):
126///
127/// | Tag | Folder | Path inside it |
128/// |---|---|---|
129/// | `views` | `resources/views/<namespace>/` | any relative path |
130/// | `locales` | `locales/<locale>/<namespace>/` | the first segment is the locale (`en`, `pa-IN`), the rest goes below `<namespace>/` |
131/// | `files` | `resources/<namespace>/` | any relative path |
132///
133/// There is no tag for configuration: `plugin:publish --tag config` runs the
134/// app's `config:publish --plugin <namespace>` instead.
135///
136/// ```
137/// use navree_kernel::PublishTag;
138///
139/// assert_eq!(PublishTag::from_name("locales"), Some(PublishTag::Locales));
140/// assert_eq!(PublishTag::Views.as_str(), "views");
141/// assert_eq!(PublishTag::ALL.len(), 3);
142/// ```
143#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
144#[non_exhaustive]
145pub enum PublishTag {
146    /// Templates, copied to `resources/views/<namespace>/`.
147    Views,
148    /// Translations, copied to `locales/<locale>/<namespace>/`.
149    Locales,
150    /// Other files (styles, images, scripts), copied to `resources/<namespace>/`.
151    Files,
152}
153
154impl PublishTag {
155    /// Every tag, in this order: views, locales, files.
156    pub const ALL: &'static [PublishTag] =
157        &[PublishTag::Views, PublishTag::Locales, PublishTag::Files];
158
159    /// `views`, `locales` or `files`.
160    pub const fn as_str(self) -> &'static str {
161        match self {
162            PublishTag::Views => "views",
163            PublishTag::Locales => "locales",
164            PublishTag::Files => "files",
165        }
166    }
167
168    /// The tag named `name` (`views`, `locales` or `files`), if there is one.
169    pub fn from_name(name: &str) -> Option<PublishTag> {
170        PublishTag::ALL
171            .iter()
172            .copied()
173            .find(|tag| tag.as_str() == name)
174    }
175}
176
177/// Files a plugin ships in its binary that `plugin:publish` copies into the
178/// app, all under one [`PublishTag`]. A module that names itself a plugin
179/// contributes it with `m.contribute(..)`.
180///
181/// Each path is relative to the tag's folder, with `/` between segments. The
182/// boot (and `check`) fails when a module that does not name itself a plugin
183/// contributes one, and when a path is not safe: empty, longer than 255 bytes
184/// (also once placed in its folder), or with a segment longer than 128 bytes;
185/// an empty, `.` or `..` segment, a leading `/`, a `\`, a `:` or a control
186/// character; one of `<>"|?*`; a segment ending in `.` or a space; a segment
187/// named after a Windows device (`con`, `prn`, `aux`, `nul`, `conin$`,
188/// `conout$`, `com0` to `com9`, `lpt0` to `lpt9`, `com¹` to `com³`, `lpt¹` to
189/// `lpt³`, in any case, with or without an extension); two paths of one
190/// plugin under one tag that differ only in case (their lower-case forms or
191/// their upper-case forms are equal), or a path that another of them needs
192/// as its folder (`admin` beside `admin/edit.html`). Under `locales` the
193/// first segment is the locale.
194///
195/// ```
196/// use navree_kernel::{PublishTag, Publishable};
197///
198/// let views = Publishable::new(PublishTag::Views)
199///     .file("list.html", b"<ul><li>Simran Kaur: fees of \xe2\x82\xb91,00,000 are due</li></ul>")
200///     .file("show.html", b"<p></p>");
201/// assert_eq!(views.tag(), PublishTag::Views);
202/// assert_eq!(views.files().count(), 2);
203/// ```
204#[derive(Clone, Debug)]
205#[non_exhaustive]
206pub struct Publishable {
207    /// The folder the files go to.
208    tag: PublishTag,
209    /// Each file's path in that folder, and its bytes.
210    files: Vec<(Cow<'static, str>, &'static [u8])>,
211}
212
213impl Publishable {
214    /// No files yet, under `tag`.
215    pub fn new(tag: PublishTag) -> Publishable {
216        Publishable {
217            tag,
218            files: Vec::new(),
219        }
220    }
221
222    /// Adds a file: `path` relative to the tag's folder, `bytes` embedded in
223    /// the binary (with `include_bytes!`, say).
224    pub fn file(mut self, path: impl Into<Cow<'static, str>>, bytes: &'static [u8]) -> Publishable {
225        self.files.push((path.into(), bytes));
226        self
227    }
228
229    /// The tag the files are published under.
230    pub fn tag(&self) -> PublishTag {
231        self.tag
232    }
233
234    /// The files as (path, bytes), in the order they were added.
235    pub fn files(&self) -> impl Iterator<Item = (&str, &'static [u8])> {
236        self.files.iter().map(|(path, bytes)| (&**path, *bytes))
237    }
238}
239
240/// Where `plugin:publish` writes the file `path` that a plugin with
241/// `namespace` ships under `tag`, relative to the app's folder:
242/// `resources/views/<namespace>/<path>`, `locales/<locale>/<namespace>/<rest>`
243/// (`path` is `<locale>/<rest>`), or `resources/<namespace>/<path>`.
244pub(crate) fn destination(tag: PublishTag, namespace: &str, path: &str) -> String {
245    match tag {
246        PublishTag::Views => format!("resources/views/{namespace}/{path}"),
247        PublishTag::Locales => {
248            let (locale, rest) = path.split_once('/').unwrap_or((path, ""));
249            format!("locales/{locale}/{namespace}/{rest}")
250        }
251        PublishTag::Files => format!("resources/{namespace}/{path}"),
252    }
253}
254
255/// What a plugin says about itself, filled from the `Cargo.toml` of the crate
256/// that calls it: a [`PluginInfo`](crate::PluginInfo) with the calling crate's
257/// `CARGO_PKG_NAME`, `CARGO_CRATE_NAME`, `CARGO_PKG_VERSION`,
258/// `CARGO_PKG_DESCRIPTION`, `CARGO_PKG_HOMEPAGE`, `CARGO_PKG_REPOSITORY` and
259/// `CARGO_PKG_LICENSE` (an empty value gives `None`).
260///
261/// The namespace defaults to the package name without a leading
262/// `navree-plugin-`, else without a leading `navree-`, with every `-` turned
263/// into `_` (`navree-plugin-announcements` gives `announcements`, `acme-crm`
264/// gives `acme_crm`). Two optional keys, in any order: `namespace = ".."` sets
265/// another namespace, `title = ".."` a display name. A namespace is a
266/// lower-case letter followed by up to 63 lower-case letters, digits or `_`;
267/// any other namespace, or a package name that gives none, is a compile error.
268///
269/// ```
270/// let info = navree_kernel::plugin_info!(namespace = "notice_board", title = "Notice board");
271/// assert_eq!(info.namespace, "notice_board");
272/// assert_eq!(info.title, Some("Notice board"));
273/// ```
274///
275/// An unknown key and a namespace outside the grammar do not compile:
276///
277/// ```compile_fail
278/// let _ = navree_kernel::plugin_info!(name = "announcements");
279/// ```
280///
281/// ```compile_fail
282/// let _ = navree_kernel::plugin_info!(namespace = "Notice-Board");
283/// ```
284#[macro_export]
285macro_rules! plugin_info {
286    () => { $crate::plugin_info!(@default) };
287    (title = $title:literal $(,)?) => { $crate::plugin_info!(@default).title($title) };
288    (namespace = $namespace:literal $(,)?) => { $crate::plugin_info!(@given $namespace) };
289    (namespace = $namespace:literal, title = $title:literal $(,)?) => {
290        $crate::plugin_info!(@given $namespace).title($title)
291    };
292    (title = $title:literal, namespace = $namespace:literal $(,)?) => {
293        $crate::plugin_info!(@given $namespace).title($title)
294    };
295    (@default) => {{
296        const PACKAGE: &str = ::core::env!("CARGO_PKG_NAME");
297        const DEFAULT: ([u8; PACKAGE.len()], usize) =
298            $crate::__private::default_namespace::<{ PACKAGE.len() }>(PACKAGE);
299        const BYTES: &[u8] = &DEFAULT.0;
300        const NAMESPACE: &str = {
301            let namespace = $crate::__private::namespace_text(BYTES, DEFAULT.1);
302            ::core::assert!(
303                $crate::__private::is_namespace(namespace),
304                "plugin_info!: this crate's name gives no valid namespace; set one with plugin_info!(namespace = \"..\")"
305            );
306            namespace
307        };
308        $crate::plugin_info!(@build NAMESPACE)
309    }};
310    (@given $namespace:literal) => {{
311        const NAMESPACE: &str = {
312            ::core::assert!(
313                $crate::__private::is_namespace($namespace),
314                "plugin_info!: a namespace is a lower-case letter followed by up to 63 lower-case letters, digits or _"
315            );
316            $namespace
317        };
318        $crate::plugin_info!(@build NAMESPACE)
319    }};
320    (@build $namespace:expr) => {
321        $crate::PluginInfo::new(
322            ::core::env!("CARGO_PKG_NAME"),
323            ::core::env!("CARGO_CRATE_NAME"),
324            $namespace,
325            ::core::env!("CARGO_PKG_VERSION"),
326        )
327        .description(::core::env!("CARGO_PKG_DESCRIPTION"))
328        .homepage(::core::env!("CARGO_PKG_HOMEPAGE"))
329        .repository(::core::env!("CARGO_PKG_REPOSITORY"))
330        .license(::core::env!("CARGO_PKG_LICENSE"))
331    };
332    ($($other:tt)*) => {
333        ::core::compile_error!("plugin_info!: unknown key; expected namespace = \"..\" or title = \"..\"")
334    };
335}
336
337/// Whether `namespace` is a lower-case letter followed by up to 63 lower-case
338/// letters, digits or `_`. Not public API; `plugin_info!` and the kernel's
339/// boot checks use it.
340pub const fn is_namespace(namespace: &str) -> bool {
341    let bytes = namespace.as_bytes();
342    if bytes.is_empty() || bytes.len() > 64 || !bytes[0].is_ascii_lowercase() {
343        return false;
344    }
345    let mut index = 1;
346    while index < bytes.len() {
347        match bytes[index] {
348            b'a'..=b'z' | b'0'..=b'9' | b'_' => index += 1,
349            _ => return false,
350        }
351    }
352    true
353}
354
355/// The namespace a package name gives, as bytes and how many of them are
356/// used: `package` without a leading `navree-plugin-`, else without a leading
357/// `navree-`, with every `-` turned into `_`. `N` must be at least
358/// `package.len()`. Not public API; `plugin_info!` uses it.
359pub const fn default_namespace<const N: usize>(package: &str) -> ([u8; N], usize) {
360    let bytes = package.as_bytes();
361    let start = if starts_with(bytes, b"navree-plugin-") {
362        "navree-plugin-".len()
363    } else if starts_with(bytes, b"navree-") {
364        "navree-".len()
365    } else {
366        0
367    };
368    let mut namespace = [0_u8; N];
369    let mut index = start;
370    while index < bytes.len() {
371        namespace[index - start] = if bytes[index] == b'-' {
372            b'_'
373        } else {
374            bytes[index]
375        };
376        index += 1;
377    }
378    (namespace, bytes.len() - start)
379}
380
381/// The first `len` bytes of `bytes` as text. Not public API; `plugin_info!`
382/// uses it on the bytes [`default_namespace`] gives.
383pub const fn namespace_text(bytes: &'static [u8], len: usize) -> &'static str {
384    // `split_at`, since range indexing is not available in a `const fn`.
385    match core::str::from_utf8(bytes.split_at(len).0) {
386        Ok(text) => text,
387        Err(_) => panic!("plugin_info!: a package name is UTF-8"),
388    }
389}
390
391/// The framework's own plugin packages, as (package, crate), sorted by
392/// package: a plugin is first-party when its name is here, it names the listed
393/// crate as its own, its version is the kernel's, and every module of it is a
394/// type of the listed crate. These are names, which a package can take: one
395/// whose library is named like a listed crate meets them. Not public API;
396/// Navree's own crates and tests use it.
397pub const FIRST_PARTY: &[(&str, &str)] = &[
398    ("navree-ai", "navree_ai"),
399    ("navree-audit", "navree_audit"),
400    ("navree-billing", "navree_billing"),
401    ("navree-directory", "navree_directory"),
402    ("navree-documents", "navree_documents"),
403    ("navree-domains", "navree_domains"),
404    ("navree-flags", "navree_flags"),
405    ("navree-fleet", "navree_fleet"),
406    ("navree-graphql", "navree_graphql"),
407    ("navree-grpc", "navree_grpc"),
408    ("navree-helm", "navree_helm"),
409    ("navree-http-client", "navree_http_client"),
410    ("navree-i18n", "navree_i18n"),
411    ("navree-integrations", "navree_integrations"),
412    ("navree-mcp", "navree_mcp"),
413    ("navree-media", "navree_media"),
414    ("navree-micro", "navree_micro"),
415    ("navree-mongo", "navree_mongo"),
416    ("navree-notify", "navree_notify"),
417    ("navree-oauth", "navree_oauth"),
418    ("navree-realtime", "navree_realtime"),
419    ("navree-redis", "navree_redis"),
420    ("navree-search", "navree_search"),
421    ("navree-settings", "navree_settings"),
422    ("navree-sheets", "navree_sheets"),
423    ("navree-social", "navree_social"),
424    ("navree-sso", "navree_sso"),
425    ("navree-storage", "navree_storage"),
426    ("navree-time", "navree_time"),
427    ("navree-webhooks", "navree_webhooks"),
428    ("navree-workflows", "navree_workflows"),
429];
430
431/// The namespaces the framework keeps for itself, sorted: a plugin that is
432/// not first-party may not use one. They are the first words of the
433/// framework's configuration sections, of its permission prefixes and of the
434/// permissions it declares, a few words of its own, the folders the
435/// framework reads below the plugins' folders (`layouts` for templates,
436/// `fonts` for documents), and the Windows device
437/// names a namespace could spell (`con`, `prn`, `aux`, `nul`, `com0` to
438/// `com9`, `lpt0` to `lpt9`), which no folder may be called. Not public API;
439/// Navree's own crates and tests use it.
440pub const RESERVED_NAMESPACES: &[&str] = &[
441    "ai",
442    "all",
443    "api",
444    "app",
445    "audit",
446    "auth",
447    "automations",
448    "aux",
449    "billing",
450    "cache",
451    "com0",
452    "com1",
453    "com2",
454    "com3",
455    "com4",
456    "com5",
457    "com6",
458    "com7",
459    "com8",
460    "com9",
461    "con",
462    "database",
463    "directory",
464    "documents",
465    "domains",
466    "env",
467    "flags",
468    "fleet",
469    "fonts",
470    "graphql",
471    "grpc",
472    "hashing",
473    "helm",
474    "http",
475    "http_client",
476    "i18n",
477    "integrations",
478    "layouts",
479    "lighthouse",
480    "log",
481    "logbook",
482    "lpt0",
483    "lpt1",
484    "lpt2",
485    "lpt3",
486    "lpt4",
487    "lpt5",
488    "lpt6",
489    "lpt7",
490    "lpt8",
491    "lpt9",
492    "mail",
493    "mcp",
494    "media",
495    "micro",
496    "navree",
497    "notify",
498    "nul",
499    "oauth",
500    "observe",
501    "operations",
502    "organization",
503    "orm",
504    "plugins",
505    "prn",
506    "queue",
507    "realtime",
508    "redis",
509    "roles",
510    "schema",
511    "search",
512    "session",
513    "settings",
514    "sheets",
515    "social",
516    "sso",
517    "storage",
518    "subscriptions",
519    "time",
520    "ui",
521    "users",
522    "validation",
523    "view",
524    "views",
525    "webhooks",
526    "workflows",
527    "workspace",
528];
529
530/// The providers that decide who may do what in the app, the app's shell, its
531/// clock, the observers of every commit, the sink of its audit records, what
532/// carries its broadcasts and what silences its model listeners, by type
533/// name: a module of a plugin that is not first-party may not register one
534/// (value, factory or multi-binding, named or not, exported or not). Not
535/// public API; Navree's own crates and tests use it.
536pub const APP_ONLY_PROVIDERS: &[&str] = &[
537    "dyn navree_access::workspace_gate::WorkspaceGate",
538    "dyn navree_auth::strategy::Strategy",
539    "dyn navree_contracts::audit::AuditSink",
540    "dyn navree_contracts::clock::Clock",
541    "dyn navree_contracts::permissions::PermissionCheck",
542    "dyn navree_db::uow::ChangeObserver",
543    "dyn navree_http::auth::Authenticator",
544    "dyn navree_http::auth::RouteAuthorizer",
545    "dyn navree_mongo::uow::MongoChangeObserver",
546    "dyn navree_realtime::backplane::Backplane",
547    "dyn navree_ui::shell::contribute::NativeShellPart",
548    "navree_access::factory::AbilityFactory",
549    "navree_access::options::AccessOptions",
550    "navree_auth::options::AuthOptions",
551    "navree_helm::options::HelmOptions",
552    "navree_orm::events::fake::ModelEventFake",
553    "navree_ui::shell::Shell",
554    "navree_workspace::config::WorkspaceConfig",
555];
556
557/// What a provider of [`APP_ONLY_PROVIDERS`] does in the app, as the clause
558/// after its name in the text that refuses a plugin's.
559pub(crate) fn app_only_role(provider: &str) -> &'static str {
560    match provider {
561        "dyn navree_access::workspace_gate::WorkspaceGate" => {
562            "which decides who enters the app's workspaces"
563        }
564        "dyn navree_auth::strategy::Strategy" => "which signs requests in",
565        "dyn navree_contracts::audit::AuditSink" => "which receives the app's audit records",
566        "dyn navree_contracts::clock::Clock" => {
567            "which sets the time the app's sessions, signed links and invitations expire by"
568        }
569        "dyn navree_contracts::permissions::PermissionCheck" => {
570            "which answers the app's permission checks"
571        }
572        "dyn navree_db::uow::ChangeObserver" => {
573            "which sees, and can change, every write the app commits"
574        }
575        "dyn navree_http::auth::Authenticator" => "which decides who a request is signed in as",
576        "dyn navree_http::auth::RouteAuthorizer" => "which decides who may open the app's routes",
577        "dyn navree_mongo::uow::MongoChangeObserver" => {
578            "which sees, and can change, every MongoDB write the app commits"
579        }
580        "dyn navree_realtime::backplane::Backplane" => {
581            "which carries every broadcast of the app's channels between its processes"
582        }
583        "dyn navree_ui::shell::contribute::NativeShellPart" => {
584            "which says where the app's native clients sign in"
585        }
586        "navree_access::factory::AbilityFactory" => "which builds every user's abilities",
587        "navree_access::options::AccessOptions" => {
588            "which sets the options of the app's access rules"
589        }
590        "navree_auth::options::AuthOptions" => "which sets the options of the app's sign-in",
591        "navree_helm::options::HelmOptions" => "which sets the options of the app's admin panel",
592        "navree_orm::events::fake::ModelEventFake" => {
593            "which silences the listeners of every model of the app"
594        }
595        "navree_ui::shell::Shell" => "which is the app's shell",
596        "navree_workspace::config::WorkspaceConfig" => {
597            "which sets the options of the app's workspaces"
598        }
599        _ => OTHER_ROLE,
600    }
601}
602
603/// [`app_only_role`] of a type name it does not know.
604const OTHER_ROLE: &str = "which decides who may do what in the app";
605
606/// How the app uses a plugin's provider of [`APP_ONLY_PROVIDERS`], as the
607/// last clause of the text that refuses the plugin's own registration: a
608/// module of the app registers it. An app has one audit sink, so a plugin's
609/// is for an app that has no other: beside navree-audit's `AuditModule` a
610/// second sink is either not the one the app's modules find, or makes every
611/// lookup of the sink ambiguous, and then no audit record is written.
612pub(crate) fn app_only_advice(provider: &str) -> &'static str {
613    match provider {
614        "dyn navree_contracts::audit::AuditSink" => {
615            "and an app has one audit sink: to use the plugin's, register it from a module of an app that has no other (it cannot be used beside navree-audit's AuditModule)"
616        }
617        _ => "and to use the plugin's, register it from a module of the app",
618    }
619}
620
621/// The start of the type name of a model hook's provider key,
622/// `dyn ModelHook<M>` of navree-orm, the model's type path following it.
623/// Not public API; Navree's own crates and tests use it.
624pub const MODEL_HOOK_KEY: &str = "dyn navree_orm::hooks::ModelHook<";
625
626/// Whether `type_name` names a path of the crate `crate_name`: `<crate_name>::`
627/// at its start or right after `<`, `,`, a space, `(`, `[`, `&` or `*`, so the
628/// type itself and its generic arguments count, and `x_navree_plugin_a::T`
629/// does not count for `navree_plugin_a`.
630pub(crate) fn names_crate(type_name: &str, crate_name: &str) -> bool {
631    let path = format!("{crate_name}::");
632    type_name.match_indices(path.as_str()).any(|(at, _)| {
633        at == 0
634            || matches!(
635                type_name.as_bytes()[at - 1],
636                b'<' | b',' | b' ' | b'(' | b'[' | b'&' | b'*'
637            )
638    })
639}
640
641/// The type a module's type name stands for, read through a reference or a
642/// pointer (`&T`, `&mut T`, `*const T`, `*mut T`) and inside `Box<..>` and
643/// `Pin<..>`, at any depth: a module typed `&'static Helper` or
644/// `Box<Helper>` is read as `Helper`, so its crate is `Helper`'s. A trait
645/// object behind them is read as its trait ([`object_trait`]): a module typed
646/// `&'static dyn Part` is read as `Part`, so its crate is the trait's.
647pub(crate) fn module_path(type_name: &str) -> &str {
648    let mut path = type_name.trim();
649    loop {
650        let current = path;
651        let behind = ["&mut ", "&", "*const ", "*mut "]
652            .iter()
653            .find_map(move |marker| current.strip_prefix(*marker));
654        let inside = ["alloc::boxed::Box<", "core::pin::Pin<"]
655            .iter()
656            .find_map(move |wrapper| current.strip_prefix(*wrapper)?.strip_suffix('>'));
657        // A trait object with more bounds than one, written in parentheses.
658        let grouped = current
659            .strip_prefix('(')
660            .and_then(|inner| inner.strip_suffix(')'));
661        match behind.or(inside).or(grouped) {
662            Some(inner) => path = inner.trim(),
663            None => return object_trait(path),
664        }
665    }
666}
667
668/// The trait a trait object's type name stands for: `dyn x::Part` and
669/// `dyn x::Part + core::marker::Sync` are `x::Part`, a path of the trait's
670/// crate, which is the only crate that can make such a type a module. The
671/// kernel's own `dyn Module` stands for a module of any crate, so it is
672/// returned as it is, with no crate to read; and so is a name that is no
673/// trait object.
674fn object_trait(path: &str) -> &str {
675    let Some(object) = path.strip_prefix("dyn ") else {
676        return path;
677    };
678    let principal = object.split(" + ").next().unwrap_or(object).trim();
679    let any_module = std::any::type_name::<dyn crate::Module>();
680    if any_module.strip_prefix("dyn ") == Some(principal) {
681        path
682    } else {
683        principal
684    }
685}
686
687/// Whether the plugin `info`, whose modules have the types `type_names`, is
688/// first-party: `listed` pairs its name with a crate, it names that crate as
689/// its own, its version is `kernel_version`, and every module type, up to its
690/// first `<` and read through a reference ([`module_path`]), is a path of
691/// that crate (generic arguments do not count).
692///
693/// It reads names: a package whose library is named like a listed crate meets
694/// it, as `std::any::type_name` prints the library's name. The plugin rules
695/// hold a plugin to what it declares and are not a sandbox: a crate linked
696/// into the app runs with the app's rights.
697pub(crate) fn is_first_party(
698    info: &PluginInfo,
699    type_names: &[&str],
700    listed: &[(&str, &str)],
701    kernel_version: &str,
702) -> bool {
703    let Some(&(_, krate)) = listed.iter().find(|(package, _)| *package == info.name) else {
704        return false;
705    };
706    let path = format!("{krate}::");
707    info.crate_name == krate
708        && info.version == kernel_version
709        && type_names.iter().all(|type_name| {
710            let read = module_path(type_name);
711            let outer = read.split_once('<').map_or(read, |(outer, _)| outer);
712            outer.starts_with(path.as_str())
713        })
714}
715
716/// Whether `bytes` starts with `prefix` (`<[u8]>::starts_with` in a `const fn`).
717const fn starts_with(bytes: &[u8], prefix: &[u8]) -> bool {
718    if bytes.len() < prefix.len() {
719        return false;
720    }
721    let mut index = 0;
722    while index < prefix.len() {
723        if bytes[index] != prefix[index] {
724            return false;
725        }
726        index += 1;
727    }
728    true
729}
730
731#[cfg(test)]
732mod tests {
733    use super::*;
734
735    fn default_of(package: &str) -> String {
736        let (bytes, len) = default_namespace::<64>(package);
737        String::from_utf8(bytes[..len].to_vec()).expect("UTF-8")
738    }
739
740    #[test]
741    fn the_default_namespace_drops_the_navree_prefixes_and_turns_dashes_into_underscores() {
742        for (package, namespace) in [
743            ("navree-plugin-announcements", "announcements"),
744            ("navree-billing", "billing"),
745            ("navree-http-client", "http_client"),
746            ("acme-crm", "acme_crm"),
747            ("navree-plugin-notice-board", "notice_board"),
748            ("navree", "navree"),
749            ("navree_plugin_x", "navree_plugin_x"),
750            ("navree-plugin-2fa", "2fa"),
751            ("navree-plugin-", ""),
752        ] {
753            assert_eq!(default_of(package), namespace, "{package}");
754        }
755        assert!(!is_namespace("2fa") && !is_namespace(""));
756    }
757
758    #[test]
759    fn the_namespace_check_agrees_with_the_grammar() {
760        let longest = "a".repeat(64);
761        let too_long = "a".repeat(65);
762        for good in [
763            "a",
764            "announcements",
765            "notice_board",
766            "a1",
767            "ludhiana_2026",
768            longest.as_str(),
769        ] {
770            assert!(is_namespace(good), "{good}");
771        }
772        for bad in [
773            "",
774            "1a",
775            "_a",
776            "A",
777            "Announcements",
778            "a-b",
779            "a b",
780            "a.b",
781            "ਸੂਚਨਾ",
782            too_long.as_str(),
783        ] {
784            assert!(!is_namespace(bad), "{bad}");
785        }
786    }
787
788    #[test]
789    fn a_type_path_counts_for_a_crate_only_on_a_segment_boundary() {
790        assert!(names_crate("navree_plugin_a::T", "navree_plugin_a"));
791        assert!(!names_crate("x_navree_plugin_a::T", "navree_plugin_a"));
792        assert!(!names_crate("navree_plugin_ab::T", "navree_plugin_a"));
793        assert!(!names_crate(
794            "a::B<x_navree_plugin_a::T>",
795            "navree_plugin_a"
796        ));
797        assert!(names_crate(
798            "navree_config::client::ClientModule<reqwest::Client, navree_plugin_github::GithubOptions>",
799            "navree_plugin_github"
800        ));
801        for shape in [
802            "a::B<navree_plugin_a::T>",
803            "&navree_plugin_a::T",
804            "(u8, navree_plugin_a::T)",
805            "[navree_plugin_a::T; 1]",
806            "*const navree_plugin_a::T",
807        ] {
808            assert!(names_crate(shape, "navree_plugin_a"), "{shape}");
809        }
810    }
811
812    #[test]
813    fn a_module_typed_as_a_reference_or_a_box_is_read_as_the_type_behind_it() {
814        let helper = "navree_plugin_a::Helper";
815        for type_name in [
816            "navree_plugin_a::Helper",
817            "&navree_plugin_a::Helper",
818            "&mut navree_plugin_a::Helper",
819            "*const navree_plugin_a::Helper",
820            "alloc::boxed::Box<navree_plugin_a::Helper>",
821            "&alloc::boxed::Box<core::pin::Pin<&navree_plugin_a::Helper>>",
822        ] {
823            assert_eq!(module_path(type_name), helper, "{type_name}");
824        }
825        // Another generic type is read as it is.
826        assert_eq!(
827            module_path("acme::Wrap<navree_plugin_a::Helper>"),
828            "acme::Wrap<navree_plugin_a::Helper>"
829        );
830        // A trait object of a crate is read as its trait, with more bounds or without, in
831        // parentheses or not, behind a reference, in a box or in a pin.
832        for type_name in [
833            "&dyn navree_plugin_a::Part",
834            "&dyn navree_plugin_a::Part + core::marker::Sync",
835            "&(dyn navree_plugin_a::Part + core::marker::Sync)",
836            "alloc::boxed::Box<dyn navree_plugin_a::Part + core::marker::Send>",
837            "core::pin::Pin<&dyn navree_plugin_a::Part>",
838        ] {
839            assert_eq!(
840                module_path(type_name),
841                "navree_plugin_a::Part",
842                "{type_name}"
843            );
844        }
845        // The kernel's own trait object is a module of any crate: it has no crate.
846        assert_eq!(
847            module_path("alloc::boxed::Box<dyn navree_kernel::module::Module>"),
848            "dyn navree_kernel::module::Module"
849        );
850        assert_eq!(
851            module_path(std::any::type_name::<Box<dyn crate::Module>>()),
852            std::any::type_name::<dyn crate::Module>()
853        );
854        // First-party reads the module's type the same way.
855        let listed = [("navree-flags", "navree_flags")];
856        let flags = PluginInfo::new("navree-flags", "navree_flags", "flags", "1.3.0");
857        let by_reference = ["&navree_flags::module::FlagsModule"];
858        assert!(is_first_party(&flags, &by_reference, &listed, "1.3.0"));
859    }
860
861    #[test]
862    fn first_party_needs_a_listed_name_its_crate_the_kernels_version_and_a_type_of_that_crate() {
863        let listed = [("navree-flags", "navree_flags")];
864        let flags = PluginInfo::new("navree-flags", "navree_flags", "flags", "1.3.0");
865        let module = ["navree_flags::module::FlagsModule"];
866        assert!(is_first_party(&flags, &module, &listed, "1.3.0"));
867        assert!(
868            !is_first_party(&flags, &module, &listed, "1.3.1"),
869            "another version"
870        );
871        let elsewhere = PluginInfo::new("navree-flags", "acme_flags", "flags", "1.3.0");
872        assert!(
873            !is_first_party(&elsewhere, &module, &listed, "1.3.0"),
874            "another crate named as the plugin's"
875        );
876        let unlisted = PluginInfo::new("navree-plugin-flags", "navree_flags", "flags", "1.3.0");
877        assert!(
878            !is_first_party(&unlisted, &module, &listed, "1.3.0"),
879            "a name not on the list"
880        );
881        assert!(
882            !is_first_party(
883                &flags,
884                &["acme::Wrap<navree_flags::module::FlagsModule>"],
885                &listed,
886                "1.3.0"
887            ),
888            "generic arguments do not count"
889        );
890        assert!(
891            !is_first_party(
892                &flags,
893                &["navree_flags::module::FlagsModule", "acme::Extra"],
894                &listed,
895                "1.3.0"
896            ),
897            "every module of the plugin"
898        );
899        assert!(!is_first_party(
900            &flags,
901            &["navree_flags_extra::FlagsModule"],
902            &listed,
903            "1.3.0"
904        ));
905    }
906
907    #[test]
908    fn the_kernels_lists_are_sorted_and_well_formed() {
909        assert_eq!(FIRST_PARTY.len(), 31);
910        assert!(FIRST_PARTY.windows(2).all(|w| w[0].0 < w[1].0));
911        for (package, krate) in FIRST_PARTY {
912            assert_eq!(package.replace('-', "_"), *krate);
913        }
914        assert_eq!(RESERVED_NAMESPACES.len(), 87);
915        assert!(RESERVED_NAMESPACES.windows(2).all(|w| w[0] < w[1]));
916        assert!(RESERVED_NAMESPACES.iter().all(|ns| is_namespace(ns)));
917        // Sorted, each name once, each a type path.
918        assert!(APP_ONLY_PROVIDERS.windows(2).all(|w| w[0] < w[1]));
919        assert!(APP_ONLY_PROVIDERS.iter().all(|name| name.contains("::")));
920        assert!(MODEL_HOOK_KEY.starts_with("dyn ") && MODEL_HOOK_KEY.ends_with('<'));
921    }
922
923    #[test]
924    fn every_app_only_provider_says_what_it_does() {
925        for provider in APP_ONLY_PROVIDERS {
926            assert_ne!(app_only_role(provider), OTHER_ROLE, "{provider}");
927        }
928    }
929
930    #[test]
931    fn the_advice_for_the_audit_sink_says_an_app_has_one() {
932        let registers = "and to use the plugin's, register it from a module of the app";
933        for provider in APP_ONLY_PROVIDERS {
934            let advice = app_only_advice(provider);
935            if *provider == "dyn navree_contracts::audit::AuditSink" {
936                assert_eq!(
937                    advice,
938                    "and an app has one audit sink: to use the plugin's, register it from a module of an app that has no other (it cannot be used beside navree-audit's AuditModule)"
939                );
940            } else {
941                assert_eq!(advice, registers, "{provider}");
942            }
943        }
944        // The refusal ends with the advice.
945        let refused = crate::KernelError::PluginProvidesAppOnly {
946            plugin: "navree-plugin-guard",
947            provider: "dyn navree_contracts::audit::AuditSink",
948            role: app_only_role("dyn navree_contracts::audit::AuditSink"),
949            module: "Provides",
950            reason: String::new(),
951        }
952        .to_string();
953        assert_eq!(
954            refused,
955            "plugin `navree-plugin-guard` provides `dyn navree_contracts::audit::AuditSink` in `Provides`, which receives the app's audit records; only a module of the app registers it: remove the plugin or update it to a version that leaves it to the app, and an app has one audit sink: to use the plugin's, register it from a module of an app that has no other (it cannot be used beside navree-audit's AuditModule)"
956        );
957    }
958
959    /// A namespace is a folder name (`resources/views/<namespace>/`): every word the path
960    /// rule refuses as a Windows device, and that the namespace grammar allows, is reserved.
961    #[test]
962    fn every_namespace_that_names_a_windows_device_is_reserved() {
963        let mut devices = Vec::new();
964        for stem in ["con", "prn", "aux", "nul", "com", "lpt"] {
965            for end in ["", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] {
966                let word = format!("{stem}{end}");
967                if is_namespace(&word) && !crate::publish::is_safe_relative_path(&word) {
968                    assert!(
969                        RESERVED_NAMESPACES.contains(&word.as_str()),
970                        "{word} is not reserved"
971                    );
972                    devices.push(word);
973                }
974            }
975        }
976        assert_eq!(devices.len(), 24, "{devices:?}");
977        for folder in ["layouts", "fonts"] {
978            assert!(RESERVED_NAMESPACES.contains(&folder), "{folder}");
979        }
980    }
981
982    #[test]
983    fn publish_tags_name_their_folders_and_all_lists_three() {
984        assert_eq!(
985            PublishTag::ALL,
986            &[PublishTag::Views, PublishTag::Locales, PublishTag::Files]
987        );
988        let names: Vec<&str> = PublishTag::ALL.iter().map(|tag| tag.as_str()).collect();
989        assert_eq!(names, ["views", "locales", "files"]);
990        for tag in PublishTag::ALL {
991            assert_eq!(PublishTag::from_name(tag.as_str()), Some(*tag));
992        }
993        assert_eq!(PublishTag::from_name("config"), None);
994        assert_eq!(PublishTag::from_name("Views"), None);
995        assert_eq!(
996            destination(PublishTag::Views, "announcements", "admin/list.html"),
997            "resources/views/announcements/admin/list.html"
998        );
999        assert_eq!(
1000            destination(
1001                PublishTag::Locales,
1002                "announcements",
1003                "pa-IN/announcements.ftl",
1004            ),
1005            "locales/pa-IN/announcements/announcements.ftl"
1006        );
1007        assert_eq!(
1008            destination(PublishTag::Files, "announcements", "banner.css"),
1009            "resources/announcements/banner.css"
1010        );
1011        let files = Publishable::new(PublishTag::Views)
1012            .file("list.html", b"<ul></ul>")
1013            .file(String::from("show.html"), b"<p></p>");
1014        assert_eq!(files.tag(), PublishTag::Views);
1015        let listed: Vec<(&str, &[u8])> = files.files().collect();
1016        assert_eq!(
1017            listed,
1018            [
1019                ("list.html", &b"<ul></ul>"[..]),
1020                ("show.html", &b"<p></p>"[..]),
1021            ]
1022        );
1023    }
1024}