Files
tiny-forge/internal/volume/resolver.go
alexei.dolgolyov 739b67856a
Build / build (push) Successful in 10m39s
feat(cutover): hard legacy cutover — drop projects/stacks/sites/deploys
The clean-break delete that closes the workload-first refactor arc.
Net diff: ~30 backend files deleted, ~20 modified, ~12k LOC removed
on the Go side; entire /projects /stacks /sites /deploy frontend
trees gone; ~6.7k LOC removed on the Svelte/TypeScript side.

Backend
- API handlers gone: internal/api/{projects,stages,stage_env,stacks,
  static_sites,deploys,instances,volume_browser}.go
- Store CRUD + tests gone: internal/store/{projects,stages,stage_env,
  stacks,static_sites,static_site_secrets,deploys,poll_state,volumes,
  workload_sync}.go (+ _test.go siblings)
- Legacy deployer pipeline gone: internal/deployer/{bluegreen,promote,
  rollback,subdomain,resolver_test}.go; deployer.go trimmed to just the
  dispatch surface used by the plugin pipeline
- internal/staticsite/{manager,healthcheck}.go and
  internal/stack/manager.go gone (the rest of those packages stay as
  helpers imported by the static + compose plugins)
- internal/registry/poller.go gone (legacy registry poller)
- internal/volume.ResolvePath gone; ResolveWorkloadPath stays
- internal/webhook: handleWebhook (project) + handleSiteWebhook (site)
  gone; only POST /api/webhook/triggers/{secret} remains
- workload-side webhook URL handlers (getWorkloadWebhook +
  regenerateWorkloadWebhook + EnsureWorkloadWebhookSecret +
  SetWorkloadWebhookSecret + GetWorkloadByWebhookSecret) gone — they
  minted URLs that would 404 against the new trigger-only ingress
- cmd/server/main.go: dropped staticsite.Manager, stack.Manager,
  staticsite.HealthChecker, registry poller, SetSiteSyncTriggerer,
  SetStaticSiteManager, SetStackManager, wireStaticBackend
- store/store.go: idempotent DROP TABLE IF EXISTS for every legacy
  table (projects, stages, stage_env, volumes, deploys, deploy_logs,
  poll_states, stacks, stack_revisions, stack_deploys, static_sites,
  static_site_secrets); FK order children-then-parents
- store/models.go: dropped Project, Stage, Deploy, DeployLog, StageEnv,
  Volume, StaticSite, StaticSiteSecret, Stack, StackRevision,
  StackDeploy types; kept WorkloadKind constants as documented strings
- internal/store/helpers.go (new): BoolToInt, rowScanner,
  GenerateWebhookSecret extracted from deleted CRUD files
- internal/api/secrets.go (new): forwards to store.GenerateWebhookSecret
  so api + store paths share one secret-generation impl (no
  panic-vs-UUID-fallback divergence)
- internal/reconciler/reconciler.go: dropped legacy stack-by-compose
  + static-site label paths; only canonical tinyforge.workload.id
  dispatch remains
- providers (gitea_content/github_provider/gitlab_provider) gained
  path-traversal rejection on every tree entry
- internal/webhook ParsedImage / ParseImageRef demoted to package-
  private (no external callers)

Frontend
- /projects /stacks /sites /deploy routes deleted (entire trees)
- ProjectCard / InstanceCard / StaleContainerCard components deleted
- api.ts: dropped every project/stage/stack/site/deploy/instance
  helper + types (Project, Stage, Stack, StaticSite, Deploy,
  Instance, Volume, etc.); kept Workload, Container, App, Settings,
  Registry, EventTrigger, LogScanRule, webhook envelopes
- WorkloadWebhook type + getWorkloadWebhook/regenerateWorkloadWebhook
  api functions gone (mirror of the backend deletion above)
- web/src/routes/+layout.svelte: dropped /projects /sites /stacks
  /deploy nav entries, trimmed quick-nav keymap
- web/src/routes/+page.svelte: dashboard rewrite — reads
  listWorkloads + listContainers only; 4-card stat grid
  (workloads/running/failed/stale) + recent workloads strip
- navCounts.ts, SystemHealthCard.svelte, ContainerLogs.svelte,
  ContainerStats.svelte, StatusBadge.svelte, TagCombobox.svelte,
  proxies/+page.svelte, containers/+page.svelte all rewired to the
  workload-first surface
- AbortController plumbing on dashboard, nav-counts, stale page,
  SystemHealthCard so navigation doesn't leave dangling fetches
- i18n: dropped projects.*, projectDetail.*, envEditor.*,
  volumeEditor.*, volumeBrowser.*, quickDeploy.*, sites.*, stacks.*,
  instance.*, confirm.* namespaces; en/ru parity preserved (1042
  keys each)

Hardening from go-reviewer + security-reviewer + typescript-reviewer
subagent passes (0 CRITICAL across all three; 1 HIGH + ~12 MEDIUM
addressed inline before commit):

- Sec H1: dead-end workload webhook URL handlers (would mint URLs
  that 404 the new trigger-only ingress) deleted across backend +
  frontend
- Go M1: IsTerminalDeployStatus dropped (no production callers)
- Go M2: ParsedImage/ParseImageRef lowercased (in-package only)
- Go M6: generateWebhookSecret unified — api shim forwards to
  store.GenerateWebhookSecret
- Doc/comment freshness: stage_id (no longer FK), ProxyRoute legacy
  field names, workloadIDRow rationale, webhook_deliveries.target_type
  enum, WebhookDeliveryLog component header

Doc
- WORKLOAD_REFACTOR_TODO: cutover marked DONE; all three Priority 1
  items are now shipped. Next focus is Priority 3 polish (apps.* i18n
  + codemap entries) and Priority 4 tests.

Behavioral notes for operators upgrading from a pre-cutover build
- Existing rows in the dropped tables disappear on first boot.
- Legacy webhook URLs at /api/webhook/{secret} and
  /api/webhook/sites/{secret} return 404; CI configs must repoint to
  /api/webhook/triggers/{secret} (the trigger-split boot backfill
  lifted any embedded workload secret onto a Trigger row, so the
  secret value itself carries over).
- Frontend routes /projects /stacks /sites /deploy are gone; nav
  links replaced with /apps and /triggers.
2026-05-16 06:00:21 +03:00

177 lines
6.1 KiB
Go

package volume
import (
"encoding/json"
"fmt"
"path/filepath"
"regexp"
"strings"
"github.com/alexei/tinyforge/internal/store"
)
// resolveAbsolute validates that the source path is under one of the allowed prefixes.
func resolveAbsolute(source, allowedPathsJSON string) (string, error) {
if source == "" {
return "", fmt.Errorf("absolute scope requires a source path")
}
cleaned := filepath.Clean(source)
if !filepath.IsAbs(cleaned) {
return "", fmt.Errorf("absolute scope requires an absolute source path (starting with /)")
}
allowed, err := parseAllowedPaths(allowedPathsJSON)
if err != nil {
return "", fmt.Errorf("failed to parse allowed volume paths: %w", err)
}
if len(allowed) == 0 {
return "", fmt.Errorf("absolute volume paths are disabled (no allowed paths configured in settings)")
}
for _, prefix := range allowed {
prefixClean := filepath.Clean(prefix)
if strings.HasPrefix(cleaned, prefixClean+string(filepath.Separator)) || cleaned == prefixClean {
return cleaned, nil
}
}
return "", fmt.Errorf("path %q is not under any allowed volume path", source)
}
// parseAllowedPaths parses a JSON array of path strings.
func parseAllowedPaths(jsonStr string) ([]string, error) {
if jsonStr == "" || jsonStr == "[]" {
return nil, nil
}
var paths []string
if err := json.Unmarshal([]byte(jsonStr), &paths); err != nil {
return nil, err
}
return paths, nil
}
// ParseAllowedPaths is the exported version for use in API validation.
func ParseAllowedPaths(jsonStr string) ([]string, error) {
return parseAllowedPaths(jsonStr)
}
// ResolveWorkloadParams holds the parameters needed to resolve a
// workload-volume's host path. Unlike ResolveParams it is keyed on the
// workload identity (name + id) rather than the legacy project/stage
// dual-key, so it survives the Workload-first cutover.
type ResolveWorkloadParams struct {
BasePath string
WorkloadID string
WorkloadName string
ImageTag string // required for "instance" scope only
AllowedVolumePaths string // JSON array of allowed absolute paths
}
// ResolveWorkloadPath returns the absolute host path for a WorkloadVolume.
// Scope semantics map onto the workload-first model:
//
// - absolute — host bind, must lie under settings.AllowedVolumePaths.
// - ephemeral — caller renders this as tmpfs; the function returns an
// error because there is no host path.
// - instance — per-tag isolation under <workload>/instance-<tag>/<source>.
// Useful for blue-green when each running instance needs its own dir.
// - stage, project — both legacy names collapse to "shared across all
// instances of this workload" under <workload>/<source>. Two names
// for one shape is intentional: it lets legacy data migrate without
// a path rewrite.
// - project_named — workload-scoped named volume under
// <workload>/_named/<name>/<source>.
// - named — globally-scoped named volume under
// _named/<name>/<source>.
//
// The <workload> directory segment is `<sanitized-name>-<short-id>`. The
// short-id suffix prevents collisions when two workloads share a name
// (the workloads table only enforces uniqueness on (kind, ref_id)).
func ResolveWorkloadPath(vol store.WorkloadVolume, params ResolveWorkloadParams) (string, error) {
scope := vol.Scope
if scope == "" {
return "", fmt.Errorf("workload volume: scope is required")
}
if scope == string(store.VolumeScopeEphemeral) {
return "", fmt.Errorf("ephemeral volumes have no host path")
}
if scope == string(store.VolumeScopeAbsolute) {
return resolveAbsolute(vol.Source, params.AllowedVolumePaths)
}
if params.BasePath == "" {
return "", fmt.Errorf("workload volume: base path is required for scope %q", scope)
}
workloadDir, err := workloadPathSegment(params.WorkloadName, params.WorkloadID)
if err != nil {
return "", err
}
switch scope {
case string(store.VolumeScopeInstance):
if params.ImageTag == "" {
return "", fmt.Errorf("instance scope requires image tag")
}
tag := sanitizePathSegment(params.ImageTag)
if tag == "" {
return "", fmt.Errorf("instance scope requires non-empty image tag")
}
return filepath.Join(params.BasePath, workloadDir, "instance-"+tag, vol.Source), nil
case string(store.VolumeScopeStage), string(store.VolumeScopeProject):
return filepath.Join(params.BasePath, workloadDir, vol.Source), nil
case string(store.VolumeScopeProjectNamed):
name := sanitizePathSegment(vol.Name)
if name == "" {
return "", fmt.Errorf("project_named scope requires name")
}
return filepath.Join(params.BasePath, workloadDir, "_named", name, vol.Source), nil
case string(store.VolumeScopeNamed):
name := sanitizePathSegment(vol.Name)
if name == "" {
return "", fmt.Errorf("named scope requires name")
}
return filepath.Join(params.BasePath, "_named", name, vol.Source), nil
default:
return "", fmt.Errorf("unknown volume scope %q", scope)
}
}
// pathSegmentSanitizer collapses anything outside the [a-zA-Z0-9_.-] set
// to a single dash. The character set matches Docker's permissive segment
// rules; the additional Trim afterward keeps the segment from starting
// or ending with a separator.
var pathSegmentSanitizer = regexp.MustCompile(`[^a-zA-Z0-9_.-]+`)
func sanitizePathSegment(s string) string {
s = strings.TrimSpace(s)
if s == "" {
return ""
}
return strings.Trim(pathSegmentSanitizer.ReplaceAllString(s, "-"), "-")
}
// workloadPathSegment builds the per-workload directory name. The
// 8-char id-short suffix disambiguates same-named workloads — only
// (kind, ref_id) is unique at the DB level, so names alone are unsafe.
// Returns an error when both identity fields are empty, since the
// resulting path would not be workload-scoped.
func workloadPathSegment(name, id string) (string, error) {
cleanName := sanitizePathSegment(name)
idShort := id
if len(idShort) > 8 {
idShort = idShort[:8]
}
idShort = sanitizePathSegment(idShort)
if cleanName == "" && idShort == "" {
return "", fmt.Errorf("workload volume: workload id or name required")
}
if cleanName == "" {
return idShort, nil
}
if idShort == "" {
return cleanName, nil
}
return cleanName + "-" + idShort, nil
}