Skip to content

Agent Zero AI framework

csrf ALLOWED_ORIGINS protection

frdelc18c04d77270
diff --git a/python/api/csrf_token.py b/python/api/csrf_token.py
index bd8615546..37bb8453a 100644
--- a/python/api/csrf_token.py
+++ b/python/api/csrf_token.py
@@ -1,4 +1,5 @@
import secrets
+from urllib.parse import urlparse
from python.helpers.api import (
ApiHandler,
Input,
@@ -7,7 +8,9 @@ from python.helpers.api import (
Response,
session,
)
-from python.helpers import runtime
+from python.helpers import runtime, dotenv, login
+import fnmatch
+
class GetCsrfToken(ApiHandler):
@@ -20,6 +23,90 @@ class GetCsrfToken(ApiHandler):
return False
async def process(self, input: Input, request: Request) -> Output:
+
+ # check for allowed origin to prevent dns rebinding attacks
+ origin_check = await self.check_allowed_origin(request)
+ if not origin_check["ok"]:
+ return {
+ "ok": False,
+ "error": f"Origin {self.get_origin_from_request(request)} not allowed when login is disabled. Set login and password or add your URL to ALLOWED_ORIGINS env variable. Currently allowed origins: {",".join(origin_check['allowed_origins'])}",
+ }
+
+ # generate a csrf token if it doesn't exist
if "csrf_token" not in session:
session["csrf_token"] = secrets.token_urlsafe(32)
- return {"token": session["csrf_token"], "runtime_id": runtime.get_runtime_id()}
+
+ # return the csrf token and runtime id
+ return {
+ "ok": True,
+ "token": session["csrf_token"],
+ "runtime_id": runtime.get_runtime_id(),
+ }
+
+ async def check_allowed_origin(self, request: Request):
+ # if login is required, this che
+ if login.is_login_required():
+ return {"ok": True, "origin": "", "allowed_origins": ""}
+ # otherwise, check if the origin is allowed
+ return await self.is_allowed_origin(request)
+
+ async def is_allowed_origin(self, request: Request):
+ # get the origin from the request
+ origin = self.get_origin_from_request(request)
+ if not origin:
+ return {"ok": False, "origin": "", "allowed_origins": ""}
+
+ # list of allowed origins
+ allowed_origins = await self.get_allowed_origins()
+
+ # check if the origin is allowed
+ match = any(
+ fnmatch.fnmatch(origin, allowed_origin)
+ for allowed_origin in allowed_origins
+ )
+ return {"ok": match, "origin": origin, "allowed_origins": allowed_origins}
+
+ def get_origin_from_request(self, request: Request):
+ # get from origin
+ r = request.headers.get("Origin") or request.environ.get("HTTP_ORIGIN")
+ if not r:
+ # try referer if origin not present
+ r = (
+ request.headers.get("Referer")
+ or request.referrer
+ or request.environ.get("HTTP_REFERER")
+ )
+ if not r:
+ return None
+ # parse and normalize
+ p = urlparse(r)
+ if not p.scheme or not p.hostname:
+ return None
+ return f"{p.scheme}://{p.hostname}" + (f":{p.port}" if p.port else "")
+
+ async def get_allowed_origins(self) -> list[str]:
+ # get the allowed origins from the environment
+ allowed_origins = [
+ origin.strip()
+ for origin in (dotenv.get_dotenv_value("ALLOWED_ORIGINS") or "").split(",")
+ if origin.strip()
+ ]
+
+ # if there are no allowed origins, allow default localhosts
+ if not allowed_origins:
+ allowed_origins = self.get_default_allowed_origins()
+
+ # always allow tunnel url if running
+ try:
+ from python.api.tunnel_proxy import process as tunnel_api_process
+
+ tunnel = await tunnel_api_process({"action": "get"})
+ if tunnel and isinstance(tunnel, dict) and tunnel["success"]:
+ allowed_origins.append(tunnel["tunnel_url"])
+ except Exception:
+ pass
+
+ return allowed_origins
+
+ def get_default_allowed_origins(self) -> list[str]:
+ return ["*://localhost:*", "*://127.0.0.1:*", "*://0.0.0.0:*"]
diff --git a/python/api/tunnel.py b/python/api/tunnel.py
index ca5d64f42..c682aff12 100644
--- a/python/api/tunnel.py
+++ b/python/api/tunnel.py
@@ -4,48 +4,51 @@ from python.helpers.tunnel_manager import TunnelManager
class Tunnel(ApiHandler):
async def process(self, input: dict, request: Request) -> dict | Response:
- action = input.get("action", "get")
-
- tunnel_manager = TunnelManager.get_instance()
+ return await process(input)
- if action == "health":
- return {"success": True}
-
- if action == "create":
- port = runtime.get_web_ui_port()
- provider = input.get("provider", "serveo") # Default to serveo
- tunnel_url = tunnel_manager.start_tunnel(port, provider)
- if tunnel_url is None:
- # Add a little delay and check again - tunnel might be starting
- import time
- time.sleep(2)
- tunnel_url = tunnel_manager.get_tunnel_url()
-
- return {
- "success": tunnel_url is not None,
- "tunnel_url": tunnel_url,
- "message": "Tunnel creation in progress" if tunnel_url is None else "Tunnel created successfully"
- }
-
- elif action == "stop":
- return self.stop()
-
- elif action == "get":
+async def process(input: dict) -> dict | Response:
+ action = input.get("action", "get")
+
+ tunnel_manager = TunnelManager.get_instance()
+
+ if action == "health":
+ return {"success": True}
+
+ if action == "create":
+ port = runtime.get_web_ui_port()
+ provider = input.get("provider", "serveo") # Default to serveo
+ tunnel_url = tunnel_manager.start_tunnel(port, provider)
+ if tunnel_url is None:
+ # Add a little delay and check again - tunnel might be starting
+ import time
+ time.sleep(2)
tunnel_url = tunnel_manager.get_tunnel_url()
- return {
- "success": tunnel_url is not None,
- "tunnel_url": tunnel_url,
- "is_running": tunnel_manager.is_running
- }
return {
- "success": False,
- "error": "Invalid action. Use 'create', 'stop', or 'get'."
- }
-
- def stop(self):
- tunnel_manager = TunnelManager.get_instance()
- tunnel_manager.stop_tunnel()
+ "success": tunnel_url is not None,
+ "tunnel_url": tunnel_url,
+ "message": "Tunnel creation in progress" if tunnel_url is None else "Tunnel created successfully"
+ }
+
+ elif action == "stop":
+ return stop()
+
+ elif action == "get":
+ tunnel_url = tunnel_manager.get_tunnel_url()
return {
- "success": True
+ "success": tunnel_url is not None,
+ "tunnel_url": tunnel_url,
+ "is_running": tunnel_manager.is_running
}
+
+ return {
+ "success": False,
+ "error": "Invalid action. Use 'create', 'stop', or 'get'."
+ }
+
+def stop():
+ tunnel_manager = TunnelManager.get_instance()
+ tunnel_manager.stop_tunnel()
+ return {
+ "success": True
+ }
diff --git a/python/api/tunnel_proxy.py b/python/api/tunnel_proxy.py
index c8b1bd75b..4df17893a 100644
--- a/python/api/tunnel_proxy.py
+++ b/python/api/tunnel_proxy.py
@@ -6,30 +6,33 @@ import requests
class TunnelProxy(ApiHandler):
async def process(self, input: dict, request: Request) -> dict | Response:
- # Get configuration from environment
- tunnel_api_port = (
- runtime.get_arg("tunnel_api_port")
- or int(dotenv.get_dotenv_value("TUNNEL_API_PORT", 0))
- or 55520
- )
+ return await process(input)
- # first verify the service is running:
+async def process(input: dict) -> dict | Response:
+ # Get configuration from environment
+ tunnel_api_port = (
+ runtime.get_arg("tunnel_api_port")
+ or int(dotenv.get_dotenv_value("TUNNEL_API_PORT", 0))
+ or 55520
+ )
+
+ # first verify the service is running:
+ service_ok = False
+ try:
+ response = requests.post(f"http://localhost:{tunnel_api_port}/", json={"action": "health"})
+ if response.status_code == 200:
+ service_ok = True
+ except Exception as e:
service_ok = False
+
+ # forward this request to the tunnel service if OK
+ if service_ok:
try:
- response = requests.post(f"http://localhost:{tunnel_api_port}/", json={"action": "health"})
- if response.status_code == 200:
- service_ok = True
+ response = requests.post(f"http://localhost:{tunnel_api_port}/", json=input)
+ return response.json()
except Exception as e:
- service_ok = False
-
- # forward this request to the tunnel service if OK
- if service_ok:
- try:
- response = requests.post(f"http://localhost:{tunnel_api_port}/", json=input)
- return response.json()
- except Exception as e:
- return {"error": str(e)}
- else:
- # forward to API handler directly
- from python.api.tunnel import Tunnel
- return await Tunnel(self.app, self.thread_lock).process(input, request)
+ return {"error": str(e)}
+ else:
+ # forward to API handler directly
+ from python.api.tunnel import process as local_process
+ return await local_process(input)
diff --git a/python/helpers/login.py b/python/helpers/login.py
new file mode 100644
index 000000000..046f6131d
--- /dev/null
+++ b/python/helpers/login.py
@@ -0,0 +1,15 @@
+from python.helpers import dotenv
+import hashlib
+
+
+def get_credentials_hash():
+ user = dotenv.get_dotenv_value("AUTH_LOGIN")
+ password = dotenv.get_dotenv_value("AUTH_PASSWORD")
+ if not user:
+ return None
+ return hashlib.sha256(f"{user}:{password}".encode()).hexdigest()
+
+
+def is_login_required():
+ user = dotenv.get_dotenv_value("AUTH_LOGIN")
+ return bool(user)
diff --git a/run_ui.py b/run_ui.py
index adbf75085..1691f69e7 100644
--- a/run_ui.py
+++ b/run_ui.py
@@ -17,6 +17,7 @@ from python.helpers import runtime, dotenv, process
from python.helpers.extract_tools import load_classes_from_folder
from python.helpers.api import ApiHandler
from python.helpers.print_style import PrintStyle
+from python.helpers import login
# disable logging
import logging
@@ -116,24 +117,17 @@ def requires_loopback(f):
return decorated
-def _get_credentials_hash():
- user = dotenv.get_dotenv_value("AUTH_LOGIN")
- password = dotenv.get_dotenv_value("AUTH_PASSWORD")
- if not user:
- return None
- return hashlib.sha256(f"{user}:{password}".encode()).hexdigest()
-
# require authentication for handlers
def requires_auth(f):
@wraps(f)
async def decorated(*args, **kwargs):
- user_pass_hash = _get_credentials_hash()
+ user_pass_hash = login.get_credentials_hash()
# If no auth is configured, just proceed
if not user_pass_hash:
return await f(*args, **kwargs)
if session.get('authentication') != user_pass_hash:
- return redirect(url_for('login'))
+ return redirect(url_for('login_handler'))
return await f(*args, **kwargs)
@@ -153,14 +147,14 @@ def csrf_protect(f):
return decorated
@webapp.route("/login", methods=["GET", "POST"])
-async def login():
+async def login_handler():
error = None
if request.method == 'POST':
user = dotenv.get_dotenv_value("AUTH_LOGIN")
password = dotenv.get_dotenv_value("AUTH_PASSWORD")
if request.form['username'] == user and request.form['password'] == password:
- session['authentication'] = _get_credentials_hash()
+ session['authentication'] = login.get_credentials_hash()
return redirect(url_for('serve_index'))
else:
error = 'Invalid Credentials. Please try again.'
@@ -169,9 +163,9 @@ async def login():
return render_template_string(login_page_content, error=error)
@webapp.route("/logout")
-async def logout():
+async def logout_handler():
session.pop('authentication', None)
- return redirect(url_for('login'))
+ return redirect(url_for('login_handler'))
# handle default address, load index
@webapp.route("/", methods=["GET"])
diff --git a/webui/js/api.js b/webui/js/api.js
index 2baa1eb9a..33f893444 100644
--- a/webui/js/api.js
+++ b/webui/js/api.js
@@ -52,7 +52,7 @@ export async function fetchApi(url, request) {
// retry the request with new token
csrfToken = null;
return await _wrap(false);
- }else if(response.redirected && response.url.endsWith("/login")){
+ } else if (response.redirected && response.url.endsWith("/login")) {
// redirect to login
window.location.href = response.url;
return;
@@ -88,7 +88,12 @@ async function getCsrfToken() {
return;
}
const json = await response.json();
- csrfToken = json.token;
- document.cookie = `csrf_token_${json.runtime_id}=${csrfToken}; SameSite=Strict; Path=/`;
- return csrfToken;
+ if (json.ok) {
+ csrfToken = json.token;
+ document.cookie = `csrf_token_${json.runtime_id}=${csrfToken}; SameSite=Strict; Path=/`;
+ return csrfToken;
+ } else {
+ if (json.error) alert(json.error);
+ throw new Error(json.error || "Failed to get CSRF token");
+ }
}