367 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
92 lines
5.0 KiB
Python
92 lines
5.0 KiB
Python
"""Bounded public realm preference; no account or credential storage."""
|
|
import json,os,stat,uuid
|
|
from pathlib import Path
|
|
|
|
KIND='last-successfully-reached-realm-v1'
|
|
MAX_BYTES=4096
|
|
|
|
def identity(profile,row):
|
|
if profile not in('octo','local-explicit')or not isinstance(row,dict):raise ValueError('Fixed profile and discovered realm required')
|
|
name,address,wire=row.get('name'),row.get('address'),row.get('wire_id')
|
|
if (not isinstance(name,str)or not 1<=len(name.encode('utf-8'))<=128 or any(ord(c)<32 or ord(c)==127 for c in name)
|
|
or not isinstance(address,str)or not 1<=len(address)<=128 or any(ord(c)<33 or ord(c)>126 for c in address)
|
|
or type(wire)is not int or not 0<=wire<=255):raise ValueError('Bounded discovered realm identity required')
|
|
return dict(profile=profile,name=name,address=address,wire_id=wire)
|
|
|
|
def _validated(value):
|
|
if not isinstance(value,dict)or set(value)!={'schema_version','kind','identity'}or type(value['schema_version'])is not int or value['schema_version']!=1 or value['kind']!=KIND:raise ValueError('Realm preference schema differs')
|
|
row=value['identity']
|
|
if not isinstance(row,dict)or set(row)!={'profile','name','address','wire_id'}or identity(row.get('profile'),row)!=row:raise ValueError('Realm preference identity differs')
|
|
return row
|
|
|
|
def _unique_object(pairs):
|
|
result={}
|
|
for key,value in pairs:
|
|
if key in result:raise ValueError('Duplicate realm preference key')
|
|
result[key]=value
|
|
return result
|
|
|
|
def read(path):
|
|
"""Missing, malformed, stale or unsafe preferences never authorize a choice."""
|
|
fd=None;directory=None
|
|
try:
|
|
path=Path(path);directory=os.open(path.parent,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW)
|
|
parent=os.fstat(directory)
|
|
if parent.st_uid!=os.getuid()or parent.st_mode&0o022:return None
|
|
fd=os.open(path.name,os.O_RDONLY|os.O_NOFOLLOW|os.O_NONBLOCK,dir_fd=directory)
|
|
before=os.fstat(fd)
|
|
if not stat.S_ISREG(before.st_mode)or before.st_uid!=os.getuid()or before.st_mode&0o077 or not 1<=before.st_size<=MAX_BYTES:return None
|
|
raw=os.read(fd,MAX_BYTES+1);after=os.fstat(fd)
|
|
if len(raw)!=before.st_size or (before.st_ino,before.st_size,before.st_mtime_ns)!=(after.st_ino,after.st_size,after.st_mtime_ns):return None
|
|
return _validated(json.loads(raw.decode('utf-8'),object_pairs_hook=_unique_object))
|
|
except (OSError,ValueError,TypeError,UnicodeError):return None
|
|
finally:
|
|
if fd is not None:os.close(fd)
|
|
if directory is not None:os.close(directory)
|
|
|
|
def matching_index(account,remembered,profile,validator):
|
|
"""Use current proof-checked list indices, never the persisted wire ID/index."""
|
|
try:
|
|
if not isinstance(remembered,dict)or remembered.get('profile')!=profile:return None
|
|
rows=account.get('realms')
|
|
if not isinstance(rows,list)or not 1<=len(rows)<=128:return None
|
|
matches=[]
|
|
for row in rows:
|
|
if (not isinstance(row,dict)or type(row.get('flags'))is not int or row['flags']&2):continue
|
|
if identity(profile,row)==remembered:matches.append(row)
|
|
if len(matches)!=1:return None
|
|
index=matches[0].get('index')
|
|
if type(index)is not int or validator(account,index,profile)!=matches[0]:return None
|
|
return index
|
|
except (ValueError,TypeError,KeyError):return None
|
|
|
|
def save(path,remembered):
|
|
"""Atomically replace only an owned regular bounded preference, mode0600."""
|
|
directory=None;temporary=None
|
|
try:
|
|
row=_validated(dict(schema_version=1,kind=KIND,identity=remembered))
|
|
path=Path(path)
|
|
directory=os.open(path.parent,os.O_RDONLY|os.O_DIRECTORY|os.O_NOFOLLOW)
|
|
st=os.fstat(directory)
|
|
if st.st_uid!=os.getuid()or st.st_mode&0o022:return False
|
|
def existing_safe():
|
|
try:r=os.stat(path.name,dir_fd=directory,follow_symlinks=False)
|
|
except FileNotFoundError:return True
|
|
return stat.S_ISREG(r.st_mode)and r.st_uid==os.getuid()and not r.st_mode&0o077 and r.st_size<=MAX_BYTES
|
|
if not existing_safe():return False
|
|
temporary='.'+path.name+'.'+uuid.uuid4().hex+'.tmp'
|
|
fd=os.open(temporary,os.O_WRONLY|os.O_CREAT|os.O_EXCL|os.O_NOFOLLOW,0o600,dir_fd=directory)
|
|
with os.fdopen(fd,'wb')as stream:
|
|
raw=(json.dumps(dict(schema_version=1,kind=KIND,identity=row),sort_keys=True,separators=(',',':'))+'\n').encode('utf-8')
|
|
if len(raw)>MAX_BYTES:raise ValueError('Realm preference size bound')
|
|
stream.write(raw);stream.flush();os.fsync(stream.fileno())
|
|
if not existing_safe():return False
|
|
os.replace(temporary,path.name,src_dir_fd=directory,dst_dir_fd=directory);temporary=None;os.fsync(directory)
|
|
return True
|
|
except (OSError,ValueError,TypeError,UnicodeError):return False
|
|
finally:
|
|
if temporary is not None and directory is not None:
|
|
try:os.unlink(temporary,dir_fd=directory)
|
|
except FileNotFoundError:pass
|
|
if directory is not None:os.close(directory)
|