wacht 0.1.0-beta.5

Official Rust SDK for the Wacht platform, providing type-safe API client and authentication middleware
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! Permission-based authorization layer for Axum.
//!
//! This module provides a Tower Layer for checking permissions after authentication.

#![cfg(feature = "axum")]

use axum::{body::Body, extract::Request, http::StatusCode, response::Response};
use std::{
    future::Future,
    pin::Pin,
    task::{Context, Poll},
};
use tower::{Layer, Service};
use tracing::{debug, error, warn};

use super::auth::{AuthContext, PermissionScope};

/// Helper function to build error responses with sanitized headers
fn build_error_response(status: StatusCode, message: &str) -> Response {
    // Sanitize message for use in headers
    let sanitized_message = message
        .chars()
        .filter(|c| c.is_ascii() && !c.is_control())
        .take(1000)
        .collect::<String>();

    let mut builder = Response::builder().status(status);

    // Add auth headers
    if status == StatusCode::UNAUTHORIZED {
        builder = builder.header("WWW-Authenticate", "Bearer");
    }

    // Try to add X-Auth-Error header
    builder = builder.header("X-Auth-Error", sanitized_message);

    // Build response with body
    builder
        .body(Body::from(message.to_string()))
        .unwrap_or_else(|_| {
            // Fallback response
            Response::builder()
                .status(status)
                .body(Body::from(format!("Error: {status}")))
                .unwrap_or_else(|_| Response::new(Body::from("Error")))
        })
}

/// Layer that checks if authenticated user has required permission.
///
/// This layer should be applied after `AuthLayer` to check specific permissions.
///
/// # Example
/// ```ignore
/// use wacht::middleware::{AuthLayer, PermissionLayer};
///
/// let app = Router::new()
///     .route("/admin", get(admin_handler))
///     .layer(PermissionLayer::organization("admin:read"))
///     .layer(AuthLayer::new());
/// ```
#[derive(Clone)]
pub struct PermissionLayer {
    permission: String,
    scope: PermissionScope,
}

impl PermissionLayer {
    /// Create a permission layer that checks organization-level permission.
    pub fn organization(permission: impl Into<String>) -> Self {
        Self {
            permission: permission.into(),
            scope: PermissionScope::Organization,
        }
    }

    /// Create a permission layer that checks workspace-level permission.
    pub fn workspace(permission: impl Into<String>) -> Self {
        Self {
            permission: permission.into(),
            scope: PermissionScope::Workspace,
        }
    }

    /// Create a permission layer with custom scope.
    pub fn new(permission: impl Into<String>, scope: PermissionScope) -> Self {
        Self {
            permission: permission.into(),
            scope,
        }
    }
}

impl<S> Layer<S> for PermissionLayer {
    type Service = PermissionService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        PermissionService {
            inner,
            permission: self.permission.clone(),
            scope: self.scope.clone(),
        }
    }
}

/// Service that checks permissions before forwarding requests.
#[derive(Clone)]
pub struct PermissionService<S> {
    inner: S,
    permission: String,
    scope: PermissionScope,
}

impl<S> Service<Request<Body>> for PermissionService<S>
where
    S: Service<Request<Body>, Response = Response> + Send + 'static + Clone,
    S::Future: Send + 'static,
{
    type Response = Response;
    type Error = std::convert::Infallible;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        match self.inner.poll_ready(cx) {
            Poll::Ready(Ok(())) => Poll::Ready(Ok(())),
            Poll::Ready(Err(_)) => {
                error!("PermissionService: Inner service poll_ready returned error");
                Poll::Ready(Ok(()))
            }
            Poll::Pending => Poll::Pending,
        }
    }

    fn call(&mut self, req: Request<Body>) -> Self::Future {
        let permission = self.permission.clone();
        let scope = self.scope.clone();
        let mut inner = self.inner.clone();

        Box::pin(async move {
            // Extract auth context from request extensions
            let auth_context = match req.extensions().get::<AuthContext>() {
                Some(ctx) => ctx,
                None => {
                    return Ok(build_error_response(
                        StatusCode::UNAUTHORIZED,
                        "No authentication context found",
                    ));
                }
            };

            // Check permission based on scope
            let has_permission = match scope {
                PermissionScope::Organization => auth_context
                    .permissions
                    .as_ref()
                    .map(|perms| {
                        perms
                            .organization
                            .as_ref()
                            .map(|perms| perms.contains(&permission))
                            .unwrap_or(false)
                    })
                    .unwrap_or(false),
                PermissionScope::Workspace => auth_context
                    .permissions
                    .as_ref()
                    .map(|perms| {
                        perms
                            .workspace
                            .as_ref()
                            .map(|perms| perms.contains(&permission))
                            .unwrap_or(false)
                    })
                    .unwrap_or(false),
            };

            if !has_permission {
                let error_msg = format!("Missing required permission: {permission}");
                return Ok(build_error_response(StatusCode::FORBIDDEN, &error_msg));
            }

            // User has permission, forward to inner service
            match inner.call(req).await {
                Ok(response) => Ok(response),
                Err(_) => {
                    error!("PermissionService: Inner service call failed");
                    Ok(build_error_response(
                        StatusCode::INTERNAL_SERVER_ERROR,
                        "Internal server error",
                    ))
                }
            }
        })
    }
}

/// Create multiple permission layers that all must be satisfied.
///
/// All permissions must be satisfied for the request to proceed.
///
/// # Example
/// ```ignore
/// use wacht::middleware::{AuthLayer, MultiplePermissionLayers};
///
/// let app = Router::new()
///     .route("/super-admin", get(handler))
///     .layer(MultiplePermissionLayers::all(vec![
///         ("admin:read", PermissionScope::Organization),
///         ("admin:write", PermissionScope::Organization),
///     ]))
///     .layer(AuthLayer::new());
/// ```
#[derive(Clone)]
pub struct MultiplePermissionLayers {
    permissions: Vec<(String, PermissionScope)>,
    require_all: bool,
}

impl MultiplePermissionLayers {
    /// Create layers that require all permissions.
    pub fn all(permissions: Vec<(&str, PermissionScope)>) -> Self {
        Self {
            permissions: permissions
                .into_iter()
                .map(|(p, s)| (p.to_string(), s))
                .collect(),
            require_all: true,
        }
    }

    /// Create layers that require any permission.
    pub fn any(permissions: Vec<(&str, PermissionScope)>) -> Self {
        Self {
            permissions: permissions
                .into_iter()
                .map(|(p, s)| (p.to_string(), s))
                .collect(),
            require_all: false,
        }
    }
}

impl<S> Layer<S> for MultiplePermissionLayers {
    type Service = MultiplePermissionService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        MultiplePermissionService {
            inner,
            permissions: self.permissions.clone(),
            require_all: self.require_all,
        }
    }
}

/// Service that checks multiple permissions.
#[derive(Clone)]
pub struct MultiplePermissionService<S> {
    inner: S,
    permissions: Vec<(String, PermissionScope)>,
    require_all: bool,
}

impl<S> Service<Request<Body>> for MultiplePermissionService<S>
where
    S: Service<Request<Body>, Response = Response> + Send + 'static + Clone,
    S::Future: Send + 'static,
{
    type Response = Response;
    type Error = std::convert::Infallible;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        match self.inner.poll_ready(cx) {
            Poll::Ready(Ok(())) => Poll::Ready(Ok(())),
            Poll::Ready(Err(_)) => {
                error!("PermissionService: Inner service poll_ready returned error");
                Poll::Ready(Ok(()))
            }
            Poll::Pending => Poll::Pending,
        }
    }

    fn call(&mut self, req: Request<Body>) -> Self::Future {
        let permissions = self.permissions.clone();
        let require_all = self.require_all;
        let mut inner = self.inner.clone();

        Box::pin(async move {
            // Extract auth context from request extensions
            let auth_context = match req.extensions().get::<AuthContext>() {
                Some(ctx) => ctx,
                None => {
                    return Ok(build_error_response(
                        StatusCode::UNAUTHORIZED,
                        "No authentication context found",
                    ));
                }
            };

            // Check permissions
            let check_permission = |permission: &str, scope: &PermissionScope| -> bool {
                match scope {
                    PermissionScope::Organization => auth_context
                        .permissions
                        .as_ref()
                        .map(|perms| {
                            perms
                                .organization
                                .as_ref()
                                .map(|perms| perms.contains(&permission.to_string()))
                                .unwrap_or(false)
                        })
                        .unwrap_or(false),
                    PermissionScope::Workspace => auth_context
                        .permissions
                        .as_ref()
                        .map(|perms| {
                            perms
                                .workspace
                                .as_ref()
                                .map(|perms| perms.contains(&permission.to_string()))
                                .unwrap_or(false)
                        })
                        .unwrap_or(false),
                }
            };

            let has_permission = if require_all {
                permissions.iter().all(|(p, s)| check_permission(p, s))
            } else {
                permissions.iter().any(|(p, s)| check_permission(p, s))
            };

            if !has_permission {
                let message = if require_all {
                    format!(
                        "Missing required permissions: {}",
                        permissions
                            .iter()
                            .map(|(p, _)| p.as_str())
                            .collect::<Vec<_>>()
                            .join(" AND ")
                    )
                } else {
                    format!(
                        "Missing required permission: {}",
                        permissions
                            .iter()
                            .map(|(p, _)| p.as_str())
                            .collect::<Vec<_>>()
                            .join(" OR ")
                    )
                };

                return Ok(build_error_response(StatusCode::FORBIDDEN, &message));
            }

            // User has permission, forward to inner service
            match inner.call(req).await {
                Ok(response) => Ok(response),
                Err(_) => {
                    error!("PermissionService: Inner service call failed");
                    Ok(build_error_response(
                        StatusCode::INTERNAL_SERVER_ERROR,
                        "Internal server error",
                    ))
                }
            }
        })
    }
}

/// Create a layer that requires at least one of the given permissions.
///
/// # Example
/// ```ignore
/// use wacht::middleware::{AuthLayer, RequireAnyPermissionLayer};
///
/// let app = Router::new()
///     .route("/content", get(handler))
///     .layer(RequireAnyPermissionLayer::new(vec![
///         ("content:read", PermissionScope::Organization),
///         ("content:manage", PermissionScope::Organization),
///     ]))
///     .layer(AuthLayer::new());
/// ```
#[derive(Clone)]
pub struct RequireAnyPermissionLayer {
    permissions: Vec<(String, PermissionScope)>,
}

impl RequireAnyPermissionLayer {
    /// Create a new layer that requires any of the given permissions.
    pub fn new(permissions: Vec<(&str, PermissionScope)>) -> Self {
        Self {
            permissions: permissions
                .into_iter()
                .map(|(p, s)| (p.to_string(), s))
                .collect(),
        }
    }
}

impl<S> Layer<S> for RequireAnyPermissionLayer {
    type Service = RequireAnyPermissionService<S>;

    fn layer(&self, inner: S) -> Self::Service {
        RequireAnyPermissionService {
            inner,
            permissions: self.permissions.clone(),
        }
    }
}

/// Service that checks if user has any of the required permissions.
#[derive(Clone)]
pub struct RequireAnyPermissionService<S> {
    inner: S,
    permissions: Vec<(String, PermissionScope)>,
}

impl<S> Service<Request<Body>> for RequireAnyPermissionService<S>
where
    S: Service<Request<Body>, Response = Response> + Send + 'static + Clone,
    S::Future: Send + 'static,
{
    type Response = Response;
    type Error = std::convert::Infallible;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        match self.inner.poll_ready(cx) {
            Poll::Ready(Ok(())) => Poll::Ready(Ok(())),
            Poll::Ready(Err(_)) => {
                error!("PermissionService: Inner service poll_ready returned error");
                Poll::Ready(Ok(()))
            }
            Poll::Pending => Poll::Pending,
        }
    }

    fn call(&mut self, req: Request<Body>) -> Self::Future {
        let permissions = self.permissions.clone();
        let mut inner = self.inner.clone();

        Box::pin(async move {
            // Extract auth context from request extensions
            let auth_context = match req.extensions().get::<AuthContext>() {
                Some(ctx) => ctx,
                None => {
                    return Ok(build_error_response(
                        StatusCode::UNAUTHORIZED,
                        "No authentication context found",
                    ));
                }
            };

            // Check if user has any of the required permissions
            let has_any_permission = permissions.iter().any(|(permission, scope)| match scope {
                PermissionScope::Organization => auth_context
                    .permissions
                    .as_ref()
                    .map(|perms| {
                        perms
                            .organization
                            .as_ref()
                            .map(|perms| perms.contains(permission))
                            .unwrap_or(false)
                    })
                    .unwrap_or(false),
                PermissionScope::Workspace => auth_context
                    .permissions
                    .as_ref()
                    .map(|perms| {
                        perms
                            .workspace
                            .as_ref()
                            .map(|perms| perms.contains(permission))
                            .unwrap_or(false)
                    })
                    .unwrap_or(false),
            });

            if !has_any_permission {
                let permission_list = permissions
                    .iter()
                    .map(|(p, _)| p.as_str())
                    .collect::<Vec<_>>()
                    .join(" OR ");

                let error_msg = format!("Missing required permission: {permission_list}");
                return Ok(build_error_response(StatusCode::FORBIDDEN, &error_msg));
            }

            // User has at least one permission, forward to inner service
            match inner.call(req).await {
                Ok(response) => Ok(response),
                Err(_) => {
                    error!("PermissionService: Inner service call failed");
                    Ok(build_error_response(
                        StatusCode::INTERNAL_SERVER_ERROR,
                        "Internal server error",
                    ))
                }
            }
        })
    }
}