-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpythonRunner.mjs
More file actions
197 lines (176 loc) · 7 KB
/
Copy pathpythonRunner.mjs
File metadata and controls
197 lines (176 loc) · 7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
/**
* Jetson 워크스페이스 내 제한 실행 — 학생용 안전 샌드박스
*/
import fs from 'fs'
import path from 'path'
import { spawnSync } from 'child_process'
import crypto from 'crypto'
const RUN_TIMEOUT_MS = Number(process.env.RUN_TIMEOUT_MS) || 30_000
const MAX_CODE_BYTES = Number(process.env.MAX_CODE_BYTES) || 64 * 1024
const MAX_OUTPUT_CHARS = Number(process.env.MAX_OUTPUT_CHARS) || 48_000
const ALLOWED_IMPORTS = new Set(
(
process.env.ALLOWED_IMPORTS ||
'math,random,json,time,datetime,collections,itertools,statistics,typing,numpy,cv2,PIL'
)
.split(',')
.map((s) => s.trim())
.filter(Boolean),
)
/** 명백히 위험한 패턴 (정규식) */
const BLOCKED_PATTERNS = [
{ re: /\bimport\s+os\b/i, msg: 'os 모듈은 사용할 수 없어요' },
{ re: /\bfrom\s+os\b/i, msg: 'os 모듈은 사용할 수 없어요' },
{ re: /\bimport\s+subprocess\b/i, msg: 'subprocess는 사용할 수 없어요' },
{ re: /\bfrom\s+subprocess\b/i, msg: 'subprocess는 사용할 수 없어요' },
{ re: /\bimport\s+shutil\b/i, msg: 'shutil은 사용할 수 없어요' },
{ re: /\bimport\s+socket\b/i, msg: '네트워크(socket)는 사용할 수 없어요' },
{ re: /\bimport\s+requests\b/i, msg: '인터넷(requests)은 사용할 수 없어요' },
{ re: /\bimport\s+urllib\b/i, msg: '인터넷(urllib)은 사용할 수 없어요' },
{ re: /\bimport\s+http\b/i, msg: 'http 모듈은 사용할 수 없어요' },
{ re: /\bimport\s+ftplib\b/i, msg: 'ftp는 사용할 수 없어요' },
{ re: /\bimport\s+pickle\b/i, msg: 'pickle은 사용할 수 없어요' },
{ re: /\bimport\s+ctypes\b/i, msg: 'ctypes는 사용할 수 없어요' },
{ re: /\bimport\s+multiprocessing\b/i, msg: 'multiprocessing은 사용할 수 없어요' },
{ re: /\bimport\s+threading\b/i, msg: 'threading은 사용할 수 없어요' },
{ re: /\bpip\s+/i, msg: 'pip 설치는 IDE에서 할 수 없어요' },
{ re: /\beval\s*\(/i, msg: 'eval()은 사용할 수 없어요' },
{ re: /\bexec\s*\(/i, msg: 'exec()은 사용할 수 없어요' },
{ re: /\bcompile\s*\(/i, msg: 'compile()은 사용할 수 없어요' },
{ re: /\b__import__\s*\(/i, msg: '__import__()은 사용할 수 없어요' },
{ re: /\bos\.system\b/i, msg: '시스템 명령(os.system)은 사용할 수 없어요' },
{ re: /\bos\.popen\b/i, msg: '시스템 명령(os.popen)은 사용할 수 없어요' },
{ re: /\bos\.exec/i, msg: '시스템 실행(os.exec*)은 사용할 수 없어요' },
{ re: /\bos\.remove\b/i, msg: '파일 삭제(os.remove)는 사용할 수 없어요' },
{ re: /\bos\.unlink\b/i, msg: '파일 삭제는 사용할 수 없어요' },
{ re: /\bshutil\.rmtree\b/i, msg: '폴더 삭제는 사용할 수 없어요' },
{ re: /\bopen\s*\(\s*['"]\//i, msg: '시스템 절대경로 파일은 열 수 없어요' },
{ re: /\bopen\s*\(\s*['"]\.\./i, msg: '상위 폴더(../) 파일은 열 수 없어요' },
]
const IMPORT_RE = /^\s*(?:import\s+([\w.]+)|from\s+([\w.]+)\s+import)/gm
/** 배포 시 RUN_VALIDATE=1 로 켜기. 기본은 검사 끔(학습·input 테스트용) */
export function shouldValidateCode() {
return process.env.RUN_VALIDATE === '1'
}
export function validatePythonCode(code) {
if (!shouldValidateCode()) return { ok: true }
if (!code || typeof code !== 'string') {
return { ok: false, reason: '코드가 비어 있어요' }
}
if (Buffer.byteLength(code, 'utf8') > MAX_CODE_BYTES) {
return { ok: false, reason: `코드가 너무 길어요 (최대 ${MAX_CODE_BYTES / 1024}KB)` }
}
for (const { re, msg } of BLOCKED_PATTERNS) {
if (re.test(code)) return { ok: false, reason: msg }
}
let m
IMPORT_RE.lastIndex = 0
while ((m = IMPORT_RE.exec(code)) !== null) {
const root = (m[1] || m[2]).split('.')[0]
if (!ALLOWED_IMPORTS.has(root)) {
return {
ok: false,
reason: `'${root}' 모듈은 허용 목록에 없어요. 사용 가능: ${[...ALLOWED_IMPORTS].sort().join(', ')}`,
}
}
}
return { ok: true }
}
function truncate(s, max) {
if (!s || s.length <= max) return s || ''
return s.slice(0, max) + '\n...(출력 잘림)'
}
/**
* @param {string} code
* @param {{ workspace: string, pythonBin?: string }} opts
*/
export function runPythonOnJetson(code, opts) {
const workspace = path.resolve(opts.workspace)
const validation = validatePythonCode(code)
if (!validation.ok) {
return { ok: false, output: '', error: validation.reason, blocked: true }
}
const runsDir = path.join(workspace, '.runs')
fs.mkdirSync(runsDir, { recursive: true })
const id = crypto.randomBytes(6).toString('hex')
const scriptPath = path.join(runsDir, `student_${id}.py`)
try {
fs.writeFileSync(scriptPath, code, 'utf-8')
const pythonBin = opts.pythonBin || process.env.PYTHON_BIN || 'python3'
const env = {
...process.env,
PYTHONNOUSERSITE: '1',
PYTHONDONTWRITEBYTECODE: '1',
HOME: runsDir,
TMPDIR: runsDir,
LANG: 'C.UTF-8',
}
delete env.PYTHONPATH
const result = spawnSync(pythonBin, ['-u', scriptPath], {
cwd: workspace,
env,
encoding: 'utf-8',
timeout: RUN_TIMEOUT_MS,
maxBuffer: 512 * 1024,
})
const stdout = truncate(result.stdout || '', MAX_OUTPUT_CHARS)
const stderr = truncate(result.stderr || '', MAX_OUTPUT_CHARS)
if (result.error?.code === 'ETIMEDOUT' || result.signal === 'SIGTERM') {
return {
ok: false,
output: stdout,
error: `실행 시간 초과 (${RUN_TIMEOUT_MS / 1000}초). 무한 루프가 있는지 확인해 주세요.`,
timedOut: true,
}
}
if (result.status !== 0) {
const errText = stderr || result.error?.message || `종료 코드 ${result.status}`
return { ok: false, output: stdout, error: errText.trim() }
}
const combined = [stdout, stderr].filter(Boolean).join(stderr && stdout ? '\n' : '')
return {
ok: true,
output: combined || '(출력 없음)',
error: null,
}
} catch (e) {
return {
ok: false,
output: '',
error: e instanceof Error ? e.message : String(e),
}
} finally {
try {
fs.unlinkSync(scriptPath)
} catch {
/* ignore */
}
}
}
export function runnerConfig() {
return {
mode: 'jetson',
interactive: true,
validateCode: shouldValidateCode(),
timeoutSec: RUN_TIMEOUT_MS / 1000,
maxCodeKb: MAX_CODE_BYTES / 1024,
allowedImports: [...ALLOWED_IMPORTS].sort(),
blockedSummary: shouldValidateCode()
? 'os, subprocess, 네트워크, eval/exec, pip, 시스템 경로 파일'
: '검사 꺼짐 (배포 시 RUN_VALIDATE=1)',
}
}
export async function checkRunnerReady(workspace) {
const pythonBin = process.env.PYTHON_BIN || 'python3'
try {
const r = spawnSync(pythonBin, ['--version'], { encoding: 'utf-8', timeout: 5000 })
const version = (r.stdout || r.stderr || '').trim()
return {
ready: r.status === 0,
python: version,
workspace: path.resolve(workspace),
}
} catch {
return { ready: false, python: null, workspace: path.resolve(workspace) }
}
}