256 lines
15 KiB
Python

#!/usr/bin/python3
"""Atlas Development artifact retention. Dry run by default; never traverses links."""
import argparse
from contextlib import contextmanager
from datetime import datetime
import errno
import stat
import subprocess
import fcntl
import json
import os
from pathlib import Path
import re
import shutil
import socket
import sys
import time
ROOT = Path('/opt/plotdirector-dev')
LEGACY = Path('/srv/apps/plotdirector-dev')
PINS = Path('/etc/plotdirector-development/retention-protected.json')
REPOSITORY = Path('/srv/repos/PlotDirector')
TEMPORARY = Path('/srv/tmp')
BUILDS = Path('/srv/repos/.plotdirector-builds')
# Only recognised published-output entries are disposable. Unknown entries fail closed.
ASSETS = {'runtimes','Help','Docs','Data','Content','wwwroot','cs','de','es','fr','it','ja','ko','pl','pt-BR','ru','tr','zh-Hans','zh-Hant','dotnet-tools.json','web.config','PlotLine','appsettings.json','appsettings.Development.json','deployment-manifest.json'}
SENSITIVE = {'.git','.retain','.protect','App_Data','uploads','DataProtectionKeys','source','evidence','acceptance'}
SOURCE_SUFFIXES = ('.patch','.tar','.tar.gz','.zip','.cs','.csproj','.sln','.slnx','.py','.sh','.razor','.cshtml','.fs','.fsproj','.vb','.vbproj','.sql','.props','.targets','.ps1','.tar.xz','.tar.bz2','.7z')
def overlaps(a,b):
return a == b or a in b.parents or b in a.parents
def success_keep(receipts, active):
ordered = sorted((d for d in receipts if d.get('status') == 'activated'), key=lambda d:datetime.fromisoformat(d['completed_utc'].replace('Z','+00:00')).timestamp(), reverse=True)
previous=[]
for d in ordered:
name=d['release']['id']
if name != active and name not in previous:previous.append(name)
return {active,*previous[:3]}, {d['release']['id'] for d in ordered}
def preflight():
for p in ('/srv',str(ROOT)):
v=os.statvfs(p); fraction=v.f_bavail/v.f_blocks
print(f'STORAGE {p} available={v.f_bavail*v.f_frsize} free={fraction:.1%}' + (' WARNING below 20%' if fraction<.2 else ''),flush=True)
def process_refs():
refs=[]
for p in Path('/proc').iterdir():
if not p.name.isdigit() or int(p.name)==os.getpid():continue
try:
for q in [p/'cwd',p/'exe',*(p/'fd').iterdir()]:
try:
dest=os.readlink(q)
if dest.startswith(('/srv/','/opt/plotdirector-dev/')):refs.append(Path(dest.removesuffix(' (deleted)')))
except OSError as error:
if error.errno not in (errno.ENOENT,errno.ESRCH):raise
for line in (p/'maps').read_text().splitlines():
fields=line.split(maxsplit=5)
if len(fields)==6 and fields[5].startswith(('/srv/','/opt/plotdirector-dev/')):refs.append(Path(fields[5].removesuffix(' (deleted)')))
args=(p/'cmdline').read_bytes().split(b'\0')
# Command arguments can reference an output directory before it is opened.
for arg in args:
s=arg.decode(errors='replace')
value=s.split('=',1)[-1]
if value.startswith(('/srv/','/opt/plotdirector-dev/')):refs.append(Path(value))
except OSError as error:
if error.errno not in (errno.ENOENT,errno.ESRCH):raise
continue
return [value for path in refs for value in (path,path.resolve())]
def marked(p):
return any((p/name).exists() or (p/name).is_symlink() for name in ('.retain','.protect'))
def linked_ancestor(p):
return any(q.is_symlink() for q in (p,*p.parents))
def valid_snapshot(p):
# Links may count among the protected snapshots, but are never deletion candidates.
try:
for name in ('PlotLine.dll','PlotLine.runtimeconfig.json','PlotLine.deps.json'):
info=(p/name).lstat()
if not stat.S_ISREG(info.st_mode) or (name.endswith('.json') and info.st_size>32*1024*1024):return False
with (p/'PlotLine.dll').open('rb') as stream:
if stream.read(2)!=b'MZ':return False
runtime=json.loads((p/'PlotLine.runtimeconfig.json').read_text())
deps=json.loads((p/'PlotLine.deps.json').read_text())
return isinstance(runtime.get('runtimeOptions'),dict) and isinstance(deps.get('targets'),dict)
except (OSError,ValueError,TypeError,AttributeError):return False
def read_pins():
# A publisher cannot change administrator pins or redirect their configuration.
for path in (PINS,*PINS.parents):
info=path.lstat()
if path.is_symlink() or info.st_uid!=0 or info.st_mode&0o022:
raise RuntimeError('Untrusted retention pin configuration')
if not stat.S_ISREG(PINS.lstat().st_mode):raise RuntimeError('Retention pins must be a regular file')
data=json.loads(PINS.read_text())
if not isinstance(data.get('paths'),list) or any(not isinstance(p,str) or not Path(p).is_absolute() or '..' in Path(p).parts for p in data['paths']):
raise RuntimeError('Retention pins require exact absolute paths')
return [value for p in data['paths'] for value in (Path(p),Path(p).resolve())]
def registered_worktrees():
# Reuse Atlas's installed secret-free Git inspection, not repository-controlled
# configuration under root. The public CLI does not allow `worktree`; its trusted
# underlying reader accepts this fixed metadata operation in the same namespace.
module=Path('/usr/local/lib/atlas-security/git_snapshot.py')
for path in (module,*module.parents):
info=path.lstat()
if path.is_symlink() or info.st_uid!=0 or info.st_mode&0o022:
raise RuntimeError('Trusted Git inspector unavailable')
code="import sys;sys.path.insert(0,'/usr/local/lib/atlas-security');from git_snapshot import read;sys.stdout.buffer.write(read(sys.argv[1],'-c','safe.directory=/input','worktree','list','--porcelain','-z'))"
listing=subprocess.check_output(['/usr/bin/python3','-I','-c',code,str(REPOSITORY)],text=True,timeout=40)
return [REPOSITORY if line[9:]=='/input' else Path(line[9:]) for line in listing.split('\0') if line.startswith('worktree ')]
def protections(active,legacy,root=None):
return [active,legacy/'current',legacy/'App_Data',legacy/'uploads',(root or ROOT)/'shared',*read_pins(),*registered_worktrees(),*process_refs()]
def mount_points():
def decode(value):
return re.sub(r'\\([0-7]{3})',lambda m:chr(int(m[1],8)),value)
return {Path(decode(line.split()[4])) for line in Path('/proc/self/mountinfo').read_text().splitlines()}
def inspect(p, published=True, age=0, bound=False):
"""Refuse repository/source, evidence, persistent files, links and mount boundaries."""
if linked_ancestor(p) or not p.is_dir():return 'link/non-directory or linked ancestor'
mounts=mount_points()
if p in mounts or os.path.ismount(p):return 'mount boundary'
if any((q/'.git').exists() or (q/'.git').is_symlink() for q in (p,*p.parents)):return 'repository/source ancestor'
if any(p/name in mounts for name in ('PlotLine.dll','PlotLine.runtimeconfig.json','PlotLine.deps.json')):return 'mount boundary'
if not valid_snapshot(p):return 'not a recognised application publish'
if re.search(r'rollback|restore|acceptance|retain|evidence|baseline',p.name,re.I):return 'named protected package'
entries=list(p.iterdir())
if published:
unknown=[x.name for x in entries if not (bound and x.is_symlink()) and x.name not in ASSETS and not x.name.endswith(('.dll','.pdb','.deps.json','.runtimeconfig.json','.staticwebassets.endpoints.json'))]
if unknown:return 'source/evidence/unknown entries: '+','.join(unknown[:4])
cutoff=time.time()-age
device=p.stat().st_dev
for base,dirs,files in os.walk(p,followlinks=False):
for name in dirs+files:
q=Path(base)/name;s=q.lstat()
if s.st_dev!=device or q in mounts or (name in dirs and os.path.ismount(q)):return 'mount boundary'
if name.casefold() in {'.retain','.protect'}:return 'retention marker'
if age and s.st_mtime>cutoff:return 'recent content'
if bound and q.is_symlink():
dest=q.resolve(strict=True)
if dest.is_relative_to(ROOT/'shared') or dest.is_relative_to(LEGACY/'current'):continue
return 'unexpected runtime binding'
if name.casefold() in {value.casefold() for value in SENSITIVE} or name.casefold().endswith(SOURCE_SUFFIXES):return 'source, pin, evidence or persistent content: '+name
if q.is_symlink():return 'contains symlink; preserve for review'
if age and p.stat().st_mtime>cutoff:return 'recent directory'
return None
def plan(root=None,legacy=None):
root=root or ROOT;legacy=legacy or LEGACY
active=(root/'current').resolve(strict=True)
if active.parent.parent!=root/'releases' or active.name!='app':raise RuntimeError('Unsafe active release target')
marker=json.loads((root/'active-deployment.json').read_text())
if marker['release']!=active.parent.name:raise RuntimeError('Active marker/symlink mismatch')
receipts=[json.loads(p.read_text()) for p in (root/'deployment-receipts').glob('*.json')]
keep,successful=success_keep(receipts,active.parent.name)
protected=protections(active,legacy,root)
candidates=[];retained=[]
def add(p,category,age=0):
reason=next(('referenced/protected' for ref in protected if overlaps(p,ref)),None)
if reason is None:reason=inspect(p,age=age)
if reason:retained.append((str(p),reason))
else:candidates.append((str(p),category))
for p in sorted((root/'releases').iterdir()):
if p.name in keep:retained.append((str(p),'active/recent successful release'));continue
if p.name not in successful:retained.append((str(p),'no success receipt; preserve'));continue
if re.search('rollback|restore|acceptance|baseline',p.name,re.I):retained.append((str(p),'named recovery package'));continue
# Keep manifest, SQL and qualification evidence; prune only the old runtime payload.
app=p/'app'
if not app.exists():continue
if p.is_symlink() or any(overlaps(p,r) for r in protected) or marked(p):
retained.append((str(p),'referenced/protected'));continue
reason=inspect(app,bound=True)
if reason:retained.append((str(p),reason))
else:candidates.append((str(app),'manifest-release-payload'))
# The legacy deployment system stopped in November; keep three newest valid snapshots,
# including archives linked onto the root filesystem. They are explicit recovery pins.
snaps=sorted(legacy.glob('current-before-*'),key=lambda p:(p.lstat().st_mtime,p.name),reverse=True)
valid=[p for p in snaps if valid_snapshot(p)]
for p in snaps:
if p in valid[:3]:retained.append((str(p),'three latest valid installation snapshots'))
else:add(p,'installation-snapshot')
if (legacy/'releases').is_dir() and not linked_ancestor(legacy/'releases'):
for p in sorted((legacy/'releases').iterdir()):add(p,'legacy-release')
for base,pattern,category,age in [(TEMPORARY,'plotdirector-dev-publish-*','temporary-publish',48*3600),(BUILDS,'*','build-package',7*86400)]:
for p in sorted(Path(base).glob(pattern)):
if p.is_dir():add(p,category,age)
return candidates,retained,active
def candidate_scope(p,category):
if not p.is_absolute() or linked_ancestor(p):return False
return {
'manifest-release-payload':p.name=='app' and p.parent.parent==ROOT/'releases',
'legacy-release':p.parent==LEGACY/'releases',
'installation-snapshot':p.parent==LEGACY and p.name.startswith('current-before-'),
'temporary-publish':p.parent==TEMPORARY and p.name.startswith('plotdirector-dev-publish-'),
'build-package':p.parent==BUILDS,
}.get(category,False)
@contextmanager
def directory_fd(path):
# Anchor removal through every ancestor without following a substituted link.
fd=os.open('/',os.O_RDONLY|os.O_DIRECTORY)
try:
for component in path.parts[1:]:
child=os.open(component,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW,dir_fd=fd)
os.close(fd);fd=child
yield fd
finally:os.close(fd)
def remove_candidate(p):
if not shutil.rmtree.avoids_symlink_attacks:raise RuntimeError('Symlink-safe removal unavailable')
identity=p.lstat()
with directory_fd(p.parent) as parent:
actual=os.stat(p.name,dir_fd=parent,follow_symlinks=False)
if (actual.st_dev,actual.st_ino)!=(identity.st_dev,identity.st_ino) or not stat.S_ISDIR(actual.st_mode):
raise RuntimeError('Candidate replaced during removal')
shutil.rmtree(p.name,dir_fd=parent)
def run(apply=False):
if socket.gethostname()!='atlas' or os.geteuid()!=0:raise RuntimeError('Atlas root only')
with (ROOT/'deployment.lock').open('r+') as lock:
fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
preflight()
candidates,retained,active=plan()
print(json.dumps({'retained_count':len(retained)} if apply else {'retained':retained}),flush=True)
before=shutil.disk_usage('/srv').free; totals={}; processed=0
for name,category in candidates:
p=Path(name)
if (ROOT/'current').resolve()!=active:raise RuntimeError('Active release changed')
if not candidate_scope(p,category):raise RuntimeError('Candidate outside approved physical scope')
# Pins, source, mounts, age, registered worktrees and processes may have
# changed since planning. Recheck immediately before any deletion.
protected=protections(active,LEGACY)
age={'temporary-publish':48*3600,'build-package':7*86400}.get(category,0)
reason=next(('referenced/protected' for ref in protected if overlaps(p,ref)),None)
if category=='manifest-release-payload' and marked(p.parent):reason='release retention marker'
reason=reason or inspect(p,age=age,bound=category=='manifest-release-payload')
if reason:
print('PRESERVE '+category+' '+name+' reason='+reason,flush=True);continue
blocks=sum(q.lstat().st_blocks*512 for base,dirs,files in os.walk(p) for q in [Path(base),*(Path(base)/n for n in files)])
print(('REMOVE ' if apply else 'WOULD REMOVE ')+category+' '+name+' bytes='+str(blocks),flush=True)
totals[category]=totals.get(category,0)+blocks
processed+=1
if apply:remove_candidate(p)
print(json.dumps({'apply':apply,'directories':processed,'planned_directories':len(candidates),'estimated_bytes':totals,'srv_available_increase':shutil.disk_usage('/srv').free-before}),flush=True)
preflight()
if __name__=='__main__':
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--apply',action='store_true');args=parser.parse_args()
run(args.apply)