feat(core): persist viewer state and integrate Cesium services and profiles
This commit is contained in:
@@ -0,0 +1,291 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Install the operator's loopback HTTPS name using macOS's own Apache.
|
||||
|
||||
Run with administrator authorization. This never restarts or replaces Core.
|
||||
The certificate is a single-host leaf, not a general-purpose signing CA.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import plistlib
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
DOMAIN = "nodedc.missioncore"
|
||||
ORIGIN = "https://" + DOMAIN
|
||||
LABEL = "com.nodedc.mission-core.https"
|
||||
ROOT = pathlib.Path("/Library/Application Support/NODE.DC/MissionCoreHTTPS")
|
||||
LOGS = pathlib.Path("/Library/Logs/NODE.DC/MissionCoreHTTPS")
|
||||
PLIST = pathlib.Path("/Library/LaunchDaemons") / (LABEL + ".plist")
|
||||
HOSTS = pathlib.Path("/private/etc/hosts")
|
||||
HOST_LINE = "127.0.0.1 nodedc.missioncore # NODE.DC Mission Core HTTPS"
|
||||
|
||||
|
||||
def config(root=ROOT, logs=LOGS, https_port=443, http_port=80, upstream_port=8000):
|
||||
"""Ports/paths can be overridden for an isolated transport qualification."""
|
||||
proxy_route = (
|
||||
f"http://127.0.0.1:{upstream_port}/ nocanon "
|
||||
"connectiontimeout=3 timeout=3600 upgrade=websocket"
|
||||
)
|
||||
return f'''ServerRoot "/usr"
|
||||
ServerName {DOMAIN}
|
||||
Listen 127.0.0.1:{http_port}
|
||||
Listen 127.0.0.1:{https_port}
|
||||
LoadModule mpm_event_module libexec/apache2/mod_mpm_event.so
|
||||
LoadModule unixd_module libexec/apache2/mod_unixd.so
|
||||
LoadModule authz_core_module libexec/apache2/mod_authz_core.so
|
||||
LoadModule ssl_module libexec/apache2/mod_ssl.so
|
||||
LoadModule proxy_module libexec/apache2/mod_proxy.so
|
||||
LoadModule proxy_http_module libexec/apache2/mod_proxy_http.so
|
||||
LoadModule headers_module libexec/apache2/mod_headers.so
|
||||
LoadModule rewrite_module libexec/apache2/mod_rewrite.so
|
||||
User _www
|
||||
Group _www
|
||||
PidFile "{root}/httpd.pid"
|
||||
DefaultRuntimeDir "{root}"
|
||||
Mutex "file:{root}" default
|
||||
ErrorLog "|/usr/sbin/rotatelogs -n 2 '{logs}/error.log' 1M"
|
||||
LogLevel warn
|
||||
ServerTokens Prod
|
||||
ServerSignature Off
|
||||
TraceEnable Off
|
||||
StartServers 1
|
||||
ServerLimit 2
|
||||
ThreadLimit 32
|
||||
ThreadsPerChild 32
|
||||
MinSpareThreads 16
|
||||
MaxSpareThreads 32
|
||||
MaxRequestWorkers 64
|
||||
MaxConnectionsPerChild 10000
|
||||
Timeout 600
|
||||
KeepAlive On
|
||||
KeepAliveTimeout 5
|
||||
LimitRequestBody 0
|
||||
AllowEncodedSlashes NoDecode
|
||||
<Directory />
|
||||
Require all denied
|
||||
</Directory>
|
||||
<VirtualHost 127.0.0.1:{http_port}>
|
||||
ServerName {DOMAIN}
|
||||
RewriteEngine On
|
||||
RewriteCond %{{HTTP_HOST}} !^{DOMAIN.replace(".", "[.]")}(:{http_port})?$ [NC]
|
||||
RewriteRule ^ - [F,L]
|
||||
RewriteRule ^/(.*)$ {ORIGIN}/$1 [R=308,NE,L]
|
||||
</VirtualHost>
|
||||
<VirtualHost 127.0.0.1:{https_port}>
|
||||
ServerName {DOMAIN}
|
||||
SSLEngine On
|
||||
SSLProtocol -all +TLSv1.2
|
||||
SSLCipherSuite HIGH:!aNULL:!MD5:!3DES
|
||||
SSLCertificateFile "{root}/server.crt"
|
||||
SSLCertificateKeyFile "{root}/server.key"
|
||||
RewriteEngine On
|
||||
RewriteCond %{{HTTP_HOST}} !^{DOMAIN.replace(".", "[.]")}(:{https_port})?$ [NC]
|
||||
RewriteRule ^ - [F,L]
|
||||
# Validate the public browser origin BEFORE mapping it to Core's origin.
|
||||
RewriteCond %{{HTTP:Origin}} !^$
|
||||
RewriteCond %{{HTTP:Origin}} !^{ORIGIN.replace(".", "[.]")}(:{https_port})?$
|
||||
RewriteRule ^ - [F,L]
|
||||
# External links may navigate to the UI; cross-site API calls remain blocked.
|
||||
RewriteCond %{{HTTP:Sec-Fetch-Site}} ^cross-site$ [NC]
|
||||
RewriteCond %{{HTTP:Sec-Fetch-Mode}} !^navigate$ [NC,OR]
|
||||
RewriteCond %{{REQUEST_URI}} ^/(api|ws)(/|$) [NC]
|
||||
RewriteRule ^ - [F,L]
|
||||
ProxyRequests Off
|
||||
ProxyPreserveHost Off
|
||||
ProxyAddHeaders Off
|
||||
RequestHeader unset Forwarded
|
||||
RequestHeader unset X-Forwarded-For
|
||||
RequestHeader unset X-Forwarded-Host
|
||||
RequestHeader unset X-Forwarded-Proto
|
||||
RequestHeader unset X-Forwarded-Port
|
||||
RequestHeader unset X-Real-IP
|
||||
RequestHeader edit Origin "^{ORIGIN.replace(".", "[.]")}(:{https_port})?$" "http://127.0.0.1:{upstream_port}"
|
||||
ProxyPass / {proxy_route}
|
||||
ProxyPassReverse / http://127.0.0.1:{upstream_port}/
|
||||
<Location />
|
||||
Require all granted
|
||||
</Location>
|
||||
</VirtualHost>
|
||||
'''
|
||||
|
||||
|
||||
def run(*args):
|
||||
result = subprocess.run(args, capture_output=True, text=True)
|
||||
if result.returncode:
|
||||
raise RuntimeError(f"{args[0]}: {result.stderr.strip()}")
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def atomic(path, content, mode=0o600):
|
||||
fd, name = tempfile.mkstemp(dir=path.parent, prefix=".https-")
|
||||
try:
|
||||
with os.fdopen(fd, "wb") as stream:
|
||||
stream.write(content)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.chmod(name, mode)
|
||||
os.replace(name, path)
|
||||
finally:
|
||||
if os.path.exists(name):
|
||||
os.unlink(name)
|
||||
|
||||
|
||||
def create_certificate(root):
|
||||
key, cert = root / "server.key", root / "server.crt"
|
||||
if key.exists() and cert.exists():
|
||||
run("/usr/bin/openssl", "x509", "-in", str(cert), "-checkend", "2592000", "-noout")
|
||||
return
|
||||
if key.exists() or cert.exists():
|
||||
raise RuntimeError("Incomplete HTTPS certificate; inspect before replacing it")
|
||||
spec = root / "certificate.conf"
|
||||
atomic(
|
||||
spec,
|
||||
f"""[req]
|
||||
prompt=no
|
||||
distinguished_name=dn
|
||||
x509_extensions=server
|
||||
[dn]
|
||||
CN={DOMAIN}
|
||||
O=NODE.DC Local Mission Core
|
||||
[server]
|
||||
subjectAltName=DNS:{DOMAIN}
|
||||
basicConstraints=critical,CA:FALSE
|
||||
keyUsage=critical,digitalSignature,keyEncipherment
|
||||
extendedKeyUsage=serverAuth
|
||||
""".encode(),
|
||||
)
|
||||
run(
|
||||
"/usr/bin/openssl",
|
||||
"req",
|
||||
"-new",
|
||||
"-x509",
|
||||
"-newkey",
|
||||
"rsa:2048",
|
||||
"-nodes",
|
||||
"-sha256",
|
||||
"-days",
|
||||
"365",
|
||||
"-config",
|
||||
str(spec),
|
||||
"-keyout",
|
||||
str(key),
|
||||
"-out",
|
||||
str(cert),
|
||||
)
|
||||
os.chmod(key, 0o600)
|
||||
os.chmod(cert, 0o644)
|
||||
spec.unlink()
|
||||
|
||||
|
||||
def install():
|
||||
if sys.platform != "darwin" or os.geteuid() != 0:
|
||||
raise RuntimeError("Use macOS administrator authorization for this installer")
|
||||
op = urllib.request.build_opener(urllib.request.ProxyHandler({}))
|
||||
with op.open("http://127.0.0.1:8000/api/health", timeout=10) as response:
|
||||
health = json.load(response)
|
||||
if health.get("service") != "mission-core-control-plane" or not health.get("ok"):
|
||||
raise RuntimeError("Canonical Mission Core is not healthy")
|
||||
before = HOSTS.read_bytes()
|
||||
for line in before.decode().splitlines():
|
||||
fields = line.split("#", 1)[0].split()
|
||||
if DOMAIN in fields[1:] and fields[0] != "127.0.0.1":
|
||||
raise RuntimeError("The requested name already resolves elsewhere in hosts")
|
||||
existing = (
|
||||
subprocess.run(
|
||||
["/bin/launchctl", "print", "system/" + LABEL], capture_output=True
|
||||
).returncode
|
||||
== 0
|
||||
)
|
||||
if not existing:
|
||||
for port in (80, 443):
|
||||
with socket.socket() as probe:
|
||||
probe.bind(("127.0.0.1", port))
|
||||
for directory in (ROOT, LOGS):
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
os.chmod(directory, 0o755)
|
||||
create_certificate(ROOT)
|
||||
conf = config().encode()
|
||||
conf_path = ROOT / "httpd.conf"
|
||||
if existing and conf_path.read_bytes() != conf:
|
||||
raise RuntimeError("Existing HTTPS configuration differs; review before restarting")
|
||||
atomic(conf_path, conf, 0o644)
|
||||
run("/usr/sbin/httpd", "-t", "-f", str(conf_path))
|
||||
# Trust is configured separately in the operator's login session. macOS
|
||||
# refuses interactive trust authorization from this background root process.
|
||||
# Never install a general signing CA or disable browser certificate checks.
|
||||
if not any(
|
||||
DOMAIN in line.split("#", 1)[0].split()[1:] for line in before.decode().splitlines()
|
||||
):
|
||||
if not (ROOT / "hosts.before").exists():
|
||||
atomic(ROOT / "hosts.before", before)
|
||||
atomic(HOSTS, before.rstrip(b"\n") + b"\n" + HOST_LINE.encode() + b"\n", 0o644)
|
||||
run("/usr/bin/dscacheutil", "-flushcache")
|
||||
declaration = plistlib.dumps(
|
||||
{
|
||||
"Label": LABEL,
|
||||
"ProgramArguments": ["/usr/sbin/httpd", "-f", str(conf_path), "-D", "FOREGROUND"],
|
||||
"RunAtLoad": True,
|
||||
"KeepAlive": True,
|
||||
"ThrottleInterval": 5,
|
||||
"AbandonProcessGroup": False,
|
||||
"ExitTimeOut": 15,
|
||||
}
|
||||
)
|
||||
if PLIST.exists() and PLIST.read_bytes() != declaration:
|
||||
raise RuntimeError("Existing HTTPS launch declaration differs; review it first")
|
||||
atomic(PLIST, declaration, 0o644)
|
||||
if not existing:
|
||||
run("/bin/launchctl", "bootstrap", "system", str(PLIST))
|
||||
for _attempt in range(20):
|
||||
check = subprocess.run(
|
||||
[
|
||||
"/usr/bin/curl",
|
||||
"--noproxy",
|
||||
"*",
|
||||
"--silent",
|
||||
"--show-error",
|
||||
"--fail",
|
||||
"--max-time",
|
||||
"5",
|
||||
"--cacert",
|
||||
str(ROOT / "server.crt"),
|
||||
ORIGIN + "/api/health",
|
||||
],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
if check.returncode == 0 and json.loads(check.stdout).get("ok"):
|
||||
receipt = {
|
||||
"url": ORIGIN,
|
||||
"upstream": "http://127.0.0.1:8000",
|
||||
"config_sha256": hashlib.sha256(conf).hexdigest(),
|
||||
"certificate": run(
|
||||
"/usr/bin/openssl",
|
||||
"x509",
|
||||
"-in",
|
||||
str(ROOT / "server.crt"),
|
||||
"-noout",
|
||||
"-dates",
|
||||
"-fingerprint",
|
||||
"-sha256",
|
||||
),
|
||||
"core_restarted": False,
|
||||
"https_health": "verified_exact_certificate",
|
||||
"browser_trust": "verify_in_operator_login_session",
|
||||
}
|
||||
atomic(ROOT / "receipt.json", (json.dumps(receipt, indent=2) + "\n").encode())
|
||||
print(json.dumps(receipt, indent=2))
|
||||
return
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError("HTTPS health failed: " + check.stderr[-500:])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
install()
|
||||
@@ -0,0 +1,196 @@
|
||||
"""Bounded Apache transport qualification; no production data is modified."""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import http.client
|
||||
import http.server
|
||||
import json
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import signal
|
||||
import socket
|
||||
import ssl
|
||||
import subprocess
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
|
||||
from install import DOMAIN, config, create_certificate
|
||||
|
||||
|
||||
class Echo(http.server.BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
def do_GET(self):
|
||||
if self.headers.get("Upgrade", "").lower() == "websocket":
|
||||
value = self.headers["Sec-WebSocket-Key"] + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
|
||||
self.send_response(101)
|
||||
self.send_header("Upgrade", "websocket")
|
||||
self.send_header("Connection", "Upgrade")
|
||||
self.send_header(
|
||||
"Sec-WebSocket-Accept",
|
||||
base64.b64encode(hashlib.sha1(value.encode()).digest()).decode(),
|
||||
)
|
||||
self.end_headers()
|
||||
self.wfile.write(b"\x81\x02ok")
|
||||
self.wfile.flush()
|
||||
self.close_connection = True
|
||||
return
|
||||
body = json.dumps(dict(self.headers)).encode()
|
||||
self.send_response(206 if self.headers.get("Range") else 200)
|
||||
if self.headers.get("Range"):
|
||||
self.send_header("Content-Range", "bytes 0-1/2")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_POST(self):
|
||||
digest = hashlib.sha256()
|
||||
left = int(self.headers["Content-Length"])
|
||||
while left:
|
||||
chunk = self.rfile.read(min(left, 65536))
|
||||
if not chunk:
|
||||
raise RuntimeError("Truncated stream")
|
||||
digest.update(chunk)
|
||||
left -= len(chunk)
|
||||
body = digest.hexdigest().encode()
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
|
||||
def free_port():
|
||||
with socket.socket() as probe:
|
||||
probe.bind(("127.0.0.1", 0))
|
||||
return probe.getsockname()[1]
|
||||
|
||||
|
||||
def main():
|
||||
# macOS's Apache cannot read an operator's protected Downloads directory.
|
||||
scratch = pathlib.Path(tempfile.mkdtemp(prefix="missioncore-https-transport-"))
|
||||
upstream = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Echo)
|
||||
threading.Thread(target=upstream.serve_forever, daemon=True).start()
|
||||
process = None
|
||||
try:
|
||||
create_certificate(scratch)
|
||||
tls_port, redirect_port = free_port(), free_port()
|
||||
(scratch / "httpd.conf").write_text(
|
||||
config(scratch, scratch, tls_port, redirect_port, upstream.server_port)
|
||||
)
|
||||
subprocess.run(
|
||||
["/usr/sbin/httpd", "-t", "-f", str(scratch / "httpd.conf")],
|
||||
check=True,
|
||||
capture_output=True,
|
||||
)
|
||||
process = subprocess.Popen(
|
||||
["/usr/sbin/httpd", "-f", str(scratch / "httpd.conf"), "-D", "FOREGROUND"],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE,
|
||||
start_new_session=True,
|
||||
)
|
||||
context = ssl.create_default_context(cafile=str(scratch / "server.crt"))
|
||||
context.check_hostname = (
|
||||
False # Test socket uses loopback; trusted test certificate still verified.
|
||||
)
|
||||
|
||||
def call(path="/", method="GET", headers=None, body=None):
|
||||
connection = http.client.HTTPSConnection(
|
||||
"127.0.0.1", tls_port, context=context, timeout=10
|
||||
)
|
||||
connection.request(
|
||||
method, path, body=body, headers={"Host": f"{DOMAIN}:{tls_port}", **(headers or {})}
|
||||
)
|
||||
response = connection.getresponse()
|
||||
result = response.status, dict(response.headers), response.read()
|
||||
connection.close()
|
||||
return result
|
||||
|
||||
for _ in range(50):
|
||||
try:
|
||||
call()
|
||||
break
|
||||
except OSError:
|
||||
if process.poll() is not None:
|
||||
errors = "\n".join(p.read_text() for p in scratch.glob("error.log*"))
|
||||
raise RuntimeError(process.stderr.read().decode() + errors) from None
|
||||
time.sleep(0.1)
|
||||
status, _, body = call(
|
||||
"/api/check",
|
||||
headers={
|
||||
"Origin": f"https://{DOMAIN}:{tls_port}",
|
||||
"Sec-Fetch-Site": "same-origin",
|
||||
"X-Forwarded-For": "8.8.8.8",
|
||||
"X-Forwarded-Proto": "https",
|
||||
},
|
||||
)
|
||||
mapped = {k.lower(): v for k, v in json.loads(body).items()}
|
||||
assert status == 200 and mapped["host"] == f"127.0.0.1:{upstream.server_port}"
|
||||
assert mapped["origin"] == f"http://127.0.0.1:{upstream.server_port}"
|
||||
assert "x-forwarded-for" not in mapped and "x-forwarded-proto" not in mapped
|
||||
assert call(headers={"Host": "evil.example"})[0] == 403
|
||||
assert call(headers={"Origin": "https://evil.example"})[0] == 403
|
||||
assert call(headers={"Origin": "null"})[0] == 403
|
||||
assert (
|
||||
call(
|
||||
"/api/check", headers={"Sec-Fetch-Site": "cross-site", "Sec-Fetch-Mode": "navigate"}
|
||||
)[0]
|
||||
== 403
|
||||
)
|
||||
assert (
|
||||
call("/", headers={"Sec-Fetch-Site": "cross-site", "Sec-Fetch-Mode": "navigate"})[0]
|
||||
== 200
|
||||
)
|
||||
assert call("/api/check", headers={"Range": "bytes=0-1"})[0] == 206
|
||||
payload = b"NODE.DC-stream-test" * 65536
|
||||
assert (
|
||||
call("/upload", "POST", body=payload)[2].decode() == hashlib.sha256(payload).hexdigest()
|
||||
)
|
||||
with (
|
||||
socket.create_connection(("127.0.0.1", tls_port), timeout=5) as tcp,
|
||||
context.wrap_socket(tcp, server_hostname=DOMAIN) as stream,
|
||||
):
|
||||
key = base64.b64encode(os.urandom(16)).decode()
|
||||
stream.sendall(
|
||||
(
|
||||
f"GET /socket HTTP/1.1\r\nHost: {DOMAIN}:{tls_port}\r\n"
|
||||
f"Origin: https://{DOMAIN}:{tls_port}\r\n"
|
||||
"Upgrade: websocket\r\nConnection: Upgrade\r\n"
|
||||
f"Sec-WebSocket-Version: 13\r\nSec-WebSocket-Key: {key}\r\n\r\n"
|
||||
).encode()
|
||||
)
|
||||
data = b""
|
||||
while b"\r\n\r\n" not in data or not data.endswith(b"\x81\x02ok"):
|
||||
part = stream.recv(4096)
|
||||
if not part:
|
||||
break
|
||||
data += part
|
||||
assert b"101 Switching Protocols" in data and data.endswith(b"\x81\x02ok")
|
||||
connection = http.client.HTTPConnection("127.0.0.1", redirect_port, timeout=5)
|
||||
connection.request("GET", "/path?q=1", headers={"Host": f"{DOMAIN}:{redirect_port}"})
|
||||
response = connection.getresponse()
|
||||
assert (
|
||||
response.status == 308
|
||||
and response.headers["Location"] == "https://nodedc.missioncore/path?q=1"
|
||||
)
|
||||
response.read()
|
||||
connection.close()
|
||||
print(
|
||||
"PASS: origin/host boundary, forwarded-header stripping, range, "
|
||||
"upload hash, WebSocket frame, HTTP redirect"
|
||||
)
|
||||
finally:
|
||||
if process is not None and process.poll() is None:
|
||||
os.killpg(process.pid, signal.SIGTERM)
|
||||
process.wait(timeout=10)
|
||||
upstream.shutdown()
|
||||
upstream.server_close()
|
||||
shutil.rmtree(scratch)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user