Refactor runtime app architecture (#1878)
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
import { mkdtemp, mkdir, realpath, symlink, writeFile } from 'fs/promises'
|
||||
import { tmpdir } from 'os'
|
||||
import { join } from 'path'
|
||||
import { Writable } from 'stream'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { SFTPWrapper } from 'ssh2'
|
||||
import { uploadBuffer, uploadDirectory, uploadFile } from './sftp-upload'
|
||||
|
||||
function createWritable(): Writable {
|
||||
return new Writable({
|
||||
write(_chunk, _encoding, callback) {
|
||||
callback()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function createSftpMock(): SFTPWrapper {
|
||||
return {
|
||||
mkdir: vi.fn((_path: string, cb: (err?: Error | null) => void) => cb(null)),
|
||||
createWriteStream: vi.fn(() => createWritable())
|
||||
} as unknown as SFTPWrapper
|
||||
}
|
||||
|
||||
describe('sftp-upload', () => {
|
||||
it('can create the first binary upload chunk without clobbering an existing temp file', async () => {
|
||||
const sftp = createSftpMock()
|
||||
|
||||
await uploadBuffer(sftp, Buffer.from('png'), '/remote/.logo.orca-upload', {
|
||||
exclusive: true
|
||||
})
|
||||
|
||||
expect(sftp.createWriteStream).toHaveBeenCalledWith('/remote/.logo.orca-upload', {
|
||||
flags: 'wx'
|
||||
})
|
||||
})
|
||||
|
||||
it('uses no-clobber writes for nested files during exclusive directory upload', async () => {
|
||||
const localDir = await mkdtemp(join(tmpdir(), 'orca-sftp-upload-'))
|
||||
await mkdir(join(localDir, 'nested'))
|
||||
await writeFile(join(localDir, 'nested', 'asset.txt'), 'asset')
|
||||
const sftp = createSftpMock()
|
||||
|
||||
await uploadDirectory(sftp, localDir, '/remote/assets', await realpath(localDir), {
|
||||
exclusive: true
|
||||
})
|
||||
|
||||
expect(sftp.mkdir).toHaveBeenCalledWith('/remote/assets/nested', expect.any(Function))
|
||||
expect(sftp.createWriteStream).toHaveBeenCalledWith('/remote/assets/nested/asset.txt', {
|
||||
flags: 'wx'
|
||||
})
|
||||
})
|
||||
|
||||
it('does not create the remote file when the local source is a symlink', async () => {
|
||||
const localDir = await mkdtemp(join(tmpdir(), 'orca-sftp-upload-'))
|
||||
await writeFile(join(localDir, 'target.txt'), 'secret')
|
||||
await symlink(join(localDir, 'target.txt'), join(localDir, 'link.txt'))
|
||||
const sftp = createSftpMock()
|
||||
|
||||
await expect(uploadFile(sftp, join(localDir, 'link.txt'), '/remote/link.txt')).rejects.toThrow()
|
||||
|
||||
expect(sftp.createWriteStream).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
+96
-18
@@ -1,16 +1,21 @@
|
||||
import { createReadStream } from 'fs'
|
||||
import { readdir } from 'fs/promises'
|
||||
import { join as pathJoin } from 'path'
|
||||
import { constants } from 'fs'
|
||||
import type { ReadStream } from 'fs'
|
||||
import { lstat, open, readdir, realpath } from 'fs/promises'
|
||||
import { isAbsolute, join as pathJoin, relative } from 'path'
|
||||
import type { SFTPWrapper } from 'ssh2'
|
||||
|
||||
export function mkdirSftp(sftp: SFTPWrapper, path: string): Promise<void> {
|
||||
export function mkdirSftp(
|
||||
sftp: SFTPWrapper,
|
||||
path: string,
|
||||
options?: { allowExisting?: boolean }
|
||||
): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
sftp.mkdir(path, (err) => {
|
||||
// Why: SFTP status code 4 (SSH_FX_FAILURE) is a generic code that
|
||||
// OpenSSH returns for "already exists," but could also cover other
|
||||
// failures (e.g. permission denied on parent). We accept this ambiguity
|
||||
// because the next operation (write/recurse) will surface the real error.
|
||||
if (err && (err as { code?: number }).code !== 4) {
|
||||
if (err && ((err as { code?: number }).code !== 4 || options?.allowExisting === false)) {
|
||||
reject(err)
|
||||
} else {
|
||||
resolve()
|
||||
@@ -22,58 +27,131 @@ export function mkdirSftp(sftp: SFTPWrapper, path: string): Promise<void> {
|
||||
export function uploadFile(
|
||||
sftp: SFTPWrapper,
|
||||
localPath: string,
|
||||
remotePath: string
|
||||
remotePath: string,
|
||||
options?: { exclusive?: boolean }
|
||||
): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let settled = false
|
||||
const readStream = createReadStream(localPath)
|
||||
const writeStream = sftp.createWriteStream(remotePath)
|
||||
let readStream: ReadStream | null = null
|
||||
let fileHandle: Awaited<ReturnType<typeof open>> | null = null
|
||||
let writeStream: ReturnType<SFTPWrapper['createWriteStream']> | null = null
|
||||
|
||||
const settle = (fn: typeof resolve | typeof reject, val?: unknown): void => {
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
settled = true
|
||||
readStream?.destroy()
|
||||
writeStream?.destroy()
|
||||
void fileHandle?.close().catch(() => {})
|
||||
fn(val as never)
|
||||
}
|
||||
|
||||
void open(localPath, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0))
|
||||
.then(async (handle) => {
|
||||
if (settled) {
|
||||
void handle.close().catch(() => {})
|
||||
return
|
||||
}
|
||||
fileHandle = handle
|
||||
const statResult = await lstat(localPath)
|
||||
if (statResult.isSymbolicLink() || !statResult.isFile()) {
|
||||
throw new Error(`Unsupported upload source: ${localPath}`)
|
||||
}
|
||||
const openedStat = await handle.stat()
|
||||
if (
|
||||
!openedStat.isFile() ||
|
||||
openedStat.size !== statResult.size ||
|
||||
(statResult.ino !== 0 && openedStat.ino !== 0 && openedStat.ino !== statResult.ino) ||
|
||||
(statResult.dev !== 0 && openedStat.dev !== 0 && openedStat.dev !== statResult.dev)
|
||||
) {
|
||||
throw new Error(`File changed during upload: ${localPath}`)
|
||||
}
|
||||
// Why: validate the local source before creating the remote write
|
||||
// target, so rejected sources do not leave empty files behind.
|
||||
writeStream = sftp.createWriteStream(remotePath, {
|
||||
flags: options?.exclusive ? 'wx' : 'w'
|
||||
})
|
||||
writeStream.on('close', () => settle(resolve))
|
||||
writeStream.on('error', (err) => settle(reject, err))
|
||||
readStream = handle.createReadStream()
|
||||
readStream.on('error', (err) => settle(reject, err))
|
||||
readStream.pipe(writeStream)
|
||||
})
|
||||
.catch((err: unknown) => settle(reject, err))
|
||||
})
|
||||
}
|
||||
|
||||
export function uploadBuffer(
|
||||
sftp: SFTPWrapper,
|
||||
buffer: Buffer,
|
||||
remotePath: string,
|
||||
options?: { append?: boolean; exclusive?: boolean }
|
||||
): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let settled = false
|
||||
const writeStream = sftp.createWriteStream(remotePath, {
|
||||
flags: options?.append ? 'a' : options?.exclusive ? 'wx' : 'w'
|
||||
})
|
||||
|
||||
const settle = (fn: typeof resolve | typeof reject, val?: unknown): void => {
|
||||
if (settled) {
|
||||
return
|
||||
}
|
||||
settled = true
|
||||
readStream.destroy()
|
||||
writeStream.destroy()
|
||||
fn(val as never)
|
||||
}
|
||||
|
||||
writeStream.on('close', () => settle(resolve))
|
||||
writeStream.on('error', (err) => settle(reject, err))
|
||||
readStream.on('error', (err) => settle(reject, err))
|
||||
|
||||
readStream.pipe(writeStream)
|
||||
writeStream.end(buffer)
|
||||
})
|
||||
}
|
||||
|
||||
export async function uploadDirectory(
|
||||
sftp: SFTPWrapper,
|
||||
localDir: string,
|
||||
remoteDir: string
|
||||
remoteDir: string,
|
||||
rootRealPath = localDir,
|
||||
options?: { exclusive?: boolean }
|
||||
): Promise<void> {
|
||||
await assertLocalUploadPathInsideRoot(rootRealPath, localDir)
|
||||
const entries = await readdir(localDir, { withFileTypes: true })
|
||||
for (const entry of entries) {
|
||||
const localPath = pathJoin(localDir, entry.name)
|
||||
const remotePath = `${remoteDir}/${entry.name}`
|
||||
await assertLocalUploadPathInsideRoot(rootRealPath, localPath)
|
||||
const statResult = await lstat(localPath)
|
||||
|
||||
// Why: skip symlinks and special files (sockets, FIFOs, devices) to
|
||||
// prevent following symlinks that could exfiltrate local files to the
|
||||
// remote. The caller's pre-scan catches symlinks up-front, but this
|
||||
// guard closes the TOCTOU gap if one is created between scan and upload.
|
||||
if (entry.isSymbolicLink() || (!entry.isFile() && !entry.isDirectory())) {
|
||||
if (statResult.isSymbolicLink() || (!statResult.isFile() && !statResult.isDirectory())) {
|
||||
continue
|
||||
}
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
await mkdirSftp(sftp, remotePath)
|
||||
await uploadDirectory(sftp, localPath, remotePath)
|
||||
if (statResult.isDirectory()) {
|
||||
await mkdirSftp(sftp, remotePath, { allowExisting: !options?.exclusive })
|
||||
await uploadDirectory(sftp, localPath, remotePath, rootRealPath, options)
|
||||
} else {
|
||||
await uploadFile(sftp, localPath, remotePath)
|
||||
await uploadFile(sftp, localPath, remotePath, { exclusive: options?.exclusive })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function assertLocalUploadPathInsideRoot(
|
||||
rootRealPath: string,
|
||||
candidatePath: string
|
||||
): Promise<void> {
|
||||
const candidateRealPath = await realpath(candidatePath)
|
||||
const relativeToRoot = relative(rootRealPath, candidateRealPath)
|
||||
if (relativeToRoot !== '' && (relativeToRoot.startsWith('..') || isAbsolute(relativeToRoot))) {
|
||||
throw new Error(`Path escaped upload root: ${candidatePath}`)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a path exists on the remote via SFTP lstat.
|
||||
* Returns true if the path exists (file, directory, or symlink).
|
||||
|
||||
@@ -74,6 +74,7 @@ export class SshRelaySession {
|
||||
| null = null
|
||||
private _onReady: ((targetId: string) => void) | null = null
|
||||
private portScanner: PortScanner | null = null
|
||||
private currentConnection: SshConnection | null = null
|
||||
|
||||
constructor(
|
||||
readonly targetId: string,
|
||||
@@ -113,6 +114,13 @@ export class SshRelaySession {
|
||||
return (this._state as RelaySessionState) === 'disposed'
|
||||
}
|
||||
|
||||
private requireReadyConnection(): SshConnection {
|
||||
if (!this.currentConnection) {
|
||||
throw new Error('SSH connection is not active')
|
||||
}
|
||||
return this.currentConnection
|
||||
}
|
||||
|
||||
getMux(): SshChannelMultiplexer | null {
|
||||
return this.mux
|
||||
}
|
||||
@@ -129,6 +137,7 @@ export class SshRelaySession {
|
||||
throw new Error(`Cannot establish relay session in state: ${this._state}`)
|
||||
}
|
||||
this._state = 'deploying'
|
||||
this.currentConnection = conn
|
||||
|
||||
try {
|
||||
const { transport } = await deployAndLaunchRelay(
|
||||
@@ -239,6 +248,7 @@ export class SshRelaySession {
|
||||
this.abortController = abortController
|
||||
|
||||
this._state = 'reconnecting'
|
||||
this.currentConnection = conn
|
||||
|
||||
// Why: stop scanning before teardownProviders so the polling timer doesn't
|
||||
// fire against a disposed multiplexer.
|
||||
@@ -371,6 +381,7 @@ export class SshRelaySession {
|
||||
this.broadcastEmptyLists()
|
||||
this.teardownProviders('shutdown')
|
||||
this.store.markSshRemotePtyLeases(this.targetId, 'terminated')
|
||||
this.currentConnection = null
|
||||
this._state = 'disposed'
|
||||
}
|
||||
|
||||
@@ -386,6 +397,7 @@ export class SshRelaySession {
|
||||
// clearing PTY ownership needed for reattach.
|
||||
this.teardownProviders('connection_lost')
|
||||
this.store.markSshRemotePtyLeases(this.targetId, 'detached')
|
||||
this.currentConnection = null
|
||||
this._state = 'disposed'
|
||||
}
|
||||
|
||||
@@ -427,7 +439,9 @@ export class SshRelaySession {
|
||||
const ptyProvider = new SshPtyProvider(this.targetId, mux)
|
||||
registerSshPtyProvider(this.targetId, ptyProvider)
|
||||
|
||||
const fsProvider = new SshFilesystemProvider(this.targetId, mux)
|
||||
const fsProvider = new SshFilesystemProvider(this.targetId, mux, () =>
|
||||
this.requireReadyConnection().sftp()
|
||||
)
|
||||
registerSshFilesystemProvider(this.targetId, fsProvider)
|
||||
|
||||
const gitProvider = new SshGitProvider(this.targetId, mux)
|
||||
|
||||
Reference in New Issue
Block a user