Skip to content

Commit 53ec051

Browse files
dhensbyclaude
andcommitted
fix: check a table's path where it is written into SQL
`create table` takes a table's path as it is, with either driver, and the tedious driver also writes it into `insert bulk`. A table built from a name always has a path with each part in brackets, but `path` is a plain property, so a path changed after the table was built reached the statement unchecked. The same was true of the table name that `declare()` writes into the name of a composite primary key constraint. The path is now checked as a qualified name where it is written, and before a connection is taken: each part must be bare, or in brackets or double quotes. A `]` in the constraint name must be doubled. Each value is read once, so the value checked is the value written. A path or name that fails raises EINJECT. The existence check that `create` runs first looks the table up by the path as a string. The paths and names that `new sql.Table()` builds are written as before. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent e105889 commit 53ec051

6 files changed

Lines changed: 266 additions & 16 deletions

File tree

‎README.md‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1949,6 +1949,18 @@ failure here releases the connection:
19491949
A name that fails one of these checks raises `EINJECT`. The `tedious` driver does not
19501950
make these checks.
19511951

1952+
### Table paths
1953+
1954+
`new sql.Table(name)` builds the table's `path` from the name, with each part in
1955+
brackets. `table.declare()` writes that path into a `create table` statement, which a bulk
1956+
load with `create` set sends with either driver. The `tedious` driver also writes the path
1957+
into the `insert bulk` statement of every bulk load. If you set `table.path` yourself, those
1958+
statements need it to be a qualified name: parts separated by `.`, each either bare, holding
1959+
only the characters a parameter name may, or in brackets or double quotes. A part between
1960+
two others may be empty, as in `db..table`, and space around the whole path is removed.
1961+
Anything else raises `EINJECT`. When `table.declare()` names a primary key constraint after
1962+
`table.name`, a `]` in that name must be written as `]]`.
1963+
19521964
### Type names and sizes
19531965

19541966
`sql.TVP()` takes the name of a table type, optionally qualified with a schema and

‎lib/msnodesqlv8/request.js‎

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ const debug = require('debug')('mssql:msv8')
55
const BaseRequest = require('../base/request')
66
const RequestError = require('../error/request-error')
77
const MSSQLError = require('../error/mssql-error')
8-
const { IDS, objectHasProperty, isValidParameterName, assertSafeColumnName, assertSafeTypeName, assertSafeTypeSize, assertSafeProcedureName } = require('../utils')
8+
const { IDS, objectHasProperty, isValidParameterName, assertSafeColumnName, assertSafeTableName, assertSafeTypeName, assertSafeTypeSize, assertSafeProcedureName } = require('../utils')
99
const { TYPES, DECLARATIONS, declare } = require('../datatypes')
1010
const { PARSERS: UDT } = require('../udt')
1111
const Table = require('../table')
@@ -241,6 +241,9 @@ class Request extends BaseRequest {
241241
assertSafeTypeSize(col.precision)
242242
assertSafeTypeSize(col.scale)
243243
})
244+
// `create table` takes the table's path and name as they are; they are checked again
245+
// where it is written. Without `create`, this driver writes neither into SQL.
246+
if (table.create) table.declare()
244247
// checked here too, so an ordering key is accepted or rejected the same way on
245248
// either driver even though this one does not build the statement itself
246249
if (options && options.order) {
@@ -353,17 +356,12 @@ class Request extends BaseRequest {
353356
}
354357

355358
if (table.create) {
356-
let objectid
357-
if (table.temporary) {
358-
objectid = `tempdb..[${table.name}]`
359-
} else {
360-
objectid = table.path
361-
}
362-
363-
// A connection is held from here on, so a column name that changed since it
364-
// was checked above must be reported through `done`, which releases it.
359+
// A connection is held from here on, so a column name, or the path, that changed
360+
// since it was checked above must be reported through `done`, which releases it.
365361
let statement
366362
try {
363+
// the path as it is checked and written, so the table looked up is the one created
364+
const objectid = table.temporary ? `tempdb..[${table.name}]` : assertSafeTableName(table.path)
367365
statement = `if object_id('${objectid.replace(/'/g, '\'\'')}') is null ${table.declare()}`
368366
} catch (e) {
369367
return done(e)

‎lib/table.js‎

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22

33
const TYPES = require('./datatypes').TYPES
44
const declareType = require('./datatypes').declare
5-
const { objectHasProperty, assertSafeColumnName } = require('./utils')
5+
const MSSQLError = require('./error/mssql-error')
6+
const { objectHasProperty, assertSafeColumnName, assertSafeTableName } = require('./utils')
67

78
const MAX = 65535 // (1 << 16) - 1
89
const JSON_COLUMN_ID = 'JSON_F52E2B61-18A1-11d1-B105-00805F49916B'
@@ -99,6 +100,12 @@ Table.prototype._makeBulk = function _makeBulk () {
99100
}
100101

101102
Table.prototype.declare = function declare () {
103+
// The path and the name are written into the statement as they are. A table built from a name
104+
// always has safe ones, but both are plain properties that can be changed after that, so they
105+
// are checked here, where they are written: the path as a qualified name, and the name, which
106+
// goes into the brackets of the primary key constraint's name, as a column name goes into its
107+
// own brackets. Each is read once, so the value checked is the value written.
108+
const path = assertSafeTableName(this.path)
102109
const pkey = this.columns.filter(col => col.primary === true).map(col => `[${assertSafeColumnName(col.name)}]`)
103110
const cols = this.columns.map(col => {
104111
const def = [`[${assertSafeColumnName(col.name)}] ${declareType(col.type, col)}`]
@@ -116,8 +123,17 @@ Table.prototype.declare = function declare () {
116123
return def.join(' ')
117124
})
118125

119-
const constraint = pkey.length > 1 ? `, constraint [PK_${this.temporary ? this.name.substr(1) : this.name}] primary key (${pkey.join(', ')})` : ''
120-
return `create table ${this.path} (${cols.join(', ')}${constraint})`
126+
let constraint = ''
127+
if (pkey.length > 1) {
128+
const name = String(this.name)
129+
// checked as it is written, after the `#` of a temporary table's name is dropped
130+
const constraintName = `PK_${this.temporary ? name.substr(1) : name}`
131+
if (constraintName.replace(/]]/g, '').includes(']')) {
132+
throw new MSSQLError(`Invalid table name '${name}'. A ']' in a table name must be written as ']]'.`, 'EINJECT')
133+
}
134+
constraint = `, constraint [${constraintName}] primary key (${pkey.join(', ')})`
135+
}
136+
return `create table ${path} (${cols.join(', ')}${constraint})`
121137
}
122138

123139
Table.fromRecordset = function fromRecordset (recordset, name) {

‎lib/tedious/request.js‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ const tds = require('tedious')
44
const debug = require('debug')('mssql:tedi')
55
const BaseRequest = require('../base/request')
66
const RequestError = require('../error/request-error')
7-
const { IDS, objectHasProperty, assertSafeColumnName, assertSafeTypeName, assertSafeTypeSize, assertSafeProcedureName } = require('../utils')
7+
const { IDS, objectHasProperty, assertSafeColumnName, assertSafeTableName, assertSafeTypeName, assertSafeTypeSize, assertSafeProcedureName } = require('../utils')
88
const { TYPES, DECLARATIONS, declare, cast } = require('../datatypes')
99
const Table = require('../table')
1010
const { PARSERS: UDT } = require('../udt')
@@ -222,6 +222,10 @@ class Request extends BaseRequest {
222222
// Checked before a connection is borrowed, so that a rejected name cannot leave
223223
// the pool short of one.
224224
table.columns.forEach(col => assertSafeColumnName(col.name))
225+
// tedious writes the path as it is into `insert bulk`, and so does `create table`, which
226+
// also takes the table's name; both are checked again where they are written.
227+
assertSafeTableName(table.path)
228+
if (table.create) table.declare()
225229
// tedious writes these into `insert bulk ... WITH (ORDER (<key> <direction>))`
226230
// UNQUOTED — unlike a column name, which it emits as `[name]`. So the quoted-identifier
227231
// rule does not apply here: what matters is that the key cannot end the clause. It is
@@ -355,7 +359,7 @@ class Request extends BaseRequest {
355359
.map(([key, direction]) => [assertSafeTypeName(key), direction]))
356360
})
357361
}
358-
bulk = connection.newBulkLoad(table.path, bulkOptions, done)
362+
bulk = connection.newBulkLoad(assertSafeTableName(table.path), bulkOptions, done)
359363
for (const col of table.columns) {
360364
// tedious emits this name as a quoted identifier of its own when it builds
361365
// the `insert bulk` statement, so it is checked here as well as in
@@ -364,7 +368,8 @@ class Request extends BaseRequest {
364368
}
365369

366370
if (table.create) {
367-
const objectid = table.temporary ? `tempdb..[${table.name}]` : table.path
371+
// the path as it is checked and written, so the table looked up is the one created
372+
const objectid = table.temporary ? `tempdb..[${table.name}]` : assertSafeTableName(table.path)
368373
statement = `if object_id('${objectid.replace(/'/g, '\'\'')}') is null ${table.declare()}`
369374
}
370375
} catch (e) {

‎lib/utils.js‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@ const QUALIFIED_NAME_PART = '(?:\\[(?:[^\\]]|\\]\\])*\\]|"(?:[^"]|"")*"|[\\p{L}\
3030
// T-SQL — but the first and last parts must be present, so a bare `.`, a leading `.proc`
3131
// and a trailing `db..` are still refused. An empty part cannot end the identifier.
3232
const QUALIFIED_NAME = new RegExp(`^(?:${QUALIFIED_NAME_PART}(?:\\.${QUALIFIED_NAME_PART}?)*\\.)?${QUALIFIED_NAME_PART}$`, 'u')
33+
// A table's path has the same form, but a bare part may hold every character a parameter name
34+
// may (see PARAM_NAME above), which the server reads as part of an identifier.
35+
const TABLE_NAME_PART = '(?:\\[(?:[^\\]]|\\]\\])*\\]|"(?:[^"]|"")*"|(?:[\\p{L}\\p{N}\\p{M}\\p{Pc}@#$・・]|\\u200C|\\u200D)+)'
36+
const TABLE_NAME = new RegExp(`^(?:${TABLE_NAME_PART}(?:\\.${TABLE_NAME_PART}?)*\\.)?${TABLE_NAME_PART}$`, 'u')
3337

3438
// A length, precision or scale is emitted into the same declaration. `max` is the only
3539
// word the declaration takes there; everything else the server wants is a number.
@@ -74,6 +78,17 @@ module.exports = {
7478
}
7579
return procedure
7680
},
81+
assertSafeTableName: (name) => {
82+
// A table's path is written as it is into `create table` and into tedious's `insert bulk`.
83+
// A table built from a name always has a path whose parts are in brackets, but `path` is a
84+
// plain property that can be changed after that, so it is checked where it is written.
85+
// Read once, and return what was read, for the same reason as the type name.
86+
const table = String(name).trim()
87+
if (!TABLE_NAME.test(table)) {
88+
throw new MSSQLError(`Invalid table name '${table}'. A table name may only contain identifier characters, unless a part is in brackets or double quotes.`, 'EINJECT')
89+
}
90+
return table
91+
},
7792
assertSafeTypeSize: (value) => {
7893
if (value == null || typeof value === 'number') {
7994
return value

0 commit comments

Comments
 (0)