Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 22 additions & 19 deletions src-tauri/src/db/dynamodb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -277,23 +277,14 @@ pub fn sign(

// ── Requests ─────────────────────────────────────────────────────────────────

/// Operations the app may send. Anything else is refused, so the command
/// can't be used to reach other DynamoDB APIs (tables are not created or
/// dropped from here).
const ALLOWED_OPS: &[&str] = &[
"ListTables",
"DescribeTable",
"DescribeTimeToLive",
"Scan",
"Query",
"GetItem",
"PutItem",
"UpdateItem",
"DeleteItem",
"BatchWriteItem",
"TransactWriteItems",
"ExecuteStatement",
];
/// Operations the app may send: the API calls the console offers (see
/// [`parse_api_call`]) and PartiQL. Anything else is refused, so the command
/// can't reach other AWS APIs. Who may run which is decided before this, by
/// the access level (`mcp::access`) and the read-only switch.
fn op_allowed(op: &str) -> bool {
op == "ExecuteStatement"
|| [API_READS, API_WRITES, API_SCHEMA, API_DANGEROUS].iter().any(|l| l.contains(&op))
}

fn client() -> &'static reqwest::Client {
static C: OnceLock<reqwest::Client> = OnceLock::new();
Expand Down Expand Up @@ -336,7 +327,7 @@ fn error_message(status: reqwest::StatusCode, body: &str) -> String {

/// One DynamoDB API call.
pub async fn request(cfg: &DynamoConfig, op: &str, body: &serde_json::Value) -> Result<serde_json::Value, String> {
if !ALLOWED_OPS.contains(&op) {
if !op_allowed(op) {
return Err(format!("DynamoDB operation \"{op}\" is not allowed"));
}
let region = resolve_region(cfg);
Expand Down Expand Up @@ -717,6 +708,18 @@ pub fn shape_from_describe(

#[cfg(test)]
mod tests {
#[test]
fn every_console_api_call_can_be_sent() {
// The console parses these; the request gate must not refuse them.
for op in [super::API_READS, super::API_WRITES, super::API_SCHEMA, super::API_DANGEROUS].concat() {
let call = super::parse_api_call(&format!("{op} {{}}")).expect("parsed").expect("valid");
assert!(super::op_allowed(&call.0), "{op} is parsed but refused");
}
assert!(super::op_allowed("ExecuteStatement"));
assert!(!super::op_allowed("DeleteBackup"));
assert!(!super::op_allowed("CreateGlobalTable"));
}

use super::*;

#[test]
Expand Down Expand Up @@ -808,7 +811,7 @@ mod tests {
session_token: None,
endpoint: Some("http://127.0.0.1:1".into()),
};
assert!(request(&cfg, "DeleteTable", &serde_json::json!({})).await.unwrap_err().contains("not allowed"));
assert!(request(&cfg, "DeleteBackup", &serde_json::json!({})).await.unwrap_err().contains("not allowed"));
}

/// Against `dev/nosql` DynamoDB Local on port 8000:
Expand Down
3 changes: 2 additions & 1 deletion src/lib/components/StudioShell.svelte
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<script>
import { formatApiCall } from '$lib/dynamo-json.js'
import ArrowLeft from '@lucide/svelte/icons/arrow-left'
import { onMount, onDestroy, untrack, tick } from 'svelte'
import { panelMotionOff, slidePanel } from '$lib/panel-motion.js'
Expand Down Expand Up @@ -7917,7 +7918,7 @@ let rowSearch = $state('')
const o = /** @type {{ table?: string | null, schema?: string | null, query?: string | null }} */ (e.payload ?? {})
if (!connection) return
if (aiMode) exitAiMode()
if (o.query) void openQueryInEditor(o.query)
if (o.query) void openQueryInEditor(isDynamo ? formatApiCall(o.query) : o.query)
else if (o.table) void openTableTab(o.schema || activeSchema, o.table)
}).then((u) => { off = u }),
).catch(() => {})
Expand Down
21 changes: 21 additions & 0 deletions src/lib/dynamo-json.js
Original file line number Diff line number Diff line change
Expand Up @@ -346,3 +346,24 @@ export function dynamoGrid(items, keys) {
)
return { columns: names.map((name, i) => ({ name, data_type: types[i] || 'null', nullable: !keys.includes(name) })), rows }
}

/**
* A DynamoDB API call as the console reads it (`{"operation": ..., "input":
* ...}` or `CreateTable {...}`), laid out over several lines. Agents hand
* these over as one long line; anything else comes back unchanged.
* @param {string} text
*/
export function formatApiCall(text) {
const s = text.trim().replace(/;$/, '').trim()
try {
if (s.startsWith('{')) {
const v = JSON.parse(s)
return v && typeof v === 'object' && typeof v.operation === 'string' ? JSON.stringify(v, null, 2) : text
}
const m = /^([A-Za-z]+)\s*(\{[\s\S]*\})$/.exec(s)
if (m) return `${m[1]} ${JSON.stringify(JSON.parse(m[2]), null, 2)}`
} catch {
// Not JSON after all: leave it as written.
}
return text
}
15 changes: 14 additions & 1 deletion src/lib/dynamo-json.test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { describe, it, expect } from 'vitest'
import {
unmarshall, unmarshallItem, marshall, marshallItem, cellText, columnsFor, keyShapes,
keyId, queryBody, scanBody, saveRequest, newItemTemplate, plainNumber, dynamoGrid,
keyId, queryBody, scanBody, saveRequest, newItemTemplate, plainNumber, dynamoGrid, formatApiCall,
} from './dynamo-json.js'

const item = {
Expand Down Expand Up @@ -135,3 +135,16 @@ describe('dynamoGrid', () => {
expect(g.rows[1][g.columns.findIndex((c) => c.name === 'tags')]).toBe(null)
})
})

describe('formatApiCall', () => {
it('lays an API call out over several lines', () => {
const one = '{"operation": "CreateTable", "input": {"TableName": "shop"}}'
expect(formatApiCall(one)).toBe('{\n "operation": "CreateTable",\n "input": {\n "TableName": "shop"\n }\n}')
expect(formatApiCall('DescribeTable {"TableName":"shop"};')).toBe('DescribeTable {\n "TableName": "shop"\n}')
})
it('leaves PartiQL and broken JSON alone', () => {
expect(formatApiCall('SELECT * FROM "shop"')).toBe('SELECT * FROM "shop"')
expect(formatApiCall('{"operation": ')).toBe('{"operation": ')
expect(formatApiCall('{"a": 1}')).toBe('{"a": 1}')
})
})
Loading