|
1 | | -from flask import Flask |
| 1 | +import re |
| 2 | +import sys |
| 3 | +import time |
| 4 | + |
| 5 | +from flask import Flask, g |
| 6 | +from flask_cors import CORS |
| 7 | +from flask_limiter import Limiter |
| 8 | +from flask_limiter.util import get_remote_address |
2 | 9 | from pymongo import MongoClient |
| 10 | +from pymongo.errors import ConnectionFailure, ServerSelectionTimeoutError |
3 | 11 | import os |
4 | 12 | import logging |
5 | 13 | from celery import Celery |
|
8 | 16 |
|
9 | 17 | load_dotenv() |
10 | 18 |
|
11 | | -__version__ = "1.1.1" |
| 19 | +__version__ = "1.2.0-beta.2" |
12 | 20 |
|
13 | 21 | MONGO_URI = os.getenv("MONGO_URI") |
| 22 | +log = logging.getLogger('gunicorn.error') |
| 23 | +log.setLevel(logging.INFO) |
| 24 | + |
| 25 | +def wait_for_mongodb_replicaset(logger, mongo_uri, max_retries=120, retry_interval=5): |
| 26 | + """ |
| 27 | + Wait for MongoDB to be ready before starting the application. |
| 28 | + For replica sets, waits for PRIMARY to be elected. |
| 29 | + """ |
| 30 | + mongo_mode = os.getenv("MONGODB_MODE", "standalone").lower() |
| 31 | + if mongo_mode == "standalone": |
| 32 | + logger.info("MongoDB is in standalone mode, skipping ReplicaSet wait") |
| 33 | + return |
| 34 | + |
| 35 | + if not mongo_uri: |
| 36 | + logger.warning("MONGO_URI not set, exiting application") |
| 37 | + sys.exit(1) |
| 38 | + |
| 39 | + logger.info(f"Waiting for MongoDB ReplicaSet to be ready and elect the primary...") |
| 40 | + |
| 41 | + for attempt in range(1, max_retries + 1): |
| 42 | + if attempt != 1: |
| 43 | + time.sleep(retry_interval) |
| 44 | + try: |
| 45 | + # Try to connect |
| 46 | + client = MongoClient( |
| 47 | + mongo_uri, serverSelectionTimeoutMS=5000, connectTimeoutMS=5000 |
| 48 | + ) |
| 49 | + |
| 50 | + # Execute a simple operation to verify PRIMARY exists |
| 51 | + client.admin.command("ping") |
| 52 | + |
| 53 | + # For replica sets, verify PRIMARY exists |
| 54 | + if "replicaSet=" in mongo_uri: |
| 55 | + if client.primary is None: |
| 56 | + continue |
| 57 | + logger.info(f"PRIMARY found: {client.primary}") |
| 58 | + |
| 59 | + client.close() |
| 60 | + logger.info("MongoDB is ready") |
| 61 | + return |
| 62 | + |
| 63 | + except (ServerSelectionTimeoutError, ConnectionFailure, Exception) as e: |
| 64 | + if attempt >= max_retries: |
| 65 | + logger.info(f"MongoDB not ready after {max_retries * retry_interval}s") |
| 66 | + logger.info(f" Error: {e}") |
| 67 | + sys.exit(1) |
| 68 | + |
| 69 | + logger.info(f" Still waiting... ({attempt}/{max_retries})") |
| 70 | + |
| 71 | +wait_for_mongodb_replicaset(log, MONGO_URI) |
14 | 72 | mongo_client = MongoClient(MONGO_URI) |
15 | 73 |
|
16 | 74 | VALUES_DIRECTORY = os.getenv("VALUES_DIRECTORY", "") |
17 | 75 | KEEP_TEMP_FILES = os.getenv("KEEP_TEMP_FILES", "false") |
18 | 76 |
|
19 | | -REDIS_HOST = os.getenv("REDIS_HOST", "snmp-redis") |
20 | | -REDIS_PORT = os.getenv("REDIS_PORT", "6379") |
21 | | -REDIS_PASSWORD = os.getenv("REDIS_PASSWORD", "") |
22 | | -REDIS_DB = os.getenv("REDIS_DB", "1") |
23 | | -CELERY_DB = os.getenv("CELERY_DB", "0") |
| 77 | +REDBEAT_URL = os.getenv("REDIS_URL", "redis://snmp-redis-headless:6379") |
| 78 | +CELERY_BROKER_URL = os.getenv("CELERY_BROKER_URL", "sentinel://snmp-redis-sentinel:26379") |
| 79 | +REDIS_SENTINEL_SERVICE = os.getenv("REDIS_SENTINEL_SERVICE", "snmp-redis-sentinel") |
| 80 | +REDIS_MODE = os.getenv("REDIS_MODE", "standalone") |
24 | 81 |
|
25 | | -if REDIS_PASSWORD: |
26 | | - redis_base = f"redis://:{REDIS_PASSWORD}@{REDIS_HOST}:{REDIS_PORT}" |
27 | | -else: |
28 | | - redis_base = f"redis://{REDIS_HOST}:{REDIS_PORT}" |
29 | 82 |
|
30 | | -# fallback |
31 | | -REDBEAT_URL = os.getenv("REDIS_URL", f"{redis_base}/{REDIS_DB}") |
32 | | -CELERY_BROKER_URL = os.getenv("CELERY_BROKER_URL", f"{redis_base}/{CELERY_DB}") |
| 83 | +class NoValuesDirectoryException(Exception): |
| 84 | + pass |
33 | 85 |
|
34 | 86 |
|
35 | | -class NoValuesDirectoryException(Exception): |
| 87 | +class AuthNotConfiguredException(Exception): |
36 | 88 | pass |
37 | 89 |
|
| 90 | + |
| 91 | +limiter = Limiter(key_func=get_remote_address, default_limits=[]) |
| 92 | + |
| 93 | + |
38 | 94 | def create_app(): |
39 | 95 | if len(VALUES_DIRECTORY) == 0: |
40 | 96 | raise NoValuesDirectoryException |
41 | 97 |
|
42 | 98 | app = Flask(__name__) |
43 | 99 |
|
| 100 | + auth_enabled = os.getenv("AUTH_ENABLED", "true").lower() == "true" |
| 101 | + if auth_enabled: |
| 102 | + missing = [] |
| 103 | + for var in ("AUTH_USERNAME", "AUTH_PASSWORD_HASH", "JWT_SECRET"): |
| 104 | + if not os.getenv(var): |
| 105 | + missing.append(var) |
| 106 | + if missing: |
| 107 | + raise AuthNotConfiguredException( |
| 108 | + f"AUTH_ENABLED=true but {', '.join(missing)} not set. " |
| 109 | + "Set these env vars or set AUTH_ENABLED=false to disable authentication." |
| 110 | + ) |
| 111 | + else: |
| 112 | + log.warning( |
| 113 | + "SECURITY: AUTH_ENABLED=false. All endpoints are accessible without authentication. " |
| 114 | + "Do NOT use this configuration in production or on any network-exposed deployment. " |
| 115 | + "Restrict access via ClusterIP/NetworkPolicy and use only for local development." |
| 116 | + ) |
| 117 | + |
| 118 | + allowed_origins_env = os.getenv("ALLOWED_ORIGINS", "").strip() |
| 119 | + if allowed_origins_env == "*": |
| 120 | + # Reflect any origin. Intended for local development only. |
| 121 | + log.warning( |
| 122 | + "SECURITY: ALLOWED_ORIGINS=* reflects any browser Origin. " |
| 123 | + "Do NOT use in production; set an explicit allow-list." |
| 124 | + ) |
| 125 | + cors_origins = [re.compile(r".*")] |
| 126 | + elif allowed_origins_env: |
| 127 | + cors_origins = [o.strip() for o in allowed_origins_env.split(",") if o.strip()] |
| 128 | + elif not auth_enabled: |
| 129 | + # When auth is disabled (dev mode), reflect any origin so the UI works |
| 130 | + # out of the box on NodePort setups. Security warning already logged above. |
| 131 | + cors_origins = [re.compile(r".*")] |
| 132 | + else: |
| 133 | + cors_origins = ["http://localhost:8080"] |
| 134 | + |
| 135 | + CORS(app, origins=cors_origins, supports_credentials=True) |
| 136 | + |
| 137 | + limiter.init_app(app) |
| 138 | + limiter.storage_uri = REDBEAT_URL |
| 139 | + |
| 140 | + if REDIS_MODE == "replication": |
| 141 | + broker_transport_options = { |
| 142 | + "priority_steps": list(range(10)), |
| 143 | + "sep": ":", |
| 144 | + "queue_order_strategy": "priority", |
| 145 | + "service_name": "mymaster", |
| 146 | + "master_name": "mymaster", |
| 147 | + "socket_timeout": 5, |
| 148 | + "retry_policy": { |
| 149 | + "max_retries": 100, |
| 150 | + "interval_start": 0, |
| 151 | + "interval_step": 2, |
| 152 | + "interval_max": 5, |
| 153 | + }, |
| 154 | + "db": 1, |
| 155 | + "sentinels": [(REDIS_SENTINEL_SERVICE, 26379)], |
| 156 | + "password": os.getenv("REDIS_PASSWORD", None), |
| 157 | + } |
| 158 | + else: |
| 159 | + broker_transport_options = { |
| 160 | + "priority_steps": list(range(10)), |
| 161 | + "sep": ":", |
| 162 | + "queue_order_strategy": "priority" |
| 163 | + } |
| 164 | + |
44 | 165 | app.config.from_mapping( |
45 | 166 | CELERY=dict( |
46 | 167 | task_default_queue="apply_changes", |
47 | 168 | broker_url=CELERY_BROKER_URL, |
48 | 169 | beat_scheduler="redbeat.RedBeatScheduler", |
49 | 170 | redbeat_redis_url = REDBEAT_URL, |
50 | | - broker_transport_options={ |
51 | | - "priority_steps": list(range(10)), |
52 | | - "sep": ":", |
53 | | - "queue_order_strategy": "priority", |
54 | | - }, |
| 171 | + broker_transport_options=broker_transport_options, |
55 | 172 | task_ignore_result=True, |
56 | 173 | redbeat_lock_key=None, |
57 | 174 | ), |
58 | 175 | ) |
59 | 176 | celery_init_app(app) |
| 177 | + |
| 178 | + from SC4SNMP_UI_backend.auth.routes import auth_blueprint |
60 | 179 | from SC4SNMP_UI_backend.profiles.routes import profiles_blueprint |
61 | 180 | from SC4SNMP_UI_backend.groups.routes import groups_blueprint |
62 | 181 | from SC4SNMP_UI_backend.inventory.routes import inventory_blueprint |
63 | 182 | from SC4SNMP_UI_backend.apply_changes.routes import apply_changes_blueprint |
| 183 | + app.register_blueprint(auth_blueprint) |
64 | 184 | app.register_blueprint(profiles_blueprint) |
65 | 185 | app.register_blueprint(groups_blueprint) |
66 | 186 | app.register_blueprint(inventory_blueprint) |
67 | 187 | app.register_blueprint(apply_changes_blueprint) |
| 188 | + |
| 189 | + from SC4SNMP_UI_backend.auth.utils import ( |
| 190 | + AUTH_ENABLED as _auth_on, |
| 191 | + refresh_token_payload, |
| 192 | + make_cookie_kwargs, |
| 193 | + COOKIE_NAME, |
| 194 | + JWT_EXPIRY_HOURS as _jwt_hours, |
| 195 | + ) |
| 196 | + |
| 197 | + @app.after_request |
| 198 | + def refresh_idle_token(response): |
| 199 | + if not _auth_on: |
| 200 | + return response |
| 201 | + try: |
| 202 | + should_refresh = g.get("refresh_token", False) |
| 203 | + payload = g.get("token_payload") |
| 204 | + except RuntimeError: |
| 205 | + return response |
| 206 | + if should_refresh and payload: |
| 207 | + new_token = refresh_token_payload(payload) |
| 208 | + response.set_cookie(**make_cookie_kwargs(new_token, max_age=_jwt_hours * 3600)) |
| 209 | + return response |
| 210 | + |
68 | 211 | gunicorn_logger = logging.getLogger('gunicorn.error') |
69 | 212 | app.logger.handlers = gunicorn_logger.handlers |
70 | 213 | app.logger.setLevel(gunicorn_logger.level) |
|
0 commit comments