(query: string)
| 127 | } |
| 128 | |
| 129 | export function checkSqlExecutionGuards(query: string): string | null { |
| 130 | const rawTextError = getRawTextGuardError(query); |
| 131 | if (rawTextError) { |
| 132 | return rawTextError; |
| 133 | } |
| 134 | |
| 135 | try { |
| 136 | const { stmts } = parseSync(query); |
| 137 | |
| 138 | for (const stmtWrapper of stmts) { |
| 139 | const stmt = stmtWrapper.stmt as Record<string, unknown>; |
| 140 | const [stmtType, data] = Object.entries(stmt)[0] as [string, Record<string, unknown>]; |
| 141 | |
| 142 | if (DATABASE_MANAGEMENT_STATEMENTS.has(stmtType)) { |
| 143 | return 'Query contains restricted operations'; |
| 144 | } |
| 145 | |
| 146 | if (stmtType === 'VariableSetStmt') { |
| 147 | if (data.kind === 'VAR_RESET_ALL') { |
| 148 | return 'RESET ALL is not allowed.'; |
| 149 | } |
| 150 | |
| 151 | const name = ((data.name as string | undefined) ?? '').toLowerCase(); |
| 152 | if (EXECUTION_CONTEXT_VARIABLES.has(name)) { |
| 153 | return 'Changing SQL execution role or session authorization is not allowed.'; |
| 154 | } |
| 155 | if (name === SEARCH_PATH_VARIABLE) { |
| 156 | return 'Changing SQL search_path is not allowed.'; |
| 157 | } |
| 158 | if (name === STATEMENT_TIMEOUT_VARIABLE) { |
| 159 | return 'Changing SQL statement_timeout is not allowed.'; |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | if (ROLE_MANAGEMENT_STATEMENTS.has(stmtType)) { |
| 164 | return 'Managing database roles is not allowed.'; |
| 165 | } |
| 166 | |
| 167 | if (stmtType === 'TransactionStmt') { |
| 168 | return 'Transaction control statements are not allowed.'; |
| 169 | } |
| 170 | } |
| 171 | |
| 172 | return null; |
| 173 | } catch (parseError) { |
| 174 | logger.warn('SQL parse error in checkSqlExecutionGuards, rejecting query:', parseError); |
| 175 | return 'Query could not be parsed and was rejected for security reasons.'; |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | /** |
| 180 | * Parse a SQL string into individual statements, properly handling: |
no test coverage detected