admin not added to postgres
This commit is contained in:
71
inspect_db.py
Normal file
71
inspect_db.py
Normal file
@@ -0,0 +1,71 @@
|
||||
import psycopg2
|
||||
import os
|
||||
import sys
|
||||
|
||||
# Hardcoding the path since we know it
|
||||
SECRETS_FILE = "/mnt/secrets/postgres.env"
|
||||
|
||||
def load_env_file(filepath):
|
||||
config = {}
|
||||
if not os.path.exists(filepath):
|
||||
print(f"❌ Error: Secrets file not found at {filepath}")
|
||||
sys.exit(1)
|
||||
with open(filepath, 'r') as f:
|
||||
for line in f:
|
||||
if '=' in line and not line.strip().startswith('#'):
|
||||
key, value = line.strip().split('=', 1)
|
||||
# Strip quotes
|
||||
if (value.startswith('"') and value.endswith('"')) or \
|
||||
(value.startswith("'") and value.endswith("'")):
|
||||
value = value[1:-1]
|
||||
config[key.strip()] = value
|
||||
return config
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("--- 🔍 Database Inspection Tool ---")
|
||||
env = load_env_file(SECRETS_FILE)
|
||||
|
||||
print(f"Connecting to: {env.get('DB_HOST')}:{env.get('DB_PORT')} (DB: {env.get('DB_NAME')})")
|
||||
|
||||
try:
|
||||
conn = psycopg2.connect(
|
||||
dbname=env.get("DB_NAME"),
|
||||
user=env.get("DB_USER"),
|
||||
password=env.get("DB_PASS"),
|
||||
host=env.get("DB_HOST"),
|
||||
port=env.get("DB_PORT", "5432")
|
||||
)
|
||||
cur = conn.cursor()
|
||||
|
||||
# 1. Get Column Names for 'users' table
|
||||
print("\n[ Table Schema: 'users' ]")
|
||||
cur.execute("""
|
||||
SELECT column_name
|
||||
FROM information_schema.columns
|
||||
WHERE table_name = 'users';
|
||||
""")
|
||||
columns = [row[0] for row in cur.fetchall()]
|
||||
print(f"Columns found: {columns}")
|
||||
|
||||
if not columns:
|
||||
print("⚠️ WARNING: No columns found! Does the table 'users' exist?")
|
||||
|
||||
# 2. Dump all users
|
||||
print("\n[ Table Content: 'users' ]")
|
||||
# We try to select 'id' specifically if it exists, otherwise *
|
||||
try:
|
||||
cur.execute("SELECT * FROM users;")
|
||||
rows = cur.fetchall()
|
||||
if not rows:
|
||||
print("⚠️ Table is EMPTY.")
|
||||
else:
|
||||
for row in rows:
|
||||
# Print raw row data
|
||||
print(f"Row: {row}")
|
||||
except Exception as e:
|
||||
print(f"Could not select data: {e}")
|
||||
|
||||
conn.close()
|
||||
|
||||
except Exception as e:
|
||||
print(f"\n❌ CONNECTION FAILED: {e}")
|
||||
@@ -24,6 +24,33 @@ HTTP_URL = "http://localhost:17170"
|
||||
LDAP_HOST = "localhost"
|
||||
LDAP_PORT = 3890
|
||||
|
||||
def nuke_corrupt_admin(pg_env, admin_user):
|
||||
print(f">>> CLEANUP: Deleting '{admin_user}' from DB...")
|
||||
|
||||
try:
|
||||
conn = psycopg2.connect(
|
||||
dbname=pg_env.get("DB_NAME"),
|
||||
user=pg_env.get("DB_USER"),
|
||||
password=pg_env.get("DB_PASS"),
|
||||
host=pg_env.get("DB_HOST"),
|
||||
port=pg_env.get("DB_PORT", "5432")
|
||||
)
|
||||
cur = conn.cursor()
|
||||
|
||||
# CORRECTED: Use 'user_id' based on your inspect_db output
|
||||
cur.execute("DELETE FROM users WHERE user_id = %s;", (admin_user,))
|
||||
|
||||
if cur.rowcount > 0:
|
||||
print(f"✅ Success: Corrupt '{admin_user}' deleted.")
|
||||
else:
|
||||
print(f"ℹ️ User '{admin_user}' was not in the DB (Clean slate).")
|
||||
|
||||
conn.commit()
|
||||
cur.close()
|
||||
conn.close()
|
||||
except Exception as e:
|
||||
print(f"❌ Database error during nuke: {e}")
|
||||
|
||||
def force_postgres_password_update(pg_env, admin_user, new_password):
|
||||
print(f">>> Manually injecting new hash for '{admin_user}' into Postgres...")
|
||||
|
||||
@@ -377,7 +404,7 @@ def setup_systemd_overrides(env, force=False, service_name="lldap"):
|
||||
lines.append("Environment=\"LLDAP_FORCE_UPDATE_PRIVATE_KEY=false\"\n")
|
||||
lines.append("Environment=\"LLDAP_FORCE_LDAP_USER_PASS_RESET=false\"\n")
|
||||
|
||||
lines.append(f"Environment=\"LLDAP_LDAP_USER_PASS={env.get('LLDAP_NEW_PASS')}\"\n")
|
||||
lines.append(f"Environment=\"LLDAP_LDAP_USER_PASS={env.get('ADMIN_PASS')}\"\n")
|
||||
|
||||
with open(override_file, 'w') as f:
|
||||
f.writelines(lines)
|
||||
@@ -395,43 +422,67 @@ def clear_ambiguous_keys():
|
||||
print(f"Removing ambiguous key file: {p}")
|
||||
os.remove(p)
|
||||
|
||||
# --- MAIN EXECUTION ---
|
||||
if __name__ == "__main__":
|
||||
print("--- Starting LLDAP Provisioning ---")
|
||||
env = load_env_file(SECRETS_FILE)
|
||||
setup_systemd_overrides(env, force=True)
|
||||
postgres_env = {}
|
||||
if os.path.exists(POSTGRES_FILE):
|
||||
postgres_env = load_env_file(POSTGRES_FILE)
|
||||
|
||||
clear_ambiguous_keys()
|
||||
|
||||
|
||||
# 1. FIX: Define new_pass EARLY so it is available for all functions
|
||||
# Fallback to ADMIN_PASS if LLDAP_NEW_PASS is not set
|
||||
if not env.get("LLDAP_NEW_PASS"):
|
||||
env["LLDAP_NEW_PASS"] = env.get("ADMIN_PASS")
|
||||
|
||||
new_pass = env.get("LLDAP_NEW_PASS")
|
||||
admin_user = env.get("ADMIN_USER", "admin")
|
||||
old_pass = env.get("LLDAP_OLD_PASS", "password")
|
||||
new_pass = env.get("LLDAP_NEW_PASS")
|
||||
base_dn = env.get("LLDAP_LDAP_BASE_DN", env.get("LLDAP_BASE_DN", "dc=poppyglen,dc=cc"))
|
||||
|
||||
# 2. Write Systemd Overrides (Now using the guaranteed env["LLDAP_NEW_PASS"])
|
||||
setup_systemd_overrides(env, force=True)
|
||||
|
||||
# 3. Load Postgres Env with Debugging
|
||||
postgres_env = {}
|
||||
if os.path.exists(POSTGRES_FILE):
|
||||
print(f"Loading Postgres config from: {POSTGRES_FILE}")
|
||||
postgres_env = load_env_file(POSTGRES_FILE)
|
||||
else:
|
||||
print(f"⚠️ WARNING: Postgres file not found at {POSTGRES_FILE}")
|
||||
print(" The manual DB password injection will be SKIPPED.")
|
||||
|
||||
clear_ambiguous_keys()
|
||||
print(f"Using Base DN: {base_dn}")
|
||||
|
||||
user_json_str = env.get("USER_JSON", "[]")
|
||||
|
||||
try:
|
||||
users = json.loads(user_json_str)
|
||||
except json.JSONDecodeError as e:
|
||||
print(f"Error parsing USER_JSON: {e}")
|
||||
sys.exit(1)
|
||||
|
||||
if postgres_env and new_pass:
|
||||
force_postgres_password_update(postgres_env, admin_user, new_pass)
|
||||
# 4. FIX: Force the Postgres Update
|
||||
# This acts as the 'Big Hammer' to fix auth issues by writing directly to the DB
|
||||
#if postgres_env and new_pass:
|
||||
# force_postgres_password_update(postgres_env, admin_user, new_pass)
|
||||
# print("ℹ️ Skipping manual Python DB injection (Letting LLDAP handle hashing natively).")
|
||||
#else:
|
||||
# print("ℹ️ Skipping manual Postgres update (Missing postgres.env or password).")
|
||||
|
||||
if postgres_env:
|
||||
# We perform a DELETE to clear any "Protocol Error" corruption
|
||||
nuke_corrupt_admin(postgres_env, admin_user)
|
||||
else:
|
||||
print("ℹ️ Skipping DB cleanup (Missing postgres.env).")
|
||||
write_lldap_config(env, postgres_env, LLDAP_CONFIG_FILE)
|
||||
|
||||
print("Restarting LLDAP to apply environment variables...")
|
||||
subprocess.run(["systemctl", "restart", "lldap"], check=False)
|
||||
time.sleep(5)
|
||||
if not wait_for_lldap(HTTP_URL, timeout=60):
|
||||
print("❌ LLDAP failed to start during Step 1.")
|
||||
sys.exit(1)
|
||||
|
||||
print("Step 2: Key adopted. Removing Force Flags for stability...")
|
||||
setup_systemd_overrides(env, force=False)
|
||||
subprocess.run(["systemctl", "restart", "lldap"], check=True)
|
||||
# BLOCK HERE until LLDAP is ready
|
||||
|
||||
if not wait_for_lldap(HTTP_URL):
|
||||
print("Check service status with: systemctl status lldap")
|
||||
sys.exit(1)
|
||||
@@ -445,18 +496,15 @@ if __name__ == "__main__":
|
||||
cookies = get_token(admin_user, old_pass)
|
||||
if cookies:
|
||||
print("Authenticated with OLD password. Rotating...")
|
||||
|
||||
# --- USE NEW LDAP ROTATION FUNCTION ---
|
||||
if change_admin_password_ldap(old_pass, new_pass, base_dn):
|
||||
# Update current_pass so subsequent LDAP logic uses the NEW password
|
||||
current_pass = new_pass
|
||||
# Re-auth HTTP to confirm and get fresh token
|
||||
cookies = get_token(admin_user, new_pass)
|
||||
else:
|
||||
print("CRITICAL: Admin rotation failed via LDAP. Exiting.")
|
||||
sys.exit(1)
|
||||
else:
|
||||
print("CRITICAL: Authentication failed completely.")
|
||||
print("Troubleshooting: Check if 'postgres.env' was loaded correctly above.")
|
||||
sys.exit(1)
|
||||
else:
|
||||
print("Authenticated with NEW password.")
|
||||
|
||||
Reference in New Issue
Block a user