# -*- coding: utf-8 -*-
"""只操作本程序创建的临时对象；全部数据为合成样本。"""
import os, sys, json, sqlite3, tempfile, pathlib, subprocess, time, socket, stat
from pathlib import Path
def emit(**kw):
    print(json.dumps(kw, ensure_ascii=False, sort_keys=True))

import shutil, threading, urllib.request, urllib.error, http.server, socketserver, contextlib
NGINX=os.environ.get('NGINX_BIN') or shutil.which('nginx')
assert NGINX, '需真实Nginx；建议用官方1.28.0独立编译并设置NGINX_BIN'
def freeport():
    s=socket.socket(); s.bind(('127.0.0.1',0)); p=s.getsockname()[1]; s.close(); return p
class Threaded(socketserver.ThreadingMixIn,http.server.HTTPServer):
    daemon_threads=True
def backend(handler,host='127.0.0.1',port=0):
    class H(http.server.BaseHTTPRequestHandler):
        protocol_version='HTTP/1.1'
        def log_message(self,*a): pass
        def do_GET(self):
            status,headers,body=handler(self.path)
            self.send_response(status)
            for k,v in headers.items(): self.send_header(k,v)
            self.send_header('Content-Length',str(len(body))); self.end_headers()
            try: self.wfile.write(body)
            except (BrokenPipeError,ConnectionResetError): pass
    s=Threaded((host,port),H); threading.Thread(target=s.serve_forever,daemon=True).start(); return s
def request(port,path='/',host='demo.test'):
    q=urllib.request.Request('http://127.0.0.1:'+str(port)+path,headers={'Host':host,'Connection':'close'})
    opener=urllib.request.build_opener(urllib.request.ProxyHandler({}))
    try: r=opener.open(q,timeout=5)
    except urllib.error.HTTPError as e: r=e
    with r: return {'status':r.code,'headers':dict(r.headers),'body':r.read().decode()}
@contextlib.contextmanager
def nginx(http_config):
    assert os.name=='posix', '本实验按Linux独立prefix设计'
    with tempfile.TemporaryDirectory(prefix='ywebs-next132-b2-nginx-') as d:
        p=Path(d); assert p.name.startswith('ywebs-next132-b2-nginx-')
        def render(body):
            text='worker_processes 1; daemon off; master_process on; pid '+d+'/nginx.pid; error_log '+d+'/error.log notice; events {worker_connections 128;} http {access_log off; client_body_temp_path '+d+'/body; proxy_temp_path '+d+'/proxy; '+body+'}'
            for forbidden in ['/var/www','/opt/ywebs','/usr/local/nginx/conf']: assert forbidden not in text
            (p/'nginx.conf').write_text(text,encoding='utf-8')
        render(http_config)
        def command(*a): return subprocess.run([NGINX,'-p',d+'/','-c',str(p/'nginx.conf')]+list(a),stdout=subprocess.PIPE,stderr=subprocess.STDOUT,universal_newlines=True)
        tested=command('-t'); assert tested.returncode==0,tested.stdout
        proc=subprocess.Popen([NGINX,'-p',d+'/','-c',str(p/'nginx.conf')],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
        time.sleep(.3); assert proc.poll() is None,(p/'error.log').read_text()
        try: yield p,proc,render,command
        finally:
            if proc.poll() is None: proc.terminate()
            try: proc.wait(timeout=5)
            except subprocess.TimeoutExpired: proc.kill(); proc.wait()
state={'status':204,'business':0}
def handler(path):
    if path.startswith('/auth'): return state['status'],{'WWW-Authenticate':'Bearer realm="demo"'} if state['status']==401 else {},b''
    state['business']+=1; return 200,{'Content-Type':'text/plain'},b'allowed'
b=backend(handler); port=freeport(); bp=b.server_port
conf='server {listen 127.0.0.1:'+str(port)+'; location = /auth {internal; proxy_pass http://127.0.0.1:'+str(bp)+'/auth; proxy_pass_request_body off; proxy_set_header Content-Length "";} location / {auth_request /auth; proxy_pass http://127.0.0.1:'+str(bp)+'/business;}}'
rows=[]
try:
    with nginx(conf):
        for status in [204,401,403,500]:
            state['status']=status; before=state['business']; r=request(port); rows.append({'auth_status':status,'client_status':r['status'],'business_dispatched':state['business']-before,'www_authenticate':r['headers'].get('WWW-Authenticate')})
    assert [x['client_status'] for x in rows]==[200,401,403,500] and [x['business_dispatched'] for x in rows]==[1,0,0,0] and rows[1]['www_authenticate']=='Bearer realm="demo"'
    emit(matrix=rows)
finally: b.shutdown(); b.server_close()
