Skip to main content

static_authz_plugin/
gear.rs

1//! Static `AuthZ` resolver plugin gear.
2
3use std::sync::{Arc, OnceLock};
4
5use async_trait::async_trait;
6use authz_resolver_sdk::{AuthZResolverPluginClient, AuthZResolverPluginSpecV1};
7use toolkit::Gear;
8use toolkit::context::GearCtx;
9use toolkit::gts::PluginV1;
10use toolkit::gts_publication::GtsPublicationInputs;
11use toolkit::plugins::bind_plugin_instances;
12use tracing::info;
13use types_registry_sdk::GtsId;
14
15use crate::config::StaticAuthZPluginConfig;
16use crate::domain::Service;
17
18/// The GTS segment of this plugin's instance.
19const INSTANCE_SEGMENT: &str = "cf.builtin.static_authz_resolver.plugin.v1";
20
21/// Static `AuthZ` resolver plugin gear.
22///
23/// The runtime publishes the plugin instance built from the configuration
24/// (`entities`) and calls `init` only once it is admitted; `init` binds the
25/// scoped client to the admitted instance, before anything can select it.
26#[toolkit::gear(
27    name = "static-authz-plugin",
28    gts_publication(entities = Self::plugin_instance),
29)]
30#[derive(Default)]
31pub struct StaticAuthZPlugin {
32    service: OnceLock<Arc<dyn AuthZResolverPluginClient>>,
33}
34
35impl StaticAuthZPlugin {
36    /// The publication's config-only documents: the plugin instance.
37    fn plugin_instance(
38        inputs: &GtsPublicationInputs<'_>,
39    ) -> anyhow::Result<Vec<(GtsId, serde_json::Value)>> {
40        let cfg: StaticAuthZPluginConfig = inputs.config_or_default()?;
41        let (id, document) = PluginV1::<AuthZResolverPluginSpecV1>::build_registration(
42            INSTANCE_SEGMENT,
43            cfg.vendor,
44            cfg.priority,
45        )?;
46        Ok(vec![(GtsId::try_new(id.as_ref())?, document)])
47    }
48}
49
50#[async_trait]
51impl Gear for StaticAuthZPlugin {
52    async fn init(&self, ctx: &GearCtx) -> anyhow::Result<()> {
53        let cfg: StaticAuthZPluginConfig = ctx.config_or_default()?;
54        info!(
55            vendor = %cfg.vendor,
56            priority = cfg.priority,
57            "Loaded plugin configuration"
58        );
59        let service: Arc<dyn AuthZResolverPluginClient> = Arc::new(Service::new());
60        self.service
61            .set(Arc::clone(&service))
62            .map_err(|_| anyhow::anyhow!("{} gear already initialized", Self::MODULE_NAME))?;
63        // The instance was admitted before `init`: bind the scoped client to
64        // it, as the admitted manifest lists it.
65        bind_plugin_instances::<AuthZResolverPluginSpecV1, _>(
66            &ctx.client_hub(),
67            ctx.gts_publication_manifest()?.documents(),
68            &service,
69        )
70    }
71}
72
73#[cfg(test)]
74#[cfg_attr(coverage_nightly, coverage(off))]
75#[path = "gear_tests.rs"]
76mod gear_tests;