Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,13 @@ jobs:
/INSTANCEDIR="D:\SQL Server"
/INSTALLSQLDATADIR="D:\SQL Server"
data-root: 'D:\SQL Server\'
# a password that needs escaping on the setup command line: a space, characters that cmd.exe would treat
# specially and a trailing backslash (setup can't pass on a double quote, so the action rejects one); the
# check step logs in with it
- os: windows-2022
sqlserver: sql-2025
variant: password
sa-password: 'Str0ng Pa ss%^!\'
name: runaction (${{ matrix.os }}, ${{ matrix.sqlserver }}${{ matrix.variant && format(', {0}', matrix.variant) || '' }})
runs-on: ${{ matrix.os }}
timeout-minutes: 30
Expand Down Expand Up @@ -250,6 +257,8 @@ jobs:
uses: ./
with:
sqlserver-version: ${{ matrix.sqlserver }}
# the fallback is the action's own default, so the other jobs keep using it
sa-password: ${{ matrix.sa-password || 'yourStrong(!)Password' }}
native-client-version: 11
odbc-version: ${{ matrix.odbc-version || '17' }}
install-updates: ${{ matrix.install-updates || 'true' }}
Expand Down
9 changes: 8 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,8 @@ See [action.yml](./action.yml):
# Version of ODBC to install. Supported versions: 17, 18.
odbc-version: ''

# The SA user password to use.
# The SA user password to use. It must not contain a double quote, which SQL
# Server setup cannot pass on.
# Default: yourStrong(!)Password
sa-password: 'yourStrong(!)Password'

Expand Down Expand Up @@ -77,6 +78,12 @@ password in a secret and pass it to `sa-password`:
sa-password: ${{ secrets.SQL_SA_PASSWORD }}
```

The action masks the password in its logs and in the later steps of the job.
GitHub prints the step inputs before the action starts, so a password that
doesn't come from a secret still shows in that step header. GitHub also leaves
out job outputs that contain a masked value, so read the `sa-password` output
from the step, not from a job output.

### SQL Server 2025

Set `sqlserver-version` to `'2025'` (or `'sql-2025'`) to install SQL Server
Expand Down
2 changes: 1 addition & 1 deletion action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ inputs:
odbc-version:
description: 'Version of ODBC to install. Supported versions: 17, 18.'
sa-password:
description: 'The SA user password to use.'
description: 'The SA user password to use. It must not contain a double quote, which SQL Server setup cannot pass on.'
default: 'yourStrong(!)Password'
db-collation:
description: 'The database collation to use.'
Expand Down
2 changes: 1 addition & 1 deletion lib/main/index.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion lib/main/index.js.map

Large diffs are not rendered by default.

9 changes: 6 additions & 3 deletions src/install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
getOsVersion,
waitForDatabase,
} from './utils.ts';
import { quoteWindowsArgument } from './windows-args.ts';
import installNativeClient from './install-native-client.ts';
import installOdbc from './install-odbc.ts';

Expand Down Expand Up @@ -144,7 +145,7 @@ export default async function install() {
}
});
if (updatePath) {
installArgs.push('/UPDATEENABLED=1', `/UpdateSource="${dirname(updatePath)}"`);
installArgs.push('/UPDATEENABLED=1', `/UpdateSource=${quoteWindowsArgument(dirname(updatePath))}`);
}
}
}
Expand All @@ -153,6 +154,8 @@ export default async function install() {
const instanceDirArgs = await findInstanceDirArgs(installArgs);
try {
// @todo - make sure that the arguments are unique / don't conflict
// the arguments are passed verbatim, so quote the values that the action adds itself; the user's
// install-arguments are passed as they are given
const exitCode = await core.group('Installing SQL Server', () => exec.exec(`"${toolPath}"`, [
'/q',
'/ACTION=Install',
Expand All @@ -162,9 +165,9 @@ export default async function install() {
'/SQLSYSADMINACCOUNTS="BUILTIN\\ADMINISTRATORS"',
'/TCPENABLED=1',
'/NPENABLED=0',
`/SQLCOLLATION="${collation}"`,
`/SQLCOLLATION=${quoteWindowsArgument(collation)}`,
'/SECURITYMODE=SQL',
`/SAPWD="${password}"`,
`/SAPWD=${quoteWindowsArgument(password)}`,
'/IACCEPTSQLSERVERLICENSETERMS',
...instanceDirArgs,
...(config.installArgs ?? []),
Expand Down
41 changes: 39 additions & 2 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import * as tc from '@actions/tool-cache';
import { generateFileHash } from './crypto.ts';
import { cacheToolDir, cacheToolFile } from './tool-cache.ts';
import type { VersionConfig } from './versions.ts';
import { quoteWindowsArgument } from './windows-args.ts';

/**
* Helper function to determine the runner being used. Uses `systeminfo` to gather version.
Expand Down Expand Up @@ -50,17 +51,53 @@ export interface Inputs {
installUpdates: boolean;
}

/**
* Register the SA password as a secret, so that it shows as *** in the logs of this and later steps. The setup and
* sqlcmd command lines that the action logs can show the password in its escaped form, so mask that form too.
*
* @param {string} password
*/
function maskPassword(password: string) {
if (!password) {
return;
}
core.setSecret(password);
const escaped = quoteWindowsArgument(password).slice(1, -1);
if (escaped !== password) {
core.setSecret(escaped);
}
}

/**
* SQL Server setup passes its arguments on to the installer that it starts, and a value with a double quote doesn't
* survive that, even when it is escaped. Stop before anything is downloaded, instead of failing later inside setup.
* The error names the input, but never the value, which can be a password.
*
* @param {string} input The input name
* @param {string} value
*/
function assertNoDoubleQuote(input: string, value: string) {
if (value.includes('"')) {
throw new Error(`The ${input} input must not contain a double quote ("), because SQL Server setup can't pass it on to the installer that it starts`);
}
}

/**
* Gather the action's inputs.
*
* @returns {Inputs}
*/
export function gatherInputs(): Inputs {
const version = core.getInput('sqlserver-version').replace(/sql-/i, '') || 'latest';
const password = core.getInput('sa-password');
maskPassword(password);
const collation = core.getInput('db-collation');
assertNoDoubleQuote('sa-password', password);
assertNoDoubleQuote('db-collation', collation);
return {
version: version.toLowerCase() === 'latest' ? '2025' : version,
password: core.getInput('sa-password'),
collation: core.getInput('db-collation'),
password,
collation,
installArgs: core.getMultilineInput('install-arguments'),
wait: core.getBooleanInput('wait-for-ready'),
skipOsCheck: core.getBooleanInput('skip-os-check'),
Expand Down
35 changes: 35 additions & 0 deletions src/windows-args.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/**
* Quote a value for a Windows command line, so that a program that splits its
* command line with the standard Windows rules (CommandLineToArgvW and the C
* runtime) gets the value back unchanged.
*
* The value is wrapped in double quotes. A double quote in the value becomes
* `\"`, and backslashes are doubled only where they come before a double quote
* or the closing quote, because backslashes anywhere else are literal.
*
* Use this for values that the action puts in a command line itself when it
* runs a program with `windowsVerbatimArguments`, where `@actions/exec` adds no
* quoting of its own.
*
* @param {string} value
* @returns {string} The quoted value, including the surrounding double quotes
*/
export function quoteWindowsArgument(value: string): string {
let quoted = '"';
let backslashes = 0;
for (const char of value) {
if (char === '\\') {
backslashes++;
continue;
}
if (char === '"') {
// each backslash before a quote must be escaped, and so must the quote itself
quoted += '\\'.repeat(backslashes * 2 + 1) + '"';
} else {
quoted += '\\'.repeat(backslashes) + char;
}
backslashes = 0;
}
// backslashes before the closing quote must be escaped, or they would escape it
return `${quoted}${'\\'.repeat(backslashes * 2)}"`;
}
16 changes: 16 additions & 0 deletions test/install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,22 @@ describe('install', () => {
'/SQLTEMPDBFILECOUNT=4',
]);
});
it('escapes the password and collation so that setup gets them unchanged', async () => {
utils.gatherInputs.mock.mockImplementation(() => defaultInputs({
version: 'box',
password: 'Ab1"cd ef\\',
collation: 'Odd"Collation',
}));
await install();
const args = exec.exec.mock.calls[0].arguments[1] as string[];
assert.ok(args.includes('/SAPWD="Ab1\\"cd ef\\\\"'), `got ${args.find((arg) => arg.startsWith('/SAPWD='))}`);
assert.ok(args.includes('/SQLCOLLATION="Odd\\"Collation"'));
// the arguments after the password must stay separate arguments
assert.equal(args[args.indexOf('/SAPWD="Ab1\\"cd ef\\\\"') + 1], '/IACCEPTSQLSERVERLICENSETERMS');
// the action's own outputs and readiness check use the password as it was given
assert.deepEqual(core.setOutput.mock.calls[0].arguments, ['sa-password', 'Ab1"cd ef\\']);
assert.deepEqual(utils.waitForDatabase.mock.calls[0].arguments, ['Ab1"cd ef\\']);
});
it('warns and waits for the database if setup requests a reboot', async () => {
exec.exec.mock.mockImplementation(async () => 3010);
await install();
Expand Down
37 changes: 36 additions & 1 deletion test/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const core = {
getInput: mock.fn(() => ''),
getMultilineInput: mock.fn(() => [] as string[]),
getBooleanInput: mock.fn(() => false),
setSecret: mock.fn(),
info: mock.fn(),
debug: mock.fn(),
warning: mock.fn(),
Expand Down Expand Up @@ -68,7 +69,7 @@ const utils = await import('../src/utils.ts');

function resetAll() {
const fns = [
core.getInput, core.getMultilineInput, core.getBooleanInput,
core.getInput, core.getMultilineInput, core.getBooleanInput, core.setSecret,
core.info, core.debug, core.warning, core.notice,
core.startGroup, core.endGroup, core.isDebug, core.platform.getDetails,
exec.exec, exec.getExecOutput,
Expand Down Expand Up @@ -212,6 +213,40 @@ describe('utils', () => {
const res = utils.gatherInputs();
assert.equal(res.version, '2025');
});
it('masks the SA password', () => {
setupInputs();
utils.gatherInputs();
assert.deepEqual(core.setSecret.mock.calls.map((c) => c.arguments), [['secret password']]);
});
it('also masks the escaped form that the command lines show', () => {
setupInputs({ 'sa-password': 'Ab1 cd\\' });
const res = utils.gatherInputs();
assert.equal(res.password, 'Ab1 cd\\');
assert.deepEqual(core.setSecret.mock.calls.map((c) => c.arguments), [['Ab1 cd\\'], ['Ab1 cd\\\\']]);
});
it('rejects a password with a double quote, without showing it', () => {
setupInputs({ 'sa-password': 'Ab1"cdef' });
assert.throws(() => utils.gatherInputs(), (error: Error) => {
assert.equal(error.message, 'The sa-password input must not contain a double quote ("), because SQL Server setup can\'t pass it on to the installer that it starts');
assert.ok(!error.message.includes('Ab1'));
return true;
});
// the password is masked before the error, so nothing that logs the error can show it
assert.deepEqual(core.setSecret.mock.calls[0].arguments, ['Ab1"cdef']);
});
it('rejects a collation with a double quote', () => {
setupInputs({ 'db-collation': 'SQL_Latin1"General' });
assert.throws(() => utils.gatherInputs(), { message: 'The db-collation input must not contain a double quote ("), because SQL Server setup can\'t pass it on to the installer that it starts' });
});
it('accepts a password with spaces, symbols and a trailing backslash', () => {
setupInputs({ 'sa-password': 'Str0ng Pa ss%^!\\' });
assert.equal(utils.gatherInputs().password, 'Str0ng Pa ss%^!\\');
});
it('does not mask an empty password', () => {
setupInputs({ 'sa-password': '' });
utils.gatherInputs();
assert.equal(core.setSecret.mock.callCount(), 0);
});
describe('with the inputs in action.yml', () => {
// each input has a different value, so a misspelt or swapped input name changes the result
const stringInputs: Record<string, string> = {
Expand Down
105 changes: 105 additions & 0 deletions test/windows-args.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { describe, it } from 'node:test';
import assert from 'node:assert/strict';

const { quoteWindowsArgument } = await import('../src/windows-args.ts');

/**
* Split a command line the way the Windows C runtime does: whitespace separates arguments outside double quotes,
* 2n backslashes before a double quote give n backslashes and toggle quoting, 2n+1 backslashes before a double
* quote give n backslashes and a literal double quote, and other backslashes are literal.
*/
function splitWindowsCommandLine(commandLine: string): string[] {
const args: string[] = [];
let current = '';
let inArgument = false;
let quoted = false;
for (let i = 0; i < commandLine.length; i++) {
const char = commandLine[i];
if (char === '\\') {
let backslashes = 0;
while (commandLine[i] === '\\') {
backslashes++;
i++;
}
if (commandLine[i] === '"') {
current += '\\'.repeat(Math.floor(backslashes / 2));
if (backslashes % 2 === 1) {
current += '"';
} else {
quoted = !quoted;
}
} else {
current += '\\'.repeat(backslashes);
i--;
}
inArgument = true;
} else if (char === '"') {
if (quoted && commandLine[i + 1] === '"') {
current += '"';
i++;
} else {
quoted = !quoted;
}
inArgument = true;
} else if ((char === ' ' || char === '\t') && !quoted) {
if (inArgument) {
args.push(current);
current = '';
inArgument = false;
}
} else {
current += char;
inArgument = true;
}
}
if (inArgument) {
args.push(current);
}
return args;
}

describe('windows-args', () => {
describe('.quoteWindowsArgument()', () => {
const examples: [string, string][] = [
['yourStrong(!)Password', '"yourStrong(!)Password"'],
['pass word', '"pass word"'],
['', '""'],
['Ab1"cdef', '"Ab1\\"cdef"'],
['Passw0rd\\', '"Passw0rd\\\\"'],
['Pass\\\\', '"Pass\\\\\\\\"'],
['a\\b', '"a\\b"'],
['a\\"b', '"a\\\\\\"b"'],
['C:\\tool-cache\\sqlupdate\\2022.0.0\\x64', '"C:\\tool-cache\\sqlupdate\\2022.0.0\\x64"'],
];
for (const [value, expected] of examples) {
it(`quotes ${JSON.stringify(value)}`, () => {
assert.equal(quoteWindowsArgument(value), expected);
});
}
it('gives every value back unchanged, without changing the arguments after it', () => {
// every string of up to 4 of these characters, including the ones that break naive quoting
const chars = ['a', '"', '\\', ' ', '\t', '%', '^', '!'];
let values = [''];
let all = [''];
for (let length = 1; length <= 4; length++) {
values = values.flatMap((value) => chars.map((char) => value + char));
all = all.concat(values);
}
for (const value of all) {
const commandLine = `"C:\\setup.exe" /q /SAPWD=${quoteWindowsArgument(value)} /IACCEPTSQLSERVERLICENSETERMS`;
assert.deepEqual(splitWindowsCommandLine(commandLine), [
'C:\\setup.exe',
'/q',
`/SAPWD=${value}`,
'/IACCEPTSQLSERVERLICENSETERMS',
], `value ${JSON.stringify(value)}`);
}
});
it('shows why the values need quoting', () => {
// the unescaped form that the action used to build loses the later switches
assert.deepEqual(splitWindowsCommandLine('/SAPWD="Ab1"cdef" /IACCEPTSQLSERVERLICENSETERMS'), [
'/SAPWD=Ab1cdef /IACCEPTSQLSERVERLICENSETERMS',
]);
});
});
});
Loading