-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathQueryExecutionPolicyServiceTest.java
More file actions
778 lines (683 loc) · 31.5 KB
/
Copy pathQueryExecutionPolicyServiceTest.java
File metadata and controls
778 lines (683 loc) · 31.5 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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
package com.dbaagent.service;
import com.dbaagent.model.QueryRequest;
import com.dbaagent.provider.DatabaseProviderRegistry;
import com.dbaagent.provider.api.DatabaseDialect;
import com.dbaagent.provider.api.QueryExecutionProvider;
import com.dbaagent.provider.mysql.MySQLQueryExecutionProvider;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class QueryExecutionPolicyServiceTest {
@Mock private DatabaseProviderRegistry providerRegistry;
@Mock private DatabaseDialect databaseDialect;
private QueryExecutionPolicyService service;
@BeforeEach
void setUp() {
// The real provider, not a stub. A stubbed isReadOnlyQuery() that always
// answered "false" made these tests assert the opposite of production:
// MySQLQueryExecutionProvider reports anything starting with WITH as
// read-only, which is how `WITH x AS (DELETE ...) SELECT` reached the
// database classified as a read.
QueryExecutionProvider realProvider = new MySQLQueryExecutionProvider();
when(providerRegistry.getDialect(anyString())).thenReturn(databaseDialect);
when(databaseDialect.queryExecution()).thenReturn(realProvider);
lenient().when(providerRegistry.getCanonicalName(anyString())).thenReturn("mysql");
service = new QueryExecutionPolicyService(providerRegistry);
}
@Test
void chatSelect_isAllowed() {
QueryExecutionPolicyService.PolicyDecision decision = service.enforce(
new QueryRequest("SELECT 1", 10, 30),
QueryExecutionContext.chat(),
"mysql"
);
assertThat(decision.mutating()).isFalse();
assertThat(decision.primaryQueryType()).isEqualTo("SELECT");
}
@Test
void chatMutation_isBlockedForAllUsers() {
QueryExecutionPolicyException exception = assertThrows(
QueryExecutionPolicyException.class,
() -> service.enforce(
new QueryRequest("DELETE FROM bookings WHERE id = 1", null, null),
QueryExecutionContext.chat(),
"mysql"
)
);
assertThat(exception.getErrorCode()).isEqualTo(QueryExecutionPolicyException.CHAT_MUTATION_BLOCKED);
}
@Test
void editorMutation_nonAdminIsBlocked() {
QueryExecutionPolicyException exception = assertThrows(
QueryExecutionPolicyException.class,
() -> service.enforce(
new QueryRequest("INSERT INTO audit_log(id) VALUES (1)", null, null),
QueryExecutionContext.editor("analyst", false, false),
"mysql"
)
);
assertThat(exception.getErrorCode()).isEqualTo(QueryExecutionPolicyException.EDITOR_MUTATION_FORBIDDEN);
}
@Test
void editorMutation_adminRequiresConfirmation() {
QueryExecutionPolicyException exception = assertThrows(
QueryExecutionPolicyException.class,
() -> service.enforce(
new QueryRequest("UPDATE customers SET property_status = 'ACTIVE' WHERE customer_id = 9", null, null),
QueryExecutionContext.editor("admin", true, false),
"mysql"
)
);
assertThat(exception.getErrorCode()).isEqualTo(QueryExecutionPolicyException.EDITOR_MUTATION_CONFIRMATION_REQUIRED);
assertThat(exception.isRequiresConfirmation()).isTrue();
assertThat(exception.getWarnings()).isNotEmpty();
}
@Test
void editorMutation_dbaRequiresConfirmation() {
QueryExecutionPolicyException exception = assertThrows(
QueryExecutionPolicyException.class,
() -> service.enforce(
new QueryRequest("UPDATE customers SET property_status = 'ACTIVE' WHERE customer_id = 9", null, null),
QueryExecutionContext.editor("dba", true, false),
"mysql"
)
);
assertThat(exception.getErrorCode()).isEqualTo(QueryExecutionPolicyException.EDITOR_MUTATION_CONFIRMATION_REQUIRED);
assertThat(exception.isRequiresConfirmation()).isTrue();
}
@Test
void editorMutation_dbaConfirmedIsAllowed() {
QueryExecutionPolicyService.PolicyDecision decision = service.enforce(
new QueryRequest("UPDATE customers SET property_status = 'ACTIVE' WHERE customer_id = 9", null, null),
QueryExecutionContext.editor("dba", true, true),
"mysql"
);
assertThat(decision.mutating()).isTrue();
assertThat(decision.primaryQueryType()).isEqualTo("UPDATE");
}
@Test
void editorMutation_developerStillForbidden() {
QueryExecutionPolicyException exception = assertThrows(
QueryExecutionPolicyException.class,
() -> service.enforce(
new QueryRequest("DELETE FROM bookings WHERE id = 1", null, null),
QueryExecutionContext.editor("developer", false, true),
"mysql"
)
);
assertThat(exception.getErrorCode()).isEqualTo(QueryExecutionPolicyException.EDITOR_MUTATION_FORBIDDEN);
assertThat(exception.getMessage()).contains("admins or DBAs");
}
@Test
void editorConfirmedDeleteWithoutWhere_isBlocked() {
QueryExecutionPolicyException exception = assertThrows(
QueryExecutionPolicyException.class,
() -> service.enforce(
new QueryRequest("DELETE FROM customers", null, null),
QueryExecutionContext.editor("admin", true, true),
"mysql"
)
);
assertThat(exception.getErrorCode()).isEqualTo(QueryExecutionPolicyException.UNSAFE_MUTATION_BLOCKED);
assertThat(exception.getMessage()).contains("without a WHERE clause");
}
// EXPLAIN UPDATE/DELETE is the one reachable path to the keyword-fallback
// containsWhereClause check for a real UPDATE/DELETE: JSqlParser only models
// EXPLAIN SELECT, so these fall through to detectExplainWrappedMutation
// rather than Update.getWhere()/Delete.getWhere(), which every ordinary
// (non-EXPLAIN) mutation test above exercises instead.
@Test
void editorConfirmedExplainUpdateWithMultilineWhere_isAllowed() {
QueryExecutionPolicyService.PolicyDecision decision = service.enforce(
new QueryRequest(
"EXPLAIN UPDATE customers\nSET property_status = 'ACTIVE'\nWHERE customer_id = 9",
null,
null
),
QueryExecutionContext.editor("admin", true, true),
"mysql"
);
assertThat(decision.mutating()).isTrue();
assertThat(decision.primaryQueryType()).isEqualTo("UPDATE");
}
@Test
void editorConfirmedExplainDeleteWithOnlyCommentedOutWhere_isBlocked() {
QueryExecutionPolicyException exception = assertThrows(
QueryExecutionPolicyException.class,
() -> service.enforce(
new QueryRequest("EXPLAIN DELETE FROM customers -- WHERE customer_id = 9\n", null, null),
QueryExecutionContext.editor("admin", true, true),
"mysql"
)
);
assertThat(exception.getErrorCode()).isEqualTo(QueryExecutionPolicyException.UNSAFE_MUTATION_BLOCKED);
assertThat(exception.getMessage()).contains("without a WHERE clause");
}
@Test
void editorMutation_multiStatementBatchIsBlocked() {
QueryExecutionPolicyException exception = assertThrows(
QueryExecutionPolicyException.class,
() -> service.enforce(
new QueryRequest("UPDATE customers SET property_status = 'ACTIVE' WHERE customer_id = 9; DELETE FROM customers WHERE customer_id = 10", null, null),
QueryExecutionContext.editor("admin", true, true),
"mysql"
)
);
assertThat(exception.getErrorCode()).isEqualTo(QueryExecutionPolicyException.UNSAFE_MUTATION_BLOCKED);
assertThat(exception.getMessage()).contains("single DDL or DML statement");
}
@Test
void readOnlyMultiStatementWithUsePreamble_isAllowed() {
QueryExecutionPolicyService.PolicyDecision decision = service.enforce(
new QueryRequest("USE analytics; SELECT 1", null, null),
QueryExecutionContext.editor("analyst", false, false),
"mysql"
);
assertThat(decision.mutating()).isFalse();
assertThat(decision.classifications()).hasSize(2);
assertThat(decision.classifications().get(0).sessionPreamble()).isTrue();
assertThat(decision.classifications().get(1).readOnly()).isTrue();
}
@Test
void explainWrappedUpdate_isTreatedAsMutation() {
QueryExecutionPolicyException exception = assertThrows(
QueryExecutionPolicyException.class,
() -> service.enforce(
new QueryRequest("EXPLAIN UPDATE customers SET property_status = 'ACTIVE' WHERE customer_id = 9", null, null),
QueryExecutionContext.chat(),
"mysql"
)
);
assertThat(exception.getErrorCode()).isEqualTo(QueryExecutionPolicyException.CHAT_MUTATION_BLOCKED);
}
@Test
void withInsert_isTreatedAsMutation() {
QueryExecutionPolicyException exception = assertThrows(
QueryExecutionPolicyException.class,
() -> service.enforce(
new QueryRequest(
"WITH src AS (SELECT 1 AS id) INSERT INTO audit_log(id) SELECT id FROM src",
null,
null
),
QueryExecutionContext.chat(),
"mysql"
)
);
assertThat(exception.getErrorCode()).isEqualTo(QueryExecutionPolicyException.CHAT_MUTATION_BLOCKED);
}
@Test
void editorConfirmedDeleteWithWhere_isAllowed() {
QueryExecutionPolicyService.PolicyDecision decision = service.enforce(
new QueryRequest("DELETE FROM customers WHERE customer_id = 9", null, null),
QueryExecutionContext.editor("admin", true, true),
"mysql"
);
assertThat(decision.mutating()).isTrue();
assertThat(decision.primaryQueryType()).isEqualTo("DELETE");
}
@Test
void editorDropTable_isBlockedEvenForAdmin() {
QueryExecutionPolicyException exception = assertThrows(
QueryExecutionPolicyException.class,
() -> service.enforce(
new QueryRequest("DROP TABLE temp_rollup", null, null),
QueryExecutionContext.editor("admin", true, true),
"mysql"
)
);
assertThat(exception.getErrorCode()).isEqualTo(QueryExecutionPolicyException.UNSAFE_MUTATION_BLOCKED);
assertThat(exception.getMessage()).contains("DROP TABLE");
}
@Test
void editorDropTableIfExists_isAlsoBlocked() {
QueryExecutionPolicyException exception = assertThrows(
QueryExecutionPolicyException.class,
() -> service.enforce(
new QueryRequest("DROP TABLE IF EXISTS temp_rollup", null, null),
QueryExecutionContext.editor("admin", true, true),
"mysql"
)
);
assertThat(exception.getErrorCode()).isEqualTo(QueryExecutionPolicyException.UNSAFE_MUTATION_BLOCKED);
assertThat(exception.getMessage()).contains("DROP TABLE");
}
@Test
void editorDropIndex_isAllowedForConfirmedAdmin() {
QueryExecutionPolicyService.PolicyDecision decision = service.enforce(
new QueryRequest("DROP INDEX idx_bookings_hotel ON bookings", null, null),
QueryExecutionContext.editor("admin", true, true),
"mysql"
);
assertThat(decision.mutating()).isTrue();
assertThat(decision.primaryQueryType()).startsWith("DROP");
assertThat(decision.primaryQueryType()).doesNotContain("TABLE");
}
@Test
void editorDropView_isAllowedForConfirmedAdmin() {
QueryExecutionPolicyService.PolicyDecision decision = service.enforce(
new QueryRequest("DROP VIEW v_active_hotels", null, null),
QueryExecutionContext.editor("admin", true, true),
"mysql"
);
assertThat(decision.mutating()).isTrue();
assertThat(decision.primaryQueryType()).startsWith("DROP");
assertThat(decision.primaryQueryType()).doesNotContain("TABLE");
}
@Test
void editorDropIndex_unconfirmedAdmin_requiresConfirmation() {
QueryExecutionPolicyException exception = assertThrows(
QueryExecutionPolicyException.class,
() -> service.enforce(
new QueryRequest("DROP INDEX idx_bookings_hotel ON bookings", null, null),
QueryExecutionContext.editor("admin", true, false),
"mysql"
)
);
// Other DROPs still flow through the standard mutation-confirmation gate.
assertThat(exception.getErrorCode())
.isEqualTo(QueryExecutionPolicyException.EDITOR_MUTATION_CONFIRMATION_REQUIRED);
assertThat(exception.isRequiresConfirmation()).isTrue();
}
@Test
void editorAlterAndCreate_areAllowedForConfirmedAdmin() {
QueryExecutionPolicyService.PolicyDecision createDecision = service.enforce(
new QueryRequest("CREATE TABLE t_new (id INT PRIMARY KEY)", null, null),
QueryExecutionContext.editor("admin", true, true),
"mysql"
);
assertThat(createDecision.mutating()).isTrue();
assertThat(createDecision.primaryQueryType()).isEqualTo("CREATE");
QueryExecutionPolicyService.PolicyDecision alterDecision = service.enforce(
new QueryRequest("ALTER TABLE customers ADD COLUMN tag VARCHAR(64)", null, null),
QueryExecutionContext.editor("admin", true, true),
"mysql"
);
assertThat(alterDecision.mutating()).isTrue();
assertThat(alterDecision.primaryQueryType()).isEqualTo("ALTER");
}
@Test
void internalDropTable_isStillAllowed() {
QueryExecutionPolicyService.PolicyDecision decision = service.enforce(
new QueryRequest("DROP TABLE temp_rollup", null, null),
QueryExecutionContext.internal(),
"mysql"
);
assertThat(decision.mutating()).isTrue();
// Internal contexts (background jobs, migrations) bypass the DROP TABLE editor gate.
assertThat(decision.primaryQueryType()).isEqualTo("DROP TABLE");
}
@Test
void internalMutation_isStillAllowed() {
QueryExecutionPolicyService.PolicyDecision decision = service.enforce(
new QueryRequest("TRUNCATE TABLE temp_rollup", null, null),
QueryExecutionContext.internal(),
"mysql"
);
assertThat(decision.mutating()).isTrue();
assertThat(decision.primaryQueryType()).isEqualTo("TRUNCATE");
}
// --- Writes hidden inside a statement that reads as a SELECT ---------------
// PostgreSQL executes data-modifying CTEs, and the parser models them as a
// Select. Each of these deleted or rewrote a whole table from a non-admin
// account before the classifier learned to look inside.
private QueryExecutionPolicyException assertBlockedForViewer(String sql) {
return assertThrows(
QueryExecutionPolicyException.class,
() -> service.enforce(
new QueryRequest(sql, null, null),
QueryExecutionContext.editor("viewer", false, false),
"postgresql"
)
);
}
@Test
void cteDelete_isBlockedForNonAdmin() {
QueryExecutionPolicyException e =
assertBlockedForViewer("WITH x AS (DELETE FROM orders RETURNING *) SELECT * FROM x");
assertThat(e.getErrorCode()).isEqualTo(QueryExecutionPolicyException.EDITOR_MUTATION_FORBIDDEN);
}
@Test
void cteUpdate_isBlockedForNonAdmin() {
assertBlockedForViewer("WITH u AS (UPDATE orders SET total = 0 RETURNING *) SELECT * FROM u");
}
@Test
void cteInsert_isBlockedForNonAdmin() {
assertBlockedForViewer("WITH i AS (INSERT INTO audit(id) VALUES (1) RETURNING *) SELECT * FROM i");
}
@Test
void cteWriteInLaterPosition_isBlockedForNonAdmin() {
assertBlockedForViewer(
"WITH a AS (SELECT 1), b AS (DELETE FROM orders RETURNING *) SELECT * FROM a");
}
@Test
void nestedCteWrite_isBlockedForNonAdmin() {
assertBlockedForViewer(
"WITH o AS (WITH i AS (DELETE FROM orders RETURNING *) SELECT * FROM i) SELECT * FROM o");
}
@Test
void selectInto_isBlockedForNonAdmin() {
assertBlockedForViewer("SELECT * INTO exfiltrated FROM customers");
}
@Test
void cteWrite_requiresConfirmationForAdmin() {
QueryExecutionPolicyException e = assertThrows(
QueryExecutionPolicyException.class,
() -> service.enforce(
new QueryRequest("WITH x AS (DELETE FROM orders RETURNING *) SELECT * FROM x", null, null),
QueryExecutionContext.editor("admin", true, false),
"postgresql"
)
);
assertThat(e.getErrorCode())
.isEqualTo(QueryExecutionPolicyException.EDITOR_MUTATION_CONFIRMATION_REQUIRED);
}
@Test
void cteWrite_isAllowedForConfirmedAdmin() {
QueryExecutionPolicyService.PolicyDecision decision = service.enforce(
new QueryRequest("WITH x AS (DELETE FROM orders RETURNING *) SELECT * FROM x", null, null),
QueryExecutionContext.editor("admin", true, true),
"postgresql"
);
assertThat(decision.mutating()).isTrue();
}
// --- The guard must not swallow legitimate reads --------------------------
@Test
void readOnlyCte_remainsAllowedForNonAdmin() {
QueryExecutionPolicyService.PolicyDecision decision = service.enforce(
new QueryRequest("WITH recent AS (SELECT * FROM orders LIMIT 10) SELECT * FROM recent", null, null),
QueryExecutionContext.editor("viewer", false, false),
"postgresql"
);
assertThat(decision.mutating()).isFalse();
assertThat(decision.primaryQueryType()).isEqualTo("SELECT");
}
@Test
void writeKeywordInsideStringLiteral_isStillAReadForNonAdmin() {
QueryExecutionPolicyService.PolicyDecision decision = service.enforce(
new QueryRequest("SELECT 'WITH x AS (DELETE FROM t)' AS example", null, null),
QueryExecutionContext.editor("viewer", false, false),
"postgresql"
);
assertThat(decision.mutating()).isFalse();
}
@Test
void writeKeywordInsideComment_isStillAReadForNonAdmin() {
QueryExecutionPolicyService.PolicyDecision decision = service.enforce(
new QueryRequest("SELECT 1 -- WITH x AS (DELETE FROM t)\n", null, null),
QueryExecutionContext.editor("viewer", false, false),
"postgresql"
);
assertThat(decision.mutating()).isFalse();
}
@Test
void hiddenWriteScan_staysLinearOnAdversarialInput() {
// The text backstop used a lazy wildcard (\bSELECT\b[\s\S]*?\bINTO)
// and a regex block-comment strip, both of which backtracked
// quadratically: 224KB of repeated "SELECT " burned ~44s of CPU inside
// the guard, before the query ever reached the database. Any
// authenticated Editor user could stall a request thread with it.
String repeatedSelect = "SELECT " + "SELECT ".repeat(32_000);
String unterminatedBlockComment = "SELECT 1 /*" + "a/*".repeat(32_000);
for (String hostile : List.of(repeatedSelect, unterminatedBlockComment)) {
long startedAt = System.currentTimeMillis();
service.enforce(
new QueryRequest(hostile, null, null),
QueryExecutionContext.editor("viewer", false, false),
"postgresql"
);
long elapsed = System.currentTimeMillis() - startedAt;
assertThat(elapsed)
.as("classification of a %d char statement must not backtrack", hostile.length())
.isLessThan(5_000L);
}
}
@Test
void insertIntoSelect_isNotMisreadAsSelectInto() {
// SELECT_INTO_PATTERN matches a bare INTO target now that the SELECT
// prefix is gone, so the caller must gate it on the statement actually
// reading as a SELECT.
QueryExecutionPolicyService.PolicyDecision decision = service.enforce(
new QueryRequest("INSERT INTO archive SELECT * FROM orders", null, null),
QueryExecutionContext.editor("admin", true, true),
"postgresql"
);
assertThat(decision.primaryQueryType()).isEqualTo("INSERT");
}
@Test
void insertIntoSelect_isStillClassifiedAsInsert() {
QueryExecutionPolicyService.PolicyDecision decision = service.enforce(
new QueryRequest("INSERT INTO archive SELECT * FROM orders", null, null),
QueryExecutionContext.editor("admin", true, true),
"postgresql"
);
assertThat(decision.primaryQueryType()).isEqualTo("INSERT");
}
// --- MCP / coding-agent surface: CREATE/ALTER go through; DROP/TRUNCATE do not ---
@Test
void mcpAdminCreate_unconfirmedRequiresConfirmation() {
QueryExecutionPolicyException exception = assertThrows(
QueryExecutionPolicyException.class,
() -> service.enforce(
new QueryRequest("CREATE TABLE t_new (id INT PRIMARY KEY)", null, null),
QueryExecutionContext.mcp("admin", true, false),
"mysql"
)
);
assertThat(exception.getErrorCode())
.isEqualTo(QueryExecutionPolicyException.EDITOR_MUTATION_CONFIRMATION_REQUIRED);
assertThat(exception.isRequiresConfirmation()).isTrue();
}
@Test
void mcpAdminCreate_confirmedIsAllowed() {
QueryExecutionPolicyService.PolicyDecision decision = service.enforce(
new QueryRequest("CREATE TABLE t_new (id INT PRIMARY KEY)", null, null),
QueryExecutionContext.mcp("admin", true, true),
"mysql"
);
assertThat(decision.mutating()).isTrue();
assertThat(decision.primaryQueryType()).isEqualTo("CREATE");
}
@Test
void mcpAdminAlter_confirmedIsAllowed() {
QueryExecutionPolicyService.PolicyDecision decision = service.enforce(
new QueryRequest("ALTER TABLE customers ADD COLUMN tag VARCHAR(64)", null, null),
QueryExecutionContext.mcp("admin", true, true),
"mysql"
);
assertThat(decision.mutating()).isTrue();
assertThat(decision.primaryQueryType()).isEqualTo("ALTER");
}
@Test
void mcpAdminCreateIndex_confirmedIsAllowed() {
QueryExecutionPolicyService.PolicyDecision decision = service.enforce(
new QueryRequest("CREATE INDEX idx_customers_tag ON customers (tag)", null, null),
QueryExecutionContext.mcp("admin", true, true),
"mysql"
);
assertThat(decision.mutating()).isTrue();
assertThat(decision.primaryQueryType()).startsWith("CREATE");
}
@Test
void mcpDeveloperCreate_isForbidden() {
QueryExecutionPolicyException exception = assertThrows(
QueryExecutionPolicyException.class,
() -> service.enforce(
new QueryRequest("CREATE TABLE t_new (id INT PRIMARY KEY)", null, null),
QueryExecutionContext.mcp("dev", false, true),
"mysql"
)
);
assertThat(exception.getErrorCode())
.isEqualTo(QueryExecutionPolicyException.EDITOR_MUTATION_FORBIDDEN);
}
@Test
void mcpAdminDropTable_isBlockedEvenWhenConfirmed() {
QueryExecutionPolicyException exception = assertThrows(
QueryExecutionPolicyException.class,
() -> service.enforce(
new QueryRequest("DROP TABLE temp_rollup", null, null),
QueryExecutionContext.mcp("admin", true, true),
"mysql"
)
);
assertThat(exception.getErrorCode())
.isEqualTo(QueryExecutionPolicyException.UNSAFE_MUTATION_BLOCKED);
assertThat(exception.getMessage()).contains("DROP and TRUNCATE");
}
@Test
void mcpAdminDropIndex_isBlockedEvenWhenConfirmed() {
QueryExecutionPolicyException exception = assertThrows(
QueryExecutionPolicyException.class,
() -> service.enforce(
new QueryRequest("DROP INDEX idx_bookings_hotel ON bookings", null, null),
QueryExecutionContext.mcp("admin", true, true),
"mysql"
)
);
assertThat(exception.getErrorCode())
.isEqualTo(QueryExecutionPolicyException.UNSAFE_MUTATION_BLOCKED);
assertThat(exception.getMessage()).contains("DROP and TRUNCATE");
}
@Test
void mcpAdminTruncate_isBlockedEvenWhenConfirmed() {
QueryExecutionPolicyException exception = assertThrows(
QueryExecutionPolicyException.class,
() -> service.enforce(
new QueryRequest("TRUNCATE TABLE temp_rollup", null, null),
QueryExecutionContext.mcp("admin", true, true),
"mysql"
)
);
assertThat(exception.getErrorCode())
.isEqualTo(QueryExecutionPolicyException.UNSAFE_MUTATION_BLOCKED);
assertThat(exception.getMessage()).contains("DROP and TRUNCATE");
}
@Test
void mcpAdminExplainDrop_isBlockedEvenWhenConfirmed() {
QueryExecutionPolicyException exception = assertThrows(
QueryExecutionPolicyException.class,
() -> service.enforce(
new QueryRequest("EXPLAIN DROP TABLE temp_rollup", null, null),
QueryExecutionContext.mcp("admin", true, true),
"mysql"
)
);
assertThat(exception.getErrorCode())
.isEqualTo(QueryExecutionPolicyException.UNSAFE_MUTATION_BLOCKED);
assertThat(exception.getMessage()).contains("DROP and TRUNCATE");
}
// ── A malformed statement is a syntax error, not a permissions problem ──────────
//
// Reported from the field: a user pasted a SELECT that still carried the double
// quotes it had in source code and was told "Only admins or DBAs can execute DDL or DML from
// the SQL Editor", which reads as a permissions problem and sent them looking for a
// role fix. The statement is neither DDL nor DML — it is not valid SQL at all.
//
// The cause is two keyword heuristics disagreeing: QueryNormalizer.detectQueryType
// sanitizes the prefix away and answers SELECT, while the provider's isReadOnlyQuery
// strips only comments, still sees the leading quote, and answers false. mutating was
// computed as (!readOnly && type != UNKNOWN), so "SELECT" became a mutation.
private static final String QUOTED_SELECT =
"\"select h.id, h.name, h.city, case when h.country = 'India' then 'IN' "
+ "when h.country = 'United States' then 'US' else 'XX' end country_code from hotel h";
@Test
void selectPastedWithItsSurroundingQuotes_isReportedAsASyntaxErrorNotAPermissionError() {
QueryExecutionPolicyException exception = assertThrows(
QueryExecutionPolicyException.class,
() -> service.enforce(
new QueryRequest(QUOTED_SELECT, 10, 30),
QueryExecutionContext.editor("analyst", false, false),
"mysql"
)
);
assertThat(exception.getErrorCode()).isEqualTo(QueryExecutionPolicyException.STATEMENT_NOT_PARSEABLE);
assertThat(exception.getMessage()).doesNotContain("Only admins or DBAs");
assertThat(exception.getMessage()).contains("could not parse");
}
/**
* An admin gets the same diagnosis rather than a confirmation prompt. Offering to
* "confirm this DDL/DML" for a statement nothing managed to classify would invite
* confirming past the guard, and the statement cannot run anyway.
*/
@Test
void aMalformedSelectIsNotOfferedToAdminsAsAConfirmableMutation() {
QueryExecutionPolicyException exception = assertThrows(
QueryExecutionPolicyException.class,
() -> service.enforce(
new QueryRequest(QUOTED_SELECT, 10, 30),
QueryExecutionContext.editor("admin", true, false),
"mysql"
)
);
assertThat(exception.getErrorCode()).isEqualTo(QueryExecutionPolicyException.STATEMENT_NOT_PARSEABLE);
assertThat(exception.isRequiresConfirmation()).isFalse();
}
/** Confirmation cannot get a malformed statement through either. */
@Test
void aConfirmedAdminStillCannotRunAMalformedStatement() {
QueryExecutionPolicyException exception = assertThrows(
QueryExecutionPolicyException.class,
() -> service.enforce(
new QueryRequest(QUOTED_SELECT, 10, 30),
QueryExecutionContext.editor("admin", true, true),
"mysql"
)
);
assertThat(exception.getErrorCode()).isEqualTo(QueryExecutionPolicyException.STATEMENT_NOT_PARSEABLE);
}
/**
* The reclassification is gated on the detected verb being read-only, so a write the
* parser rejects keeps its mutation handling instead of being excused as a typo. This
* is the half that stops the fix from becoming a bypass.
*/
@Test
void anUnparseableWriteIsStillTreatedAsAMutation() {
QueryExecutionPolicyException exception = assertThrows(
QueryExecutionPolicyException.class,
() -> service.enforce(
new QueryRequest("DELETE FROM hotel WHERE (((", 10, 30),
QueryExecutionContext.editor("analyst", false, false),
"mysql"
)
);
assertThat(exception.getErrorCode()).isEqualTo(QueryExecutionPolicyException.EDITOR_MUTATION_FORBIDDEN);
}
/**
* The data-modifying CTE this whole guard exists for must not slip through the new
* branch: `detectHiddenWrite` vetoes it before the parse result is consulted, so a
* malformed variant is still a blocked write rather than a reported typo.
*/
@Test
void aMalformedDataModifyingCteIsStillBlockedAsAWrite() {
QueryExecutionPolicyException exception = assertThrows(
QueryExecutionPolicyException.class,
() -> service.enforce(
new QueryRequest("WITH x AS (DELETE FROM hotel RETURNING *) SELECT * FROM x WHERE (((", 10, 30),
QueryExecutionContext.editor("analyst", false, false),
"mysql"
)
);
assertThat(exception.getErrorCode()).isEqualTo(QueryExecutionPolicyException.EDITOR_MUTATION_FORBIDDEN);
}
/** The same query without the stray quote is an ordinary read. */
@Test
void theSameSelectWithoutTheStrayQuoteIsAllowed() {
QueryExecutionPolicyService.PolicyDecision decision = service.enforce(
new QueryRequest(QUOTED_SELECT.substring(1), 10, 30),
QueryExecutionContext.editor("analyst", false, false),
"mysql"
);
assertThat(decision.mutating()).isFalse();
assertThat(decision.primaryQueryType()).isEqualTo("SELECT");
}
}