Skip to content

Commit 5fd79ce

Browse files
committed
feat: unify AI permissions across connections and Data Studio
1 parent 9537aa4 commit 5fd79ce

28 files changed

Lines changed: 1151 additions & 805 deletions

‎DESIGN.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,3 +328,7 @@ Check each affected surface. Documentation-only changes need source, link, and i
328328
- Theme preview tiles scope the same light/dark tokens instead of maintaining a second miniature palette.
329329
- Automated contrast checks cover text on workspace, chrome, raised, selection, and semantic feedback surfaces, plus foregrounds on solid actions. Editor theme tests cover light/dark switching and token inheritance.
330330
- Continue to verify real content, narrow windows, keyboard focus, system appearance changes, and native window controls on the target operating systems. Theme tests do not replace native-platform interaction checks.
331+
332+
### AI permission controls
333+
334+
Connection dialogs expose a collapsed AI permissions section shared by Data Studio and external MCP. Default to system inheritance, show effective allowed actions, and reveal per-action Inherit / Allow / Deny under Customize. The system settings page edits action defaults, without a separate connection allowlist or MCP exposure switch. Preserve shared Select, Label, Button, neutral surfaces, localized English/Chinese copy, keyboard focus, and loading/error/retry states. See [AI permissions](docs/AI_PERMISSIONS.md) for enforcement and migration behavior.

‎docs/AI_PERMISSIONS.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
# AI permissions
2+
3+
SQL database and document database connections share one AI permission chain across built-in Data Studio and external MCP clients. This policy does not grant database privileges or change manual database access.
4+
5+
For each action (read, create data, update data, delete data, manage structure/administration), resolve an explicit connection allow/deny first, otherwise use the system default, otherwise deny. Omitted connection decisions inherit; explicit false is a denial. Presets are shortcuts for these individual decisions.
6+
7+
Data Studio only operates on attached connections. Inherited attachment permissions use the live connection policy, rather than a permission snapshot. Custom conversation restrictions can narrow access, but cannot grant an operation denied by the connection chain. Ask/Auto controls confirmation and never grants CRUD permissions. Backend checks run again before execution, including retries.
8+
9+
An empty set of allowed actions denies access. There is no separate MCP exposure setting or connection allowlist. Connection metadata returned to AI clients excludes inaccessible connections; Data Studio discovery is additionally limited to its attached connections. The MCP server's availability and auto-start preference remain service settings.
10+
11+
Read & modify data includes data deletion but excludes structure and administration. Mixed operations require every affected permission: SQL writes inspect statement tokens, bulk requests inspect every action, and aggregation pipelines that write require write and management access. Risk controls confirmation independently from action permissions.
12+
13+
Legacy allowlists migrate to explicit connection decisions preserving exclusions. When an allowlist existed, new connections default to no access. Existing per-connection restrictions are preserved. Corrupt or unreadable policy files deny execution rather than falling back to permissive settings. Policy writes are atomic and take effect for subsequent calls without restarting the bridge.
14+
15+
Both applications pin the shared permission implementation to an exact Git revision in their Cargo manifests and lockfiles so builds use the same policy behavior.

‎src-tauri/Cargo.lock‎

Lines changed: 2 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎src-tauri/Cargo.toml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,8 +87,8 @@ http = "1"
8787
log = "0.4"
8888
futures = "0.3"
8989
rand = "0.8"
90-
# data-studio-agent: pinned to latest release tag.
91-
data-studio-agent = { git = "https://github.com/geek-fun/data-studio-agent.git", tag = "v0.1.9" }
90+
# Pin the shared AI permission chain to a reproducible revision.
91+
data-studio-agent = { git = "https://github.com/geek-fun/data-studio-agent.git", rev = "c36fb2b16a4031053c3990dcd4d4b8e84d4d597f" }
9292

9393
# Archive extraction (JRE downloads)
9494
flate2 = "1.0"

‎src-tauri/src/agent/executor.rs‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,25 @@ impl ToolExecutor for SqlKitToolExecutor {
2424
connection_config: &Value,
2525
) -> Result<ToolEnvelope, String> {
2626
let start = std::time::Instant::now();
27+
let app = crate::APP_HANDLE.get().ok_or("App not initialized")?;
28+
let policy = crate::mcp_bridge::load_permission_policy(app)?;
29+
let cap = data_studio_agent::capabilities::registry::registry()
30+
.get(tool_name)
31+
.ok_or("Unknown capability")?;
32+
let id = connection_config
33+
.get("connectionId")
34+
.and_then(Value::as_str);
35+
let restriction = connection_config
36+
.get("permissions")
37+
.filter(|v| !v.is_null())
38+
.map(|v| {
39+
serde_json::from_value::<
40+
data_studio_agent::capabilities::permissions::PermissionRules,
41+
>(v.clone())
42+
})
43+
.transpose()
44+
.map_err(|e| e.to_string())?;
45+
policy.authorize(cap, arguments, id, restriction.as_ref())?;
2746

2847
let conn_opt = if connection_config.is_null() {
2948
None
@@ -38,6 +57,33 @@ impl ToolExecutor for SqlKitToolExecutor {
3857
)
3958
.await?;
4059

60+
let raw = if tool_name.ends_with("__list_connections") {
61+
let mut result: Value = serde_json::from_str(&raw).map_err(|e| e.to_string())?;
62+
if let Some(connections) = result.get("connections").and_then(Value::as_array) {
63+
let filtered = connections
64+
.iter()
65+
.filter(|connection| {
66+
let id = match &connection["id"] {
67+
Value::String(id) => id.clone(),
68+
Value::Number(id) => id.to_string(),
69+
_ => return false,
70+
};
71+
let in_scope = connection_config
72+
.get("__allowed_connection_ids")
73+
.and_then(Value::as_array)
74+
.is_some_and(|ids| {
75+
ids.iter().any(|allowed| allowed.as_str() == Some(&id))
76+
});
77+
in_scope && policy.effective_permissions(&id).any_allowed()
78+
})
79+
.cloned()
80+
.collect::<Vec<_>>();
81+
result["connections"] = serde_json::json!(filtered);
82+
}
83+
result.to_string()
84+
} else {
85+
raw
86+
};
4187
let duration_ms = start.elapsed().as_millis() as u64;
4288
let (full_result, truncated) = char_truncate(&raw, TOOL_ENVELOPE_MAX_CHARS);
4389
let (summary, _) = char_truncate(&full_result, TOOL_ENVELOPE_SUMMARY_CHARS);

‎src-tauri/src/agent_adapters.rs‎

Lines changed: 21 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
use std::collections::HashMap;
88
use std::sync::Arc;
99

10-
use crate::mcp_bridge::McpConfig;
1110
use data_studio_agent as lib;
1211
use data_studio_agent::storage;
1312
use data_studio_agent::traits::{CancelMap, ConfirmMap, EventEmitter};
@@ -69,29 +68,29 @@ pub async fn run_agent_loop(
6968
.unwrap_or(false)
7069
};
7170

72-
let app_data_dir = app.path().app_data_dir().map_err(|e| e.to_string())?;
71+
let policy_app = app.clone();
72+
let permission_connections = connections.clone();
7373
let should_deny = move |tool_name: &str, conn_id: Option<&str>| -> bool {
74-
// Reload per call so permission changes made in Settings apply to the
75-
// next tool call instead of being snapshotted for the whole run.
76-
let policy = McpConfig::load(&app_data_dir).policy;
77-
match data_studio_agent::capabilities::registry::registry().get(tool_name) {
78-
Some(cap) => {
79-
// Allowlist set but no connection specified: a DB capability would
80-
// fall back to the default connection, bypassing the allowlist.
81-
// AppLocal tools (list_connections etc.) need no connection.
82-
if !policy.allowed_connection_ids.is_empty()
83-
&& conn_id.is_none()
84-
&& !matches!(
85-
cap.source_kind,
86-
data_studio_agent::capabilities::types::SourceKind::AppLocal
87-
)
88-
{
89-
return true;
90-
}
91-
!policy.allows(cap.risk_level, conn_id)
92-
}
93-
None => false,
74+
let Some(cap) = data_studio_agent::capabilities::registry::registry().get(tool_name) else {
75+
return true;
76+
};
77+
if matches!(
78+
cap.source_kind,
79+
data_studio_agent::capabilities::types::SourceKind::AppLocal
80+
| data_studio_agent::capabilities::types::SourceKind::File
81+
) {
82+
return false;
9483
}
84+
let Some(id) = conn_id
85+
.and_then(|id| permission_connections.get(id))
86+
.and_then(|cfg| cfg.get("connectionId"))
87+
.and_then(Value::as_str)
88+
else {
89+
return true;
90+
};
91+
crate::mcp_bridge::load_permission_policy(&policy_app)
92+
.map(|policy| !policy.effective_permissions(id).any_allowed())
93+
.unwrap_or(true)
9594
};
9695

9796
lib::loop_runner::run_agent_loop(

‎src-tauri/src/capabilities/sql_write.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -366,7 +366,7 @@ pub(crate) fn register_write_tools(reg: &mut CapabilityRegistry) {
366366

367367
reg.register(Capability {
368368
name: "sqlkit__execute_delete",
369-
description: "Execute a destructive DELETE or TRUNCATE statement. DESTRUCTIVE: permanently removes data. Requires Full Access with Confirm Destructive in Settings → MCP Bridge.",
369+
description: "Execute a destructive DELETE or TRUNCATE statement. DESTRUCTIVE: permanently removes data. Requires Delete data permission for this connection.",
370370
handler: Arc::new(ExecuteDeleteHandler),
371371
input_schema: json!({"type": "object", "properties": {
372372
"connection_id": connection_id_schema(),
@@ -381,7 +381,7 @@ pub(crate) fn register_write_tools(reg: &mut CapabilityRegistry) {
381381

382382
reg.register(Capability {
383383
name: "sqlkit__execute_ddl",
384-
description: "Execute a DDL statement (CREATE, ALTER, DROP, and other schema changes). DESTRUCTIVE for DROP/ALTER: permanently changes schema. Requires Full Access with Confirm Destructive in Settings → MCP Bridge.",
384+
description: "Execute a DDL statement (CREATE, ALTER, DROP, and other schema changes). Changes database structure. Requires Manage structure & administration permission for this connection.",
385385
handler: Arc::new(ExecuteDdlHandler),
386386
input_schema: json!({"type": "object", "properties": {
387387
"connection_id": connection_id_schema(),

‎src-tauri/src/lib.rs‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,8 @@ pub fn run() {
268268
Ok(())
269269
})
270270
.invoke_handler(tauri::generate_handler![
271+
crate::mcp_bridge::get_ai_permissions,
272+
crate::mcp_bridge::save_ai_permissions,
271273
// SSH profile management + host-key store
272274
crate::ssh::commands::list_ssh_profiles,
273275
crate::ssh::commands::save_ssh_profile,

0 commit comments

Comments
 (0)