-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathpermission.rs
More file actions
287 lines (265 loc) · 9.35 KB
/
Copy pathpermission.rs
File metadata and controls
287 lines (265 loc) · 9.35 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
//! Permission policy primitives that produce a [`PermissionHandler`](crate::handler::PermissionHandler).
//!
//! Compose these into a session via the builder methods
//! [`SessionConfig::approve_all_permissions`](crate::types::SessionConfig::approve_all_permissions),
//! [`deny_all_permissions`](crate::types::SessionConfig::deny_all_permissions),
//! and [`approve_permissions_if`](crate::types::SessionConfig::approve_permissions_if).
//! The same primitives are also available as standalone functions that
//! return an `Arc<dyn PermissionHandler>` you can install via
//! [`SessionConfig::with_permission_handler`](crate::types::SessionConfig::with_permission_handler).
//!
//! For a one-shot approve / deny without composition, see
//! [`ApproveAllHandler`](crate::handler::ApproveAllHandler) and
//! [`DenyAllHandler`](crate::handler::DenyAllHandler).
use std::sync::Arc;
use async_trait::async_trait;
use crate::handler::{PermissionHandler, PermissionResult, permission_handler_failure};
use crate::types::{PermissionRequestData, RequestId, SessionId};
/// Return a [`PermissionHandler`] that approves requests when managed settings
/// are disabled.
///
/// When managed settings are enabled, the handler logs an error and returns a
/// user-not-available decision.
pub fn approve_all() -> Arc<dyn PermissionHandler> {
Arc::new(PolicyHandler {
policy: Policy::ApproveAll,
})
}
/// Return a [`PermissionHandler`] that denies every request.
pub fn deny_all() -> Arc<dyn PermissionHandler> {
Arc::new(PolicyHandler {
policy: Policy::DenyAll,
})
}
/// Return a [`PermissionHandler`] that consults a predicate for each
/// request. `true` approves, `false` denies.
///
/// ```rust,no_run
/// # use github_copilot_sdk::permission;
/// let handler = permission::approve_if(|data| {
/// data.extra.get("tool").and_then(|v| v.as_str()) != Some("shell")
/// });
/// # let _ = handler;
/// ```
pub fn approve_if<F>(predicate: F) -> Arc<dyn PermissionHandler>
where
F: Fn(&PermissionRequestData) -> bool + Send + Sync + 'static,
{
Arc::new(PolicyHandler {
policy: Policy::Predicate(Arc::new(predicate)),
})
}
/// Internal policy enum used by both the standalone helpers and the
/// `SessionConfig` policy builders.
///
/// Stored as `pub(crate)` on `SessionConfig::permission_policy` so that
/// the order of `with_permission_handler(...)` and the policy builders
/// does not matter -- the policy is applied at `Client::create_session`
/// time.
#[derive(Clone)]
pub(crate) enum Policy {
ApproveAll,
DenyAll,
Predicate(Arc<dyn Fn(&PermissionRequestData) -> bool + Send + Sync>),
}
impl std::fmt::Debug for Policy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::ApproveAll => f.write_str("Policy::ApproveAll"),
Self::DenyAll => f.write_str("Policy::DenyAll"),
Self::Predicate(_) => f.write_str("Policy::Predicate(<fn>)"),
}
}
}
/// Resolve the effective permission handler for a session, given the
/// caller-supplied handler and policy. Called by `Client::create_session`
/// and `Client::resume_session`.
///
/// Semantics:
/// - When `policy` is `Some`, the policy entirely replaces the handler
/// for permission decisions. (Caller-supplied handler, if any, is
/// discarded -- the policy is what answers permission requests.)
/// - When `policy` is `None` and `handler` is `Some`, the handler stands.
/// - When both are `None`, returns `None` (no handler -- the SDK sends
/// `requestPermission: false`).
pub(crate) fn resolve_handler(
handler: Option<Arc<dyn PermissionHandler>>,
policy: Option<Policy>,
) -> Option<Arc<dyn PermissionHandler>> {
match (handler, policy) {
(_, Some(policy)) => Some(Arc::new(PolicyHandler { policy })),
(handler, None) => handler,
}
}
struct PolicyHandler {
policy: Policy,
}
#[async_trait]
impl PermissionHandler for PolicyHandler {
async fn handle(
&self,
_session_id: SessionId,
_request_id: RequestId,
data: PermissionRequestData,
) -> PermissionResult {
let approved = match &self.policy {
Policy::ApproveAll => true,
Policy::DenyAll => false,
Policy::Predicate(f) => f(&data),
};
if approved {
if matches!(self.policy, Policy::ApproveAll) && data.managed_settings_enabled {
permission_handler_failure(
"approve-all policy cannot be used when managed settings are enabled",
)
} else if data.managed_approval_required == Some(true) {
PermissionResult::no_result()
} else {
PermissionResult::approve_once()
}
} else {
PermissionResult::reject(None)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn data() -> PermissionRequestData {
PermissionRequestData {
extra: serde_json::json!({ "tool": "shell" }),
..Default::default()
}
}
#[tokio::test]
async fn approve_all_approves() {
let h = approve_all();
assert!(matches!(
h.handle(SessionId::from("s"), RequestId::new("1"), data())
.await,
PermissionResult::Decision {
decision: crate::types::PermissionDecision::ApproveOnce(_),
..
}
));
}
#[tokio::test]
async fn approve_all_fails_when_managed_settings_enabled() {
let h = approve_all();
let mut request = data();
request.managed_settings_enabled = true;
assert!(matches!(
h.handle(SessionId::from("s"), RequestId::new("1"), request)
.await,
PermissionResult::Decision {
decision: crate::types::PermissionDecision::UserNotAvailable(_),
..
}
));
}
#[tokio::test]
async fn deny_all_denies() {
let h = deny_all();
assert!(matches!(
h.handle(SessionId::from("s"), RequestId::new("1"), data())
.await,
PermissionResult::Decision {
decision: crate::types::PermissionDecision::Reject(_),
..
}
));
}
#[tokio::test]
async fn approve_if_consults_predicate() {
let h = approve_if(|d| d.extra.get("tool").and_then(|v| v.as_str()) != Some("shell"));
assert!(matches!(
h.handle(SessionId::from("s"), RequestId::new("1"), data())
.await,
PermissionResult::Decision {
decision: crate::types::PermissionDecision::Reject(_),
..
}
));
}
#[tokio::test]
async fn approve_if_leaves_managed_approval_pending_when_predicate_approves() {
let h = approve_if(|_| true);
let mut request = data();
request.managed_approval_required = Some(true);
assert!(matches!(
h.handle(SessionId::from("s"), RequestId::new("1"), request)
.await,
PermissionResult::NoResult
));
}
#[tokio::test]
async fn approve_if_still_rejects_managed_request_when_predicate_denies() {
let h = approve_if(|_| false);
let mut request = data();
request.managed_approval_required = Some(true);
assert!(matches!(
h.handle(SessionId::from("s"), RequestId::new("1"), request)
.await,
PermissionResult::Decision {
decision: crate::types::PermissionDecision::Reject(_),
..
}
));
}
#[tokio::test]
async fn resolve_handler_policy_wins() {
struct AlwaysApprove;
#[async_trait]
impl PermissionHandler for AlwaysApprove {
async fn handle(
&self,
_: SessionId,
_: RequestId,
_: PermissionRequestData,
) -> PermissionResult {
PermissionResult::approve_once()
}
}
let resolved =
resolve_handler(Some(Arc::new(AlwaysApprove)), Some(Policy::DenyAll)).unwrap();
// Policy wins -- the AlwaysApprove handler is discarded.
assert!(matches!(
resolved
.handle(SessionId::from("s"), RequestId::new("1"), data())
.await,
PermissionResult::Decision {
decision: crate::types::PermissionDecision::Reject(_),
..
}
));
}
#[tokio::test]
async fn resolve_handler_with_only_handler() {
struct H;
#[async_trait]
impl PermissionHandler for H {
async fn handle(
&self,
_: SessionId,
_: RequestId,
_: PermissionRequestData,
) -> PermissionResult {
PermissionResult::approve_once()
}
}
let resolved = resolve_handler(Some(Arc::new(H)), None).unwrap();
assert!(matches!(
resolved
.handle(SessionId::from("s"), RequestId::new("1"), data())
.await,
PermissionResult::Decision {
decision: crate::types::PermissionDecision::ApproveOnce(_),
..
}
));
}
#[test]
fn resolve_handler_with_neither_returns_none() {
assert!(resolve_handler(None, None).is_none());
}
}