Ver Fonte

fix: docker build context and setup password rotation

lanfr144 há 1 semana atrás
pai
commit
f001814252
3 ficheiros alterados com 90 adições e 4 exclusões
  1. 4 0
      .env
  2. 8 4
      docker-compose.yml
  3. 78 0
      rotate_passwords.py

+ 4 - 0
.env

@@ -10,3 +10,7 @@ GIT_USERNAME=lanfr144
 TAIGA_URL=http://192.168.130.161/taiga
 TAIGA_TOKEN=your_local_taiga_token
 TAIGA_PROJECT_SLUG=your_project_slug
+
+DB_READER_PASS=reader_pass
+DB_LOADER_PASS=loader_pass
+DB_APP_AUTH_PASS=app_auth_placeholder_pass

+ 8 - 4
docker-compose.yml

@@ -37,13 +37,14 @@ services:
 
   app:
     build:
-      context: ./docker/app
+      context: .
+      dockerfile: docker/app/Dockerfile
     ports:
       - "8501:8501"
     environment:
       - DB_HOST=mysql
       - DB_USER=db_reader
-      - DB_PASS=reader_pass
+      - DB_PASS=${DB_READER_PASS}
       - OLLAMA_HOST=http://ollama:11434
     depends_on:
       mysql:
@@ -52,11 +53,14 @@ services:
 
   ingest:
     build:
-      context: ./docker/ingest
+      context: .
+      dockerfile: docker/ingest/Dockerfile
     environment:
       - DB_HOST=mysql
       - DB_USER=db_loader
-      - DB_PASS=loader_pass
+      - DB_PASS=${DB_LOADER_PASS}
+    volumes:
+      - ./:/app
     depends_on:
       mysql:
         condition: service_healthy

+ 78 - 0
rotate_passwords.py

@@ -0,0 +1,78 @@
+import pymysql
+import os
+import secrets
+import string
+import subprocess
+
+def generate_password(length=16):
+    characters = string.ascii_letters + string.digits + "!@#$%^&*"
+    return ''.join(secrets.choice(characters) for _ in range(length))
+
+def update_env_file(passwords):
+    env_file = '.env'
+    lines = []
+    if os.path.exists(env_file):
+        with open(env_file, 'r') as f:
+            lines = f.readlines()
+            
+    # Remove old password lines
+    lines = [l for l in lines if not any(l.startswith(f"{k}=") for k in passwords.keys())]
+    
+    # Add new passwords
+    for key, val in passwords.items():
+        lines.append(f"{key}={val}\n")
+        
+    with open(env_file, 'w') as f:
+        f.writelines(lines)
+    print("✅ .env file updated with new synchronized passwords.")
+
+def main():
+    print("🔄 Starting Password Synchronization Routine...")
+    
+    # 1. Connect to MySQL as root
+    try:
+        conn = pymysql.connect(
+            host='127.0.0.1',  # Assuming we run this from host to mapped port, or within a container network
+            user='root',
+            password='root_pass',
+            database='food_db'
+        )
+    except Exception as e:
+        print(f"❌ Could not connect to MySQL: {e}")
+        return
+
+    # 2. Generate new passwords
+    new_passwords = {
+        'DB_READER_PASS': generate_password(),
+        'DB_LOADER_PASS': generate_password(),
+        'DB_APP_AUTH_PASS': generate_password()
+    }
+    
+    # 3. Update MySQL Users
+    try:
+        with conn.cursor() as cursor:
+            cursor.execute("ALTER USER 'db_reader'@'%' IDENTIFIED BY %s", (new_passwords['DB_READER_PASS'],))
+            cursor.execute("ALTER USER 'db_loader'@'%' IDENTIFIED BY %s", (new_passwords['DB_LOADER_PASS'],))
+            cursor.execute("ALTER USER 'db_app_auth'@'%' IDENTIFIED BY %s", (new_passwords['DB_APP_AUTH_PASS'],))
+            cursor.execute("FLUSH PRIVILEGES")
+            conn.commit()
+        print("✅ Database user passwords rotated successfully.")
+    except Exception as e:
+        print(f"❌ Failed to alter database users: {e}")
+    finally:
+        conn.close()
+        
+    # 4. Update .env file so Docker Compose picks it up
+    update_env_file(new_passwords)
+    
+    # 5. Gracefully restart client containers to sync connection
+    print("🔄 Restarting App and Ingest containers to synchronize new credentials...")
+    try:
+        subprocess.run(["docker-compose", "up", "-d", "app"], check=True)
+        # We don't necessarily need to restart ingest if it's manual, but we can recreate it if it was running.
+        print("✅ Client containers synchronized with new database passwords!")
+    except Exception as e:
+        print(f"⚠️ Failed to restart docker containers: {e}")
+
+if __name__ == "__main__":
+    main()