feat: database management — custom credentials, dump upload/restore

Backend:
- Add dbUsername/dbPassword columns to Application entity
- Add optional DB credential fields to CreateApplicationDto
- Auto-generate dbPassword (crypto.randomBytes) and default dbUsername='appuser'
  when databaseType != 'none' on app creation
- Store both username and password in K8s DB secret (was password-only)
- Read DB_USER/POSTGRES_USER/MYSQL_USER from secretKeyRef instead of hardcoded
- New restoreDatabaseDump() in KubernetesService: creates K8s Job with
  psql/mysql client to restore uploaded SQL dump, waits for completion,
  returns logs
- New POST /applications/:id/db-upload endpoint with 500MB file limit

Frontend:
- Add dbUsername/dbPassword to Application and CreateApplicationDto types
- Deploy page: show username/password fields when database is selected,
  with generate-random-password button and show/hide toggle
- App detail page: new Database section with connection info (host, port,
  db name, username, password with copy-to-clipboard), SQL dump upload
  area with drag-and-drop, and restore output logs display

Security:
- Database remains ClusterIP only (no external exposure)
- Credentials stored in K8s Secrets (base64-encoded)
- Dump file uploaded as temporary K8s Secret, auto-cleaned after restore
This commit is contained in:
keyhan
2026-04-06 22:47:41 +03:30
parent 3c3e0e48fa
commit 9e3347cb71
9 changed files with 496 additions and 13 deletions
+180 -1
View File
@@ -6,7 +6,7 @@ import api from '@/lib/api';
import { toast } from 'react-toastify';
import type { Application, Deployment, ResourceUsage, ClusterPublic, ClusterPoolPublic } from '@/types';
import { useState, useRef, useCallback, useEffect } from 'react';
import { Hexagon, Rocket, Play, Square, RotateCw, Globe, Package, Server, Scale, CheckCircle, Clock, XCircle, AlertCircle, Link, GitBranch, KeyRound, FolderUp, BarChart3, ChevronDown, FileText, Monitor, Hammer, Settings, RefreshCw, Upload, Circle, Pin } from 'lucide-react';
import { Hexagon, Rocket, Play, Square, RotateCw, Globe, Package, Server, Scale, CheckCircle, Clock, XCircle, AlertCircle, Link, GitBranch, KeyRound, FolderUp, BarChart3, ChevronDown, FileText, Monitor, Hammer, Settings, RefreshCw, Upload, Circle, Pin, Database, Eye, EyeOff, Copy, Check } from 'lucide-react';
const statusColors: Record<string, string> = {
running: 'badge-green',
@@ -54,6 +54,11 @@ export default function AppDetailPage() {
const [uploadProgress, setUploadProgress] = useState(0);
const [isDragging, setIsDragging] = useState(false);
const [showResources, setShowResources] = useState(false);
const [showDbPassword, setShowDbPassword] = useState(false);
const [copiedField, setCopiedField] = useState<string | null>(null);
const [dbRestoreLogs, setDbRestoreLogs] = useState<string | null>(null);
const dbFileInputRef = useRef<HTMLInputElement>(null);
const [isDraggingDb, setIsDraggingDb] = useState(false);
const [resourceForm, setResourceForm] = useState({
cpuRequest: '',
cpuLimit: '',
@@ -227,6 +232,29 @@ export default function AppDetailPage() {
},
});
const dbUploadMutation = useMutation({
mutationFn: (file: File) => {
const formData = new FormData();
formData.append('file', file);
return api.post(`/applications/${appId}/db-upload`, formData, {
headers: { 'Content-Type': 'multipart/form-data' },
});
},
onSuccess: (res) => {
const data = res.data;
setDbRestoreLogs(data.logs || null);
if (data.success) {
toast.success('Database restored successfully!');
} else {
toast.error(data.message || 'Database restore failed');
}
},
onError: (err: any) => {
toast.error(err.response?.data?.message || 'Failed to upload database dump');
setDbRestoreLogs(null);
},
});
const handleFileUpload = useCallback((file: File) => {
if (!file.name.endsWith('.zip') && !file.name.endsWith('.tar.gz') && !file.name.endsWith('.tgz')) {
toast.error('Please upload a .zip or .tar.gz file');
@@ -255,6 +283,41 @@ export default function AppDetailPage() {
setIsDragging(false);
}, []);
const handleDbFileUpload = useCallback((file: File) => {
if (!file.name.endsWith('.sql') && !file.name.endsWith('.gz') && !file.name.endsWith('.dump')) {
toast.error('Please upload a .sql, .dump, or .gz file');
return;
}
if (file.size > 500 * 1024 * 1024) {
toast.error('File size must be less than 500MB');
return;
}
setDbRestoreLogs(null);
dbUploadMutation.mutate(file);
}, [dbUploadMutation]);
const handleDbDrop = useCallback((e: React.DragEvent) => {
e.preventDefault();
setIsDraggingDb(false);
const file = e.dataTransfer.files[0];
if (file) handleDbFileUpload(file);
}, [handleDbFileUpload]);
const handleDbDragOver = useCallback((e: React.DragEvent) => {
e.preventDefault();
setIsDraggingDb(true);
}, []);
const handleDbDragLeave = useCallback(() => {
setIsDraggingDb(false);
}, []);
const copyToClipboard = useCallback((text: string, field: string) => {
navigator.clipboard.writeText(text);
setCopiedField(field);
setTimeout(() => setCopiedField(null), 2000);
}, []);
if (isLoading || !app) {
return (
<div className="space-y-6 animate-fade-in">
@@ -537,6 +600,122 @@ export default function AppDetailPage() {
</div>
</div>
{/* Database Info & Dump Upload */}
{app.databaseType !== 'none' && (
<div className="card">
<h2 className="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2">
<Database className="w-5 h-5" /> Database
<span className="badge badge-blue text-xs">{app.databaseType}</span>
</h2>
{/* Connection Info */}
<div className="bg-gray-50 rounded-xl p-4 mb-4 space-y-2">
<h3 className="text-sm font-semibold text-gray-700 mb-3">Connection Info (Internal Cluster)</h3>
{[
{ label: 'Host', value: `${app.name}-db`, field: 'host' },
{ label: 'Port', value: app.databaseType === 'postgresql' ? '5432' : '3306', field: 'port' },
{ label: 'Database', value: app.name.replace(/-/g, '_'), field: 'database' },
{ label: 'Username', value: app.dbUsername || 'appuser', field: 'username' },
].map(({ label, value, field }) => (
<div key={field} className="flex items-center justify-between">
<span className="text-sm text-gray-500">{label}</span>
<div className="flex items-center gap-2">
<span className="text-sm font-mono text-gray-800">{value}</span>
<button
onClick={() => copyToClipboard(value, field)}
className="p-1 text-gray-400 hover:text-gray-600 transition-colors"
title="Copy"
>
{copiedField === field ? <Check className="w-3.5 h-3.5 text-green-500" /> : <Copy className="w-3.5 h-3.5" />}
</button>
</div>
</div>
))}
{/* Password row with show/hide */}
<div className="flex items-center justify-between">
<span className="text-sm text-gray-500">Password</span>
<div className="flex items-center gap-2">
<span className="text-sm font-mono text-gray-800">
{showDbPassword ? (app.dbPassword || '—') : '••••••••••••'}
</span>
<button
onClick={() => setShowDbPassword(!showDbPassword)}
className="p-1 text-gray-400 hover:text-gray-600 transition-colors"
title={showDbPassword ? 'Hide' : 'Show'}
>
{showDbPassword ? <EyeOff className="w-3.5 h-3.5" /> : <Eye className="w-3.5 h-3.5" />}
</button>
<button
onClick={() => copyToClipboard(app.dbPassword || '', 'password')}
className="p-1 text-gray-400 hover:text-gray-600 transition-colors"
title="Copy"
>
{copiedField === 'password' ? <Check className="w-3.5 h-3.5 text-green-500" /> : <Copy className="w-3.5 h-3.5" />}
</button>
</div>
</div>
<p className="text-xs text-gray-400 mt-2 pt-2 border-t border-gray-200">
Database is only accessible within the cluster. Not exposed externally.
</p>
</div>
{/* DB Dump Upload */}
<h3 className="text-sm font-semibold text-gray-700 mb-3">Restore Database Dump</h3>
<div
onDrop={handleDbDrop}
onDragOver={handleDbDragOver}
onDragLeave={handleDbDragLeave}
onClick={() => dbFileInputRef.current?.click()}
className={`border-2 border-dashed rounded-xl p-6 text-center cursor-pointer transition-all
${isDraggingDb
? 'border-blue-500 bg-blue-50'
: 'border-gray-300 hover:border-blue-400 hover:bg-gray-50'
}
${dbUploadMutation.isPending ? 'pointer-events-none opacity-60' : ''}
`}
>
<input
ref={dbFileInputRef}
type="file"
accept=".sql,.gz,.dump"
className="hidden"
onChange={(e) => {
const file = e.target.files?.[0];
if (file) handleDbFileUpload(file);
e.target.value = '';
}}
/>
{dbUploadMutation.isPending ? (
<div className="space-y-2">
<Database className="w-8 h-8 mx-auto text-blue-400 animate-pulse" />
<p className="text-sm font-medium text-gray-700">Restoring database...</p>
<p className="text-xs text-gray-500">This may take a few minutes</p>
</div>
) : (
<div className="space-y-2">
<Database className="w-8 h-8 mx-auto text-gray-400" />
<p className="text-sm font-medium text-gray-700">Upload SQL dump to restore</p>
<p className="text-xs text-gray-500">
Drag & drop a <strong>.sql</strong> file here, or click to browse
</p>
<p className="text-xs text-gray-400">Max size: 500MB</p>
</div>
)}
</div>
{/* Restore Logs */}
{dbRestoreLogs && (
<div className="mt-4">
<h4 className="text-xs font-semibold text-gray-600 mb-2">Restore Output</h4>
<pre className="bg-gray-900 text-green-400 p-4 rounded-xl text-xs font-mono overflow-x-auto max-h-[300px] overflow-y-auto whitespace-pre-wrap break-words">
{dbRestoreLogs}
</pre>
</div>
)}
</div>
)}
{/* Resource Monitoring & Scaling */}
<div className="card">
<div className="flex items-center justify-between mb-4">
+74 -1
View File
@@ -7,7 +7,7 @@ import api from '@/lib/api';
import { useAuthStore } from '@/lib/store';
import { toast } from 'react-toastify';
import type { CreateApplicationDto, ClusterPublic, ClusterPoolPublic } from '@/types';
import { Hexagon, FolderUp, Link as LinkIcon, CheckCircle, Package, Server, Scale, Home, Target, BarChart3, RotateCw, KeyRound, Rocket, Clock, Upload, XCircle } from 'lucide-react';
import { Hexagon, FolderUp, Link as LinkIcon, CheckCircle, Package, Server, Scale, Home, Target, BarChart3, RotateCw, KeyRound, Rocket, Clock, Upload, XCircle, Database, Eye, EyeOff, RefreshCw } from 'lucide-react';
const steps = ['Basic Info', 'Runtime & Database', 'Resources', 'Review'];
@@ -39,6 +39,7 @@ export default function DeployPage() {
const [uploadProgress, setUploadProgress] = useState(0);
const [isDragging, setIsDragging] = useState(false);
const [clusterMode, setClusterMode] = useState<'default' | 'manual' | 'pool'>('default');
const [showDbPassword, setShowDbPassword] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const { data: clusters = [] } = useQuery<ClusterPublic[]>({
@@ -389,6 +390,66 @@ export default function DeployPage() {
))}
</div>
</div>
{/* Database Credentials — shown when a DB is selected */}
{form.databaseType !== 'none' && (
<div className="p-4 bg-blue-50/50 border border-blue-200 rounded-xl space-y-4">
<div className="flex items-center gap-2">
<Database className="w-5 h-5 text-blue-500" />
<h3 className="text-sm font-semibold text-gray-800">Database Credentials</h3>
<span className="text-xs text-gray-400">(optional auto-generated if empty)</span>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div>
<label className="block text-xs text-gray-500 mb-1">Username</label>
<input
className="input-field"
placeholder="appuser"
value={form.dbUsername || ''}
onChange={(e) => setForm({ ...form, dbUsername: e.target.value })}
/>
</div>
<div>
<label className="block text-xs text-gray-500 mb-1">Password</label>
<div className="relative">
<input
className="input-field pr-20"
type={showDbPassword ? 'text' : 'password'}
placeholder="Auto-generated"
value={form.dbPassword || ''}
onChange={(e) => setForm({ ...form, dbPassword: e.target.value })}
/>
<div className="absolute inset-y-0 right-0 flex items-center gap-1 pr-2">
<button
type="button"
onClick={() => {
const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let pass = '';
for (let i = 0; i < 20; i++) pass += chars.charAt(Math.floor(Math.random() * chars.length));
setForm({ ...form, dbPassword: pass });
setShowDbPassword(true);
}}
className="p-1 text-gray-400 hover:text-blue-500 transition-colors"
title="Generate random password"
>
<RefreshCw className="w-4 h-4" />
</button>
<button
type="button"
onClick={() => setShowDbPassword(!showDbPassword)}
className="p-1 text-gray-400 hover:text-gray-600 transition-colors"
>
{showDbPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
</button>
</div>
</div>
</div>
</div>
<p className="text-xs text-gray-400">
These credentials are used for internal cluster communication only. The database is not exposed externally.
</p>
</div>
)}
</div>
)}
@@ -682,6 +743,18 @@ export default function DeployPage() {
<span className="text-sm text-gray-500">Database</span>
<span className="text-sm font-medium">{form.databaseType}</span>
</div>
{form.databaseType !== 'none' && (
<>
<div className="flex justify-between">
<span className="text-sm text-gray-500">DB Username</span>
<span className="text-sm font-medium">{form.dbUsername || 'appuser (default)'}</span>
</div>
<div className="flex justify-between">
<span className="text-sm text-gray-500">DB Password</span>
<span className="text-sm font-medium">{form.dbPassword ? '••••••••' : 'Auto-generated'}</span>
</div>
</>
)}
<div className="flex justify-between">
<span className="text-sm text-gray-500">Source</span>
<span className="text-sm font-medium">