Skip to main content

hyperlane_plugin_tenant/
impl.rs

1use super::*;
2
3/// Constructors for [`TenantRecord`].
4impl TenantRecord {
5    /// Creates an active [`TenantRecord`] with `id` and `plan`.
6    ///
7    /// # Arguments
8    ///
9    /// - `I` - Tenant identifier.
10    /// - `P` - Subscription plan or tier name.
11    ///
12    /// # Returns
13    ///
14    /// - `Self` - Active tenant record.
15    pub fn active<I, P>(id: I, plan: P) -> Self
16    where
17        I: Into<String>,
18        P: Into<String>,
19    {
20        Self {
21            id: id.into(),
22            status: TenantStatus::Active,
23            plan: plan.into(),
24        }
25    }
26
27    /// Creates a suspended [`TenantRecord`] that causes requests to receive `403 Forbidden`.
28    ///
29    /// # Arguments
30    ///
31    /// - `I` - Tenant identifier.
32    ///
33    /// # Returns
34    ///
35    /// - `Self` - Suspended tenant record.
36    pub fn suspended<I>(id: I) -> Self
37    where
38        I: Into<String>,
39    {
40        Self {
41            id: id.into(),
42            status: TenantStatus::Suspended,
43            plan: String::new(),
44        }
45    }
46}
47
48/// Context extraction helper for [`TenantContext`].
49impl TenantContext {
50    /// Retrieves the resolved [`TenantContext`] attached by [`TenantHook`] from `ctx`.
51    ///
52    /// # Arguments
53    ///
54    /// - `&Context` - Active Hyperlane request context.
55    ///
56    /// # Returns
57    ///
58    /// - `Option<Self>` - Resolved tenant context, if present.
59    #[inline]
60    pub fn from_context(ctx: &Context) -> Option<Self> {
61        ctx.try_get_attribute::<Self, _>(ATTR_TENANT_CONTEXT)
62    }
63}
64
65/// Default construction for [`TenantConfig`].
66impl Default for TenantConfig {
67    /// Constructs a [`TenantConfig`] inspecting `x-tenant-id` without requiring pre-registration.
68    ///
69    /// # Returns
70    ///
71    /// - `Self` - Default configuration.
72    fn default() -> Self {
73        Self {
74            header_name: DEFAULT_TENANT_HEADER.to_owned(),
75            base_domain: None,
76            path_prefix: None,
77            default_tenant: None,
78            require_known: false,
79            tenants: Vec::new(),
80            exempt_prefixes: Vec::new(),
81        }
82    }
83}
84
85/// Fluent builder helpers for [`TenantConfig`].
86impl TenantConfig {
87    /// Configures subdomain extraction under `base_domain` (for example `"app.example.com"`).
88    ///
89    /// # Arguments
90    ///
91    /// - `D` - Base domain without leading dot.
92    ///
93    /// # Returns
94    ///
95    /// - `Self` - Updated configuration.
96    pub fn with_base_domain<D>(mut self, base_domain: D) -> Self
97    where
98        D: Into<String>,
99    {
100        self.set_base_domain(Some(base_domain.into()));
101        self
102    }
103
104    /// Configures path-prefix tenant extraction (for example `"/t"` matches `"/t/acme/..."`).
105    ///
106    /// # Arguments
107    ///
108    /// - `P` - Leading path prefix.
109    ///
110    /// # Returns
111    ///
112    /// - `Self` - Updated configuration.
113    pub fn with_path_prefix<P>(mut self, prefix: P) -> Self
114    where
115        P: Into<String>,
116    {
117        self.set_path_prefix(Some(prefix.into()));
118        self
119    }
120
121    /// Configures whether unknown tenant IDs are rejected with `404 Not Found`.
122    ///
123    /// # Arguments
124    ///
125    /// - `bool` - Require tenant registration.
126    ///
127    /// # Returns
128    ///
129    /// - `Self` - Updated configuration.
130    pub fn with_require_known(mut self, require: bool) -> Self {
131        self.set_require_known(require);
132        self
133    }
134
135    /// Registers a static [`TenantRecord`] in the compiled directory.
136    ///
137    /// # Arguments
138    ///
139    /// - `TenantRecord` - Tenant metadata entry.
140    ///
141    /// # Returns
142    ///
143    /// - `Self` - Updated configuration.
144    pub fn with_tenant(mut self, record: TenantRecord) -> Self {
145        self.get_mut_tenants().push(record);
146        self
147    }
148
149    /// Configures path prefixes exempt from tenant resolution.
150    ///
151    /// # Arguments
152    ///
153    /// - `I` - Iterator of exempt prefixes.
154    ///
155    /// # Returns
156    ///
157    /// - `Self` - Updated configuration.
158    pub fn with_exempt_prefixes<I, S>(mut self, prefixes: I) -> Self
159    where
160        I: IntoIterator<Item = S>,
161        S: Into<String>,
162    {
163        self.set_exempt_prefixes(prefixes.into_iter().map(Into::into).collect());
164        self
165    }
166}
167
168/// Resolution engine for [`TenantPlugin`].
169impl TenantPlugin {
170    /// Compiles a standalone [`TenantPlugin`] from `config` and an optional custom [`TenantResolver`].
171    ///
172    /// # Arguments
173    ///
174    /// - `TenantConfig` - Tenant configuration.
175    /// - `Option<Arc<dyn TenantResolver>>` - Optional dynamic resolver.
176    ///
177    /// # Returns
178    ///
179    /// - `Self` - Compiled plugin.
180    pub fn new(config: TenantConfig, resolver: Option<Arc<dyn TenantResolver>>) -> Self {
181        let header_lower: String = config.get_header_name().trim().to_ascii_lowercase();
182        let dot_base_domain: Option<String> =
183            config
184                .try_get_base_domain()
185                .as_ref()
186                .and_then(|d: &String| {
187                    let clean: &str = d.trim().trim_start_matches('.');
188                    if clean.is_empty() {
189                        None
190                    } else {
191                        Some(format!(".{}", clean.to_ascii_lowercase()))
192                    }
193                });
194        let normalized_path_prefix: Option<String> = config
195            .try_get_path_prefix()
196            .as_ref()
197            .map(|p: &String| normalize_prefix(p));
198        let exempt_prefixes: Box<[String]> = config
199            .get_exempt_prefixes()
200            .iter()
201            .filter(|p: &&String| !p.trim().is_empty())
202            .map(|p: &String| normalize_prefix(p))
203            .collect::<Vec<String>>()
204            .into_boxed_slice();
205        let mut registry: HashMapXxHash3_64<String, TenantRecord> = hash_map_xx_hash3_64();
206        for rec in config.get_tenants() {
207            registry.insert(rec.get_id().clone(), rec.clone());
208        }
209        let missing_wire: Vec<u8> =
210            build_error_wire(HttpStatus::BadRequest, DEFAULT_MISSING_TENANT_BODY);
211        let unknown_wire: Vec<u8> =
212            build_error_wire(HttpStatus::NotFound, DEFAULT_UNKNOWN_TENANT_BODY);
213        let suspended_wire: Vec<u8> =
214            build_error_wire(HttpStatus::Forbidden, DEFAULT_SUSPENDED_TENANT_BODY);
215        Self {
216            config,
217            header_lower,
218            dot_base_domain,
219            normalized_path_prefix,
220            exempt_prefixes,
221            registry,
222            resolver,
223            missing_wire,
224            unknown_wire,
225            suspended_wire,
226        }
227    }
228
229    /// Initializes the global [`TenantPlugin`] singleton once.
230    ///
231    /// # Arguments
232    ///
233    /// - `TenantConfig` - Tenant configuration.
234    ///
235    /// # Returns
236    ///
237    /// - `&'static Self` - Reference to the global plugin.
238    pub fn init(config: TenantConfig) -> &'static Self {
239        TENANT_PLUGIN.get_or_init(|| Self::new(config, None))
240    }
241
242    /// Initializes the global [`TenantPlugin`] singleton with a custom [`TenantResolver`].
243    ///
244    /// # Arguments
245    ///
246    /// - `TenantConfig` - Tenant configuration.
247    /// - `Arc<dyn TenantResolver>` - Dynamic tenant resolver.
248    ///
249    /// # Returns
250    ///
251    /// - `&'static Self` - Reference to the global plugin.
252    pub fn init_with_resolver(
253        config: TenantConfig,
254        resolver: Arc<dyn TenantResolver>,
255    ) -> &'static Self {
256        TENANT_PLUGIN.get_or_init(|| Self::new(config, Some(resolver)))
257    }
258
259    /// Returns the initialized global [`TenantPlugin`], if configured.
260    ///
261    /// # Returns
262    ///
263    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
264    #[inline(always)]
265    pub fn get() -> Option<&'static Self> {
266        TENANT_PLUGIN.get()
267    }
268
269    /// Resolves tenant identity and status for `request`.
270    ///
271    /// # Arguments
272    ///
273    /// - `&Request` - Incoming HTTP request.
274    ///
275    /// # Returns
276    ///
277    /// - `TenantResolution` - Exempt, Resolved, Missing, Unknown, or Suspended outcome.
278    #[inline]
279    pub fn resolve(&self, request: &Request) -> TenantResolution {
280        let Self {
281            config,
282            header_lower,
283            dot_base_domain,
284            normalized_path_prefix,
285            exempt_prefixes,
286            registry,
287            resolver,
288            ..
289        } = self;
290        let path: &str = request.get_path();
291        if exempt_prefixes
292            .iter()
293            .any(|p: &String| path_matches_prefix(path, p))
294        {
295            return TenantResolution::Exempt;
296        }
297        let extracted: Option<(&str, TenantSource)> = if !header_lower.is_empty()
298            && let Some(val) = request
299                .get_headers()
300                .get(header_lower.as_str())
301                .and_then(|vals: &VecDeque<String>| vals.back())
302            && is_valid_tenant_id(val.trim())
303        {
304            Some((val.trim(), TenantSource::Header))
305        } else if let Some(dot_base) = dot_base_domain
306            && let Some(host_val) = request
307                .get_headers()
308                .get(HOST)
309                .and_then(|vals: &VecDeque<String>| vals.back())
310            && let Some(sub) = extract_subdomain(host_val, dot_base)
311        {
312            Some((sub, TenantSource::Subdomain))
313        } else if let Some(prefix) = normalized_path_prefix
314            && let Some(seg) = extract_path_tenant(path, prefix)
315        {
316            Some((seg, TenantSource::PathPrefix))
317        } else if let Some(default_id) = config.try_get_default_tenant() {
318            Some((default_id.as_str(), TenantSource::Default))
319        } else {
320            None
321        };
322        let Some((tenant_id, source)) = extracted else {
323            return TenantResolution::Missing;
324        };
325        if let Some(rec) = registry.get(tenant_id) {
326            return match rec.get_status() {
327                TenantStatus::Active => TenantResolution::Resolved(TenantContext {
328                    tenant_id: rec.get_id().clone(),
329                    plan: rec.get_plan().clone(),
330                    source,
331                }),
332                TenantStatus::Suspended => TenantResolution::Suspended,
333            };
334        }
335        if let Some(custom) = resolver
336            && let Some(rec) = custom.resolve(tenant_id)
337        {
338            return match rec.get_status() {
339                TenantStatus::Active => TenantResolution::Resolved(TenantContext {
340                    tenant_id: rec.get_id().clone(),
341                    plan: rec.get_plan().clone(),
342                    source,
343                }),
344                TenantStatus::Suspended => TenantResolution::Suspended,
345            };
346        }
347        if config.get_require_known() {
348            TenantResolution::Unknown
349        } else {
350            TenantResolution::Resolved(TenantContext {
351                tenant_id: tenant_id.to_owned(),
352                plan: String::new(),
353                source,
354            })
355        }
356    }
357}
358
359/// Implements [`ServerHook`] for [`TenantHook`].
360impl ServerHook for TenantHook {
361    /// Constructs a per-request [`TenantHook`].
362    ///
363    /// # Arguments
364    ///
365    /// - `&mut Stream` - Connection stream.
366    /// - `&mut Context` - Request context.
367    ///
368    /// # Returns
369    ///
370    /// - `Self` - Hook instance.
371    #[inline(always)]
372    async fn new(_: &mut Stream, _: &mut Context) -> Self {
373        Self
374    }
375
376    /// Resolves tenant identity, rejects invalid/unknown/suspended tenants, and attaches [`TenantContext`].
377    ///
378    /// # Arguments
379    ///
380    /// - `Self` - Hook instance.
381    /// - `&mut Stream` - Connection stream.
382    /// - `&mut Context` - Request context.
383    ///
384    /// # Returns
385    ///
386    /// - `Status` - `Status::Continue` when admitted; `Status::Reject` on `400`/`403`/`404`.
387    #[inline(always)]
388    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
389        let Some(plugin) = TenantPlugin::get() else {
390            return Status::Continue;
391        };
392        match plugin.resolve(ctx.get_request()) {
393            TenantResolution::Exempt => Status::Continue,
394            TenantResolution::Resolved(tenant_ctx) => {
395                ctx.set_attribute(ATTR_TENANT_CONTEXT, tenant_ctx);
396                Status::Continue
397            }
398            TenantResolution::Missing => {
399                let TenantPlugin { missing_wire, .. } = plugin;
400                let _: Result<(), ResponseError> = stream.try_send(missing_wire).await;
401                Status::Reject
402            }
403            TenantResolution::Unknown => {
404                let TenantPlugin { unknown_wire, .. } = plugin;
405                let _: Result<(), ResponseError> = stream.try_send(unknown_wire).await;
406                Status::Reject
407            }
408            TenantResolution::Suspended => {
409                let TenantPlugin { suspended_wire, .. } = plugin;
410                let _: Result<(), ResponseError> = stream.try_send(suspended_wire).await;
411                Status::Reject
412            }
413        }
414    }
415}