Files
compras/scripts/install-client-hiring-release.py
T
nala 47649bd46c
tests / ci (push) Canceled after 0s
commit compras1 3011
2026-11-30 09:33:36 +02:00

121 lines
6.5 KiB
Python

"""Guarded installation of the authorised client hiring flow in the selected application."""
from pathlib import Path
import hashlib
import json
import os
import shutil
import subprocess
import sys
import uuid
import zipfile
root = Path('/var/www/compras-deploy/current').resolve()
assert root == Path('/var/www/compras-deploy/releases/presentation-20261129')
archive = Path('/root/compras-release-client-hiring.zip')
assert hashlib.sha256(archive.read_bytes()).hexdigest() == 'e6ecf82d0943fab658c65fff6b5d9c1c194104e743c38b158eb87fa8fe091e79'
z = zipfile.ZipFile(archive)
old = json.loads((root/'compras-release.json').read_text())
new = json.loads(z.read('compras-release.json'))
assert old['release_id'] == 'compras-47dfeee7485db877' and new['release_id'] == 'compras-e4e3196d1877e804'
assert old['components'] == new['components']
assert set(old['source_files']) <= set(new['source_files'])
changed = [n for n in old['source_files'] if old['source_files'][n] != new['source_files'][n]]
added = [n for n in new['source_files'] if n not in old['source_files']]
print(json.dumps({'changed': changed, 'added': added}), flush=True)
if '--install-authorized' not in sys.argv:
sys.exit(0)
allowed = {'app/Http/Controllers/PeopleHiringController.php', 'app/Http/Controllers/PeopleReportController.php',
'app/Http/Middleware/EnsureWorkContext.php', 'app/Models/Concerns/HasWorkContext.php',
'app/Services/PeopleAccess.php', 'app/Services/PeopleHiring.php', 'app/Services/PeopleWorkdesk.php',
'app/Console/Commands/SgcDeliveryCheck.php', 'app/Services/WorkContext.php',
'resources/js/lib/procurement-navigation.ts', 'resources/js/pages/people/index.tsx',
'resources/js/pages/people/show.tsx', 'routes/preview.php', 'routes/web.php'}
expected_added = {'app/Models/BusinessClient.php', 'app/Services/BusinessClients.php', 'app/Services/ThirdPartyHiring.php',
'app/Http/Controllers/BusinessClientController.php', 'config/third_party.php',
'database/migrations/2026_11_29_000004_create_business_clients.php', 'resources/js/pages/company/clients.tsx'}
assert set(changed) <= allowed and set(added) == expected_added
subprocess.run(['/usr/bin/php', str(root/'scripts/verify-compras-release.php'), str(root), '--installed'], check=True)
backup = Path('/var/backups/compras-presentation-20261129/client-hiring-installed')
backup.mkdir(mode=0o700, exist_ok=False)
env = (root/'.env').resolve()
assert env == Path('/var/www/compras-deploy/demonstration-20261129/.env')
env_attributes = env.stat()
assert env_attributes.st_gid == __import__('grp').getgrnam('www-data').gr_gid and env_attributes.st_mode & 0o040
shutil.copy2(env, backup/'selected.env.private')
(backup/'selected.env.private').chmod(0o600)
saved = changed + ['compras-release.json', 'public/build/manifest.json', 'public/build/fonts-manifest.json']
for name in saved:
destination = backup/name
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(root/name, destination)
with (backup/'database.dump').open('xb') as stream:
subprocess.run(['runuser', '-u', 'postgres', '--', 'pg_dump', '-Fc', '-d', 'compras_demo_20261129'], stdout=stream, check=True)
def write(name, data):
assert not Path(name).is_absolute() and '..' not in Path(name).parts
path = root/name
assert not path.is_symlink()
path.parent.mkdir(parents=True, exist_ok=True)
temp = path.with_name(path.name+'.client-next')
temp.write_bytes(data)
temp.chmod(0o644)
os.replace(temp, path)
def php(*args):
result = subprocess.run(['runuser', '-u', 'www-data', '--', '/usr/bin/php', *args], cwd=root, capture_output=True)
if result.returncode:
diagnostic = backup/'failed-command.private.log'
diagnostic.write_bytes(result.stdout+result.stderr)
diagnostic.chmod(0o600)
raise RuntimeError('Native command failed; private diagnostic: '+str(diagnostic))
return result.stdout.decode()
restore = 'compras_client_restore_'+uuid.uuid4().hex[:12]
created = False
maintenance = False
try:
migration = 'database/migrations/2026_11_29_000004_create_business_clients.php'
write(migration, z.read(migration))
write('scripts/upgrade-client-registry.php', Path('/root/upgrade-client-registry.php').read_bytes())
isolation = json.loads(Path('/var/backups/compras-presentation-20261129/client-registry-isolation.json').read_text())
assert isolation['state'] == 'passed' and isolation['active_registry_unchanged'] and isolation['active_empty_schema_matches_native_migration']
recovery = isolation['recovery_upgrade']
assert recovery['state'] == 'passed'
php('artisan', 'down', '--retry=3')
maintenance = True
for name in changed+added:
write(name, z.read(name))
schema = json.loads(php('scripts/upgrade-client-registry.php', '--record-verified-empty-registry'))
assert schema['state'] == 'passed'
for asset in new['frontend']['files']:
name = 'public/build/'+asset
assert not (root/name).exists() or (root/name).read_bytes() == z.read(name), 'Immutable asset collision'
if not (root/name).exists():
write(name, z.read(name))
for name in ['public/build/fonts-manifest.json', 'public/build/manifest.json', 'compras-release.json']:
write(name, z.read(name))
lines = env.read_text().splitlines()
assert not any(line.startswith('SGC_PEOPLE_THIRD_PARTY_ENABLED=') for line in lines)
env.write_text('\n'.join(lines)+'\nSGC_PEOPLE_THIRD_PARTY_ENABLED=true\n')
php('artisan', 'config:cache')
subprocess.run(['/usr/bin/php', str(root/'scripts/verify-compras-release.php'), str(root), '--installed'], check=True)
except BaseException:
env.write_bytes((backup/'selected.env.private').read_bytes())
os.chown(env, env_attributes.st_uid, env_attributes.st_gid)
env.chmod(env_attributes.st_mode & 0o777)
for name in saved:
write(name, (backup/name).read_bytes())
php('artisan', 'config:cache')
raise
finally:
if maintenance:
php('artisan', 'up')
if created:
subprocess.run(['runuser', '-u', 'postgres', '--', 'dropdb', restore], check=True)
proof = {'state': 'passed', 'release_id': new['release_id'], 'backup': str(backup),
'same_selected_application': True, 'recovery_copy_upgrade': recovery, 'selected_schema_upgrade': schema,
'new_configuration': {'SGC_PEOPLE_THIRD_PARTY_ENABLED': True}, 'existing_permissions_changed': False,
'external_financial_or_hr_dispatch': False, 'temporary_recovery_database_removed': True}
(backup/'result.json').write_text(json.dumps(proof, indent=2)+'\n')
print(json.dumps(proof))