-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathhaproxy_agent.py
More file actions
1719 lines (1518 loc) · 76.1 KB
/
haproxy_agent.py
File metadata and controls
1719 lines (1518 loc) · 76.1 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""An agent for HaProxy that takes care of most of the authentication logic of AppAPI. Python 3.12 required."""
# SPDX-FileCopyrightText: 2025 Nextcloud GmbH and Nextcloud contributors
# SPDX-License-Identifier: AGPL-3.0-or-later
import asyncio
import contextlib
import io
import ipaddress
import json
import logging
import os
import re
import socket
import tarfile
import time
from base64 import b64encode
from enum import IntEnum
from ipaddress import IPv4Address, IPv6Address, ip_address
from typing import Any, Literal, Self
import aiohttp
from aiohttp import web
from haproxyspoa.payloads.ack import AckPayload
from haproxyspoa.spoa_server import SpoaServer
from pydantic import BaseModel, Field, ValidationError, computed_field, model_validator
APPID_PATTERN = re.compile(r"(?:^|/)exapps/([^/]+)")
SHARED_KEY = os.environ.get("HP_SHARED_KEY")
NC_INSTANCE_URL = os.environ.get("NC_INSTANCE_URL")
SPOA_ADDRESS = os.environ.get("HP_SPOA_ADDRESS", "127.0.0.1:9600")
SPOA_HOST, SPOA_PORT = SPOA_ADDRESS.rsplit(":", 1)
SPOA_PORT = int(SPOA_PORT)
# Set up the logging configuration
LOG_LEVEL = os.environ["HP_LOG_LEVEL"].upper()
logging.basicConfig(level=LOG_LEVEL)
LOGGER = logging.getLogger(__name__)
LOGGER.setLevel(level=LOG_LEVEL)
logging.getLogger("haproxyspoa").setLevel(level=LOG_LEVEL)
logging.getLogger("aiohttp").setLevel(level=LOG_LEVEL)
NC_REQ_URL = NC_INSTANCE_URL.removesuffix("/").removesuffix("/index.php")
EX_APP_URL = f"{NC_REQ_URL}/index.php/apps/app_api/harp/exapp-meta"
USER_INFO_URL = f"{NC_REQ_URL}/index.php/apps/app_api/harp/user-info"
EXCLUDE_HEADERS_USER_INFO = {"host", "content-length"}
SPOA_AGENT = SpoaServer()
DOCKER_API_HOST = "127.0.0.1"
TRUSTED_PROXIES_STR = os.environ.get("HP_TRUSTED_PROXY_IPS", "")
TRUSTED_PROXIES = []
if TRUSTED_PROXIES_STR:
try:
TRUSTED_PROXIES = [
ipaddress.ip_network(proxy.strip()) for proxy in TRUSTED_PROXIES_STR.split(",") if proxy.strip()
]
LOGGER.info("Trusting reverse proxies for client IP detection: %s", [str(p) for p in TRUSTED_PROXIES])
except ValueError as e:
LOGGER.error(
"Invalid value for HP_TRUSTED_PROXY_IPS: %s. Client IP detection from headers is disabled. "
"The X-Forwarded-For and X-Real-IP headers will not be respected. "
"This can lead to the outer proxy's IP being blocked during a bruteforce attempt instead of the actual client's IP.",
e,
)
TRUSTED_PROXIES = []
###############################################################################
# Definitions
###############################################################################
class AccessLevel(IntEnum):
PUBLIC = 0
USER = 1
ADMIN = 2
class ExAppRoute(BaseModel):
url: str = Field(..., description="REGEX for URL, e.g. r'^/private/.*'")
access_level: AccessLevel = Field(..., description="ADMIN(2), USER(1), or PUBLIC(0)")
bruteforce_protection: list[int] = Field(
[], description="List with HTTP statuses to trigger the bruteforce protection."
)
str_bruteforce_protection: str = Field(
"", description="Private field, that will be automatically initialized from the 'bruteforce_protection' value."
)
@model_validator(mode="after")
def encode_bruteforce_protection_values(self) -> Self:
self.str_bruteforce_protection = json.dumps(self.bruteforce_protection) if self.bruteforce_protection else ""
return self
class ExApp(BaseModel):
exapp_token: str = Field(...)
exapp_version: str = Field(...)
host: str = Field(...)
port: int = Field(...)
routes: list[ExAppRoute] = Field([])
resolved_host: str = Field("", description="Contains resolved host field to the IP address.")
class NcUser(BaseModel):
user_id: str = Field("", description="The Nextcloud user ID if not an anonymous user.")
access_level: AccessLevel = Field(..., description="ADMIN(2), USER(1), or PUBLIC(0)")
class ExAppName(BaseModel):
name: str = Field(..., description="ExApp name.")
instance_id: str = Field("", description="Nextcloud instance ID.")
@computed_field
@property
def exapp_container_name(self) -> str:
return f"nc_app_{self.instance_id}_{self.name}" if self.instance_id else f"nc_app_{self.name}"
@computed_field
@property
def exapp_container_volume(self) -> str:
return f"{self.exapp_container_name}_data"
class CreateExAppMounts(BaseModel):
source: str = Field(...)
target: str = Field(...)
mode: str = Field("rw")
class CreateExAppPayload(ExAppName):
image_id: str = Field(..., description="Docker image ID.")
network_mode: str = Field(..., description="Desired NetworkMode for the container.")
environment_variables: list[str] = Field([], description="ExApp environment variables.")
restart_policy: str = Field("unless-stopped", description="Desired RestartPolicy for the container.")
compute_device: Literal["cpu", "rocm", "cuda"] = Field(
"cpu", description="Possible values: 'cpu', 'rocm' or 'cuda'"
)
mount_points: list[CreateExAppMounts] = Field([], description="List of mount points for the container.")
resource_limits: dict[str, Any] = Field({}, description="Resource limits for the container.")
class RemoveExAppPayload(ExAppName):
remove_data: bool = Field(False, description="Flag indicating whether the Docker ExApp volume should be deleted.")
class InstallCertificatesPayload(ExAppName):
system_certs_bundle: str | None = Field(None, description="Content of the system CA bundle (concatenated PEMs).")
install_frp_certs: bool = Field(True, description="Flag to control installation of FRP certificates.")
###############################################################################
# In-memory caches
###############################################################################
EXAPP_CACHE_LOCK = asyncio.Lock()
EXAPP_CACHE: dict[str, ExApp] = {}
SESSION_CACHE_LOCK = asyncio.Lock()
SESSION_CACHE: dict[str, tuple[NcUser, float]] = {} # Stores NcUser and timestamp
SESSION_REQUEST_WINDOW = float(os.environ.get("HP_SESSION_LIFETIME", "3")) # Keep session information for 3 seconds
if SESSION_REQUEST_WINDOW < 0:
raise ValueError("`HP_SESSION_LIFETIME` cannot be less than 0")
if SESSION_REQUEST_WINDOW > 10:
raise ValueError("`HP_SESSION_LIFETIME` cannot be greater than 10")
BLACKLIST_CACHE_LOCK = asyncio.Lock()
BLACKLIST_CACHE: dict[str, list[float]] = {} # ip_str -> list of timestamps of failures
# 5 minutes in seconds
BLACKLIST_REQUEST_WINDOW = int(os.getenv("HP_BLACKLIST_WINDOW", "300"))
# 10 invalid attempts during BLACKLIST_REQUEST_WINDOW
BLACKLIST_MAX_FAILS_COUNT = int(os.getenv("HP_BLACKLIST_COUNT", "10"))
###############################################################################
# BLACKLIST CACHE functions
###############################################################################
def get_true_client_ip(
direct_ip: ipaddress.IPv4Address | ipaddress.IPv6Address, headers: dict[str, str]
) -> ipaddress.IPv4Address | ipaddress.IPv6Address:
"""Determine the true client IP by inspecting headers from trusted proxies."""
if not TRUSTED_PROXIES:
return direct_ip
is_trusted = any(direct_ip in network for network in TRUSTED_PROXIES)
if not is_trusted:
return direct_ip
# The request is from a trusted proxy, so we can check the headers.
# X-Forwarded-For can be a list: client, proxy1, proxy2. We want the first one.
x_forwarded_for = headers.get("x-forwarded-for")
if x_forwarded_for:
true_ip_str = x_forwarded_for.split(",")[0].strip()
try:
return ipaddress.ip_address(true_ip_str)
except ValueError:
LOGGER.warning("Could not parse IP from X-Forwarded-For header: %s", true_ip_str)
x_real_ip = headers.get("x-real-ip")
if x_real_ip:
try:
return ipaddress.ip_address(x_real_ip)
except ValueError:
LOGGER.warning("Could not parse IP from X-Real-IP header: %s", x_real_ip)
return direct_ip # If headers are present but invalid, fall back to the direct IP of the proxy
async def record_ip_failure(ip_address: str | IPv4Address | IPv6Address) -> None:
"""Record a failed request attempt for this IP using BLACKLIST_CACHE."""
ip_str = str(ip_address)
now = time.time()
async with BLACKLIST_CACHE_LOCK:
attempts = BLACKLIST_CACHE.get(ip_str, [])
# Purge attempts that are older than the allowed window.
attempts = [ts for ts in attempts if now - ts < BLACKLIST_REQUEST_WINDOW]
attempts.append(now)
BLACKLIST_CACHE[ip_str] = attempts
LOGGER.warning("Recorded failure for IP %s. Failures in window: %d", ip_str, len(attempts))
async def is_ip_banned(ip_address: str | IPv4Address | IPv6Address) -> bool:
"""Return True if IP has exceeded the maximum allowed failures in the request window."""
ip_str = str(ip_address)
now = time.time()
async with BLACKLIST_CACHE_LOCK:
attempts = BLACKLIST_CACHE.get(ip_str, [])
# Purge expired attempts.
attempts = [ts for ts in attempts if now - ts < BLACKLIST_REQUEST_WINDOW]
BLACKLIST_CACHE[ip_str] = attempts
if len(attempts) >= BLACKLIST_MAX_FAILS_COUNT:
return True
return False
###############################################################################
# SESSION CACHE functions
###############################################################################
async def record_session(pass_cookie: str, nc_user: NcUser) -> None:
now = time.time()
async with SESSION_CACHE_LOCK:
SESSION_CACHE[pass_cookie] = (nc_user, now)
LOGGER.error("Recorded session for cookie %s, User %s", pass_cookie, nc_user.user_id)
async def get_session(pass_cookie: str) -> NcUser | None:
"""Retrieve the session for the given IP address."""
now = time.time()
async with SESSION_CACHE_LOCK:
session_data = SESSION_CACHE.get(pass_cookie)
if session_data:
nc_user, timestamp = session_data
# Check if the session is still valid based on the SESSION_REQUEST_WINDOW
if now - timestamp <= SESSION_REQUEST_WINDOW:
return nc_user
# Session expired, remove it
del SESSION_CACHE[pass_cookie]
LOGGER.error("Session for cookie %s expired", pass_cookie)
return None
###############################################################################
# SPOA Handlers
###############################################################################
@SPOA_AGENT.handler("exapps_msg")
async def exapps_msg(
path: str, headers: str, client_ip: ipaddress.IPv4Address | ipaddress.IPv6Address, pass_cookie: str
) -> AckPayload:
reply = AckPayload()
request_headers = parse_headers(headers)
client_ip_str = str(get_true_client_ip(client_ip, request_headers))
reply = reply.set_txn_var("true_client_ip", client_ip_str)
LOGGER.debug("Incoming request to ExApp: path=%s, headers=%s, ip=%s", path, headers, client_ip_str)
# Check if the IP is banned based on failed attempts in BLACKLIST_CACHE.
if await is_ip_banned(client_ip_str):
LOGGER.warning("IP %s is banned due to excessive failed attempts.", client_ip_str)
return reply.set_txn_var("bad_request", 1)
match = APPID_PATTERN.search(path)
if not match:
LOGGER.error("Invalid request path, cannot find AppID: %s", path)
await record_ip_failure(client_ip_str)
return reply.set_txn_var("not_found", 1)
exapp_id = match.group(1)
exapp_id_lower = exapp_id.lower()
target_path = path.removeprefix(f"/exapps/{exapp_id}")
reply = reply.set_txn_var("target_path", target_path)
# Special handling for AppAPI requests
if exapp_id == "app_api":
return await handle_app_api_request(target_path, request_headers, client_ip_str, reply)
exapp_route_bruteforce_protection = None
authorization_app_api = ""
exapp_record = None
if all(
key in request_headers
for key in [
"ex-app-version",
"ex-app-id",
"ex-app-host",
"ex-app-port",
"authorization-app-api",
"harp-shared-key",
]
):
# This is a direct request from AppAPI to ExApp using AppAPI PHP functions "requestToExAppXXX"
if request_headers["harp-shared-key"] != SHARED_KEY:
await record_ip_failure(client_ip)
return reply.set_txn_var("bad_request", 1)
exapp_record = ExApp(
exapp_token="",
exapp_version=request_headers["ex-app-version"],
host=request_headers["ex-app-host"],
port=int(request_headers["ex-app-port"]),
)
authorization_app_api = request_headers["authorization-app-api"]
if not exapp_record:
async with EXAPP_CACHE_LOCK:
exapp_record = EXAPP_CACHE.get(exapp_id_lower)
if not exapp_record:
try:
exapp_record = await nc_get_exapp(exapp_id_lower)
if not exapp_record:
LOGGER.error("No such ExApp enabled: %s", exapp_id)
await record_ip_failure(client_ip_str)
return reply.set_txn_var("not_found", 1)
LOGGER.info("Received new ExApp record: %s", exapp_record)
EXAPP_CACHE[exapp_id_lower] = exapp_record
except ValidationError as e:
LOGGER.error("Invalid ExApp metadata from Nextcloud: %s", e)
return reply.set_txn_var("not_found", 1)
except Exception as e:
LOGGER.exception("Failed to fetch ExApp metadata from Nextcloud", exc_info=e)
return reply.set_txn_var("not_found", 1)
route_allowed = False
if authorization_app_api:
route_allowed = True # We skip routes checking for AppAPI signed requests
elif target_path in ("/heartbeat", "/init", "/enabled"):
LOGGER.error("Only requests from AppAPI allowed to the internal endpoints.")
await record_ip_failure(client_ip_str)
return reply.set_txn_var("bad_request", 1)
else:
nc_user = None
if pass_cookie or "authorization" in request_headers:
# We also pass requests with "authorization" to the Nextcloud to support App Passwords and Basic Auth.
nc_user = await get_session(pass_cookie)
if not nc_user:
try:
nc_user = await nc_get_user(exapp_id_lower, request_headers)
if nc_user and pass_cookie:
await record_session(pass_cookie, nc_user)
except ValidationError as e:
LOGGER.error("Invalid user info from Nextcloud: %s", e)
return reply.set_txn_var("unauthorized", 1)
except Exception as e:
LOGGER.exception("Failed to fetch user info from Nextcloud", exc_info=e)
return reply.set_txn_var("unauthorized", 1)
for route in exapp_record.routes:
try:
if re.match(route.url, target_path):
if route.access_level == AccessLevel.PUBLIC:
exapp_route_bruteforce_protection = route.str_bruteforce_protection
route_allowed = True
break
if nc_user and route.access_level <= nc_user.access_level:
exapp_route_bruteforce_protection = route.str_bruteforce_protection
route_allowed = True
break
LOGGER.error("Access denied for '%s' to %s", nc_user.user_id if nc_user else "", target_path)
await record_ip_failure(client_ip_str)
return reply.set_txn_var("forbidden", 1)
except re.error as err:
LOGGER.error("Invalid regex %s in route for exapp %s: %s", route.url, exapp_id, err)
if not route_allowed:
LOGGER.error("No defined route for handling %s", target_path)
await record_ip_failure(client_ip_str)
return reply.set_txn_var("not_found", 1)
if not authorization_app_api:
user_id = nc_user.user_id if nc_user else ""
authorization_app_api = b64encode(f"{user_id}:{exapp_record.exapp_token}".encode(errors="ignore"))
if exapp_route_bruteforce_protection:
reply = reply.set_txn_var("statuses_to_trigger_bp", exapp_route_bruteforce_protection)
reply = reply.set_txn_var("backend", "ex_apps_backend_w_bruteforce")
else:
reply = reply.set_txn_var("backend", "ex_apps_backend")
if not exapp_record.resolved_host:
try:
ip_address(exapp_record.host)
exapp_record.resolved_host = exapp_record.host
except ValueError:
exapp_record.resolved_host = resolve_ip(exapp_record.host)
if not exapp_record.resolved_host:
LOGGER.error("Cannot resolve '%s' to IP address.", exapp_record.host)
return reply.set_txn_var("not_found", 1)
LOGGER.info("Rerouting request to %s:%s with path=%s", exapp_record.resolved_host, exapp_record.port, target_path)
reply = reply.set_txn_var("target_ip", exapp_record.resolved_host)
reply = reply.set_txn_var("target_port", exapp_record.port)
reply = reply.set_txn_var("exapp_token", authorization_app_api)
reply = reply.set_txn_var("exapp_version", exapp_record.exapp_version)
return reply.set_txn_var("exapp_id", exapp_id)
@SPOA_AGENT.handler("exapps_response_status_msg")
async def exapps_response_status_msg(status: int, client_ip: str, statuses_to_trigger_bp: str) -> AckPayload:
reply = AckPayload()
if not statuses_to_trigger_bp:
return reply.set_txn_var("bp_triggered", 0)
statuses = json.loads(statuses_to_trigger_bp)
if status not in statuses:
return reply.set_txn_var("bp_triggered", 0)
LOGGER.warning("Bruteforce protection(status=%s) triggered IP=%s.", status, client_ip)
await record_ip_failure(client_ip)
return reply.set_txn_var("bp_triggered", 1)
###############################################################################
# Helper functions
###############################################################################
async def handle_app_api_request(
target_path: str,
request_headers: dict[str, str],
str_client_ip: str,
reply: AckPayload,
) -> AckPayload:
"""Handle the special case where the ExApp ID is 'app_api'."""
LOGGER.debug("Request from AppAPI received: %s", target_path)
if request_headers.get("harp-shared-key") != SHARED_KEY:
await record_ip_failure(str_client_ip)
return reply.set_txn_var("unauthorized", 1)
docker_engine_port = request_headers.get("docker-engine-port")
if docker_engine_port and not target_path.startswith("/docker/"):
reply = reply.set_txn_var("target_port", int(docker_engine_port))
return reply.set_txn_var("backend", "docker_engine_backend")
return reply.set_txn_var("backend", "nextcloud_control_backend")
def parse_headers(headers_str: str) -> dict[str, str]:
"""Parse a string containing HTTP headers into a dictionary.
Each header should be on its own line in the format "Header-Name: value".
The header names are normalized to lowercase.
"""
headers = {}
for line in headers_str.splitlines():
line = line.strip()
if not line:
continue
if ":" not in line:
LOGGER.info("Malformed line in header: %s", line)
continue
key, value = line.split(":", 1)
headers[key.strip().lower()] = value.strip()
return headers
async def nc_get_exapp(app_id: str) -> ExApp | None:
async with aiohttp.ClientSession() as session, session.get(
EX_APP_URL, headers={"harp-shared-key": SHARED_KEY}, params={"appId": app_id}
) as resp:
if not resp.ok:
if resp.status == 404:
return None
raise Exception("Failed to fetch ExApp metadata from Nextcloud.", await resp.text())
data = await resp.json()
return ExApp.model_validate(data)
async def nc_get_user(app_id: str, all_headers: dict[str, str]) -> NcUser | None:
ext_headers = {k: v for k, v in all_headers.items() if k.lower() not in EXCLUDE_HEADERS_USER_INFO}
LOGGER.debug("all_headers = %s\next_headers = %s", str(all_headers), str(ext_headers))
async with aiohttp.ClientSession() as session, session.get(
USER_INFO_URL,
headers={**ext_headers, "harp-shared-key": SHARED_KEY},
params={"appId": app_id},
) as resp:
if not resp.ok:
LOGGER.info("Failed to fetch ExApp metadata from Nextcloud.", await resp.text())
if resp.status // 100 == 4:
return None
raise Exception("Failed to fetch ExApp metadata from Nextcloud.", await resp.text())
data = await resp.json()
return NcUser.model_validate(data)
def resolve_ip(hostname: str) -> str:
with contextlib.suppress(socket.gaierror):
addr_info = socket.getaddrinfo(hostname, None)
for family, _, _, _, sockaddr in addr_info:
if family == socket.AF_INET: # IPv4
return sockaddr[0]
# If no IPv4, return first IPv6
for family, _, _, _, sockaddr in addr_info:
if family == socket.AF_INET6: # IPv6
return sockaddr[0]
return ""
###############################################################################
# Misc routes
###############################################################################
async def get_info(request: web.Request):
return web.json_response({"version": 0.3})
###############################################################################
# ExApp routes
###############################################################################
async def add_exapp(request: web.Request):
data = await request.json()
# Overwrite if already exists
async with EXAPP_CACHE_LOCK:
try:
EXAPP_CACHE[request.match_info["app_id"].lower()] = ExApp.model_validate(data)
except ValidationError:
raise web.HTTPBadRequest() from None
return web.HTTPNoContent()
async def delete_exapp(request: web.Request):
async with EXAPP_CACHE_LOCK:
old = EXAPP_CACHE.pop(request.match_info["app_id"].lower(), None)
if old is None:
raise web.HTTPNotFound()
return web.HTTPNoContent()
###############################################################################
# FRP Plugin Authentication
###############################################################################
async def frp_auth(request: web.Request):
if request.method != "POST":
raise web.HTTPBadRequest()
try:
json_data = await request.json()
client_ip = str(json_data["content"]["client_address"]).split(":")[0]
except Exception:
raise web.HTTPBadRequest() from None
if await is_ip_banned(client_ip):
return web.json_response({"reject": True, "reject_reason": "banned"})
auth_token = json_data["content"]["metas"].get("token", "")
if auth_token == SHARED_KEY:
return web.json_response({"reject": False, "unchange": True})
await record_ip_failure(client_ip)
raise web.HTTPBadRequest()
###############################################################################
# Endpoints for AppAPI to work with the Docker API
###############################################################################
def get_docker_engine_port(request: web.Request) -> int:
docker_engine_port_str = request.headers.get("docker-engine-port")
if not docker_engine_port_str:
LOGGER.error("Missing 'docker-engine-port' header.")
raise web.HTTPBadRequest(text="Missing 'docker-engine-port' header.")
try:
docker_engine_port = int(docker_engine_port_str)
if not (0 < docker_engine_port < 65536):
raise ValueError("Port out of valid range") from None
return docker_engine_port
except ValueError:
LOGGER.error("Invalid 'docker-engine-port' header value: %s", docker_engine_port_str)
raise web.HTTPBadRequest(text=f"Invalid 'docker-engine-port' header value: {docker_engine_port_str}") from None
async def docker_exapp_exists(request: web.Request):
docker_engine_port = get_docker_engine_port(request)
try:
payload_dict = await request.json()
except json.JSONDecodeError:
raise web.HTTPBadRequest(text="Invalid JSON body") from None
try:
payload = ExAppName.model_validate(payload_dict)
except ValidationError as e:
raise web.HTTPBadRequest(text=f"Payload validation error: {e}") from None
container_name = payload.exapp_container_name
docker_api_url = f"http://{DOCKER_API_HOST}:{docker_engine_port}/containers/{container_name}/json"
LOGGER.debug("Checking for container '%s' via Docker API at %s", container_name, docker_api_url)
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=15.0)) as session:
try:
async with session.get(docker_api_url) as resp:
if resp.status == 200:
LOGGER.info("Container '%s' exists.", container_name)
return web.json_response({"exists": True})
if resp.status == 404:
LOGGER.info("Container '%s' does not exist.", container_name)
return web.json_response({"exists": False})
error_text = await resp.text()
LOGGER.error(
"Error checking container '%s' with Docker API (status %s): %s",
container_name,
resp.status,
error_text,
)
raise web.HTTPServiceUnavailable(text=f"Error communicating with Docker Engine: Status {resp.status}")
except aiohttp.ClientConnectorError as e:
LOGGER.error("Could not connect to Docker Engine at %s:%s: %s", DOCKER_API_HOST, docker_engine_port, e)
raise web.HTTPServiceUnavailable(
text=f"Could not connect to Docker Engine on port {docker_engine_port}"
) from e
except TimeoutError as e:
LOGGER.error(
"Timeout while trying to communicate with Docker Engine at %s:%s for container '%s'",
DOCKER_API_HOST,
docker_engine_port,
container_name,
)
raise web.HTTPGatewayTimeout(
text=f"Timeout communicating with Docker Engine on port {docker_engine_port}"
) from e
except Exception as e:
LOGGER.exception("Unexpected error while checking container '%s' existence via Docker API.", container_name)
raise web.HTTPInternalServerError(
text="An unexpected error occurred while checking container status."
) from e
async def docker_exapp_create(request: web.Request):
docker_engine_port = get_docker_engine_port(request)
try:
payload_dict = await request.json()
except json.JSONDecodeError:
LOGGER.warning("Invalid JSON body received for /docker/exapp/create")
raise web.HTTPBadRequest(text="Invalid JSON body") from None
try:
payload = CreateExAppPayload.model_validate(payload_dict)
except ValidationError as e:
LOGGER.warning("Payload validation error for /docker/exapp/create: %s", e)
raise web.HTTPBadRequest(text=f"Payload validation error: {e}") from None
container_name = payload.exapp_container_name
volume_name = payload.exapp_container_volume
image_id = payload.image_id
container_config = {
"Image": image_id,
"Hostname": payload.name,
"HostConfig": {
"NetworkMode": payload.network_mode,
"Mounts": [
{
"Type": "volume",
"Source": volume_name,
"Target": f"/{volume_name}",
"ReadOnly": False,
}
],
"RestartPolicy": {
"Name": payload.restart_policy,
},
},
"Env": payload.environment_variables,
}
if payload.network_mode not in ("host", "bridge"):
container_config["NetworkingConfig"] = {"EndpointsConfig": {payload.network_mode: {"Aliases": [payload.name]}}}
if payload.compute_device == "cuda":
container_config["HostConfig"]["DeviceRequests"] = [
{
"Driver": "nvidia",
"Count": -1,
"Capabilities": [["compute", "utility"]],
}
]
elif payload.compute_device == "rocm":
devices = []
for device in ("/dev/kfd", "/dev/dri"):
devices.append({"PathOnHost": device, "PathInContainer": device, "CgroupPermissions": "rwm"})
container_config["HostConfig"]["Devices"] = devices
if payload.resource_limits:
if "memory" in payload.resource_limits:
container_config["HostConfig"]["Memory"] = payload.resource_limits["memory"]
if "nanoCPUs" in payload.resource_limits:
container_config["HostConfig"]["NanoCPUs"] = payload.resource_limits["nanoCPUs"]
for extra_mount in payload.mount_points:
container_config["HostConfig"]["Mounts"].append(
{
"Source": extra_mount.source,
"Target": extra_mount.target,
"Type": "bind",
"Readonly": extra_mount.mode == "ro",
}
)
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=60.0)) as session:
create_volume_url = f"http://{DOCKER_API_HOST}:{docker_engine_port}/volumes/create"
inspect_volume_url = f"http://{DOCKER_API_HOST}:{docker_engine_port}/volumes/{volume_name}"
LOGGER.debug("Checking/Creating volume '%s' via Docker API", volume_name)
try:
async with session.get(inspect_volume_url) as resp_inspect:
if resp_inspect.status == 200:
LOGGER.info("Volume '%s' already exists.", volume_name)
elif resp_inspect.status == 404:
LOGGER.info("Volume '%s' not found, attempting to create.", volume_name)
async with session.post(create_volume_url, json={"Name": volume_name}) as resp_create:
if resp_create.status == 201:
LOGGER.info("Volume '%s' created successfully.", volume_name)
else:
error_text = await resp_create.text()
LOGGER.error(
"Failed to create volume '%s' (status %s): %s",
volume_name,
resp_create.status,
error_text,
)
raise web.HTTPServiceUnavailable(
text=f"Failed to create volume '{volume_name}': Status {resp_create.status}"
)
else:
error_text = await resp_inspect.text()
LOGGER.error(
"Error inspecting volume '%s' (status %s): %s", volume_name, resp_inspect.status, error_text
)
raise web.HTTPServiceUnavailable(
text=f"Error inspecting volume '{volume_name}': Status {resp_inspect.status}"
)
except aiohttp.ClientConnectorError as e:
LOGGER.error("Could not connect to Docker Engine for volume operation: %s", e)
raise web.HTTPServiceUnavailable(
text=f"Could not connect to Docker Engine on port {docker_engine_port}"
) from e
except TimeoutError as e:
LOGGER.error("Timeout during volume operation for '%s'", volume_name)
raise web.HTTPGatewayTimeout(text="Timeout communicating with Docker Engine for volume operation") from e
except web.HTTPServiceUnavailable:
raise
except Exception as e:
LOGGER.exception("Unexpected error during volume management for '%s'", volume_name)
raise web.HTTPInternalServerError(text="Unexpected error during volume management.") from e
create_container_url = f"http://{DOCKER_API_HOST}:{docker_engine_port}/containers/create?name={container_name}"
LOGGER.debug(
"Attempting to create container '%s' with image '%s' via Docker API at %s",
container_name,
image_id,
create_container_url,
)
try:
async with session.post(create_container_url, json=container_config) as resp:
if resp.status == 201:
container_data = await resp.json()
container_id = container_data.get("Id")
LOGGER.info("Container '%s' (ID: %s) created successfully.", container_name, container_id)
return web.json_response({"id": container_id, "name": container_name}, status=201)
if resp.status == 409:
error_text = await resp.text()
LOGGER.warning("Container '%s' already exists (status 409): %s.", container_name, error_text)
raise web.HTTPConflict(text=f"Container with name '{container_name}' already exists.")
error_text = await resp.text()
LOGGER.error(
"Error creating container '%s' with Docker API (status %s): %s",
container_name,
resp.status,
error_text,
)
raise web.HTTPServiceUnavailable(
text=f"Error creating container '{container_name}': Status {resp.status}"
)
except aiohttp.ClientConnectorError as e:
LOGGER.error("Could not connect to Docker Engine for container creation: %s", e)
raise web.HTTPServiceUnavailable(
text=f"Could not connect to Docker Engine on port {docker_engine_port}"
) from e
except TimeoutError as e:
LOGGER.error("Timeout during container creation for '%s'", container_name)
raise web.HTTPGatewayTimeout(text="Timeout communicating with Docker Engine for container creation") from e
except (web.HTTPServiceUnavailable, web.HTTPConflict, web.HTTPInternalServerError):
raise
except Exception as e:
LOGGER.exception("Unexpected error during container creation for '%s'", container_name)
raise web.HTTPInternalServerError(text="An unexpected error occurred during container creation.") from e
async def docker_exapp_start(request: web.Request):
docker_engine_port = get_docker_engine_port(request)
try:
payload_dict = await request.json()
except json.JSONDecodeError:
LOGGER.warning("Invalid JSON body received for /docker/exapp/start")
raise web.HTTPBadRequest(text="Invalid JSON body") from None
try:
payload = ExAppName.model_validate(payload_dict)
except ValidationError as e:
LOGGER.warning("Payload validation error for /docker/exapp/start: %s", e)
raise web.HTTPBadRequest(text=f"Payload validation error: {e}") from None
container_name = payload.exapp_container_name
start_container_url = f"http://{DOCKER_API_HOST}:{docker_engine_port}/containers/{container_name}/start"
LOGGER.info("Attempting to start container '%s' via Docker API at %s", container_name, start_container_url)
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=30.0)) as session:
try:
async with session.post(start_container_url) as resp:
if resp.status == 204:
LOGGER.info("Container '%s' started successfully.", container_name)
return web.HTTPNoContent()
if resp.status == 304:
LOGGER.info("Container '%s' was already started.", container_name)
return web.HTTPOk(text="Container already started")
if resp.status == 404:
LOGGER.warning("Container '%s' not found, cannot start.", container_name)
raise web.HTTPNotFound(text=f"Container '{container_name}' not found.")
error_text = await resp.text()
LOGGER.error(
"Error starting container '%s' with Docker API (status %s): %s",
container_name,
resp.status,
error_text,
)
raise web.HTTPServiceUnavailable(
text=f"Error starting container '{container_name}' via Docker Engine: Status {resp.status}"
)
except aiohttp.ClientConnectorError as e:
LOGGER.error(
"Could not connect to Docker Engine at %s:%s to start container: %s",
DOCKER_API_HOST,
docker_engine_port,
e,
)
raise web.HTTPServiceUnavailable(
text=f"Could not connect to Docker Engine on port {docker_engine_port}"
) from e
except TimeoutError as e:
LOGGER.error(
"Timeout while trying to start container '%s' via Docker Engine at %s:%s",
DOCKER_API_HOST,
container_name,
docker_engine_port,
)
raise web.HTTPGatewayTimeout(text="Timeout communicating with Docker Engine for container start") from e
except (web.HTTPNotFound, web.HTTPServiceUnavailable):
raise
except Exception as e:
LOGGER.exception("Unexpected error while starting container '%s' via Docker API.", container_name)
raise web.HTTPInternalServerError(text="An unexpected error occurred during container start.") from e
async def docker_exapp_stop(request: web.Request):
docker_engine_port = get_docker_engine_port(request)
try:
payload_dict = await request.json()
except json.JSONDecodeError:
LOGGER.warning("Invalid JSON body received for /docker/exapp/stop")
raise web.HTTPBadRequest(text="Invalid JSON body") from None
try:
payload = ExAppName.model_validate(payload_dict)
except ValidationError as e:
LOGGER.warning("Payload validation error for /docker/exapp/stop: %s", e)
raise web.HTTPBadRequest(text=f"Payload validation error: {e}") from None
container_name = payload.exapp_container_name
stop_container_url = f"http://{DOCKER_API_HOST}:{docker_engine_port}/containers/{container_name}/stop"
LOGGER.info("Attempting to stop container '%s' via Docker API at %s", container_name, stop_container_url)
async with aiohttp.ClientSession(timeout=aiohttp.ClientTimeout(total=30.0)) as session:
try:
async with session.post(stop_container_url) as resp:
if resp.status == 204:
LOGGER.info("Container '%s' stopped successfully.", container_name)
return web.HTTPNoContent()
if resp.status == 304:
LOGGER.info("Container '%s' was already stopped.", container_name)
return web.HTTPOk(text="Container already stopped")
if resp.status == 404:
LOGGER.warning("Container '%s' not found, cannot stop.", container_name)
raise web.HTTPNotFound(text=f"Container '{container_name}' not found.")
error_text = await resp.text()
LOGGER.error(
"Error stopping container '%s' with Docker API (status %s): %s",
container_name,
resp.status,
error_text,
)
raise web.HTTPServiceUnavailable(
text=f"Error stopping container '{container_name}' via Docker Engine: Status {resp.status}"
)
except aiohttp.ClientConnectorError as e:
LOGGER.error(
"Could not connect to Docker Engine at %s:%s to stop container: %s",
DOCKER_API_HOST,
docker_engine_port,
e,
)
raise web.HTTPServiceUnavailable(
text=f"Could not connect to Docker Engine on port {docker_engine_port}"
) from e
except TimeoutError as e:
LOGGER.error(
"Timeout while trying to stop container '%s' via Docker Engine at %s:%s",
DOCKER_API_HOST,
container_name,
docker_engine_port,
)
raise web.HTTPGatewayTimeout(text="Timeout communicating with Docker Engine for container stop") from e
except (web.HTTPNotFound, web.HTTPServiceUnavailable):
raise
except Exception as e:
LOGGER.exception("Unexpected error while stopping container '%s' via Docker API.", container_name)
raise web.HTTPInternalServerError(text="An unexpected error occurred during container stop.") from e
async def docker_exapp_wait_for_start(request: web.Request):
docker_engine_port = get_docker_engine_port(request)
try:
payload_dict = await request.json()
except json.JSONDecodeError:
LOGGER.warning("Invalid JSON body received for /docker/exapp/wait_for_start")
raise web.HTTPBadRequest(text="Invalid JSON body") from None
try:
payload = ExAppName.model_validate(payload_dict)
except ValidationError as e:
LOGGER.warning("Payload validation error for /docker/exapp/wait_for_start: %s", e)
raise web.HTTPBadRequest(text=f"Payload validation error: {e}") from None
container_name = payload.exapp_container_name
inspect_url = f"http://{DOCKER_API_HOST}:{docker_engine_port}/containers/{container_name}/json"
max_tries = 180
sleep_interval = 0.5
total_wait_time = max_tries * sleep_interval
client_timeout = aiohttp.ClientTimeout(total=total_wait_time + 15.0)
LOGGER.info(
"Waiting for container '%s' to start (max %d tries, interval %.1fs, total wait %.1fs).",
container_name,
max_tries,
sleep_interval,
total_wait_time,
)
last_known_status: str | None = "unknown"
last_known_health: str | None = None
async with aiohttp.ClientSession(timeout=client_timeout) as session:
for attempt in range(max_tries):
try:
async with session.get(inspect_url) as resp:
if resp.status == 200:
container_info = await resp.json()
state = container_info.get("State", {})
current_status = state.get("Status")
current_health = state.get("Health", {}).get("Status")
last_known_status = current_status
last_known_health = current_health
LOGGER.debug(
"Container '%s' attempt %d/%d: Status='%s', Health='%s'",
container_name,
attempt + 1,
max_tries,
current_status,
current_health,
)
if current_status == "running":
if current_health is None or current_health == "healthy":
LOGGER.info(
"Container '%s' is running and healthy (or no healthcheck).", container_name
)
return web.json_response(
{"started": True, "status": current_status, "health": current_health}
)
if current_health == "unhealthy":
LOGGER.warning(
"Container '%s' is running but unhealthy. Reporting as not successfully started.",
container_name,
)
return web.json_response(