diff --git a/apple/Packages/TableProCore/Sources/TableProSQLGrammar/SQLReadOnlyFunctionCalls.swift b/apple/Packages/TableProCore/Sources/TableProSQLGrammar/SQLReadOnlyFunctionCalls.swift new file mode 100644 index 0000000000..1264a0ed5f --- /dev/null +++ b/apple/Packages/TableProCore/Sources/TableProSQLGrammar/SQLReadOnlyFunctionCalls.swift @@ -0,0 +1,351 @@ +import Foundation + +// The one place that says which calls Read-Only runs on an engine whose functions can write, when the driver cannot hold +// the statement to the engine's read-only mode. A built-in here reads only: nothing that writes, locks, sleeps, waits or +// reaches a file (GET_LOCK, SLEEP, LOAD_FILE, NEXTVAL, SETVAL, a DBMS_ package) is listed. A qualified or quoted name, a +// name the scanner cannot read, and anything else may be a function the user wrote. A call written without parentheses, +// which Oracle and Dameng accept for a function with no arguments, cannot be told from a column and is not seen. +public enum SQLReadOnlyFunctionCalls { + // An autonomous-transaction function on Oracle and Dameng, a stored function on MySQL, MariaDB and OceanBase, PL/pgSQL + // on the PostgreSQL family. TiDB, StarRocks and Databend have no stored function or UDF that writes; SQL Server, + // Snowflake, BigQuery, Trino and Redshift refuse a write from a function a query calls; ClickHouse, the SQLite engines + // and Cassandra have none. + public static let queryFunctionsCanWrite: Set = [ + "Oracle", "Dameng", + "MySQL", "MariaDB", "OceanBase", + "PostgreSQL", "CockroachDB", "PGlite", "KingbaseES", + ] + + static let commonBuiltins: Set = [ + "COUNT", "SUM", "AVG", "MIN", "MAX", "STDDEV", "STDDEV_POP", "STDDEV_SAMP", "VARIANCE", "VAR_POP", "VAR_SAMP", + "CORR", "COVAR_POP", "COVAR_SAMP", "GROUPING", + "ROW_NUMBER", "RANK", "DENSE_RANK", "PERCENT_RANK", "CUME_DIST", "NTILE", "LAG", "LEAD", "FIRST_VALUE", + "LAST_VALUE", "NTH_VALUE", + "COALESCE", "NULLIF", "GREATEST", "LEAST", "CAST", "EXTRACT", + "LOWER", "UPPER", "LENGTH", "TRIM", "LTRIM", "RTRIM", "SUBSTR", "SUBSTRING", "REPLACE", "CONCAT", "LPAD", "RPAD", + "REVERSE", "ASCII", "REGEXP_REPLACE", "REGEXP_SUBSTR", "REGEXP_INSTR", "REGEXP_LIKE", "POSITION", "TRANSLATE", + "ABS", "CEIL", "CEILING", "FLOOR", "ROUND", "MOD", "POWER", "SQRT", "EXP", "LN", "LOG", "SIGN", "SIN", "COS", + "TAN", "ASIN", "ACOS", "ATAN", "ATAN2", + "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "LOCALTIMESTAMP", + "JSON_VALUE", "JSON_QUERY", "JSON_OBJECT", "JSON_ARRAY", "JSON_TABLE", + ] + + // Oracle and Dameng. + static let oracleBuiltins: Set = [ + "NVL", "NVL2", "DECODE", "LNNVL", "NANVL", "LISTAGG", "MEDIAN", "RATIO_TO_REPORT", + "TO_CHAR", "TO_DATE", "TO_NUMBER", "TO_TIMESTAMP", "TO_TIMESTAMP_TZ", "TO_DSINTERVAL", "TO_YMINTERVAL", + "NUMTODSINTERVAL", "NUMTOYMINTERVAL", "TO_NCHAR", "HEXTORAW", "RAWTOHEX", "ROWIDTOCHAR", "CONVERT", + "INSTR", "INSTRB", "LENGTHB", "SUBSTRB", "INITCAP", "CHR", "SOUNDEX", "REGEXP_COUNT", + "TRUNC", "BITAND", "WIDTH_BUCKET", "REMAINDER", + "ADD_MONTHS", "MONTHS_BETWEEN", "LAST_DAY", "NEXT_DAY", "NEW_TIME", "FROM_TZ", "TZ_OFFSET", "SYS_EXTRACT_UTC", + "SYS_GUID", "SYS_CONTEXT", "USERENV", "ORA_HASH", "STANDARD_HASH", "XMLTABLE", + ] + + // MySQL, MariaDB and the servers that answer as MySQL. + static let mysqlBuiltins: Set = [ + "IF", "IFNULL", "ISNULL", "GROUP_CONCAT", "JSON_ARRAYAGG", "JSON_OBJECTAGG", "BIT_AND", "BIT_OR", "BIT_XOR", + "ANY_VALUE", "CONVERT", + "CONCAT_WS", "CHAR_LENGTH", "CHARACTER_LENGTH", "OCTET_LENGTH", "BIT_LENGTH", "LCASE", "UCASE", "LEFT", "RIGHT", + "MID", "LOCATE", "INSTR", "FIND_IN_SET", "FIELD", "ELT", "STRCMP", "SUBSTRING_INDEX", "REPEAT", "SPACE", "CHAR", + "FORMAT", "QUOTE", "SOUNDEX", "HEX", "UNHEX", "BIN", "OCT", "CONV", + "TRUNCATE", "POW", "LOG2", "LOG10", "COT", "DEGREES", "RADIANS", "PI", "RAND", "CRC32", + "NOW", "SYSDATE", "CURDATE", "CURTIME", "LOCALTIME", "UTC_DATE", "UTC_TIME", "UTC_TIMESTAMP", "DATE", "TIME", + "TIMESTAMP", "YEAR", "QUARTER", "MONTH", "WEEK", "WEEKDAY", "WEEKOFYEAR", "YEARWEEK", "DAY", "DAYOFMONTH", + "DAYOFWEEK", "DAYOFYEAR", "DAYNAME", "MONTHNAME", "HOUR", "MINUTE", "SECOND", "MICROSECOND", "DATE_FORMAT", + "TIME_FORMAT", "STR_TO_DATE", "DATE_ADD", "DATE_SUB", "ADDDATE", "SUBDATE", "ADDTIME", "SUBTIME", "DATEDIFF", + "TIMEDIFF", "TIMESTAMPDIFF", "TIMESTAMPADD", "UNIX_TIMESTAMP", "FROM_UNIXTIME", "FROM_DAYS", "TO_DAYS", + "TO_SECONDS", "SEC_TO_TIME", "TIME_TO_SEC", "MAKEDATE", "MAKETIME", "PERIOD_ADD", "PERIOD_DIFF", "LAST_DAY", + "CONVERT_TZ", + "JSON_EXTRACT", "JSON_UNQUOTE", "JSON_CONTAINS", "JSON_CONTAINS_PATH", "JSON_KEYS", "JSON_LENGTH", "JSON_TYPE", + "JSON_VALID", "JSON_SEARCH", "JSON_DEPTH", + "MD5", "SHA", "SHA1", "SHA2", "UUID", "UUID_SHORT", + "DATABASE", "SCHEMA", "USER", "CURRENT_USER", "SESSION_USER", "SYSTEM_USER", "VERSION", "CONNECTION_ID", + ] + + // An older PostgreSQL-family driver without the mode. + static let postgresBuiltins: Set = [ + "NOW", "TO_CHAR", "TO_DATE", "TO_NUMBER", "TO_TIMESTAMP", "DATE_TRUNC", "DATE_PART", "AGE", "TRUNC", "LEFT", + "RIGHT", "CHAR_LENGTH", "CHARACTER_LENGTH", "OCTET_LENGTH", "SPLIT_PART", "STRING_AGG", "ARRAY_AGG", + "ARRAY_LENGTH", "INITCAP", "CHR", "MD5", "FORMAT", "CONCAT_WS", "TO_JSON", "TO_JSONB", "JSON_AGG", "JSONB_AGG", + "JSON_BUILD_OBJECT", "JSONB_BUILD_OBJECT", "JSON_BUILD_ARRAY", "JSONB_BUILD_ARRAY", "GENERATE_SERIES", + "BOOL_AND", "BOOL_OR", "EVERY", "POW", "LOG10", "PI", "RANDOM", + ] + + private static let oracleFamily: Set = ["Oracle", "Dameng"] + private static let mysqlFamily: Set = ["MySQL", "MariaDB", "OceanBase", "TiDB", "StarRocks", "Databend"] + private static let postgresFamily: Set = ["PostgreSQL", "CockroachDB", "PGlite", "KingbaseES", "Redshift"] + + private static let oracleCalls = commonBuiltins.union(oracleBuiltins) + private static let mysqlCalls = commonBuiltins.union(mysqlBuiltins) + private static let postgresCalls = commonBuiltins.union(postgresBuiltins) + private static let anyCalls = commonBuiltins.union(oracleBuiltins).union(mysqlBuiltins).union(postgresBuiltins) + + public static func builtins(forDatabaseTypeId typeId: String) -> Set { + if oracleFamily.contains(typeId) { return oracleCalls } + if mysqlFamily.contains(typeId) { return mysqlCalls } + if postgresFamily.contains(typeId) { return postgresCalls } + return anyCalls + } + + // Reserved in Oracle, MySQL and PostgreSQL alike, so no function a query calls can carry the bare name. + static let reservedWords: Set = [ + "SELECT", "FROM", "WHERE", "AND", "OR", "NOT", "IN", "EXISTS", "AS", "ON", "WITH", "GROUP", "ORDER", "HAVING", + "UNION", "DISTINCT", "ELSE", "THEN", "ALL", "VALUES", "BETWEEN", "TABLE", + ] + + // A word another engine lets a user function carry stands before a parenthesis only in this syntax. + private enum Syntax { + // Right after a call's closing parenthesis: `SUM(x) OVER (`. + case afterCall + // After a call, opening with this word: `COUNT(*) FILTER (WHERE`, `MAX(x) KEEP (DENSE_RANK`. + case afterCallOpening(String) + // After one of these words: `GROUP BY (`, `GROUPING SETS (`, `USE INDEX (`. + case afterWord(Set) + // After a name, a literal or a closing parenthesis: `t PARTITION (`, `x LIKE (`, `) EXCEPT (`. + case afterOperand + // Opening with one of these words: `ARRAY(SELECT`, `LATERAL (SELECT`. + case opening(Set) + // After a comparison: `= ANY (`. + case afterComparison + // Its parenthesized part followed by one of these words: `MATCH (a) AGAINST`, `INTERVAL (n) DAY`. + case followedBy(Set) + } + + private static let intervalUnits: Set = [ + "MICROSECOND", "SECOND", "MINUTE", "HOUR", "DAY", "WEEK", "MONTH", "QUARTER", "YEAR", + ] + + private static let syntax: [String: [Syntax]] = [ + "BY": [.afterWord(["GROUP", "ORDER", "PARTITION", "CONNECT"])], + "OVER": [.afterCall], + "FILTER": [.afterCallOpening("WHERE")], + "KEEP": [.afterCallOpening("DENSE_RANK")], + "AGAINST": [.afterCall], + "MATCH": [.followedBy(["AGAINST"])], + "INTERVAL": [.followedBy(intervalUnits)], + "CASE": [.followedBy(["WHEN"])], + "WHEN": [.afterOperand, .afterWord(["CASE"])], + "PARTITION": [.afterOperand], + "PIVOT": [.afterOperand], + "UNPIVOT": [.afterOperand], + "CUBE": [.afterWord(["BY"])], + "ROLLUP": [.afterWord(["BY"])], + "SETS": [.afterWord(["GROUPING"])], + "ARRAY": [.opening(["SELECT", "WITH"])], + "LATERAL": [.opening(["SELECT", "WITH"])], + "ANY": [.afterComparison], + "SOME": [.afterComparison], + "JOIN": [.afterOperand, .afterWord(["INNER", "LEFT", "RIGHT", "FULL", "OUTER", "CROSS", "NATURAL", "FOR"])], + "USING": [.afterOperand], + "INDEX": [.afterWord(["USE", "FORCE", "IGNORE"])], + "KEY": [.afterWord(["USE", "FORCE", "IGNORE"])], + "LIKE": [.afterOperand], + "IS": [.afterOperand], + "INTERSECT": [.afterOperand], + "EXCEPT": [.afterOperand], + "MINUS": [.afterOperand], + "LIMIT": [.afterOperand], + "OFFSET": [.afterOperand], + // Word operators: `10 DIV (2)`, `a XOR (b)`. + "DIV": [.afterOperand], + "XOR": [.afterOperand], + "REGEXP": [.afterOperand], + "RLIKE": [.afterOperand], + "ILIKE": [.afterOperand], + "ESCAPE": [.afterOperand], + ] + + // After one of these a call can start, so a word that follows it is not standing after an operand. Word operators + // are among them: `10 DIV pivot(1)` calls `pivot`. + private static let introducers: Set = reservedWords.union(syntax.keys).union([ + "SET", "INTO", "RETURN", "RETURNING", "PRIOR", "CALL", "DO", "EXECUTE", "FOR", "CONNECT", + "MOD", "COLLATE", "BINARY", "UNIQUE", "SOUNDS", "MEMBER", "OF", "SIMILAR", "TO", "ASC", "DESC", "NULLS", + ]) + + private static let openParenthesis = UInt16(UnicodeScalar("(").value) + private static let closeParenthesis = UInt16(UnicodeScalar(")").value) + private static let period = UInt16(UnicodeScalar(".").value) + private static let colon = UInt16(UnicodeScalar(":").value) + private static let quoteOpeners: Set = [0x22, 0x60, 0x5B] + private static let comparisons: Set = [0x3D, 0x3C, 0x3E, 0x21] + + // Under every way the engine could lex the text, as the classifier reads it. A type with a length, such as + // `DECIMAL(10, 2)` in a cast, is the engine's own type, not a call: `typeNames` are the engine's types. + public static func callsUnlistedFunction( + _ sql: String, + databaseTypeId: String, + readings: SQLLexicalReadings, + typeNames: Set + ) -> Bool { + let typeNames = Set(typeNames.map { $0.uppercased() }) + let known = builtins(forDatabaseTypeId: databaseTypeId) + return readings.all.contains { grammar in + SQLStatementClassifier.statements(of: sql, grammar: grammar).contains { statement in + statementCallsUnlistedFunction(statement, grammar: grammar, builtins: known, typeNames: typeNames) + } + } + } + + private static func statementCallsUnlistedFunction( + _ statement: String, + grammar: SQLLexicalGrammar, + builtins: Set, + typeNames: Set + ) -> Bool { + // A plain EXPLAIN plans its statement without running it. + if let explain = SQLExplainStatement.read(statement, grammar: grammar) { + switch explain.reading { + case .describesObject, .explains(_, false): + return false + case .explains(_, true), .unreadable: + break + } + } + let source = statement as NSString + let code = SQLCodeProjection.code(of: statement, grammar: grammar) as NSString + var quoted: [Range]? + return SQLFunctionCallScanner.calls(in: source, code: code).contains { call in + guard case .named(let name, let start) = call.callee, + !quoteOpeners.contains(source.character(at: start)) + else { return true } + let word = name.uppercased() + switch qualifier(before: start, in: code) { + case .member: + return true + case .cast: + return !typeNames.contains(word) + case .unqualified: + break + } + if builtins.contains(word) || typeNames.contains(word) || reservedWords.contains(word) { return false } + guard let rules = syntax[word] else { return true } + let spans = quoted ?? quotedSpans(in: source, grammar: grammar) + quoted = spans + let site = CallSite(code: code, quotedSpans: spans, nameStart: start, parenthesis: call.parenthesis) + return !rules.contains { site.matches($0) } + } + } + + // Where a literal or a quoted name sits. The projection blanks comments too, and a comment is not a token. + private static func quotedSpans(in source: NSString, grammar: SQLLexicalGrammar) -> [Range] { + var spans: [Range] = [] + var index = 0 + while index < source.length { + guard let span = SQLNonCodeSpan.span(at: index, in: source, grammar: grammar) else { + index += 1 + continue + } + if span.kind == .quoted { spans.append(span.start.. Qualifier { + var cursor = start - 1 + while cursor >= 0, SQLFunctionCallScanner.isBlank(code.character(at: cursor)) { + cursor -= 1 + } + guard cursor >= 0 else { return .unqualified } + let unit = code.character(at: cursor) + if unit == period { return .member } + guard unit == colon else { return .unqualified } + return cursor > 0 && code.character(at: cursor - 1) == colon ? .cast : .member + } + + private enum Neighbor: Equatable { + case start + case word(String) + case symbol(UInt16) + // A literal or a quoted name, which the projection blanked. + case quoted + } + + private struct CallSite { + let code: NSString + let quotedSpans: [Range] + let nameStart: Int + let parenthesis: Int + + func matches(_ rule: Syntax) -> Bool { + switch rule { + case .afterCall: + return before == .symbol(SQLReadOnlyFunctionCalls.closeParenthesis) + case .afterCallOpening(let word): + return before == .symbol(SQLReadOnlyFunctionCalls.closeParenthesis) && firstWord(after: parenthesis) == word + case .afterWord(let words): + guard case .word(let word) = before else { return false } + return words.contains(word) + case .afterOperand: + switch before { + case .quoted: + return true + case .symbol(let unit): + return unit == SQLReadOnlyFunctionCalls.closeParenthesis + case .word(let word): + return !SQLReadOnlyFunctionCalls.introducers.contains(word) + case .start: + return false + } + case .opening(let words): + return firstWord(after: parenthesis).map { words.contains($0) } ?? false + case .afterComparison: + guard case .symbol(let unit) = before else { return false } + return SQLReadOnlyFunctionCalls.comparisons.contains(unit) + case .followedBy(let words): + return wordAfterGroup().map { words.contains($0) } ?? false + } + } + + private var before: Neighbor { + var cursor = nameStart - 1 + while cursor >= 0, SQLFunctionCallScanner.isBlank(code.character(at: cursor)) { + if quotedSpans.contains(where: { $0.contains(cursor) }) { return .quoted } + cursor -= 1 + } + guard cursor >= 0 else { return .start } + let unit = code.character(at: cursor) + guard SQLFunctionCallScanner.isIdentifierUnit(unit) else { return .symbol(unit) } + var start = cursor + while start > 0, SQLFunctionCallScanner.isIdentifierUnit(code.character(at: start - 1)) { + start -= 1 + } + return .word(code.substring(with: NSRange(location: start, length: cursor - start + 1)).uppercased()) + } + + private func firstWord(after index: Int) -> String? { + var cursor = index + 1 + while cursor < code.length, SQLFunctionCallScanner.isBlank(code.character(at: cursor)) { + cursor += 1 + } + var end = cursor + while end < code.length, SQLFunctionCallScanner.isIdentifierUnit(code.character(at: end)) { + end += 1 + } + guard end > cursor else { return nil } + return code.substring(with: NSRange(location: cursor, length: end - cursor)).uppercased() + } + + private func wordAfterGroup() -> String? { + var depth = 0 + for index in parenthesis.. Bool? + + // Whether every statement `sql` runs, under every way the engine could lex it, only reads or changes rows. A + // request form `requestIsData` cannot read, but `request` tiers, is refused. + static func isDataStatement( + _ sql: String, + databaseTypeId: String, + readings: SQLLexicalReadings, + request: RequestClassification? = nil, + requestIsData: RequestDataStatement? = nil + ) -> Bool { + guard let lexings = readings.lexings(of: sql) else { return false } + let tiering = SQLStatementTiering(databaseTypeId: databaseTypeId, readings: readings, request: request) + var seen: Set = [] + return lexings.allSatisfy { lexing in + runnableStatements(of: lexing.text, grammar: lexing.grammar).allSatisfy { statement in + guard seen.insert(SQLLexing(grammar: lexing.grammar, text: statement)).inserted else { return true } + if let answer = requestIsData?(statement, lexing.grammar) { return answer } + if let request, request(statement, lexing.grammar) != nil { return false } + return tiering.isDataStatement(statement, grammar: lexing.grammar) + } + } + } + + // Whether an unqualified table lands in a schema whose tables the server acts on. Oracle and Dameng name the + // session's schema after the user, so SYSTEM there is a login with tables of its own; SYS is the dictionary. + static func isSystemScope(database: String?, schema: String?, databaseTypeId: String) -> Bool { + let schemas = SQLStatementTiering.systemSchemas(for: databaseTypeId) + let namesUser = databaseTypeId == "Oracle" || databaseTypeId == "Dameng" + let readSchema = namesUser ? schema.flatMap { $0.uppercased() == "SYS" ? $0 : nil } : schema + return [database, readSchema].contains { $0.map { schemas.contains($0.uppercased()) } == true } + } +} + +extension SQLStatementTiering { + static let rowChangeKeywords: Set = ["INSERT", "UPDATE", "DELETE", "MERGE", "UPSERT"] + + // `REPLACE [LOW_PRIORITY | DELAYED] INTO t`. ClickHouse's `REPLACE TABLE` and Teradata's `REPLACE VIEW` define. + static let replaceRowWords: Set = ["INTO", "LOW_PRIORITY", "DELAYED"] + + // MySQL makes INTO optional in `REPLACE t VALUES (...)`. + static let mySQLFamily: Set = ["MySQL", "MariaDB", "TiDB", "OceanBase"] + + static let postgreSQLFamily: Set = ["PostgreSQL", "CockroachDB", "PGlite", "KingbaseES", "Redshift"] + + // An UPDATE of `pg_settings` runs SET; KingbaseES names its catalog `sys_` as well. + static func systemRelationPrefixes(for databaseTypeId: String) -> [String] { + guard postgreSQLFamily.contains(databaseTypeId) else { return [] } + return databaseTypeId == "KingbaseES" ? ["PG_", "SYS_"] : ["PG_"] + } + + // SQL Server's msdb holds the SQL Agent jobs it runs. + static func systemSchemas(for databaseTypeId: String) -> Set { + if mySQLFamily.contains(databaseTypeId) { return ["MYSQL", "PERFORMANCE_SCHEMA", "SYS"] } + switch databaseTypeId { + case "KingbaseES": return ["PG_CATALOG", "SYS_CATALOG"] + case "CockroachDB": return ["PG_CATALOG", "SYSTEM", "CRDB_INTERNAL"] + case "PostgreSQL", "PGlite", "Redshift": return ["PG_CATALOG"] + case "SQL Server": return ["MSDB"] + case "Oracle": return ["SYS", "SYSTEM"] + case "Dameng": return ["SYS"] + case "ClickHouse": return ["SYSTEM"] + default: return [] + } + } + + // A ClickHouse ALTER action that is not a row change, after a comma at the statement's depth. + static let clickHouseAlterActions: Set = [ + "ADD", "DROP", "MODIFY", "RENAME", "CLEAR", "COMMENT", "MATERIALIZE", "FREEZE", "UNFREEZE", "ATTACH", "DETACH", + "MOVE", "REPLACE", "FETCH", "RESET", "REMOVE", "APPLY", + ] + + func isDataStatement(_ statement: String, grammar: SQLLexicalGrammar) -> Bool { + if statementClassification(statement, grammar: grammar).tier == .safe { return true } + if let batch = CQLBatch.statements(in: statement, grammar: grammar) { + return batch.allSatisfy { isDataStatement($0, grammar: grammar) } + } + guard !SQLProceduralBlock.runs(statement, grammar: grammar) else { return false } + return changesOnlyRows(StatementCode(statement, grammar: grammar), grammar: grammar, depth: 0) + } + + private func changesOnlyRows(_ code: StatementCode, grammar: SQLLexicalGrammar, depth: Int) -> Bool { + guard depth <= Self.deepestNesting else { return false } + let calls = SQLFunctionCallScanner.calls(in: code.text, code: code.code as NSString) + guard !changesSessionOrServer(code, calls: calls, grammar: grammar), + dynamicSQLClassification(code, grammar: grammar, depth: depth) == nil, + Self.conditionalCommentClassification(code.statement, grammar: grammar) == nil + else { return false } + if SQLExplainStatement.keywords.contains(code.keyword) { + return explainedStatementChangesOnlyRows(code, grammar: grammar, depth: depth) + } + if code.keyword == "WITH" { + return commonTableExpressionsChangeOnlyRows(code, grammar: grammar, depth: depth) + } + return keywordChangesOnlyRows(code, grammar: grammar) + } + + // A plain EXPLAIN already read as safe; what is left runs its statement, writes its plan or stores statistics. + private func explainedStatementChangesOnlyRows(_ code: StatementCode, grammar: SQLLexicalGrammar, depth: Int) -> Bool { + guard let explain = SQLExplainStatement.read(code.statement, grammar: grammar), + case .explains(let start, true) = explain.reading, + !code.tokens.contains(where: { $0.location < start && $0.word == "INTO" }) + else { return false } + let explained = StatementCode(code.text.substring(from: start), grammar: grammar) + if explain.keyword == "ANALYZE", explained.keyword == "TABLE" { return false } + return changesOnlyRows(explained, grammar: grammar, depth: depth + 1) + } + + private func commonTableExpressionsChangeOnlyRows( + _ code: StatementCode, + grammar: SQLLexicalGrammar, + depth: Int + ) -> Bool { + guard depth <= Self.deepestNesting, + let list = SQLCommonTableExpressions.read(code.statement, grammar: grammar) + else { return false } + let main = StatementCode(code.text.substring(from: list.mainStatement), grammar: grammar) + let bodies = list.bodies.map { StatementCode(code.text.substring(with: $0), grammar: grammar) } + return ([main] + bodies).allSatisfy { part in + part.keyword == "WITH" + ? commonTableExpressionsChangeOnlyRows(part, grammar: grammar, depth: depth + 1) + : keywordChangesOnlyRows(part, grammar: grammar) + } + } + + private func keywordChangesOnlyRows(_ code: StatementCode, grammar: SQLLexicalGrammar) -> Bool { + let keyword = code.keyword + // `SELECT ... INTO` makes a table on PostgreSQL and SQL Server, and sets a variable on MySQL. + if isQuery(keyword) { return !code.contains("INTO") } + let changesRows: Bool + if keyword == "REPLACE" { + changesRows = Self.mySQLFamily.contains(databaseTypeId) + || Self.word(after: keyword, in: code).map(Self.replaceRowWords.contains) == true + } else if keyword == "ALTER" { + changesRows = databaseTypeId == Self.clickHouse && Self.changesClickHouseRows(code) + } else { + changesRows = Self.rowChangeKeywords.contains(keyword) + && !Self.updatesStatistics(code) && !Self.insertsProcedureResults(code) + } + return changesRows && !namesSystemRelation(code, grammar: grammar) + } + + // A call that sets the session, signals the server or runs work elsewhere, which a SELECT or an INSERT can carry. A + // sequence's next value is a row's key, so it passes. + private func changesSessionOrServer( + _ code: StatementCode, + calls: [SQLFunctionCallScanner.Call], + grammar: SQLLexicalGrammar + ) -> Bool { + let callsOne = calls.contains { call in + guard case .named(let name, _) = call.callee else { return true } + if SQLStateChangingFunctions.sequences.contains(name.uppercased().lowercased()) { return false } + return SQLStateChangingFunctions.contains(name) + || (databaseTypeId == Self.duckDB && SQLStateChangingFunctions.isDuckDBCall(name)) + } + return callsOne + || SQLStateChangingFunctions.namesStateChangingTable(in: code.text, tokens: code.tokens, grammar: grammar) + } + + // Any qualifier naming a system schema, or on the PostgreSQL family any `pg_` relation, since an unqualified one + // resolves to pg_catalog first. A row change that only reads one in a subquery is refused too. + private func namesSystemRelation(_ code: StatementCode, grammar: SQLLexicalGrammar) -> Bool { + let schemas = Self.systemSchemas(for: databaseTypeId) + let prefixes = Self.systemRelationPrefixes(for: databaseTypeId) + guard !schemas.isEmpty || !prefixes.isEmpty else { return false } + return code.tokens.indices.contains { index in + if !prefixes.isEmpty, Self.spellsEscapedName(at: index, in: code) { return true } + guard let name = Self.identifier(at: index, in: code, grammar: grammar) else { return false } + if schemas.contains(name), code.isSymbol(Self.period, at: index + 1) { return true } + let isCall = code.tokens.indices.contains(index + 1) && code.tokens[index + 1].kind == .open + return !isCall && prefixes.contains(where: name.hasPrefix) + } + } + + // A word, or the name inside an identifier quote, in capitals. + private static func identifier(at index: Int, in code: StatementCode, grammar: SQLLexicalGrammar) -> String? { + let token = code.tokens[index] + if let word = token.word { return word } + guard token.kind == .quoted, + let span = SQLNonCodeSpan.span(at: token.location, in: code.text, grammar: grammar), + identifierQuotes.contains(code.text.character(at: span.start)) + else { return nil } + let inner = NSRange(location: span.start + 1, length: max(0, span.contentEnd - span.start - 1)) + return code.text.substring(with: inner).uppercased() + } + + // PostgreSQL's `U&"pg\005fsettings"` spells a name in escapes this reader does not decode: the word U, then `&`, + // then the quoted name, with nothing between them. + private static func spellsEscapedName(at index: Int, in code: StatementCode) -> Bool { + let tokens = code.tokens + return index >= 2 && tokens[index].kind == .quoted && tokens[index - 2].word == "U" + && code.isSymbol(ampersand, at: index - 1) + && tokens[index - 1].location == tokens[index - 2].location + 1 + && tokens[index].location == tokens[index - 1].location + 1 + } + + private static let ampersand = UInt16(UnicodeScalar("&").value) + + private static func word(after keyword: String, in code: StatementCode) -> String? { + guard let verb = code.tokens.firstIndex(where: { $0.word == keyword }), + code.tokens.indices.contains(verb + 1) + else { return nil } + return code.tokens[verb + 1].word + } + + // `ALTER TABLE t [ON CLUSTER c] UPDATE ... WHERE` and `... DELETE WHERE` are the row changes ClickHouse's grid + // writes with. Any other action in the same ALTER defines. + private static func changesClickHouseRows(_ code: StatementCode) -> Bool { + let tokens = code.tokens + guard let verb = tokens.firstIndex(where: { $0.word == "ALTER" }), + tokens.indices.contains(verb + 2), tokens[verb + 1].word == "TABLE" + else { return false } + let depth = tokens[verb].depth + var index = verb + 2 + while tokens.indices.contains(index + 2), code.isSymbol(period, at: index + 1) { + index += 2 + } + index += 1 + if tokens.indices.contains(index + 2), tokens[index].word == "ON", tokens[index + 1].word == "CLUSTER" { + index += 3 + } + guard tokens.indices.contains(index), tokens[index].word == "UPDATE" || tokens[index].word == "DELETE" else { + return false + } + return !tokens.indices.dropFirst(index + 1).contains { later in + tokens[later].kind == .comma && tokens[later].depth == depth && tokens.indices.contains(later + 1) + && tokens[later + 1].word.map(clickHouseAlterActions.contains) == true + } + } + + // T-SQL's `UPDATE STATISTICS t` rebuilds statistics. A table named statistics is followed by SET, and T-SQL's own + // reader cuts that SET off as a statement of its own. + private static func updatesStatistics(_ code: StatementCode) -> Bool { + guard code.keyword == "UPDATE", + let verb = code.tokens.firstIndex(where: { $0.word == "UPDATE" }), + code.tokens.indices.contains(verb + 1), code.tokens[verb + 1].word == "STATISTICS" + else { return false } + return !(code.tokens.indices.contains(verb + 2) && code.tokens[verb + 2].word == "SET") + } + + // T-SQL's `INSERT INTO t EXEC proc` runs the procedure and stores what it returns. + private static func insertsProcedureResults(_ code: StatementCode) -> Bool { + guard code.keyword == "INSERT" else { return false } + return code.tokens.contains { $0.depth == 0 && ($0.word == "EXEC" || $0.word == "EXECUTE") } + } +} diff --git a/apple/Packages/TableProCore/Sources/TableProSQLGrammar/SQLStatementClassifier.swift b/apple/Packages/TableProCore/Sources/TableProSQLGrammar/SQLStatementClassifier.swift index bec2495864..2a220e964c 100644 --- a/apple/Packages/TableProCore/Sources/TableProSQLGrammar/SQLStatementClassifier.swift +++ b/apple/Packages/TableProCore/Sources/TableProSQLGrammar/SQLStatementClassifier.swift @@ -277,6 +277,11 @@ extension SQLStatementTiering { if isQuery(keyword) { return code.contains("INTO") ? .write : .safe } + // `INSERT OVERWRITE` empties the table first on Snowflake, Databricks and Hive; Hive's `... DIRECTORY` writes files. + if keyword == "INSERT", let verb = code.tokens.firstIndex(where: { $0.kind != .open }), + code.tokens.indices.contains(verb + 1), code.tokens[verb + 1].word == "OVERWRITE" { + return StatementClassification(tier: .destructive, reachesFilesystemOrExecutesCode: code.contains("DIRECTORY")) + } if keyword == "VACUUM" { // SQLite's `VACUUM [schema] INTO 'file'` writes a file whatever stands between the two words. return StatementClassification(tier: .write, reachesFilesystemOrExecutesCode: code.contains("INTO")) diff --git a/apple/Packages/TableProCore/Tests/TableProSQLGrammarTests/SQLDataStatementTests.swift b/apple/Packages/TableProCore/Tests/TableProSQLGrammarTests/SQLDataStatementTests.swift new file mode 100644 index 0000000000..f58010a799 --- /dev/null +++ b/apple/Packages/TableProCore/Tests/TableProSQLGrammarTests/SQLDataStatementTests.swift @@ -0,0 +1,137 @@ +import Foundation +import TableProSQLGrammar +import Testing + +struct SQLDataStatementTests { + private static func isData(_ sql: String, _ engine: String = "PostgreSQL") -> Bool { + let readings = SQLLexicalReadings.resolve(databaseTypeId: engine, declared: nil, session: nil) + return SQLStatementClassifier.isDataStatement(sql, databaseTypeId: engine, readings: readings) + } + + @Test("A read or a row change is a data statement", arguments: [ + ("SELECT * FROM orders WHERE id = 1", "PostgreSQL"), + ("INSERT INTO orders (id, note) VALUES (1, 'a')", "PostgreSQL"), + ("UPDATE orders SET paid = true WHERE id = 1", "PostgreSQL"), + ("DELETE FROM orders WHERE id = 1", "PostgreSQL"), + ("MERGE INTO orders o USING staged s ON o.id = s.id WHEN MATCHED THEN UPDATE SET note = s.note", "PostgreSQL"), + ("WITH gone AS (DELETE FROM orders WHERE id = 1 RETURNING *) INSERT INTO archive SELECT * FROM gone", "PostgreSQL"), + ("WITH recent AS (SELECT id FROM orders) UPDATE orders SET seen = true WHERE id IN (SELECT id FROM recent)", + "PostgreSQL"), + ("EXPLAIN ANALYZE UPDATE orders SET paid = true WHERE id = 1", "PostgreSQL"), + ("EXPLAIN SELECT * FROM orders", "PostgreSQL"), + ("INSERT INTO orders (id) VALUES (nextval('orders_id_seq'))", "PostgreSQL"), + ("SELECT nextval('orders_id_seq')", "PostgreSQL"), + ("SHOW search_path", "PostgreSQL"), + ("REPLACE INTO orders (id) VALUES (1)", "MySQL"), + ("INSERT INTO orders (id) VALUES (1) ON DUPLICATE KEY UPDATE note = 'b'", "MySQL"), + ("UPSERT INTO orders (id, note) VALUES (1, 'a')", "CockroachDB"), + ("INSERT OR REPLACE INTO orders (id) VALUES (1)", "SQLite"), + ("UPDATE statistics SET hits = hits + 1 WHERE id = 1", "PostgreSQL"), + ("BEGIN BATCH INSERT INTO ks.t (id) VALUES (1); UPDATE ks.t SET v = 'b' WHERE id = 2; APPLY BATCH", "Cassandra"), + ("REPLACE orders VALUES (1)", "MySQL"), + ("SELECT * FROM pg_settings WHERE name = 'search_path'", "PostgreSQL"), + ("ALTER TABLE shop.orders UPDATE note = 'a' WHERE id = 1", "ClickHouse"), + ("ALTER TABLE orders ON CLUSTER main DELETE WHERE id = 1", "ClickHouse"), + ]) + func rowWorkIsData(sql: String, engine: String) { + #expect(Self.isData(sql, engine)) + } + + @Test("A definition, a grant, a session or transaction statement and a call are not", arguments: [ + ("GRANT SELECT ON orders TO app", "PostgreSQL"), + ("REVOKE ALL ON orders FROM app", "PostgreSQL"), + ("ALTER ROLE app_user WITH SUPERUSER", "PostgreSQL"), + ("SET session_replication_role = replica", "PostgreSQL"), + ("RESET ALL", "PostgreSQL"), + ("CREATE TABLE notes (id int)", "PostgreSQL"), + ("ALTER TABLE orders ADD COLUMN note text", "PostgreSQL"), + ("COMMENT ON TABLE orders IS 'x'", "PostgreSQL"), + ("BEGIN", "PostgreSQL"), + ("COMMIT", "PostgreSQL"), + ("CALL purge_orders()", "PostgreSQL"), + ("LOCK TABLE orders", "PostgreSQL"), + ("VACUUM orders", "PostgreSQL"), + ("ANALYZE orders", "PostgreSQL"), + ("REFRESH MATERIALIZED VIEW totals", "PostgreSQL"), + ("LISTEN orders_changed", "PostgreSQL"), + ("PREPARE purge AS DELETE FROM orders WHERE id = $1", "PostgreSQL"), + ("SELECT set_config('role', 'admin', false)", "PostgreSQL"), + ("SELECT pg_terminate_backend(42)", "PostgreSQL"), + ("SELECT pg_advisory_lock(1)", "PostgreSQL"), + ("SELECT * INTO orders_copy FROM orders", "PostgreSQL"), + ("EXPLAIN ANALYZE CREATE TABLE copy AS SELECT * FROM orders", "PostgreSQL"), + ("WITH x AS (SELECT 1) SELECT * INTO copy FROM x", "PostgreSQL"), + ("SELECT 1; GRANT ALL ON orders TO app", "PostgreSQL"), + ("USE shop", "MySQL"), + ("SET @limit = 10", "MySQL"), + ("SELECT COUNT(*) INTO @total FROM orders", "MySQL"), + ("LOCK TABLES orders WRITE", "MySQL"), + ("UPDATE STATISTICS dbo.orders", "SQL Server"), + ("INSERT INTO dbo.orders EXEC dbo.load_orders", "SQL Server"), + ("EXEC sp_configure 'show advanced options', 1", "SQL Server"), + ("PRAGMA foreign_keys = OFF", "SQLite"), + ("ALTER SESSION SET NLS_DATE_FORMAT = 'YYYY-MM-DD'", "Oracle"), + ("BEGIN purge_orders; END;", "Oracle"), + ("OPTIMIZE TABLE orders FINAL", "ClickHouse"), + ("SYSTEM FLUSH LOGS", "ClickHouse"), + ("DEFINE TABLE person SCHEMAFULL", "SurrealDB"), + ("USE ks", "Cassandra"), + ("GRANT SELECT ON ks.t TO app", "Cassandra"), + ("REPLACE VIEW totals AS SELECT 1", "Teradata"), + ("ALTER TABLE orders UPDATE note = 'a' WHERE id = 1, DROP COLUMN note", "ClickHouse"), + ("ALTER TABLE orders ADD COLUMN note String", "ClickHouse"), + ("ALTER TABLE orders UPDATE note = 'a' WHERE id = 1", "MySQL"), + ]) + func schemaPrivilegeAndSessionAreNot(sql: String, engine: String) { + #expect(!Self.isData(sql, engine)) + } + + @Test("A row change on a table the server acts on is not", arguments: [ + ("UPDATE pg_settings SET setting = 'replica' WHERE name = 'session_replication_role'", "PostgreSQL"), + ("UPDATE pg_catalog.pg_authid SET rolsuper = true WHERE rolname = 'app'", "PostgreSQL"), + ("INSERT INTO \"pg_catalog\".\"pg_authid\" (rolname) VALUES ('x')", "PostgreSQL"), + ("UPDATE sys_settings SET setting = 'x' WHERE name = 'search_path'", "KingbaseES"), + ("UPSERT INTO system.users (username) VALUES ('x')", "CockroachDB"), + ("UPDATE mysql.user SET Super_priv = 'Y' WHERE User = 'app'", "MySQL"), + ("UPDATE `performance_schema`.`setup_consumers` SET ENABLED = 'NO'", "MariaDB"), + ("UPDATE orders SET note = set_config('role', 'admin', false) WHERE id = 1", "PostgreSQL"), + ("INSERT INTO log SELECT pg_terminate_backend(pid) FROM pg_stat_activity", "PostgreSQL"), + ("UPDATE U&\"pg\\005fsettings\" SET setting = 'x' WHERE name = 'search_path'", "PostgreSQL"), + ("INSERT INTO msdb.dbo.sysjobsteps (job_id, command) VALUES (1, 'x')", "SQL Server"), + ("UPDATE system.help SET text = 'x'", "Oracle"), + ]) + func systemRelationsAreNot(sql: String, engine: String) { + #expect(!Self.isData(sql, engine)) + } + + @Test("A scope in the engine's own schemas is a system scope, in any case, and only on that engine") + func systemScopesFollowTheEngine() { + #expect(SQLStatementClassifier.isSystemScope(database: "mysql", schema: nil, databaseTypeId: "MariaDB")) + #expect(SQLStatementClassifier.isSystemScope(database: "MSDB", schema: "dbo", databaseTypeId: "SQL Server")) + #expect(SQLStatementClassifier.isSystemScope(database: "app", schema: "pg_catalog", databaseTypeId: "PostgreSQL")) + #expect(!SQLStatementClassifier.isSystemScope(database: "mysql", schema: nil, databaseTypeId: "PostgreSQL")) + #expect(!SQLStatementClassifier.isSystemScope(database: "shop", schema: nil, databaseTypeId: "MySQL")) + #expect(!SQLStatementClassifier.isSystemScope(database: "ORCL", schema: "SYSTEM", databaseTypeId: "Oracle")) + #expect(SQLStatementClassifier.isSystemScope(database: "ORCL", schema: "sys", databaseTypeId: "Oracle")) + } + + @Test("A call that happens to start like a catalog name is not a catalog relation") + func catalogNamedCallIsData() { + #expect(Self.isData("UPDATE orders SET pid = pg_backend_pid() WHERE id = 1")) + } + + @Test("A request form with no data reading is refused, and its own reading decides") + func requestFormsAnswerForThemselves() { + let readings = SQLLexicalReadings.resolve(databaseTypeId: "PostgreSQL", declared: nil, session: nil) + let tagged: SQLStatementClassifier.RequestClassification = { statement, _ in + statement.hasPrefix("REQ ") ? .write : nil + } + #expect(!SQLStatementClassifier.isDataStatement( + "REQ CreateTable", databaseTypeId: "PostgreSQL", readings: readings, request: tagged + )) + #expect(SQLStatementClassifier.isDataStatement( + "REQ PutItem", databaseTypeId: "PostgreSQL", readings: readings, request: tagged, + requestIsData: { statement, _ in statement.hasPrefix("REQ ") ? statement.hasSuffix("PutItem") : nil } + )) + } +} diff --git a/apple/Packages/TableProCore/Tests/TableProSQLGrammarTests/SQLReadOnlyFunctionCallsTests.swift b/apple/Packages/TableProCore/Tests/TableProSQLGrammarTests/SQLReadOnlyFunctionCallsTests.swift new file mode 100644 index 0000000000..2a39159880 --- /dev/null +++ b/apple/Packages/TableProCore/Tests/TableProSQLGrammarTests/SQLReadOnlyFunctionCallsTests.swift @@ -0,0 +1,37 @@ +import Foundation +import TableProSQLGrammar +import Testing + +struct SQLReadOnlyFunctionCallsTests { + private static func callsUnlisted(_ sql: String, _ engine: String, types: Set = []) -> Bool { + let readings = SQLLexicalReadings.resolve(databaseTypeId: engine, declared: nil, session: nil) + return SQLReadOnlyFunctionCalls.callsUnlistedFunction(sql, databaseTypeId: engine, readings: readings, typeNames: types) + } + + @Test("A user function, a qualified or quoted name and a call in a later statement are unlisted", arguments: [ + "SELECT purge_orders()", + "SELECT app.count(id) FROM orders", + "SELECT `purge_orders`() FROM orders", + "SELECT 1;\nSELECT purge_orders()", + ]) + func userCallsAreUnlisted(sql: String) { + #expect(Self.callsUnlisted(sql, "MySQL")) + } + + @Test("Built-ins, a plain EXPLAIN and the engine's own types are listed") + func builtinsAreListed() { + #expect(!Self.callsUnlisted("SELECT COUNT(*), LOWER(name), DATE_FORMAT(at, '%Y') FROM orders", "MySQL")) + #expect(!Self.callsUnlisted("EXPLAIN SELECT purge_orders()", "PostgreSQL")) + #expect(!Self.callsUnlisted("SELECT total::numeric(10, 2) FROM orders", "PostgreSQL", types: ["numeric"])) + #expect(Self.callsUnlisted("SELECT total::numeric(10, 2) FROM orders", "PostgreSQL")) + } + + @Test("The engines whose functions a query can call to write are the type ids the apps use") + func writingEnginesAreTypeIds() { + #expect(SQLReadOnlyFunctionCalls.queryFunctionsCanWrite == [ + "Oracle", "Dameng", "MySQL", "MariaDB", "OceanBase", "PostgreSQL", "CockroachDB", "PGlite", "KingbaseES", + ]) + #expect(SQLReadOnlyFunctionCalls.builtins(forDatabaseTypeId: "Oracle").contains("NVL")) + #expect(!SQLReadOnlyFunctionCalls.builtins(forDatabaseTypeId: "MySQL").contains("NVL")) + } +} diff --git a/apple/Packages/TableProCore/Tests/TableProSQLGrammarTests/SQLStatementClassifierTests.swift b/apple/Packages/TableProCore/Tests/TableProSQLGrammarTests/SQLStatementClassifierTests.swift index 215e428eef..aff53133bc 100644 --- a/apple/Packages/TableProCore/Tests/TableProSQLGrammarTests/SQLStatementClassifierTests.swift +++ b/apple/Packages/TableProCore/Tests/TableProSQLGrammarTests/SQLStatementClassifierTests.swift @@ -53,6 +53,15 @@ struct SQLStatementClassifierTests { #expect(Self.classify("SELECT * FROM `payroll.csv`", "DuckDB").reachesFilesystemOrExecutesCode) } + @Test("INSERT OVERWRITE empties the table before it inserts, and into a directory writes files") + func insertOverwriteIsDestructive() { + #expect(Self.tier("INSERT OVERWRITE INTO orders SELECT * FROM staged", "Snowflake") == .destructive) + #expect(Self.tier("INSERT OVERWRITE TABLE orders SELECT * FROM staged", "Snowflake") == .destructive) + #expect(Self.classify("INSERT OVERWRITE DIRECTORY '/tmp/out' SELECT * FROM orders", "Snowflake") + .reachesFilesystemOrExecutesCode) + #expect(Self.tier("INSERT INTO orders (overwrite) VALUES (1)", "Snowflake") == .write) + } + @Test("T-SQL calls the procedure a batch opens with when no statement begins with that word", arguments: [ "SHOW 'x'", "HELP 'x'", "INFO 'x'", "show tables", "EXPLAIN SELECT 1", "DESCRIBE orders", ]) diff --git a/apple/TablePro/Core/AI/Chat/ChatToolContext.swift b/apple/TablePro/Core/AI/Chat/ChatToolContext.swift index 8724ff8fa4..b5ea5bf614 100644 --- a/apple/TablePro/Core/AI/Chat/ChatToolContext.swift +++ b/apple/TablePro/Core/AI/Chat/ChatToolContext.swift @@ -5,15 +5,8 @@ import Foundation -/// Per-call context passed to `ChatTool.execute(input:context:)`. Carries the session's connection, -/// the shared `MCPConnectionBridge` actor that does the underlying database work, and the -/// `MCPAuthPolicy` that authorizes the call and gates writes through the connection's safe-mode -/// dialog. -/// -/// `connectionId` is the session's own connection and is the only connection a tool may act on. A -/// tool never reads `connection_id` out of the model's input: that is what let an approval computed -/// against one connection authorize a statement executed against another. `ChatToolTarget` is the -/// one door, and it is why this type no longer carries a resolver of its own. +// `connectionId` is the only connection a tool may act on: a tool never reads `connection_id` from the model's input, +// which once let an approval for one connection run a statement on another. `ChatToolTarget` is the one door. struct ChatToolContext: Sendable { typealias PolicyLookup = @Sendable (UUID) async -> AIConnectionPolicy? @@ -21,18 +14,14 @@ struct ChatToolContext: Sendable { let bridge: MCPConnectionBridge let authPolicy: MCPAuthPolicy - /// The agent session this call belongs to. Only the audit entry for an outside MCP server reads - /// it, and it reads it because "which conversation sent this" is the first question asked of a - /// call that left the machine. + // Read only by an outside MCP server's audit entry, where the conversation that sent a call is the first question. let sessionId: UUID? - /// Whether the user answered this call's own approval card with Run or Always. - /// - /// Only an explicit answer pre-clears the execution gate's confirmation, because only then has - /// the user been shown this statement and this connection. A grant carried over from - /// `aiAlwaysAllowedTools` is consent for the tool, not for the statement, so the gate still asks - /// and still shows the SQL. Every chat tool used to pass `.confirmationPreCleared` - /// unconditionally, which skipped the only screen naming what was about to run and where. + // The mode the tool was resolved in, which also limits what it may run: Edit runs data statements only. + let chatMode: AIChatMode + + // Only a Run or Always on this call's own card pre-clears the gate's confirmation: only then was the user shown + // this statement on this connection. A grant from `aiAlwaysAllowedTools` is consent to the tool, not the statement. let approvalWasExplicit: Bool private let policyLookup: PolicyLookup @@ -41,6 +30,7 @@ struct ChatToolContext: Sendable { connectionId: UUID?, bridge: MCPConnectionBridge, authPolicy: MCPAuthPolicy, + chatMode: AIChatMode, sessionId: UUID? = nil, approvalWasExplicit: Bool = false, policyLookup: @escaping PolicyLookup = ChatToolContext.savedPolicy @@ -48,27 +38,25 @@ struct ChatToolContext: Sendable { self.connectionId = connectionId self.bridge = bridge self.authPolicy = authPolicy + self.chatMode = chatMode self.sessionId = sessionId self.approvalWasExplicit = approvalWasExplicit self.policyLookup = policyLookup } - /// The same context bound to one block's approval outcome. - /// - /// One context is built per streaming round and shared by every block in it, including blocks - /// that run concurrently, so provenance cannot live on the shared value. + // One context serves a round's blocks, some running at once, so each block's approval is bound to a copy. func carrying(approvalWasExplicit: Bool) -> ChatToolContext { ChatToolContext( connectionId: connectionId, bridge: bridge, authPolicy: authPolicy, + chatMode: chatMode, sessionId: sessionId, approvalWasExplicit: approvalWasExplicit, policyLookup: policyLookup ) } - /// This connection's AI Policy, or nil when there is no such connection. func aiPolicy(for connectionId: UUID) async -> AIConnectionPolicy? { await policyLookup(connectionId) } @@ -84,7 +72,6 @@ struct ChatToolContext: Sendable { } } - /// The write capabilities this call may claim, which is where approval provenance is spent. var writeCapabilities: CallerCapabilities { approvalWasExplicit ? [.mayWrite, .mayRunDestructive, .confirmationPreCleared] diff --git a/apple/TablePro/Core/AI/Chat/Tools/ExecuteQueryChatTool.swift b/apple/TablePro/Core/AI/Chat/Tools/ExecuteQueryChatTool.swift index a80934bf33..d2a5ee1185 100644 --- a/apple/TablePro/Core/AI/Chat/Tools/ExecuteQueryChatTool.swift +++ b/apple/TablePro/Core/AI/Chat/Tools/ExecuteQueryChatTool.swift @@ -61,8 +61,8 @@ struct ExecuteQueryChatTool: ChatTool { takingScriptsOn: meta.databaseType ) - // The refusals MCP makes, from the same gate. AI Policy, checked above, governs the assistant, so the - // External Clients level is not asked. + // The refusals MCP makes, from the same gate, plus Edit's. AI Policy, checked above, governs the assistant, so + // the External Clients level is not asked. let classification: QueryClassification do { classification = try ExternalStatementGate.classify( @@ -76,7 +76,8 @@ struct ExecuteQueryChatTool: ChatTool { allowsMultiStatement: capabilities.contains(.mayRunMultiStatement), destructiveAlternative: String( localized: "In Agent mode, use confirm_destructive_operation with the explicit confirmation phrase." - ) + ), + allowsOnlyDataStatements: context.chatMode != .agent ) ) } catch let refusal as ExternalStatementGateError { @@ -98,6 +99,13 @@ struct ExecuteQueryChatTool: ChatTool { database: database, schema: schema ) + // A table named without a schema lands in the scope's, and the engine's own schemas hold its grant, setup and + // settings tables. + if context.chatMode != .agent, classification.tier != .safe, SQLStatementClassifier.isSystemScope( + database: scope.database, schema: scope.schema, databaseTypeId: meta.databaseType.rawValue + ) { + return ChatToolResult(content: ExternalStatementGate.dataStatementRefusal, isError: true) + } let planned = try await context.bridge.plannedScript(scope: scope, query: query, maxRows: maxRows) let operation = try await context.authPolicy.checkSafeModeDialog( operation: PendingOperation( diff --git a/apple/TablePro/Core/Coordinators/PaginationCoordinator.swift b/apple/TablePro/Core/Coordinators/PaginationCoordinator.swift index d510cdd1b8..5d1dbde6ac 100644 --- a/apple/TablePro/Core/Coordinators/PaginationCoordinator.swift +++ b/apple/TablePro/Core/Coordinators/PaginationCoordinator.swift @@ -173,7 +173,7 @@ final class PaginationCoordinator: ObservableObject { columns: queryColumns.columns, columnTypes: queryColumns.columnTypes ) let safeModeIsReadOnly = parent.runsAtReadOnly - let gate = browseFilters == nil && parent.rawFilterNeedsReadOnlyGate(filters, tabId: tabId) + let gate = browseFilters == nil && parent.rawFilterNeedsReadOnlyGate(filters) ? countSQL.map { parent.rawFilterRequest(sql: $0, canPrompt: true) } : nil @@ -190,7 +190,6 @@ final class PaginationCoordinator: ObservableObject { var refusal: ExecutionGateError? if let gate { refusal = await parent.executionGate.authorize(gate).denialError - if refusal == nil { parent.approveReadOnlyRawFilter(filters, tabId: tabId) } } let outcome: Result if case .cancelledByUser? = refusal { @@ -345,6 +344,25 @@ final class PaginationCoordinator: ObservableObject { guard let self, !parent.isTearingDown else { return } do { + // The level may have changed since the statement first ran, so the gate reads it again, as a sort's rerun does. + let decision = await parent.executionGate.authorize(OperationRequest( + connectionId: scope.connectionId, + databaseType: parent.connection.type, + sql: baseQuery, + kind: .readQuery, + caller: .userInterface, + capabilities: .interactiveUser, + operationDescription: String(localized: "Fetch All"), + scope: scope + )) + if case .cancelledByUser? = decision.denialError { + await MainActor.run { [weak self] in + self?.parent.tabManager.mutate(tabId: tabId) { $0.pagination.isLoadingMore = false } + } + return + } + if let denial = decision.denialError { throw denial } + let start = CFAbsoluteTimeGetCurrent() progressLog.info("[fetchAll] executing full query: \(baseQuery.prefix(100), privacy: .private)") let result = try await parent.withExecutionDriver( diff --git a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Helpers.swift b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Helpers.swift index b188b2ff03..55bb572c96 100644 --- a/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Helpers.swift +++ b/apple/TablePro/Core/Coordinators/QueryExecutionCoordinator+Helpers.swift @@ -767,7 +767,7 @@ extension QueryExecutionCoordinator { filters: filters, logicMode: logicMode, safeModeIsReadOnly: parent.runsAtReadOnly, - gate: parent.rawFilterNeedsReadOnlyGate(filters, tabId: tabId) + gate: parent.rawFilterNeedsReadOnlyGate(filters) ? sql.map { parent.rawFilterRequest(sql: $0, canPrompt: false) } : nil ) @@ -776,12 +776,8 @@ extension QueryExecutionCoordinator { // Nobody asked for this count, so nothing may ask the user about it: a refusal leaves the total unknown. var plan = prepared.plan - if let count = prepared.count, let gate = count.gate { - if await parent.executionGate.authorize(gate).isAuthorized { - parent.approveReadOnlyRawFilter(count.filters, tabId: tabId) - } else { - plan = .clear - } + if let count = prepared.count, let gate = count.gate, !(await parent.executionGate.authorize(gate).isAuthorized) { + plan = .clear } let outcome = await Self.rowCountOutcome( diff --git a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+CuratedDefaults.swift b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+CuratedDefaults.swift index bad9d1bcba..8f2bbbe41e 100644 --- a/apple/TablePro/Core/Plugins/PluginMetadataRegistry+CuratedDefaults.swift +++ b/apple/TablePro/Core/Plugins/PluginMetadataRegistry+CuratedDefaults.swift @@ -5,6 +5,7 @@ import Foundation import TableProPluginKit +import TableProSQLGrammar import TableProSQLVocabulary import TableProUtilities @@ -20,17 +21,12 @@ extension PluginMetadataRegistry { // their driver creates is a SQLite database. static let sqliteFileExtensions = ["db", "db3", "s3db", "sl3", "sqlite", "sqlite3", "sqlitedb"] - // Engines where a function a SELECT calls can change data: an autonomous-transaction function on Oracle and Dameng, - // a stored function on MySQL, MariaDB and OceanBase, PL/pgSQL on the PostgreSQL family. Read-Only asks before such a - // call only when the live driver cannot run the statement in the engine's read-only mode. MySQL and MariaDB are - // listed by type because an OceanBase server answers as MySQL, so only the driver's own bit tells them apart. TiDB, - // StarRocks and Databend have no stored function or UDF that writes; SQL Server, Snowflake, BigQuery, Trino and - // Redshift refuse a write from a function a query calls; ClickHouse, the SQLite engines and Cassandra have none. - static let queryFunctionsCanWrite: Set = [ - .oracle, .dameng, - .mysql, .mariadb, .oceanbase, - .postgresql, .cockroachdb, .pglite, .kingbasees, - ] + // Engines where a function a SELECT calls can change data. Read-Only refuses a call off the built-in list only when + // the live driver cannot run the statement in the engine's read-only mode. MySQL and MariaDB are listed by type + // because an OceanBase server answers as MySQL, so only the driver's own bit tells them apart. + static let queryFunctionsCanWrite = Set( + SQLReadOnlyFunctionCalls.queryFunctionsCanWrite.map(DatabaseType.init(rawValue:)) + ) // swiftlint:disable:next function_body_length static func curatedDefaults() -> [(typeId: String, snapshot: PluginMetadataSnapshot)] { diff --git a/apple/TablePro/Core/Services/Execution/DefaultExecutionGate.swift b/apple/TablePro/Core/Services/Execution/DefaultExecutionGate.swift index 4ce9545812..a27dd9a569 100644 --- a/apple/TablePro/Core/Services/Execution/DefaultExecutionGate.swift +++ b/apple/TablePro/Core/Services/Execution/DefaultExecutionGate.swift @@ -140,40 +140,24 @@ internal actor DefaultExecutionGate: ExecutionGate { } // The classifier tiers `SELECT purge_orders()` as a read. Where the driver cannot run it in the engine's read-only - // mode and a function on the engine can write, a call off the built-in list is asked about, or refused when a - // profile or the engine floor holds the level, since an answer there would let a write past them. Nil runs it. + // mode and a function on the engine can write, a call off the built-in list is one the gate cannot tell from a + // write, so Read-Only refuses it like one, whatever the caller was cleared for. Nil runs it. private func readOnlyFunctionRefusal(_ request: OperationRequest, sql: String) async -> OperationDecision? { let policy = await readOnlyFunctionPolicyResolver(request.connectionId, request.databaseType) guard policy.functionsCanWrite, ReadOnlyFunctionCalls.callsUnlistedFunction(sql, databaseType: request.databaseType) else { return nil } - if policy.levelIsHeld { + guard let level = policy.levelThatRunsIt else { return .denied(reason: String( localized: "Cannot run this query: it calls a function that can change data, and Safe Mode is held at Read-Only for this connection." )) } - let caps = request.capabilities - guard !caps.contains(.preCleared), !caps.contains(.confirmationPreCleared) else { return nil } - if caps.contains(.cannotPrompt) { - return .denied(reason: String(localized: "Confirmation is required for this operation")) - } - let confirmed = await confirming.confirm( - OperationConfirmationRequest( - sql: request.sql, - operationDescription: String(localized: "This query calls a function that can change data"), - connectionId: request.connectionId, - connectionName: await connectionNameResolver(request.connectionId), - databaseType: request.databaseType, - caller: request.caller, - isDestructive: false, - scope: request.scope, - statements: request.statements - ) - ) - guard confirmed else { - return .denied(reason: String(localized: "Operation cancelled by user"), cause: .cancelledByUser) - } - return nil + return .denied(reason: String( + format: String( + localized: "Cannot run this query at Read-Only: it calls a function that can change data. Switch Safe Mode to %@ to run it." + ), + level.displayName + )) } private func resolveEffectiveWrite(_ request: OperationRequest, tier: QueryTier?) async -> Bool { diff --git a/apple/TablePro/Core/Services/Execution/ExecutionGateProvider.swift b/apple/TablePro/Core/Services/Execution/ExecutionGateProvider.swift index d2afb9b51e..c6f8dac2ca 100644 --- a/apple/TablePro/Core/Services/Execution/ExecutionGateProvider.swift +++ b/apple/TablePro/Core/Services/Execution/ExecutionGateProvider.swift @@ -48,12 +48,15 @@ internal enum ExecutionGateProvider { case .stored(let stored): (nil, stored) case .unknown: (nil, nil) } - let managedMinimum = ManagedPolicyResolver.minimumSafeModeLevel(policy: ManagedPolicyReader.shared) + let floor: SafeModeLevel? = if let connection { + AgentModeSafeModeFloor.effectiveFloor(for: connection)?.level + } else { + ManagedPolicyResolver.minimumSafeModeLevel(policy: ManagedPolicyReader.shared) + } return ReadOnlyFunctionPolicy( functionsCanWrite: liveDriver?.enforcesReadOnlyMode != true && PluginMetadataRegistry.queryFunctionsCanWrite.contains(databaseType), - levelIsHeld: managedMinimum?.blocksAllWrites == true - || connection?.safeModeFloor?.level.blocksAllWrites == true + floor: floor ) } diff --git a/apple/TablePro/Core/Services/Execution/ExternalStatementGate.swift b/apple/TablePro/Core/Services/Execution/ExternalStatementGate.swift index 04b4747b0c..8c7380dae9 100644 --- a/apple/TablePro/Core/Services/Execution/ExternalStatementGate.swift +++ b/apple/TablePro/Core/Services/Execution/ExternalStatementGate.swift @@ -32,9 +32,10 @@ internal enum ExternalStatementGate { internal let loadsExtensions: Bool internal let allowsDestructive: Bool internal let allowsMultiStatement: Bool - /// What this transport offers instead, appended to the destructive refusal. MCP has a tool - /// for it; AppleScript confirms interactively and never reaches the refusal. + // Appended to the destructive refusal: MCP has a tool for it, AppleScript confirms and never reaches it. internal let destructiveAlternative: String? + // The assistant's Edit mode: queries and row changes, no schema, privilege, session or transaction statement. + internal let allowsOnlyDataStatements: Bool internal init( sql: String, @@ -44,7 +45,8 @@ internal enum ExternalStatementGate { loadsExtensions: Bool, allowsDestructive: Bool, allowsMultiStatement: Bool = false, - destructiveAlternative: String? = nil + destructiveAlternative: String? = nil, + allowsOnlyDataStatements: Bool = false ) { self.sql = sql self.connectionId = connectionId @@ -54,6 +56,7 @@ internal enum ExternalStatementGate { self.allowsDestructive = allowsDestructive self.allowsMultiStatement = allowsMultiStatement self.destructiveAlternative = destructiveAlternative + self.allowsOnlyDataStatements = allowsOnlyDataStatements } } @@ -102,6 +105,11 @@ internal enum ExternalStatementGate { ) } + if statement.allowsOnlyDataStatements, + QueryClassifier.isSQLDataStatement(statement.sql, databaseType: statement.databaseType) == false { + throw ExternalStatementGateError.denied(dataStatementRefusal) + } + return classification } @@ -120,6 +128,14 @@ internal enum ExternalStatementGate { localized: "This statement is destructive, like DROP, TRUNCATE or a DELETE with no WHERE." ) + internal static let dataStatementRefusal = String( + localized: """ + Edit mode runs only queries and data changes, such as SELECT, INSERT, UPDATE, DELETE and MERGE. \ + A schema, privilege, session or transaction statement, or a change to the database's own tables, \ + needs Agent mode, or run it yourself in a query tab. + """ + ) + internal static let notDestructiveRefusal = String( localized: """ This tool runs only destructive statements, like DROP, TRUNCATE or a DELETE with no WHERE. \ diff --git a/apple/TablePro/Core/Services/Execution/ReadOnlyFunctionCalls.swift b/apple/TablePro/Core/Services/Execution/ReadOnlyFunctionCalls.swift index 9763858675..4b78874bf2 100644 --- a/apple/TablePro/Core/Services/Execution/ReadOnlyFunctionCalls.swift +++ b/apple/TablePro/Core/Services/Execution/ReadOnlyFunctionCalls.swift @@ -11,346 +11,27 @@ import TableProSQLGrammar internal struct ReadOnlyFunctionPolicy: Sendable, Equatable { // The live driver cannot run a statement in the engine's read-only mode, and a function on this engine can write. var functionsCanWrite = false - // A configuration profile or the connection's floor holds it at Read-Only, so no answer may let a write through. - var levelIsHeld = false + // What holds the level up: a read-only engine or file, a configuration profile, Agent mode. + var floor: SafeModeLevel? + + var levelThatRunsIt: SafeModeLevel? { + SafeModeFloor.levelThatWrites(above: floor) + } } -// The one place that says which calls Read-Only lets through without asking, on an engine whose functions can write and -// a driver that cannot hold the statement to the engine's read-only mode. A built-in here reads only: nothing that -// writes, locks, sleeps, waits or reaches a file (GET_LOCK, SLEEP, LOAD_FILE, NEXTVAL, SETVAL, a DBMS_ package) is listed. -// A qualified or quoted name, a name the scanner cannot read, and anything else may be a function the user wrote. A -// call written without parentheses, which Oracle and Dameng accept for a function with no arguments, cannot be told -// from a column and is not seen. +// The Mac's reading of `SQLReadOnlyFunctionCalls`, with the engine's types from its plugin's dialect. internal enum ReadOnlyFunctionCalls { - static let commonBuiltins: Set = [ - "COUNT", "SUM", "AVG", "MIN", "MAX", "STDDEV", "STDDEV_POP", "STDDEV_SAMP", "VARIANCE", "VAR_POP", "VAR_SAMP", - "CORR", "COVAR_POP", "COVAR_SAMP", "GROUPING", - "ROW_NUMBER", "RANK", "DENSE_RANK", "PERCENT_RANK", "CUME_DIST", "NTILE", "LAG", "LEAD", "FIRST_VALUE", - "LAST_VALUE", "NTH_VALUE", - "COALESCE", "NULLIF", "GREATEST", "LEAST", "CAST", "EXTRACT", - "LOWER", "UPPER", "LENGTH", "TRIM", "LTRIM", "RTRIM", "SUBSTR", "SUBSTRING", "REPLACE", "CONCAT", "LPAD", "RPAD", - "REVERSE", "ASCII", "REGEXP_REPLACE", "REGEXP_SUBSTR", "REGEXP_INSTR", "REGEXP_LIKE", "POSITION", "TRANSLATE", - "ABS", "CEIL", "CEILING", "FLOOR", "ROUND", "MOD", "POWER", "SQRT", "EXP", "LN", "LOG", "SIGN", "SIN", "COS", - "TAN", "ASIN", "ACOS", "ATAN", "ATAN2", - "CURRENT_DATE", "CURRENT_TIME", "CURRENT_TIMESTAMP", "LOCALTIMESTAMP", - "JSON_VALUE", "JSON_QUERY", "JSON_OBJECT", "JSON_ARRAY", "JSON_TABLE", - ] - - // Oracle and Dameng. - static let oracleBuiltins: Set = [ - "NVL", "NVL2", "DECODE", "LNNVL", "NANVL", "LISTAGG", "MEDIAN", "RATIO_TO_REPORT", - "TO_CHAR", "TO_DATE", "TO_NUMBER", "TO_TIMESTAMP", "TO_TIMESTAMP_TZ", "TO_DSINTERVAL", "TO_YMINTERVAL", - "NUMTODSINTERVAL", "NUMTOYMINTERVAL", "TO_NCHAR", "HEXTORAW", "RAWTOHEX", "ROWIDTOCHAR", "CONVERT", - "INSTR", "INSTRB", "LENGTHB", "SUBSTRB", "INITCAP", "CHR", "SOUNDEX", "REGEXP_COUNT", - "TRUNC", "BITAND", "WIDTH_BUCKET", "REMAINDER", - "ADD_MONTHS", "MONTHS_BETWEEN", "LAST_DAY", "NEXT_DAY", "NEW_TIME", "FROM_TZ", "TZ_OFFSET", "SYS_EXTRACT_UTC", - "SYS_GUID", "SYS_CONTEXT", "USERENV", "ORA_HASH", "STANDARD_HASH", "XMLTABLE", - ] - - // MySQL, MariaDB and the servers that answer as MySQL. - static let mysqlBuiltins: Set = [ - "IF", "IFNULL", "ISNULL", "GROUP_CONCAT", "JSON_ARRAYAGG", "JSON_OBJECTAGG", "BIT_AND", "BIT_OR", "BIT_XOR", - "ANY_VALUE", "CONVERT", - "CONCAT_WS", "CHAR_LENGTH", "CHARACTER_LENGTH", "OCTET_LENGTH", "BIT_LENGTH", "LCASE", "UCASE", "LEFT", "RIGHT", - "MID", "LOCATE", "INSTR", "FIND_IN_SET", "FIELD", "ELT", "STRCMP", "SUBSTRING_INDEX", "REPEAT", "SPACE", "CHAR", - "FORMAT", "QUOTE", "SOUNDEX", "HEX", "UNHEX", "BIN", "OCT", "CONV", - "TRUNCATE", "POW", "LOG2", "LOG10", "COT", "DEGREES", "RADIANS", "PI", "RAND", "CRC32", - "NOW", "SYSDATE", "CURDATE", "CURTIME", "LOCALTIME", "UTC_DATE", "UTC_TIME", "UTC_TIMESTAMP", "DATE", "TIME", - "TIMESTAMP", "YEAR", "QUARTER", "MONTH", "WEEK", "WEEKDAY", "WEEKOFYEAR", "YEARWEEK", "DAY", "DAYOFMONTH", - "DAYOFWEEK", "DAYOFYEAR", "DAYNAME", "MONTHNAME", "HOUR", "MINUTE", "SECOND", "MICROSECOND", "DATE_FORMAT", - "TIME_FORMAT", "STR_TO_DATE", "DATE_ADD", "DATE_SUB", "ADDDATE", "SUBDATE", "ADDTIME", "SUBTIME", "DATEDIFF", - "TIMEDIFF", "TIMESTAMPDIFF", "TIMESTAMPADD", "UNIX_TIMESTAMP", "FROM_UNIXTIME", "FROM_DAYS", "TO_DAYS", - "TO_SECONDS", "SEC_TO_TIME", "TIME_TO_SEC", "MAKEDATE", "MAKETIME", "PERIOD_ADD", "PERIOD_DIFF", "LAST_DAY", - "CONVERT_TZ", - "JSON_EXTRACT", "JSON_UNQUOTE", "JSON_CONTAINS", "JSON_CONTAINS_PATH", "JSON_KEYS", "JSON_LENGTH", "JSON_TYPE", - "JSON_VALID", "JSON_SEARCH", "JSON_DEPTH", - "MD5", "SHA", "SHA1", "SHA2", "UUID", "UUID_SHORT", - "DATABASE", "SCHEMA", "USER", "CURRENT_USER", "SESSION_USER", "SYSTEM_USER", "VERSION", "CONNECTION_ID", - ] - - // An older PostgreSQL-family driver without the mode. - static let postgresBuiltins: Set = [ - "NOW", "TO_CHAR", "TO_DATE", "TO_NUMBER", "TO_TIMESTAMP", "DATE_TRUNC", "DATE_PART", "AGE", "TRUNC", "LEFT", - "RIGHT", "CHAR_LENGTH", "CHARACTER_LENGTH", "OCTET_LENGTH", "SPLIT_PART", "STRING_AGG", "ARRAY_AGG", - "ARRAY_LENGTH", "INITCAP", "CHR", "MD5", "FORMAT", "CONCAT_WS", "TO_JSON", "TO_JSONB", "JSON_AGG", "JSONB_AGG", - "JSON_BUILD_OBJECT", "JSONB_BUILD_OBJECT", "JSON_BUILD_ARRAY", "JSONB_BUILD_ARRAY", "GENERATE_SERIES", - "BOOL_AND", "BOOL_OR", "EVERY", "POW", "LOG10", "PI", "RANDOM", - ] - - private static let oracleFamily: Set = [.oracle, .dameng] - private static let mysqlFamily: Set = [.mysql, .mariadb, .oceanbase, .tidb, .starrocks, .databend] - private static let postgresFamily: Set = [.postgresql, .cockroachdb, .pglite, .kingbasees, .redshift] - - private static let oracleCalls = commonBuiltins.union(oracleBuiltins) - private static let mysqlCalls = commonBuiltins.union(mysqlBuiltins) - private static let postgresCalls = commonBuiltins.union(postgresBuiltins) - private static let anyCalls = commonBuiltins.union(oracleBuiltins).union(mysqlBuiltins).union(postgresBuiltins) - static func builtins(for databaseType: DatabaseType) -> Set { - if oracleFamily.contains(databaseType) { return oracleCalls } - if mysqlFamily.contains(databaseType) { return mysqlCalls } - if postgresFamily.contains(databaseType) { return postgresCalls } - return anyCalls - } - - // Reserved in Oracle, MySQL and PostgreSQL alike, so no function a query calls can carry the bare name. - static let reservedWords: Set = [ - "SELECT", "FROM", "WHERE", "AND", "OR", "NOT", "IN", "EXISTS", "AS", "ON", "WITH", "GROUP", "ORDER", "HAVING", - "UNION", "DISTINCT", "ELSE", "THEN", "ALL", "VALUES", "BETWEEN", "TABLE", - ] - - // A word another engine lets a user function carry stands before a parenthesis only in this syntax. - private enum Syntax { - // Right after a call's closing parenthesis: `SUM(x) OVER (`. - case afterCall - // After a call, opening with this word: `COUNT(*) FILTER (WHERE`, `MAX(x) KEEP (DENSE_RANK`. - case afterCallOpening(String) - // After one of these words: `GROUP BY (`, `GROUPING SETS (`, `USE INDEX (`. - case afterWord(Set) - // After a name, a literal or a closing parenthesis: `t PARTITION (`, `x LIKE (`, `) EXCEPT (`. - case afterOperand - // Opening with one of these words: `ARRAY(SELECT`, `LATERAL (SELECT`. - case opening(Set) - // After a comparison: `= ANY (`. - case afterComparison - // Its parenthesized part followed by one of these words: `MATCH (a) AGAINST`, `INTERVAL (n) DAY`. - case followedBy(Set) + SQLReadOnlyFunctionCalls.builtins(forDatabaseTypeId: databaseType.rawValue) } - private static let intervalUnits: Set = [ - "MICROSECOND", "SECOND", "MINUTE", "HOUR", "DAY", "WEEK", "MONTH", "QUARTER", "YEAR", - ] - - private static let syntax: [String: [Syntax]] = [ - "BY": [.afterWord(["GROUP", "ORDER", "PARTITION", "CONNECT"])], - "OVER": [.afterCall], - "FILTER": [.afterCallOpening("WHERE")], - "KEEP": [.afterCallOpening("DENSE_RANK")], - "AGAINST": [.afterCall], - "MATCH": [.followedBy(["AGAINST"])], - "INTERVAL": [.followedBy(intervalUnits)], - "CASE": [.followedBy(["WHEN"])], - "WHEN": [.afterOperand, .afterWord(["CASE"])], - "PARTITION": [.afterOperand], - "PIVOT": [.afterOperand], - "UNPIVOT": [.afterOperand], - "CUBE": [.afterWord(["BY"])], - "ROLLUP": [.afterWord(["BY"])], - "SETS": [.afterWord(["GROUPING"])], - "ARRAY": [.opening(["SELECT", "WITH"])], - "LATERAL": [.opening(["SELECT", "WITH"])], - "ANY": [.afterComparison], - "SOME": [.afterComparison], - "JOIN": [.afterOperand, .afterWord(["INNER", "LEFT", "RIGHT", "FULL", "OUTER", "CROSS", "NATURAL", "FOR"])], - "USING": [.afterOperand], - "INDEX": [.afterWord(["USE", "FORCE", "IGNORE"])], - "KEY": [.afterWord(["USE", "FORCE", "IGNORE"])], - "LIKE": [.afterOperand], - "IS": [.afterOperand], - "INTERSECT": [.afterOperand], - "EXCEPT": [.afterOperand], - "MINUS": [.afterOperand], - "LIMIT": [.afterOperand], - "OFFSET": [.afterOperand], - // Word operators: `10 DIV (2)`, `a XOR (b)`. - "DIV": [.afterOperand], - "XOR": [.afterOperand], - "REGEXP": [.afterOperand], - "RLIKE": [.afterOperand], - "ILIKE": [.afterOperand], - "ESCAPE": [.afterOperand], - ] - - // After one of these a call can start, so a word that follows it is not standing after an operand. Word operators - // are among them: `10 DIV pivot(1)` calls `pivot`. - private static let introducers: Set = reservedWords.union(syntax.keys).union([ - "SET", "INTO", "RETURN", "RETURNING", "PRIOR", "CALL", "DO", "EXECUTE", "FOR", "CONNECT", - "MOD", "COLLATE", "BINARY", "UNIQUE", "SOUNDS", "MEMBER", "OF", "SIMILAR", "TO", "ASC", "DESC", "NULLS", - ]) - - private static let openParenthesis = UInt16(UnicodeScalar("(").value) - private static let closeParenthesis = UInt16(UnicodeScalar(")").value) - private static let period = UInt16(UnicodeScalar(".").value) - private static let colon = UInt16(UnicodeScalar(":").value) - private static let quoteOpeners: Set = [0x22, 0x60, 0x5B] - private static let comparisons: Set = [0x3D, 0x3C, 0x3E, 0x21] - - // Under every way the engine could lex the text, as the classifier reads it. A type with a length, such as - // `DECIMAL(10, 2)` in a cast, is the engine's own type, not a call. static func callsUnlistedFunction(_ sql: String, databaseType: DatabaseType) -> Bool { - let typeNames = Set( - (PluginMetadataRegistry.shared.snapshot(for: databaseType)?.editor.sqlDialect?.dataTypes ?? []) - .map { $0.uppercased() } + SQLReadOnlyFunctionCalls.callsUnlistedFunction( + sql, + databaseTypeId: databaseType.rawValue, + readings: databaseType.lexicalReadings, + typeNames: Set(PluginMetadataRegistry.shared.snapshot(for: databaseType)?.editor.sqlDialect?.dataTypes ?? []) ) - let known = builtins(for: databaseType) - return databaseType.lexicalReadings.all.contains { grammar in - SQLStatementClassifier.statements(of: sql, grammar: grammar).contains { statement in - statementCallsUnlistedFunction(statement, grammar: grammar, builtins: known, typeNames: typeNames) - } - } - } - - private static func statementCallsUnlistedFunction( - _ statement: String, - grammar: SQLLexicalGrammar, - builtins: Set, - typeNames: Set - ) -> Bool { - // A plain EXPLAIN plans its statement without running it. - if let explain = SQLExplainStatement.read(statement, grammar: grammar) { - switch explain.reading { - case .describesObject, .explains(_, false): - return false - case .explains(_, true), .unreadable: - break - } - } - let source = statement as NSString - let code = SQLCodeProjection.code(of: statement, grammar: grammar) as NSString - var quoted: [Range]? - return SQLFunctionCallScanner.calls(in: source, code: code).contains { call in - guard case .named(let name, let start) = call.callee, - !quoteOpeners.contains(source.character(at: start)) - else { return true } - let word = name.uppercased() - switch qualifier(before: start, in: code) { - case .member: - return true - case .cast: - return !typeNames.contains(word) - case .unqualified: - break - } - if builtins.contains(word) || typeNames.contains(word) || reservedWords.contains(word) { return false } - guard let rules = syntax[word] else { return true } - let spans = quoted ?? quotedSpans(in: source, grammar: grammar) - quoted = spans - let site = CallSite(code: code, quotedSpans: spans, nameStart: start, parenthesis: call.parenthesis) - return !rules.contains { site.matches($0) } - } - } - - // Where a literal or a quoted name sits. The projection blanks comments too, and a comment is not a token. - private static func quotedSpans(in source: NSString, grammar: SQLLexicalGrammar) -> [Range] { - var spans: [Range] = [] - var index = 0 - while index < source.length { - guard let span = SQLNonCodeSpan.span(at: index, in: source, grammar: grammar) else { - index += 1 - continue - } - if span.kind == .quoted { spans.append(span.start.. Qualifier { - var cursor = start - 1 - while cursor >= 0, SQLFunctionCallScanner.isBlank(code.character(at: cursor)) { - cursor -= 1 - } - guard cursor >= 0 else { return .unqualified } - let unit = code.character(at: cursor) - if unit == period { return .member } - guard unit == colon else { return .unqualified } - return cursor > 0 && code.character(at: cursor - 1) == colon ? .cast : .member - } - - private enum Neighbor: Equatable { - case start - case word(String) - case symbol(UInt16) - // A literal or a quoted name, which the projection blanked. - case quoted - } - - private struct CallSite { - let code: NSString - let quotedSpans: [Range] - let nameStart: Int - let parenthesis: Int - - func matches(_ rule: Syntax) -> Bool { - switch rule { - case .afterCall: - return before == .symbol(ReadOnlyFunctionCalls.closeParenthesis) - case .afterCallOpening(let word): - return before == .symbol(ReadOnlyFunctionCalls.closeParenthesis) && firstWord(after: parenthesis) == word - case .afterWord(let words): - guard case .word(let word) = before else { return false } - return words.contains(word) - case .afterOperand: - switch before { - case .quoted: - return true - case .symbol(let unit): - return unit == ReadOnlyFunctionCalls.closeParenthesis - case .word(let word): - return !ReadOnlyFunctionCalls.introducers.contains(word) - case .start: - return false - } - case .opening(let words): - return firstWord(after: parenthesis).map { words.contains($0) } ?? false - case .afterComparison: - guard case .symbol(let unit) = before else { return false } - return ReadOnlyFunctionCalls.comparisons.contains(unit) - case .followedBy(let words): - return wordAfterGroup().map { words.contains($0) } ?? false - } - } - - private var before: Neighbor { - var cursor = nameStart - 1 - while cursor >= 0, SQLFunctionCallScanner.isBlank(code.character(at: cursor)) { - if quotedSpans.contains(where: { $0.contains(cursor) }) { return .quoted } - cursor -= 1 - } - guard cursor >= 0 else { return .start } - let unit = code.character(at: cursor) - guard SQLFunctionCallScanner.isIdentifierUnit(unit) else { return .symbol(unit) } - var start = cursor - while start > 0, SQLFunctionCallScanner.isIdentifierUnit(code.character(at: start - 1)) { - start -= 1 - } - return .word(code.substring(with: NSRange(location: start, length: cursor - start + 1)).uppercased()) - } - - private func firstWord(after index: Int) -> String? { - var cursor = index + 1 - while cursor < code.length, SQLFunctionCallScanner.isBlank(code.character(at: cursor)) { - cursor += 1 - } - var end = cursor - while end < code.length, SQLFunctionCallScanner.isIdentifierUnit(code.character(at: end)) { - end += 1 - } - guard end > cursor else { return nil } - return code.substring(with: NSRange(location: cursor, length: end - cursor)).uppercased() - } - - private func wordAfterGroup() -> String? { - var depth = 0 - for index in parenthesis.. Bool? { + guard let request = DynamoDBRequestStatement(statement, grammar: grammar) else { return nil } + guard let action = request.action else { return false } + switch action { + case .createTable, .updateTable, .deleteTable, .updateTimeToLive, .updateContinuousBackups, .tagResource, + .untagResource: + return false + case .executeStatement, .executeTransaction, .batchExecuteStatement: + guard let carried = request.partiQLStatements, carried.count == request.partiQLEntryCount, + carried.allSatisfy({ isSQLDataStatement($0, databaseType: .dynamodb) == true }) + else { return false } + case .browse, .scan, .query, .getItem, .batchGetItem, .transactGetItems, .describeTable, .listTables, + .describeTimeToLive, .describeContinuousBackups, .listTagsOfResource, .describeLimits, .putItem, + .updateItem, .deleteItem, .batchWriteItem, .transactWriteItems: + break + } + return request.hasOnlyReadWindowAfterBody || isSQLDataStatement(request.trailingText, databaseType: .dynamodb) == true + } + private static func dynamoDBTier(of request: DynamoDBRequestStatement) -> QueryTier { guard let action = request.action else { return .destructive } guard let body = request.body, body.isObject else { return worstTier(of: action) } diff --git a/apple/TablePro/Core/Utilities/SQL/QueryClassifier+Flux.swift b/apple/TablePro/Core/Utilities/SQL/QueryClassifier+Flux.swift index c194e6cc24..a491062c49 100644 --- a/apple/TablePro/Core/Utilities/SQL/QueryClassifier+Flux.swift +++ b/apple/TablePro/Core/Utilities/SQL/QueryClassifier+Flux.swift @@ -5,6 +5,11 @@ import TableProSQLGrammar // The SQL reading tiers a Flux read as an unknown statement, a write, so it would refuse every Flux read on a read-only // connection. Each statement is read as the driver receives it, through the driver's own routing and Flux reading. extension QueryClassifier { + // Flux reads, and writes points with `to()`; it defines no bucket or user. + static func fluxIsDataStatement(_ statement: String) -> Bool? { + InfluxStatement.isFlux(statement) ? true : nil + } + static func fluxClassification(_ statement: String) -> QueryClassification? { guard InfluxStatement.isFlux(statement) else { return nil } let reading = FluxScriptReading(InfluxStatement.fluxBody(of: statement)) diff --git a/apple/TablePro/Core/Utilities/SQL/QueryClassifier.swift b/apple/TablePro/Core/Utilities/SQL/QueryClassifier.swift index 19d3dc08ff..badfc034c4 100644 --- a/apple/TablePro/Core/Utilities/SQL/QueryClassifier.swift +++ b/apple/TablePro/Core/Utilities/SQL/QueryClassifier.swift @@ -62,6 +62,36 @@ enum QueryClassifier { } } + // Nil on an engine with a query language of its own, Cypher, KafkaQL or a shell: which of its commands define, + // grant or set the session is not a SQL question. + static func isSQLDataStatement(_ sql: String, databaseType: DatabaseType) -> Bool? { + let readings = databaseType.lexicalReadings + guard (PluginMetadataRegistry.shared.snapshot(for: databaseType)?.editorLanguage ?? .sql) == .sql, + documentStoreClassification(sql, databaseType: databaseType, readings: readings) == nil, + redisClassification(sql, databaseType: databaseType) == nil + else { return nil } + let leading = StatementBlank.trimming(SQLLeadingComments.stripping(sql, grammar: readings.execution)) + guard beancountClassification(leading, databaseType: databaseType) == nil else { return nil } + return SQLStatementClassifier.isDataStatement( + sql, + databaseTypeId: databaseType.rawValue, + readings: readings, + request: requestClassification(for: databaseType), + requestIsData: requestDataStatement(for: databaseType) + ) + } + + private static func requestDataStatement(for databaseType: DatabaseType) -> SQLStatementClassifier.RequestDataStatement? { + switch databaseType { + case .dynamodb: + return { statement, grammar in dynamoDBIsDataStatement(statement, grammar: grammar) } + case .influxdb: + return { statement, _ in fluxIsDataStatement(statement) } + default: + return nil + } + } + static func isWriteQuery(_ sql: String, databaseType: DatabaseType) -> Bool { let readings = databaseType.lexicalReadings return classify(sql, databaseType: databaseType, readings: readings) { $0.tier != .safe }.tier != .safe diff --git a/apple/TablePro/Models/AI/AIModels.swift b/apple/TablePro/Models/AI/AIModels.swift index 0f8e7d1efe..4d64392be3 100644 --- a/apple/TablePro/Models/AI/AIModels.swift +++ b/apple/TablePro/Models/AI/AIModels.swift @@ -257,7 +257,7 @@ enum AIChatMode: String, Codable, CaseIterable, Identifiable, Sendable { case .ask: return String(localized: "Ask: read-only schema lookups. AI can browse but not run queries.") case .edit: - return String(localized: "Edit: read-only tools plus running queries. Destructive DDL stays blocked.") + return String(localized: "Edit: read-only tools plus queries and data changes. On SQL databases, schema, privilege and session statements need Agent mode.") case .agent: return String(localized: "Agent: full tool access including destructive DDL. Safe mode still gates execution.") } @@ -269,9 +269,10 @@ enum AIChatMode: String, Codable, CaseIterable, Identifiable, Sendable { return "You are in Ask mode. Tools are read-only: schema lookups only. You cannot run queries or modify data." case .edit: return """ - You are in Edit mode. You can read schema and run SELECT/INSERT/UPDATE/DELETE via execute_query. \ - Leave schema, privilege and session changes, such as CREATE, ALTER, GRANT or SET, to Agent mode. \ - Destructive statements, such as DROP, TRUNCATE or a DELETE with no WHERE, are blocked. + You are in Edit mode. You can read schema and run queries and data changes, such as \ + SELECT, INSERT, UPDATE, DELETE and MERGE, via execute_query. On a SQL database, execute_query refuses \ + schema, privilege, session and transaction statements, such as CREATE, ALTER, GRANT, SET or BEGIN: \ + they need Agent mode. Destructive statements, such as DROP, TRUNCATE or a DELETE with no WHERE, are blocked. """ case .agent: return """ diff --git a/apple/TablePro/Models/Connection/SafeModeFloor.swift b/apple/TablePro/Models/Connection/SafeModeFloor.swift index a68045e83e..f6e618ea5d 100644 --- a/apple/TablePro/Models/Connection/SafeModeFloor.swift +++ b/apple/TablePro/Models/Connection/SafeModeFloor.swift @@ -99,4 +99,11 @@ internal extension SafeModeFloor { static func levels(allowedBy floor: SafeModeFloor?) -> [SafeModeLevel] { SafeModeLevel.allCases.filter { floor?.allows($0) ?? true } } + + // The level a refusal at Read-Only tells the user to switch to: the weakest the menu offers above `floor`, never + // below Alert. Nil when the floor itself is Read-Only. + static func levelThatWrites(above floor: SafeModeLevel?) -> SafeModeLevel? { + guard let floor, floor.strictness > SafeModeLevel.alert.strictness else { return .alert } + return floor.blocksAllWrites ? nil : floor + } } diff --git a/apple/TablePro/Resources/Localizable.xcstrings b/apple/TablePro/Resources/Localizable.xcstrings index 93949bd22a..1a9bf2a87c 100644 --- a/apple/TablePro/Resources/Localizable.xcstrings +++ b/apple/TablePro/Resources/Localizable.xcstrings @@ -34856,6 +34856,9 @@ } } } + }, + "Cannot run this query at Read-Only: it calls a function that can change data. Switch Safe Mode to %@ to run it." : { + }, "Cannot run this query: it calls a function that can change data, and Safe Mode is held at Read-Only for this connection." : { @@ -70865,6 +70868,9 @@ } } } + }, + "Edit mode runs only queries and data changes, such as SELECT, INSERT, UPDATE, DELETE and MERGE. A schema, privilege, session or transaction statement, or a change to the database's own tables, needs Agent mode, or run it yourself in a query tab." : { + }, "Edit Profile…" : { "localizations" : { @@ -71102,6 +71108,9 @@ } } } + }, + "Edit: read-only tools plus queries and data changes. On SQL databases, schema, privilege and session statements need Agent mode." : { + }, "Edit: read-only tools plus running queries. Destructive DDL stays blocked." : { "localizations" : { @@ -183205,6 +183214,9 @@ } } } + }, + "TablePro's Safe Mode is held at Read-Only for this connection, so this tool cannot run." : { + }, "TablePro's Safe Mode is set to read-only for this connection. Destructive operations are not permitted." : { "localizations" : { @@ -183285,6 +183297,9 @@ } } } + }, + "TablePro's Safe Mode is set to Read-Only for this connection. Switch it to %@ to allow this tool." : { + }, "tables" : { "localizations" : { diff --git a/apple/TablePro/ViewModels/AIChatViewModel+Streaming.swift b/apple/TablePro/ViewModels/AIChatViewModel+Streaming.swift index cdb7924280..7f17df24e1 100644 --- a/apple/TablePro/ViewModels/AIChatViewModel+Streaming.swift +++ b/apple/TablePro/ViewModels/AIChatViewModel+Streaming.swift @@ -230,6 +230,7 @@ extension AIChatViewModel { connectionId: self.connection?.id, bridge: ChatToolBootstrap.bridge, authPolicy: ChatToolBootstrap.authPolicy, + chatMode: chatMode, sessionId: self.sessionId ) } diff --git a/apple/TablePro/ViewModels/AIChatViewModel+ToolApproval.swift b/apple/TablePro/ViewModels/AIChatViewModel+ToolApproval.swift index 45a1770230..8d93cc8a57 100644 --- a/apple/TablePro/ViewModels/AIChatViewModel+ToolApproval.swift +++ b/apple/TablePro/ViewModels/AIChatViewModel+ToolApproval.swift @@ -151,19 +151,26 @@ extension AIChatViewModel { return .pending } - if let connection, alwaysAllowedTools(for: connection).contains(toolName) { - return .approved - } - if let connection { - let safeModeLevel = liveSafeModeLevel(for: connection) - if safeModeLevel.blocksAllWrites { + // Read-Only comes first: an Always Allow grant is consent to the tool, not to a level that refuses writes. + if let connection, liveSafeModeLevel(for: connection).blocksAllWrites { + guard let level = SafeModeFloor.levelThatWrites(above: AgentModeSafeModeFloor.effectiveFloor(for: connection)?.level) + else { return .denied(reason: String( - localized: "TablePro's Safe Mode is set to read-only for this connection. Set it to Confirm Writes or higher to allow this tool." + localized: "TablePro's Safe Mode is held at Read-Only for this connection, so this tool cannot run." )) } - if !safeModeLevel.requiresConfirmation { - return .approved - } + return .denied(reason: String( + format: String( + localized: "TablePro's Safe Mode is set to Read-Only for this connection. Switch it to %@ to allow this tool." + ), + level.displayName + )) + } + if let connection, alwaysAllowedTools(for: connection).contains(toolName) { + return .approved + } + if let connection, !liveSafeModeLevel(for: connection).requiresConfirmation { + return .approved } return .pending } @@ -249,6 +256,7 @@ extension AIChatViewModel { connectionId: connection?.id, bridge: ChatToolBootstrap.bridge, authPolicy: ChatToolBootstrap.authPolicy, + chatMode: mode, sessionId: sessionId ) await handleCopilotToolInvocation( diff --git a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ReadOnlySafeMode.swift b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ReadOnlySafeMode.swift index 65a0a04884..7120e5ee3a 100644 --- a/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ReadOnlySafeMode.swift +++ b/apple/TablePro/Views/Main/Extensions/MainContentCoordinator+ReadOnlySafeMode.swift @@ -21,33 +21,19 @@ extension MainContentCoordinator { filters.filter { $0.isEnabled && $0.isRawSQL }.map(\.value) } - private static func rawFilterKey(_ filters: [TableFilter]) -> String { - Set(rawFilterExpressions(filters)).sorted().joined(separator: "\n") - } - - // A raw filter is text the user typed, inside a query no gate reads below the Full levels. At Read-Only one that - // calls a function goes to the gate before the browse or a count sends it, and the gate asks where the driver cannot - // hold the engine to read-only. Once per filter text and tab: its page turns, sorts and counts run what was approved, - // until a profile or a floor holds the level, after which every run goes to the gate, which refuses. - func rawFilterNeedsReadOnlyGate(_ filters: [TableFilter], tabId: UUID) -> Bool { + // A raw filter is text the user typed, inside a query no gate reads below the Full levels. At Read-Only, where the + // driver cannot hold the engine to read-only, one that calls a function goes to the gate, which refuses it, before + // a browse, page turn, sort or count sends it. + func rawFilterNeedsReadOnlyGate(_ filters: [TableFilter]) -> Bool { let expressions = Self.rawFilterExpressions(filters) - guard !expressions.isEmpty, runsAtReadOnly else { return false } - let approved = approvedReadOnlyRawFilters[tabId] == Self.rawFilterKey(filters) && !readOnlyLevelIsHeld - guard !approved else { return false } + guard !expressions.isEmpty, runsAtReadOnly, + ExecutionGateProvider.readOnlyFunctionPolicy( + connectionId: connectionId, databaseType: connection.type, in: services.databaseManager + ).functionsCanWrite + else { return false } return expressions.contains { ReadOnlyFunctionCalls.callsUnlistedFunction($0, databaseType: connection.type) } } - func approveReadOnlyRawFilter(_ filters: [TableFilter], tabId: UUID) { - guard !readOnlyLevelIsHeld else { return } - approvedReadOnlyRawFilters[tabId] = Self.rawFilterKey(filters) - } - - private var readOnlyLevelIsHeld: Bool { - ExecutionGateProvider.readOnlyFunctionPolicy( - connectionId: connectionId, databaseType: connection.type, in: services.databaseManager - ).levelIsHeld - } - func rawFilterRequest(sql: String, canPrompt: Bool) -> OperationRequest { OperationRequest( connectionId: connectionId, diff --git a/apple/TablePro/Views/Main/MainContentCoordinator.swift b/apple/TablePro/Views/Main/MainContentCoordinator.swift index 95198bade6..effdcb46fa 100644 --- a/apple/TablePro/Views/Main/MainContentCoordinator.swift +++ b/apple/TablePro/Views/Main/MainContentCoordinator.swift @@ -174,8 +174,6 @@ final class MainContentCoordinator: ObservableObject { let tabSessionRegistry: TabSessionRegistry let queryExecutor: QueryExecutor internal var executionGate: any ExecutionGate = ExecutionGateProvider.shared - // The raw filter text each tab had approved at Read-Only. - var approvedReadOnlyRawFilters: [UUID: String] = [:] let windowSidebarState: WindowSidebarState // MARK: - Services @@ -1086,8 +1084,8 @@ final class MainContentCoordinator: ObservableObject { let level = safeModeLevel let asksBeforeFirstLoad = level.appliesToAllQueries && level.requiresConfirmation && tab.execution.lastExecutedAt == nil - let asksAboutRawFilter = rawFilterNeedsReadOnlyGate(Self.browseFilters(tab.filterState), tabId: tab.id) - if asksBeforeFirstLoad || asksAboutRawFilter { + let gatesRawFilter = rawFilterNeedsReadOnlyGate(Self.browseFilters(tab.filterState)) + if asksBeforeFirstLoad || gatesRawFilter { guard !isShowingSafeModePrompt else { turnAwayTableLoad(tabId: tab.id, trigger: trigger) return nil @@ -1124,7 +1122,6 @@ final class MainContentCoordinator: ObservableObject { } switch decision { case .authorized: - if asksAboutRawFilter { approveReadOnlyRawFilter(Self.browseFilters(tab.filterState), tabId: tabId) } executeQueryInternal( sql, isAutoLoad: true, trigger: trigger, viewport: viewport, source: .sameSource, onTab: tabId ) diff --git a/apple/TableProMobile/TableProMobile/Helpers/ReadOnlyFunctionGuard.swift b/apple/TableProMobile/TableProMobile/Helpers/ReadOnlyFunctionGuard.swift new file mode 100644 index 0000000000..9693630ddb --- /dev/null +++ b/apple/TableProMobile/TableProMobile/Helpers/ReadOnlyFunctionGuard.swift @@ -0,0 +1,19 @@ +import Foundation +import TableProModels +import TableProSQLGrammar +import TableProSQLVocabulary + +// No iOS driver runs a read in the engine's read-only mode, so at Read-Only a call off the built-in list, on an engine +// whose functions can write, cannot be told from a write and is refused like one. +nonisolated enum ReadOnlyFunctionGuard { + static func refuses(_ sql: String, databaseType: DatabaseType, level: SafeModeLevel) -> Bool { + let typeId = databaseType.rawValue + guard level.blocksWrites, SQLReadOnlyFunctionCalls.queryFunctionsCanWrite.contains(typeId) else { return false } + return SQLReadOnlyFunctionCalls.callsUnlistedFunction( + sql, + databaseTypeId: typeId, + readings: SQLLexicalReadings.resolve(databaseTypeId: typeId, declared: nil, session: nil), + typeNames: SQLEngineVocabulary.curated(forDatabaseTypeId: typeId)?.dataTypes ?? [] + ) + } +} diff --git a/apple/TableProMobile/TableProMobile/Localizable.xcstrings b/apple/TableProMobile/TableProMobile/Localizable.xcstrings index 852d55e896..18769fa956 100644 --- a/apple/TableProMobile/TableProMobile/Localizable.xcstrings +++ b/apple/TableProMobile/TableProMobile/Localizable.xcstrings @@ -18209,6 +18209,9 @@ } } } + }, + "Query Blocked" : { + }, "Query Error" : { "localizations" : { @@ -22958,6 +22961,9 @@ }, "This pipeline is not something MongoDB can read: %@" : { + }, + "This query calls a function that can change data, which Read-Only does not run. Switch Safe Mode to %@ to run it." : { + }, "This row has no _id, so TablePro cannot tell which document to change." : { diff --git a/apple/TableProMobile/TableProMobile/Views/QueryEditorView.swift b/apple/TableProMobile/TableProMobile/Views/QueryEditorView.swift index 9e877511d7..83688e6ce3 100644 --- a/apple/TableProMobile/TableProMobile/Views/QueryEditorView.swift +++ b/apple/TableProMobile/TableProMobile/Views/QueryEditorView.swift @@ -40,6 +40,7 @@ struct QueryEditorView: View { @State private var executionStartTime: Date? @State private var showWriteConfirmation = false @State private var showWriteBlockedAlert = false + @State private var showFunctionBlockedAlert = false @State private var pendingWriteQuery = "" @State private var showClearConfirmation = false @State private var showShareSheet = false @@ -231,6 +232,11 @@ struct QueryEditorView: View { } message: { Text("This connection is in read-only mode. Write queries are not allowed.") } + .alert(String(localized: "Query Blocked"), isPresented: $showFunctionBlockedAlert) { + Button("OK", role: .cancel) {} + } message: { + Text("This query calls a function that can change data, which Read-Only does not run. Switch Safe Mode to \(SafeModeLevel.confirmWrites.displayName) to run it.") + } .confirmationDialog(String(localized: "Execute Write Query?"), isPresented: $showWriteConfirmation, titleVisibility: .visible) { Button(String(localized: "Execute"), role: .destructive) { executeTask = Task { await executeQueryDirect(pendingWriteQuery) } @@ -854,6 +860,9 @@ struct QueryEditorView: View { case .proceed: break } + } else if ReadOnlyFunctionGuard.refuses(trimmed, databaseType: databaseType, level: safeModeLevel) { + showFunctionBlockedAlert = true + return } await executeQueryDirect(trimmed) diff --git a/apple/TableProMobile/TableProMobileTests/Helpers/ReadOnlyFunctionGuardTests.swift b/apple/TableProMobile/TableProMobileTests/Helpers/ReadOnlyFunctionGuardTests.swift new file mode 100644 index 0000000000..e22591e53c --- /dev/null +++ b/apple/TableProMobile/TableProMobileTests/Helpers/ReadOnlyFunctionGuardTests.swift @@ -0,0 +1,32 @@ +import Foundation +@testable import TableProMobile +import TableProModels +import Testing + +struct ReadOnlyFunctionGuardTests { + @Test("Read-Only refuses a call off the built-in list on an engine whose functions can write", arguments: [ + DatabaseType.postgresql, .mysql, .mariadb, .oceanbase, .oracle, + ]) + func refusesAnUnlistedCall(type: DatabaseType) { + #expect(ReadOnlyFunctionGuard.refuses("SELECT purge_orders()", databaseType: type, level: .readOnly)) + #expect(ReadOnlyFunctionGuard.refuses("SELECT app.count(id) FROM orders", databaseType: type, level: .readOnly)) + } + + @Test("Built-ins, a cast to the engine's own type and a plain EXPLAIN run", arguments: [ + (DatabaseType.postgresql, "SELECT COUNT(*), LOWER(name), NOW() FROM orders WHERE total::numeric(10, 2) > 1"), + (.postgresql, "EXPLAIN SELECT purge_orders()"), + (.mysql, "SELECT DATE_FORMAT(created_at, '%Y-%m'), CAST(total AS DECIMAL(10, 2)) FROM orders"), + (.oracle, "SELECT NVL(note, 'x'), TO_CHAR(created, 'YYYY') FROM orders"), + ]) + func runsBuiltins(type: DatabaseType, sql: String) { + #expect(!ReadOnlyFunctionGuard.refuses(sql, databaseType: type, level: .readOnly)) + } + + @Test("Only Read-Only refuses, and only where a function a query calls can write") + func refusesOnlyAtReadOnlyWhereFunctionsWrite() { + #expect(!ReadOnlyFunctionGuard.refuses("SELECT purge_orders()", databaseType: .postgresql, level: .confirmWrites)) + #expect(!ReadOnlyFunctionGuard.refuses("SELECT purge_orders()", databaseType: .postgresql, level: .off)) + #expect(!ReadOnlyFunctionGuard.refuses("SELECT purge_orders()", databaseType: .mssql, level: .readOnly)) + #expect(!ReadOnlyFunctionGuard.refuses("SELECT purge_orders()", databaseType: .sqlite, level: .readOnly)) + } +} diff --git a/apple/TableProTests/Core/AI/AIConnectionAccessGateTests.swift b/apple/TableProTests/Core/AI/AIConnectionAccessGateTests.swift index 88d10d09a6..0eadf3f2cc 100644 --- a/apple/TableProTests/Core/AI/AIConnectionAccessGateTests.swift +++ b/apple/TableProTests/Core/AI/AIConnectionAccessGateTests.swift @@ -300,7 +300,8 @@ internal struct AIConnectionAccessGateSavedPolicyTests { return ChatToolContext( connectionId: connectionId, bridge: MCPConnectionBridge(), - authPolicy: MCPAuthPolicy() + authPolicy: MCPAuthPolicy(), + chatMode: .agent ) { id in await MainActor.run { AIConnectionAccessGate.policy( diff --git a/apple/TableProTests/Core/AI/Chat/ChatToolTargetTests.swift b/apple/TableProTests/Core/AI/Chat/ChatToolTargetTests.swift index 46128d57cf..c647f63ddb 100644 --- a/apple/TableProTests/Core/AI/Chat/ChatToolTargetTests.swift +++ b/apple/TableProTests/Core/AI/Chat/ChatToolTargetTests.swift @@ -21,6 +21,7 @@ struct ChatToolTargetTests { connectionId: connectionId, bridge: MCPConnectionBridge(), authPolicy: MCPAuthPolicy(), + chatMode: .agent, approvalWasExplicit: approvalWasExplicit ) } diff --git a/apple/TableProTests/Core/AI/Chat/ListConnectionsChatToolTests.swift b/apple/TableProTests/Core/AI/Chat/ListConnectionsChatToolTests.swift index dde0ff317a..4b133fbe4a 100644 --- a/apple/TableProTests/Core/AI/Chat/ListConnectionsChatToolTests.swift +++ b/apple/TableProTests/Core/AI/Chat/ListConnectionsChatToolTests.swift @@ -22,6 +22,7 @@ struct ListConnectionsChatToolTests { connectionId: connectionId, bridge: MCPConnectionBridge(), authPolicy: MCPAuthPolicy(), + chatMode: .agent, policyLookup: { _ in policy } ) } diff --git a/apple/TableProTests/Core/AI/ChatToolRegistryTests.swift b/apple/TableProTests/Core/AI/ChatToolRegistryTests.swift index bfe51320d7..6c02460b83 100644 --- a/apple/TableProTests/Core/AI/ChatToolRegistryTests.swift +++ b/apple/TableProTests/Core/AI/ChatToolRegistryTests.swift @@ -33,7 +33,8 @@ struct ChatToolRegistryTests { private static let stubContext = ChatToolContext( connectionId: nil, bridge: MCPConnectionBridge(), - authPolicy: MCPAuthPolicy() + authPolicy: MCPAuthPolicy(), + chatMode: .agent ) @Test("Registered tool can be looked up by name") diff --git a/apple/TableProTests/Core/AI/ExecuteToolUsesTests.swift b/apple/TableProTests/Core/AI/ExecuteToolUsesTests.swift index 1fc171948a..432b006ae4 100644 --- a/apple/TableProTests/Core/AI/ExecuteToolUsesTests.swift +++ b/apple/TableProTests/Core/AI/ExecuteToolUsesTests.swift @@ -52,7 +52,8 @@ struct ExecuteToolUsesTests { ChatToolContext( connectionId: nil, bridge: MCPConnectionBridge(), - authPolicy: MCPAuthPolicy() + authPolicy: MCPAuthPolicy(), + chatMode: .agent ) } diff --git a/apple/TableProTests/Core/Execution/ExternalStatementGateTests.swift b/apple/TableProTests/Core/Execution/ExternalStatementGateTests.swift index d97525a317..68cdca381e 100644 --- a/apple/TableProTests/Core/Execution/ExternalStatementGateTests.swift +++ b/apple/TableProTests/Core/Execution/ExternalStatementGateTests.swift @@ -20,7 +20,8 @@ struct ExternalStatementGateTests { loadsExtensions: Bool = false, allowsDestructive: Bool = true, allowsMultiStatement: Bool = false, - destructiveAlternative: String? = nil + destructiveAlternative: String? = nil, + allowsOnlyDataStatements: Bool = false ) -> ExternalStatementGate.Statement { ExternalStatementGate.Statement( sql: sql, @@ -30,7 +31,8 @@ struct ExternalStatementGateTests { loadsExtensions: loadsExtensions, allowsDestructive: allowsDestructive, allowsMultiStatement: allowsMultiStatement, - destructiveAlternative: destructiveAlternative + destructiveAlternative: destructiveAlternative, + allowsOnlyDataStatements: allowsOnlyDataStatements ) } @@ -51,6 +53,33 @@ struct ExternalStatementGateTests { #expect(classification.tier == .safe) } + @Test("A caller held to data statements is refused a grant, a role change or a SET, and only that caller", arguments: [ + "GRANT ALL ON orders TO app", "ALTER ROLE app WITH SUPERUSER", "SET search_path = evil", "SELECT set_config('role', 'admin', false)", + ]) + func dataStatementsOnlyRefusesTheRest(sql: String) { + #expect(refusal(statement(sql, allowsOnlyDataStatements: true)) == .denied(ExternalStatementGate.dataStatementRefusal)) + #expect(refusal(statement(sql)) == nil) + } + + @Test("A caller held to data statements runs reads and row changes") + func dataStatementsOnlyRunsRowWork() { + for sql in ["SELECT * FROM orders", "UPDATE orders SET paid = true WHERE id = 1", "INSERT INTO orders (id) VALUES (1)"] { + #expect(refusal(statement(sql, allowsOnlyDataStatements: true)) == nil) + } + } + + // A query language of the engine's own has no data statement to tell from a definition, so the flag leaves it to + // the tier rules. + @Test("A caller held to data statements keeps the tier rules on an engine with its own query language", arguments: [ + (DatabaseType.mongodb, "db.orders.insertOne({a: 1})"), + (.kafka, "PRODUCE INTO \"orders\" KEY \"k\" VALUE \"v\""), + (.surrealdb, "DEFINE TABLE person SCHEMAFULL"), + ]) + func dataStatementsOnlyLeavesOtherLanguages(type: DatabaseType, sql: String) { + #expect(QueryClassifier.isSQLDataStatement(sql, databaseType: type) == nil) + #expect(refusal(statement(sql, databaseType: type, allowsOnlyDataStatements: true)) == nil) + } + @Test("A MongoDB read passes a connection that is read only for external clients", arguments: [ #"db.c.aggregate([{"$match": {"k": {"$nin": ["x"]}}}])"#, #"db.c.find({}, {"_id": 1}).limit(1)"#, diff --git a/apple/TableProTests/Core/MCP/MCPAnswerBudgetPayloadTests.swift b/apple/TableProTests/Core/MCP/MCPAnswerBudgetPayloadTests.swift index 1fae86a8f1..323e9d7f79 100644 --- a/apple/TableProTests/Core/MCP/MCPAnswerBudgetPayloadTests.swift +++ b/apple/TableProTests/Core/MCP/MCPAnswerBudgetPayloadTests.swift @@ -82,6 +82,7 @@ struct MCPAnswerBudgetPayloadTests { historyRecorder: RecordingQueryHistory(), executionGate: AlwaysAllowGate() ), + chatMode: .agent, policyLookup: { _ in .alwaysAllow } ) diff --git a/apple/TableProTests/Core/MCP/MCPScriptResultTests.swift b/apple/TableProTests/Core/MCP/MCPScriptResultTests.swift index 221b7a6283..31d439be41 100644 --- a/apple/TableProTests/Core/MCP/MCPScriptResultTests.swift +++ b/apple/TableProTests/Core/MCP/MCPScriptResultTests.swift @@ -191,7 +191,8 @@ struct MCPScriptResultTests { let context = ChatToolContext( connectionId: driver.connection.id, bridge: MCPConnectionBridge(), - authPolicy: authPolicy() + authPolicy: authPolicy(), + chatMode: .agent ) let result = try await ExecuteQueryChatTool().execute(input: .object(["query": .string(script)]), context: context) @@ -229,6 +230,7 @@ struct MCPScriptResultTests { historyRecorder: DiscardingHistory(), executionGate: gate ), + chatMode: .agent, sessionId: sessionId, approvalWasExplicit: true, policyLookup: { _ in .alwaysAllow } diff --git a/apple/TableProTests/Core/Services/Execution/ExecutionGateTests.swift b/apple/TableProTests/Core/Services/Execution/ExecutionGateTests.swift index 986ea8a82a..77f1f2668e 100644 --- a/apple/TableProTests/Core/Services/Execution/ExecutionGateTests.swift +++ b/apple/TableProTests/Core/Services/Execution/ExecutionGateTests.swift @@ -877,40 +877,47 @@ struct ExecutionGateTests { ) } - private static let writableFunctions = ReadOnlyFunctionPolicy(functionsCanWrite: true, levelIsHeld: false) + private static let writableFunctions = ReadOnlyFunctionPolicy(functionsCanWrite: true) - @Test("Read-Only asks before a read that calls a function the engine could let write") - func readOnlyAsksBeforeAFunctionCall() async { + @Test("Read-Only refuses a read that calls a function the engine could let write, and names the level to switch to") + func readOnlyRefusesAFunctionCall() async { let confirm = StubConfirming(answer: true) let gate = makeReadOnlyGate(policy: Self.writableFunctions, confirm: confirm) let decision = await gate.authorize(makeRequest(sql: "SELECT purge_orders()", kind: .readQuery)) - #expect(decision.isAuthorized) - #expect(confirm.callCount == 1) - #expect(confirm.lastRequest?.sql == "SELECT purge_orders()") - #expect(confirm.lastDestructive == false) + guard case .denied(let reason, let cause) = decision else { + Issue.record("Read-Only must refuse a call it cannot tell from a write") + return + } + #expect(reason.contains("Alert")) + #expect(cause == .policy) + #expect(confirm.callCount == 0) } - @Test("A Cancel at that question is a Cancel, and nothing runs") - func readOnlyFunctionCallCancelled() async { - let confirm = StubConfirming(answer: false) + @Test( + "A caller cleared before the gate is refused the call all the same", + arguments: [CallerCapabilities.preCleared, .confirmationPreCleared] + ) + func clearedCallerIsRefusedTheCall(cleared: CallerCapabilities) async { + let confirm = StubConfirming(answer: true) let gate = makeReadOnlyGate(policy: Self.writableFunctions, confirm: confirm) - let decision = await gate.authorize(makeRequest(sql: "SELECT purge_orders()", kind: .readQuery)) + let decision = await gate.authorize(makeRequest( + sql: "SELECT purge_orders()", + kind: .readQuery, + capabilities: CallerCapabilities.interactiveUser.union(cleared) + )) - guard case .denied(_, let cause) = decision else { - Issue.record("A Cancel must deny") - return - } - #expect(cause == .cancelledByUser) + #expect(!decision.isAuthorized) + #expect(confirm.callCount == 0) } @Test("A managed policy or an engine floor holding Read-Only refuses the call without asking") func heldReadOnlyRefusesAFunctionCall() async { let confirm = StubConfirming(answer: true) let gate = makeReadOnlyGate( - policy: ReadOnlyFunctionPolicy(functionsCanWrite: true, levelIsHeld: true), + policy: ReadOnlyFunctionPolicy(functionsCanWrite: true, floor: .readOnly), confirm: confirm ) @@ -920,12 +927,34 @@ struct ExecutionGateTests { Issue.record("A held Read-Only must refuse") return } - #expect(reason.contains("Read-Only")) + #expect(reason.contains("held at Read-Only")) + #expect(!reason.contains("Alert")) #expect(cause == .policy) #expect(confirm.callCount == 0) } - @Test("A caller that cannot prompt is denied the call") + @Test( + "The refusal names the weakest level the menu offers that runs the call", + arguments: [ + (SafeModeLevel?.none, SafeModeLevel?.some(.alert)), (.silent, .alert), (.alert, .alert), + (.alertFull, .alertFull), (.safeModeFull, .safeModeFull), (.readOnly, nil), + ] + ) + func refusalNamesTheLevelThatRunsIt(floor: SafeModeLevel?, named: SafeModeLevel?) async { + let policy = ReadOnlyFunctionPolicy(functionsCanWrite: true, floor: floor) + let gate = makeReadOnlyGate(policy: policy, confirm: StubConfirming(answer: true)) + + let reason = await gate.authorize(makeRequest(sql: "SELECT purge_orders()", kind: .readQuery)).deniedReason + + #expect(policy.levelThatRunsIt == named) + if let named { + #expect(reason?.hasSuffix("Switch Safe Mode to \(named.displayName) to run it.") == true) + } else { + #expect(reason?.contains("held at Read-Only") == true) + } + } + + @Test("A caller that cannot prompt gets the same refusal") func readOnlyFunctionCallDeniedWithoutPrompt() async { let confirm = StubConfirming(answer: true) let gate = makeReadOnlyGate(policy: Self.writableFunctions, confirm: confirm) @@ -934,12 +963,12 @@ struct ExecutionGateTests { makeRequest(sql: "SELECT purge_orders()", kind: .readQuery, capabilities: [.cannotPrompt]) ) - #expect(decision.deniedReason?.contains("Confirmation") == true) + #expect(decision.deniedReason?.contains("Alert") == true) #expect(confirm.callCount == 0) } @Test( - "Read-Only runs built-ins, keywords before a parenthesis and a plain EXPLAIN without asking", + "Read-Only runs built-ins, keywords before a parenthesis and a plain EXPLAIN", arguments: [ "SELECT COUNT(*), MAX(total), LOWER(name) FROM orders WHERE id IN (1, 2) AND EXISTS (SELECT 1)", "SELECT ROW_NUMBER() OVER (PARTITION BY region ORDER BY total) FROM orders", @@ -958,15 +987,15 @@ struct ExecutionGateTests { } @Test( - "A qualified name, a quoted name and a call in a later statement are asked about", + "A qualified name, a quoted name and a call in a later statement are refused", arguments: [ "SELECT app.count(id) FROM orders", "SELECT `purge_orders`() FROM orders", "SELECT 1;\nSELECT purge_orders()", ] ) - func readOnlyAsksAboutAnyOtherCall(sql: String) async { - let confirm = StubConfirming(answer: false) + func readOnlyRefusesAnyOtherCall(sql: String) async { + let confirm = StubConfirming(answer: true) let gate = makeReadOnlyGate(policy: Self.writableFunctions, confirm: confirm) let decision = await gate.authorize( @@ -974,11 +1003,11 @@ struct ExecutionGateTests { ) #expect(!decision.isAuthorized) - #expect(confirm.callCount == 1) + #expect(confirm.callCount == 0) } @Test( - "A user function named like a keyword another engine leaves unreserved is asked about", + "A user function named like a keyword another engine leaves unreserved is refused", arguments: [ "SELECT filter(x) FROM orders", "SELECT `within`(1) FROM orders", @@ -994,18 +1023,18 @@ struct ExecutionGateTests { "SELECT id FROM orders WHERE /* don't */ offset(1) = 1", ] ) - func keywordNamedFunctionIsAsked(sql: String) async { - let confirm = StubConfirming(answer: false) + func keywordNamedFunctionIsRefused(sql: String) async { + let confirm = StubConfirming(answer: true) let gate = makeReadOnlyGate(policy: Self.writableFunctions, confirm: confirm) let decision = await gate.authorize(makeRequest(sql: sql, kind: .readQuery)) #expect(!decision.isAuthorized) - #expect(confirm.callCount == 1) + #expect(confirm.callCount == 0) } @Test( - "A keyword in the syntax that uses it before a parenthesis runs without asking", + "A keyword in the syntax that uses it before a parenthesis runs", arguments: [ "SELECT MAX(sal) KEEP (DENSE_RANK FIRST ORDER BY hired) FROM emp", "SELECT LISTAGG(name, ',') WITHIN GROUP (ORDER BY name) FROM emp", @@ -1029,7 +1058,7 @@ struct ExecutionGateTests { } @Test( - "A word operator before a parenthesis runs without asking", + "A word operator before a parenthesis runs", arguments: [ "SELECT 10 DIV (2), paid XOR (refunded) FROM orders", "SELECT id FROM orders WHERE name REGEXP ('^a') OR name RLIKE ('b$')", @@ -1047,7 +1076,7 @@ struct ExecutionGateTests { } @Test( - "The fallback engines' everyday built-ins run without asking", + "The fallback engines' everyday built-ins run", arguments: [ (DatabaseType.oracle, "SELECT DECODE(status, 1, 'open', 'closed'), NVL2(a, b, c), INSTR(name, 'x') FROM orders"), (.oracle, "SELECT ADD_MONTHS(created, 1), MONTHS_BETWEEN(a, b), TO_TIMESTAMP(t), SYS_GUID() FROM orders"), @@ -1069,13 +1098,13 @@ struct ExecutionGateTests { #expect(confirm.callCount == 0) } - // GET_LOCK is refused as a write before the question; the others are asked about, and the test answers Cancel. + // GET_LOCK is refused as a write; SLEEP and BENCHMARK are off the built-in list. @Test( "A built-in that locks, sleeps or waits never runs on its own", arguments: ["SELECT GET_LOCK('a', 10)", "SELECT SLEEP(5)", "SELECT BENCHMARK(1000, MD5('a'))"] ) func lockingOrSleepingBuiltinDoesNotRun(sql: String) async { - let confirm = StubConfirming(answer: false) + let confirm = StubConfirming(answer: true) let gate = makeReadOnlyGate(policy: Self.writableFunctions, confirm: confirm) let decision = await gate.authorize(makeRequest(sql: sql, kind: .readQuery)) @@ -1096,7 +1125,7 @@ struct ExecutionGateTests { } } - @Test("A driver that runs the statement in the engine's read-only mode is not asked about") + @Test("A driver that runs the statement in the engine's read-only mode runs the call") func enforcingDriverRunsTheCall() async { let confirm = StubConfirming(answer: false) let gate = makeReadOnlyGate(policy: ReadOnlyFunctionPolicy(), confirm: confirm) @@ -1107,7 +1136,7 @@ struct ExecutionGateTests { #expect(confirm.callCount == 0) } - @Test("Only Read-Only asks: Silent runs the same call", arguments: [SafeModeLevel.silent, .alert]) + @Test("Only Read-Only refuses: Silent and Alert run the same call", arguments: [SafeModeLevel.silent, .alert]) func otherLevelsDoNotAsk(level: SafeModeLevel) async { let confirm = StubConfirming(answer: false) let gate = makeReadOnlyGate(level: level, policy: Self.writableFunctions, confirm: confirm) @@ -1118,7 +1147,7 @@ struct ExecutionGateTests { #expect(confirm.callCount == 0) } - @Test("A metadata read is never asked about") + @Test("A metadata read is never refused for its calls") func metadataReadSkipsTheFunctionCheck() async { let confirm = StubConfirming(answer: false) let gate = makeReadOnlyGate(policy: Self.writableFunctions, confirm: confirm) @@ -1152,7 +1181,7 @@ struct ReadOnlyFunctionPolicyTests { #expect(!PluginMetadataRegistry.queryFunctionsCanWrite.contains(type)) } - @Test("A live MySQL driver without the mode needs the question, and one with it does not") + @Test("A live MySQL driver without the mode is refused the call, and one with it is not") func liveDriverDecides() { let connection = DatabaseConnection(name: "Shop", database: "shop", type: .mysql, safeModeLevel: .readOnly) defer { DatabaseManager.shared.removeSession(for: connection.id) } @@ -1163,7 +1192,7 @@ struct ReadOnlyFunctionPolicyTests { let enforcing = ExecutionGateProvider.readOnlyFunctionPolicy(connectionId: connection.id, databaseType: .mysql) #expect(older.functionsCanWrite) - #expect(!older.levelIsHeld) + #expect(older.levelThatRunsIt == .alert) #expect(!enforcing.functionsCanWrite) #expect(ExecutionGateProvider.runsAtReadOnly(connection.id)) } diff --git a/apple/TableProTests/Core/WritePolicy/AgentWritePolicyMatrixTests.swift b/apple/TableProTests/Core/WritePolicy/AgentWritePolicyMatrixTests.swift index 4b441b8b19..b9b3679e59 100644 --- a/apple/TableProTests/Core/WritePolicy/AgentWritePolicyMatrixTests.swift +++ b/apple/TableProTests/Core/WritePolicy/AgentWritePolicyMatrixTests.swift @@ -189,6 +189,7 @@ extension GlobalStateSuites { connectionId: rig.connection.id, bridge: MCPConnectionBridge(), authPolicy: rig.authPolicy, + chatMode: .agent, sessionId: UUID() ), explicitlyApproved: clicked ? [block.id] : [], diff --git a/apple/TableProTests/Core/WritePolicy/DestructiveStatementRoutingTests.swift b/apple/TableProTests/Core/WritePolicy/DestructiveStatementRoutingTests.swift index 95755d9282..82c1c64a6a 100644 --- a/apple/TableProTests/Core/WritePolicy/DestructiveStatementRoutingTests.swift +++ b/apple/TableProTests/Core/WritePolicy/DestructiveStatementRoutingTests.swift @@ -59,13 +59,14 @@ extension GlobalStateSuites { private static let unfilteredDelete = DestructiveRoute(sql: "DELETE FROM matrix_rows", destructive: true) - private func makeRig(_ prompts: WritePolicyPrompts, _ databaseType: DatabaseType) -> Rig { - let connection = WritePolicyRig.connection( + private func makeRig(_ prompts: WritePolicyPrompts, _ databaseType: DatabaseType, database: String? = nil) -> Rig { + var connection = WritePolicyRig.connection( type: databaseType, externalAccess: .readWrite, aiPolicy: .alwaysAllow, safeMode: .silent ) + if let database { connection.database = database } guard databaseType == .mssql else { let rig = WritePolicyRig(connection: connection, prompts: prompts, live: true) return Rig(rig: rig, received: { rig.driver.received }, rowCaps: { [] }) @@ -121,16 +122,19 @@ extension GlobalStateSuites { private func assistant( _ tool: any ChatTool, _ route: DestructiveRoute, - answer: WritePolicyPrompts.Answer = .approveAll + answer: WritePolicyPrompts.Answer = .approveAll, + mode: AIChatMode = .agent, + database: String? = nil ) async -> Outcome { let prompts = WritePolicyPrompts(answer) - let setup = makeRig(prompts, route.databaseType) + let setup = makeRig(prompts, route.databaseType, database: database) let rig = setup.rig defer { rig.tearDown() } let context = ChatToolContext( connectionId: rig.connection.id, bridge: MCPConnectionBridge(), authPolicy: rig.authPolicy, + chatMode: mode, sessionId: UUID(), policyLookup: { _ in .alwaysAllow } ) @@ -199,6 +203,52 @@ extension GlobalStateSuites { #expect(outcome.received.isEmpty) } + @Test("Edit runs a row change and refuses a schema, privilege or session statement that Agent runs", arguments: [ + ("UPDATE matrix_rows SET note = 'x' WHERE id = 1", true), + ("INSERT INTO matrix_rows (id) VALUES (2)", true), + ("ALTER ROLE app_user WITH SUPERUSER", false), + ("GRANT ALL ON matrix_rows TO app_user", false), + ("SET session_replication_role = replica", false), + ("CREATE TABLE notes (id int)", false), + ]) + func editRunsOnlyDataStatements(sql: String, isData: Bool) async { + let route = DestructiveRoute(sql: sql, destructive: false) + let edit = await assistant(ExecuteQueryChatTool(), route, mode: .edit) + let agent = await assistant(ExecuteQueryChatTool(), route, mode: .agent) + + #expect(edit.ran == isData, "\(edit.text)") + #expect(edit.received.contains { $0.contains(sql) } == isData) + if !isData { + #expect(edit.text == ExternalStatementGate.dataStatementRefusal) + #expect(edit.prompts.isEmpty) + } + #expect(agent.ran, "\(agent.text)") + #expect(agent.received.contains { $0.contains(sql) }) + } + + @Test("Edit refuses a row change that lands in the engine's own schema, which Agent runs") + func editRefusesARowChangeInASystemSchema() async { + let route = DestructiveRoute( + sql: "UPDATE user SET Super_priv = 'Y' WHERE User = 'app'", destructive: false, databaseType: .mysql + ) + let edit = await assistant(ExecuteQueryChatTool(), route, mode: .edit, database: "mysql") + let agent = await assistant(ExecuteQueryChatTool(), route, mode: .agent, database: "mysql") + + #expect(!edit.ran) + #expect(edit.text == ExternalStatementGate.dataStatementRefusal) + #expect(edit.received.isEmpty) + #expect(agent.ran, "\(agent.text)") + } + + @Test("Edit refuses a transaction statement before anything reaches the database", arguments: ["BEGIN", "COMMIT"]) + func editRefusesTransactionStatements(sql: String) async { + let edit = await assistant(ExecuteQueryChatTool(), DestructiveRoute(sql: sql, destructive: false), mode: .edit) + + #expect(!edit.ran) + #expect(edit.text == ExternalStatementGate.dataStatementRefusal) + #expect(edit.received.isEmpty) + } + @Test("A DELETE with no WHERE the user declines never reaches the database") func declinedUnfilteredDeleteDoesNotRun() async { let overMCP = await mcp(ConfirmDestructiveOperationTool.name, Self.unfilteredDelete, answer: .refuseAll) diff --git a/apple/TableProTests/ViewModels/AIChatAlwaysAllowTests.swift b/apple/TableProTests/ViewModels/AIChatAlwaysAllowTests.swift index 792da18a78..edf161e38b 100644 --- a/apple/TableProTests/ViewModels/AIChatAlwaysAllowTests.swift +++ b/apple/TableProTests/ViewModels/AIChatAlwaysAllowTests.swift @@ -86,6 +86,19 @@ struct AIChatAlwaysAllowTests { #expect(state == .approved) } + @Test("Read-Only refuses a granted write tool, and names the level that allows it") + func readOnlyBeatsAGrant() { + let connection = DatabaseConnection(name: "Prod", safeModeLevel: .readOnly, aiAlwaysAllowedTools: ["writer"]) + + let state = viewModel(holding: connection).computeInitialApprovalState(for: "writer", registry: registry) + + guard case .denied(let reason) = state else { + Issue.record("Read-Only must deny a granted write tool") + return + } + #expect(reason.contains(SafeModeLevel.alert.displayName)) + } + @Test("Always Allow after a revoke is stored again") func alwaysAllowAfterARevokeIsStored() throws { var paneCopy = try stored(alwaysAllowed: []) diff --git a/apple/TableProTests/ViewModels/AIChatStoppedWriteTests.swift b/apple/TableProTests/ViewModels/AIChatStoppedWriteTests.swift index 9b431f7079..8072ca9ea9 100644 --- a/apple/TableProTests/ViewModels/AIChatStoppedWriteTests.swift +++ b/apple/TableProTests/ViewModels/AIChatStoppedWriteTests.swift @@ -86,6 +86,7 @@ struct AIChatStoppedWriteTests { historyRecorder: history, executionGate: AlwaysAllowGate() ), + chatMode: .agent, policyLookup: { _ in .alwaysAllow } )) let registry = ChatToolRegistry() diff --git a/apple/TableProTests/Views/Main/FetchAllQueryTaskTests.swift b/apple/TableProTests/Views/Main/FetchAllQueryTaskTests.swift index 4e18a0aadb..5409b0869d 100644 --- a/apple/TableProTests/Views/Main/FetchAllQueryTaskTests.swift +++ b/apple/TableProTests/Views/Main/FetchAllQueryTaskTests.swift @@ -54,6 +54,42 @@ struct FetchAllQueryTaskTests { #expect(tabManager.tabs.first { $0.id == tab.id }?.pagination.isLoadingMore == false) } + @Test("Fetch All asks the gate again, and a refusal reaches no driver") + func refusedFetchAllRunsNothing() async { + let connection = TestFixtures.makeConnection() + let driver = GatedQueryDriver(connection: connection) + var session = ConnectionSession(connection: connection, driver: driver) + session.status = .connected + session.browseDatabase = connection.database + DatabaseManager.shared.injectSession(session, for: connection.id) + defer { DatabaseManager.shared.removeSession(for: connection.id) } + + let tabManager = QueryTabManager() + let coordinator = MainContentCoordinator( + connection: connection, + tabManager: tabManager, + changeManager: DataChangeManager(), + toolbarState: ConnectionToolbarState() + ) + coordinator.executionGate = AlwaysDenyGate() + // Open, so a fetch that skipped the gate would finish and be counted rather than hang. + await driver.release() + let tab = QueryTab(title: "Query", query: "SELECT purge_orders()", tabType: .query) + tabManager.tabs.append(tab) + tabManager.selectedTabId = tab.id + + coordinator.paginationCoordinator.performFetchAll( + tabId: tab.id, + baseQuery: "SELECT purge_orders()", + scope: DatabaseScope(connectionId: connection.id, database: connection.database, schema: nil) + ) + await coordinator.queryTasks.task(for: tab.id)?.value + + #expect(driver.queryCount == 0) + #expect(tabManager.tabs.first { $0.id == tab.id }?.execution.errorMessage != nil) + #expect(tabManager.tabs.first { $0.id == tab.id }?.pagination.isLoadingMore == false) + } + @Test("Fetch All on a query tab shows what its own run printed, not the first run's or anything before it") func fetchAllReplacesTheOutput() async { let firstRun = PluginServerOutput(lines: ["NOTICE: page 1"], isTruncated: false) @@ -107,6 +143,12 @@ private final class GatedQueryDriver: DatabaseDriver, @unchecked Sendable { private let answer = AsyncGate() var serverOutputs: [PluginServerOutput] = [] + private let lock = NSLock() + private var queries = 0 + + var queryCount: Int { + lock.withLock { queries } + } init(connection: DatabaseConnection) { self.connection = connection @@ -123,6 +165,7 @@ private final class GatedQueryDriver: DatabaseDriver, @unchecked Sendable { /// The gate ignores cancellation, so the answer still comes back after the task is cancelled. func executeUserQuery(query: String, rowCap: Int?, parameters: [Any?]?) async throws -> QueryResult { + lock.withLock { queries += 1 } await answer.wait() return Self.emptyResult } diff --git a/apple/TableProTests/Views/Main/ReadOnlySafeModeEntryPointTests.swift b/apple/TableProTests/Views/Main/ReadOnlySafeModeEntryPointTests.swift index ff6c749947..c7529f4654 100644 --- a/apple/TableProTests/Views/Main/ReadOnlySafeModeEntryPointTests.swift +++ b/apple/TableProTests/Views/Main/ReadOnlySafeModeEntryPointTests.swift @@ -20,7 +20,15 @@ private final class ReadOnlyRecordingDriver: PluginDriverStub, @unchecked Sendab let context: PluginStatementContext? } - var capabilities: PluginCapabilities { [.readOnlyStatements, .enforcesReadOnlyMode] } + private let enforcesReadOnlyMode: Bool + + init(enforcesReadOnlyMode: Bool = true) { + self.enforcesReadOnlyMode = enforcesReadOnlyMode + } + + var capabilities: PluginCapabilities { + enforcesReadOnlyMode ? [.readOnlyStatements, .enforcesReadOnlyMode] : [.readOnlyStatements] + } var supportsSchemas: Bool { false } var supportsTransactions: Bool { true } var currentSchema: String? { nil } @@ -174,9 +182,10 @@ struct ReadOnlySafeModeEntryPointTests { private func makeFixture( _ level: SafeModeLevel, - type: DatabaseType = .postgresql + type: DatabaseType = .postgresql, + enforcesReadOnlyMode: Bool = true ) -> (CoordinatorFixture, ReadOnlyRecordingDriver) { - let driver = ReadOnlyRecordingDriver() + let driver = ReadOnlyRecordingDriver(enforcesReadOnlyMode: enforcesReadOnlyMode) let connection = makeConnection(level, type: type) let fixture = CoordinatorFixture( connection: connection, @@ -263,38 +272,39 @@ struct ReadOnlySafeModeEntryPointTests { // MARK: - Table browse - @Test("A raw filter that calls a function goes to the gate at Read-Only and runs in the read-only mode") - func rawFilterBrowseIsGatedAndCarriesTheMode() async throws { + @Test("A raw filter that calls a function runs in the read-only mode at Read-Only, without the gate, on a driver with it") + func rawFilterBrowseCarriesTheMode() async throws { let (fixture, driver) = makeFixture(.readOnly) let gate = RequestRecordingGate(allows: true) fixture.coordinator.executionGate = gate defer { fixture.coordinator.cancelAllQueryTasks() } - let tab = fixture.addTab(rawFilterTableTab()) + fixture.addTab(rawFilterTableTab()) - let confirmation = fixture.coordinator.executeTableTabQueryDirectly(viewport: .firstRow) - #expect(confirmation != nil) - await confirmation?.value + #expect(fixture.coordinator.executeTableTabQueryDirectly(viewport: .firstRow) == nil) try await waitUntil { driver.call(containing: Self.purge) != nil } - #expect(await gate.requests.first?.sql == tab.content.query) + #expect(await gate.requests.isEmpty) #expect(driver.call(containing: Self.purge)?.context?.enforcesReadOnly == true) } - @Test("A page turn or sort under the same raw filter is not asked about again") - func rawFilterIsAskedOncePerFilter() async throws { - let (fixture, driver) = makeFixture(.readOnly) + @Test("On a driver without the mode, every load under the raw filter goes to the gate") + func rawFilterIsGatedOnEveryRun() async throws { + let (fixture, driver) = makeFixture(.readOnly, enforcesReadOnlyMode: false) let gate = RequestRecordingGate(allows: true) fixture.coordinator.executionGate = gate defer { fixture.coordinator.cancelAllQueryTasks() } - fixture.addTab(rawFilterTableTab()) + let tab = fixture.addTab(rawFilterTableTab()) - await fixture.coordinator.executeTableTabQueryDirectly(viewport: .firstRow)?.value + let first = fixture.coordinator.executeTableTabQueryDirectly(viewport: .firstRow) + #expect(first != nil) + await first?.value try await waitUntil { driver.call(containing: Self.purge) != nil } - let again = fixture.coordinator.executeTableTabQueryDirectly(viewport: .firstRow) - try await waitUntil { driver.calls.filter { $0.query.contains(Self.purge) }.count >= 2 } + let second = fixture.coordinator.executeTableTabQueryDirectly(viewport: .firstRow) + #expect(second != nil) + await second?.value - #expect(again == nil) - #expect(await gate.requests.count == 1) + let browses = await gate.requests.filter { $0.sql == tab.content.query } + #expect(browses.count == 2) } // A view, or a row security policy, can call a writing function with no call in the browse's text. @@ -333,8 +343,8 @@ struct ReadOnlySafeModeEntryPointTests { } // DuckDB counts on its session driver, which this test installs; a pooled engine would open a connection of its own. - @Test("Count Exactly with a raw filter that calls a function asks the gate and runs in the read-only mode") - func countExactlyIsGatedAndCarriesTheMode() async throws { + @Test("Count Exactly with a raw filter that calls a function runs in the read-only mode without the gate") + func countExactlyCarriesTheMode() async throws { let (fixture, driver) = makeFixture(.readOnly, type: .duckdb) let gate = RequestRecordingGate(allows: true) fixture.coordinator.executionGate = gate @@ -344,10 +354,27 @@ struct ReadOnlySafeModeEntryPointTests { fixture.coordinator.paginationCoordinator.requestExactRowCount() try await waitUntil { driver.call(containing: "COUNT") != nil } - #expect(await gate.requests.contains { $0.sql?.contains("COUNT") == true }) + #expect(await !gate.requests.contains { $0.sql?.contains("COUNT") == true }) #expect(driver.call(containing: "COUNT")?.context?.enforcesReadOnly == true) } + @Test("Count Exactly with a raw filter that calls a function goes to the gate on a driver without the mode") + func countExactlyIsGatedWithoutTheMode() async throws { + let (fixture, driver) = makeFixture(.readOnly, type: .mysql, enforcesReadOnlyMode: false) + let gate = RequestRecordingGate(allows: false) + fixture.coordinator.executionGate = gate + defer { fixture.coordinator.cancelAllQueryTasks() } + let tab = fixture.addTab(rawFilterTableTab()) + + fixture.coordinator.paginationCoordinator.requestExactRowCount() + try await waitUntil { + fixture.tabManager.tabs.first { $0.id == tab.id }?.pagination.isCountingExact == false + } + + #expect(await gate.requests.contains { $0.sql?.contains("COUNT") == true }) + #expect(driver.call(containing: "COUNT") == nil) + } + // MARK: - Export @Test("Every export read runs in the read-only mode at Read-Only, filtered or not, and Silent changes nothing") @@ -517,7 +544,7 @@ struct ReadOnlySafeModeEntryPointTests { authenticating: StubAuthenticating(answer: true), safeModeLevelResolver: { _ in .readOnly }, forcesWriteResolver: { _ in false }, - readOnlyFunctionPolicyResolver: { _, _ in ReadOnlyFunctionPolicy(functionsCanWrite: true, levelIsHeld: true) } + readOnlyFunctionPolicyResolver: { _, _ in ReadOnlyFunctionPolicy(functionsCanWrite: true, floor: .readOnly) } ) var item = ExportObjectItem(name: "ORDERS", kind: .table) item.rowScope = PluginExportRowScope(filter: "purge_orders() = 1") @@ -575,31 +602,27 @@ struct ReadOnlySafeModeEntryPointTests { #expect(call?.context?.enforcesReadOnly == true) } - // MARK: - Held level + // MARK: - Driver without the mode - // A profile or a floor that comes after an approval leaves nothing to approve: the gate refuses every run. - @Test("A held Read-Only never runs a raw filter approved before it was held") - func heldLevelIgnoresAnEarlierApproval() async throws { - let (fixture, driver) = makeFixture(.readOnly) - let gate = RequestRecordingGate(allows: false) - fixture.coordinator.executionGate = gate + @Test("A raw filter that calls a function is refused at Read-Only on a driver without the mode, with no question") + func rawFilterIsRefusedWithoutTheMode() async throws { + let (fixture, driver) = makeFixture(.readOnly, enforcesReadOnlyMode: false) + let confirm = StubConfirming(answer: true) + fixture.coordinator.executionGate = DefaultExecutionGate( + confirming: confirm, + authenticating: StubAuthenticating(answer: true), + safeModeLevelResolver: { _ in .readOnly }, + forcesWriteResolver: { _ in false }, + readOnlyFunctionPolicyResolver: { _, _ in ReadOnlyFunctionPolicy(functionsCanWrite: true) } + ) defer { fixture.coordinator.cancelAllQueryTasks() } - let tab = fixture.addTab(rawFilterTableTab()) - let filters = MainContentCoordinator.browseFilters(tab.filterState) - fixture.coordinator.approveReadOnlyRawFilter(filters, tabId: tab.id) - #expect(!fixture.coordinator.rawFilterNeedsReadOnlyGate(filters, tabId: tab.id)) + fixture.addTab(rawFilterTableTab()) - var held = fixture.connection - held.type = .cloudflareR2SQL - var session = ConnectionSession(connection: held, driver: PluginDriverAdapter(connection: held, pluginDriver: driver)) - session.status = .connected - DatabaseManager.shared.injectSession(session, for: held.id) + let refusal = fixture.coordinator.executeTableTabQueryDirectly(viewport: .firstRow) + #expect(refusal != nil) + await refusal?.value - #expect(fixture.coordinator.rawFilterNeedsReadOnlyGate(filters, tabId: tab.id)) - let confirmation = fixture.coordinator.executeTableTabQueryDirectly(viewport: .firstRow) - #expect(confirmation != nil) - await confirmation?.value - #expect(await gate.requests.count == 1) + #expect(confirm.callCount == 0) #expect(driver.call(containing: Self.purge) == nil) } diff --git a/apple/changelog.d/4244.changed.md b/apple/changelog.d/4244.changed.md new file mode 100644 index 0000000000..4e2b7024e5 --- /dev/null +++ b/apple/changelog.d/4244.changed.md @@ -0,0 +1 @@ +Read-Only blocks a query that calls a function which may change data, and names the level that runs it. diff --git a/apple/changelog.d/4244.fixed.1.md b/apple/changelog.d/4244.fixed.1.md new file mode 100644 index 0000000000..4b1d4f0e42 --- /dev/null +++ b/apple/changelog.d/4244.fixed.1.md @@ -0,0 +1 @@ +An Always Allow grant let the assistant's query tool run on a Read-Only connection. diff --git a/apple/changelog.d/4244.fixed.2.md b/apple/changelog.d/4244.fixed.2.md new file mode 100644 index 0000000000..1c35888d89 --- /dev/null +++ b/apple/changelog.d/4244.fixed.2.md @@ -0,0 +1 @@ +INSERT OVERWRITE, which empties the table first, was not treated as a destructive statement. diff --git a/apple/changelog.d/4244.fixed.md b/apple/changelog.d/4244.fixed.md new file mode 100644 index 0000000000..c7c8746842 --- /dev/null +++ b/apple/changelog.d/4244.fixed.md @@ -0,0 +1 @@ +Fetch All ran its query again without Safe Mode's check, so a level raised since the first run did not apply. diff --git a/apple/changelog.d/4244.security.1.md b/apple/changelog.d/4244.security.1.md new file mode 100644 index 0000000000..45675771ba --- /dev/null +++ b/apple/changelog.d/4244.security.1.md @@ -0,0 +1 @@ +Read-Only on iPhone and iPad ran a query that called a function which writes data. diff --git a/apple/changelog.d/4244.security.md b/apple/changelog.d/4244.security.md new file mode 100644 index 0000000000..92bb7c9495 --- /dev/null +++ b/apple/changelog.d/4244.security.md @@ -0,0 +1 @@ +On SQL databases the assistant's Edit mode ran schema, privilege, session and transaction statements, such as GRANT.