#!/usr/bin/env python3
"""GoF Adapter: append an owner-downloaded key fragment without displaying it.
Python 3.10+ standard library only. No network, key issuance, or key revocation.
"""
import argparse,fcntl,hashlib,json,os,re,resource,stat,subprocess,sys,tempfile
from pathlib import Path
LIMIT=2*1024*1024
RULES={'api':{'NEXISCOMMS_API_KEY':None,'NEXISCOMMS_API_BASE_URL':'https://app.nexiscomms.com','NEXISCOMMS_ACCOUNT_ID':None},'mcp':{'NEXISCOMMS_MCP_KEY':None,'NEXISCOMMS_MCP_URL':'https://app.nexiscomms.com/mcp','NEXISCOMMS_ACCOUNT_ID':None}}
class Held(Exception):pass
class PrivateArgumentParser(argparse.ArgumentParser):
 def error(self,message):raise Held('invalid_cli_arguments')
def need(value,label):
 if not value:raise Held(label)
def sha(data):return hashlib.sha256(data).hexdigest()
def fingerprint(s):return(s.st_dev,s.st_ino,s.st_mode,s.st_uid,s.st_gid,s.st_nlink,s.st_size,s.st_mtime_ns,s.st_ctime_ns)
def canonical(path):
 p=Path(os.path.abspath(os.path.expanduser(str(path))))
 need(p.resolve()==p,'symlink_path_refused');return p
def metadata(s,maximum):
 need(stat.S_ISREG(s.st_mode)and s.st_uid==os.getuid()and s.st_nlink==1 and s.st_size<=maximum,'owned_regular_single_link_file_required')
def snapshot(path,maximum=LIMIT,private=True):
 try:fd=os.open(path,os.O_RDONLY|os.O_NOFOLLOW)
 except FileNotFoundError:return None,b''
 try:
  s=os.fstat(fd);metadata(s,maximum)
  if private:need(stat.S_IMODE(s.st_mode)==0o600,'private_destination_0600_required')
  raw=b''
  while len(raw)<=maximum:
   part=os.read(fd,min(65536,maximum+1-len(raw)))
   if not part:break
   raw+=part
  need(len(raw)<=maximum and fingerprint(s)==fingerprint(os.fstat(fd))==fingerprint(os.lstat(path)),'file_changed_during_read')
  return fingerprint(s),raw
 finally:os.close(fd)
def source(path,purpose,expected_account=None):
 parent=os.lstat(path.parent);need(stat.S_ISDIR(parent.st_mode)and parent.st_uid==os.getuid()and not parent.st_mode&0o022,'owned_private_download_directory_required')
 need(re.fullmatch('nexiscomms-'+purpose+'-[a-f0-9]{32}\\.env',path.name),'download_filename_purpose_or_key_id_invalid')
 fd=os.open(path,os.O_RDONLY|os.O_NOFOLLOW)
 try:
  s=os.fstat(fd);metadata(s,8192);need(fingerprint(s)==fingerprint(os.lstat(path)),'download_changed_before_protection')
  # Open only for metadata, then protect before reading any credential bytes.
  os.fchmod(fd,0o600);s=os.fstat(fd);raw=os.read(fd,8193)
  need(len(raw)<=8192 and not os.read(fd,1)and fingerprint(s)==fingerprint(os.fstat(fd))==fingerprint(os.lstat(path)),'download_changed_during_read')
  need(stat.S_IMODE(s.st_mode)==0o600,'private_download_required')
  text=raw.decode('ascii');rows=text.splitlines();need(len(rows)==3 and text.endswith('\n'),'exact_three_download_entries_required')
  values={}
  for line in rows:
   need('='in line,'literal_download_assignment_required');name,value=line.split('=',1)
   need(name in RULES[purpose]and name not in values and value and '\x00'not in value,'unknown_duplicate_or_empty_download_entry');values[name]=value
  need(set(values)==set(RULES[purpose]),'exact_purpose_entries_required')
  keyname='NEXISCOMMS_'+purpose.upper()+'_KEY'
  need(re.fullmatch('mnx_[A-Za-z0-9_-]{40,100}',values[keyname]),'canonical_NexisComms_key_required')
  account=values['NEXISCOMMS_ACCOUNT_ID'];need(re.fullmatch('[a-f0-9]{32}',account),'canonical_account_required')
  if expected_account is not None:need(account==expected_account,'download_account_mismatch')
  for name,value in RULES[purpose].items():
   if value is not None:need(values[name]==value,'canonical_HTTPS_endpoint_required')
  return fingerprint(s),raw,values
 finally:os.close(fd)
def git_gate(path):
 options={'cwd':str(path.parent),'capture_output':True,'timeout':10,'env':{'PATH':os.environ.get('PATH','/usr/bin:/bin'),'GIT_OPTIONAL_LOCKS':'0','LC_ALL':'C'}}
 r=subprocess.run(['git','rev-parse','--show-toplevel'],**options)
 if r.returncode!=0:
  # Only Git's exact no-repository result permits a non-Git destination.
  # Corrupt metadata, dubious ownership, permissions and config failures hold.
  absent=b'fatal: not a git repository (or any of the parent directories): .git'
  need(r.returncode==128 and not r.stdout and r.stderr.strip()==absent,'Git_repository_detection_failed')
  for directory in (path.parent,*path.parent.parents):
   try:(directory/'.git').lstat()
   except FileNotFoundError:continue
   else:raise Held('Git_metadata_present_but_unreadable_or_invalid')
  return False
 root=Path(os.fsdecode(r.stdout).strip()).resolve();need(path.is_relative_to(root),'destination_outside_repository')
 name=str(path.relative_to(root));options['cwd']=str(root)
 r=subprocess.run(['git','ls-files','--error-unmatch','--',name],**options);need(r.returncode==1 and not r.stdout,'destination_must_be_untracked')
 r=subprocess.run(['git','check-ignore','--no-index','-q','--',name],**options);need(r.returncode==0,'destination_must_be_Git_ignored')
 return True
def merged(old,values):
 # Atomic compare-and-swap below may replace the inode, NEVER existing bytes:
 # the complete original destination is an exact prefix of the new file.
 need(b'\x00'not in old and not old.startswith(b'\xef\xbb\xbf'),'literal_text_destination_required')
 assignment=re.compile(rb'^[ \t]*(?:export[ \t]+)?([A-Za-z_][A-Za-z0-9_]*)[ \t]*=(.*)$')
 public={'NEXISCOMMS_API_BASE_URL','NEXISCOMMS_MCP_URL','NEXISCOMMS_ACCOUNT_ID'}
 pending=dict(values);seen=set();quote=None
 for line in old.splitlines(keepends=True):
  content=b''
  if quote is None:
   match=assignment.match(line)
   bare=re.fullmatch(rb'[ \t]*(?:export[ \t]+)?([A-Za-z_][A-Za-z0-9_]*)[ \t]*(?:#[^\r\n]*)?(?:\r?\n)?',line)
   if bare and bare[1].decode()in values:raise Held('existing_credential_name_collision'if bare[1].decode()not in public else'existing_public_metadata_conflict')
   if match:
    name=match[1].decode();content=match[2].lstrip(b' \t')
    if name in values:
     need(name in public,'existing_credential_name_collision')
     need(name not in seen,'duplicate_existing_public_metadata_refused');seen.add(name)
     literal=content.strip()
     # Only exact literal public metadata is compatible. Ambiguous quoting,
     # expansion, multiline values or comments fail closed, without output.
     if literal[:1]in(b'"',b"'"):
      q=literal[:1];need(len(literal)>=2 and literal[-1:]==q and q not in literal[1:-1],'existing_public_metadata_conflict');literal=literal[1:-1]
     need(literal==values[name].encode(),'existing_public_metadata_conflict');pending.pop(name)
    if content[:1]in(b'"',b"'"):quote=content[:1];content=content[1:]
  if quote is not None:
   escaped=False
   for byte in content if content else line:
    if escaped:escaped=False
    elif byte==92 and quote==b'"':escaped=True
    elif bytes([byte])==quote:quote=None;break
 need(quote is None,'well_formed_destination_quotes_required')
 extra=b''.join(n.encode()+b'='+v.encode()+b'\n'for n,v in pending.items())
 raw=old+(b'\n'if old and not old.endswith(b'\n')else b'')+extra
 need(raw.startswith(old)and len(raw)<=LIMIT,'bounded_exact_prefix_append_required');return raw

class EnvImportAdapter:
 def __init__(self,source_path,destination,purpose,expected_account=None,move=False):
  need(purpose in RULES,'api_or_mcp_purpose_required');self.src=canonical(source_path);self.dest=canonical(destination);self.purpose=purpose;self.expected=expected_account;self.move=move
  need(self.src!=self.dest,'source_and_destination_must_differ')
 def run(self,before_replace=None):
  git_gate(self.dest);parent=os.lstat(self.dest.parent);need(stat.S_ISDIR(parent.st_mode)and parent.st_uid==os.getuid()and not parent.st_mode&0o022,'owned_private_destination_directory_required')
  sf,raw,values=source(self.src,self.purpose,self.expected)
  lock=self.dest.parent/(self.dest.name+'.nexiscomms-import.lock');fd=os.open(lock,os.O_RDWR|os.O_CREAT|os.O_NOFOLLOW,0o600);temp=None;committed=False
  try:
   ls=os.fstat(fd);metadata(ls,4096);need(stat.S_IMODE(ls.st_mode)==0o600,'private_import_lock_required');fcntl.flock(fd,fcntl.LOCK_EX|fcntl.LOCK_NB)
   prior,old=snapshot(self.dest);result=merged(old,values)
   out,name=tempfile.mkstemp(prefix=self.dest.name+'.nexiscomms-import-',dir=self.dest.parent);temp=Path(name)
   # Explicitly excluded temporary sibling names are required before any write.
   try:
    git_gate(temp);os.fchmod(out,0o600)
   except BaseException:
    os.close(out);raise
   with os.fdopen(out,'wb')as stream:stream.write(result);stream.flush();os.fsync(stream.fileno())
   if before_replace:before_replace()
   git_gate(self.dest);now,current=snapshot(self.dest);need(prior==now and sha(old)==sha(current),'destination_compare_and_swap_failed')
   ns=os.lstat(self.dest.parent);need((ns.st_dev,ns.st_ino,ns.st_uid)==(parent.st_dev,parent.st_ino,parent.st_uid),'destination_directory_changed')
   os.replace(temp,self.dest);temp=None;self.fsync_parent()
   actual,stored=snapshot(self.dest);need(actual is not None and stored==result,'destination_verification_failed');committed=True
   if self.move:
    new_sf,new_raw=snapshot(self.src,8192);need(new_sf==sf and sha(new_raw)==sha(raw),'download_changed_before_move_cleanup')
    self.src.unlink();directory=os.open(self.src.parent,os.O_RDONLY|os.O_DIRECTORY)
    try:os.fsync(directory)
    finally:os.close(directory)
   return{'imported':True,'purpose':self.purpose,'destination_mode':'0600','unrelated_entries_preserved':True,'append_only':True,'original_destination_bytes_preserved':True,'source_removed':self.move,'secret_printed':False}
  except BaseException as error:
   error.destination_persisted=committed;raise
  finally:
   if temp is not None:temp.unlink(missing_ok=True)
   os.close(fd)
 def fsync_parent(self):
  fd=os.open(self.dest.parent,os.O_RDONLY|os.O_DIRECTORY)
  try:os.fsync(fd)
  finally:os.close(fd)
def main():
 resource.setrlimit(resource.RLIMIT_CORE,(0,0));os.umask(0o077)
 p=PrivateArgumentParser(description='Append a downloaded NexisComms key fragment privately; never prints key values.')
 p.add_argument('--source',required=True);p.add_argument('--destination',required=True);p.add_argument('--purpose',choices=sorted(RULES),required=True);p.add_argument('--expected-account');p.add_argument('--move',action='store_true');a=p.parse_args()
 if a.expected_account:need(re.fullmatch('[a-f0-9]{32}',a.expected_account),'canonical_expected_account_required')
 print(json.dumps(EnvImportAdapter(a.source,a.destination,a.purpose,a.expected_account,a.move).run(),sort_keys=True))
if __name__=='__main__':
 try:main()
 except SystemExit:
  raise
 except BaseException as error:
  reason=str(error)if type(error)is Held and re.fullmatch('[a-zA-Z0-9_]+',str(error))else'import_held'
  print(json.dumps({'imported':getattr(error,'destination_persisted',False),'cleanup_or_import_held':True,'category':reason,'secret_printed':False},sort_keys=True));sys.exit(1)
