cerbos 0.5.0

Rust SDK for working with Cerbos: an open core, language-agnostic, scalable authorization solution
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
// Copyright 2021-2025 Zenauth Ltd.
// SPDX-License-Identifier: Apache-2.0
use std::time::Duration;

use tokio::runtime::{Builder, Runtime};
use tonic::{
    codegen::InterceptedService,
    metadata::Ascii,
    metadata::MetadataValue,
    service::Interceptor,
    transport::{Certificate, Channel, ClientTlsConfig, Uri},
    Request, Status,
};
use tower::service_fn;
use uuid::Uuid;

use crate::genpb::cerbos::{
    request::v1::{CheckResourcesRequest, PlanResourcesRequest},
    svc::v1::cerbos_service_client::CerbosServiceClient,
};

use self::model::{ProtobufWrapper, Resource, ResourceList};
use anyhow::Context;
use hyper_util::rt::TokioIo;

pub mod attr;

#[cfg(feature = "testcontainers")]
pub mod container;

#[cfg(feature = "hub")]
pub mod hub;

#[cfg(feature = "admin")]
pub mod admin;

#[cfg(feature = "serde")]
pub mod deser;

pub mod model;

pub type Result<T> = anyhow::Result<T>;

/// Cerbos gRPC endpoint kind.
#[derive(Debug)]
pub enum CerbosEndpoint<S>
where
    S: Into<String> + Send,
{
    HostPort(S, u16),
    #[cfg(unix)]
    UnixDomainSocket(S),
}

/// Options for constructing the Cerbos client.
pub struct CerbosClientOptions<S>
where
    S: Into<String> + Send,
{
    endpoint: CerbosEndpoint<S>,
    tls_config: Option<ClientTlsConfig>,
    timeout: Duration,
    request_id_gen: fn() -> String,
    playground_instance: Option<String>,
    user_agent: String,
    #[cfg(feature = "admin")]
    admin_creds: Option<admin::BasicAuth>,
}

impl<S> CerbosClientOptions<S>
where
    S: Into<String> + Send,
{
    pub fn new(endpoint: CerbosEndpoint<S>) -> Self {
        Self {
            endpoint,
            tls_config: Some(ClientTlsConfig::new()),
            timeout: Duration::from_secs(2),
            request_id_gen: gen_uuid,
            playground_instance: None,
            user_agent: "cerbos-rs".to_string(),
            #[cfg(feature = "admin")]
            admin_creds: None,
        }
    }

    /// Disable TLS
    pub fn with_plaintext(mut self) -> Self {
        self.tls_config = None;
        self
    }

    /// Set timeout for API calls
    pub fn with_timeout(mut self, duration: Duration) -> Self {
        self.timeout = duration;
        self
    }

    /// Domain name in the TLS certificate.
    pub fn with_tls_domain_name(mut self, domain: impl Into<String>) -> Self {
        self.tls_config = self
            .tls_config
            .or_else(|| Some(ClientTlsConfig::new()))
            .map(|c| c.domain_name(domain));
        self
    }

    /// CA cert to verify the server TLS certificate.
    pub fn with_tls_ca_cert_pem(mut self, pem: impl AsRef<[u8]>) -> Self {
        let cert = Certificate::from_pem(pem);

        self.tls_config = self
            .tls_config
            .or_else(|| Some(ClientTlsConfig::new()))
            .map(|c| c.ca_certificate(cert));
        self
    }

    /// Request ID generator to use. Defaults to UUID.
    pub fn with_request_id_gen(mut self, id_gen: fn() -> String) -> Self {
        self.request_id_gen = id_gen;
        self
    }

    /// Configure the client to use the Cerbos playground.
    pub fn with_playground_instance(mut self, id: impl Into<String>) -> Self {
        self.playground_instance = Some(id.into());
        self
    }

    /// Set a custom user agent for the client.
    pub fn with_user_agent(mut self, ua: impl Into<String>) -> Self {
        self.user_agent = ua.into();
        self
    }
    #[cfg(feature = "admin")]
    pub fn with_admin_credentials(
        mut self,
        username: impl Into<String>,
        password: impl Into<String>,
    ) -> Self {
        use admin::BasicAuth;

        self.admin_creds = Some(BasicAuth::new(username.into(), password.into()));
        self
    }
    pub(crate) fn build_channel(self) -> Result<Channel> {
        match self.endpoint {
            CerbosEndpoint::HostPort(host, port) => {
                let protocol = self.tls_config.as_ref().map_or_else(|| "http", |_| "https");
                let endpoint_addr = format!("{}://{}:{}", protocol, host.into(), port);
                let mut endpoint = Channel::from_shared(endpoint_addr.clone())
                    .with_context(|| format!("Failed to create channel for {endpoint_addr}"))?
                    .connect_timeout(self.timeout)
                    .timeout(self.timeout)
                    .user_agent(self.user_agent.clone())
                    .with_context(|| "Failed to create channel")?;

                endpoint = match self.tls_config {
                    Some(tc) => endpoint
                        .tls_config(tc)
                        .with_context(|| "Failed to create TLS configuration")?,
                    None => endpoint,
                };

                Ok(endpoint.connect_lazy())
            }
            #[cfg(unix)]
            CerbosEndpoint::UnixDomainSocket(path) => {
                let mut endpoint = Channel::from_static("https://127.0.0.1:3593")
                    .connect_timeout(self.timeout)
                    .timeout(self.timeout)
                    .user_agent(self.user_agent.clone())
                    .with_context(|| "Failed to create channel")?;

                endpoint = match self.tls_config {
                    Some(tc) => endpoint
                        .tls_config(tc)
                        .with_context(|| "Failed to create TLS configuration")?,
                    None => endpoint,
                };

                let uds: &'static str = Box::leak(path.into().into_boxed_str());
                let connect = move |_: Uri| async {
                    tokio::net::UnixStream::connect(uds.to_string())
                        .await
                        .map(TokioIo::new)
                };
                Ok(endpoint.connect_with_connector_lazy(service_fn(connect)))
            }
        }
    }
}

/// Asynchronous Cerbos client
pub struct CerbosAsyncClient {
    stub: CerbosServiceClient<InterceptedService<Channel, CerbosInterceptor>>,
    request_id_gen: fn() -> String,
}

impl CerbosAsyncClient {
    /// Create a new Cerbos client using client options
    pub async fn new<S>(conf: CerbosClientOptions<S>) -> Result<Self>
    where
        S: Into<String> + Send,
    {
        let playground_instance = match conf.playground_instance {
            Some(ref instance) => Some(instance.parse()?),
            None => None,
        };

        let request_timeout = conf.timeout;
        let request_id_gen = conf.request_id_gen;
        let channel = conf.build_channel()?;
        let stub = CerbosServiceClient::with_interceptor(
            channel,
            CerbosInterceptor {
                playground_instance,
                request_timeout,
            },
        );

        Ok(Self {
            stub,
            request_id_gen,
        })
    }

    /// Check access to multiple resources
    pub async fn check_resources(
        &mut self,
        principal: model::Principal,
        resources: model::ResourceList,
        aux_data: Option<model::AuxData>,
    ) -> Result<model::CheckResourcesResponse> {
        let req = CheckResourcesRequest {
            request_id: (self.request_id_gen)(),
            principal: Some(principal.to_pb()),
            resources: resources.resources,
            aux_data: aux_data.map(|a| a.to_pb()),
            ..Default::default()
        };

        let resp = self
            .stub
            .check_resources(req)
            .await
            .with_context(|| "CheckResources call failed")?;

        Ok(model::CheckResourcesResponse {
            response: resp.get_ref().to_owned(),
        })
    }

    /// Check access to a single resource
    pub async fn is_allowed<S>(
        &mut self,
        action: S,
        principal: model::Principal,
        resource: Resource,
        aux_data: Option<model::AuxData>,
    ) -> Result<bool>
    where
        S: Into<String> + Clone,
    {
        let resp = self
            .check_resources(
                principal,
                ResourceList::new().add(resource, [action.clone()]),
                aux_data,
            )
            .await?;
        Ok(resp
            .iter()
            .next()
            .map(|r| r.is_allowed(action.into()))
            .unwrap_or(false))
    }

    /// Produce a query plan for selecting resources that the principal can perform the given
    /// action on.
    pub async fn plan_resources<S>(
        &mut self,
        action: S,
        principal: model::Principal,
        resource: model::ResourceKind,
        aux_data: Option<model::AuxData>,
    ) -> Result<model::PlanResourcesResponse>
    where
        S: Into<String> + Clone,
    {
        #[allow(deprecated)]
        let req = PlanResourcesRequest {
            request_id: (self.request_id_gen)(),
            action: action.into(),
            principal: Some(principal.to_pb()),
            resource: Some(resource.to_pb()),
            aux_data: aux_data.map(|a| a.to_pb()),
            ..Default::default()
        };

        let resp = self
            .stub
            .plan_resources(req)
            .await
            .with_context(|| "PlanResources call failed")?;

        Ok(model::PlanResourcesResponse {
            response: resp.get_ref().to_owned(),
        })
    }

    /// Produce a query plan for selecting resources that the principal can perform the given
    /// actions on. Requires Cerbos 0.44.0 and above.
    pub async fn plan_resources_for_actions<A, S>(
        &mut self,
        actions: A,
        principal: model::Principal,
        resource: model::ResourceKind,
        aux_data: Option<model::AuxData>,
    ) -> Result<model::PlanResourcesResponse>
    where
        S: Into<String> + Clone,
        A: IntoIterator<Item = S>,
    {
        let req = PlanResourcesRequest {
            request_id: (self.request_id_gen)(),
            actions: actions.into_iter().map(|a| a.into()).collect(),
            principal: Some(principal.to_pb()),
            resource: Some(resource.to_pb()),
            aux_data: aux_data.map(|a| a.to_pb()),
            ..Default::default()
        };

        let resp = self
            .stub
            .plan_resources(req)
            .await
            .with_context(|| "PlanResources call failed")?;

        Ok(model::PlanResourcesResponse {
            response: resp.get_ref().to_owned(),
        })
    }
}

pub struct CerbosSyncClient {
    runtime: Runtime,
    client: CerbosAsyncClient,
}

impl CerbosSyncClient {
    pub fn new<S>(conf: CerbosClientOptions<S>) -> Result<Self>
    where
        S: Into<String> + Send,
    {
        let runtime = Builder::new_multi_thread().enable_all().build()?;
        let client = runtime.block_on(CerbosAsyncClient::new(conf))?;
        Ok(Self { runtime, client })
    }

    pub fn check_resources(
        &mut self,
        principal: model::Principal,
        resources: model::ResourceList,
        aux_data: Option<model::AuxData>,
    ) -> Result<model::CheckResourcesResponse> {
        self.runtime
            .block_on(self.client.check_resources(principal, resources, aux_data))
    }

    pub fn is_allowed<S>(
        &mut self,
        action: S,
        principal: model::Principal,
        resource: Resource,
        aux_data: Option<model::AuxData>,
    ) -> Result<bool>
    where
        S: Into<String> + Clone,
    {
        self.runtime.block_on(
            self.client
                .is_allowed(action, principal, resource, aux_data),
        )
    }

    pub fn plan_resources<S>(
        &mut self,
        action: S,
        principal: model::Principal,
        resource: model::ResourceKind,
        aux_data: Option<model::AuxData>,
    ) -> Result<model::PlanResourcesResponse>
    where
        S: Into<String> + Clone,
    {
        self.runtime.block_on(
            self.client
                .plan_resources(action, principal, resource, aux_data),
        )
    }
}

fn gen_uuid() -> String {
    Uuid::new_v4().hyphenated().to_string()
}

struct CerbosInterceptor {
    request_timeout: Duration,
    playground_instance: Option<MetadataValue<Ascii>>,
}

impl Interceptor for CerbosInterceptor {
    fn call(&mut self, mut request: Request<()>) -> std::result::Result<Request<()>, Status> {
        let metadata = request.metadata_mut();
        if let Some(ref playground_md) = self.playground_instance {
            metadata.insert("playground-instance", playground_md.clone());
        }

        request.set_timeout(self.request_timeout);
        Ok(request)
    }
}