#!/usr/bin/env python3
# summary: Serve the authenticated fleet certificate authority.
"""starchaser fleet ca serve SOURCE

Share a public fleet authority and sign only an own controller's checked server CSR.
Use Open on my phone in Settings > Mission Control to set up phone trust.
serve reads one authenticated fleet request from standard input.
"""
import importlib.machinery,importlib.util,ipaddress,json,socket,sys
from pathlib import Path
_F=None
_P=None

def module(name,path):
    loader=importlib.machinery.SourceFileLoader(name,str(path));spec=importlib.util.spec_from_loader(name,loader);m=importlib.util.module_from_spec(spec);loader.exec_module(m);return m

def fleet():
    global _F
    if _F is None:_F=module('phone_fleet_registry',Path(__file__).resolve().with_name('starchaser-fleet'))
    return _F

def phone():
    global _P
    if _P is None:
        path=Path(__file__).resolve().parent.parent/'system/usr/local/lib/starchaser/phone_trust.py'
        if not path.is_file():path=Path('/usr/local/lib/starchaser/phone_trust.py')
        _P=module('phone_fleet_protocol',path)
    return _P

def identity(F):
    value=F.load()['security'].get('identity')
    if value and not F.verify_fleet_identity(value):raise ValueError("The fleet identity couldn't be verified. Open Settings > Fleet.")
    return value['certificate']['body'] if value else None

def receive(source,request):
    F=fleet();root=identity(F)
    entry=F.get('dev-'+source)
    if not root or root['founder']!=F.device_id() or not entry or not F.certified_identity(F._security_members(F.load()).get(entry['id']),entry):raise ValueError('Only a current own fleet computer can use this authority.')
    if not isinstance(request,dict) or request.get('root')!=root['rootKey']:raise ValueError('The fleet authority changed. Refresh Fleet and try again.')
    directory=F.DEVICES/'fleet-web-ca';P=phone();ca=P.ensure_ca(directory,root_binding=root['rootKey'])
    if request.get('op')=='authority' and set(request)=={'op','root'}:return {'ok':True,'authority':ca.read_text(),'root':root['rootKey']}
    if request.get('op')!='sign' or set(request)!={'op','root','csr','hostname','addresses'}:raise ValueError('Use a public server certificate request.')
    hostname=(entry.get('hostname') or F.load_link().peer(source).get('name') or '').split('.')[0]+'.local'
    if request['hostname']!=hostname:raise ValueError('The request must use this controller’s known .local name. Refresh Fleet and try again.')
    P.checked_names(request['hostname'],request['addresses'])
    known=set()
    addresses=entry.get('addresses') or {}
    for value in [addresses.get('last'),addresses.get('tailscale'),*(addresses.get('lan') or []),*F.load_link().candidates(F.load_link().peer(source))]:
        try:known.add(str(ipaddress.ip_address(value)))
        except (ValueError,TypeError):pass
    if any(str(ipaddress.ip_address(value)) not in known for value in request['addresses']):raise ValueError("The request has an address this controller hasn't reported. Refresh Fleet and try again.")
    if not F.NO_SPAWN:
        L=F.load_link();L.notify_desktop(L.session_env(),'preferences-system',F.display_name(entry)+' is setting up phone trust','Your fleet is signing this computer’s private-network Mission Control certificate. Settings > Fleet records the action. Removing the computer ends its permission.')
    cert=P.sign_csr(directory,request['csr'],request['hostname'],request['addresses'])
    F.record_activity(source,F.display_name(entry),'Signed a Mission Control certificate')
    return {'ok':True,'root':root['rootKey'],'authority':ca.read_text(),'certificate':cert}

def obtain(directory,hostname,addresses):
    F=fleet();P=phone();root=identity(F);directory=Path(directory)
    if not root:return (*P.server_certificate(directory,hostname,addresses),P.ensure_ca(directory))
    import hashlib
    binding=directory/'authority.root';cert,key,ca=(directory/name for name in ('server.crt','server.key','authority.crt'))
    if binding.is_file() and binding.read_text().strip()==hashlib.sha256(root['rootKey'].encode()).hexdigest() and all(path.is_file() for path in (cert,key,ca)):
        try:P.accept_leaf(directory,cert.read_text(),ca.read_text(),key,hostname,addresses)
        except (ValueError,OSError):pass
        else:return cert,key,ca
    if root['founder']==F.device_id():
        ca=P.ensure_ca(directory,root_binding=root['rootKey']);cert,key=P.server_certificate(directory,hostname,addresses);return cert,key,ca
    entry=F.get('dev-'+root['founder'])
    if not entry:raise ValueError('The fleet’s certificate authority computer was removed. Keep using an existing controller, or start a new fleet and install its new phone trust profile.')
    L=F.load_link()
    try:peer=L.peer(root['founder'])
    except (KeyError,ValueError):raise ValueError('Turn on the fleet’s certificate authority computer and refresh Fleet before setting up this controller.') from None
    csr,key=P.create_request(directory,hostname,addresses)
    request={'op':'sign','root':root['rootKey'],'csr':csr,'hostname':hostname,'addresses':addresses}
    result=L.ssh_to(peer,'phone-ca',input=json.dumps(request)+'\n',timeout=40)
    try:answer=json.loads(result.stdout or '{}')
    except ValueError:answer={}
    if result.returncode or not answer.get('ok') or answer.get('root')!=root['rootKey']:raise ValueError(answer.get('error') or 'Turn on '+F.display_name(entry)+' once to sign this controller’s certificate, then try again.')
    cert=P.accept_leaf(directory,answer.get('certificate'),answer.get('authority'),key,hostname,addresses)
    ca=P.import_authority(directory,answer['authority'],root['rootKey'])
    return cert,key,ca

def main(args):
    if args in ([],['--help'],['-h'],['help']):
        print(__doc__);return
    if len(args)==2 and args[0]=='serve':
        data=sys.stdin.buffer.readline(65537)
        if len(data)>65536:raise ValueError('The certificate request is too large.')
        print(json.dumps(receive(args[1],json.loads(data))))
    else:raise ValueError('Use Open on my phone in Settings > Mission Control.')
if __name__=='__main__':
    try:main(sys.argv[1:])
    except (ValueError,OSError,KeyError):print(json.dumps({'ok':False,'error':'The fleet certificate request was refused. Check current membership, the authority computer and this controller’s name in Fleet.'}));raise SystemExit(1)
