Skip to content
Draft
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
8 changes: 8 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,12 @@ jobs:
sqlserver: sql-2019
variant: no-updates
install-updates: 'false'
# a password that needs escaping on the setup command line: a double quote, a space, characters that
# cmd.exe would treat specially and a trailing backslash; 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 @@ -201,6 +207,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
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,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 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 @@ -15,6 +15,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 @@ -143,13 +144,15 @@ export default async function install() {
}
});
if (updatePath) {
installArgs.push('/UPDATEENABLED=1', `/UpdateSource="${dirname(updatePath)}"`);
installArgs.push('/UPDATEENABLED=1', `/UpdateSource=${quoteWindowsArgument(dirname(updatePath))}`);
}
}
}
const instanceName = 'MSSQLSERVER';
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 @@ -159,9 +162,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',
...(config.installArgs ?? []),
...installArgs,
Expand Down
22 changes: 21 additions & 1 deletion 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,16 +51,35 @@ 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);
}
}

/**
* 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);
return {
version: version.toLowerCase() === 'latest' ? '2025' : version,
password: core.getInput('sa-password'),
password,
collation: core.getInput('db-collation'),
installArgs: core.getMultilineInput('install-arguments'),
wait: core.getBooleanInput('wait-for-ready'),
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 @@ -193,6 +193,22 @@ describe('install', () => {
]);
});
}
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
19 changes: 18 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,22 @@ 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('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