-
Notifications
You must be signed in to change notification settings - Fork 76
fix: support library downloads with virtual fs uris #1910
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
smorrisj
wants to merge
6
commits into
main
Choose a base branch
from
bug/web-table-dl
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
27d9741
fix: support table download with virtual fs uris
smorrisj efc29ae
fix: remove arbitrary timeout
smorrisj 0ac8037
chore: code cleanup
smorrisj d057b61
chore: add copyright to new files
smorrisj f665637
chore: cleanup
smorrisj 3fe2f50
Merge branch 'main' into bug/web-table-dl
smorrisj File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
225 changes: 225 additions & 0 deletions
225
client/src/components/LibraryNavigator/browserDownload.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,225 @@ | ||
| // Copyright © 2023, SAS Institute Inc., Cary, NC, USA. All Rights Reserved. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| import { Uri, env, l10n } from "vscode"; | ||
|
|
||
| import { randomBytes, timingSafeEqual } from "crypto"; | ||
| import { createServer } from "http"; | ||
|
|
||
| import LibraryDataProvider from "./LibraryDataProvider"; | ||
| import { LibraryItem } from "./types"; | ||
|
|
||
| const DOWNLOAD_TOKEN_BYTES = 24; // 192-bit token | ||
| const MAX_DOWNLOAD_FILENAME_LENGTH = 250; | ||
| const BROWSER_CONNECTION_TIMEOUT_MS = 60_000; | ||
| const DOWNLOAD_ENDPOINT_PATH = "/sas-library-download"; | ||
| const DOWNLOAD_TOKEN_PARAM = "token"; | ||
| const DEFAULT_DOWNLOAD_FILENAME = "table.csv"; | ||
|
|
||
| export function isValidDownloadToken( | ||
| candidate: string | null, | ||
| token: string, | ||
| ): boolean { | ||
| if (!candidate || candidate.length !== token.length) { | ||
| return false; | ||
| } | ||
| return timingSafeEqual(Buffer.from(candidate), Buffer.from(token)); | ||
| } | ||
|
|
||
| export function sanitizeDownloadFilename( | ||
| fileName: string, | ||
| maxLength: number, | ||
| fallback: string, | ||
| ): string { | ||
| // Preserve Unicode while removing only dangerous characters | ||
| return ( | ||
| fileName | ||
| .trim() | ||
| // eslint-disable-next-line no-control-regex | ||
| .replace(/[\x00-\x1f"\r\n]/g, "") // Remove control chars + quotes | ||
| .replace(/\.\.+/g, ".") // Collapse multiple dots (path traversal) | ||
| .replace(/^\.+/, "") // Remove leading dots | ||
| .slice(0, maxLength) || fallback | ||
| ); | ||
| } | ||
|
|
||
| export type DownloadRequestOutcome = | ||
| | { readonly outcome: 405 } | ||
| | { readonly outcome: 410 } | ||
| | { readonly outcome: 404 } | ||
| | { readonly outcome: "stream" }; | ||
|
|
||
| export function classifyDownloadRequest( | ||
| method: string | undefined, | ||
| url: string | undefined, | ||
| token: string, | ||
| endpointPath: string, | ||
| tokenParam: string, | ||
| requestLock: boolean, | ||
| ): DownloadRequestOutcome { | ||
| if (method !== "GET") { | ||
| return { outcome: 405 }; | ||
| } | ||
| if (requestLock) { | ||
| return { outcome: 410 }; | ||
| } | ||
| const requestUrl = url ? new URL(url, "http://127.0.0.1") : undefined; | ||
| if ( | ||
| !requestUrl || | ||
| requestUrl.pathname !== endpointPath || | ||
| !isValidDownloadToken(requestUrl.searchParams.get(tokenParam), token) | ||
| ) { | ||
| return { outcome: 404 }; | ||
| } | ||
| return { outcome: "stream" }; | ||
| } | ||
|
|
||
| export async function streamTableToBrowserDownload( | ||
| item: LibraryItem, | ||
| fileName: string, | ||
| libraryDataProvider: LibraryDataProvider, | ||
| ): Promise<void> { | ||
| const token = randomBytes(DOWNLOAD_TOKEN_BYTES).toString("hex"); | ||
| const asciiFileName = sanitizeDownloadFilename( | ||
| fileName, | ||
| MAX_DOWNLOAD_FILENAME_LENGTH, | ||
| DEFAULT_DOWNLOAD_FILENAME, | ||
| ); | ||
| const encodedFileName = encodeURIComponent(asciiFileName); | ||
|
|
||
| await new Promise<void>((resolve, reject) => { | ||
| let timeoutId: NodeJS.Timeout | undefined; | ||
| let requestLock = false; | ||
| let settled = false; | ||
|
|
||
| const settleResolve = () => { | ||
| if (settled) { | ||
| return; | ||
| } | ||
| settled = true; | ||
| if (timeoutId) { | ||
| clearTimeout(timeoutId); | ||
| timeoutId = undefined; | ||
| } | ||
| server.removeListener("error", errorHandler); | ||
| resolve(); | ||
| }; | ||
|
|
||
| const settleReject = (error: Error) => { | ||
| if (settled) { | ||
| return; | ||
| } | ||
| settled = true; | ||
| if (timeoutId) { | ||
| clearTimeout(timeoutId); | ||
| timeoutId = undefined; | ||
| } | ||
| server.removeListener("error", errorHandler); | ||
| server.close(() => {}); | ||
| reject(error); | ||
| }; | ||
|
|
||
| const server = createServer((request, response) => { | ||
| const verdict = classifyDownloadRequest( | ||
| request.method, | ||
| request.url, | ||
| token, | ||
| DOWNLOAD_ENDPOINT_PATH, | ||
| DOWNLOAD_TOKEN_PARAM, | ||
| requestLock, | ||
| ); | ||
|
|
||
| if (verdict.outcome !== "stream") { | ||
| response.statusCode = verdict.outcome; | ||
| if (verdict.outcome === 405) { | ||
| response.setHeader("Allow", "GET"); | ||
| } | ||
| response.end(); | ||
| return; | ||
| } | ||
|
|
||
| requestLock = true; | ||
| if (timeoutId) { | ||
| clearTimeout(timeoutId); | ||
| timeoutId = undefined; | ||
| } | ||
|
|
||
| response.setHeader("Content-Type", "text/csv; charset=utf-8"); | ||
| response.setHeader("Cache-Control", "no-store"); | ||
| response.setHeader("Pragma", "no-cache"); | ||
| response.setHeader("X-Content-Type-Options", "nosniff"); | ||
| response.setHeader( | ||
| "Content-Disposition", | ||
| `attachment; filename="${asciiFileName}"; filename*=UTF-8''${encodedFileName}`, | ||
| ); | ||
|
|
||
| libraryDataProvider | ||
| .writeTableContentsToStream(response, item) | ||
| .then(() => { | ||
| if (!response.writableEnded) { | ||
| response.end(); | ||
| } | ||
| settleResolve(); | ||
| }) | ||
| .catch((error) => { | ||
| if (!response.headersSent) { | ||
| response.statusCode = 500; | ||
| response.setHeader("Content-Type", "text/plain"); | ||
| response.end("Download failed"); | ||
| } else { | ||
| // Headers already sent - destroy connection to signal error to browser | ||
| response.destroy(); | ||
| } | ||
| settleReject(error); | ||
| }); | ||
| }); | ||
|
|
||
| const errorHandler = (error: Error) => { | ||
| if (timeoutId) { | ||
| clearTimeout(timeoutId); | ||
| timeoutId = undefined; | ||
| } | ||
| settleReject(error); | ||
| }; | ||
|
|
||
| server.on("error", errorHandler); | ||
|
|
||
| server.listen(0, "127.0.0.1", async () => { | ||
| try { | ||
| const address = server.address(); | ||
| if (!address || typeof address === "string") { | ||
| throw new Error(l10n.t("Unable to start download server.")); | ||
| } | ||
|
|
||
| // asExternalUri only transforms scheme+host+port — the proxy strips | ||
| // path and query. Resolve just the base, then append path+token. | ||
| const baseLocalUri = Uri.parse(`http://127.0.0.1:${address.port}`); | ||
| const externalBase = await env.asExternalUri(baseLocalUri); | ||
| const externalUri = Uri.parse( | ||
| `${externalBase.toString(true).replace(/\/+$/, "")}${DOWNLOAD_ENDPOINT_PATH}?${DOWNLOAD_TOKEN_PARAM}=${token}`, | ||
| ); | ||
| // Timeout guards against the browser never making the request. | ||
| // Once the request arrives and streaming begins, settleResolve() | ||
| // is called from the request handler instead. | ||
| // Arm before openExternal so no window exists between open and guard. | ||
| timeoutId = setTimeout(() => { | ||
| settleReject( | ||
| new Error( | ||
| l10n.t( | ||
| "Timed out waiting for the browser to start the download.", | ||
| ), | ||
| ), | ||
| ); | ||
| }, BROWSER_CONNECTION_TIMEOUT_MS); | ||
|
|
||
| const opened = await env.openExternal(externalUri); | ||
|
|
||
| if (!opened) { | ||
| throw new Error(l10n.t("Failed to open browser download URL.")); | ||
| } | ||
| } catch (error) { | ||
| server.close(); | ||
| settleReject(error); | ||
| } | ||
| }); | ||
| }); | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't love that we're only exposing these functions so that we can test them. I'd prefer just running all tests through what's available in the public interface, but I'm guessing it's likely easier this way and requires less setup