fix: comprehensive security, performance, and quality hardening

Security: apply AdminOnly middleware to mutating routes, require
ENCRYPTION_KEY and ADMIN_PASSWORD (no insecure defaults), restrict
CORS to same-origin, fix OIDC token delivery via cookie instead of
URL query param, add rate limiting on login, add MaxBytesReader,
validate volume paths against traversal, add security headers,
validate user roles, add Secure flag to OIDC cookie.

Performance: set SQLite MaxOpenConns(1) to prevent SQLITE_BUSY,
add FK indexes on 8 columns, track notifier goroutines with
WaitGroup for graceful shutdown, use GetRegistryByName instead of
GetAllRegistries in deployer, pass basePath param to avoid redundant
settings query, return empty slices from store to remove reflection.

Quality: refactor TriggerDeploy to delegate to runDeploy (~100 lines
removed), consolidate duplicated utilities (extractPort, boolToInt,
now, isTerminalStatus) into shared exports, migrate all log.Printf
to slog structured logging, use consistent webhook response envelope,
remove dead code (parseEnvVars, duplicate auth types).

UX: clean up NPM proxy on instance removal via API, add README with
quickstart guide, add .env.example, require ADMIN_PASSWORD in
docker-compose, document staging-net prerequisite.
This commit is contained in:
2026-03-29 12:49:24 +03:00
parent c5bfc586c1
commit be6ad15efc
32 changed files with 519 additions and 392 deletions
+22 -8
View File
@@ -11,7 +11,7 @@ import (
// CreateDeploy inserts a new deploy record.
func (s *Store) CreateDeploy(d Deploy) (Deploy, error) {
d.ID = uuid.New().String()
d.StartedAt = now()
d.StartedAt = Now()
if d.Status == "" {
d.Status = "pending"
}
@@ -73,9 +73,9 @@ func (s *Store) GetRecentDeploys(limit int) ([]Deploy, error) {
// UpdateDeployStatus sets the status (and optionally error and finished_at) on a deploy.
func (s *Store) UpdateDeployStatus(id string, status string, deployErr string) error {
ts := now()
ts := Now()
var finishedAt string
if isTerminalDeployStatus(status) {
if IsTerminalDeployStatus(status) {
finishedAt = ts
}
@@ -113,7 +113,7 @@ func (s *Store) AppendDeployLog(deployID string, message string, level string) e
}
_, err := s.db.Exec(
`INSERT INTO deploy_logs (deploy_id, message, level, created_at) VALUES (?, ?, ?, ?)`,
deployID, message, level, now(),
deployID, message, level, Now(),
)
if err != nil {
return fmt.Errorf("append deploy log: %w", err)
@@ -132,7 +132,7 @@ func (s *Store) GetDeployLogs(deployID string) ([]DeployLog, error) {
}
defer rows.Close()
var logs []DeployLog
logs := []DeployLog{}
for rows.Next() {
var l DeployLog
if err := rows.Scan(&l.ID, &l.DeployID, &l.Message, &l.Level, &l.CreatedAt); err != nil {
@@ -145,7 +145,7 @@ func (s *Store) GetDeployLogs(deployID string) ([]DeployLog, error) {
// scanDeploys is a helper that scans deploy rows from a cursor.
func scanDeploys(rows *sql.Rows) ([]Deploy, error) {
var deploys []Deploy
deploys := []Deploy{}
for rows.Next() {
var d Deploy
if err := rows.Scan(&d.ID, &d.ProjectID, &d.StageID, &d.InstanceID, &d.ImageTag, &d.Status, &d.StartedAt, &d.FinishedAt, &d.Error); err != nil {
@@ -156,8 +156,8 @@ func scanDeploys(rows *sql.Rows) ([]Deploy, error) {
return deploys, rows.Err()
}
// isTerminalDeployStatus returns true if the status indicates the deploy is finished.
func isTerminalDeployStatus(status string) bool {
// IsTerminalDeployStatus returns true if the status indicates the deploy is finished.
func IsTerminalDeployStatus(status string) bool {
switch status {
case "success", "failed", "rolled_back":
return true
@@ -165,3 +165,17 @@ func isTerminalDeployStatus(status string) bool {
return false
}
}
// CleanupOldDeploys removes deploy records and their logs older than the given
// number of days. Returns the number of deploys removed.
func (s *Store) CleanupOldDeploys(retentionDays int) (int64, error) {
cutoff := fmt.Sprintf("-%d days", retentionDays)
result, err := s.db.Exec(
`DELETE FROM deploys WHERE started_at < datetime('now', ?)`, cutoff,
)
if err != nil {
return 0, fmt.Errorf("cleanup old deploys: %w", err)
}
n, _ := result.RowsAffected()
return n, nil
}
+5 -5
View File
@@ -11,7 +11,7 @@ import (
// CreateInstance inserts a new instance record.
func (s *Store) CreateInstance(inst Instance) (Instance, error) {
inst.ID = uuid.New().String()
inst.CreatedAt = now()
inst.CreatedAt = Now()
inst.UpdatedAt = inst.CreatedAt
_, err := s.db.Exec(
@@ -32,7 +32,7 @@ func (s *Store) CreateInstanceWithID(inst Instance) (Instance, error) {
if inst.ID == "" {
return Instance{}, fmt.Errorf("instance ID is required")
}
inst.CreatedAt = now()
inst.CreatedAt = Now()
inst.UpdatedAt = inst.CreatedAt
_, err := s.db.Exec(
@@ -75,7 +75,7 @@ func (s *Store) GetInstancesByStageID(stageID string) ([]Instance, error) {
}
defer rows.Close()
var instances []Instance
instances := []Instance{}
for rows.Next() {
var inst Instance
if err := rows.Scan(&inst.ID, &inst.StageID, &inst.ProjectID, &inst.ContainerID, &inst.ImageTag,
@@ -89,7 +89,7 @@ func (s *Store) GetInstancesByStageID(stageID string) ([]Instance, error) {
// UpdateInstance updates an existing instance's mutable fields.
func (s *Store) UpdateInstance(inst Instance) error {
inst.UpdatedAt = now()
inst.UpdatedAt = Now()
result, err := s.db.Exec(
`UPDATE instances SET stage_id=?, project_id=?, container_id=?, image_tag=?, subdomain=?, npm_proxy_id=?, status=?, port=?, updated_at=?
WHERE id=?`,
@@ -108,7 +108,7 @@ func (s *Store) UpdateInstance(inst Instance) error {
// UpdateInstanceStatus sets only the status field on an instance.
func (s *Store) UpdateInstanceStatus(id string, status string) error {
ts := now()
ts := Now()
result, err := s.db.Exec(
`UPDATE instances SET status=?, updated_at=? WHERE id=?`,
status, ts, id,
+1 -1
View File
@@ -63,7 +63,7 @@ func (s *Store) GetAllPollStates() ([]PollState, error) {
}
defer rows.Close()
var states []PollState
states := []PollState{}
for rows.Next() {
var ps PollState
if err := rows.Scan(&ps.StageID, &ps.LastTag, &ps.LastPolled); err != nil {
+3 -3
View File
@@ -11,7 +11,7 @@ import (
// CreateProject inserts a new project and returns it.
func (s *Store) CreateProject(p Project) (Project, error) {
p.ID = uuid.New().String()
p.CreatedAt = now()
p.CreatedAt = Now()
p.UpdatedAt = p.CreatedAt
_, err := s.db.Exec(
@@ -52,7 +52,7 @@ func (s *Store) GetAllProjects() ([]Project, error) {
}
defer rows.Close()
var projects []Project
projects := []Project{}
for rows.Next() {
var p Project
if err := rows.Scan(&p.ID, &p.Name, &p.Registry, &p.Image, &p.Port, &p.Healthcheck, &p.Env, &p.Volumes, &p.CreatedAt, &p.UpdatedAt); err != nil {
@@ -65,7 +65,7 @@ func (s *Store) GetAllProjects() ([]Project, error) {
// UpdateProject updates an existing project's mutable fields.
func (s *Store) UpdateProject(p Project) error {
p.UpdatedAt = now()
p.UpdatedAt = Now()
result, err := s.db.Exec(
`UPDATE projects SET name=?, registry=?, image=?, port=?, healthcheck=?, env=?, volumes=?, updated_at=?
WHERE id=?`,
+3 -3
View File
@@ -11,7 +11,7 @@ import (
// CreateRegistry inserts a new registry.
func (s *Store) CreateRegistry(r Registry) (Registry, error) {
r.ID = uuid.New().String()
r.CreatedAt = now()
r.CreatedAt = Now()
r.UpdatedAt = r.CreatedAt
_, err := s.db.Exec(
@@ -68,7 +68,7 @@ func (s *Store) GetAllRegistries() ([]Registry, error) {
}
defer rows.Close()
var registries []Registry
registries := []Registry{}
for rows.Next() {
var r Registry
if err := rows.Scan(&r.ID, &r.Name, &r.URL, &r.Type, &r.Token, &r.Owner, &r.CreatedAt, &r.UpdatedAt); err != nil {
@@ -81,7 +81,7 @@ func (s *Store) GetAllRegistries() ([]Registry, error) {
// UpdateRegistry updates an existing registry's mutable fields.
func (s *Store) UpdateRegistry(r Registry) error {
r.UpdatedAt = now()
r.UpdatedAt = Now()
result, err := s.db.Exec(
`UPDATE registries SET name=?, url=?, type=?, token=?, owner=?, updated_at=?
WHERE id=?`,
+1 -1
View File
@@ -21,7 +21,7 @@ func (s *Store) GetSettings() (Settings, error) {
// UpdateSettings upserts the global settings row.
func (s *Store) UpdateSettings(st Settings) error {
st.UpdatedAt = now()
st.UpdatedAt = Now()
_, err := s.db.Exec(
`UPDATE settings SET
domain=?, server_ip=?, network=?, subdomain_pattern=?, notification_url=?,
+5 -5
View File
@@ -11,13 +11,13 @@ import (
// CreateStageEnv inserts a new stage environment variable override.
func (s *Store) CreateStageEnv(env StageEnv) (StageEnv, error) {
env.ID = uuid.New().String()
env.CreatedAt = now()
env.CreatedAt = Now()
env.UpdatedAt = env.CreatedAt
_, err := s.db.Exec(
`INSERT INTO stage_env (id, stage_id, key, value, encrypted, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?)`,
env.ID, env.StageID, env.Key, env.Value, boolToInt(env.Encrypted),
env.ID, env.StageID, env.Key, env.Value, BoolToInt(env.Encrypted),
env.CreatedAt, env.UpdatedAt,
)
if err != nil {
@@ -37,7 +37,7 @@ func (s *Store) GetStageEnvByStageID(stageID string) ([]StageEnv, error) {
}
defer rows.Close()
var envs []StageEnv
envs := []StageEnv{}
for rows.Next() {
env, err := scanStageEnv(rows)
if err != nil {
@@ -69,11 +69,11 @@ func (s *Store) GetStageEnvByID(id string) (StageEnv, error) {
// UpdateStageEnv updates an existing stage environment variable override.
func (s *Store) UpdateStageEnv(env StageEnv) error {
env.UpdatedAt = now()
env.UpdatedAt = Now()
result, err := s.db.Exec(
`UPDATE stage_env SET key=?, value=?, encrypted=?, updated_at=?
WHERE id=?`,
env.Key, env.Value, boolToInt(env.Encrypted), env.UpdatedAt, env.ID,
env.Key, env.Value, BoolToInt(env.Encrypted), env.UpdatedAt, env.ID,
)
if err != nil {
return fmt.Errorf("update stage env: %w", err)
+9 -9
View File
@@ -11,14 +11,14 @@ import (
// CreateStage inserts a new stage for a project.
func (s *Store) CreateStage(st Stage) (Stage, error) {
st.ID = uuid.New().String()
st.CreatedAt = now()
st.CreatedAt = Now()
st.UpdatedAt = st.CreatedAt
_, err := s.db.Exec(
`INSERT INTO stages (id, project_id, name, tag_pattern, auto_deploy, max_instances, confirm, promote_from, subdomain, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
st.ID, st.ProjectID, st.Name, st.TagPattern, boolToInt(st.AutoDeploy), st.MaxInstances,
boolToInt(st.Confirm), st.PromoteFrom, st.Subdomain, st.CreatedAt, st.UpdatedAt,
st.ID, st.ProjectID, st.Name, st.TagPattern, BoolToInt(st.AutoDeploy), st.MaxInstances,
BoolToInt(st.Confirm), st.PromoteFrom, st.Subdomain, st.CreatedAt, st.UpdatedAt,
)
if err != nil {
return Stage{}, fmt.Errorf("insert stage: %w", err)
@@ -37,7 +37,7 @@ func (s *Store) GetStagesByProjectID(projectID string) ([]Stage, error) {
}
defer rows.Close()
var stages []Stage
stages := []Stage{}
for rows.Next() {
st, err := scanStage(rows)
if err != nil {
@@ -70,12 +70,12 @@ func (s *Store) GetStageByID(id string) (Stage, error) {
// UpdateStage updates an existing stage's mutable fields.
func (s *Store) UpdateStage(st Stage) error {
st.UpdatedAt = now()
st.UpdatedAt = Now()
result, err := s.db.Exec(
`UPDATE stages SET name=?, tag_pattern=?, auto_deploy=?, max_instances=?, confirm=?, promote_from=?, subdomain=?, updated_at=?
WHERE id=?`,
st.Name, st.TagPattern, boolToInt(st.AutoDeploy), st.MaxInstances,
boolToInt(st.Confirm), st.PromoteFrom, st.Subdomain, st.UpdatedAt, st.ID,
st.Name, st.TagPattern, BoolToInt(st.AutoDeploy), st.MaxInstances,
BoolToInt(st.Confirm), st.PromoteFrom, st.Subdomain, st.UpdatedAt, st.ID,
)
if err != nil {
return fmt.Errorf("update stage: %w", err)
@@ -100,8 +100,8 @@ func (s *Store) DeleteStage(id string) error {
return nil
}
// boolToInt converts a bool to an integer for SQLite storage.
func boolToInt(b bool) int {
// BoolToInt converts a bool to an integer for SQLite storage.
func BoolToInt(b bool) int {
if b {
return 1
}
+24 -2
View File
@@ -24,6 +24,10 @@ func New(dbPath string) (*Store, error) {
return nil, fmt.Errorf("open database: %w", err)
}
// SQLite only allows one writer at a time. Limit connections to prevent SQLITE_BUSY.
db.SetMaxOpenConns(1)
db.SetConnMaxLifetime(0)
// Enable WAL mode and foreign keys for better concurrency and referential integrity.
pragmas := []string{
"PRAGMA journal_mode=WAL",
@@ -79,6 +83,24 @@ func (s *Store) runMigrations() error {
// Ignore errors from already-applied migrations (duplicate column).
_, _ = s.db.Exec(m)
}
// Create indexes on foreign key columns for query performance.
indexes := []string{
`CREATE INDEX IF NOT EXISTS idx_instances_stage_id ON instances(stage_id)`,
`CREATE INDEX IF NOT EXISTS idx_instances_project_id ON instances(project_id)`,
`CREATE INDEX IF NOT EXISTS idx_deploys_project_id ON deploys(project_id)`,
`CREATE INDEX IF NOT EXISTS idx_deploys_stage_id ON deploys(stage_id)`,
`CREATE INDEX IF NOT EXISTS idx_deploy_logs_deploy_id ON deploy_logs(deploy_id)`,
`CREATE INDEX IF NOT EXISTS idx_stages_project_id ON stages(project_id)`,
`CREATE INDEX IF NOT EXISTS idx_stage_env_stage_id ON stage_env(stage_id)`,
`CREATE INDEX IF NOT EXISTS idx_volumes_project_id ON volumes(project_id)`,
}
for _, idx := range indexes {
if _, err := s.db.Exec(idx); err != nil {
return fmt.Errorf("create index: %w", err)
}
}
return nil
}
@@ -224,7 +246,7 @@ CREATE TABLE IF NOT EXISTS volumes (
);
`
// now returns the current time formatted for SQLite storage.
func now() string {
// Now returns the current time formatted for SQLite storage.
func Now() string {
return time.Now().UTC().Format("2006-01-02 15:04:05")
}
+4 -4
View File
@@ -31,7 +31,7 @@ type AuthSettings struct {
// CreateUser inserts a new user record.
func (s *Store) CreateUser(u User) (User, error) {
u.ID = uuid.New().String()
u.CreatedAt = now()
u.CreatedAt = Now()
u.UpdatedAt = u.CreatedAt
_, err := s.db.Exec(
@@ -88,7 +88,7 @@ func (s *Store) GetAllUsers() ([]User, error) {
}
defer rows.Close()
var users []User
users := []User{}
for rows.Next() {
var u User
if err := rows.Scan(&u.ID, &u.Username, &u.PasswordHash, &u.Email, &u.Role, &u.CreatedAt, &u.UpdatedAt); err != nil {
@@ -101,7 +101,7 @@ func (s *Store) GetAllUsers() ([]User, error) {
// UpdateUser updates a user's mutable fields (username, email, role).
func (s *Store) UpdateUser(u User) error {
u.UpdatedAt = now()
u.UpdatedAt = Now()
result, err := s.db.Exec(
`UPDATE users SET username=?, email=?, role=?, updated_at=? WHERE id=?`,
u.Username, u.Email, u.Role, u.UpdatedAt, u.ID,
@@ -118,7 +118,7 @@ func (s *Store) UpdateUser(u User) error {
// UpdateUserPassword updates a user's password hash.
func (s *Store) UpdateUserPassword(id string, passwordHash string) error {
ts := now()
ts := Now()
result, err := s.db.Exec(
`UPDATE users SET password_hash=?, updated_at=? WHERE id=?`,
passwordHash, ts, id,
+3 -3
View File
@@ -11,7 +11,7 @@ import (
// CreateVolume inserts a new volume configuration for a project.
func (s *Store) CreateVolume(vol Volume) (Volume, error) {
vol.ID = uuid.New().String()
vol.CreatedAt = now()
vol.CreatedAt = Now()
vol.UpdatedAt = vol.CreatedAt
if vol.Mode == "" {
@@ -41,7 +41,7 @@ func (s *Store) GetVolumesByProjectID(projectID string) ([]Volume, error) {
}
defer rows.Close()
var vols []Volume
vols := []Volume{}
for rows.Next() {
vol, err := scanVolume(rows)
if err != nil {
@@ -71,7 +71,7 @@ func (s *Store) GetVolumeByID(id string) (Volume, error) {
// UpdateVolume updates an existing volume configuration.
func (s *Store) UpdateVolume(vol Volume) error {
vol.UpdatedAt = now()
vol.UpdatedAt = Now()
result, err := s.db.Exec(
`UPDATE volumes SET source=?, target=?, mode=?, updated_at=?
WHERE id=?`,