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
3 changes: 2 additions & 1 deletion Production/Installer/Installer/InstallerApi.py
Original file line number Diff line number Diff line change
Expand Up @@ -453,4 +453,5 @@ def CloseWindow(self):

def LogClientError(self, Message):
if isinstance(Message, str):
Logger.warning("UI: %s", Message[:300].replace("\n", " "))
# One log line whatever the page sends: control characters (line breaks included) become spaces.
Logger.warning("UI: %s", "".join(Ch if Ch >= " " and Ch != "\x7f" else " " for Ch in Message[:300]))
18 changes: 17 additions & 1 deletion Production/Installer/Installer/Locations.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,15 @@
Apps list ...\\Uninstall\\RAMMIT-InstallerTest (override: RAMMIT_INSTALLER_UNINSTALL_NAME)
protocol ...\\Classes\\RAMMIT-InstallerTest (override: RAMMIT_INSTALLER_PROTOCOL)
folders %TEMP%\\RAMMIT-InstallerTest\\{Desktop, StartMenu, LocalAppData} (override: RAMMIT_INSTALLER_TEST_ROOT)
releases RAMMIT_INSTALLER_RELEASES_URL may point at a fake release server (ignored outside test mode)
releases RAMMIT_INSTALLER_RELEASES_URL may point at a fake release server ON THIS PC (127.0.0.1 or
localhost; ignored outside test mode, and test mode refuses to start with any other address, so
an environment variable can never make the installer download from somewhere on the network)

Call Reload() after changing those environment variables (the tests do); everything else reads Current.
"""
import os
import tempfile
import urllib.parse

RealRegKeyPath = r"Software\CBlock Digital\RAMMIT"
UninstallParentPath = r"Software\Microsoft\Windows\CurrentVersion\Uninstall"
Expand Down Expand Up @@ -79,6 +82,19 @@ def _CheckTestModeIsolated(self):
Problems.append("install folder")
if Problems:
raise RuntimeError("Test mode would touch the real " + ", ".join(Problems))
if self.ReleasesUrlOverride and not _IsLoopbackUrl(self.ReleasesUrlOverride):
raise RuntimeError("Test mode's release server must be on this PC (http://127.0.0.1:<port>/...)")


def _IsLoopbackUrl(Url):
"""True for an http(s) URL whose host is this PC itself, written as 127.0.0.1, localhost or [::1]."""
try:
Parts = urllib.parse.urlsplit(Url)
Parts.port # raises ValueError for a port that isn't a number
except ValueError:
return False
return (Parts.scheme in ("http", "https") and (Parts.hostname or "") in ("127.0.0.1", "localhost", "::1")
and Parts.username is None and Parts.password is None)


def _KnownFolder(Name, Fallback):
Expand Down
48 changes: 45 additions & 3 deletions Production/Installer/Installer/Releases.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,14 @@
One API request lists every version (the old installer needed one request per commit and hit the
60-per-hour limit, which is why it carried a token). The zip is only trusted after its SHA-256 matches.

What is fetched, and nothing else:
the list https://api.github.com/repos/<ReleaseRepo>/releases
zip + .sha256 https://github.com/<ReleaseRepo>/releases/download/... (_CheckAssetUrl: this repo's own
release files only, whatever link the list names), which GitHub redirects to its file
hosts (AllowedDownloadHosts, checked on every redirect by _CheckUrl)
The checksum comes from the same release as the zip: it catches a damaged or swapped download, not a release
published by someone who took over the repo. Only signing the files can cover that (SECURITY.md).

Test mode can point ReleasesUrl() at a fake server (see Locations.py).
"""
import hashlib
Expand Down Expand Up @@ -84,7 +92,9 @@ def ParseReleases(Data):
Version = CleanVersion(str(Item.get("tag_name", "")))
if ParseVersion(Version) is None:
continue
Assets = {A.get("name"): A for A in Item.get("assets", []) if isinstance(A, dict)}
RawAssets = Item.get("assets")
Assets = {A.get("name"): A for A in (RawAssets if isinstance(RawAssets, list) else [])
if isinstance(A, dict) and isinstance(A.get("name"), str)}
ZipName = f"RAMMIT-{Version}.zip"
Zip, Sha = Assets.get(ZipName), Assets.get(ZipName + ".sha256")
if not Zip or not Sha:
Expand All @@ -99,12 +109,17 @@ def ParseReleases(Data):
"Published": str(Item.get("published_at") or "")[:10],
"ZipName": ZipName,
"ZipUrl": str(Zip.get("browser_download_url", "")),
"ZipSize": int(Zip.get("size") or 0),
"ZipSize": _Size(Zip.get("size")),
"ShaUrl": str(Sha.get("browser_download_url", "")),
}
return sorted(Found.values(), key=lambda R: ParseVersion(R["Version"]), reverse=True)


def _Size(Value):
"""An asset's size from the list, or 0 when it isn't a sensible whole number (only used for the progress bar)."""
return Value if isinstance(Value, int) and not isinstance(Value, bool) and 0 <= Value <= MaxZipBytes else 0


def LatestStable(ReleaseList):
return next((R for R in ReleaseList if not R["Prerelease"]), None)

Expand All @@ -124,10 +139,35 @@ def _CheckUrl(Url):
Base = urllib.parse.urlsplit(Override)
if (Parts.scheme, Parts.netloc) == (Base.scheme, Base.netloc):
return
if Parts.scheme != "https" or (Parts.hostname or "") not in AllowedDownloadHosts | {"api.github.com"}:
try:
Port = Parts.port
except ValueError:
Port = -1
if (Parts.scheme != "https" or (Parts.hostname or "") not in AllowedDownloadHosts | {"api.github.com"}
or Port not in (None, 443) or Parts.username is not None or Parts.password is not None):
raise ReleaseError("A download link pointed somewhere unexpected, so it was not used.", f"refused URL host {Parts.hostname!r}")


def _CheckAssetUrl(Url):
"""A release file's link (zip or .sha256) as the release list names it: only a download from this repo's own
releases on github.com (or the test override's server). The list is the only thing that says where the files
are, so without this any file on GitHub, in anyone's repo, could be named as "the RAMMIT zip" together with a
checksum that matches it."""
_CheckUrl(Url)
Parts = urllib.parse.urlsplit(Url)
Override = Locations.Current.ReleasesUrlOverride
if Override:
Base = urllib.parse.urlsplit(Override)
if (Parts.scheme, Parts.netloc) == (Base.scheme, Base.netloc):
return
Wanted = f"/{ReleaseRepo}/releases/download/".lower()
Path = urllib.parse.unquote(Parts.path)
if ((Parts.hostname or "") != "github.com" or Parts.port is not None or Parts.username is not None
or not Path.lower().startswith(Wanted) or ".." in Path or "\\" in Path):
raise ReleaseError("A download link pointed somewhere unexpected, so it was not used.",
f"release file is not from {ReleaseRepo}'s releases: {Url[:200]!r}")


class _CheckedRedirects(urllib.request.HTTPRedirectHandler):
def redirect_request(self, Req, Fp, Code, Msg, Headers, NewUrl):
_CheckUrl(NewUrl)
Expand Down Expand Up @@ -173,6 +213,7 @@ def FetchReleases():


def FetchExpectedSha(Release):
_CheckAssetUrl(Release["ShaUrl"])
with _Open(Release["ShaUrl"], "application/octet-stream") as Response:
Text = _ReadCapped(Response, MaxShaBytes).decode("ascii", "replace")
return ParseShaFile(Text, Release["ZipName"])
Expand Down Expand Up @@ -216,6 +257,7 @@ def DownloadRelease(Release, DestDir, OnProgress=None):

def _Download(Release, ZipPath, Expected, OnProgress):
Done, LastReport = 0, 0.0
_CheckAssetUrl(Release["ZipUrl"])
with _Open(Release["ZipUrl"], "application/octet-stream", Timeout=60) as Response:
Total = int(Response.headers.get("Content-Length") or Release.get("ZipSize") or 0)
if Total > MaxZipBytes:
Expand Down
9 changes: 6 additions & 3 deletions Production/Installer/Installer/UiServer.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
* 127.0.0.1 on a random free port, GET/HEAD only
* any Host header other than its own address is refused (blocks DNS-rebinding pages)
* exact-path lookups in the dict: no directory listings, no ../, only allowlisted file types
* every response carries a strict Content-Security-Policy, nosniff and no-store
* every response (page, scripts, images, errors) carries a strict Content-Security-Policy, nosniff and no-store
* idle connections are dropped after 15 seconds
"""
import http.server
import os
Expand Down Expand Up @@ -49,6 +50,7 @@ def LoadEmbeddedUi(BundleDir):
class _Handler(http.server.BaseHTTPRequestHandler):
server_version = "RAMMIT-Setup"
sys_version = ""
timeout = 15 # seconds a connection may sit idle: a local program can't hold threads open by never sending a request

def log_message(self, format, *args): # noqa: A002 - stdlib signature
pass
Expand Down Expand Up @@ -83,8 +85,9 @@ def _Send(self, Status, Body, ContentType, SendBody):
self.send_header("X-Content-Type-Options", "nosniff")
self.send_header("Referrer-Policy", "no-referrer")
self.send_header("Cross-Origin-Resource-Policy", "same-origin")
if ContentType.startswith("text/html"):
self.send_header("Content-Security-Policy", ContentSecurityPolicy)
# On every response, not only pages: an .svg opened on its own is a document too, and would otherwise
# run any script inside it with the bridge attached.
self.send_header("Content-Security-Policy", ContentSecurityPolicy)
self.end_headers()
if SendBody:
self.wfile.write(Body)
Expand Down
2 changes: 1 addition & 1 deletion Production/Installer/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ Screenshots/ written by TestUi.mjs and SmokeExe.py
$env:RAMMIT_INSTALLER_TEST = "1" # registry: HKCU\Software\CBlock Digital\RAMMIT-InstallerTest
# Apps list: ...\Uninstall\RAMMIT-InstallerTest
# folders: %TEMP%\RAMMIT-InstallerTest\{Desktop,StartMenu,LocalAppData}
$env:RAMMIT_INSTALLER_RELEASES_URL = "http://127.0.0.1:<port>/repos/OWNER/RAMMIT/releases" # fake server (test mode only)
$env:RAMMIT_INSTALLER_RELEASES_URL = "http://127.0.0.1:<port>/repos/OWNER/RAMMIT/releases" # fake server (test mode only; must be 127.0.0.1 or localhost)
python Installer\Installer.py
```

Expand Down
88 changes: 88 additions & 0 deletions Production/Installer/Tests/TestInstaller.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,57 @@ def test_download_links_to_other_hosts_are_refused(self):
Releases._CheckUrl("https://github.com/OWNER/RAMMIT/releases/download/v1.0.0/RAMMIT-1.0.0.zip")
Releases._CheckUrl("https://objects.githubusercontent.com/abc")

def test_release_files_must_come_from_this_repos_releases(self):
# 1.2.1: the release list names where the zip and its checksum are. Any github.com link used to be accepted,
# so a list naming a file in someone else's repo (with a checksum that matches it) would have been installed.
os.environ.pop("RAMMIT_INSTALLER_RELEASES_URL")
Locations.Reload()
Repo = Releases.ReleaseRepo
Releases._CheckAssetUrl(f"https://github.com/{Repo}/releases/download/v1.0.0/RAMMIT-1.0.0.zip")
Releases._CheckAssetUrl(f"https://github.com/{Repo.lower()}/releases/download/v1.0.0/RAMMIT-1.0.0.zip.sha256")
for Bad in ("https://github.com/someone/else/releases/download/v1.0.0/RAMMIT-1.0.0.zip",
f"https://github.com/{Repo}-evil/releases/download/v1.0.0/RAMMIT-1.0.0.zip",
f"https://github.com/{Repo}/archive/refs/heads/main.zip",
f"https://github.com/{Repo}/releases/download/../../../someone/else/x.zip",
f"https://github.com/{Repo}/releases/download/%2e%2e/%2e%2e/x.zip",
f"https://objects.githubusercontent.com/{Repo}/releases/download/v1.0.0/RAMMIT-1.0.0.zip",
f"https://api.github.com/{Repo}/releases/download/v1.0.0/RAMMIT-1.0.0.zip",
f"https://github.com:8443/{Repo}/releases/download/v1.0.0/RAMMIT-1.0.0.zip",
f"https://user@github.com/{Repo}/releases/download/v1.0.0/RAMMIT-1.0.0.zip",
f"https://github.com.evil.example/{Repo}/releases/download/v1.0.0/RAMMIT-1.0.0.zip",
f"http://github.com/{Repo}/releases/download/v1.0.0/RAMMIT-1.0.0.zip", ""):
with self.assertRaises(Releases.ReleaseError, msg=Bad):
Releases._CheckAssetUrl(Bad)
for Bad in ("https://github.com:8443/x", "https://user:pw@github.com/x", "https://github.com:bad/x"):
with self.assertRaises(Releases.ReleaseError, msg=Bad):
Releases._CheckUrl(Bad)

def test_a_list_naming_another_repos_file_installs_nothing(self):
Elsewhere = "https://github.com/someone/else/releases/download/v1.0.0/RAMMIT-1.0.0.zip"
Release = dict(Releases.FindRelease(Releases.FetchReleases(), "1.0.0"))
os.environ.pop("RAMMIT_INSTALLER_RELEASES_URL")
Locations.Reload() # as a real installer: no test server to trust
for Swapped in ({"ZipUrl": Elsewhere}, {"ShaUrl": Elsewhere + ".sha256"}):
with mock.patch.object(Releases, "_Open") as Open, self.assertRaises(Releases.ReleaseError):
if "ShaUrl" in Swapped:
Releases.FetchExpectedSha(dict(Release, **Swapped))
else:
Releases._Download(dict(Release, **Swapped), os.path.join(self.Env.Root, "x.zip"), "0" * 64, None)
Open.assert_not_called() # refused before any request is made
self.assertFalse(os.path.exists(os.path.join(self.Env.Root, "x.zip")))

def test_odd_release_lists_never_crash(self):
def Rel(**Extra):
Assets = [{"name": "RAMMIT-1.0.0.zip", "browser_download_url": "https://github.com/o/r/a.zip", "size": 10},
{"name": "RAMMIT-1.0.0.zip.sha256", "browser_download_url": "https://github.com/o/r/a.sha256"}]
return dict({"tag_name": "v1.0.0", "assets": Assets}, **Extra)
self.assertEqual(Releases.ParseReleases([Rel(assets=None), Rel(assets="x"), Rel(assets={"a": 1}), Rel(assets=[5, None])]), [])
for Size in ("big", -1, 1.5, True, None, [1], 10 ** 30):
Odd = Rel()
Odd["assets"][0]["size"] = Size
self.assertEqual(Releases.ParseReleases([Odd])[0]["ZipSize"], 0, Size)
self.assertEqual(Releases.ParseReleases([Rel()])[0]["ZipSize"], 10)

def test_offline_gives_a_friendly_error(self):
self.Server.Offline = True
with self.assertRaises(Releases.ReleaseError) as Caught:
Expand Down Expand Up @@ -838,7 +889,33 @@ def test_release_override_ignored_outside_test_mode(self):
self.assertTrue(Releases.ReleasesUrl().startswith("https://api.github.com/repos/"))


def test_test_mode_release_server_must_be_on_this_pc(self):
# 1.2.1: test mode is switched on by environment variables, which the released RAMMIT-Setup.exe reads too.
# Its fake release server may only be on this PC, so those variables can't point a download at the network.
os.environ["RAMMIT_INSTALLER_TEST"] = "1"
for Bad in ("http://evil.example/repos/o/r/releases", "https://evil.example/x", "http://127.0.0.1.evil.example/x",
"http://user@127.0.0.1:8000/x", "ftp://127.0.0.1/x", "http://10.0.0.5:8000/x", "//127.0.0.1/x",
"http://127.0.0.1:bad/x"):
os.environ["RAMMIT_INSTALLER_RELEASES_URL"] = Bad
with self.assertRaises(RuntimeError, msg=Bad):
Locations.Reload()
for Good in ("http://127.0.0.1:8000/repos/o/r/releases", "http://localhost:8000/x", "http://[::1]:8000/x"):
os.environ["RAMMIT_INSTALLER_RELEASES_URL"] = Good
self.assertEqual(Locations.Reload().ReleasesUrlOverride, Good)


class TestApiSurface(InstallerTestCase):
def test_client_errors_are_logged_on_one_line(self):
Api = InstallerApi.InstallerApi()
with mock.patch.object(InstallerApi.Logger, "warning") as Warn:
Api.LogClientError("boom\r\n2026-11-10 12:00:00 INFO Install finished\x1b[2J\x00" + "x" * 500)
Api.LogClientError(["not", "text"])
Warn.assert_called_once()
Text = Warn.call_args.args[1]
self.assertFalse(any(Ch < " " or Ch == "\x7f" for Ch in Text), repr(Text[:60]))
self.assertLessEqual(len(Text), 300)
self.assertTrue(Text.startswith("boom 2026-11-10"))

def test_no_public_state_and_bad_arguments_return_errors(self):
Api = InstallerApi.InstallerApi()
Api._AttachWindow(Support.EventWindow())
Expand Down Expand Up @@ -926,6 +1003,17 @@ def Get(self, Path, Host=None, Method="GET"):
Connection.close()
return Response.status, dict(Response.getheaders()), Body

def test_every_response_carries_the_policy(self):
# 1.2.1: also scripts, images and errors, not only the page (an .svg opened on its own is a document too).
for Path, Wanted in (("/JS/Installer.js", 200), ("/RAMMIT-Downloader.png", 200), ("/nope.svg", 404)):
Status, Headers, _Body = self.Get(Path)
self.assertEqual(Status, Wanted, Path)
self.assertIn("script-src 'self'", Headers.get("Content-Security-Policy", ""), Path)
Status, Headers, _Body = self.Get("/HTML/Installer.html", Host="evil.example")
self.assertEqual(Status, 403)
self.assertIn("default-src 'none'", Headers.get("Content-Security-Policy", ""))
self.assertTrue(0 < UiServer._Handler.timeout <= 60) # idle connections are dropped

def test_hardening(self):
Status, Headers, Body = self.Get("/HTML/Installer.html")
self.assertEqual(Status, 200)
Expand Down
22 changes: 16 additions & 6 deletions Production/Installer/Workflow/Release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
# * the paths assume the repo layout App/, Src/, Tests/, Tools/, Installer/, Installer.spec at the root
# (today: Production/RAMMIT-Stable + Production/Installer)
# * requirements.txt must pin exact versions with hashes (pip --require-hashes)
# * never write ${{ github.ref_name }} (or any other ${{ ... }} a pusher controls) inside a run: script. GitHub
# pastes it into the script before PowerShell reads it, so a tag named v1";<command>;" would run <command>
# with this job's write token. The steps below read it from $env:TagName / $env:GitRef instead.
#
# Tag push v1.2.3 -> checks, build, smoke test, DRAFT release with the three assets.
# Any other push -> the same checks and build, no release.
Expand Down Expand Up @@ -63,13 +66,17 @@ jobs:

- name: Tag must equal App/Version.py
if: startsWith(github.ref, 'refs/tags/v')
env:
TagName: ${{ github.ref_name }}
run: |
$Version = (python -c "from App.Version import AppVersion; print(AppVersion)").Trim()
if ("v$Version" -ne "${{ github.ref_name }}") { throw "tag ${{ github.ref_name }} != App/Version.py v$Version" }
if ("v$Version" -cne $env:TagName) { throw "tag $($env:TagName) != App/Version.py v$Version" }

- name: Build app zip + .sha256, and RAMMIT-Setup.exe
env:
GitRef: ${{ github.ref }}
run: |
$Channel = if ("${{ github.ref }}".StartsWith("refs/tags/v")) { "Stable" } else { "Dev" }
$Channel = if ($env:GitRef.StartsWith("refs/tags/v")) { "Stable" } else { "Dev" }
./Build.ps1 -SkipChecks -Channel $Channel
if ($LASTEXITCODE) { throw "Build.ps1" }
$env:RAMMIT_VERSION_FILE = "$PWD/App/Version.py"
Expand All @@ -93,8 +100,11 @@ jobs:
if: startsWith(github.ref, 'refs/tags/v')
env:
GH_TOKEN: ${{ github.token }}
TagName: ${{ github.ref_name }}
run: |
$Version = "${{ github.ref_name }}".TrimStart("v")
$Pre = if ($Version.Contains("-")) { "--prerelease" } else { "" }
gh release create "${{ github.ref_name }}" --draft $Pre --title "RAMMIT $Version" --generate-notes `
"dist/RAMMIT-Setup.exe" "dist/RAMMIT-$Version.zip" "dist/RAMMIT-$Version.zip.sha256"
# The tag equals "v" + App/Version.py (checked above), so the version is read from there, not from the tag.
$Version = (python -c "from App.Version import AppVersion; print(AppVersion)").Trim()
$Arguments = @($env:TagName, "--draft", "--title", "RAMMIT $Version", "--generate-notes")
if ($Version.Contains("-")) { $Arguments += "--prerelease" }
gh release create @Arguments "dist/RAMMIT-Setup.exe" "dist/RAMMIT-$Version.zip" "dist/RAMMIT-$Version.zip.sha256"
if ($LASTEXITCODE) { throw "gh release create" }
Loading