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
|
// TODO: This whole thing depends on having spice server running...which I do not want
// in a public secd library (or really at all). We will eventually get rid of this in
// favor of a light weight solution that leverages the Zanzibar API but disregards the
// scaling part.
#[allow(clippy::module_inception)]
pub mod spice {
tonic::include_proto!("authzed.api.v1");
}
use spice::permissions_service_client::PermissionsServiceClient;
use spice::schema_service_client::SchemaServiceClient;
use spice::WriteSchemaRequest;
use std::matches;
use tonic::metadata::MetadataValue;
use tonic::transport::Channel;
use tonic::{Request, Response, Status, Streaming};
use crate::auth::z::{self, Subject};
use crate::client::spice::spice::{
relationship_update, ObjectReference, Relationship, RelationshipUpdate, SubjectReference,
};
use self::spice::check_permission_response::Permissionship;
use self::spice::{
consistency, CheckPermissionRequest, Consistency, LookupResourcesRequest,
LookupResourcesResponse, WriteRelationshipsRequest,
};
#[derive(Debug, thiserror::Error, derive_more::Display)]
pub enum SpiceError {
TonicTransport(#[from] tonic::transport::Error),
TonicStatus(#[from] tonic::Status),
}
pub(crate) struct Spice {
channel: Channel,
secret: String,
}
impl Spice {
pub async fn new(secret: String, server: String) -> Self {
let channel = Channel::from_shared(server)
.expect("invalid SPICE_SERVER uri")
.connect()
.await
.expect("initialization error: Spice failed to connect to DB.");
Spice { channel, secret }
}
pub async fn lookup_resources(
&self,
ns: &str,
relation: &str,
subj: &Subject,
) -> Result<Vec<String>, SpiceError> {
let mut client =
PermissionsServiceClient::with_interceptor(self.channel.clone(), |req: Request<()>| {
self.intercept(req)
});
let request = tonic::Request::new(LookupResourcesRequest {
consistency: Some(Consistency {
requirement: Some(consistency::Requirement::MinimizeLatency(true)),
}),
resource_object_type: ns.to_string(),
permission: relation.to_string(),
subject: Some(SubjectReference::from(subj)),
context: None,
});
let mut res = vec![];
let mut response: Streaming<LookupResourcesResponse> =
client.lookup_resources(request).await?.into_inner();
if let Some(d) = response.message().await? {
res.push(d.resource_object_id);
}
Ok(res)
}
pub async fn check_permission(&self, r: &z::Relationship) -> Result<bool, SpiceError> {
let mut client =
PermissionsServiceClient::with_interceptor(self.channel.clone(), |req: Request<()>| {
self.intercept(req)
});
let request = tonic::Request::new(CheckPermissionRequest {
consistency: Some(Consistency {
requirement: Some(consistency::Requirement::MinimizeLatency(true)),
}),
resource: Some(ObjectReference::from(&r.object)),
permission: r.relation.clone(),
subject: Some(SubjectReference::from(&r.subject)),
context: None,
});
let response = client.check_permission(request).await?.into_inner();
Ok(matches!(
Permissionship::from_i32(response.permissionship),
Some(Permissionship::HasPermission)
))
}
pub async fn write_relationship(&self, rs: &[z::Relationship]) -> Result<(), SpiceError> {
let mut client =
PermissionsServiceClient::with_interceptor(self.channel.clone(), |req: Request<()>| {
self.intercept(req)
});
let request = tonic::Request::new(WriteRelationshipsRequest {
updates: rs
.iter()
.map(|t| RelationshipUpdate {
operation: (relationship_update::Operation::Touch as i32),
relationship: Some(Relationship {
resource: Some(ObjectReference::from(&t.object)),
relation: t.relation.clone(),
subject: Some(SubjectReference::from(&t.subject)),
optional_caveat: None,
}),
})
.collect(),
optional_preconditions: vec![],
});
client.write_relationships(request).await?;
Ok(())
}
pub async fn write_schema(&self, schema: &str) -> Result<(), SpiceError> {
let mut client =
SchemaServiceClient::with_interceptor(self.channel.clone(), |req: Request<()>| {
self.intercept(req)
});
let request = tonic::Request::new(WriteSchemaRequest {
schema: schema.into(),
});
client.write_schema(request).await?;
Ok(())
}
fn intercept(&self, mut req: Request<()>) -> Result<Request<()>, Status> {
req.metadata_mut().insert(
"authorization",
MetadataValue::from_str(&format!("Bearer {}", self.secret)).unwrap(),
);
Ok(req)
}
}
impl From<&z::Subject> for SubjectReference {
fn from(s: &z::Subject) -> Self {
let tup = match s {
Subject::User(u) => (u.0.clone(), u.1.clone().to_string(), "".to_string()),
Subject::UserSet { user, relation } => {
(user.0.clone(), user.1.clone().to_string(), relation.clone())
}
};
SubjectReference {
object: Some(ObjectReference {
object_type: tup.0,
object_id: tup.1,
}),
optional_relation: tup.2,
}
}
}
impl From<&z::Object> for ObjectReference {
fn from(o: &z::Object) -> Self {
ObjectReference {
object_type: o.0.clone(),
object_id: o.1.clone().to_string(),
}
}
}
|