-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.py
306 lines (261 loc) · 11.3 KB
/
server.py
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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
# Copyright (c) 2022, TU Wien
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import os
import shlex
import subprocess
from pathlib import Path
from string import Template
from typing import List, Optional
from grader_service.handlers.base_handler import (GraderBaseHandler,
RequestHandlerConfig)
from grader_service.orm.lecture import Lecture
from grader_service.orm.submission import Submission
from grader_service.orm.takepart import Role, Scope
from grader_service.registry import VersionSpecifier, register_handler
from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound
from tornado.ioloop import IOLoop
from tornado.process import Subprocess
from tornado.web import HTTPError, stream_request_body
class GitBaseHandler(GraderBaseHandler):
async def data_received(self, chunk: bytes):
return self.process.stdin.write(chunk)
def write_error(self, status_code: int, **kwargs) -> None:
self.clear()
if status_code == 401:
self.set_header("WWW-Authenticate",
'Basic realm="User Visible Realm"')
self.set_status(status_code)
def on_finish(self):
if hasattr(
self, "process"
): # if we exit super prepare (authentication) process is not created
if self.process.stdin is not None:
self.process.stdin.close()
if self.process.stdout is not None:
self.process.stdout.close()
if self.process.stderr is not None:
self.process.stderr.close()
IOLoop.current().spawn_callback(self.process.wait_for_exit)
async def git_response(self):
try:
while data := await self.process.stdout.read_bytes(8192,
partial=True):
self.write(data)
await self.flush()
except Exception as e:
print(f"Error from git response {e}")
def _check_git_repo_permissions(self, rpc: str, role: Role,
pathlets: List[str]):
repo_type = pathlets[2]
if role.role == Scope.student:
# 1. no source or release interaction with source repo for students
# 2. no pull allowed for autograde for students
if ((repo_type in ["source", "release", "edit"])
or (repo_type == "autograde" and rpc == "upload-pack")):
raise HTTPError(403)
# 3. students should not be able to pull other submissions
# -> add query param for sub_id
if (repo_type == "feedback") and (rpc == "upload-pack"):
try:
sub_id = int(pathlets[3])
except (ValueError, IndexError):
raise HTTPError(403)
submission = self.session.query(Submission).get(sub_id)
if submission is None or submission.username != self.user.name:
raise HTTPError(403)
# 4. no push allowed for autograde and feedback
# -> the autograder executor can push locally (will bypass this)
if ((repo_type in ["autograde", "feedback"])
and (rpc in ["send-pack", "receive-pack"])):
raise HTTPError(403)
def gitlookup(self, rpc: str):
pathlets = self.request.path.strip("/").split("/")
# pathlets = ['services', 'grader', 'git',
# 'lecture_code', 'assignment_id', 'repo_type', ...]
if len(pathlets) < 6:
return None
pathlets = pathlets[3:]
lecture_path = os.path.abspath(os.path.join(self.gitbase, pathlets[0]))
assignment_path = os.path.abspath(
os.path.join(self.gitbase, pathlets[0], pathlets[1])
)
repo_type = pathlets[2]
if repo_type not in {
"source",
"release",
"assignment",
"autograde",
"feedback",
"edit"
}:
return None
# get lecture and assignment if they exist
try:
lecture = (
self.session.query(Lecture).filter(Lecture.code == pathlets[0]).one() # noqa
)
except NoResultFound:
raise HTTPError(404, reason="Lecture was not found")
except MultipleResultsFound:
raise HTTPError(500, reason="Found more than one lecture")
role = self.session.query(Role).get((self.user.name, lecture.id))
self._check_git_repo_permissions(rpc, role, pathlets)
try:
assignment = self.get_assignment(lecture.id, int(pathlets[1]))
except ValueError:
raise HTTPError(404, "Assignment not found")
if repo_type == "assignment":
repo_type: str = assignment.type
# create directories once we know they exist in the database
if not os.path.exists(lecture_path):
os.mkdir(lecture_path)
if not os.path.exists(assignment_path):
os.mkdir(assignment_path)
submission = None
if repo_type in ["autograde", "feedback", "edit"]:
try:
sub_id = int(pathlets[3])
except (ValueError, IndexError):
raise HTTPError(403)
submission = self.session.query(Submission).get(sub_id)
path = self.construct_git_dir(repo_type, lecture, assignment,
submission=submission)
if path is None:
return None
os.makedirs(os.path.dirname(path), exist_ok=True)
is_git = self.is_base_git_dir(path)
# return git repo
if os.path.exists(path) and is_git:
self.write_pre_receive_hook(path)
return path
else:
os.mkdir(path)
# this path has to be a git dir -> call git init
try:
self.log.info("Running: git init --bare")
subprocess.run(["git", "init", "--bare", path], check=True)
except subprocess.CalledProcessError:
return None
if repo_type in ["user", "group"]:
repo_path_release = self.construct_git_dir('release',
assignment.lecture,
assignment)
safe_repo_path_release = repo_path_release
err_msg = "Error: expceted path or str, got None"
assert safe_repo_path_release is not None, err_msg
if not os.path.exists(safe_repo_path_release):
return None
self.duplicate_release_repo(
repo_path_release=safe_repo_path_release,
repo_path_user=path,
assignment=assignment,
message="Initialize with Release",
checkout_main=True)
self.write_pre_receive_hook(path)
return path
def write_pre_receive_hook(self, path: str):
hook_dir = os.path.join(path, "hooks")
if not os.path.exists(hook_dir):
os.mkdir(hook_dir)
hook_file = os.path.join(hook_dir, "pre-receive")
if not os.path.exists(hook_file):
tpl = Template(self._read_hook_template())
hook = tpl.safe_substitute({
"tpl_max_file_size": self._get_hook_max_file_size(),
"tpl_file_extensions": self._get_hook_file_allow_pattern(),
"tpl_max_file_count": self._get_hook_max_file_count()
})
with open(hook_file, "wt") as f:
os.chmod(hook_file, 0o755)
f.write(hook)
@staticmethod
def _get_hook_file_allow_pattern(extensions: Optional[List[str]] = None) -> str: # noqa E501
pattern = ""
if extensions is None:
req_handler_conf = RequestHandlerConfig.instance()
extensions = req_handler_conf.git_allowed_file_extensions
if len(extensions) > 0:
allow_patterns = ["\\." + s.strip(".").replace(".", "\\.") for s in extensions] # noqa E501
pattern = "|".join(allow_patterns)
return pattern
@staticmethod
def _get_hook_max_file_size():
return RequestHandlerConfig.instance().git_max_file_size_mb
@staticmethod
def _get_hook_max_file_count():
return RequestHandlerConfig.instance().git_max_file_count
@staticmethod
def _read_hook_template() -> str:
file_path = Path(__file__).parent / "hook_templates" / "pre-receive"
with open(file_path, mode="rt") as f:
return f.read()
@staticmethod
def _create_path(path):
if not os.path.exists(path):
os.mkdir(path)
def get_gitdir(self, rpc: str):
"""Determine the git repository for this request"""
gitdir = self.gitlookup(rpc)
if gitdir is None:
raise HTTPError(404, "unable to find repository")
self.log.info("Accessing git at: %s", gitdir)
return gitdir
@register_handler(path="/.*/git-(.*)", version_specifier=VersionSpecifier.NONE)
@stream_request_body
class RPCHandler(GitBaseHandler):
"""Request handler for RPC calls
Use this handler to handle example.git/git-upload-pack
and example.git/git-receive-pack URLs"""
async def prepare(self):
await super().prepare()
self.rpc = self.path_args[0]
self.gitdir = self.get_gitdir(rpc=self.rpc)
self.cmd = f'git {self.rpc} --stateless-rpc "{self.gitdir}"'
self.log.info(f"Running command: {self.cmd}")
self.process = Subprocess(
shlex.split(self.cmd),
stdin=Subprocess.STREAM,
stderr=Subprocess.STREAM,
stdout=Subprocess.STREAM,
)
async def post(self, rpc):
self.set_header("Content-Type", "application/x-git-%s-result" % rpc)
self.set_header(
"Cache-Control", "no-store, no-cache, must-revalidate, max-age=0"
)
await self.git_response()
await self.finish()
@register_handler(path="/.*/info/refs",
version_specifier=VersionSpecifier.NONE)
class InfoRefsHandler(GitBaseHandler):
"""Request handler for info/refs
Use this handler to handle example.git/info/refs?service= URLs"""
async def prepare(self):
await super().prepare()
if self.get_status() != 200:
return
self.rpc = self.get_argument("service")[4:]
self.cmd = f'git {self.rpc} --stateless-rpc --advertise-refs "{self.get_gitdir(self.rpc)}"' # noqa E501
self.log.info(f"Running command: {self.cmd}")
self.process = Subprocess(
shlex.split(self.cmd),
stdin=Subprocess.STREAM,
stderr=Subprocess.STREAM,
stdout=Subprocess.STREAM,
)
async def get(self):
self.set_header("Content-Type",
"application/x-git-%s-advertisement" % self.rpc)
self.set_header(
"Cache-Control", "no-store, no-cache, must-revalidate, max-age=0"
)
prelude = f"# service=git-{self.rpc}\n0000"
size = str(hex(len(prelude))[2:].rjust(4, "0"))
self.write(size)
self.write(prelude)
await self.flush()
await self.git_response()
await self.finish()