161 lines
5.3 KiB
Go
161 lines
5.3 KiB
Go
package server
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"git.a-wan.net/alan/pipelines/internal/protocol"
|
|
"github.com/yuin/goldmark"
|
|
"github.com/yuin/goldmark/extension"
|
|
)
|
|
|
|
const reportLimit = 2 << 20
|
|
|
|
// renderReport is deterministic and deliberately structural: no factual or
|
|
// completion validation is implied. Raw HTML is disabled by Goldmark's default
|
|
// renderer; the document has no scripts, stylesheets or remote dependencies.
|
|
func renderReport(format string, output map[string]any) (string, []byte, error) {
|
|
if err := protocol.ValidateOutputFormat(format); err != nil {
|
|
return "", nil, err
|
|
}
|
|
var markdown string
|
|
for _, key := range []string{"markdown", "report", "result", "summary", "message"} {
|
|
if text, ok := output[key].(string); ok && strings.TrimSpace(text) != "" {
|
|
markdown = text
|
|
break
|
|
}
|
|
}
|
|
if strings.TrimSpace(markdown) == "" {
|
|
return "", nil, fmt.Errorf("requested report requires nonempty textual output (markdown, report, result, summary or message)")
|
|
}
|
|
if len(markdown) > reportLimit {
|
|
return "", nil, fmt.Errorf("report source exceeds size limit")
|
|
}
|
|
if format == "markdown" {
|
|
return "report.md", []byte(markdown), nil
|
|
}
|
|
var body bytes.Buffer
|
|
if err := goldmark.New(goldmark.WithExtensions(extension.GFM)).Convert([]byte(markdown), &body); err != nil {
|
|
return "", nil, err
|
|
}
|
|
// No external resources are fetched even if markdown includes image links.
|
|
doc := "<!doctype html>\n<html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width\"><meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; style-src 'unsafe-inline'; img-src data:; base-uri 'none'; form-action 'none'\"><title>Run report</title><style>body{max-width:70rem;margin:3rem auto;padding:0 1.5rem;font:18px/1.6 system-ui}pre{white-space:pre-wrap}img{max-width:100%}table{border-collapse:collapse}td,th{border:1px solid;padding:.4rem}</style></head><body><main>" + body.String() + "</main></body></html>\n"
|
|
if len(doc) > reportLimit {
|
|
return "", nil, fmt.Errorf("rendered report exceeds size limit")
|
|
}
|
|
return "report.html", []byte(doc), nil
|
|
}
|
|
|
|
// finalizeDeliverable runs before the successful terminal store transition.
|
|
// Fixed names and os.Root keep writes confined even if a stage left symlinks.
|
|
// Existing files (including model-created reports) are never overwritten.
|
|
func (r *runner) finalizeDeliverable(ctx context.Context, id int64, sequence int, output map[string]any) error {
|
|
detail, err := r.store.GetRun(ctx, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if detail.OutputFormat == "" {
|
|
return nil
|
|
}
|
|
if detail.Status != protocol.RunStatusQueued && detail.Status != protocol.RunStatusRunning {
|
|
return nil // never create evidence for an already-settled/canceled run
|
|
}
|
|
if sequence <= 0 {
|
|
return fmt.Errorf("requested report has no completed visit")
|
|
}
|
|
name, body, err := renderReport(detail.OutputFormat, output)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
var visit *protocol.RunStep
|
|
for i := range detail.Steps {
|
|
if detail.Steps[i].Sequence == sequence {
|
|
visit = &detail.Steps[i]
|
|
break
|
|
}
|
|
}
|
|
if visit == nil || visit.Status != "completed" {
|
|
return fmt.Errorf("requested report has no completed terminal visit")
|
|
}
|
|
var inventoried int64
|
|
for _, file := range visit.Artifacts {
|
|
inventoried += file.SizeBytes
|
|
}
|
|
if len(visit.Artifacts) >= maxArtifactFiles || inventoried+int64(len(body)) > maxArtifactTotalBytes {
|
|
return fmt.Errorf("requested report exceeds artifact inventory bounds")
|
|
}
|
|
root, err := os.OpenRoot(r.artifactsRoot)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer root.Close()
|
|
run := strconv.FormatInt(id, 10)
|
|
public := filepath.Join(run, "public")
|
|
// Refuse symlinked directories, rather than using another visit's files.
|
|
for _, dir := range []string{run, public} {
|
|
info, err := root.Lstat(dir)
|
|
if os.IsNotExist(err) {
|
|
err = root.Mkdir(dir, 0755)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
continue
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !info.IsDir() || info.Mode()&os.ModeSymlink != 0 {
|
|
return fmt.Errorf("report directory is not a normal directory")
|
|
}
|
|
}
|
|
target := filepath.Join(public, name)
|
|
file, err := root.OpenFile(target, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
|
|
if err != nil {
|
|
return fmt.Errorf("create requested report: %w", err)
|
|
}
|
|
written, writeErr := file.Write(body)
|
|
if writeErr == nil && written != len(body) {
|
|
writeErr = io.ErrShortWrite
|
|
}
|
|
if writeErr == nil {
|
|
writeErr = file.Sync()
|
|
}
|
|
closeErr := file.Close()
|
|
if writeErr != nil {
|
|
return writeErr
|
|
}
|
|
if closeErr != nil {
|
|
return closeErr
|
|
}
|
|
info, err := root.Lstat(target)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !info.Mode().IsRegular() || info.Size() <= 0 || info.Size() > reportLimit {
|
|
return fmt.Errorf("requested report is missing, empty, not a normal file or oversized")
|
|
}
|
|
check, err := root.Open(target)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
actual, err := io.ReadAll(io.LimitReader(check, reportLimit+1))
|
|
check.Close()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !bytes.Equal(actual, body) {
|
|
return fmt.Errorf("requested report changed during verification")
|
|
}
|
|
contentType := "text/markdown; charset=utf-8"
|
|
if detail.OutputFormat == "html" {
|
|
contentType = "text/html; charset=utf-8"
|
|
}
|
|
return r.store.RecordDeliverable(ctx, id, sequence, protocol.StageArtifact{Name: "public/" + name, SizeBytes: info.Size(), ContentType: contentType, URL: artifactURL(id, sequence, "public/"+name)})
|
|
}
|