Initial commit: Agentic OS troubleshooting platform
Self-hosted, Docker-based agentic troubleshooting platform: FastAPI backend + LangGraph agent, Next.js UI, tiered LLM routing (local Ollama -> Gemini -> DeepSeek -> OpenRouter), MCP server manager, encrypted device credentials, RBAC, audit log, project-memory + Obsidian integrations, and editable troubleshooting decision rules tuned for the GeneseasX vessel stack. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1
backend/app/core/__init__.py
Normal file
1
backend/app/core/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
|
||||
38
backend/app/core/crypto.py
Normal file
38
backend/app/core/crypto.py
Normal file
@@ -0,0 +1,38 @@
|
||||
"""Symmetric encryption of device credentials at rest (Fernet)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
|
||||
from cryptography.fernet import Fernet, InvalidToken
|
||||
|
||||
from app.config import settings
|
||||
|
||||
|
||||
def _fernet() -> Fernet:
|
||||
key = settings.credential_encryption_key
|
||||
if not key:
|
||||
# Derive a stable (but weak) key from SECRET_KEY so dev works without extra config.
|
||||
digest = hashlib.sha256(settings.secret_key.encode()).digest()
|
||||
key = base64.urlsafe_b64encode(digest).decode()
|
||||
try:
|
||||
return Fernet(key)
|
||||
except (ValueError, TypeError):
|
||||
# Treat provided value as raw material and derive a valid Fernet key
|
||||
digest = hashlib.sha256(key.encode()).digest()
|
||||
return Fernet(base64.urlsafe_b64encode(digest))
|
||||
|
||||
|
||||
def encrypt_secret(plaintext: str | None) -> str | None:
|
||||
if not plaintext:
|
||||
return None
|
||||
return _fernet().encrypt(plaintext.encode()).decode()
|
||||
|
||||
|
||||
def decrypt_secret(token: str | None) -> str | None:
|
||||
if not token:
|
||||
return None
|
||||
try:
|
||||
return _fernet().decrypt(token.encode()).decode()
|
||||
except InvalidToken:
|
||||
return None
|
||||
57
backend/app/core/deps.py
Normal file
57
backend/app/core/deps.py
Normal file
@@ -0,0 +1,57 @@
|
||||
"""Auth + RBAC dependencies for FastAPI routes."""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.security import decode_access_token
|
||||
from app.database import get_db
|
||||
from app.models.enums import Role
|
||||
from app.models.user import User
|
||||
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login")
|
||||
|
||||
# Privilege ordering: higher number = more privilege
|
||||
_ROLE_RANK = {Role.readonly: 0, Role.support: 1, Role.admin: 2}
|
||||
|
||||
|
||||
async def get_current_user(
|
||||
token: str = Depends(oauth2_scheme),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> User:
|
||||
creds_error = HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Could not validate credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
payload = decode_access_token(token)
|
||||
if not payload or "sub" not in payload:
|
||||
raise creds_error
|
||||
result = await db.execute(select(User).where(User.email == payload["sub"]))
|
||||
user = result.scalar_one_or_none()
|
||||
if user is None or not user.is_active:
|
||||
raise creds_error
|
||||
return user
|
||||
|
||||
|
||||
def require_role(minimum: Role) -> Callable:
|
||||
"""Return a dependency that enforces a minimum role."""
|
||||
|
||||
async def _guard(user: User = Depends(get_current_user)) -> User:
|
||||
if _ROLE_RANK[user.role] < _ROLE_RANK[minimum]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=f"Requires at least '{minimum.value}' role",
|
||||
)
|
||||
return user
|
||||
|
||||
return _guard
|
||||
|
||||
|
||||
require_admin = require_role(Role.admin)
|
||||
require_support = require_role(Role.support)
|
||||
require_readonly = require_role(Role.readonly)
|
||||
32
backend/app/core/security.py
Normal file
32
backend/app/core/security.py
Normal file
@@ -0,0 +1,32 @@
|
||||
"""Password hashing and JWT helpers."""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from jose import JWTError, jwt
|
||||
from passlib.context import CryptContext
|
||||
|
||||
from app.config import settings
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return pwd_context.hash(password)
|
||||
|
||||
|
||||
def verify_password(plain: str, hashed: str) -> bool:
|
||||
return pwd_context.verify(plain, hashed)
|
||||
|
||||
|
||||
def create_access_token(subject: str, role: str) -> str:
|
||||
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.access_token_expire_minutes)
|
||||
payload = {"sub": subject, "role": role, "exp": expire}
|
||||
return jwt.encode(payload, settings.secret_key, algorithm=settings.algorithm)
|
||||
|
||||
|
||||
def decode_access_token(token: str) -> dict | None:
|
||||
try:
|
||||
return jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm])
|
||||
except JWTError:
|
||||
return None
|
||||
Reference in New Issue
Block a user