-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathuser_permissions.rs
More file actions
356 lines (316 loc) · 11.1 KB
/
user_permissions.rs
File metadata and controls
356 lines (316 loc) · 11.1 KB
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
use crate::errors::ApiError;
use crate::headers::ClientCacheControl;
use crate::opa_client::cached::{
query_user_permissions_cached, UserPermissionsQuery, UserPermissionsResult,
};
use crate::openapi::AUTHZ_TAG;
use crate::{headers::presets, state::AppState};
use axum::{
extract::{Json, State},
http::HeaderMap,
response::{IntoResponse, Response},
};
use http::header::CACHE_CONTROL;
use std::collections::HashMap;
// Wrapper type for proper response serialization
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, utoipa::ToSchema)]
pub struct UserPermissionsResults(pub HashMap<String, UserPermissionsResult>);
impl IntoResponse for UserPermissionsResults {
fn into_response(self) -> Response {
axum::Json(self.0).into_response()
}
}
impl From<HashMap<String, UserPermissionsResult>> for UserPermissionsResults {
fn from(map: HashMap<String, UserPermissionsResult>) -> Self {
UserPermissionsResults(map)
}
}
#[utoipa::path(
post,
path = "/user-permissions",
tag = AUTHZ_TAG,
request_body = UserPermissionsQuery,
params(
("Authorization" = String, Header, description = "Authorization header"),
("Cache-Control" = String, Header, description = "Cache control directives"),
),
responses(
(status = 200, description = "User permissions retrieved successfully", body = UserPermissionsResults),
(status = 422, description = "Invalid request payload"),
(status = 500, description = "Internal server error")
)
)]
pub(super) async fn user_permissions_handler(
State(state): State<AppState>,
headers: HeaderMap,
Json(query): Json<UserPermissionsQuery>,
) -> Response {
// Parse client cache control headers
let cache_control = ClientCacheControl::from_header_value(headers.get(CACHE_CONTROL));
// Use the cached OPA client function which handles caching internally
let permissions = match query_user_permissions_cached(&state, &query, &cache_control).await {
Ok(permissions) => permissions,
Err(err) => {
log::error!("Failed to send request to OPA: {err}");
return ApiError::from(err).into_response();
}
};
// Create response using the map
let response = UserPermissionsResults::from(permissions);
// Create response with appropriate cache headers
let mut http_response = Json(response).into_response();
presets::private_cache(state.config.cache.ttl).apply(&mut http_response);
http_response
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_utils::TestFixture;
use http::{Method, StatusCode};
use serde_json::json;
#[tokio::test]
async fn test_user_permissions_success() {
// Setup test fixture
let fixture = TestFixture::new().await;
// Setup mock OPA response using the helper method
fixture
.add_opa_mock(
Method::POST,
"/v1/data/permit/user_permissions",
json!({
"result": {
"permissions": {
"resource1": {
"tenant": {
"key": "tenant1",
"attributes": {}
},
"resource": {
"key": "resource1",
"type": "document",
"attributes": {}
},
"permissions": ["document:read", "document:write"],
"roles": ["editor"]
}
}
}
}),
StatusCode::OK,
1,
)
.await;
// Send request to the API
let response = fixture
.post(
"/user-permissions",
&json!({
"user": {
"key": "test-user",
"first_name": "Test",
"last_name": "User",
"email": "test@example.com",
"attributes": {}
},
"tenants": ["tenant1"],
"resources": ["resource1"],
"resource_types": ["document"]
}),
)
.await;
// Verify response status and body
response.assert_ok();
let result_map: UserPermissionsResults = response.json_as();
// Check the response structure
assert_eq!(result_map.0.len(), 1);
assert!(result_map.0.contains_key("resource1"));
let resource_result = &result_map.0["resource1"];
assert_eq!(resource_result.permissions.len(), 2);
assert!(resource_result
.permissions
.contains(&"document:read".to_string()));
assert!(resource_result
.permissions
.contains(&"document:write".to_string()));
assert_eq!(resource_result.roles.as_ref().unwrap()[0], "editor");
// Verify mock expectations
fixture.opa_mock.verify().await;
}
#[tokio::test]
async fn test_user_permissions_empty_result() {
// Setup test fixture
let fixture = TestFixture::new().await;
// Setup mock OPA response using the helper method
fixture
.add_opa_mock(
Method::POST,
"/v1/data/permit/user_permissions",
json!({
"result": {
"permissions": {}
}
}),
StatusCode::OK,
1,
)
.await;
// Send request
let response = fixture
.post(
"/user-permissions",
&json!({
"user": {
"key": "test-user",
"attributes": {}
},
"tenants": ["tenant1"]
}),
)
.await;
// Verify response - should still be 200 OK with empty results
response.assert_ok();
let result_map: UserPermissionsResults = response.json_as();
assert_eq!(result_map.0.len(), 0, "Expected empty permissions map");
// Verify mock expectations
fixture.opa_mock.verify().await;
}
#[tokio::test]
async fn test_user_permissions_opa_error() {
// Setup test fixture
let fixture = TestFixture::new().await;
// Create request JSON directly
let request_json = json!({
"user": {
"key": "test-user",
"attributes": {}
}
});
// Setup mock OPA response with error (500 status code)
fixture
.add_opa_mock(
Method::POST,
"/v1/data/permit/user_permissions",
"Internal Server Error",
StatusCode::INTERNAL_SERVER_ERROR,
1,
)
.await;
// Send request
let response = fixture.post("/user-permissions", &request_json).await;
// Verify response - should be a 502 Bad Gateway when OPA returns 5xx
response.assert_status(StatusCode::BAD_GATEWAY);
// Verify mock expectations
fixture.opa_mock.verify().await;
}
#[tokio::test]
async fn test_user_permissions_no_cache_control() {
// Setup test fixture
let fixture = TestFixture::new().await;
// Create request JSON directly
let request_json = json!({
"user": {
"key": "test-user",
"attributes": {}
},
"resource_types": ["document"]
});
// Create response JSON directly
let response_json = json!({
"result": {
"permissions": {
"resource1": {
"tenant": {
"key": "tenant1",
"attributes": {}
},
"resource": {
"key": "resource1",
"type": "document",
"attributes": {}
},
"permissions": ["document:read"]
}
}
}
});
// Setup mock OPA response using the helper method
fixture
.add_opa_mock(
Method::POST,
"/v1/data/permit/user_permissions",
response_json,
StatusCode::OK,
1,
)
.await;
// Send request to the API
let response = fixture.post("/user-permissions", &request_json).await;
// Simply verify the request was successful
response.assert_ok();
let result_map: UserPermissionsResults = response.json_as();
assert_eq!(result_map.0.len(), 1);
// Verify mock expectations
fixture.opa_mock.verify().await;
}
#[tokio::test]
async fn test_user_permissions_with_no_store_header() {
// Setup test fixture
let fixture = TestFixture::new().await;
// Create request JSON directly
let request_json = json!({
"user": {
"key": "test-user-cache",
"attributes": {}
},
"resource_types": ["document"]
});
// Create response JSON directly
let response_json = json!({
"result": {
"permissions": {
"resource1": {
"tenant": {
"key": "tenant1",
"attributes": {}
},
"resource": {
"key": "resource1",
"type": "document",
"attributes": {}
},
"permissions": ["document:read"]
}
}
}
});
// Setup mock OPA response using the helper method
fixture
.add_opa_mock(
Method::POST,
"/v1/data/permit/user_permissions",
response_json,
StatusCode::OK,
1,
)
.await;
// Send request with no-store cache header
let custom_headers = &[(CACHE_CONTROL.as_str(), "no-store")];
let response = fixture
.post_with_headers("/user-permissions", &request_json, custom_headers)
.await;
// Verify response is successful
response.assert_ok();
let result_map: UserPermissionsResults = response.json_as();
assert_eq!(
result_map.0.len(),
1,
"Should have one resource in permissions"
);
assert!(
result_map.0.contains_key("resource1"),
"Should contain resource1 entry"
);
// Verify mock expectations
fixture.opa_mock.verify().await;
}
}