File size: 4,717 Bytes
caf8059
 
 
 
 
 
5fd201e
caf8059
 
 
 
 
5fd201e
fc92530
 
caf8059
 
 
 
 
 
 
5fd201e
 
caf8059
 
 
 
 
 
 
5fd201e
0109623
caf8059
 
 
 
 
 
 
 
 
 
 
 
0109623
caf8059
 
 
5fd201e
 
 
0109623
 
 
 
 
caf8059
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
"""Single public HTTPS ingress for the existing app; local ports/UI remain unchanged."""
import json
from urllib.parse import urlsplit


class SpaceIngress:
    def __init__(self,app,origin,internal_port=7860,*,bridge=None):
        parsed=urlsplit(origin)
        if parsed.scheme!='https' or not parsed.hostname or parsed.path not in ('','/') or parsed.query or parsed.fragment or parsed.username or parsed.password:
            raise ValueError('INVALID_SPACE_ORIGIN')
        self.app,self.origin,self.host=app,origin.rstrip('/'),parsed.netloc
        self.internal=f'http://127.0.0.1:{internal_port}';self.internal_host=f'127.0.0.1:{internal_port}'
        self.bridge=bridge
        if bridge:
            bridge.app=app;bridge.internal=self.internal;bridge.internal_host=self.internal_host;bridge.internal_port=internal_port

    async def __call__(self,scope,receive,send):
        if scope['type']!='http':return await self.app(scope,receive,send)
        headers=dict(scope['headers']);host=headers.get(b'host',b'').decode();method=scope['method'];path=scope['path']
        health=method in {'GET','HEAD'} and path in {'/','/health/live'} and host.split(':')[0] in {'127.0.0.1','localhost','0.0.0.0'}
        if host!=self.host and not health:return await self.reject(send,400)
        if method not in {'GET','HEAD','OPTIONS'} and headers.get(b'origin',b'').decode()!=self.origin:return await self.reject(send,403)
        if any(key in headers for key in (b'x-user-id',b'x-tenant-id',b'x-internal-authorization',b'authorization')):return await self.reject(send,400)
        if self.bridge and await self.bridge.handle(scope,receive,send):return
        forwarded=[]
        for key,value in scope['headers']:
            if key==b'host':value=self.internal_host.encode()
            if key==b'origin' and value.decode()==self.origin:value=self.internal.encode()
            forwarded.append((key,value))
        inner={**scope,'headers':forwarded,'scheme':'http','server':('127.0.0.1',int(self.internal_host.split(':')[-1]))}
        start=None;body=bytearray();rewrite_session=path=='/api/session' and method=='GET'
        rewrite_runtime=bool(self.bridge and path=='/runtime.js' and method=='GET')
        rewrite_admin=bool(self.bridge and path in {'/admin/','/admin/index.html'} and method=='GET')
        def response_headers(values):
            result=[]
            for key,value in values:
                if key.lower()==b'content-security-policy':value=value.replace(b"frame-ancestors 'none'",b"frame-ancestors 'self' https://huggingface.co")
                if key.lower()==b'set-cookie':value=value.replace(b'SameSite=strict',b'SameSite=none').replace(b'samesite=strict',b'SameSite=none')+b'; Secure; Partitioned'
                if key.lower()==b'location' and value.startswith(self.internal.encode()):value=self.origin.encode()+value[len(self.internal):]
                result.append((key,value))
            return result
        async def outward(message):
            nonlocal start
            if message['type']=='http.response.start':
                message={**message,'headers':response_headers(message['headers'])}
                if (rewrite_session or rewrite_runtime or rewrite_admin) and message['status']==200:start=message;return
            if start is not None and message['type']=='http.response.body':
                body.extend(message.get('body',b''))
                if message.get('more_body'):return
                if rewrite_session:
                    value=json.loads(body);value.update(preview_origin=self.origin,workbench_origin=self.origin)
                    payload=json.dumps(value,ensure_ascii=False).encode()
                elif rewrite_runtime:payload=self.bridge.patch_runtime(body)
                else:
                    text=body.decode('utf-8')
                    if text.count('</body>')!=1:raise RuntimeError('SPACE_ADMIN_ADAPTER_MISMATCH')
                    payload=text.replace('</body>','<script type="module" src="/space/preview-parent.js"></script></body>').encode()
                start['headers']=[(k,v) for k,v in start['headers'] if k.lower()!=b'content-length']+[(b'content-length',str(len(payload)).encode())]
                await send(start);start=None;await send({'type':'http.response.body','body':payload});return
            await send(message)
        await self.app(inner,receive,outward)

    @staticmethod
    async def reject(send,status):
        body=b'{"code":"SPACE_INGRESS_DENIED"}'
        await send({'type':'http.response.start','status':status,'headers':[(b'content-type',b'application/json'),(b'content-length',str(len(body)).encode())]})
        await send({'type':'http.response.body','body':body})