mssql 9.1.3 → 9.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Microsoft SQL Server client for Node.js
4
4
 
5
- [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Appveyor CI][appveyor-image]][appveyor-url] [![Join the chat at https://gitter.im/patriksimek/node-mssql](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/patriksimek/node-mssql?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
5
+ [![NPM Version][npm-image]][npm-url] [![NPM Downloads][downloads-image]][downloads-url] [![Join the chat at https://gitter.im/patriksimek/node-mssql](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/patriksimek/node-mssql?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
6
6
 
7
7
  Supported TDS drivers:
8
8
  - [Tedious][tedious-url] (pure JavaScript - Windows/macOS/Linux, default)
@@ -108,6 +108,13 @@ async () => {
108
108
  * [bulk](#bulk-table-options-callback)
109
109
  * [cancel](#cancel)
110
110
 
111
+ ### Identifier rules
112
+
113
+ * [Parameter names](#parameter-names)
114
+ * [Column names](#column-names)
115
+ * [Type names and sizes](#type-names-and-sizes)
116
+ * [Procedure names](#procedure-names)
117
+
111
118
  ### Transactions
112
119
 
113
120
  * [Transaction](#transaction)
@@ -746,6 +753,7 @@ request.execute('procedure_name', (err, result) => {
746
753
 
747
754
  __Errors__
748
755
  - EREQUEST (`RequestError`) - *Message from SQL Server*
756
+ - EINJECT (`RequestError`) - Procedure name or parameter type is not a valid identifier. See [Identifiers](#identifiers).
749
757
  - ECANCEL (`RequestError`) - Cancelled.
750
758
  - ETIMEOUT (`RequestError`) - Request timeout.
751
759
  - ENOCONN (`RequestError`) - No connection is specified for that request.
@@ -798,7 +806,7 @@ sql.map.register(Number, sql.BigInt)
798
806
 
799
807
  __Errors__ (synchronous)
800
808
  - EARGS (`RequestError`) - Invalid number of arguments.
801
- - EINJECT (`RequestError`) - SQL injection warning.
809
+ - EINJECT (`RequestError`) - Parameter name is not a valid identifier. See [Identifiers](#identifiers).
802
810
 
803
811
  ---------------------------------------
804
812
 
@@ -823,7 +831,7 @@ request.output('output_parameter', sql.VarChar(50), 'abc')
823
831
 
824
832
  __Errors__ (synchronous)
825
833
  - EARGS (`RequestError`) - Invalid number of arguments.
826
- - EINJECT (`RequestError`) - SQL injection warning.
834
+ - EINJECT (`RequestError`) - Parameter name is not a valid identifier. See [Identifiers](#identifiers).
827
835
 
828
836
  ---------------------------------------
829
837
 
@@ -907,6 +915,7 @@ __Errors__
907
915
  - ECONNCLOSED (`ConnectionError`) - Connection is closed.
908
916
  - ENOTBEGUN (`TransactionError`) - Transaction has not begun.
909
917
  - EABORT (`TransactionError`) - Transaction was aborted (by user or because of an error).
918
+ - EINJECT (`RequestError`) - Parameter type is not a valid identifier. See [Identifiers](#identifiers).
910
919
 
911
920
  ```javascript
912
921
  const request = new sql.Request()
@@ -952,6 +961,7 @@ __Errors__
952
961
  - ECONNCLOSED (`ConnectionError`) - Connection is closed.
953
962
  - ENOTBEGUN (`TransactionError`) - Transaction has not begun.
954
963
  - EABORT (`TransactionError`) - Transaction was aborted (by user or because of an error).
964
+ - EINJECT (`RequestError`) - Parameter type is not a valid identifier. See [Identifiers](#identifiers).
955
965
 
956
966
  You can enable multiple recordsets in queries with the `request.multiple = true` command.
957
967
 
@@ -998,6 +1008,7 @@ __Errors__
998
1008
  - ECONNCLOSED (`ConnectionError`) - Connection is closed.
999
1009
  - ENOTBEGUN (`TransactionError`) - Transaction has not begun.
1000
1010
  - EABORT (`TransactionError`) - Transaction was aborted (by user or because of an error).
1011
+ - EINJECT (`RequestError`) - Table name, column name or parameter type is not a valid identifier. See [Identifiers](#identifiers).
1001
1012
 
1002
1013
  ---------------------------------------
1003
1014
 
@@ -1088,6 +1099,16 @@ transaction.begin(err => {
1088
1099
  })
1089
1100
  ```
1090
1101
 
1102
+ __Transaction name__
1103
+
1104
+ Set `transaction.name` before calling `begin` to give the transaction a name. The server shows it in `sys.dm_tran_active_transactions`. It must be a string of at most 32 characters, counted in UTF-16 code units, or `null` or `undefined` for no name. The `msnodesqlv8` driver doesn't send it. See [Transaction names](#transaction-names).
1105
+
1106
+ ```javascript
1107
+ const transaction = new sql.Transaction(/* [pool] */)
1108
+ transaction.name = 'nightly import'
1109
+ await transaction.begin()
1110
+ ```
1111
+
1091
1112
  ### Events
1092
1113
 
1093
1114
  - **begin** - Dispatched when transaction begin.
@@ -1117,6 +1138,7 @@ transaction.begin(err => {
1117
1138
  __Errors__
1118
1139
  - ENOTOPEN (`ConnectionError`) - Connection not yet open.
1119
1140
  - EALREADYBEGUN (`TransactionError`) - Transaction has already begun.
1141
+ - EINJECT (`TransactionError`) - Transaction name is not a string, or is longer than 32 characters (`tedious` driver). See [Transaction names](#transaction-names).
1120
1142
 
1121
1143
  ---------------------------------------
1122
1144
 
@@ -1228,7 +1250,7 @@ ps.input('input_parameter', sql.VarChar(50))
1228
1250
 
1229
1251
  __Errors__ (synchronous)
1230
1252
  - EARGS (`PreparedStatementError`) - Invalid number of arguments.
1231
- - EINJECT (`PreparedStatementError`) - SQL injection warning.
1253
+ - EINJECT (`PreparedStatementError`) - Parameter name is not a valid identifier. See [Identifiers](#identifiers).
1232
1254
 
1233
1255
  ---------------------------------------
1234
1256
 
@@ -1250,7 +1272,7 @@ ps.output('output_parameter', sql.VarChar(50))
1250
1272
 
1251
1273
  __Errors__ (synchronous)
1252
1274
  - EARGS (`PreparedStatementError`) - Invalid number of arguments.
1253
- - EINJECT (`PreparedStatementError`) - SQL injection warning.
1275
+ - EINJECT (`PreparedStatementError`) - Parameter name is not a valid identifier. See [Identifiers](#identifiers).
1254
1276
 
1255
1277
  ---------------------------------------
1256
1278
 
@@ -1823,6 +1845,182 @@ Results in:
1823
1845
  ]
1824
1846
  ```
1825
1847
 
1848
+ ## Identifiers
1849
+
1850
+ Values are sent to the server as parameters and may hold anything. A few things
1851
+ are not values, and cannot be: the name of a parameter, the name of a table or a
1852
+ column in a bulk load, the type a parameter is declared as, the name of a stored
1853
+ procedure, and the name of a transaction. Those are *identifiers*, and
1854
+ no SQL database can bind them, so this library builds them into the statement it
1855
+ sends. It checks them, and rejects anything that could end the identifier and have
1856
+ the rest of the value read as SQL.
1857
+
1858
+ That check is not a substitute for your own. If any of these comes from somewhere
1859
+ you do not control, map it to a value you expect first:
1860
+
1861
+ ```javascript
1862
+ const columns = { name: 'name', created: 'created_at' } // what you allow
1863
+ const column = columns[req.query.sortBy] // what they asked for
1864
+ if (!column) throw new Error('unknown column')
1865
+
1866
+ request.input(column, sql.NVarChar, value)
1867
+ ```
1868
+
1869
+ ### Parameter names
1870
+
1871
+ `request.input()`, `request.output()` and the same methods on a prepared statement
1872
+ take a name without the leading `@`. It may hold letters, digits, marks and
1873
+ connector punctuation from any script, along with `@`, `#`, `$` and the two
1874
+ zero-width joiners. A name that is not a string or a number is rejected, as is one
1875
+ holding an invisible format character, because one of them is a separator the
1876
+ server treats as ending the identifier.
1877
+
1878
+ Anything else raises `EINJECT`. Note that a name this library accepts may still be
1879
+ one the server rejects; the check is deliberately wider than the server's own rules
1880
+ so that it only refuses what could change the shape of the statement.
1881
+
1882
+ ### Column names
1883
+
1884
+ `table.columns.add()` names a column in a bulk load, and the name is emitted as a
1885
+ quoted identifier. A `]` ends that quoting, so a name holding one must double it,
1886
+ which is how T-SQL escapes it:
1887
+
1888
+ ```javascript
1889
+ table.columns.add('a]]b', sql.Int) // the column named a]b
1890
+ ```
1891
+
1892
+ A single `]` raises `EINJECT`. Column names are not otherwise restricted: spaces,
1893
+ punctuation and reserved words are all fine, because the quoting handles them.
1894
+
1895
+ With the `msnodesqlv8` driver, a bulk load into a column whose name holds a `]`
1896
+ raises `EINJECT`, because that driver cannot write such a name. See
1897
+ [Bulk load table names](#bulk-load-table-names).
1898
+
1899
+ The keys of `options.order` are also identifiers, but the driver writes them into the bulk
1900
+ statement's `ORDER (...)` clause *unquoted* rather than as `[name]`. They follow the type
1901
+ name rule instead: bare, or quoted with brackets or double quotes.
1902
+
1903
+ ```javascript
1904
+ request.bulk(table, { order: { created_at: 'ASC' } })
1905
+ request.bulk(table, { order: { '[Created At]': 'DESC' } }) // quote a spaced name yourself
1906
+ ```
1907
+
1908
+ ### Bulk load table names
1909
+
1910
+ With the `msnodesqlv8` driver, a bulk load finds its table through the driver's table
1911
+ manager. The table manager writes the table name into a query of its own, and then
1912
+ writes an `INSERT` from what it found. This library gives it the name without its
1913
+ brackets, and the table manager splits that name on every `.`. Before a connection is
1914
+ taken, this library checks each part:
1915
+
1916
+ - The table and schema names are written into a quoted string, so they must not hold a
1917
+ single `'`. The table manager reads a doubled `''` as one `'`. The `tedious` driver
1918
+ does not, so there the same name is a different table.
1919
+ - The database name is written unquoted. It may hold the characters a parameter name
1920
+ may, with space around it, or it may be in double quotes. It must not hold a `'`. Any
1921
+ part before the database is checked in the same way. The table manager reads double
1922
+ quotes as quoting, but the `tedious` driver reads them as part of the name.
1923
+ - The name of a temporary table, one that starts with `#`, is written unquoted into the
1924
+ `INSERT`, so every part may hold only the characters a parameter name may.
1925
+ - No part may hold a `$` followed by a backtick, a `'` or a `&`. The table manager
1926
+ replaces each of these pairs with a part of its own query.
1927
+
1928
+ ```javascript
1929
+ // what request.bulk(table) does with the msnodesqlv8 driver, for each of these tables
1930
+ new sql.Table('dbo.[My Table]') // fine
1931
+ new sql.Table("[O'Brien]") // EINJECT: a single ' in the table name
1932
+ new sql.Table('[my db].dbo.orders') // EINJECT: a space in an unquoted database name
1933
+ new sql.Table('[#my temp]') // EINJECT: a space in a temporary table name
1934
+ ```
1935
+
1936
+ When the table manager has found the table, this library checks what it found. A
1937
+ failure here releases the connection:
1938
+
1939
+ - A table in `tempdb` is written into the `INSERT` as the name you gave, so each part of
1940
+ that name is checked as the database name is. This applies when the connection's own
1941
+ database is `tempdb`, too.
1942
+ - Any other table is written as `[database].[schema].[table]`, from the names the
1943
+ server reported, without doubling a `]`. A table whose database, schema or table name
1944
+ holds a `]` is rejected.
1945
+ - Each column the driver writes to is written as `[name]`, without doubling a `]`, so a
1946
+ column whose name holds one is rejected. The driver does not write to identity,
1947
+ computed and other read-only columns, so their names may hold one.
1948
+
1949
+ A name that fails one of these checks raises `EINJECT`. The `tedious` driver does not
1950
+ make these checks.
1951
+
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
+
1964
+ ### Type names and sizes
1965
+
1966
+ `sql.TVP()` takes the name of a table type, optionally qualified with a schema and
1967
+ optionally quoted with brackets or double quotes. A size — the length, precision or
1968
+ scale of a type such as `sql.VarChar()` — must be a number, or the word `max` the
1969
+ declaration accepts in its place. Padding is trimmed.
1970
+
1971
+ ```javascript
1972
+ request.input('rows', sql.TVP('dbo.[My Type]'), table)
1973
+ request.input('name', sql.VarChar(50), value)
1974
+ request.input('note', sql.VarChar('max'), value)
1975
+ ```
1976
+
1977
+ A size is checked wherever it is built into SQL, which includes the declaration a
1978
+ bulk load sends and the parameter list a query sends, not only `sql.TVP()`.
1979
+
1980
+ A type that is not one of `sql.TYPES` is declared with its own `declaration`. That
1981
+ declaration is checked by the same rule as the name of a table type, and may end with a
1982
+ size in parentheses: one or two numbers, or `max`, as in `nvarchar(50)` or
1983
+ `decimal(10, 2)`. A type given directly as a `tedious` type is declared by `tedious`
1984
+ itself, not by this library.
1985
+
1986
+ ### Procedure names
1987
+
1988
+ `request.execute()` takes the name of a stored procedure, optionally qualified with
1989
+ a server, database and schema and optionally quoted with brackets or double quotes.
1990
+ An omitted part may be left empty, as T-SQL allows. The `msnodesqlv8` driver builds
1991
+ this into the statement it sends; the `tedious` driver sends it as a bound remote
1992
+ procedure call and could not be injected through it. Both check it, so a name is
1993
+ accepted or rejected the same way whichever driver you use.
1994
+
1995
+ ```javascript
1996
+ request.execute('dbo.[My Procedure]')
1997
+ request.execute('master..sp_who') // an omitted schema is fine
1998
+ ```
1999
+
2000
+ The first and last parts must be present, so `.proc` and `db..` are rejected.
2001
+
2002
+ Anything else raises `EINJECT`. Numbered procedures — the deprecated
2003
+ `procedure;1` form — are rejected, because the `;` cannot be told apart from the
2004
+ end of a statement.
2005
+
2006
+ ### Transaction names
2007
+
2008
+ With the `tedious` driver, `transaction.name` must be a string of at most 32
2009
+ characters, counted in UTF-16 code units, or `null` or `undefined` for no name;
2010
+ anything else raises `EINJECT` before a connection is taken. The server refuses a
2011
+ longer name. From TDS 7.2 (the default `tdsVersion` is `7_4`) the driver sends the
2012
+ name to the server as data, so it may hold any character. On a connection that uses
2013
+ TDS 7.1, because `options.tdsVersion`
2014
+ is `7_1` or because the server supports nothing newer, the driver builds the name
2015
+ into a `BEGIN TRAN` statement instead, so there it is sent as a quoted identifier
2016
+ with any `]` doubled. It cannot end the statement, and the server stores the name
2017
+ exactly as given, as it does on newer TDS versions, except that over TDS 7.1 it
2018
+ refuses a name containing a NUL character or U+FFFF.
2019
+
2020
+ The `msnodesqlv8` driver doesn't send the name.
2021
+
2022
+ ---------------------------------------
2023
+
1826
2024
  ## Errors
1827
2025
 
1828
2026
  There are 4 types of errors you can handle:
@@ -1855,14 +2053,15 @@ Name | Code | Message
1855
2053
  `TransactionError` | EALREADYBEGUN | Transaction has already begun.
1856
2054
  `TransactionError` | EREQINPROG | Can't commit/rollback transaction. There is a request in progress.
1857
2055
  `TransactionError` | EABORT | Transaction has been aborted.
2056
+ `TransactionError` | EINJECT | Transaction name is not a string, or is longer than 32 characters.
1858
2057
  `RequestError` | EREQUEST | Message from SQL Server. Error object contains additional details.
1859
2058
  `RequestError` | ECANCEL | Cancelled.
1860
2059
  `RequestError` | ETIMEOUT | Request timeout.
1861
2060
  `RequestError` | EARGS | Invalid number of arguments.
1862
- `RequestError` | EINJECT | SQL injection warning.
2061
+ `RequestError` | EINJECT | Parameter name, table name, column name or type is not a valid identifier.
1863
2062
  `RequestError` | ENOCONN | No connection is specified for that request.
1864
2063
  `PreparedStatementError` | EARGS | Invalid number of arguments.
1865
- `PreparedStatementError` | EINJECT | SQL injection warning.
2064
+ `PreparedStatementError` | EINJECT | Parameter name is not a valid identifier.
1866
2065
  `PreparedStatementError` | EALREADYPREPARED | Statement is already prepared.
1867
2066
  `PreparedStatementError` | ENOTPREPARED | Statement is not prepared.
1868
2067
 
@@ -2093,8 +2292,6 @@ to create new connections or not
2093
2292
  [downloads-url]: https://www.npmjs.com/package/mssql
2094
2293
  [david-image]: https://img.shields.io/david/tediousjs/node-mssql.svg?style=flat-square
2095
2294
  [david-url]: https://david-dm.org/tediousjs/node-mssql
2096
- [appveyor-image]: https://ci.appveyor.com/api/projects/status/e5gq1a0ujwams9t7/branch/master?svg=true
2097
- [appveyor-url]: https://ci.appveyor.com/project/tediousjs/node-mssql
2098
2295
 
2099
2296
  [tedious-url]: https://www.npmjs.com/package/tedious
2100
2297
  [msnodesqlv8-url]: https://www.npmjs.com/package/msnodesqlv8
@@ -2,7 +2,7 @@
2
2
 
3
3
  const debug = require('debug')('mssql:base')
4
4
  const { EventEmitter } = require('events')
5
- const { IDS, objectHasProperty } = require('../utils')
5
+ const { IDS, objectHasProperty, isValidParameterName } = require('../utils')
6
6
  const globalConnection = require('../global-connection')
7
7
  const { TransactionError, PreparedStatementError } = require('../error')
8
8
  const shared = require('../shared')
@@ -91,8 +91,8 @@ class PreparedStatement extends EventEmitter {
91
91
  */
92
92
 
93
93
  input (name, type) {
94
- if ((/(--| |\/\*|\*\/|')/).test(name)) {
95
- throw new PreparedStatementError(`SQL injection warning for param '${name}'`, 'EINJECT')
94
+ if (!isValidParameterName(name)) {
95
+ throw new PreparedStatementError(`Invalid parameter name '${name}'. Parameter names may only contain identifier characters`, 'EINJECT')
96
96
  }
97
97
 
98
98
  if (arguments.length < 2) {
@@ -144,8 +144,8 @@ class PreparedStatement extends EventEmitter {
144
144
  */
145
145
 
146
146
  output (name, type) {
147
- if (/(--| |\/\*|\*\/|')/.test(name)) {
148
- throw new PreparedStatementError(`SQL injection warning for param '${name}'`, 'EINJECT')
147
+ if (!isValidParameterName(name)) {
148
+ throw new PreparedStatementError(`Invalid parameter name '${name}'. Parameter names may only contain identifier characters`, 'EINJECT')
149
149
  }
150
150
 
151
151
  if (arguments.length < 2) {
@@ -235,17 +235,25 @@ class PreparedStatement extends EventEmitter {
235
235
  const req = new shared.driver.Request(this)
236
236
  req.stream = false
237
237
  req.output('handle', TYPES.Int)
238
- req.input('params', TYPES.NVarChar, ((() => {
239
- const result = []
238
+ let params
239
+ try {
240
+ params = []
240
241
  for (const name in this.parameters) {
241
242
  if (!objectHasProperty(this.parameters, name)) {
242
243
  continue
243
244
  }
244
245
  const param = this.parameters[name]
245
- result.push(`@${name} ${declare(param.type, param)}${param.io === 2 ? ' output' : ''}`)
246
+ // a connection is held here, so a rejected declaration has to be reported
247
+ // through the path that releases it
248
+ params.push(`@${name} ${declare(param.type, param)}${param.io === 2 ? ' output' : ''}`)
246
249
  }
247
- return result
248
- })()).join(','))
250
+ } catch (e) {
251
+ this.parent.release(this._acquiredConnection)
252
+ this._acquiredConnection = null
253
+ this._acquiredConfig = null
254
+ return callback(new PreparedStatementError(e, 'EREQUEST'))
255
+ }
256
+ req.input('params', TYPES.NVarChar, params.join(','))
249
257
  req.input('stmt', TYPES.NVarChar, this.statement)
250
258
  req.execute('sp_prepare', (err, result) => {
251
259
  if (err) {
@@ -3,7 +3,7 @@
3
3
  const debug = require('debug')('mssql:base')
4
4
  const { EventEmitter } = require('events')
5
5
  const { Readable } = require('stream')
6
- const { IDS, objectHasProperty } = require('../utils')
6
+ const { IDS, objectHasProperty, isValidParameterName } = require('../utils')
7
7
  const globalConnection = require('../global-connection')
8
8
  const { RequestError, ConnectionError } = require('../error')
9
9
  const { TYPES } = require('../datatypes')
@@ -107,8 +107,8 @@ class Request extends EventEmitter {
107
107
  */
108
108
 
109
109
  input (name, type, value) {
110
- if ((/(--| |\/\*|\*\/|')/).test(name)) {
111
- throw new RequestError(`SQL injection warning for param '${name}'`, 'EINJECT')
110
+ if (!isValidParameterName(name)) {
111
+ throw new RequestError(`Invalid parameter name '${name}'. Parameter names may only contain identifier characters`, 'EINJECT')
112
112
  }
113
113
 
114
114
  if (arguments.length < 2) {
@@ -170,8 +170,8 @@ class Request extends EventEmitter {
170
170
  output (name, type, value) {
171
171
  if (!type) { type = TYPES.NVarChar }
172
172
 
173
- if ((/(--| |\/\*|\*\/|')/).test(name)) {
174
- throw new RequestError(`SQL injection warning for param '${name}'`, 'EINJECT')
173
+ if (!isValidParameterName(name)) {
174
+ throw new RequestError(`Invalid parameter name '${name}'. Parameter names may only contain identifier characters`, 'EINJECT')
175
175
  }
176
176
 
177
177
  if ((type === TYPES.Text) || (type === TYPES.NText) || (type === TYPES.Image)) {
package/lib/datatypes.js CHANGED
@@ -1,5 +1,5 @@
1
1
  'use strict'
2
- const objectHasProperty = require('./utils').objectHasProperty
2
+ const { objectHasProperty, assertSafeTypeName, assertSafeTypeDeclaration, assertSafeTypeSize } = require('./utils')
3
3
  const inspect = Symbol.for('nodejs.util.inspect.custom')
4
4
 
5
5
  const TYPES = {
@@ -132,21 +132,37 @@ for (const key in TYPES) {
132
132
  }
133
133
 
134
134
  module.exports.declare = (type, options) => {
135
+ // sizes and the type name reach the generated declaration directly, so they are checked
136
+ // here rather than trusted from whatever built the parameter. Each is read only in the
137
+ // branch that emits it, so a type that takes no size still needs no options.
135
138
  switch (type) {
136
- case TYPES.VarChar: case TYPES.VarBinary:
137
- return `${type.declaration} (${options.length > 8000 ? 'MAX' : (options.length == null ? 'MAX' : options.length)})`
138
- case TYPES.NVarChar:
139
- return `${type.declaration} (${options.length > 4000 ? 'MAX' : (options.length == null ? 'MAX' : options.length)})`
140
- case TYPES.Char: case TYPES.NChar: case TYPES.Binary:
141
- return `${type.declaration} (${options.length == null ? 1 : options.length})`
142
- case TYPES.Decimal: case TYPES.Numeric:
143
- return `${type.declaration} (${options.precision == null ? 18 : options.precision}, ${options.scale == null ? 0 : options.scale})`
144
- case TYPES.Time: case TYPES.DateTime2: case TYPES.DateTimeOffset:
145
- return `${type.declaration} (${options.scale == null ? 7 : options.scale})`
139
+ case TYPES.VarChar: case TYPES.VarBinary: {
140
+ const length = assertSafeTypeSize(options.length)
141
+ return `${type.declaration} (${length > 8000 ? 'MAX' : (length == null ? 'MAX' : length)})`
142
+ }
143
+ case TYPES.NVarChar: {
144
+ const length = assertSafeTypeSize(options.length)
145
+ return `${type.declaration} (${length > 4000 ? 'MAX' : (length == null ? 'MAX' : length)})`
146
+ }
147
+ case TYPES.Char: case TYPES.NChar: case TYPES.Binary: {
148
+ const length = assertSafeTypeSize(options.length)
149
+ return `${type.declaration} (${length == null ? 1 : length})`
150
+ }
151
+ case TYPES.Decimal: case TYPES.Numeric: {
152
+ const precision = assertSafeTypeSize(options.precision)
153
+ const scale = assertSafeTypeSize(options.scale)
154
+ return `${type.declaration} (${precision == null ? 18 : precision}, ${scale == null ? 0 : scale})`
155
+ }
156
+ case TYPES.Time: case TYPES.DateTime2: case TYPES.DateTimeOffset: {
157
+ const scale = assertSafeTypeSize(options.scale)
158
+ return `${type.declaration} (${scale == null ? 7 : scale})`
159
+ }
146
160
  case TYPES.TVP:
147
- return `${options.tvpType} readonly`
161
+ return `${assertSafeTypeName(options.tvpType)} readonly`
148
162
  default:
149
- return type.declaration
163
+ // Every type in TYPES has a declaration of one word. Any other object passed as a type
164
+ // writes its own, so it is checked, and read once.
165
+ return assertSafeTypeDeclaration(type.declaration)
150
166
  }
151
167
  }
152
168
 
@@ -4,7 +4,8 @@ const msnodesql = require('msnodesqlv8')
4
4
  const debug = require('debug')('mssql:msv8')
5
5
  const BaseRequest = require('../base/request')
6
6
  const RequestError = require('../error/request-error')
7
- const { IDS, objectHasProperty } = require('../utils')
7
+ const MSSQLError = require('../error/mssql-error')
8
+ const { IDS, objectHasProperty, isValidParameterName, assertSafeColumnName, assertSafeTableName, assertSafeTypeName, assertSafeTypeSize, assertSafeProcedureName } = require('../utils')
8
9
  const { TYPES, DECLARATIONS, declare } = require('../datatypes')
9
10
  const { PARSERS: UDT } = require('../udt')
10
11
  const Table = require('../table')
@@ -14,6 +15,81 @@ const JSON_COLUMN_ID = 'JSON_F52E2B61-18A1-11d1-B105-00805F49916B'
14
15
  const XML_COLUMN_ID = 'XML_F52E2B61-18A1-11d1-B105-00805F49916B'
15
16
  const EMPTY_BUFFER = Buffer.alloc(0)
16
17
 
18
+ // msnodesqlv8 bulk loads through its table manager, which looks the table up by writing the
19
+ // name it is given into the text of a query of its own, splitting it on every `.` to do so.
20
+ // The last part, the table, and the one before it, the schema, are written inside quoted
21
+ // strings, which only a `'` can end, and a doubled one is how a string holds it. The part
22
+ // before the schema is the database, which is written bare, as an identifier, and also inside
23
+ // one of those strings. Any part before the database is held to the same rule, although the
24
+ // table manager drops it. The name of a table in tempdb is also written bare, whole, as the
25
+ // target of the INSERT that the table manager builds once it has found the table. A bare part
26
+ // may hold the characters a parameter name may (see lib/utils.js): those that cannot end an
27
+ // identifier.
28
+ const isBarePart = part => isValidParameterName(part)
29
+ // The database, and each part of the name of a table in tempdb, may also have space around it,
30
+ // which is read as space between words, or be in double quotes. In double quotes it is a quoted
31
+ // identifier, which only a `"` can end, or, with QUOTED_IDENTIFIER off, a string where no string
32
+ // is allowed, so the query does not compile and nothing in it runs. Neither form may hold a `'`.
33
+ // The database is also written inside a string, which a `'` would end, and in the INSERT a `'`
34
+ // would start one. The server reads NEL and ZERO WIDTH SPACE as space too, but `\s` does not
35
+ // match them.
36
+ const PADDING = /^[\s\u0085\u200b]+|[\s\u0085\u200b]+$/g
37
+ const isDatabasePart = part => {
38
+ const trimmed = part.replace(PADDING, '')
39
+ return isBarePart(trimmed) || /^"[^"']+"$/.test(trimmed)
40
+ }
41
+ const endsQuotedString = part => part.replace(/''/g, '').includes('\'')
42
+ // The table manager puts each part into its query with String.prototype.replace. That reads $`
43
+ // in the part as the text of the query before the placeholder, $' as the text after it, and $&
44
+ // as the placeholder. A name that holds one of these does not name the table it seems to. The
45
+ // text it copies brings the quotes of the query with it, so these are rejected in every part.
46
+ const COPIES_QUERY = /\$[`'&]/
47
+
48
+ // Takes the name the table manager is to be given, and returns what was read, so the name it
49
+ // is given is the one that was checked.
50
+ const assertSafeBulkTable = (name) => {
51
+ const table = String(name)
52
+ const parts = table.split('.')
53
+ if (parts[parts.length - 1].charAt(0) === '#') {
54
+ if (!parts.every(isBarePart)) {
55
+ throw new MSSQLError(`Invalid table name '${table}'. msnodesqlv8 writes the name of a temporary table unquoted, so it may only contain identifier characters.`, 'EINJECT')
56
+ }
57
+ } else if (!parts.slice(0, -2).every(isDatabasePart)) {
58
+ throw new MSSQLError(`Invalid table name '${table}'. msnodesqlv8 writes the database name unquoted, so it may only contain identifier characters, or be in double quotes and contain no '.`, 'EINJECT')
59
+ } else if (parts.slice(-2).some(endsQuotedString)) {
60
+ throw new MSSQLError(`Invalid table name '${table}'. msnodesqlv8 writes the table and schema names into a quoted string, which a ' would end.`, 'EINJECT')
61
+ } else if (COPIES_QUERY.test(table)) {
62
+ throw new MSSQLError(`Invalid table name '${table}'. msnodesqlv8 replaces $\`, $' and $& in a table name with parts of its own query.`, 'EINJECT')
63
+ }
64
+ return table
65
+ }
66
+
67
+ // Checked once the table manager has found the table, against what it found, since that is
68
+ // what it builds its INSERT from. A table in tempdb is written as the name it was given, so
69
+ // each part of that name is held to the database rule above. The connection's own database
70
+ // can be tempdb, so the name need not say so. Any other table is written as
71
+ // `[database].[schema].[table]`, from the names the server reported, and each column it writes
72
+ // to as `[name]`. In both, any `]` in a name is left as it is. The columns it writes to are
73
+ // those it does not count as read only. A driver without `isReadOnly()` on its columns, such
74
+ // as 2.0.0, counts these flags instead.
75
+ const isReadOnlyColumn = col => typeof col.isReadOnly === 'function'
76
+ ? col.isReadOnly()
77
+ : (col.is_identity || col.is_computed || col.is_hidden || col.generated_always_type)
78
+
79
+ const assertSafeBulkInsert = (table, columns) => {
80
+ if (columns[0].table_catalog === 'tempdb' && !table.split('.').every(isDatabasePart)) {
81
+ throw new MSSQLError(`Invalid table name '${table}'. msnodesqlv8 writes the name of a table in tempdb unquoted, so each part may only contain identifier characters, or be in double quotes and contain no '.`, 'EINJECT')
82
+ }
83
+ if (columns[0].table_catalog !== 'tempdb' && ['table_catalog', 'table_schema', 'table_name'].some(k => String(columns[0][k]).includes(']'))) {
84
+ throw new MSSQLError(`Invalid table name '${columns[0].table_catalog}.${columns[0].table_schema}.${columns[0].table_name}'. msnodesqlv8 cannot bulk load into a table whose name contains ']'.`, 'EINJECT')
85
+ }
86
+ for (const col of columns) {
87
+ if (!isReadOnlyColumn(col) && String(col.name).includes(']')) {
88
+ throw new MSSQLError(`Invalid column name '${col.name}'. msnodesqlv8 cannot bulk load into a column whose name contains ']'.`, 'EINJECT')
89
+ }
90
+ }
91
+ }
92
+
17
93
  const castParameter = function (value, type) {
18
94
  if (value == null) {
19
95
  if ((type === TYPES.Binary) || (type === TYPES.VarBinary) || (type === TYPES.Image)) {
@@ -154,16 +230,46 @@ class Request extends BaseRequest {
154
230
 
155
231
  try {
156
232
  table._makeBulk()
233
+ // Checked before a connection is borrowed, so that a rejected name cannot leave
234
+ // the pool short of one.
235
+ table.columns.forEach(col => {
236
+ assertSafeColumnName(col.name)
237
+ // This driver hands the column definition to its table manager rather than writing
238
+ // it into SQL, so a size never reaches a statement here. It is checked all the same,
239
+ // so that a column either works on both drivers or on neither.
240
+ assertSafeTypeSize(col.length)
241
+ assertSafeTypeSize(col.precision)
242
+ assertSafeTypeSize(col.scale)
243
+ })
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()
247
+ // checked here too, so an ordering key is accepted or rejected the same way on
248
+ // either driver even though this one does not build the statement itself
249
+ if (options && options.order) {
250
+ Object.keys(options.order).forEach(key => assertSafeTypeName(key))
251
+ }
157
252
  } catch (e) {
158
253
  return callback(new RequestError(e, 'EREQUEST'))
159
254
  }
160
255
 
161
256
  if (!table.name) {
162
- setImmediate(callback, new RequestError('Table name must be specified for bulk insert.', 'ENAME'))
257
+ return setImmediate(callback, new RequestError('Table name must be specified for bulk insert.', 'ENAME'))
163
258
  }
164
259
 
165
260
  if (table.name.charAt(0) === '@') {
166
- setImmediate(callback, new RequestError("You can't use table variables for bulk insert.", 'ENAME'))
261
+ return setImmediate(callback, new RequestError("You can't use table variables for bulk insert.", 'ENAME'))
262
+ }
263
+
264
+ // The table manager is given the path with its brackets removed, as before, and it is
265
+ // given the string that is checked here. The check is made before a connection is
266
+ // borrowed, and on the path rather than where the table is built, because `path` is a
267
+ // plain property that can be changed after the table is built.
268
+ let target
269
+ try {
270
+ target = assertSafeBulkTable(table.path.replace(/\[|\]/g, ''))
271
+ } catch (e) {
272
+ return callback(new RequestError(e, 'EREQUEST'))
167
273
  }
168
274
 
169
275
  this.parent.acquire(this, (err, connection) => {
@@ -189,8 +295,11 @@ class Request extends BaseRequest {
189
295
  connection.hasError = true
190
296
  }
191
297
 
298
+ // a rejected identifier keeps its own code; anything else is a driver
299
+ // error, whose numeric code must not become the public one
300
+ const rejectedIdentifier = err.code === 'EINJECT'
192
301
  err = new RequestError(err)
193
- err.code = 'EREQUEST'
302
+ err.code = rejectedIdentifier ? 'EINJECT' : 'EREQUEST'
194
303
  }
195
304
 
196
305
  this.parent.release(connection)
@@ -204,20 +313,42 @@ class Request extends BaseRequest {
204
313
 
205
314
  const go = () => {
206
315
  const tm = connection.tableMgr()
207
- return tm.bind(table.path.replace(/\[|\]/g, ''), mgr => {
316
+ // the table manager reports a failed lookup as (null, err), not error first
317
+ return tm.bind(target, (mgr, err) => {
318
+ if (err) {
319
+ return done(err)
320
+ }
321
+
208
322
  if (mgr.columns.length === 0) {
209
323
  return done(new RequestError('Table was not found on the server.', 'ENAME'))
210
324
  }
211
325
 
212
326
  const rows = []
213
- for (const row of Array.from(table.rows)) {
214
- const item = {}
215
- for (let index = 0; index < table.columns.length; index++) {
216
- const col = table.columns[index]
217
- item[col.name] = row[index]
327
+ try {
328
+ assertSafeBulkInsert(target, mgr.columns)
329
+
330
+ for (const col of table.columns) {
331
+ // re-checked here for the same reason as the name below, in case the
332
+ // definition changed since it was checked above
333
+ assertSafeTypeSize(col.length)
334
+ assertSafeTypeSize(col.precision)
335
+ assertSafeTypeSize(col.scale)
218
336
  }
219
337
 
220
- rows.push(item)
338
+ for (const row of Array.from(table.rows)) {
339
+ const item = {}
340
+ for (let index = 0; index < table.columns.length; index++) {
341
+ const col = table.columns[index]
342
+ // this driver hands the name to its table manager rather than writing
343
+ // it into SQL, but it is checked here all the same: a name either
344
+ // works on both drivers or on neither
345
+ item[assertSafeColumnName(col.name)] = row[index]
346
+ }
347
+
348
+ rows.push(item)
349
+ }
350
+ } catch (e) {
351
+ return done(e)
221
352
  }
222
353
 
223
354
  mgr.insertRows(rows, done)
@@ -225,14 +356,18 @@ class Request extends BaseRequest {
225
356
  }
226
357
 
227
358
  if (table.create) {
228
- let objectid
229
- if (table.temporary) {
230
- objectid = `tempdb..[${table.name}]`
231
- } else {
232
- objectid = table.path
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.
361
+ let statement
362
+ 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)
365
+ statement = `if object_id('${objectid.replace(/'/g, '\'\'')}') is null ${table.declare()}`
366
+ } catch (e) {
367
+ return done(e)
233
368
  }
234
369
 
235
- return connection.queryRaw(`if object_id('${objectid.replace(/'/g, '\'\'')}') is null ${table.declare()}`, function (err) {
370
+ return connection.queryRaw(statement, function (err) {
236
371
  if (err) { return done(err) }
237
372
  go()
238
373
  })
@@ -314,12 +449,18 @@ class Request extends BaseRequest {
314
449
 
315
450
  if (!this._nested) {
316
451
  const input = []
317
- for (const name in this.parameters) {
318
- if (!objectHasProperty(this.parameters, name)) {
319
- continue
452
+ try {
453
+ for (const name in this.parameters) {
454
+ if (!objectHasProperty(this.parameters, name)) {
455
+ continue
456
+ }
457
+ const param = this.parameters[name]
458
+ // this callback is dispatched on its own tick, so a rejected declaration has
459
+ // to be handed back rather than thrown
460
+ input.push(`@${param.name} ${declare(param.type, param)}`)
320
461
  }
321
- const param = this.parameters[name]
322
- input.push(`@${param.name} ${declare(param.type, param)}`)
462
+ } catch (e) {
463
+ return callback(new RequestError(e, 'EREQUEST'))
323
464
  }
324
465
 
325
466
  const sets = []
@@ -634,14 +775,32 @@ class Request extends BaseRequest {
634
775
  if (err) return callback(err)
635
776
 
636
777
  const params = []
637
- for (const name in this.parameters) {
638
- if (!objectHasProperty(this.parameters, name)) {
639
- continue
640
- }
641
- const param = this.parameters[name]
642
- if (param.io === 2) {
643
- params.push(`@${param.name} ${declare(param.type, param)}`)
778
+ let procedureName
779
+ try {
780
+ // this is built into `exec @___return___ = <name>` below and run as SQL text, so it is
781
+ // checked before it is emitted
782
+ procedureName = assertSafeProcedureName(procedure)
783
+ for (const name in this.parameters) {
784
+ if (!objectHasProperty(this.parameters, name)) {
785
+ continue
786
+ }
787
+ const param = this.parameters[name]
788
+ if (param.io === 2) {
789
+ // this callback is dispatched on its own tick, so a rejected declaration has
790
+ // to be handed back rather than thrown
791
+ params.push(`@${param.name} ${declare(param.type, param)}`)
792
+ } else {
793
+ // An input parameter is bound rather than written into the command, so only an
794
+ // output parameter's size is declared here and nothing would otherwise check an
795
+ // input's. It is checked so that a size is accepted or rejected the same way
796
+ // whichever driver is in use.
797
+ assertSafeTypeSize(param.length)
798
+ assertSafeTypeSize(param.precision)
799
+ assertSafeTypeSize(param.scale)
800
+ }
644
801
  }
802
+ } catch (e) {
803
+ return callback(new RequestError(e, 'EREQUEST'))
645
804
  }
646
805
 
647
806
  // set output params w/ values
@@ -657,7 +816,7 @@ class Request extends BaseRequest {
657
816
  }
658
817
 
659
818
  let cmd = `declare ${['@___return___ int'].concat(params).join(', ')};${sets.join(';')};`
660
- cmd += `exec @___return___ = ${procedure} `
819
+ cmd += `exec @___return___ = ${procedureName} `
661
820
 
662
821
  const spp = []
663
822
  for (const name in this.parameters) {
package/lib/table.js CHANGED
@@ -2,7 +2,8 @@
2
2
 
3
3
  const TYPES = require('./datatypes').TYPES
4
4
  const declareType = require('./datatypes').declare
5
- const objectHasProperty = require('./utils').objectHasProperty
5
+ const MSSQLError = require('./error/mssql-error')
6
+ const { objectHasProperty, assertSafeColumnName, assertSafeTableName } = require('./utils')
6
7
 
7
8
  const MAX = 65535 // (1 << 16) - 1
8
9
  const JSON_COLUMN_ID = 'JSON_F52E2B61-18A1-11d1-B105-00805F49916B'
@@ -99,9 +100,15 @@ Table.prototype._makeBulk = function _makeBulk () {
99
100
  }
100
101
 
101
102
  Table.prototype.declare = function declare () {
102
- const pkey = this.columns.filter(col => col.primary === true).map(col => `[${col.name}]`)
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)
109
+ const pkey = this.columns.filter(col => col.primary === true).map(col => `[${assertSafeColumnName(col.name)}]`)
103
110
  const cols = this.columns.map(col => {
104
- const def = [`[${col.name}] ${declareType(col.type, col)}`]
111
+ const def = [`[${assertSafeColumnName(col.name)}] ${declareType(col.type, col)}`]
105
112
 
106
113
  if (col.nullable === true) {
107
114
  def.push('null')
@@ -116,8 +123,17 @@ Table.prototype.declare = function declare () {
116
123
  return def.join(' ')
117
124
  })
118
125
 
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})`
121
137
  }
122
138
 
123
139
  Table.fromRecordset = function fromRecordset (recordset, name) {
@@ -4,7 +4,7 @@ const tds = require('tedious')
4
4
  const debug = require('debug')('mssql:tedi')
5
5
  const BaseRequest = require('../base/request')
6
6
  const RequestError = require('../error/request-error')
7
- const { IDS, objectHasProperty } = require('../utils')
7
+ const { IDS, objectHasProperty, assertSafeColumnName, assertSafeTableName, assertSafeTypeName, assertSafeTypeSize, assertSafeProcedureName } = require('../utils')
8
8
  const { TYPES, DECLARATIONS, declare, cast } = require('../datatypes')
9
9
  const Table = require('../table')
10
10
  const { PARSERS: UDT } = require('../udt')
@@ -23,6 +23,18 @@ const N_TYPES = {
23
23
  NumericN: 0x6C
24
24
  }
25
25
 
26
+ // A bulk load needs a tedious type for every column: one of sql.TYPES, which maps to one, or a
27
+ // tedious type given directly. tedious calls the type's declaration() when it writes the
28
+ // statement, after a connection has been taken, and would throw for anything else, so anything
29
+ // else is refused first.
30
+ const getTediousBulkType = function (col) {
31
+ const type = getTediousType(col.type)
32
+ if (!type || typeof type.declaration !== 'function') {
33
+ throw new Error(`Column '${col.name}' has a type that the tedious driver cannot bulk load.`)
34
+ }
35
+ return type
36
+ }
37
+
26
38
  const getTediousType = function (type) {
27
39
  switch (type) {
28
40
  case TYPES.VarChar: return tds.TYPES.VarChar
@@ -219,6 +231,22 @@ class Request extends BaseRequest {
219
231
 
220
232
  try {
221
233
  table._makeBulk()
234
+ // Checked before a connection is borrowed, so that a rejected name cannot leave
235
+ // the pool short of one.
236
+ table.columns.forEach(col => {
237
+ assertSafeColumnName(col.name)
238
+ getTediousBulkType(col)
239
+ })
240
+ // tedious writes the path as it is into `insert bulk`, and so does `create table`, which
241
+ // also takes the table's name; both are checked again where they are written.
242
+ assertSafeTableName(table.path)
243
+ if (table.create) table.declare()
244
+ // tedious writes these into `insert bulk ... WITH (ORDER (<key> <direction>))`
245
+ // UNQUOTED — unlike a column name, which it emits as `[name]`. So the quoted-identifier
246
+ // rule does not apply here: what matters is that the key cannot end the clause. It is
247
+ // checked as an identifier, bare or quoted, which is what that position accepts. The
248
+ // checked keys are rebuilt into the options actually handed to the driver, so the value
249
+ // that was validated is the one emitted even if the caller's object changes after.
222
250
  } catch (e) {
223
251
  return callback(new RequestError(e, 'EREQUEST'))
224
252
  }
@@ -332,15 +360,39 @@ class Request extends BaseRequest {
332
360
  }
333
361
  }
334
362
 
335
- const bulk = connection.newBulkLoad(table.path, options, done)
363
+ // A connection is held from here on, so anything that can throw has to hand the
364
+ // error back through `done`, which releases it. That includes newBulkLoad itself:
365
+ // tedious validates the bulk options there and throws for a bad `order` direction,
366
+ // which would otherwise strand the borrowed connection.
367
+ let bulk
368
+ let statement
369
+ try {
370
+ let bulkOptions = options
371
+ if (options && options.order) {
372
+ bulkOptions = Object.assign({}, options, {
373
+ order: Object.fromEntries(Object.entries(options.order)
374
+ .map(([key, direction]) => [assertSafeTypeName(key), direction]))
375
+ })
376
+ }
377
+ bulk = connection.newBulkLoad(assertSafeTableName(table.path), bulkOptions, done)
378
+ for (const col of table.columns) {
379
+ // tedious emits this name as a quoted identifier of its own when it builds
380
+ // the `insert bulk` statement, so it is checked here as well as in
381
+ // Table#declare, in case the name changed since it was checked above.
382
+ bulk.addColumn(assertSafeColumnName(col.name), getTediousBulkType(col), { nullable: col.nullable, length: assertSafeTypeSize(col.length), scale: assertSafeTypeSize(col.scale), precision: assertSafeTypeSize(col.precision) })
383
+ }
336
384
 
337
- for (const col of table.columns) {
338
- bulk.addColumn(col.name, getTediousType(col.type), { nullable: col.nullable, length: col.length, scale: col.scale, precision: col.precision })
385
+ if (table.create) {
386
+ // the path as it is checked and written, so the table looked up is the one created
387
+ const objectid = table.temporary ? `tempdb..[${table.name}]` : assertSafeTableName(table.path)
388
+ statement = `if object_id('${objectid.replace(/'/g, '\'\'')}') is null ${table.declare()}`
389
+ }
390
+ } catch (e) {
391
+ return done(e)
339
392
  }
340
393
 
341
394
  if (table.create) {
342
- const objectid = table.temporary ? `tempdb..[${table.name}]` : table.path
343
- const req = new tds.Request(`if object_id('${objectid.replace(/'/g, '\'\'')}') is null ${table.declare()}`, err => {
395
+ const req = new tds.Request(statement, err => {
344
396
  if (err) return done(err)
345
397
 
346
398
  connection.execBulkLoad(bulk, table.rows)
@@ -439,6 +491,26 @@ class Request extends BaseRequest {
439
491
  connection.on('errorMessage', errorHandlers.errorMessage = handleError.bind(null, false, connection))
440
492
  connection.on('error', errorHandlers.error = handleError.bind(null, true, connection))
441
493
 
494
+ // Give up before the request is sent: the listeners attached just above have to
495
+ // come off the connection before it goes back to the pool, or they accumulate on
496
+ // it and fire for whoever borrows it next.
497
+ const abandon = (err) => {
498
+ delete this._cancel
499
+
500
+ if (hasReturned) {
501
+ return
502
+ }
503
+
504
+ for (const event in errorHandlers) {
505
+ connection.removeListener(event, errorHandlers[event])
506
+ }
507
+
508
+ this.parent.release(connection)
509
+ hasReturned = true
510
+
511
+ return callback(err)
512
+ }
513
+
442
514
  debug('request(%d): query', IDS.get(this), command)
443
515
 
444
516
  const req = new tds.Request(command, err => {
@@ -647,20 +719,23 @@ class Request extends BaseRequest {
647
719
  param.value = getTediousType(param.type).validate(param.value, this.parent.collation)
648
720
  } catch (e) {
649
721
  e.message = `Validation failed for parameter '${name}'. ${e.message}`
650
- const err = new RequestError(e, 'EPARAM')
651
-
652
- this.parent.release(connection)
653
- return callback(err)
722
+ return abandon(new RequestError(e, 'EPARAM'))
654
723
  }
655
724
  }
656
725
 
657
726
  const declarations = []
658
- for (const name in this.parameters) {
659
- if (!objectHasProperty(this.parameters, name)) {
660
- continue
727
+ try {
728
+ for (const name in this.parameters) {
729
+ if (!objectHasProperty(this.parameters, name)) {
730
+ continue
731
+ }
732
+ const param = this.parameters[name]
733
+ // a connection is held here, so a rejected declaration has to be reported
734
+ // through the path that releases it
735
+ declarations.push(`@${name} ${declare(param.type, param)}`)
661
736
  }
662
- const param = this.parameters[name]
663
- declarations.push(`@${name} ${declare(param.type, param)}`)
737
+ } catch (e) {
738
+ return abandon(new RequestError(e, 'EREQUEST'))
664
739
  }
665
740
 
666
741
  const assigns = []
@@ -688,16 +763,22 @@ class Request extends BaseRequest {
688
763
  req.sqlTextOrProcedure = `declare ${declarations.join(', ')};select ${assigns.join(', ')};${req.sqlTextOrProcedure};${batchHasOutput ? (`select 1 as [___return___], ${selects.join(', ')}`) : ''}`
689
764
  }
690
765
  } else {
691
- for (const name in this.parameters) {
692
- if (!objectHasProperty(this.parameters, name)) {
693
- continue
694
- }
695
- const param = this.parameters[name]
696
- if (param.io === 1) {
697
- req.addParameter(param.name, getTediousType(param.type), parameterCorrection(param.value), { length: param.length, scale: param.scale, precision: param.precision })
698
- } else {
699
- req.addOutputParameter(param.name, getTediousType(param.type), parameterCorrection(param.value), { length: param.length, scale: param.scale, precision: param.precision })
766
+ try {
767
+ for (const name in this.parameters) {
768
+ if (!objectHasProperty(this.parameters, name)) {
769
+ continue
770
+ }
771
+ const param = this.parameters[name]
772
+ // tedious builds the sp_executesql declaration from these, so a rejected size
773
+ // has to be reported through the path that releases the connection
774
+ if (param.io === 1) {
775
+ req.addParameter(param.name, getTediousType(param.type), parameterCorrection(param.value), { length: assertSafeTypeSize(param.length), scale: assertSafeTypeSize(param.scale), precision: assertSafeTypeSize(param.precision) })
776
+ } else {
777
+ req.addOutputParameter(param.name, getTediousType(param.type), parameterCorrection(param.value), { length: assertSafeTypeSize(param.length), scale: assertSafeTypeSize(param.scale), precision: assertSafeTypeSize(param.precision) })
778
+ }
700
779
  }
780
+ } catch (e) {
781
+ return abandon(new RequestError(e, 'EREQUEST'))
701
782
  }
702
783
  }
703
784
 
@@ -793,6 +874,35 @@ class Request extends BaseRequest {
793
874
  connection.on('errorMessage', errorHandlers.errorMessage = handleError.bind(null, false, connection))
794
875
  connection.on('error', errorHandlers.error = handleError.bind(null, true, connection))
795
876
 
877
+ // A connection is held from here on. handleError builds a fresh Error and would
878
+ // relabel a rejected identifier as EREQUEST, so anything that can throw here is
879
+ // handed back through this instead, which keeps the code and releases the connection.
880
+ const abandon = (err) => {
881
+ delete this._cancel
882
+
883
+ if (hasReturned) {
884
+ return
885
+ }
886
+
887
+ for (const event in errorHandlers) {
888
+ connection.removeListener(event, errorHandlers[event])
889
+ }
890
+
891
+ this.parent.release(connection)
892
+ hasReturned = true
893
+
894
+ return callback(err)
895
+ }
896
+
897
+ let procedureName
898
+ try {
899
+ procedureName = assertSafeProcedureName(procedure)
900
+ } catch (e) {
901
+ // wrapped like every other rejection here, so the caller sees the same error class
902
+ // whichever driver is in use; MSSQLError keeps the EINJECT code through the wrap
903
+ return abandon(new RequestError(e, 'EREQUEST'))
904
+ }
905
+
796
906
  if (debug.enabled) {
797
907
  // log stored procedure executions and provided parameters
798
908
  const params = Object.keys(this.parameters).map(k => this.parameters[k])
@@ -805,7 +915,7 @@ class Request extends BaseRequest {
805
915
  debug('request(%d): execute %s %O', IDS.get(this), procedure, logParams)
806
916
  }
807
917
 
808
- const req = new tds.Request(procedure, err => {
918
+ const req = new tds.Request(procedureName, err => {
809
919
  // to make sure we handle no-sql errors as well
810
920
  if (err && (!errors.length || (errors.length && err.message !== errors[errors.length - 1].message))) {
811
921
  err = new RequestError(err, 'EREQUEST')
@@ -967,16 +1077,20 @@ class Request extends BaseRequest {
967
1077
  output[parameterName] = value
968
1078
  })
969
1079
 
970
- for (const name in this.parameters) {
971
- if (!objectHasProperty(this.parameters, name)) {
972
- continue
973
- }
974
- const param = this.parameters[name]
975
- if (param.io === 1) {
976
- req.addParameter(param.name, getTediousType(param.type), parameterCorrection(param.value), { length: param.length, scale: param.scale, precision: param.precision })
977
- } else {
978
- req.addOutputParameter(param.name, getTediousType(param.type), parameterCorrection(param.value), { length: param.length, scale: param.scale, precision: param.precision })
1080
+ try {
1081
+ for (const name in this.parameters) {
1082
+ if (!objectHasProperty(this.parameters, name)) {
1083
+ continue
1084
+ }
1085
+ const param = this.parameters[name]
1086
+ if (param.io === 1) {
1087
+ req.addParameter(param.name, getTediousType(param.type), parameterCorrection(param.value), { length: assertSafeTypeSize(param.length), scale: assertSafeTypeSize(param.scale), precision: assertSafeTypeSize(param.precision) })
1088
+ } else {
1089
+ req.addOutputParameter(param.name, getTediousType(param.type), parameterCorrection(param.value), { length: assertSafeTypeSize(param.length), scale: assertSafeTypeSize(param.scale), precision: assertSafeTypeSize(param.precision) })
1090
+ }
979
1091
  }
1092
+ } catch (e) {
1093
+ return abandon(new RequestError(e, 'EREQUEST'))
980
1094
  }
981
1095
 
982
1096
  connection.callProcedure(req)
@@ -5,6 +5,15 @@ const BaseTransaction = require('../base/transaction')
5
5
  const { IDS } = require('../utils')
6
6
  const TransactionError = require('../error/transaction-error')
7
7
 
8
+ // From TDS 7.2 the driver sends the transaction name in a transaction manager request, where it
9
+ // is data. Before 7.2 it writes `BEGIN TRAN <name>` into a SQL batch instead, and there a bare
10
+ // name is read as SQL: whitespace, `;`, `:` or a comment ends it, and even a lone keyword such as
11
+ // `commit` runs as a statement of its own. So on those versions the name is sent as a quoted
12
+ // identifier, with `]`, the only character that can end it, doubled. The server then stores
13
+ // exactly the name given, as it does on the newer versions. An empty name means no name, and an
14
+ // empty quoted identifier is not allowed, so it is sent as it is.
15
+ const quoteTransactionName = (name) => name === '' ? name : `[${name.replace(/]/g, ']]')}]`
16
+
8
17
  class Transaction extends BaseTransaction {
9
18
  constructor (parent) {
10
19
  super(parent)
@@ -32,6 +41,23 @@ class Transaction extends BaseTransaction {
32
41
  super._begin(isolationLevel, err => {
33
42
  if (err) return callback(err)
34
43
 
44
+ // Read once: the name checked here is the name sent, whatever a later read would return.
45
+ let name
46
+ try {
47
+ name = this.name
48
+ } catch (err) {
49
+ return callback(err)
50
+ }
51
+ if (name == null) name = ''
52
+ if (typeof name !== 'string') {
53
+ return callback(new TransactionError('Invalid transaction name. A transaction name must be a string.', 'EINJECT'))
54
+ }
55
+ // The server refuses a name longer than 32 UTF-16 code units, which is what length counts.
56
+ // Refuse it here, before a connection is taken, so that a name cannot cost one.
57
+ if (name.length > 32) {
58
+ return callback(new TransactionError('Invalid transaction name. A transaction name may be at most 32 characters long.', 'EINJECT'))
59
+ }
60
+
35
61
  debug('transaction(%d): begin', IDS.get(this))
36
62
 
37
63
  this.parent.acquire(this, (err, connection, config) => {
@@ -41,13 +67,17 @@ class Transaction extends BaseTransaction {
41
67
  this._acquiredConnection.on('rollbackTransaction', this._abort)
42
68
  this._acquiredConfig = config
43
69
 
70
+ // The driver records the TDS version the server agreed at login here, and makes the same
71
+ // comparison to decide how to send the name.
72
+ const sentName = connection.config.options.tdsVersion < '7_2' ? quoteTransactionName(name) : name
73
+
44
74
  connection.beginTransaction(err => {
45
75
  if (err) err = new TransactionError(err)
46
76
 
47
77
  debug('transaction(%d): begun', IDS.get(this))
48
78
 
49
79
  callback(err)
50
- }, this.name, this.isolationLevel)
80
+ }, sentName, this.isolationLevel)
51
81
  })
52
82
  })
53
83
  }
package/lib/utils.js CHANGED
@@ -1,3 +1,5 @@
1
+ const MSSQLError = require('./error/mssql-error')
2
+
1
3
  const IDS = new WeakMap()
2
4
  const INCREMENT = {
3
5
  Connection: 1,
@@ -7,8 +9,120 @@ const INCREMENT = {
7
9
  PreparedStatement: 1
8
10
  }
9
11
 
12
+ // Parameter names are emitted into generated T-SQL as `@<name>`. The `@` occupies the
13
+ // identifier's first position, so every character of the name sits in a subsequent
14
+ // position, where T-SQL also permits digits and `$`. The set is deliberately wider than
15
+ // the names the server will accept: it excludes the characters that could end the
16
+ // identifier and let the rest of the name be read as SQL, and nothing else, so a name
17
+ // the server dislikes still fails there rather than becoming an error here. The
18
+ // exception is the invisible format characters, which are rejected outright.
19
+ // Only the two zero-width joiners are taken from the format characters; the rest of that
20
+ // category includes ZERO WIDTH SPACE, which the server does treat as a separator.
21
+ const PARAM_NAME = /^(?:[\p{L}\p{N}\p{M}\p{Pc}@#$・・]|\u200C|\u200D)*$/u
22
+ // A table-valued parameter's type name is emitted into the parameter declaration, and a
23
+ // stored procedure's name is emitted into an `exec`, so both are checked the way the server
24
+ // reads a qualified name: one or more parts separated by `.`, each either bare, holding only
25
+ // the characters an identifier is made of, or quoted in brackets or double quotes, where
26
+ // anything goes until the closing mark. Nothing that gets through can end the statement it
27
+ // sits in and have the rest read as SQL.
28
+ const QUALIFIED_NAME_PART = '(?:\\[(?:[^\\]]|\\]\\])*\\]|"(?:[^"]|"")*"|[\\p{L}\\p{N}\\p{M}\\p{Pc}@#$]+)'
29
+ // An intermediate part may be omitted — `db..proc` and `server.db..proc` are ordinary
30
+ // T-SQL — but the first and last parts must be present, so a bare `.`, a leading `.proc`
31
+ // and a trailing `db..` are still refused. An empty part cannot end the identifier.
32
+ const QUALIFIED_NAME = new RegExp(`^(?:${QUALIFIED_NAME_PART}(?:\\.${QUALIFIED_NAME_PART}?)*\\.)?${QUALIFIED_NAME_PART}$`, 'u')
33
+ // A type that is not one of sql.TYPES declares itself, and its declaration takes the same form,
34
+ // optionally with a size after it: one or two numbers, or the word `max`, in parentheses.
35
+ const TYPE_DECLARATION = new RegExp(`^(?:${QUALIFIED_NAME_PART}(?:\\.${QUALIFIED_NAME_PART}?)*\\.)?${QUALIFIED_NAME_PART}(?:\\s*\\(\\s*(?:\\d+|max)\\s*(?:,\\s*\\d+\\s*)?\\))?$`, 'iu')
36
+ // A table's path has the same form, but a bare part may hold every character a parameter name
37
+ // may (see PARAM_NAME above), which the server reads as part of an identifier.
38
+ const TABLE_NAME_PART = '(?:\\[(?:[^\\]]|\\]\\])*\\]|"(?:[^"]|"")*"|(?:[\\p{L}\\p{N}\\p{M}\\p{Pc}@#$・・]|\\u200C|\\u200D)+)'
39
+ const TABLE_NAME = new RegExp(`^(?:${TABLE_NAME_PART}(?:\\.${TABLE_NAME_PART}?)*\\.)?${TABLE_NAME_PART}$`, 'u')
40
+
41
+ // A length, precision or scale is emitted into the same declaration. `max` is the only
42
+ // word the declaration takes there; everything else the server wants is a number.
43
+ const TYPE_SIZE = /^\w*$/
44
+
45
+ // A column name is emitted as a quoted identifier, `[name]`, by this module and again by
46
+ // the driver's own bulk load. Only `]` can terminate that quoting early, and doubling it
47
+ // is the documented way to include one literally.
48
+ const escapesQuotedIdentifier = (name) => String(name).replace(/]]/g, '').includes(']')
49
+
10
50
  module.exports = {
11
51
  objectHasProperty: (object, property) => Object.prototype.hasOwnProperty.call(object, property),
52
+ isValidParameterName: (name) => {
53
+ // Only primitives are accepted: an object could return a different value from a second
54
+ // toString() call, passing validation here and emitting something else into the SQL.
55
+ const type = typeof name
56
+ return (type === 'string' || type === 'number') && PARAM_NAME.test(String(name))
57
+ },
58
+ assertSafeTypeName: (name) => {
59
+ // A type name is optional: the tedious driver takes it from the Table passed as the
60
+ // value, and only uses this one when it is given.
61
+ if (name == null) {
62
+ return name
63
+ }
64
+ // Read once, and return what was read. Whatever is emitted is what was checked, so a
65
+ // value that reports a different name the second time cannot reach the SQL.
66
+ const type = String(name).trim()
67
+ if (!QUALIFIED_NAME.test(type)) {
68
+ throw new MSSQLError(`Invalid type name '${type}'. Type names may only contain identifier characters.`, 'EINJECT')
69
+ }
70
+ return type
71
+ },
72
+ assertSafeProcedureName: (name) => {
73
+ // The msnodesqlv8 driver builds `exec @___return___ = <name>` as SQL text, so the name is
74
+ // checked before it is emitted. The tedious driver sends it as a bound RPC and cannot be
75
+ // injected through it, but it is checked there too so that a name is accepted or rejected
76
+ // the same way whichever driver is in use.
77
+ // Read once, and return what was read, for the same reason as the type name.
78
+ const procedure = String(name).trim()
79
+ if (!QUALIFIED_NAME.test(procedure)) {
80
+ throw new MSSQLError(`Invalid procedure name '${procedure}'. Procedure names may only contain identifier characters.`, 'EINJECT')
81
+ }
82
+ return procedure
83
+ },
84
+ assertSafeTypeDeclaration: (declaration) => {
85
+ // Read once, and return what was read, for the same reason as the type name.
86
+ const type = String(declaration).trim()
87
+ if (!TYPE_DECLARATION.test(type)) {
88
+ throw new MSSQLError(`Invalid type declaration '${type}'. A type may only be declared with identifier characters, unless a part is in brackets or double quotes, and a size in parentheses.`, 'EINJECT')
89
+ }
90
+ return type
91
+ },
92
+ assertSafeTableName: (name) => {
93
+ // A table's path is written as it is into `create table` and into tedious's `insert bulk`.
94
+ // A table built from a name always has a path whose parts are in brackets, but `path` is a
95
+ // plain property that can be changed after that, so it is checked where it is written.
96
+ // Read once, and return what was read, for the same reason as the type name.
97
+ const table = String(name).trim()
98
+ if (!TABLE_NAME.test(table)) {
99
+ 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')
100
+ }
101
+ return table
102
+ },
103
+ assertSafeTypeSize: (value) => {
104
+ if (value == null || typeof value === 'number') {
105
+ return value
106
+ }
107
+ // Read once and return what was read, for the same reason as the type name. Padding is
108
+ // trimmed rather than refused, and a word the server will reject still reaches it.
109
+ const size = String(value).trim()
110
+ if (!TYPE_SIZE.test(size)) {
111
+ throw new MSSQLError(`Invalid type size '${size}'. A length, precision or scale must be a number.`, 'EINJECT')
112
+ }
113
+ return size
114
+ },
115
+ assertSafeColumnName: (name) => {
116
+ const type = typeof name
117
+ if (type !== 'string' && type !== 'number') {
118
+ throw new MSSQLError(`Invalid column name '${String(name)}'. Column names must be a string or a number.`, 'EINJECT')
119
+ }
120
+ const column = String(name)
121
+ if (escapesQuotedIdentifier(column)) {
122
+ throw new MSSQLError(`Invalid column name '${column}'. A ']' in a column name must be written as ']]'.`, 'EINJECT')
123
+ }
124
+ return column
125
+ },
12
126
  INCREMENT,
13
127
  IDS: {
14
128
  get: IDS.get.bind(IDS),
package/package.json CHANGED
@@ -21,7 +21,7 @@
21
21
  "azure",
22
22
  "node-mssql"
23
23
  ],
24
- "version": "9.1.3",
24
+ "version": "9.1.5",
25
25
  "main": "index.js",
26
26
  "repository": "github:tediousjs/node-mssql",
27
27
  "license": "MIT",
@@ -36,12 +36,12 @@
36
36
  "devDependencies": {
37
37
  "@commitlint/cli": "^17.6.6",
38
38
  "@commitlint/config-conventional": "^17.6.6",
39
- "@semantic-release/commit-analyzer": "^10.0.1",
40
- "@semantic-release/github": "^9.0.3",
41
- "@semantic-release/npm": "^10.0.4",
42
- "@semantic-release/release-notes-generator": "^11.0.4",
39
+ "@semantic-release/commit-analyzer": "^13.0.1",
40
+ "@semantic-release/github": "^12.0.6",
41
+ "@semantic-release/npm": "^13.1.5",
42
+ "@semantic-release/release-notes-generator": "^14.1.0",
43
43
  "mocha": "^10.0.0",
44
- "semantic-release": "^21.0.7",
44
+ "semantic-release": "^25.0.3",
45
45
  "standard": "^17.0.0"
46
46
  },
47
47
  "engines": {