From c721cc6b5b9f8edf4031351fa79e241998276632 Mon Sep 17 00:00:00 2001 From: rektdie Date: Sun, 15 Nov 2026 00:42:43 +0100 Subject: [PATCH 1/2] Accept engine sources from Gitea servers Tests, tunes and datagen could only use https://github.com//. Gitea servers listed under "gitea_hosts" in Config/config.json are now accepted too, starting with https://gitea.rektdie.com. - OpenBench/git_hosts.py holds all host logic: repo validation, API base, resolving a branch/tag/sha, compare counts, diff links and source URLs. - The server talks to Gitea with the token in Config/credentials.gitea and sends it nowhere else; Github requests stay unchanged. - Gitea may require a login even to read, so workers cannot download the archive themselves. The server gives them a /giteaSource/ link signed with an HMAC of repo and commit (SECRET_KEY), and streams the archive from the Gitea API. No client change, no client version bump. - Diff links, the out-of-date check and the profile page handle Gitea repos; the repo fields of the forms accept every configured prefix. - Private engines stay Github-only, they depend on Github Actions artifacts. - Static version bumped to v5 for the changed default_text.js. Co-Authored-By: Claude Opus 5.5 --- Config/config.json | 4 + OpenBench/config.py | 7 +- OpenBench/git_hosts.py | 193 +++++++++++++++++++++++ OpenBench/static/default_text.js | 7 +- OpenBench/templatetags/mytags.py | 8 +- OpenBench/urls.py | 1 + OpenBench/utils.py | 12 +- OpenBench/views.py | 32 +++- OpenBench/workloads/verify_workload.py | 63 ++++---- Templates/OpenBench/create_workload.html | 4 +- Templates/OpenBench/profile.html | 2 +- 11 files changed, 283 insertions(+), 50 deletions(-) create mode 100644 OpenBench/git_hosts.py diff --git a/Config/config.json b/Config/config.json index a63a657..a98b3fe 100644 --- a/Config/config.json +++ b/Config/config.json @@ -8,6 +8,10 @@ "require_manual_registration" : false, "balance_engine_throughputs" : true, + "gitea_hosts" : [ + "https://gitea.rektdie.com" + ], + "books" : [ "2moves_v1.epd", "3moves_FRC.epd", diff --git a/OpenBench/config.py b/OpenBench/config.py index 69f8693..3dcf6d8 100644 --- a/OpenBench/config.py +++ b/OpenBench/config.py @@ -25,7 +25,7 @@ import traceback from OpenSite.settings import PROJECT_PATH -OPENBENCH_STATIC_VERSION = 'v4' +OPENBENCH_STATIC_VERSION = 'v5' OPENBENCH_CONFIG = None # Initialized by OpenBench/apps.py @@ -101,6 +101,11 @@ def verify_general_config(conf): assert type(conf.get("require_manual_registration") == bool) assert type(conf.get("balance_engine_throughputs" ) == bool) + # Optional: Gitea servers that may serve engine sources, e.g. "https://gitea.example.com" + hosts = conf.get("gitea_hosts", []) + assert type(hosts) == list + assert all(type(x) == str and x.startswith('https://') and x.count('/') == 2 for x in hosts) + def verify_engine_basics(conf): assert type(conf.get('private')) == bool diff --git a/OpenBench/git_hosts.py b/OpenBench/git_hosts.py new file mode 100644 index 0000000..903452a --- /dev/null +++ b/OpenBench/git_hosts.py @@ -0,0 +1,193 @@ +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # +# # +# OpenBench is a chess engine testing framework authored by Andrew Grant. # +# # +# # +# OpenBench is free software: you can redistribute it and/or modify # +# it under the terms of the GNU General Public License as published by # +# the Free Software Foundation, either version 3 of the License, or # +# (at your option) any later version. # +# # +# OpenBench is distributed in the hope that it will be useful, # +# but WITHOUT ANY WARRANTY; without even the implied warranty of # +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # +# GNU General Public License for more details. # +# # +# You should have received a copy of the GNU General Public License # +# along with this program. If not, see . # +# # +# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # + +# Everything OpenBench needs to know about where engine sources live. +# +# Sources can be on Github, or on a Gitea server listed under "gitea_hosts" in +# Config/config.json. A Gitea server is reached with the API token stored in +# Config/credentials.gitea, and that token is never sent to any other host. +# +# Workers download sources with a plain GET and no credentials. Github archives +# are public, so workers fetch them directly. Gitea servers may require a login +# even to read, so the server hands workers a signed link to /giteaSource/, +# which fetches the archive with the token and passes it through. + +import hashlib +import hmac +import os +import re +import urllib.parse + +import requests + +import OpenBench.config + +from OpenSite.settings import PROJECT_PATH, SECRET_KEY + +GITHUB_PREFIX = 'https://github.com/' +GITHUB_PATTERN = r'^https:\/\/github\.com\/[A-Za-z0-9-]+\/[A-Za-z0-9_.-]+\/?$' +REPO_TAIL = r'\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/?$' +REQUEST_TIMEOUT = 30 + +def gitea_hosts(): + return [host.rstrip('/') for host in OpenBench.config.OPENBENCH_CONFIG.get('gitea_hosts', [])] + +def repo_prefixes(): + return [GITHUB_PREFIX] + ['%s/' % (host) for host in gitea_hosts()] + +def gitea_host(repo): + for host in gitea_hosts(): + if repo.startswith(host + '/'): + return host + return None + +def is_gitea(repo): + return gitea_host(repo) is not None + +def is_valid_repo(repo): + + if re.match(GITHUB_PATTERN, repo): + return True + + host = gitea_host(repo) + return bool(host and re.match(REPO_TAIL, repo[len(host):])) + +def owner_and_name(repo): + host = gitea_host(repo) or GITHUB_PREFIX.rstrip('/') + owner, name = repo[len(host):].strip('/').split('/')[:2] + return owner, name + +def api_base(repo): + + if (host := gitea_host(repo)): + return '%s/api/v1/repos/%s/%s' % ((host,) + owner_and_name(repo)) + + return repo.rstrip('/').replace('github.com', 'api.github.com/repos') + +def read_gitea_token(): + path = os.path.join(PROJECT_PATH, 'Config', 'credentials.gitea') + if os.path.exists(path): + with open(path) as fin: + return fin.readline().strip() or None + +def gitea_headers(): + token = read_gitea_token() + return { 'Authorization' : 'token %s' % (token) } if token else {} + +def api_headers(engine, repo): + + if is_gitea(repo): + return gitea_headers() + + import OpenBench.utils + return OpenBench.utils.read_git_credentials(engine) or {} + +def fetch_commit(repo, ref, headers): + + # Returns { 'sha', 'tree', 'message' } for a branch, tag, or commit sha. + # Raises when the reference cannot be resolved. + + base = api_base(repo) + bysha = bool(re.search('^[0-9a-fA-F]{40}$', ref)) + + if is_gitea(repo): + # One endpoint resolves branches, tags and commit shas alike + params = { 'sha' : ref, 'limit' : 1, 'stat' : 'false', 'verification' : 'false', 'files' : 'false' } + data = requests.get(base + '/commits', params=params, headers=headers, timeout=REQUEST_TIMEOUT).json() + data = data[0] + + else: + # Lookup branch or commit sha, but will fail for tags + url = '%s/%s/%s' % (base, 'commits' if bysha else 'branches', ref) + data = requests.get(url, headers=headers, timeout=REQUEST_TIMEOUT).json() + + # Check to see if the branch name was actually a tag name + if not bysha and 'commit' not in data: + url = '%s/commits/%s' % (base, ref) + data = requests.get(url, headers=headers, timeout=REQUEST_TIMEOUT).json() + + # Actual branches have to go one layer deeper + elif not bysha: data = data['commit'] + + # A lookup by sha must land on exactly that commit + if bysha and data['sha'].lower() != ref.lower(): + raise ValueError('%s resolved to %s' % (ref, data['sha'])) + + return { + 'sha' : data['sha'], + 'tree' : (data['commit'].get('tree') or {}).get('sha'), + 'message' : data['commit']['message'], + } + +def commits_ahead(repo, dev_sha, base_sha, headers): + + # Number of commits on base_sha that dev_sha does not have + base = api_base(repo) + + if is_gitea(repo): + url = '%s/compare/%s...%s' % (base, dev_sha, base_sha) + params = { 'verification' : 'false', 'files' : 'false' } + return int(requests.get(url, params=params, headers=headers, timeout=REQUEST_TIMEOUT).json().get('total_commits', 0)) + + url = '%s/compare/%s...%s' % (base, dev_sha, base_sha) + return int(requests.get(url, headers=headers, timeout=REQUEST_TIMEOUT).json().get('ahead_by', 0)) + +def compare_url(repo, base_sha, dev_sha): + + repo = repo.rstrip('/') + + if is_gitea(repo): + return '%s/compare/%s...%s' % (repo, base_sha, dev_sha) + + return '%s/compare/%s..%s' % (repo, base_sha, dev_sha) + +def source_signature(repo, sha): + message = ('%s\n%s' % (repo.rstrip('/'), sha.lower())).encode('utf-8') + return hmac.new(SECRET_KEY.encode('utf-8'), message, hashlib.sha256).hexdigest() + +def source_url(request, repo, commit): + + # Github serves archives by tree sha, so identical trees share one download + if not is_gitea(repo): + return '%s/archive/%s.zip' % (repo.rstrip('/'), commit['tree']) + + query = urllib.parse.urlencode({ + 'repo' : repo.rstrip('/'), + 'sha' : commit['sha'], + 'sig' : source_signature(repo, commit['sha']), + }) + + return request.build_absolute_uri('/giteaSource/?%s' % (query)) + +def verify_source_request(repo, sha, sig): + + return ( + is_valid_repo(repo) and is_gitea(repo) + and re.match('^[0-9a-fA-F]{40}$', sha or '') + and hmac.compare_digest(source_signature(repo, sha), sig or '') + ) + +def open_gitea_archive(repo, sha): + + # Streams the .zip for one commit from the Gitea API + url = '%s/archive/%s.zip' % (api_base(repo), sha) + response = requests.get(url, headers=gitea_headers(), stream=True, timeout=REQUEST_TIMEOUT) + response.raise_for_status() + return response diff --git a/OpenBench/static/default_text.js b/OpenBench/static/default_text.js index b49303e..74e9dab 100644 --- a/OpenBench/static/default_text.js +++ b/OpenBench/static/default_text.js @@ -1,5 +1,9 @@ function enforce_default_text(id, text) { + // `text` may be a list of accepted prefixes; the first one is the default. + var prefixes = Array.isArray(text) ? text : [text]; + text = prefixes[0]; + window.addEventListener('DOMContentLoaded', function() { var field = document.getElementById(id); @@ -9,7 +13,8 @@ function enforce_default_text(id, text) { field.addEventListener('input', function() { - if (field.value.startsWith(text) || field.value === text) + // Accept any allowed prefix, and anything still being typed towards one + if (prefixes.some(function(p) { return field.value.startsWith(p) || p.startsWith(field.value); })) return; if (field.value.endsWith('/')) diff --git a/OpenBench/templatetags/mytags.py b/OpenBench/templatetags/mytags.py index d1beae7..8994f25 100644 --- a/OpenBench/templatetags/mytags.py +++ b/OpenBench/templatetags/mytags.py @@ -22,6 +22,7 @@ import html import json import re, django import OpenBench.config, OpenBench.utils, OpenBench.stats, OpenBench.models +import OpenBench.git_hosts from django.utils.safestring import mark_safe @@ -53,14 +54,17 @@ def gitDiffLink(test): if test.dev_engine in engines and engines[test.dev_engine]['private']: repo = OpenBench.config.OPENBENCH_CONFIG['engines'][test.dev_engine]['source'] + elif OpenBench.git_hosts.is_gitea(test.dev_repo): + repo = test.dev_repo # Gitea sources point at this server's /giteaSource/ else: repo = OpenBench.utils.path_join(*test.dev.source.split('/')[:-2]) if test.test_mode == 'SPSA': + if OpenBench.git_hosts.is_gitea(repo): + return OpenBench.utils.path_join(repo, 'commit', test.dev.sha) return OpenBench.utils.path_join(repo, 'compare', test.dev.sha[:8]) - return OpenBench.utils.path_join(repo, 'compare', - '{0}..{1}'.format( test.base.sha[:8], test.dev.sha[:8])) + return OpenBench.git_hosts.compare_url(repo, test.base.sha[:8], test.dev.sha[:8]) def shortStatBlock(test): diff --git a/OpenBench/urls.py b/OpenBench/urls.py index d8648f0..d4156db 100644 --- a/OpenBench/urls.py +++ b/OpenBench/urls.py @@ -83,6 +83,7 @@ urlpatterns = [ django.urls.path(r'clientWorkerInfo/', OpenBench.views.client_worker_info), django.urls.path(r'clientGetWorkload/', OpenBench.views.client_get_workload), django.urls.path(r'clientGetNetwork///', OpenBench.views.client_get_network), + django.urls.path(r'giteaSource/', OpenBench.views.gitea_source), django.urls.path(r'clientBenchError/', OpenBench.views.client_bench_error), django.urls.path(r'clientSubmitNPS/', OpenBench.views.client_submit_nps), django.urls.path(r'clientSubmitError/', OpenBench.views.client_submit_error), diff --git a/OpenBench/utils.py b/OpenBench/utils.py index 86ad9a0..1652146 100644 --- a/OpenBench/utils.py +++ b/OpenBench/utils.py @@ -436,16 +436,12 @@ def branch_is_out_of_date(test): if test.dev_engine != test.base_engine: return False - # Format the request to the Github endpoint - base = 'https://api.github.com/repos/' - base = test.dev_repo.replace('github.com', 'api.github.com/repos') - url = path_join(base, 'compare', '%s...%s' % (test.dev.sha, test.base.sha)) + import OpenBench.git_hosts try: - # Out of date if ahead_by is non-zero - headers = read_git_credentials(test.dev_engine) - data = requests.get(url, headers=headers).json() - return data.get('ahead_by', 0) > 0 + # Out of date if the base has commits that the dev branch lacks + headers = OpenBench.git_hosts.api_headers(test.dev_engine, test.dev_repo) + return OpenBench.git_hosts.commits_ahead(test.dev_repo, test.dev.sha, test.base.sha, headers) > 0 except: # If something went wrong, just ignore it diff --git a/OpenBench/views.py b/OpenBench/views.py index 949ba49..1d366d3 100644 --- a/OpenBench/views.py +++ b/OpenBench/views.py @@ -25,6 +25,7 @@ import django.shortcuts import django.contrib.auth import OpenBench.config +import OpenBench.git_hosts import OpenBench.utils import OpenBench.uiutils @@ -232,7 +233,10 @@ def profile_config(request): for (engine, current_repo) in profile.repos.items(): repo_name = request.POST.get('engine-repo-%s' % (engine), '').removesuffix('/') - repo = 'https://github.com/%s' % (repo_name) + repo = repo_name if repo_name.startswith('https://') else 'https://github.com/%s' % (repo_name) + + if repo_name and not OpenBench.git_hosts.is_valid_repo(repo): + return redirect(request, '/profile/', error='Repositories must be on Github or a configured Gitea server') if repo != current_repo and repo_name: changes += 'Updated Engine: %s to use %s\n' % (engine, repo) @@ -246,8 +250,8 @@ def profile_config(request): if engine_name != 'None' and engine_repo: - if not engine_repo.startswith('https://github.com/'): - return redirect(request, '/profile/', error='Repositories must be on Github') + if not OpenBench.git_hosts.is_valid_repo(engine_repo): + return redirect(request, '/profile/', error='Repositories must be on Github or a configured Gitea server') if not profile.engine: profile.engine = engine_name @@ -802,6 +806,28 @@ def client_worker_info(request): # Pass back the Machine Id, and Secret Token for this session return JsonResponse({ 'machine_id' : machine.id, 'secret' : machine.secret }) +def gitea_source(request): + + # Workers download sources with a plain GET. The link carries a signature + # made at test creation, so only repo/sha pairs this server handed out work. + repo = request.GET.get('repo', '') + sha = request.GET.get('sha' , '') + sig = request.GET.get('sig' , '') + + if not OpenBench.git_hosts.verify_source_request(repo, sha, sig): + return django.http.HttpResponseForbidden('Invalid source link') + + try: + upstream = OpenBench.git_hosts.open_gitea_archive(repo, sha) + except Exception: + import traceback; traceback.print_exc() + return HttpResponse('Unable to fetch the source archive', status=502) + + owner, name = OpenBench.git_hosts.owner_and_name(repo) + response = django.http.StreamingHttpResponse(upstream.iter_content(chunk_size=1 << 16), content_type='application/zip') + response['Content-Disposition'] = 'attachment; filename="%s-%s.zip"' % (name, sha[:8]) + return response + @csrf_exempt def client_get_network(request, engine, name): diff --git a/OpenBench/workloads/verify_workload.py b/OpenBench/workloads/verify_workload.py index 16b8944..8dbbc24 100644 --- a/OpenBench/workloads/verify_workload.py +++ b/OpenBench/workloads/verify_workload.py @@ -42,6 +42,7 @@ import requests import traceback import OpenBench.config +import OpenBench.git_hosts import OpenBench.utils from OpenBench.models import * @@ -245,9 +246,10 @@ def verify_draw_adj(errors, request, field): except: errors.append('Invalid Draw Adjudication Setting. Try "None"?') def verify_github_repo(errors, request, field): - pattern = r'^https:\/\/github\.com\/[A-Za-z0-9-]+\/[A-Za-z0-9_.-]+\/?$' - try: assert re.match(pattern, request.POST[field]) - except: errors.append('Sources must be found on https://github.com//') + try: assert OpenBench.git_hosts.is_valid_repo(request.POST[field]) + except: + hosts = ', '.join('%s/' % (prefix) for prefix in OpenBench.git_hosts.repo_prefixes()) + errors.append('Sources must be found on %s' % (hosts)) def verify_network(errors, request, field, field_name, engine_field): try: @@ -353,19 +355,26 @@ def collect_github_info(errors, request, field): # Get branch name / commit sha / tag, and the API path for it branch = request.POST['{0}_branch'.format(field)] - bysha = bool(re.search('^[0-9a-fA-F]{40}$', branch)) # All API requests will share this common path. Some engines are private. - base = request.POST['%s_repo' % (field)].replace('github.com', 'api.github.com/repos') + repo = request.POST['%s_repo' % (field)] + base = OpenBench.git_hosts.api_base(repo) engine = request.POST['%s_engine' % (field)] private = OpenBench.config.OPENBENCH_CONFIG['engines'][engine]['private'] + gitea = OpenBench.git_hosts.is_gitea(repo) headers = {} ## Step 1: Verify the target of the API requests - ## [A] We will not attempt to reach any site other than api.github.com + ## [A] We will not attempt to reach any site other than api.github.com, + ## or a Gitea server listed under "gitea_hosts" in the config ## [B] Private engines may only use their main repo for sources of tests ## [C] Determine which, if any, credentials we want to pass along + # Private engines rely on Github Actions artifacts, which Gitea does not offer + if private and gitea: + errors.append('Private engines must be hosted on Github') + return (None, None) + # Private engines must have a token stored in credentials.enginename if private and not (headers := OpenBench.utils.read_git_credentials(engine)): errors.append('Server does not have access tokens for this engine') @@ -377,36 +386,27 @@ def collect_github_info(errors, request, field): return (None, None) # Avoid leaking our credentials to other websites - if not base.startswith('https://api.github.com/'): - errors.append('OpenBench may only reach Github\'s API') + if not OpenBench.git_hosts.is_valid_repo(repo): + errors.append('OpenBench may only reach Github\'s API or a configured Gitea server') return (None, None) - ## Step 2: Connect to the Github API for the given Branch or Commit SHA. + # Gitea servers get their own token, and nothing else + if gitea: + headers = OpenBench.git_hosts.gitea_headers() + + ## Step 2: Connect to the Github or Gitea API for the given Branch or Commit SHA. ## [A] We will attempt to parse the most recent commit message for a ## bench, unless one was supplied. ## [B] We will translate any branch name into a commit SHA for later use, ## so we may compare branches and generate diff URLs ## [C] If the engine is public, we will construct the URL to download the - ## source code from Github into a .zip file. + ## source code into a .zip file. Gitea sources go through this server. ## [D] If the engine is private, we will carry onto Step 3. - try: # Fetch data from the Github API - - # Lookup branch or commit sha, but will fail for tags - url = OpenBench.utils.path_join(base, 'commits' if bysha else 'branches', branch) - data = requests.get(url, headers=headers).json() - - # Check to see if the branch name was actually a tag name - if not bysha and 'commit' not in data: - url = OpenBench.utils.path_join(base, 'commits', branch) - data = requests.get(url, headers=headers).json() - - # Actual branches have to go one layer deeper - elif not bysha: data = data['commit'] - - # Check that all the data we need going forward is present - assert 'message' in data['commit'] and 'sha' in data - assert private or 'sha' in data['commit']['tree'] + try: # Resolve the branch, tag, or commit sha + commit = OpenBench.git_hosts.fetch_commit(repo, branch, headers) + assert commit['message'] is not None and commit['sha'] + assert private or commit['tree'] except: # Unable to find for whatever reason traceback.print_exc() @@ -414,22 +414,21 @@ def collect_github_info(errors, request, field): return (None, None) # Extract the bench from the web form, or from the commit message - if not (bench := determine_bench(request, field, data['commit']['message'])): + if not (bench := determine_bench(request, field, commit['message'])): errors.append('Unable to parse a Bench for %s' % (branch)) return (None, None) # Public Engines: Construct the .zip download and return everything if not private: - treeurl = data['commit']['tree']['sha'] + '.zip' - source = OpenBench.utils.path_join(request.POST['%s_repo' % (field)], 'archive', treeurl) - return (source, branch, data['sha'], bench), True + source = OpenBench.git_hosts.source_url(request, repo, commit) + return (source, branch, commit['sha'], bench), True ## Step 3: Construct the URL for the API request to list all Artifacts ## [A] OpenBench artifacts are always run via a file named openbench.yml ## [B] These should contain combinations for windows/linux, avx2/avx512, popcnt/pext ## [C] If those artifacts are not found, we flag the test as awaiting, and try later. - url, has_all = fetch_artifact_url(base, engine, headers, data['sha']) + url, has_all = fetch_artifact_url(base, engine, headers, commit['sha']) return (url, branch, data['sha'], bench), has_all def requests_illegal_fork(request, field): diff --git a/Templates/OpenBench/create_workload.html b/Templates/OpenBench/create_workload.html index 7edb8b4..bf917e8 100644 --- a/Templates/OpenBench/create_workload.html +++ b/Templates/OpenBench/create_workload.html @@ -15,8 +15,8 @@ document.addEventListener( 'DOMContentLoaded', function () { change_engine('{{ profile.engine }}', 'dev', '{{workload}}'); - enforce_default_text('dev_repo', 'https://github.com/'); - enforce_default_text('base_repo', 'https://github.com/'); + enforce_default_text('dev_repo', ['https://github.com/'{% for host in config.gitea_hosts %}, '{{host}}/'{% endfor %}]); + enforce_default_text('base_repo', ['https://github.com/'{% for host in config.gitea_hosts %}, '{{host}}/'{% endfor %}]); }, false ); diff --git a/Templates/OpenBench/profile.html b/Templates/OpenBench/profile.html index c8915e9..6599d0b 100644 --- a/Templates/OpenBench/profile.html +++ b/Templates/OpenBench/profile.html @@ -7,7 +7,7 @@ {% endblock %} -- 2.47.3 From 754283d95e21cf185c08be8f4da67382c97f03a9 Mon Sep 17 00:00:00 2001 From: rektdie Date: Sun, 15 Nov 2026 00:45:17 +0100 Subject: [PATCH 2/2] Sign Gitea source links with the Gitea token settings.py, SECRET_KEY included, is part of the public repository, so links signed with it could be forged to read any repository the token can see. The token in Config/credentials.gitea is gitignored and is now the signing key. Without a token, Gitea tests are refused at creation and no link validates. Co-Authored-By: Claude Opus 5.5 --- OpenBench/git_hosts.py | 26 ++++++++++++++++++-------- OpenBench/workloads/verify_workload.py | 8 +++++--- 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/OpenBench/git_hosts.py b/OpenBench/git_hosts.py index 903452a..76c8fe3 100644 --- a/OpenBench/git_hosts.py +++ b/OpenBench/git_hosts.py @@ -28,6 +28,11 @@ # are public, so workers fetch them directly. Gitea servers may require a login # even to read, so the server hands workers a signed link to /giteaSource/, # which fetches the archive with the token and passes it through. +# +# The links are signed with the Gitea token itself, not Django's SECRET_KEY: +# settings.py is part of the public repository, and a forged link would let +# anyone read every repository the token can see. Replacing the token +# invalidates the source links of tests created before. import hashlib import hmac @@ -39,7 +44,7 @@ import requests import OpenBench.config -from OpenSite.settings import PROJECT_PATH, SECRET_KEY +from OpenSite.settings import PROJECT_PATH GITHUB_PREFIX = 'https://github.com/' GITHUB_PATTERN = r'^https:\/\/github\.com\/[A-Za-z0-9-]+\/[A-Za-z0-9_.-]+\/?$' @@ -159,8 +164,13 @@ def compare_url(repo, base_sha, dev_sha): return '%s/compare/%s..%s' % (repo, base_sha, dev_sha) def source_signature(repo, sha): - message = ('%s\n%s' % (repo.rstrip('/'), sha.lower())).encode('utf-8') - return hmac.new(SECRET_KEY.encode('utf-8'), message, hashlib.sha256).hexdigest() + + # Without a token there is nothing secret to sign with, and nothing to fetch with + if not (key := read_gitea_token()): + return None + + message = ('openbench-gitea-source\n%s\n%s' % (repo.rstrip('/'), sha.lower())).encode('utf-8') + return hmac.new(key.encode('utf-8'), message, hashlib.sha256).hexdigest() def source_url(request, repo, commit): @@ -178,11 +188,11 @@ def source_url(request, repo, commit): def verify_source_request(repo, sha, sig): - return ( - is_valid_repo(repo) and is_gitea(repo) - and re.match('^[0-9a-fA-F]{40}$', sha or '') - and hmac.compare_digest(source_signature(repo, sha), sig or '') - ) + if not (is_valid_repo(repo) and is_gitea(repo) and re.match('^[0-9a-fA-F]{40}$', sha or '')): + return False + + expected = source_signature(repo, sha) + return bool(expected) and hmac.compare_digest(expected, sig or '') def open_gitea_archive(repo, sha): diff --git a/OpenBench/workloads/verify_workload.py b/OpenBench/workloads/verify_workload.py index 8dbbc24..fb2e55d 100644 --- a/OpenBench/workloads/verify_workload.py +++ b/OpenBench/workloads/verify_workload.py @@ -390,9 +390,11 @@ def collect_github_info(errors, request, field): errors.append('OpenBench may only reach Github\'s API or a configured Gitea server') return (None, None) - # Gitea servers get their own token, and nothing else - if gitea: - headers = OpenBench.git_hosts.gitea_headers() + # Gitea servers get their own token, and nothing else. The token also signs + # the source links handed to workers, so there is no Gitea without one. + if gitea and not (headers := OpenBench.git_hosts.gitea_headers()): + errors.append('Server does not have a Gitea token (Config/credentials.gitea)') + return (None, None) ## Step 2: Connect to the Github or Gitea API for the given Branch or Commit SHA. ## [A] We will attempt to parse the most recent commit message for a -- 2.47.3