Disable unused vendor integrations and notices #58
4 changed files with 306 additions and 0 deletions
33
.forgejo/workflows/unused-vendor-settings.yml
Normal file
33
.forgejo/workflows/unused-vendor-settings.yml
Normal file
|
|
@ -0,0 +1,33 @@
|
|||
name: Unused Vendor Settings Operations Build
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: ['ops/unused-vendor-settings-*']
|
||||
|
||||
jobs:
|
||||
unused-vendor-settings:
|
||||
runs-on: dune-ci
|
||||
steps:
|
||||
- name: Check out exact revision
|
||||
shell: bash
|
||||
env:
|
||||
REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
git init .
|
||||
git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA"
|
||||
git checkout --detach FETCH_HEAD
|
||||
- name: Validate and package the scoped vendor configuration operation
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
python3 tools/test_unused_vendor_settings.py -v
|
||||
mkdir unused-vendor-artifacts
|
||||
cp tools/disable-unused-vendor-settings.py tools/unused-vendor-settings.json unused-vendor-artifacts/
|
||||
printf '%s\n' "$(git rev-parse HEAD)" > unused-vendor-artifacts/SOURCE_COMMIT
|
||||
(cd unused-vendor-artifacts && sha256sum -- *.py *.json SOURCE_COMMIT > SHA256SUMS)
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: DuneRealms-Unused-Vendor-Settings
|
||||
path: unused-vendor-artifacts/
|
||||
if-no-files-found: error
|
||||
164
tools/disable-unused-vendor-settings.py
Normal file
164
tools/disable-unused-vendor-settings.py
Normal file
|
|
@ -0,0 +1,164 @@
|
|||
"""Disable optional vendor integrations on an explicitly selected server."""
|
||||
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
|
||||
SETTINGS = {
|
||||
'Towny': (
|
||||
'settings/config.yml', {
|
||||
'plugin.update_notifications.alerts',
|
||||
'new_world_settings.plot_management.block_delete.enabled',
|
||||
'new_world_settings.plot_management.mayor_plotblock_delete.enabled',
|
||||
},
|
||||
),
|
||||
'MedievalFactions': (
|
||||
'config.yml', {
|
||||
'addons.suggestions', 'dynmap.enableDynmapIntegration',
|
||||
'update-check.enabled', 'usage-reporting.enabled',
|
||||
},
|
||||
),
|
||||
}
|
||||
MANIFEST = json.loads(Path(__file__).with_name('unused-vendor-settings.json').read_text(encoding='utf-8-sig'))
|
||||
PINS = MANIFEST['configs']
|
||||
YAML_KEY = re.compile(rb'^([ ]*)([a-zA-Z0-9_-]+):[ \t]*(.*?)(\r?\n)?$')
|
||||
BOOL = re.compile(rb"^(['\"]?)(true|false)\1([ \t]*(?:#.*)?)$")
|
||||
|
||||
|
||||
def patch(data, targets):
|
||||
parents = []
|
||||
seen = set()
|
||||
output = []
|
||||
for line in data.splitlines(keepends=True):
|
||||
parsed = YAML_KEY.fullmatch(line)
|
||||
if parsed:
|
||||
spaces, key, value, _ = parsed.groups()
|
||||
level = len(spaces)
|
||||
while parents and parents[-1][0] >= level:
|
||||
parents.pop()
|
||||
parents.append((level, key.decode('ascii')))
|
||||
path = '.'.join(name for _, name in parents)
|
||||
if path in targets:
|
||||
boolean = BOOL.fullmatch(value)
|
||||
if path in seen or boolean is None:
|
||||
raise ValueError(f'Expected one explicit boolean for {path}')
|
||||
seen.add(path)
|
||||
if boolean[2] == b'true':
|
||||
start = parsed.start(3) + boolean.start(2)
|
||||
line = line[:start] + b'false' + line[start + 4:]
|
||||
output.append(line)
|
||||
if seen != targets:
|
||||
raise ValueError(f'Missing reviewed settings: {sorted(targets - seen)}')
|
||||
return b''.join(output)
|
||||
|
||||
|
||||
def digest(data):
|
||||
return hashlib.sha256(data).hexdigest()
|
||||
|
||||
|
||||
def patch_world(data):
|
||||
if len(re.findall(rb'(?m)^usingPlotManagementRevert=false(?=\r?$)', data)) != 1:
|
||||
raise ValueError('Expected Towny plot regeneration already disabled')
|
||||
for field in (b'usingPlotManagementDelete', b'usingPlotManagementMayorDelete'):
|
||||
prefix = rb'(?m)^' + field + b'='
|
||||
if len(re.findall(prefix, data)) != 1:
|
||||
raise ValueError(f'Expected one Towny world field: {field.decode()}')
|
||||
data, count = re.subn(prefix + rb'true(?=\r?$)', field + b'=false', data)
|
||||
if count != 1:
|
||||
raise ValueError(f'Expected enabled Towny world field: {field.decode()}')
|
||||
return data
|
||||
|
||||
|
||||
def read_pinned(path, pin):
|
||||
if not path.is_file() or path.resolve(strict=True) != path:
|
||||
raise ValueError(f'Expected regular config at {path}')
|
||||
data = path.read_bytes()
|
||||
if digest(data) != pin:
|
||||
raise ValueError(f'Unexpected config revision: {path}')
|
||||
return data
|
||||
|
||||
|
||||
def identity(metadata):
|
||||
return (metadata.st_dev, metadata.st_ino, metadata.st_uid, metadata.st_gid,
|
||||
metadata.st_mode, metadata.st_size, metadata.st_mtime_ns)
|
||||
|
||||
|
||||
def write(path, data, original_stat):
|
||||
with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as handle:
|
||||
staged = Path(handle.name)
|
||||
try:
|
||||
handle.write(data)
|
||||
handle.flush()
|
||||
os.fchown(handle.fileno(), original_stat.st_uid, original_stat.st_gid)
|
||||
os.fchmod(handle.fileno(), original_stat.st_mode & 0o7777)
|
||||
os.fsync(handle.fileno())
|
||||
os.replace(staged, path)
|
||||
finally:
|
||||
staged.unlink(missing_ok=True)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('server', choices=sorted(PINS))
|
||||
parser.add_argument('--apply', action='store_true', help='Apply while the instance is stopped')
|
||||
args = parser.parse_args()
|
||||
root = Path('/opt/dunerealms/lobby' if args.server == 'lobby' else
|
||||
f'/opt/dunerealms/servers/{args.server}')
|
||||
unit = f'dune-{args.server}.service'
|
||||
state = subprocess.check_output(
|
||||
['systemctl', 'show', '-p', 'WorkingDirectory', '-p', 'ActiveState', '-p', 'MainPID', unit],
|
||||
text=True,
|
||||
)
|
||||
state = dict(line.split('=', 1) for line in state.splitlines())
|
||||
if state['WorkingDirectory'] != str(root):
|
||||
raise ValueError('Service has unexpected working directory')
|
||||
if args.apply and (state['ActiveState'] not in {'inactive', 'failed'} or state['MainPID'] != '0'):
|
||||
raise ValueError('Stop the reviewed service before applying')
|
||||
changes = {}
|
||||
for vendor, (relative, targets) in SETTINGS.items():
|
||||
path = root / 'plugins' / vendor / relative
|
||||
data = read_pinned(path, PINS[args.server][vendor])
|
||||
changes[path] = (data, patch(data, targets), path.stat())
|
||||
worlds = root / 'plugins/Towny/data/worlds'
|
||||
reviewed = MANIFEST['worlds'][args.server]
|
||||
if {path.stem for path in worlds.glob('*.txt')} != reviewed.keys():
|
||||
raise ValueError('Towny world inventory differs from the reviewed scope')
|
||||
for world, pin in reviewed.items():
|
||||
if not re.fullmatch(r'[a-z0-9_]+', world):
|
||||
raise ValueError('Invalid reviewed Towny world name')
|
||||
path = worlds / f'{world}.txt'
|
||||
data = read_pinned(path, pin)
|
||||
changes[path] = (data, patch_world(data), path.stat())
|
||||
written = []
|
||||
if args.apply:
|
||||
try:
|
||||
for path, (before, after, metadata) in changes.items():
|
||||
if path.read_bytes() != before or identity(path.stat()) != identity(metadata):
|
||||
raise ValueError(f'Config changed after preflight: {path}')
|
||||
if before != after:
|
||||
write(path, after, metadata)
|
||||
written.append(path)
|
||||
for path, (_, after, _) in changes.items():
|
||||
if path.read_bytes() != after:
|
||||
raise ValueError(f'Config readback differs: {path}')
|
||||
except Exception:
|
||||
for path in reversed(written):
|
||||
before, after, metadata = changes[path]
|
||||
if path.read_bytes() == after:
|
||||
write(path, before, metadata)
|
||||
raise
|
||||
print(json.dumps({
|
||||
'unit': unit, 'status': 'applied' if args.apply else 'planned',
|
||||
'changes': {str(path): {'before': digest(before), 'after': digest(after)}
|
||||
for path, (before, after, _) in changes.items()},
|
||||
}, indent=2))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
55
tools/test_unused_vendor_settings.py
Normal file
55
tools/test_unused_vendor_settings.py
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
import re
|
||||
import runpy
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
MODULE = runpy.run_path(str(Path(__file__).with_name('disable-unused-vendor-settings.py')))
|
||||
patch = MODULE['patch']
|
||||
|
||||
|
||||
class UnusedVendorSettingsTest(unittest.TestCase):
|
||||
def test_preserves_quotes_comments_line_endings_and_unrelated_settings(self):
|
||||
source = (b'plugin:\r\n update_notifications:\r\n alerts: "true" # vendor\r\n'
|
||||
b' major_only: true\r\nother:\r\n alerts: true')
|
||||
targets = {'plugin.update_notifications.alerts'}
|
||||
self.assertEqual(patch(source, targets), source.replace(b'"true"', b'"false"'))
|
||||
|
||||
def test_nested_paths_and_already_disabled_values(self):
|
||||
source = (b'addons:\n suggestions: true\ndynmap:\n enableDynmapIntegration: true\n'
|
||||
b'update-check:\n enabled: true\nusage-reporting:\n enabled: false\n'
|
||||
b'dpc-api:\n login-reminder: true\n')
|
||||
targets = MODULE['SETTINGS']['MedievalFactions'][1]
|
||||
after = patch(source, targets)
|
||||
self.assertEqual(after, source.replace(b': true', b': false', 3))
|
||||
self.assertEqual(patch(after, targets), after)
|
||||
|
||||
def test_refuses_missing_invalid_and_duplicate_target(self):
|
||||
for data in (b'a: true', b'b: yes', b'b: true\nb: false'):
|
||||
with self.subTest(data=data), self.assertRaises(ValueError):
|
||||
patch(data, {'b'})
|
||||
|
||||
def test_pins_cover_only_six_servers_and_exact_vendors(self):
|
||||
pins = MODULE['PINS']
|
||||
self.assertEqual(set(pins), {'lobby', 'arrakis', 'caladan', 'giedi_prime',
|
||||
'kaitain', 'sigma_draconis_iv'})
|
||||
for vendors in pins.values():
|
||||
self.assertEqual(vendors.keys(), MODULE['SETTINGS'].keys())
|
||||
self.assertTrue(all(re.fullmatch(r'[0-9a-f]{64}', sha) for sha in vendors.values()))
|
||||
worlds = MODULE['MANIFEST']['worlds']
|
||||
self.assertEqual(worlds.keys(), pins.keys())
|
||||
self.assertEqual(sum(map(len, worlds.values())), 12)
|
||||
self.assertTrue(all(re.fullmatch(r'[0-9a-f]{64}', sha)
|
||||
for server in worlds.values() for sha in server.values()))
|
||||
|
||||
def test_world_cleanup_changes_only_the_two_block_deletion_flags(self):
|
||||
source = (b'usingTowny=true\r\nusingPlotManagementDelete=true\r\n'
|
||||
b'usingPlotManagementRevert=false\r\nusingPlotManagementMayorDelete=true')
|
||||
expected = source.replace(b'Delete=true', b'Delete=false')
|
||||
self.assertEqual(MODULE['patch_world'](source), expected)
|
||||
with self.assertRaises(ValueError):
|
||||
MODULE['patch_world'](source.replace(b'Revert=false', b'Revert=true'))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
54
tools/unused-vendor-settings.json
Normal file
54
tools/unused-vendor-settings.json
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
{
|
||||
"configs": {
|
||||
"arrakis": {
|
||||
"Towny": "7189d2eb3a1e09c4bb9ab5cb10abed23733f77ede426200b217afb5cdea0a07e",
|
||||
"MedievalFactions": "d8c325ca1b41aa17df580b72b4e8e79714691215a51f3dc7c8332a3f24e99d57"
|
||||
},
|
||||
"caladan": {
|
||||
"Towny": "6bfa13a9d3e7be27731f3a27e995987cf2870c52a56253d626b55b6ea5efdbff",
|
||||
"MedievalFactions": "95c94f07e91f8599f676bdc03ef333d0682338f2bf7d6f0f9d5f31cd6fabe652"
|
||||
},
|
||||
"giedi_prime": {
|
||||
"Towny": "7440231da22718cba4c402d8b07594484aacd840b3c01ab81c4d2a6f1fcfac1f",
|
||||
"MedievalFactions": "d8c325ca1b41aa17df580b72b4e8e79714691215a51f3dc7c8332a3f24e99d57"
|
||||
},
|
||||
"kaitain": {
|
||||
"Towny": "30a82b404c01fd5e496451db8bfe552ba63fe7accea5b9a385b76a81e9a55bd2",
|
||||
"MedievalFactions": "d8c325ca1b41aa17df580b72b4e8e79714691215a51f3dc7c8332a3f24e99d57"
|
||||
},
|
||||
"lobby": {
|
||||
"Towny": "f5cd49775e87df639278450ff097b48d25c52740c1c86a682d77d11293cd06bb",
|
||||
"MedievalFactions": "987b468f275f55dc42363a622196d2632c096754dce5d42c5b630e0c493159bc"
|
||||
},
|
||||
"sigma_draconis_iv": {
|
||||
"Towny": "aa4c3f796decb6ffac0edd35bfc93629432f3fcd9cd4edece6beff99f5374858",
|
||||
"MedievalFactions": "d8c325ca1b41aa17df580b72b4e8e79714691215a51f3dc7c8332a3f24e99d57"
|
||||
}
|
||||
},
|
||||
"worlds": {
|
||||
"arrakis": {
|
||||
"arrakis": "38515707a5fdbe3bbdab8b5e98eecf78f4dc56281bee7fc832236600df50470d"
|
||||
},
|
||||
"caladan": {
|
||||
"caladan": "a3944a9bb1324077b5e27ca79032dde3fc948eed3d433f5b8442c518e36bee0d"
|
||||
},
|
||||
"giedi_prime": {
|
||||
"giedi_prime_nether": "c1d2b41ad6f9f4fb77b3bcb6fe8b11265a83e782748a4a55bc66b1822a24b970",
|
||||
"giedi_prime": "a29c5e086390c80ae6ee10d425bd8d32e394329d459682daea0bc2ed9bb8fb7a"
|
||||
},
|
||||
"kaitain": {
|
||||
"kaitain": "fe1e1e559e09ba22617d24684e5d52867492d5364b47e1c824bc38df3777466d"
|
||||
},
|
||||
"lobby": {
|
||||
"lobby_base_the_end": "754be43d1581571c72bd82b309b2952fec597dd88b1f28c1cfa4d6ac6f1dd282",
|
||||
"lobby_arrakis": "ce4ab142405c3dbfde8a868da1e0f3b3e9ceae200475b4d9141b4dcd2b573390",
|
||||
"guild_lobby": "02ee73eb2ba510c9cd26d0942fd7ae508ca3f6f6dc9faa3a499af36a3580ccb2",
|
||||
"lobby_base_nether": "6e2bda320e8f5c4be78542c6a61e9618031ad68a0ccc5cfc854d22232304332f",
|
||||
"lobby_base": "460f547f47b88e7a34f709135d3973492cb874cfd86a847e0be14a0c23145982"
|
||||
},
|
||||
"sigma_draconis_iv": {
|
||||
"sigma_draconis_iv": "09109791b7f1263c3518ad7e1537543260698b29aa0c78c0860f834a9409740a",
|
||||
"sigma_draconis_iv_the_end": "1f9c567303a0e351c5918c1a20e2a36324dd43adfe5a84d8504e8643edf70c54"
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue

Staff