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
4 changes: 2 additions & 2 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ The build step (`npm run build`) also runs `npm run docs`, which regenerates the
2. Validates OS compatibility using version config from `src/versions.ts`
3. Optionally installs SQL Native Client (`src/install-native-client.ts`) and ODBC driver (`src/install-odbc.ts`)
4. Downloads or cache-hits the SQL Server installer (box+exe, standalone exe, or SSEI bootstrapper)
5. Optionally downloads cumulative updates (resolves Microsoft download-page JSON, falls back to legacy `<a href>` links if the metadata is missing or unusable, fetches the page up to three times, retrying network errors, timeouts and non-2xx responses after 5 and then 10 seconds, and if resolving or downloading the update fails, warns and installs without updates)
5. Optionally downloads cumulative updates (fetches the Microsoft download page with `@actions/http-client`, so that the page request follows `HTTPS_PROXY` and `NO_PROXY` like the downloads, and reads the body as a stream with a 30-second limit, because `readBody()` never settles when the connection closes early; after an HTTP 403 when no proxy applies, tries the page once with Node's `fetch`, because Microsoft has refused `@actions/http-client` requests before; tries the page up to three times, retrying every failure after 5 and then 10 seconds; resolves the download-page JSON and falls back to legacy `<a href>` links if the metadata is missing or unusable; and if resolving or downloading the update fails, warns and installs without updates)
6. Runs the installer via `@actions/exec` (exit code 3010, "succeeded but reboot required", is logged as a warning and treated as success; any other non-zero code fails the action)
7. Waits for the database to be ready with `waitForDatabase()` from `src/utils.ts` (up to 6 `sqlcmd` logins with exponential backoff); if the database is not ready, or `sqlcmd` can't run, the action warns, or fails if setup exited 3010

Expand All @@ -66,7 +66,7 @@ The build step (`npm run build`) also runs `npm run docs`, which regenerates the

## Conventions

- **Testing:** Uses the built-in [`node:test`](https://nodejs.org/api/test.html) runner with `--experimental-test-module-mocks` and `node:assert/strict`. No Mocha, Chai, Sinon, or c8. Each test file mirrors its source file (e.g., `test/install.ts` tests `src/install.ts`).
- **Testing:** Uses the built-in [`node:test`](https://nodejs.org/api/test.html) runner with `--experimental-test-module-mocks` and `node:assert/strict`. No Mocha, Chai, Sinon, or c8. Each test file mirrors its source file (e.g., `test/install.ts` tests `src/install.ts`). `test/update-page-proxy.ts` is the exception: it fetches update pages through a real loopback CONNECT proxy with the unmocked `@actions/http-client`, so keep it unmocked.
- **Mocking pattern:** Create `mock.fn()` stubs at the top of the test file, call `mock.module(specifier, { namedExports, defaultExport })` for each dependency you need to replace, then `await import('../src/sut.ts')` to load the system-under-test against those mocks. Reset call history and implementations in `beforeEach` using `fn.mock.resetCalls()` and `fn.mock.mockImplementation(...)`. Because a given `mock.module()` call cannot be replaced mid-run, the tests share one mock per module across all cases and vary behaviour via `mockImplementation`/`mockImplementationOnce(impl, onCall)` — note that `mockImplementationOnce` without `onCall` applies to the next call, so a second one queued before that call replaces the first. Pass an explicit index when queueing sequential once-implementations.
- **Coverage caveat:** `--experimental-test-coverage` under-reports coverage for files that are `mock.module()`-replaced in sibling tests (the aggregator treats the mock shadow as an uncovered run of the real file). Running a source file's own test file in isolation gives a more accurate figure for that file, but not every file reaches 100% that way. Treat the aggregated numbers as a lower bound while this feature is experimental.
- **Commit messages:** Follow [Conventional Commits](https://www.conventionalcommits.org/) enforced by commitlint. Semantic-release uses these to generate automated releases and changelogs, so correct commit types are critical.
Expand Down
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,11 +108,41 @@ When `install-updates: true` is set for a version with a configured update URL,
the action downloads the update before starting SQL Server setup. Download-page
requests are tried up to three times on network errors, timeouts, or non-2xx
responses (including 403 and 404), with 5- and 10-second delays before retries.
When Microsoft refuses a page request with a 403 and no proxy applies, the
action immediately tries the page again with Node's built-in `fetch`. Microsoft
has accepted `fetch` at times when it refused the HTTP client of the action.
If the update still can't be downloaded, the action logs a warning with the
reason and installs SQL Server without updates. Update URLs are configured for
SQL Server 2016 and later, including 2025 (and so the default, `'latest'`);
older versions skip updates.

#### Proxies

The action fetches the download page with the same HTTP client as its
downloads. So the page request follows the runner's proxy settings
(`HTTPS_PROXY` and `NO_PROXY`). When the action uses a proxy for the page, it
says so in the log. If the action can't fetch the page through the proxy, set
`NO_PROXY` on the setup-sqlserver step to fetch the page directly:

```yaml
- uses: tediousjs/setup-sqlserver@v4
with:
install-updates: true
env:
NO_PROXY: www.microsoft.com
```

Only the download pages are on `www.microsoft.com`, so this doesn't change how
the action downloads the installers and updates. Through a proxy, the action
doesn't try `fetch` after a 403, because `fetch` doesn't use the proxy.

The `NO_PROXY` of the step replaces the runner's value for that step only. So
add any other hosts from the runner's list that the step needs. Set it on the
step, not on the job, so that the other steps keep the runner's value. Each
entry also matches its subdomains, so `microsoft.com` or `.microsoft.com` also
sends the installer and update downloads directly. A `*.` wildcard doesn't
work.

### Caching

Downloaded SQL Server installers, cumulative updates, and ODBC and Native
Expand Down
6 changes: 3 additions & 3 deletions 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.

1 change: 1 addition & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
"@actions/core": "^3.0.1",
"@actions/exec": "^3.0.0",
"@actions/glob": "^0.7.0",
"@actions/http-client": "^4.0.1",
"@actions/io": "^3.0.2",
"@actions/tool-cache": "^4.0.0"
}
Expand Down
129 changes: 109 additions & 20 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import { mkdtemp, readdir } from 'node:fs/promises';
import { basename, extname, dirname, join as joinPaths, win32 } from 'node:path';
import type { IncomingMessage } from 'node:http';
import { text } from 'node:stream/consumers';
import { setTimeout as delay } from 'node:timers/promises';
import * as core from '@actions/core';
import * as exec from '@actions/exec';
import * as glob from '@actions/glob';
import { HttpClient } from '@actions/http-client';
import { getProxyUrl } from '@actions/http-client/lib/proxy';
import * as io from '@actions/io';
import * as tc from '@actions/tool-cache';
import { generateFileHash } from './crypto.ts';
Expand Down Expand Up @@ -401,30 +405,115 @@ function describeCause(cause: unknown): string {
return [message, code].filter(Boolean).join(' / ');
}

/**
* The time in milliseconds that a cumulative update page request can be idle before it fails, and the time that its
* body can take. A proxy that never answers the CONNECT request isn't limited, the same as for the downloads.
*/
const UPDATE_PAGE_TIMEOUT = 30_000;

/**
* Describe a failure and its cause, for a log message. Leave out the cause when the message already contains it.
*
* @param {unknown} error
* @returns {string}
*/
function describeError(error: unknown): string {
const reason = error instanceof Error ? error.message : String(error);
const causeDetails = error instanceof Error ? describeCause(error.cause) : '';
return causeDetails && !reason.includes(causeDetails) ? `${reason} (${causeDetails})` : reason;
}

/**
* Read the body of a cumulative update page response. HttpClientResponse.readBody() never settles when the
* connection closes before the end of the body, so read the stream, which then fails. Also fail when the body takes
* longer than UPDATE_PAGE_TIMEOUT.
*
* @param {IncomingMessage} message
* @param {string} url
* @returns {Promise<string>}
*/
async function readPageBody(message: IncomingMessage, url: string): Promise<string> {
const timer = setTimeout(() => message.destroy(new Error(`Request timeout: ${url}`)), UPDATE_PAGE_TIMEOUT);
try {
return await text(message);
} finally {
clearTimeout(timer);
}
}

/**
* Fetch a cumulative update page with Node's fetch, which ignores the proxy settings.
*
* @param {string} url
* @returns {Promise<string>}
*/
async function fetchPageWithFetch(url: string): Promise<string> {
const res = await fetch(url, { signal: AbortSignal.timeout(UPDATE_PAGE_TIMEOUT) });
if (!res.ok) {
throw new Error(`HTTP ${res.status}`);
}
return await res.text();
}

/**
* Fetch a Microsoft download page, to find its cumulative update. The request uses @actions/http-client, which the
* downloads also use, so that it follows the same proxy settings (HTTPS_PROXY and NO_PROXY). If Microsoft refuses
* the request with HTTP 403 and no proxy applies, try the page again with Node's fetch in the same attempt.
*
* @param {string} url
* @returns {Promise<string>} The page
*/
async function fetchUpdatePage(url: string): Promise<string> {
const attempts = 3;
for (let attempt = 1; ; attempt++) {
let retryable = false;
try {
const res = await fetch(url, { signal: AbortSignal.timeout(30_000) });
if (!res.ok) {
retryable = true;
throw new Error(`HTTP ${res.status}`);
}
return await res.text();
} catch (error) {
retryable ||= error instanceof TypeError || (error instanceof Error && error.name === 'TimeoutError');
let reason = error instanceof Error ? error.message : String(error);
const causeDetails = error instanceof Error ? describeCause(error.cause) : '';
if (causeDetails) {
reason += ` (${causeDetails})`;
}
if (!retryable || attempt === attempts) {
throw new Error(`Unable to fetch cumulative update page ${url} after ${attempt} attempt(s): ${reason}`, { cause: error });
const pageUrl = new URL(url);
// http-client uses the proxy only when its URL has a host name
const found = getProxyUrl(pageUrl);
const proxy = found?.hostname ? found : undefined;
// name the proxy by its host, but not when the proxy URL has credentials: if they aren't encoded, parts of them can
// end up in the host
const proxyValue = pageUrl.protocol === 'https:'
? process.env.https_proxy || process.env.HTTPS_PROXY
: process.env.http_proxy || process.env.HTTP_PROXY;
const proxyName = proxy && !proxyValue?.includes('@') ? `the proxy ${proxy.host}` : 'the proxy';
const proxyHint = proxy
? `. The request went through ${proxyName}. To fetch the page directly, set NO_PROXY=${pageUrl.hostname} on the setup-sqlserver step`
: '';
if (proxy) {
core.info(`Fetching the cumulative update page through ${proxyName}`);
}
const client = new HttpClient('setup-sqlserver', [], { socketTimeout: UPDATE_PAGE_TIMEOUT });
try {
for (let attempt = 1; ; attempt++) {
try {
const res = await client.get(url);
const body = await readPageBody(res.message, url);
const status = res.message.statusCode ?? 0;
if (status === 403 && !proxy) {
// Microsoft has refused @actions/http-client requests for these pages before, while it accepted
// Node's fetch from the same runners. Node's fetch ignores the proxy settings, so use it only when
// no proxy applies.
core.info('Microsoft refused the cumulative update page request (HTTP 403); trying the page with fetch');
try {
return await fetchPageWithFetch(url);
} catch (error) {
throw new Error(`HTTP 403; with fetch: ${describeError(error)}`, { cause: error });
}
}
if (status < 200 || status > 299) {
throw new Error(`HTTP ${status}`);
}
return body;
} catch (error) {
const reason = describeError(error);
if (attempt === attempts) {
throw new Error(`Unable to fetch cumulative update page ${url} after ${attempt} attempt(s): ${reason}${proxyHint}`, { cause: error });
}
core.info(`Cumulative update page fetch failed (${reason}); retrying (${attempt + 1}/${attempts})`);
await delay(5000 * attempt);
}
core.info(`Cumulative update page fetch failed (${reason}); retrying (${attempt + 1}/${attempts})`);
await delay(5000 * attempt);
}
} finally {
client.dispose();
}
}

Expand Down
143 changes: 143 additions & 0 deletions test/update-page-proxy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
// Fetch a cumulative update page through a real proxy. Unlike test/utils.ts, this file does not mock
// @actions/http-client, so it checks that the page request really follows the proxy settings.
import { createServer, type Server } from 'node:http';
import { connect } from 'node:net';
import { describe, it, before, after, beforeEach, afterEach, mock } from 'node:test';
import assert from 'node:assert/strict';

const core = {
info: mock.fn(),
debug: mock.fn(),
warning: mock.fn(),
notice: mock.fn(),
isDebug: mock.fn(() => false),
};
const tc = {
downloadTool: mock.fn(async () => 'C:\\tmp\\update'),
cacheFile: mock.fn(async () => 'C:\\tools\\sqlupdate'),
};
const io = { mv: mock.fn(async () => {}) };

mock.module('@actions/core', { namedExports: core });
mock.module('@actions/tool-cache', { namedExports: tc });
mock.module('@actions/io', { namedExports: io });
mock.module('node:timers/promises', { namedExports: { setTimeout: async () => {} } });

const utils = await import('../src/utils.ts');

const updateUrl = 'https://download.microsoft.com/download/0/SQLServer2022-KB1-x64.exe';

function listen(server: Server): Promise<number> {
return new Promise((resolve) => {
server.listen(0, '127.0.0.1', () => {
const address = server.address();
resolve(typeof address === 'object' && address ? address.port : 0);
});
});
}

describe('cumulative update page through a proxy', () => {
// the page is on a host that doesn't exist, so the request can only reach it through the proxy
const config = { version: '2022', updateUrl: 'http://cu-page.test/en-us/download/details.aspx?id=1' };
let cut = false;
const page = createServer((req, res) => {
if (cut) {
// send part of the body, then close the connection
res.writeHead(200, { 'content-type': 'text/html', 'content-length': '1000' });
res.write('<a href=', () => req.socket.destroy());
return;
}
res.writeHead(200, { 'content-type': 'text/html' });
res.end(`<a href="${updateUrl}">download</a>`);
});
const tunnels: string[] = [];
let refuse = false;
// a CONNECT proxy that sends every tunnel to the page server
const proxy = createServer((_req, res) => {
res.writeHead(502).end();
});
let pagePort = 0;
let proxyPort = 0;
const env = ['https_proxy', 'HTTPS_PROXY', 'http_proxy', 'HTTP_PROXY', 'no_proxy', 'NO_PROXY'];
const original: Record<string, string | undefined> = {};

before(async () => {
pagePort = await listen(page);
proxy.on('connect', (req, socket) => {
tunnels.push(req.url ?? '');
if (refuse) {
socket.end('HTTP/1.1 407 Proxy Authentication Required\r\n\r\n');
return;
}
const upstream = connect(pagePort, '127.0.0.1', () => {
socket.write('HTTP/1.1 200 Connection Established\r\n\r\n');
upstream.pipe(socket);
socket.pipe(upstream);
});
upstream.on('error', () => socket.destroy());
socket.on('error', () => upstream.destroy());
});
proxyPort = await listen(proxy);
});
after(() => {
page.close();
proxy.close();
});
beforeEach(() => {
for (const name of env) {
original[name] = process.env[name];
delete process.env[name];
}
process.env.HTTP_PROXY = `http://127.0.0.1:${proxyPort}`;
tunnels.length = 0;
refuse = false;
cut = false;
for (const fn of [core.info, core.debug, core.warning, core.notice, tc.downloadTool, tc.cacheFile, io.mv]) {
fn.mock.resetCalls();
}
});
// restore in the reverse order: Windows treats https_proxy and HTTPS_PROXY as one variable, so the first save has
// the value and must be restored last
afterEach(() => {
for (const name of [...env].reverse()) {
if (original[name] === undefined) {
delete process.env[name];
} else {
process.env[name] = original[name];
}
}
});

it('fetches the page through the proxy', { timeout: 10_000 }, async () => {
await utils.downloadUpdateInstaller(config);
assert.deepEqual(tunnels, ['cu-page.test:80']);
assert.equal(tc.downloadTool.mock.calls[0].arguments[0], updateUrl);
assert.ok(core.info.mock.calls.some((c) => c.arguments[0] === `Fetching the cumulative update page through the proxy 127.0.0.1:${proxyPort}`));
});
it('reports a proxy that refuses the request, and how to fetch the page directly', { timeout: 10_000 }, async () => {
refuse = true;
await assert.rejects(() => utils.downloadUpdateInstaller(config), (error: Error) => {
assert.match(error.message, /after 3 attempt\(s\): .*statusCode=407/);
assert.match(error.message, /To fetch the page directly, set NO_PROXY=cu-page\.test on the setup-sqlserver step$/);
return true;
});
assert.equal(tunnels.length, 3);
assert.equal(tc.downloadTool.mock.callCount(), 0);
});
it('uses HTTPS_PROXY for an https page', { timeout: 10_000 }, async () => {
// the update pages are https, so this is the path that the action uses; the proxy refuses the tunnel, so the
// test needs no TLS server
delete process.env.HTTP_PROXY;
process.env.HTTPS_PROXY = `http://127.0.0.1:${proxyPort}`;
refuse = true;
const httpsConfig = { ...config, updateUrl: 'https://cu-page.test/en-us/download/details.aspx?id=1' };
await assert.rejects(() => utils.downloadUpdateInstaller(httpsConfig), /statusCode=407.*set NO_PROXY=cu-page\.test on the setup-sqlserver step$/);
assert.deepEqual(tunnels, ['cu-page.test:443', 'cu-page.test:443', 'cu-page.test:443']);
});
it('fails and retries when the connection closes before the end of the page', { timeout: 10_000 }, async () => {
cut = true;
await assert.rejects(() => utils.downloadUpdateInstaller(config), /after 3 attempt\(s\): aborted\./);
assert.equal(tunnels.length, 3);
assert.equal(tc.downloadTool.mock.callCount(), 0);
});
});
Loading
Loading