package isolation import ( "context" "encoding/json" "errors" "fmt" "io" "net/http" "os" "path/filepath" "regexp" "sea-vhost/internal/hosting" "strings" "time" ) type WebsiteSpec struct { Project ProjectSpec `json:"project"` SiteName string `json:"siteName"` Domain string `json:"domain"` Runtime string `json:"runtime"` Settings hosting.WebsiteSettings `json:"settings"` } type SiteLogSpec struct { Project ProjectSpec `json:"project"` SiteName string `json:"siteName"` Domain string `json:"domain"` Kind string `json:"kind"` Lines int `json:"lines"` Search string `json:"search"` } type SiteLog struct { Available bool `json:"available"` Lines []string `json:"lines"` Truncated bool `json:"truncated"` } type SiteOperations interface { ConfigureWebsite(context.Context, WebsiteSpec) error ReadSiteLog(context.Context, SiteLogSpec) (SiteLog, error) } func (c *Client) ConfigureWebsite(ctx context.Context, v WebsiteSpec) error { return c.request(ctx, "/v1/site/settings", v, nil) } func (c *Client) ReadSiteLog(ctx context.Context, v SiteLogSpec) (SiteLog, error) { var out SiteLog e := c.request(ctx, "/v1/site/log", v, &out) return out, e } func (Mock) ConfigureWebsite(context.Context, WebsiteSpec) error { return nil } func (Mock) ReadSiteLog(context.Context, SiteLogSpec) (SiteLog, error) { return SiteLog{Available: true, Lines: []string{}}, nil } func (a Agent) configureWebsite(w http.ResponseWriter, r *http.Request) { var v WebsiteSpec d := json.NewDecoder(r.Body) d.DisallowUnknownFields() if d.Decode(&v) != nil || d.Decode(&struct{}{}) != io.EOF || !phpSiteNamePattern.MatchString(v.SiteName) || !webDomainPattern.MatchString(v.Domain) || v.Settings.Validate() != nil { http.Error(w, "invalid website settings", 400) return } if v.Runtime != "PHP" && v.Settings.Rewrite != "none" { http.Error(w, "rewrite templates require PHP", 422) return } paths, e := a.webProtectionPaths(WebProtectionSpec{Project: v.Project, Domain: v.Domain}) if e != nil || verifySiteExtensionInclude(paths.siteConfig, paths.siteExtension) != nil { http.Error(w, "managed site unavailable", 412) return } raw, e := os.ReadFile(paths.siteConfig) root, _ := a.projectPath(v.Project) if e != nil || !strings.Contains(string(raw), root) { http.Error(w, "website does not match host root", 412) return } content := regexp.MustCompile(`(?m)^[ \t]*index\s+[^;\n]+;[ \t]*\r?\n?`).ReplaceAllString(string(raw), "") content = regexp.MustCompile(`(?m)^[ \t]*error_page\s+(?:404|503)\s+[^;\n]+;[ \t]*\r?\n?`).ReplaceAllString(content, "") restoreMain, e := writeManagedFile(paths.siteConfig, []byte(content)) if e != nil { http.Error(w, "cannot stage website config", 412) return } restoreSettings, e := writeManagedFile(filepath.Join(filepath.Dir(paths.siteExtension), "sea-vhost-site.conf"), []byte(renderWebsite(v.Settings))) if e != nil { restoreMain() http.Error(w, "cannot stage settings", 412) return } ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) defer cancel() if a.runNginx(ctx, "-t") != nil || a.runNginx(ctx, "-s", "reload") != nil { restoreSettings() restoreMain() _ = a.runNginx(ctx, "-t") _ = a.runNginx(ctx, "-s", "reload") http.Error(w, "Nginx rejected settings; previous config restored", 422) return } w.WriteHeader(200) } func renderWebsite(v hosting.WebsiteSettings) string { var b strings.Builder b.WriteString("# Managed by Sea vHost\nindex " + strings.Join(v.Index, " ") + ";\n") if v.Error404 != "" { fmt.Fprintf(&b, "error_page 404 /%s;\n", v.Error404) } if v.Error503 != "" { fmt.Fprintf(&b, "error_page 503 /%s;\n", v.Error503) } if v.ForceHTTPS { b.WriteString("set $svh_https_redirect 0;\nif ($scheme = http) { set $svh_https_redirect 1; }\nif ($uri ~ ^/\\.well-known/acme-challenge/) { set $svh_https_redirect 0; }\nif ($svh_https_redirect = 1) { return 301 https://$host$request_uri; }\n") } if v.Maintenance { exclude := "^/(?:\\.well-known/acme-challenge/" if v.Error503 != "" { exclude += "|" + regexp.QuoteMeta(v.Error503) + "$" } exclude += ")" fmt.Fprintf(&b, "if ($uri !~ %s) { return 503; }\n", exclude) } if v.RedirectURL != "" { fmt.Fprintf(&b, "if ($uri !~ ^/\\.well-known/acme-challenge/) { return %d %s; }\n", v.RedirectCode, v.RedirectURL) } switch v.Rewrite { case "wordpress", "laravel": b.WriteString("location / { try_files $uri $uri/ /index.php?$query_string; }\n") case "thinkphp": b.WriteString("location / { try_files $uri $uri/ /index.php?s=$uri&$args; }\n") case "spa": b.WriteString("location / { try_files $uri $uri/ /index.html; }\n") } return b.String() } var logBearer = regexp.MustCompile(`(?i)(authorization["' :=]+)(?:bearer|basic) +[^\s,;"']+`) var logSecret = regexp.MustCompile(`(?i)(password|passwd|secret|token|authorization)(["' :=]+)([^\s&,;"']+)`) func (a Agent) readSiteLog(w http.ResponseWriter, r *http.Request) { var v SiteLogSpec d := json.NewDecoder(r.Body) d.DisallowUnknownFields() if d.Decode(&v) != nil || d.Decode(&struct{}{}) != io.EOF || !phpSiteNamePattern.MatchString(v.SiteName) || !webDomainPattern.MatchString(v.Domain) || len(v.Search) > 200 { http.Error(w, "invalid log request", 400) return } root, e := a.projectPath(v.Project) if e != nil || requirePhysicalDirectory(root) != nil { http.Error(w, "host unavailable", 412) return } dir := a.NginxLogRoot if dir == "" { dir = "/www/wwwlogs" } name := v.Domain + ".log" switch v.Kind { case "access": case "error": name = v.Domain + ".error.log" case "runtime": dir = root name = ".sea-runtime/logs/" + v.SiteName + ".log" case "php": dir = root name = ".sea-runtime/php/fpm-error.log" default: http.Error(w, "invalid log kind", 400) return } result, e := tailSiteLog(dir, name, v.Lines, v.Search) if e != nil { http.Error(w, "cannot safely read site log", 422) return } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(result) } func tailSiteLog(dir, name string, lines int, search string) (SiteLog, error) { out := SiteLog{Lines: []string{}} if lines < 1 || lines > 1000 { lines = 200 } root, e := os.OpenRoot(dir) if e != nil { return out, e } defer root.Close() i, e := root.Lstat(name) if errors.Is(e, os.ErrNotExist) { return out, nil } if e != nil || !i.Mode().IsRegular() || i.Mode()&os.ModeSymlink != 0 { return out, errors.New("unsafe log") } f, e := root.Open(name) if e != nil { return out, e } defer f.Close() size := i.Size() offset := int64(0) if size > 256<<10 { offset = size - (256 << 10) out.Truncated = true } f.Seek(offset, io.SeekStart) raw, e := io.ReadAll(io.LimitReader(f, 256<<10)) if e != nil { return out, e } text := strings.ToValidUTF8(string(raw), "�") all := strings.Split(strings.TrimSuffix(text, "\n"), "\n") if offset > 0 && len(all) > 0 { all = all[1:] } for _, line := range all { if search == "" || strings.Contains(strings.ToLower(line), strings.ToLower(search)) { out.Lines = append(out.Lines, logSecret.ReplaceAllString(logBearer.ReplaceAllString(line, "${1}[REDACTED]"), "${1}${2}[REDACTED]")) } } if len(out.Lines) > lines { out.Lines = out.Lines[len(out.Lines)-lines:] out.Truncated = true } out.Available = true return out, nil }