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
91 changes: 67 additions & 24 deletions images/renderer/renderer.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,22 @@
from nbconvert.exporters import HTMLExporter

import os
import stat
import markdown
import docutils.core

BASE_PATH = os.environ["BASE_PATH"]
URL_PREFIX = os.environ["URL_PREFIX"]
REAL_BASE_PATH = os.path.realpath(BASE_PATH)

# Users control the content of rst files. Do not let directives such as
# include, raw or csv-table read files from the renderer filesystem.
# Do not let docutils config files change these settings.
RST_SETTINGS = {
"file_insertion_enabled": False,
"raw_enabled": False,
"_disable_config": True,
}


def get_extension(path, format):
Expand All @@ -21,33 +32,66 @@ def get_extension(path, format):
return splits[-1]


def render_ipynb(full_path, format):
def is_allowed_path(real_path):
"""
Return True if a resolved path is in BASE_PATH and is not hidden.
nginx does not serve dotfiles, thus the renderer must not render them.
"""
if os.path.commonpath([REAL_BASE_PATH, real_path]) != REAL_BASE_PATH:
return False
relative_path = os.path.relpath(real_path, REAL_BASE_PATH)
return not any(part.startswith(".") for part in relative_path.split(os.sep))


def open_file(file_path):
"""
Open a regular file in BASE_PATH and return a text file object.

Check the path of the open file descriptor, not the requested path.
Thus a user cannot change a symlink after the check to read a different
file. O_NONBLOCK prevents a block on a FIFO.
"""
fd = os.open(
os.path.join(BASE_PATH, file_path), os.O_RDONLY | os.O_NONBLOCK
)
try:
real_path = os.readlink("/proc/self/fd/%d" % fd)
if not stat.S_ISREG(os.fstat(fd).st_mode) or not is_allowed_path(
real_path
):
raise PermissionError(file_path)
return open(fd, encoding="utf-8")
except BaseException:
os.close(fd)
raise


def render_ipynb(file_handle, format):
"""
Render a given ipynb file
"""
exporter = HTMLExporter()
with open(full_path, encoding="utf-8") as file_handle:
html, _ = exporter.from_file(file_handle)
html, _ = exporter.from_file(file_handle)
return Response(html, mimetype="text/html")


def render_md(full_path, format):
def render_md(file_handle, format):
"""
Render a given markdown file
"""
with open(full_path, encoding="utf-8") as file_handle:
text = file_handle.read()
html = markdown.markdown(text)
html = markdown.markdown(file_handle.read())
return Response(html, mimetype="text/html")


def render_rst(full_path, format):
def render_rst(file_handle, format):
"""
Render a given reStructuredText file
"""
with open(full_path, encoding="utf-8") as file_handle:
text = file_handle.read()
html = docutils.core.publish_string(source=text, writer_name="html")
html = docutils.core.publish_string(
source=file_handle.read(),
writer_name="html",
settings_overrides=RST_SETTINGS,
)
return Response(html, mimetype="text/html")


Expand All @@ -62,26 +106,25 @@ def render_rst(full_path, format):
@Request.application
def application(request):
file_path = request.path.lstrip(URL_PREFIX)
full_path = os.path.join(BASE_PATH, file_path)
# Protect against path traversal attacks, if they make it this far.
if not full_path.startswith(BASE_PATH):
# DANGER!
return Response("Suspicious url", status=403)
format = request.args.get("format", None)
if format == "raw":
# Let nginx serve raw files
accel_path = os.path.join("/accelredir/", file_path)
return Response("", headers={"X-Accel-Redirect": accel_path})

try:
extension = get_extension(full_path, format)
if format == "raw":
# Let nginx serve raw files
with open_file(file_path):
pass
accel_path = os.path.join("/accelredir/", file_path)
return Response("", headers={"X-Accel-Redirect": accel_path})

extension = get_extension(file_path, format)
if extension and extension in handlers:
return handlers[extension](full_path, format)
with open_file(file_path) as file_handle:
return handlers[extension](file_handle, format)
else:
return Response("No handlers for format %s" % extension, status=400)
except FileNotFoundError:
return Response("Not found", status=404)
return Response(full_path)
except PermissionError:
return Response("Forbidden", status=403)


if __name__ == "__main__":
Expand Down
4 changes: 4 additions & 0 deletions paws/templates/nbserve/nginx.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -117,13 +117,17 @@ data:
fancyindex on;

alias /data/project/paws/userhomes/;
# Users can create symlinks to hidden files of other
# users or to files in this container. Do not follow them.
disable_symlinks on from=$document_root;
}


location /accelredir {
internal;

alias /data/project/paws/userhomes/;
disable_symlinks on from=$document_root;
}

# this section is what allows:
Expand Down
26 changes: 26 additions & 0 deletions paws/templates/public.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ apiVersion: v1
kind: ServiceAccount
metadata:
name: paws-public
# nbserve and the renderer do not use the Kubernetes API
automountServiceAccountToken: false
---
apiVersion: apps/v1
kind: Deployment
Expand Down Expand Up @@ -92,6 +94,7 @@ spec:
volumeMounts:
- mountPath: /data/project/paws/userhomes
name: pawshomes
readOnly: true
resources:
requests:
memory: {{ .Values.pawspublic.renderer.requests.memory }}
Expand Down Expand Up @@ -154,6 +157,29 @@ spec:
selector:
name: renderer
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
labels:
name: renderer
name: renderer
spec:
podSelector:
matchLabels:
name: renderer
policyTypes:
- Ingress
ingress:
# Only nbserve sends requests to the renderer.
# User pods must not bypass the nginx checks in nbserve.
- from:
- podSelector:
matchLabels:
name: nbserve
ports:
- protocol: TCP
port: 8000
---
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
Expand Down
2 changes: 1 addition & 1 deletion paws/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pawspublic:
renderer:
image:
name: quay.io/wikimedia-paws-prod/renderer
tag: pr-537 # renderer tag managed by github actions
tag: pr-540 # renderer tag managed by github actions
# pawspublic.nbserve.image.template safely defines image:tag name in yaml
template: "{{ .Values.pawspublic.renderer.image.name}}:{{.Values.pawspublic.renderer.image.tag }}"
requests:
Expand Down
Loading