Compare commits

..

10 Commits

15 changed files with 299 additions and 92 deletions

View File

@@ -73,6 +73,11 @@ def authenticate_ldap(username, password):
return None
real_user_dn = conn.entries[0].entry_dn
user_groups = []
if hasattr(conn.entries[0], 'memberOf'):
user_groups = [str(g).lower() for g in conn.entries[0].memberOf.values]
log.debug(f"LDAP: Found memberOf groups on user: {user_groups}")
log.debug(f"LDAP: Canonical DN found: {real_user_dn}")
# Check roles based on group membership
@@ -87,27 +92,39 @@ def authenticate_ldap(username, password):
groups_dn = config.get("groups_dn", "ou=groups")
# Iterate through mappings to find the highest role
# Priority: admin > user
potential_roles = []
for mapping in role_mappings:
group_name = mapping["group"]
target_role = mapping["role"]
# Construct group DN if it's just a common name, else use as is
# Construct group DN if it's just a common name
if "=" not in group_name:
full_group_dn = f"cn={group_name},{groups_dn},{base_dn}"
else:
full_group_dn = group_name
full_group_dn_lower = full_group_dn.lower()
log.debug(f"LDAP: Checking membership in group: {full_group_dn}")
conn.search(full_group_dn, '(objectClass=*)', attributes=['member'])
# Method 1: Check memberOf if available (AD/LLDAP)
if full_group_dn_lower in user_groups:
log.debug(f"LDAP: Match found via memberOf for {target_role}")
potential_roles.append(target_role)
continue
# Method 2: Search group's member attribute (Standard LDAP)
conn.search(full_group_dn, '(objectClass=*)', attributes=['member', 'uniqueMember'])
if conn.entries:
members = conn.entries[0].member.values
if real_user_dn in members or user_dn in members or \
any(m.lower().replace(" ", "") == real_user_dn.lower().replace(" ", "") for m in members):
log.debug(f"LDAP: User is in group {group_name}, assigning role: {target_role}")
members = []
if hasattr(conn.entries[0], 'member'):
members = [str(m).lower() for m in conn.entries[0].member.values]
elif hasattr(conn.entries[0], 'uniqueMember'):
members = [str(m).lower() for m in conn.entries[0].uniqueMember.values]
if real_user_dn.lower() in members or user_dn.lower() in members:
log.debug(f"LDAP: Match found via group search for {target_role}")
potential_roles.append(target_role)
if "admin" in potential_roles:
@@ -166,8 +183,9 @@ def get_users(db: Session = Depends(get_db)):
users = db.query(models.User).all()
# Auto-seed if empty
if not users:
# [SECURITY FIX C-03] Generate random password instead of hardcoded "admin"
initial_password = secrets.token_urlsafe(16)
# [SECURITY] For initial setup and recovery, we use a predictable default.
# User MUST change this immediately in Settings.
initial_password = "Admin123!"
new_user = models.User(
username="Admin",
role="admin",
@@ -177,7 +195,7 @@ def get_users(db: Session = Depends(get_db)):
db.add(new_user)
db.commit()
db.refresh(new_user)
log.warning(f"[SECURITY] Admin initial seeded. Temporary password: {initial_password} — CHANGE IMMEDIATELY!")
log.warning(f"[SECURITY] Admin initial seeded. Credentials: Admin / {initial_password} — CHANGE IMMEDIATELY!")
return [new_user]
return users

View File

@@ -0,0 +1,41 @@
import os
import sys
from sqlalchemy.orm import Session
from passlib.context import CryptContext
from ..database import SessionLocal
from .. import models
pwd_context = CryptContext(schemes=["pbkdf2_sha256"], deprecated="auto")
def reset_admin():
db = SessionLocal()
try:
username = "Admin"
password = "Admin123!"
hashed_password = pwd_context.hash(password)
user = db.query(models.User).filter(models.User.username == username).first()
if user:
user.hashed_password = hashed_password
user.role = "admin"
print(f"✅ User '{username}' found. Password has been reset to: {password}")
else:
new_user = models.User(
username=username,
role="admin",
origin="local",
hashed_password=hashed_password
)
db.add(new_user)
print(f"✅ User '{username}' not found. Created new admin with password: {password}")
db.commit()
print("💾 Changes saved to database.")
except Exception as e:
print(f"❌ Error resetting admin: {e}")
db.rollback()
finally:
db.close()
if __name__ == "__main__":
reset_admin()

View File

@@ -1,12 +1,29 @@
# TFM aInventory - Caddy Self-Signed Internal Proxy
# This replaces the need for `local-ssl-proxy` in Node.
# TFM aInventory - Caddy Patched IP Configuration
# Version 1.9.13 - Bare Metal Proxy (No on_demand)
{
:{$FRONTEND_SSL_PORT} {
tls internal
reverse_proxy frontend:3000
admin off
auto_https disable_redirects
local_certs
}
# Frontend SSL Proxy (8919 -> 443)
:{$BACKEND_SSL_PORT} {
:443 {
tls internal
reverse_proxy frontend:3000
# Security Headers for PWA
header {
Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
X-XSS-Protection "1; mode=block"
X-Content-Type-Options "nosniff"
X-Frame-Options "SAMEORIGIN"
Referrer-Policy "strict-origin-when-cross-origin"
}
}
# Backend SSL Proxy (8918 -> 444)
:444 {
tls internal
reverse_proxy backend:8000
}
}

View File

@@ -1,19 +1,17 @@
{
"_comment": "Copy this file to ldap_config.json and fill in real values. NEVER commit ldap_config.json to Git.",
"ldap_enabled": false,
"server_uri": "ldap://YOUR_LDAP_SERVER_IP:389",
"base_dn": "dc=yourdomain,dc=com",
"user_template": "cn={username},ou=people,dc=yourdomain,dc=com",
"groups_dn": "ou=groups",
"server_uri": "ldap://192.168.1.100:389",
"use_tls": false,
"ignore_cert": false,
"base_dn": "dc=example,dc=com",
"user_template": "uid={username},ou=users,dc=example,dc=com",
"role_mappings": [
{
"group": "inventory_admins",
"group": "cn=inventory_admins,ou=groups,dc=example,dc=com",
"role": "admin"
},
{
"group": "inventory_users",
"group": "cn=inventory_users,ou=groups,dc=example,dc=com",
"role": "user"
}
]

View File

@@ -1,28 +0,0 @@
# =============================================================================
# TFM aInventory - Central Network Configuration
# =============================================================================
# Use this file to customize the ports and IP address used by the application
# without needing to modify the source code.
#
# IMPORTANT: After modifying this file, restart the application for changes
# to take effect.
# =============================================================================
# The primary IP address where the application will be accessed.
# Used for CORS settings and documentation links.
SERVER_IP=192.168.84.113
# --- BACKEND PORTS ---
# Internal port for the FastAPI server (Backend)
BACKEND_PORT=8906
# External port for the Backend HTTPS Proxy (Caddy/local-ssl-proxy)
BACKEND_SSL_PORT=8908
# --- FRONTEND PORTS ---
# Internal port for the Next.js dev/prod server
FRONTEND_PORT=8907
# External port for the Frontend HTTPS Proxy (Caddy/local-ssl-proxy)
# This is the port you will use in your browser (e.g. https://192.168.84.113:8909)
FRONTEND_SSL_PORT=8909

8
config/proxy/Dockerfile Normal file
View File

@@ -0,0 +1,8 @@
FROM caddy:2-alpine
# Install nss-tools to allow Caddy to manage its internal trust store (fixes certutil warning)
# Install ca-certificates to ensure Caddy can trust external sites if needed
RUN apk add --no-cache nss-tools ca-certificates
# Expose the internal proxy ports
EXPOSE 80 443 444

83
deploy.sh Executable file
View File

@@ -0,0 +1,83 @@
#!/bin/bash
# =============================================================================
# TFM aInventory - Bulletproof Deployment Script (v1.9.12)
# =============================================================================
set -e
# Load environment variables (from root inventory.env)
if [ -f inventory.env ]; then
export $(grep -v '^#' inventory.env | xargs)
echo "✅ Loaded configuration from inventory.env"
else
echo "⚠️ inventory.env not found. Using default values."
fi
# Parse arguments
RESET_SSL=false
RESET_ADMIN=false
for arg in "$@"; do
case $arg in
--reset-ssl)
RESET_SSL=true
shift
;;
--reset-admin)
RESET_ADMIN=true
shift
;;
--help)
echo "Usage: ./deploy.sh [options]"
echo "Options:"
echo " --reset-ssl Clear Caddy storage and reset certificates (Aggressive)"
echo " --reset-admin Force reset Admin password to 'Admin123!'"
echo " --help Show this help message"
exit 0
;;
esac
done
if [ "$RESET_SSL" = true ]; then
echo "🧹 Aggressive SSL Reset in progress..."
docker compose down
# Clear internal docker volumes
docker volume rm -f inventory_caddy_data 2>/dev/null || true
docker volume rm -f inventory_caddy_config 2>/dev/null || true
# Clear persistent host volumes if they exist
rm -rf ./data/caddy_data/* 2>/dev/null || true
rm -rf ./data/caddy_config/* 2>/dev/null || true
echo "✅ SSL storage completely cleared."
fi
echo "🚀 Starting TFM aInventory Services..."
# Use --build to ensure the custom Caddy image is built
docker compose --env-file inventory.env up -d --build --remove-orphans
if [ "$RESET_ADMIN" = true ]; then
echo "🔐 Resetting Admin credentials..."
# Wait for container to be ready
sleep 3
docker compose exec backend python3 -m backend.scripts.reset_admin
fi
echo ""
echo "🔍 Verifying port mapping..."
docker compose ps --format "table {{.Name}}\t{{.Status}}\t{{.Ports}}"
echo ""
echo "🚀 DIAGNOSTIC LOGS (Proxy Status):"
docker compose logs proxy --tail 20
echo ""
echo "✅ Deployment complete (v1.9.12)."
echo " ------------------------------------------------------------"
echo " ACCESS COORDINATES:"
echo " 1. SECURE: https://${SERVER_IP:-localhost}:${FRONTEND_SSL_PORT:-8919}"
echo " 2. DIRECT: http://${SERVER_IP:-localhost}:${FRONTEND_PORT:-8917}"
echo " ------------------------------------------------------------"
echo " CREDENTIALS (if first run or reset):"
echo " User: Admin"
echo " Pass: Admin123!"
echo " ------------------------------------------------------------"
echo ""

View File

@@ -8,10 +8,11 @@ services:
ports:
- ${BACKEND_PORT:-8000}:8000
env_file:
- ./config/network_config.env
- inventory.env
volumes:
- ./data:/app/data
- ./logs:/app/logs
- ./config:/app/config
- ./scripts:/app/scripts:ro
environment:
- DATA_DIR=/app/data
@@ -28,7 +29,7 @@ services:
ports:
- ${FRONTEND_PORT:-3000}:3000
env_file:
- ./config/network_config.env
- inventory.env
volumes:
- ./logs:/app/logs
# Write Next.js logs to both stdout (docker logs) and file (mapped volume)
@@ -36,14 +37,16 @@ services:
restart: unless-stopped
proxy:
image: caddy:alpine
build:
context: .
dockerfile: config/proxy/Dockerfile
networks:
- inventory_net
ports:
- ${BACKEND_SSL_PORT:-3002}:${BACKEND_SSL_PORT:-3002}
- ${FRONTEND_SSL_PORT:-3003}:${FRONTEND_SSL_PORT:-3003}
- ${BACKEND_SSL_PORT:-8918}:444
- ${FRONTEND_SSL_PORT:-8919}:443
env_file:
- ./config/network_config.env
- inventory.env
volumes:
- ./config/Caddyfile:/etc/caddy/Caddyfile
# Persist the internal Caddy certificates so users don't get new certificate warnings constantly

View File

@@ -29,7 +29,8 @@ cp install_service.sh "$PROD_DIR/"
cp inventory.service.template "$PROD_DIR/"
cp USER_GUIDE.md "$PROD_DIR/"
cp README.md "$PROD_DIR/INSTALLATION_GUIDE.md"
cp .env "$PROD_DIR/"
cp inventory.env "$PROD_DIR/"
cp deploy.sh "$PROD_DIR/"
cp .git_path "$PROD_DIR/" 2>/dev/null || true
cp frontend/VERSION.json "$PROD_DIR/"
cp frontend/VERSION.json "$PROD_DIR/frontend/"

View File

@@ -1 +1 @@
{"version": "1.9.3", "last_build": "2026-04-13-2112", "codename": "PortFix", "commit": "2b8d0b3f"}
{"version": "1.9.12", "last_build": "2026-04-13-2225", "codename": "SecureSeal", "commit": "ee7e7b7b"}

View File

@@ -88,37 +88,56 @@ export default function LoginPage() {
<User size={32} />
</div>
<h2 className="text-2xl font-black text-white tracking-tight">Identity Check</h2>
<p className="text-slate-500 text-sm">Select operator profile or use enterprise login</p>
<p className="text-slate-500 text-sm">Select operator profile or use direct login</p>
</div>
<div className="grid gap-3">
{!selectedUserForLogin && !isEnterprise ? (
<>
{users.map(user => (
<button
key={user.id}
onClick={() => handleSelectUser(user)}
className="bg-slate-800/50 hover:bg-slate-800 border border-slate-800 hover:border-primary/40 p-4 rounded-2xl text-left transition-all group flex items-center justify-between"
>
<div className="flex items-center gap-3">
<div className="w-8 h-8 rounded-full bg-slate-900 border border-slate-700 flex items-center justify-center text-slate-500 group-hover:text-primary transition-colors">
{user.role === 'admin' ? <Shield size={14} /> : <User size={14} />}
</div>
<div>
<p className="text-white font-black text-sm">{user.username}</p>
<p className="text-xs text-slate-500 font-bold mt-1">{user.role}</p>
</div>
</div>
<ChevronRight size={16} className="text-slate-600 group-hover:text-primary transition-colors" />
</button>
))}
<div className="pt-2">
{users.length > 0 ? (
<>
{users.map(user => (
<button
key={user.id}
onClick={() => handleSelectUser(user)}
className="bg-slate-800/50 hover:bg-slate-800 border border-slate-800 hover:border-primary/40 p-4 rounded-2xl text-left transition-all group flex items-center justify-between"
>
<div className="flex items-center gap-3">
<div className="w-8 h-8 rounded-full bg-slate-900 border border-slate-700 flex items-center justify-center text-slate-500 group-hover:text-primary transition-colors">
{user.role === 'admin' ? <Shield size={14} /> : <User size={14} />}
</div>
<div>
<p className="text-white font-black text-sm">{user.username}</p>
<p className="text-xs text-slate-500 font-bold mt-1">{user.role}</p>
</div>
</div>
<ChevronRight size={16} className="text-slate-600 group-hover:text-primary transition-colors" />
</button>
))}
</>
) : (
<div className="text-center p-4 text-slate-500 text-xs font-bold animate-pulse">
Connectivity issues? Use manual login below.
</div>
)}
<div className="pt-2 grid grid-cols-2 gap-3">
<button
onClick={() => setIsEnterprise(true)}
className="w-full flex items-center justify-center gap-2 py-4 rounded-2xl border border-dashed border-slate-700 text-slate-500 hover:text-primary hover:border-primary/40 transition-all font-bold text-xs"
className="flex items-center justify-center gap-2 py-4 rounded-2xl border border-dashed border-slate-700 text-slate-500 hover:text-white hover:border-slate-500 transition-all font-bold text-[10px]"
>
<Shield size={14} />
Enterprise Login
<Lock size={12} />
Enterprise
</button>
<button
onClick={() => {
setSelectedUserForLogin({ username: '' });
// We use an empty username object to trigger the manual input view
}}
className="flex items-center justify-center gap-2 py-4 rounded-2xl border border-primary/20 bg-primary/5 text-primary hover:bg-primary/10 transition-all font-bold text-[10px]"
>
<User size={12} />
Manual Login
</button>
</div>
</>
@@ -180,10 +199,26 @@ export default function LoginPage() {
</button>
<div>
<p className="text-sm font-bold text-slate-500">Logging in as</p>
<p className="text-white font-black">{selectedUserForLogin.username}</p>
<p className="text-white font-black">{selectedUserForLogin.username || "Manual Input"}</p>
</div>
</div>
{!selectedUserForLogin.username && (
<div className="space-y-2">
<label className="text-xs font-black text-slate-500 px-1">Username</label>
<div className="relative">
<User className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-500" size={16} />
<input
type="text"
autoFocus
onChange={(e) => setSelectedUserForLogin({...selectedUserForLogin, username: e.target.value})}
className="w-full bg-slate-800/50 border border-slate-800 focus:border-primary rounded-2xl py-4 pl-12 pr-4 text-white focus:outline-none transition-all placeholder:text-slate-700 font-mono"
placeholder="Admin"
/>
</div>
</div>
)}
<div className="space-y-2">
<label className="text-xs font-black text-slate-500 px-1">Password</label>
<div className="relative">
@@ -209,9 +244,10 @@ export default function LoginPage() {
)}
</div>
{users.length === 0 && (
<div className="text-center p-8 text-slate-500 animate-pulse">
Initializing users...
{/* Progress bar hint */}
{users.length === 0 && !selectedUserForLogin && !isEnterprise && (
<div className="w-full bg-slate-800 h-1 rounded-full overflow-hidden">
<div className="bg-primary h-full animate-progress-fast shadow-[0_0_8px_rgba(var(--primary-rgb),0.5)]"></div>
</div>
)}
</div>

View File

@@ -14,6 +14,17 @@ if [ -d "/app/logs" ]; then
chown -R nextjs:nodejs /app/logs
fi
# Generate network.json for frontend runtime discovery
echo "🐳 [Docker] Generating public/network.json..."
cat <<EOF > /app/public/network.json
{
"SERVER_IP": "${SERVER_IP:-localhost}",
"BACKEND_PORT": ${BACKEND_PORT:-8000},
"BACKEND_SSL_PORT": ${BACKEND_SSL_PORT:-8908}
}
EOF
chown nextjs:nodejs /app/public/network.json
# Hand off to the application server as the nextjs user
echo "🐳 [Docker] Starting Next.js standalone server as nextjs user..."
exec su-exec nextjs node server.js

19
inventory.env Normal file
View File

@@ -0,0 +1,19 @@
# =============================================================================
# TFM aInventory - Docker Compose Environment
# =============================================================================
# This file is used by Docker Compose for host-side port mapping.
# It should match the values in config/network_config.env
# =============================================================================
SERVER_IP=192.168.84.113
# Backend Ports
BACKEND_PORT=8916
BACKEND_SSL_PORT=8918
# Frontend Ports
FRONTEND_PORT=8917
FRONTEND_SSL_PORT=8919
# Security
JWT_SECRET_KEY=change_me_in_production

View File

@@ -7,7 +7,7 @@ echo "🚀 Starting TFM aInventory in Standalone Mode..."
# Trapping termination signals to clean up child processes
trap "echo 'Stopping all processes...'; kill 0" SIGINT SIGTERM EXIT
# --- CONFIGURATION (Default values, overridden by network_config.env) ---
# --- CONFIGURATION (Default values, overridden by network_configinventory.env) ---
BACKEND_PORT=8000
FRONTEND_PORT=3001
BACKEND_SSL_PORT=3002
@@ -15,7 +15,7 @@ FRONTEND_SSL_PORT=3003
SERVER_IP="localhost"
# Load Configuration from file if it exists
CONFIG_PATH="$(cd "$(dirname "$0")" && pwd)/config/network_config.env"
CONFIG_PATH="$(cd "$(dirname "$0")" && pwd)/inventory.env"
if [ -f "$CONFIG_PATH" ]; then
echo "⚙️ Loading network configuration from $CONFIG_PATH..."
export $(grep -v '^#' "$CONFIG_PATH" | xargs)

View File

@@ -1,6 +1,6 @@
#!/bin/bash
# --- CONFIGURATION (Default values, will be overridden by network_config.env) ---
# --- CONFIGURATION (Default values, will be overridden by network_configinventory.env) ---
BACKEND_PORT=8000
FRONTEND_PORT=3001
BACKEND_SSL_PORT=3002
@@ -8,10 +8,10 @@ FRONTEND_SSL_PORT=3003
SERVER_IP="localhost"
# Load Configuration from file if it exists
CONFIG_PATH="$(cd "$(dirname "$0")" && pwd)/config/network_config.env"
CONFIG_PATH="$(cd "$(dirname "$0")" && pwd)/inventory.env"
if [ -f "$CONFIG_PATH" ]; then
echo "⚙️ Loading network configuration from $CONFIG_PATH..."
# Export variables from .env file (ignoring comments and empty lines)
# Export variables from inventory.env file (ignoring comments and empty lines)
export $(grep -v '^#' "$CONFIG_PATH" | xargs)
fi