Skip to content

Commit

Permalink
Fix various issues reported by sonarcloud
Browse files Browse the repository at this point in the history
Dockerfiles:
- Run containers as non-root user

Python:
- Add CSRF protection
- Split safe and unsafe routes
- Don't run in debug mode

JavaScript:
- Don't use asynchronous constructor side-effects
- Add integrity check to external resources

#patch
  • Loading branch information
gregtyler committed Oct 15, 2024
1 parent b9817be commit df58597
Show file tree
Hide file tree
Showing 9 changed files with 90 additions and 46 deletions.
5 changes: 4 additions & 1 deletion fixtures/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ WORKDIR /app

COPY fixtures/package.json package.json
COPY fixtures/package-lock.json package-lock.json
RUN npm ci
RUN npm ci --ignore-scripts

FROM python:3-alpine3.17

Expand All @@ -26,4 +26,7 @@ COPY docs/schemas static/schemas

EXPOSE 80

RUN addgroup -S app && adduser -S -g app app
USER app

CMD [ "flask", "run", "--host", "0.0.0.0", "--port", "80"]
95 changes: 54 additions & 41 deletions fixtures/app.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,18 @@
import requests, os, logging, sys, json
import requests, os, logging, sys, json, uuid
from lib.aws_auth import AwsAuth
from lib.jwt import generate_jwt
from urllib.parse import quote

from flask import Flask, render_template, request, jsonify
from flask_wtf import CSRFProtect

app = Flask(__name__, static_url_path="/assets")
app.config.update(
SECRET_KEY=uuid.uuid4().__str__(),
)

csrf = CSRFProtect()
csrf.init_app(app)

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
Expand Down Expand Up @@ -49,52 +57,57 @@ def health_check_dependencies():
return jsonify({"ok": False})


@app.route("/", methods=["GET", "POST"])
def index():
aws_auth = AwsAuth()

uid = request.form.get("uid", "")
json_data = request.form.get("json-data", "{}")
@app.route("/", methods=["GET"])
def get_index():
base_url = os.environ["BASE_URL"]

template_data = {
"base_url": base_url,
"uid": uid,
"json_data": json_data,
}

if request.method == "GET":
return render_template("index.html", **template_data)

if request.method == "POST":
url = base_url + "/lpas/" + uid

if aws_auth.is_authed:
headers = aws_auth.get_headers(method="PUT", url=url, data=json_data)
else:
headers = {}
return render_template(
"index.html",
**{
"base_url": base_url,
"json_data": "{}",
},
)

token = generate_jwt(os.environ["JWT_SECRET_KEY"])

resp = requests.put(
url,
json_data,
headers={
**headers,
"Content-Type": "application/json",
"X-Jwt-Authorization": "Bearer " + token,
},
)
@app.route("/", methods=["POST"])
def post_index():
aws_auth = AwsAuth()

return render_template(
"index.html",
**template_data,
success=resp.status_code < 400,
error=json.loads(resp.text),
)
uid = request.form.get("uid", "")
json_data = request.form.get("json-data", "{}")
base_url = os.environ["BASE_URL"]

return "error"
url = base_url + "/lpas/" + quote(uid)

if aws_auth.is_authed:
headers = aws_auth.get_headers(method="PUT", url=url, data=json_data)
else:
headers = {}

token = generate_jwt(os.environ["JWT_SECRET_KEY"])

resp = requests.put(
url,
json_data,
headers={
**headers,
"Content-Type": "application/json",
"X-Jwt-Authorization": "Bearer " + token,
},
)

return render_template(
"index.html",
**{
"base_url": base_url,
"uid": uid,
"json_data": json_data,
},
success=resp.status_code < 400,
error=json.loads(resp.text),
)


if __name__ == "__main__":
app.run(debug=True, host="0.0.0.0", port=80)
app.run(host="0.0.0.0", port=80)
1 change: 1 addition & 0 deletions fixtures/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
Flask==3.0.3
Flask-WTF==1.2.1
requests==2.32.3
Jinja2==3.1.4
jsonschema==4.23.0
Expand Down
12 changes: 10 additions & 2 deletions fixtures/static/js/json-schema-editor.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,6 @@ export class JsonSchemaEditor {
}

this.$module = $module;

this.init();
}

async init() {
Expand Down Expand Up @@ -319,4 +317,14 @@ export class JsonSchemaEditor {

return $container;
}

/**
* @param {Element} $module
*/
static async create($module) {
const $editor = new JsonSchemaEditor($module);
$editor.init();

return $editor;
}
}
2 changes: 1 addition & 1 deletion fixtures/static/js/main.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@ export function initAll() {
Object.entries(initiators).forEach(([name, Component]) => {
const $elements = document.querySelectorAll(`[data-module="${name}"]`);

$elements.forEach(($element) => new Component($element));
$elements.forEach(($element) => Component.create($element));
});
}
7 changes: 7 additions & 0 deletions fixtures/static/js/uid-generator.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,11 @@ export class UidGenerator {
`M-` +
[value.slice(0, 4), value.slice(4, 8), value.slice(8, 12)].join("-");
}

/**
* @param {Element} $module
*/
static async create($module) {
return new UidGenerator($module);
}
}
8 changes: 7 additions & 1 deletion fixtures/templates/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,8 @@ <h2 class="govuk-error-summary__title">{{ error.detail }}</h2>
{% endif %} {% endif %}

<form method="post">
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}" />

<div class="govuk-form-group">
<label class="govuk-label govuk-label--m" for="f-uid">UID</label>
<input
Expand Down Expand Up @@ -100,7 +102,11 @@ <h2 class="govuk-error-summary__title">{{ error.detail }}</h2>
</main>
</div>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jsonSchemaLibrary.min.js"></script>
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jsonSchemaLibrary.min.js"
integrity="sha384-RePbUf/gtYzyS1nEErY0oNbL9zMtjU3TXf4Dj4FBEmhclyRv8pPvibkBEMUpd/c3"
crossorigin="anonymous"
></script>
<script type="module">
import { initAll as govukInitAll } from "./assets/govuk-frontend.min.js";
import { initAll as appInitAll } from "./assets/js/main.mjs";
Expand Down
3 changes: 3 additions & 0 deletions lambda/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,7 @@ RUN apk upgrade libssl3 libcrypto3

COPY --from=build-env /go/bin/main /var/task/main

RUN addgroup -S app && adduser -S -g app app
USER app

ENTRYPOINT [ "/var/task/main" ]
3 changes: 3 additions & 0 deletions mock-apigw/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,7 @@ FROM alpine:3

COPY --from=build-env /go/bin/main /var/task/main

RUN addgroup -S app && adduser -S -g app app
USER app

ENTRYPOINT [ "/var/task/main" ]

0 comments on commit df58597

Please sign in to comment.