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
4 changes: 4 additions & 0 deletions omarchyd/server.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import {createUpdater} from './updater.mjs'
import {createSystemApps} from './system-apps.mjs'
import {controlHostService, hostServiceLogs, listHostServices} from './host-services.mjs'
import {createTailscale} from './tailscale.mjs'
import {allowUploadBody} from './upload-body.mjs'
import {createConnect} from './connect.mjs'
import {createOidc} from './oidc.mjs'
import {createHyprland, isVncInput} from './hyprland.mjs'
Expand Down Expand Up @@ -1556,12 +1557,14 @@ WantedBy=graphical-session.target
const auth = accounts.authenticate(req)
if (!auth) return sendJson(res, 401, {error: 'unauthorized'})
ownerOnly(auth, 'upload files to containers')
allowUploadBody(req)
return sendJson(res, 200, await containers.acceptUpload(url.searchParams.get('name') ?? '', url.searchParams.get('path') ?? '', req, url.searchParams.get('hostId')))
}
if (url.pathname === '/api/swarm/files/upload' && req.method === 'POST') {
const auth = accounts.authenticate(req)
if (!auth) return sendJson(res, 401, {error: 'unauthorized'})
ownerOnly(auth, 'upload files to the local swarm')
allowUploadBody(req)
const id = url.searchParams.get('id') ?? ''
const remotePath = url.searchParams.get('path') ?? ''
let size = 0
Expand All @@ -1578,6 +1581,7 @@ WantedBy=graphical-session.target
if ((fileKind === 'upload' || fileKind === 'upload-chunk') && req.method === 'POST') {
const auth = accounts.authenticate(req)
if (!auth || auth.kind !== 'browser') return sendJson(res, 401, {error: 'unauthorized'})
allowUploadBody(req)
return await (fileKind === 'upload' ? files.upload(req, res, url) : files.uploadChunk(req, res, url))
}
if ((fileKind === 'view' || fileKind === 'download') && req.method === 'GET') {
Expand Down
38 changes: 38 additions & 0 deletions omarchyd/upload-body.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Node gives every request body 5 minutes, then answers 408. A file upload is allowed
// 12 hours, the same ceiling the web server already puts on its relay. That longer
// limit applies only while an upload body is still arriving, and only on that server.
// Headers keep their own shorter limit. A server that already has no request limit is left alone.

const depths = new WeakMap()
const saved = new WeakMap()

export const UPLOAD_BODY_MS = 12 * 60 * 60 * 1000

export function allowUploadBody(req) {
const server = req.socket?.server
if (!server || typeof server.requestTimeout !== 'number') return () => {}
// Already unlimited, or already as long as an upload, and not because of us.
if (!depths.has(server) && (server.requestTimeout === 0 || server.requestTimeout >= UPLOAD_BODY_MS)) return () => {}
const n = (depths.get(server) ?? 0) + 1
depths.set(server, n)
if (n === 1) {
saved.set(server, server.requestTimeout)
server.requestTimeout = UPLOAD_BODY_MS
}
let released = false
const release = () => {
if (released) return
released = true
const left = (depths.get(server) ?? 1) - 1
if (left > 0) {
depths.set(server, left)
return
}
depths.delete(server)
const previous = saved.get(server)
saved.delete(server)
if (typeof previous === 'number') server.requestTimeout = previous
}
req.on('close', release)
return release
}
4 changes: 4 additions & 0 deletions server/app.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import {createBackendClient, BackendError} from './backend.mjs'
import {hashId, newSessionId} from './store.mjs'
import {createRemoteGate} from './remote-gate.mjs'
import {createQuickTransfer, cleanUploadName, transferPlace, PORTAL_JS, portalHtml} from './quick-transfer.mjs'
import {allowUploadBody} from '../omarchyd/upload-body.mjs'

export const VERSION = '0.9.135'

Expand Down Expand Up @@ -1445,6 +1446,7 @@ export function createApp({store, staticDir, connectorDir = staticDir ? join(sta
const hostId = String(req.query.hostId ?? '')
if (!CONTAINER_NAME.test(name) || !path.startsWith('/')) return res.status(400).json({error: {code: 'BAD_REQUEST', message: 'Missing file parameters'}})
if (hostId && !/^[0-9a-f]{12}$/.test(hostId)) return res.status(400).json({error: {code: 'BAD_REQUEST', message: 'That computer isn’t valid.'}})
allowUploadBody(req)
const params = new URLSearchParams({name, path})
if (hostId) params.set('hostId', hostId)
try {
Expand All @@ -1467,6 +1469,7 @@ export function createApp({store, staticDir, connectorDir = staticDir ? join(sta
const id = String(req.query.id ?? '')
const remotePath = String(req.query.path ?? '')
if (!/^[0-9a-f]{12}$/.test(id) || !remotePath) return res.status(400).json({error: {code: 'BAD_REQUEST', message: 'Missing file parameters'}})
allowUploadBody(req)
try {
let size = 0
const chunks = []
Expand Down Expand Up @@ -2119,6 +2122,7 @@ export function createApp({store, staticDir, connectorDir = staticDir ? join(sta
url.searchParams.set('offset', offset)
url.searchParams.set('total', total)
}
allowUploadBody(req)
const {Readable} = await import('node:stream')
const upstream = await fetchImpl(url, {
method: 'POST',
Expand Down
93 changes: 93 additions & 0 deletions test/upload-body.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
// A file upload may take longer than Node's 5 minute body limit. Other requests keep it.
import assert from 'node:assert/strict'
import http from 'node:http'
import net from 'node:net'
import {test} from 'node:test'

import {UPLOAD_BODY_MS, allowUploadBody} from '../omarchyd/upload-body.mjs'

function start() {
return new Promise((resolve) => {
const server = http.createServer({connectionsCheckingInterval: 40, requestTimeout: 200, headersTimeout: 100}, (req, res) => {
if (req.url.startsWith('/upload')) allowUploadBody(req)
req.on('data', () => {})
req.on('end', () => {
if (!res.writableEnded) res.end('done')
})
})
server.listen(0, '127.0.0.1', () => resolve(server))
})
}

function post(port, path, bodyDelay) {
return new Promise((resolve) => {
const sock = net.connect(port, '127.0.0.1', () => {
sock.write(`POST ${path} HTTP/1.1\r\nHost: localhost\r\nContent-Length: 4\r\n\r\n`)
setTimeout(() => sock.write('abcd'), bodyDelay)
})
let buf = ''
const timer = setTimeout(() => {
sock.destroy()
resolve({status: 0, body: buf})
}, 2000)
sock.on('data', (d) => {
buf += d
const m = buf.match(/HTTP\/1\.1 (\d+)/)
if (m && (buf.includes('done') || m[1] === '408')) {
clearTimeout(timer)
sock.end()
resolve({status: Number(m[1]), body: buf})
}
})
sock.on('error', () => {
clearTimeout(timer)
resolve({status: 0, body: buf})
})
})
}

test('a slow upload body is allowed 12 hours, and any other slow body is still cut off', async () => {
const server = await start()
try {
assert.equal(server.requestTimeout, 200)
assert.equal(server.headersTimeout, 100)
const refused = await post(server.address().port, '/other', 500)
assert.equal(refused.status, 408)
assert.equal(server.requestTimeout, 200, 'a request that is not an upload leaves the limit alone')

const kept = await post(server.address().port, '/upload', 500)
assert.equal(kept.status, 200)
assert.equal(server.requestTimeout, 200, 'the 5 minute limit returns when the upload body finishes')

const refusedAgain = await post(server.address().port, '/other', 500)
assert.equal(refusedAgain.status, 408)
} finally {
await new Promise((resolve) => server.close(resolve))
}
})

test('two overlapping uploads keep the longer limit until both bodies have finished', async () => {
const server = await start()
const port = server.address().port
try {
const first = post(port, '/upload', 700)
await new Promise((r) => setTimeout(r, 80))
assert.equal(server.requestTimeout, UPLOAD_BODY_MS)
assert.equal(server.headersTimeout, 100, 'headers keep their own limit')
const second = post(port, '/upload', 400)
await new Promise((r) => setTimeout(r, 200))
assert.equal(server.requestTimeout, UPLOAD_BODY_MS, 'the first upload is still arriving')
assert.equal((await second).status, 200)
assert.equal(server.requestTimeout, UPLOAD_BODY_MS, 'one upload is still arriving')
assert.equal((await first).status, 200)
assert.equal(server.requestTimeout, 200)
} finally {
await new Promise((resolve) => server.close(resolve))
}
})

test('the web server does not turn the limit off for every request', async () => {
const {readFile} = await import('node:fs/promises')
const cli = await readFile(new URL('../server/cli.mjs', import.meta.url), 'utf8')
assert.doesNotMatch(cli, /requestTimeout\s*=\s*0/)
})
Loading