hyperlane-plugin-tenant 23.3.0

A zero-allocation multi-tenant resolution and isolation plugin for the Hyperlane framework supporting X-Tenant-Id header, Host subdomain, and path-prefix extraction, XxHash3_64 tenant registry, pluggable TenantResolver, and prebuilt 400/403/404 wire responses.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use super::*;

/// Constructors for [`TenantRecord`].
impl TenantRecord {
    /// Creates an active [`TenantRecord`] with `id` and `plan`.
    ///
    /// # Arguments
    ///
    /// - `I` - Tenant identifier.
    /// - `P` - Subscription plan or tier name.
    ///
    /// # Returns
    ///
    /// - `Self` - Active tenant record.
    pub fn active<I, P>(id: I, plan: P) -> Self
    where
        I: Into<String>,
        P: Into<String>,
    {
        Self {
            id: id.into(),
            status: TenantStatus::Active,
            plan: plan.into(),
        }
    }

    /// Creates a suspended [`TenantRecord`] that causes requests to receive `403 Forbidden`.
    ///
    /// # Arguments
    ///
    /// - `I` - Tenant identifier.
    ///
    /// # Returns
    ///
    /// - `Self` - Suspended tenant record.
    pub fn suspended<I>(id: I) -> Self
    where
        I: Into<String>,
    {
        Self {
            id: id.into(),
            status: TenantStatus::Suspended,
            plan: String::new(),
        }
    }
}

/// Context extraction helper for [`TenantContext`].
impl TenantContext {
    /// Retrieves the resolved [`TenantContext`] attached by [`TenantHook`] from `ctx`.
    ///
    /// # Arguments
    ///
    /// - `&Context` - Active Hyperlane request context.
    ///
    /// # Returns
    ///
    /// - `Option<Self>` - Resolved tenant context, if present.
    #[inline]
    pub fn from_context(ctx: &Context) -> Option<Self> {
        ctx.try_get_attribute::<Self, _>(ATTR_TENANT_CONTEXT)
    }
}

/// Default construction for [`TenantConfig`].
impl Default for TenantConfig {
    /// Constructs a [`TenantConfig`] inspecting `x-tenant-id` without requiring pre-registration.
    ///
    /// # Returns
    ///
    /// - `Self` - Default configuration.
    fn default() -> Self {
        Self {
            header_name: DEFAULT_TENANT_HEADER.to_owned(),
            base_domain: None,
            path_prefix: None,
            default_tenant: None,
            require_known: false,
            tenants: Vec::new(),
            exempt_prefixes: Vec::new(),
        }
    }
}

/// Fluent builder helpers for [`TenantConfig`].
impl TenantConfig {
    /// Configures subdomain extraction under `base_domain` (for example `"app.example.com"`).
    ///
    /// # Arguments
    ///
    /// - `D` - Base domain without leading dot.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_base_domain<D>(mut self, base_domain: D) -> Self
    where
        D: Into<String>,
    {
        self.set_base_domain(Some(base_domain.into()));
        self
    }

    /// Configures path-prefix tenant extraction (for example `"/t"` matches `"/t/acme/..."`).
    ///
    /// # Arguments
    ///
    /// - `P` - Leading path prefix.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_path_prefix<P>(mut self, prefix: P) -> Self
    where
        P: Into<String>,
    {
        self.set_path_prefix(Some(prefix.into()));
        self
    }

    /// Configures whether unknown tenant IDs are rejected with `404 Not Found`.
    ///
    /// # Arguments
    ///
    /// - `bool` - Require tenant registration.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_require_known(mut self, require: bool) -> Self {
        self.set_require_known(require);
        self
    }

    /// Registers a static [`TenantRecord`] in the compiled directory.
    ///
    /// # Arguments
    ///
    /// - `TenantRecord` - Tenant metadata entry.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_tenant(mut self, record: TenantRecord) -> Self {
        self.get_mut_tenants().push(record);
        self
    }

    /// Configures path prefixes exempt from tenant resolution.
    ///
    /// # Arguments
    ///
    /// - `I` - Iterator of exempt prefixes.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_exempt_prefixes<I, S>(mut self, prefixes: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.set_exempt_prefixes(prefixes.into_iter().map(Into::into).collect());
        self
    }
}

/// Resolution engine for [`TenantPlugin`].
impl TenantPlugin {
    /// Compiles a standalone [`TenantPlugin`] from `config` and an optional custom [`TenantResolver`].
    ///
    /// # Arguments
    ///
    /// - `TenantConfig` - Tenant configuration.
    /// - `Option<Arc<dyn TenantResolver>>` - Optional dynamic resolver.
    ///
    /// # Returns
    ///
    /// - `Self` - Compiled plugin.
    pub fn new(config: TenantConfig, resolver: Option<Arc<dyn TenantResolver>>) -> Self {
        let header_lower: String = config.get_header_name().trim().to_ascii_lowercase();
        let dot_base_domain: Option<String> =
            config
                .try_get_base_domain()
                .as_ref()
                .and_then(|d: &String| {
                    let clean: &str = d.trim().trim_start_matches('.');
                    if clean.is_empty() {
                        None
                    } else {
                        Some(format!(".{}", clean.to_ascii_lowercase()))
                    }
                });
        let normalized_path_prefix: Option<String> = config
            .try_get_path_prefix()
            .as_ref()
            .map(|p: &String| normalize_prefix(p));
        let exempt_prefixes: Box<[String]> = config
            .get_exempt_prefixes()
            .iter()
            .filter(|p: &&String| !p.trim().is_empty())
            .map(|p: &String| normalize_prefix(p))
            .collect::<Vec<String>>()
            .into_boxed_slice();
        let mut registry: HashMapXxHash3_64<String, TenantRecord> = hash_map_xx_hash3_64();
        for rec in config.get_tenants() {
            registry.insert(rec.get_id().clone(), rec.clone());
        }
        let missing_wire: Vec<u8> =
            build_error_wire(HttpStatus::BadRequest, DEFAULT_MISSING_TENANT_BODY);
        let unknown_wire: Vec<u8> =
            build_error_wire(HttpStatus::NotFound, DEFAULT_UNKNOWN_TENANT_BODY);
        let suspended_wire: Vec<u8> =
            build_error_wire(HttpStatus::Forbidden, DEFAULT_SUSPENDED_TENANT_BODY);
        Self {
            config,
            header_lower,
            dot_base_domain,
            normalized_path_prefix,
            exempt_prefixes,
            registry,
            resolver,
            missing_wire,
            unknown_wire,
            suspended_wire,
        }
    }

    /// Initializes the global [`TenantPlugin`] singleton once.
    ///
    /// # Arguments
    ///
    /// - `TenantConfig` - Tenant configuration.
    ///
    /// # Returns
    ///
    /// - `&'static Self` - Reference to the global plugin.
    pub fn init(config: TenantConfig) -> &'static Self {
        TENANT_PLUGIN.get_or_init(|| Self::new(config, None))
    }

    /// Initializes the global [`TenantPlugin`] singleton with a custom [`TenantResolver`].
    ///
    /// # Arguments
    ///
    /// - `TenantConfig` - Tenant configuration.
    /// - `Arc<dyn TenantResolver>` - Dynamic tenant resolver.
    ///
    /// # Returns
    ///
    /// - `&'static Self` - Reference to the global plugin.
    pub fn init_with_resolver(
        config: TenantConfig,
        resolver: Arc<dyn TenantResolver>,
    ) -> &'static Self {
        TENANT_PLUGIN.get_or_init(|| Self::new(config, Some(resolver)))
    }

    /// Returns the initialized global [`TenantPlugin`], if configured.
    ///
    /// # Returns
    ///
    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
    #[inline(always)]
    pub fn get() -> Option<&'static Self> {
        TENANT_PLUGIN.get()
    }

    /// Resolves tenant identity and status for `request`.
    ///
    /// # Arguments
    ///
    /// - `&Request` - Incoming HTTP request.
    ///
    /// # Returns
    ///
    /// - `TenantResolution` - Exempt, Resolved, Missing, Unknown, or Suspended outcome.
    #[inline]
    pub fn resolve(&self, request: &Request) -> TenantResolution {
        let Self {
            config,
            header_lower,
            dot_base_domain,
            normalized_path_prefix,
            exempt_prefixes,
            registry,
            resolver,
            ..
        } = self;
        let path: &str = request.get_path();
        if exempt_prefixes
            .iter()
            .any(|p: &String| path_matches_prefix(path, p))
        {
            return TenantResolution::Exempt;
        }
        let extracted: Option<(&str, TenantSource)> = if !header_lower.is_empty()
            && let Some(val) = request
                .get_headers()
                .get(header_lower.as_str())
                .and_then(|vals: &VecDeque<String>| vals.back())
            && is_valid_tenant_id(val.trim())
        {
            Some((val.trim(), TenantSource::Header))
        } else if let Some(dot_base) = dot_base_domain
            && let Some(host_val) = request
                .get_headers()
                .get(HOST)
                .and_then(|vals: &VecDeque<String>| vals.back())
            && let Some(sub) = extract_subdomain(host_val, dot_base)
        {
            Some((sub, TenantSource::Subdomain))
        } else if let Some(prefix) = normalized_path_prefix
            && let Some(seg) = extract_path_tenant(path, prefix)
        {
            Some((seg, TenantSource::PathPrefix))
        } else if let Some(default_id) = config.try_get_default_tenant() {
            Some((default_id.as_str(), TenantSource::Default))
        } else {
            None
        };
        let Some((tenant_id, source)) = extracted else {
            return TenantResolution::Missing;
        };
        if let Some(rec) = registry.get(tenant_id) {
            return match rec.get_status() {
                TenantStatus::Active => TenantResolution::Resolved(TenantContext {
                    tenant_id: rec.get_id().clone(),
                    plan: rec.get_plan().clone(),
                    source,
                }),
                TenantStatus::Suspended => TenantResolution::Suspended,
            };
        }
        if let Some(custom) = resolver
            && let Some(rec) = custom.resolve(tenant_id)
        {
            return match rec.get_status() {
                TenantStatus::Active => TenantResolution::Resolved(TenantContext {
                    tenant_id: rec.get_id().clone(),
                    plan: rec.get_plan().clone(),
                    source,
                }),
                TenantStatus::Suspended => TenantResolution::Suspended,
            };
        }
        if config.get_require_known() {
            TenantResolution::Unknown
        } else {
            TenantResolution::Resolved(TenantContext {
                tenant_id: tenant_id.to_owned(),
                plan: String::new(),
                source,
            })
        }
    }
}

/// Implements [`ServerHook`] for [`TenantHook`].
impl ServerHook for TenantHook {
    /// Constructs a per-request [`TenantHook`].
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Self` - Hook instance.
    #[inline(always)]
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    /// Resolves tenant identity, rejects invalid/unknown/suspended tenants, and attaches [`TenantContext`].
    ///
    /// # Arguments
    ///
    /// - `Self` - Hook instance.
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Status` - `Status::Continue` when admitted; `Status::Reject` on `400`/`403`/`404`.
    #[inline(always)]
    async fn handle(self, stream: &mut Stream, ctx: &mut Context) -> Status {
        let Some(plugin) = TenantPlugin::get() else {
            return Status::Continue;
        };
        match plugin.resolve(ctx.get_request()) {
            TenantResolution::Exempt => Status::Continue,
            TenantResolution::Resolved(tenant_ctx) => {
                ctx.set_attribute(ATTR_TENANT_CONTEXT, tenant_ctx);
                Status::Continue
            }
            TenantResolution::Missing => {
                let TenantPlugin { missing_wire, .. } = plugin;
                let _: Result<(), ResponseError> = stream.try_send(missing_wire).await;
                Status::Reject
            }
            TenantResolution::Unknown => {
                let TenantPlugin { unknown_wire, .. } = plugin;
                let _: Result<(), ResponseError> = stream.try_send(unknown_wire).await;
                Status::Reject
            }
            TenantResolution::Suspended => {
                let TenantPlugin { suspended_wire, .. } = plugin;
                let _: Result<(), ResponseError> = stream.try_send(suspended_wire).await;
                Status::Reject
            }
        }
    }
}