package daemon import ( "archive/zip" "context" "crypto/sha256" "encoding/hex" "errors" "fmt" "hash" "io" "io/fs" "mime" "net/http" "os" "path/filepath" "slices" "strings" "time" "albedo/cli/internal/daemon/protocol" ) // ExportTagger is the local redaction model as the daemon reports it. State // is absent, downloading, verifying, ready or failed; nothing downloads // until InstallExportTagger asks for it. type ExportTagger struct { State, ModelID, RulesVersion string // Name, CardURL and License describe the pinned model. Name, CardURL, License string // Host is the daemon's own name for the machine the model lives on. Host string ErrorCode, Error string // BytesTotal is the model's whole size, known before it downloads. BytesDone, BytesTotal int64 Revision int64 RuntimeAvailable bool } // Ready reports a model that can scan: installed and with its runtime. func (t ExportTagger) Ready() bool { return t.State == "ready" && t.RuntimeAvailable } // TraceExport is one redacted copy of a session's trace. State is scanning, // review, ready, failed or cancelled; only a ready export downloads, and // only ApproveTraceExport makes one ready. type TraceExport struct { CreatedAt, UpdatedAt time.Time ID, SessionID, Scope, State string // Phase is collecting, scanning or packaging while State is scanning. Phase string ModelID, RulesVersion string ErrorCode, Error string // ETag is the validator ApproveTraceExport has to send; only reads of // the single export carry it. ETag string // ArchiveSHA256 and ArchiveBytes describe the archive from review on. ArchiveSHA256 string Categories []ExportCount Omissions []ExportCount First, Upper, RequestUpper int64 // Done and Total count the Unicode scalars sent to the tagger. Done, Total int64 Findings int64 // Lines counts the redacted trace's rows from review on. Lines int64 ArchiveBytes int64 Revision int64 } // ExportCount is how many findings of one category, or omissions of one // kind, an export has. type ExportCount struct { Name string Count int64 } // ExportPreviewLine is one row of the redacted trace.jsonl, numbered from 1 // as the archive orders it, or a piece of a long row: Offset is the piece's // UTF-8 byte offset in the row and Complete marks the row's last piece. type ExportPreviewLine struct { Text string Line int64 Offset int64 Complete bool } // ExportPreview is one page of the redacted copy; Next is empty on the last. type ExportPreview struct { Next string Lines []ExportPreviewLine } // ArchiveDownload is where an export's archive was written, and its size. type ArchiveDownload struct { Path string Bytes int64 } // ErrArchiveExists refuses to write over a file the caller did not agree to // replace. var ErrArchiveExists = errors.New("a file already exists at that path") // archiveEntries are the files an export archive holds, and all it holds. var archiveEntries = []string{"manifest.json", "redaction-report.json", "trace.jsonl"} // archiveLimit bounds one downloaded archive. var archiveLimit int64 = 2 << 30 var ( taggerStates = []string{"absent", "downloading", "verifying", "ready", "failed"} exportStates = []string{"scanning", "review", "ready", "failed", "cancelled"} exportScopes = []string{"session", "turn"} ) func taggerValue(w protocol.ExportTagger) (ExportTagger, error) { if !slices.Contains(taggerStates, w.State) || w.BytesDone < 0 || w.BytesTotal < 0 { return ExportTagger{}, fieldError("tagger state") } t := ExportTagger{State: w.State, Revision: w.Revision, ModelID: w.ModelID, RulesVersion: w.RulesVersion, Name: w.Name, CardURL: w.CardURL, License: w.License, Host: w.Host, BytesDone: w.BytesDone, BytesTotal: w.BytesTotal, RuntimeAvailable: w.Runtime.Available} if w.Error != nil { t.ErrorCode, t.Error = w.Error.Code, w.Error.Detail } return t, nil } func exportValue(w protocol.ExportJob) (TraceExport, error) { if w.ID == "" || w.SessionID == "" || !slices.Contains(exportStates, w.State) || !slices.Contains(exportScopes, w.Scope) { return TraceExport{}, fieldError("export") } created, err := time.Parse(time.RFC3339Nano, w.CreatedAt) if err != nil { return TraceExport{}, fieldError("created_at") } updated, err := time.Parse(time.RFC3339Nano, w.UpdatedAt) if err != nil { return TraceExport{}, fieldError("updated_at") } if w.Progress.Done < 0 || w.Progress.Total < 0 || w.Findings < 0 || w.Lines < 0 { return TraceExport{}, fieldError("progress") } e := TraceExport{ID: w.ID, SessionID: w.SessionID, Scope: w.Scope, State: w.State, Phase: value(w.Phase), ModelID: w.ModelID, RulesVersion: w.RulesVersion, CreatedAt: created, UpdatedAt: updated, First: w.First, Upper: w.Upper, RequestUpper: w.RequestUpper, Done: w.Progress.Done, Total: w.Progress.Total, Findings: w.Findings, Lines: w.Lines, Revision: w.Revision} if w.Archive != nil { if w.Archive.Bytes < 0 || len(w.Archive.Sha256) != sha256.Size*2 { return TraceExport{}, fieldError("archive") } e.ArchiveBytes, e.ArchiveSHA256 = w.Archive.Bytes, strings.ToLower(w.Archive.Sha256) } if w.State == "ready" && w.Archive == nil { return TraceExport{}, fieldError("archive") } for _, c := range w.Categories { e.Categories = append(e.Categories, ExportCount{Name: c.Category, Count: c.Count}) } for _, o := range w.Omissions { e.Omissions = append(e.Omissions, ExportCount{Name: o.Kind, Count: o.Count}) } if w.Error != nil { e.ErrorCode, e.Error = w.Error.Code, w.Error.Detail } return e, nil } // taggerRequest runs one tagger route that answers with the tagger. func taggerRequest(ctx context.Context, conn *Connection, op operation, statuses []int) (ExportTagger, error) { var tagger ExportTagger decode := func(data []byte) error { var w protocol.ExportTagger if err := decodeRequired(data, &w); err != nil { return err } var err error tagger, err = taggerValue(w) return err } if statuses == nil { return tagger, executeRead(ctx, conn, op, decode) } return tagger, executeMutation(ctx, conn, op, statuses, func(data []byte, _ int) error { return decode(data) }) } // GetExportTagger reads the local redaction model's state. func GetExportTagger(ctx context.Context, conn *Connection) (ExportTagger, error) { return taggerRequest(ctx, conn, operation{Name: "read redaction model", BuildRequest: func(base string, _ io.Reader) (*http.Request, error) { return protocol.NewGetExportTaggerRequest(base) }, Policy: readRecovery}, nil) } // InstallExportTagger starts or resumes the model's download on the daemon's // machine. It is the only thing that downloads it. func InstallExportTagger(ctx context.Context, conn *Connection) (ExportTagger, error) { return taggerRequest(ctx, conn, operation{Name: "download redaction model", BuildRequest: func(base string, _ io.Reader) (*http.Request, error) { return protocol.NewInstallExportTaggerRequest(base) }, Policy: noRecovery}, []int{200, 202}) } // CancelExportTagger stops a download; verified parts stay for a resume. func CancelExportTagger(ctx context.Context, conn *Connection) (ExportTagger, error) { return taggerRequest(ctx, conn, operation{Name: "cancel redaction model download", BuildRequest: func(base string, _ io.Reader) (*http.Request, error) { return protocol.NewCancelExportTaggerRequest(base) }, Policy: noRecovery}, []int{200, 202}) } // RemoveExportTagger deletes the local model; the daemon refuses while an // export is scanning with it. func RemoveExportTagger(ctx context.Context, conn *Connection) (ExportTagger, error) { return taggerRequest(ctx, conn, operation{Name: "remove redaction model", BuildRequest: func(base string, _ io.Reader) (*http.Request, error) { return protocol.NewDeleteExportTaggerRequest(base) }, Policy: noRecovery}, []int{200}) } // exportRequest runs one route that answers with an export, checking it is // the one asked about. A read without statuses keeps the export's ETag. func exportRequest(ctx context.Context, conn *Connection, op operation, id string, statuses []int) (TraceExport, error) { var export TraceExport decode := func(data []byte) error { var w protocol.ExportJob if err := decodeRequired(data, &w); err != nil { return err } var err error if export, err = exportValue(w); err != nil { return err } if export.ID != id { return fieldError("export id") } return nil } if statuses == nil { etag := "" op.Validator = &etag err := executeRead(ctx, conn, op, decode) export.ETag = etag return export, err } return export, executeMutation(ctx, conn, op, statuses, func(data []byte, _ int) error { return decode(data) }) } // NewExportID is the id a client picks for an export, so asking again with it // returns the same export instead of starting another. func NewExportID() (string, error) { return operationID() } // CreateTraceExport starts scanning a redacted copy of session's trace: // scope is session for all of it or turn for the latest turn. A lost reply // is asked once more with the same id, which the daemon answers with the // export that id already started. func CreateTraceExport(ctx context.Context, conn *Connection, sessionID, id, scope string) (TraceExport, error) { if id == "" || !slices.Contains(exportScopes, scope) { return TraceExport{}, errors.New("an export needs an id and a scope of session or turn") } op := operation{Name: "start export", BuildRequest: func(base string, body io.Reader) (*http.Request, error) { return protocol.NewCreateExportRequestWithBody(base, sessionID, "application/json", body) }, Body: protocol.ExportCreate{ID: id, Scope: scope}, Policy: noRecovery} export, err := exportRequest(ctx, conn, op, id, []int{200, 202}) if _, uncertain := errors.AsType[*UncertainOutcomeError](err); uncertain && ctx.Err() == nil { export, err = exportRequest(ctx, conn, op, id, []int{200, 202}) } if err == nil && export.SessionID != sessionID { return TraceExport{}, &ProtocolError{Code: "invalid_response", Operation: op.Name, Field: "session_id", Cause: errors.New("the export belongs to another session")} } return export, err } // ListTraceExports lists session's exports, newest first as the daemon // orders them. func ListTraceExports(ctx context.Context, conn *Connection, sessionID string) ([]TraceExport, error) { var exports []TraceExport params := protocol.ListExportsParams{} err := walkPages(func(next *string) (protocol.ExportJobPage, *string, error) { params.Next = next var page protocol.ExportJobPage err := executeRead(ctx, conn, operation{Name: "list exports", BuildRequest: func(base string, _ io.Reader) (*http.Request, error) { return protocol.NewListExportsRequest(base, sessionID, ¶ms) }, Policy: readRecovery}, func(data []byte) error { return decodeRequired(data, &page) }) return page, page.Next, err }, func(page protocol.ExportJobPage) error { for _, w := range page.Items { export, err := exportValue(w) if err != nil { return &ProtocolError{Code: "invalid_response", Operation: "list exports", Field: "items", Cause: err} } if export.SessionID != sessionID { return &ProtocolError{Code: "invalid_response", Operation: "list exports", Field: "session_id", Cause: errors.New("an export of another session was listed")} } exports = append(exports, export) } return nil }, "export page cursor") return exports, err } // GetTraceExport reads one export with the validator approving it needs. func GetTraceExport(ctx context.Context, conn *Connection, id string) (TraceExport, error) { return exportRequest(ctx, conn, operation{Name: "read export", BuildRequest: func(base string, _ io.Reader) (*http.Request, error) { return protocol.NewGetExportRequest(base, id) }, Policy: readRecovery}, id, nil) } // GetTraceExportPreview reads one page of the redacted copy, which is the // exact trace.jsonl the archive will hold. next is empty for the first page. func GetTraceExportPreview(ctx context.Context, conn *Connection, id, next string) (ExportPreview, error) { params := protocol.PreviewExportParams{Next: optionalText(next)} var page ExportPreview err := executeRead(ctx, conn, operation{Name: "read export preview", BuildRequest: func(base string, _ io.Reader) (*http.Request, error) { return protocol.NewPreviewExportRequest(base, id, ¶ms) }, Policy: readRecovery}, func(data []byte) error { var w protocol.ExportPreviewPage if err := decodeRequired(data, &w); err != nil { return err } if w.Next != nil && (*w.Next == "" || *w.Next == next) { return fieldError("next") } page.Next = value(w.Next) for _, item := range w.Items { if item.Line < 1 || item.Offset < 0 { return fieldError("items") } page.Lines = append(page.Lines, ExportPreviewLine{Line: item.Line, Offset: item.Offset, Text: item.Text, Complete: item.Complete}) } return nil }) return page, err } // ApproveTraceExport records that the person reviewed the redacted copy at // the revision etag names, which makes it downloadable. A copy that changed // since is refused. func ApproveTraceExport(ctx context.Context, conn *Connection, id, etag string) (TraceExport, error) { if etag == "" { return TraceExport{}, errors.New("approving an export requires the revision you reviewed; refresh it first") } return exportRequest(ctx, conn, operation{Name: "approve export", BuildRequest: func(base string, body io.Reader) (*http.Request, error) { return protocol.NewApproveExportRequestWithBody(base, id, &protocol.ApproveExportParams{IfMatch: etag}, "application/json", body) }, Headers: http.Header{"If-Match": {etag}}, Body: protocol.ExportApprove{Reviewed: true}, Policy: noRecovery}, id, []int{200}) } // CancelTraceExport stops a scan; nothing of it can be downloaded after. func CancelTraceExport(ctx context.Context, conn *Connection, id string) (TraceExport, error) { return exportRequest(ctx, conn, operation{Name: "cancel export", BuildRequest: func(base string, _ io.Reader) (*http.Request, error) { return protocol.NewCancelExportRequest(base, id) }, Policy: noRecovery}, id, []int{200, 202}) } // DeleteTraceExport removes the redacted copy; the session is untouched. func DeleteTraceExport(ctx context.Context, conn *Connection, id string) error { return executeMutation(ctx, conn, operation{Name: "delete export", BuildRequest: func(base string, _ io.Reader) (*http.Request, error) { return protocol.NewDeleteExportRequest(base, id) }, Policy: noRecovery}, []int{200, 204}, func([]byte, int) error { return nil }) } // ArchivePath resolves where the person asked an archive to go: ~ is their // home, and a relative path is under the working directory. It reports // whether a file is already there, and refuses a directory or a folder that // does not exist. func ArchivePath(input string) (string, bool, error) { path := strings.TrimSpace(input) if path == "" { return "", false, errors.New("choose where to save the archive") } if path == "~" || strings.HasPrefix(path, "~/") { home, err := os.UserHomeDir() if err != nil { return "", false, err } path = filepath.Join(home, path[1:]) } path, err := filepath.Abs(path) if err != nil { return "", false, err } if info, statErr := os.Stat(filepath.Dir(path)); statErr != nil || !info.IsDir() { return "", false, fmt.Errorf("no folder %s", filepath.Dir(path)) } info, err := os.Lstat(path) switch { case errors.Is(err, fs.ErrNotExist): return path, false, nil case err != nil: return "", false, err case info.IsDir(): return "", false, fmt.Errorf("%s is a folder; name the archive file", path) } return path, true, nil } // DownloadTraceExport streams a ready export's archive to path, which // ArchivePath resolved. The bytes go to a private temporary file beside it; // a cut-off transfer resumes with a range request against the same archive. // The file must have the export's size and sha256 and hold the archive's // three entries and nothing else before it takes the path. A file already // there is replaced only when replace says the person agreed. A failure or // cancel leaves nothing behind. progress, when given, hears the bytes // written and the archive's size. func DownloadTraceExport(ctx context.Context, conn *Connection, export TraceExport, path string, replace bool, progress func(done, total int64)) (ArchiveDownload, error) { switch { case conn == nil: return ArchiveDownload{}, errors.New("not connected to Albedo") case export.State != "ready" || export.ArchiveSHA256 == "": return ArchiveDownload{}, errors.New("only an approved export can be downloaded") case export.ArchiveBytes > archiveLimit: return ArchiveDownload{}, fmt.Errorf("the archive is %d bytes, more than this client's limit of %d", export.ArchiveBytes, archiveLimit) case !filepath.IsAbs(path): return ArchiveDownload{}, errors.New("the archive path must be absolute") } file, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".*.partial") if err != nil { return ArchiveDownload{}, err } temporary := file.Name() defer func() { if file != nil { _ = file.Close() } if err != nil { _ = os.Remove(temporary) } }() d := &archiveDownload{file: file, sum: sha256.New(), total: export.ArchiveBytes, report: progress, id: export.ID, etag: `"sha256-` + export.ArchiveSHA256 + `"`} op := operation{Name: "download export", Policy: readRecovery} for attempt := 0; ; attempt++ { err = d.fetch(ctx, conn, op) resumable := &resumableError{} if err == nil || !errors.As(err, &resumable) || attempt == 2 || ctx.Err() != nil { break } } if err != nil { return ArchiveDownload{}, errors.Join(err, ctx.Err()) } if got := hex.EncodeToString(d.sum.Sum(nil)); got != export.ArchiveSHA256 { err = errors.New("the archive does not match the sha256 the daemon reported") return ArchiveDownload{}, err } if err = checkArchive(file, d.written); err != nil { return ArchiveDownload{}, err } if err = file.Sync(); err != nil { return ArchiveDownload{}, err } closed := file.Close() file = nil if err = closed; err != nil { return ArchiveDownload{}, err } if err = placeArchive(temporary, path, replace); err != nil { return ArchiveDownload{}, err } return ArchiveDownload{Path: path, Bytes: d.written}, nil } // placeArchive gives the checked file its name. Without replace a hard link // takes the name only while it is free, so a file that appeared meanwhile // is kept. func placeArchive(temporary, path string, replace bool) error { if replace { return os.Rename(temporary, path) } err := os.Link(temporary, path) if errors.Is(err, fs.ErrExist) { return ErrArchiveExists } if err != nil { return err } return os.Remove(temporary) } // archiveDownload is one archive arriving in a private file, possibly over // several requests. type archiveDownload struct { file *os.File sum hash.Hash report func(done, total int64) // failed is the local file's write failure, which no retry mends. failed error id string etag string written int64 total int64 } // resumableError is a transfer that broke off and may continue from the // bytes already written. type resumableError struct{ cause error } func (e *resumableError) Error() string { return e.cause.Error() } func (e *resumableError) Unwrap() error { return e.cause } // fetch asks for the rest of the archive and appends it. A daemon that // answers a range request with the whole archive starts the file again. func (d *archiveDownload) fetch(ctx context.Context, conn *Connection, op operation) error { params := protocol.DownloadExportParams{} if d.written > 0 { params.Range, params.IfRange = new(fmt.Sprintf("bytes=%d-", d.written)), &d.etag } op.BuildRequest = func(base string, _ io.Reader) (*http.Request, error) { return protocol.NewDownloadExportRequest(base, d.id, ¶ms) } snapshot, err := conn.operationEndpoint(op) if err != nil { return err } req, err := operationRequest(ctx, snapshot, op, nil) if err != nil { return err } req.Header.Set("Accept", "application/zip") // Identity keeps Content-Length, which tells a cut-off body apart. req.Header.Set("Accept-Encoding", "identity") res, err := conn.HTTPClient().Do(req) if err == nil && res.StatusCode != http.StatusOK && res.StatusCode != http.StatusPartialContent { err = readHTTPError(res, 64*1024) _ = res.Body.Close() } if err != nil { recovered, recoveryErr := recoverOperation(ctx, conn, op, snapshot, err, 0) if recoveryErr != nil { return recoveryErr } if recovered { return &resumableError{err} } return err } defer res.Body.Close() if media, _, _ := mime.ParseMediaType(res.Header.Get("Content-Type")); media != "application/zip" { return &ProtocolError{Code: "invalid_response", Operation: op.Name, Field: "content type", Cause: fmt.Errorf("expected application/zip, got %q", res.Header.Get("Content-Type"))} } if etag := res.Header.Get("ETag"); etag != "" && etag != d.etag { return errors.New("the daemon is serving a different archive than the one approved") } if res.StatusCode == http.StatusPartialContent { var from int64 if _, scanErr := fmt.Sscanf(res.Header.Get("Content-Range"), "bytes %d-", &from); scanErr != nil || from != d.written { return &ProtocolError{Code: "invalid_response", Operation: op.Name, Field: "content range", Cause: fmt.Errorf("asked from byte %d, got %q", d.written, res.Header.Get("Content-Range"))} } } else if d.written > 0 { if err = d.restart(); err != nil { return err } } _, err = io.Copy(d, io.LimitReader(res.Body, d.total-d.written+1)) switch { case d.failed != nil: return d.failed case d.written > d.total: return fmt.Errorf("the archive is longer than the %d bytes the daemon reported", d.total) case err != nil: return &resumableError{fmt.Errorf("the archive download stopped after %d of %d bytes: %w", d.written, d.total, err)} case d.written < d.total: return &resumableError{fmt.Errorf("the archive download stopped after %d of %d bytes", d.written, d.total)} } return nil } // restart empties the file for an archive sent again from its start. func (d *archiveDownload) restart() error { if _, err := d.file.Seek(0, io.SeekStart); err != nil { return err } if err := d.file.Truncate(0); err != nil { return err } d.sum.Reset() d.written = 0 return nil } func (d *archiveDownload) Write(p []byte) (int, error) { n, err := d.file.Write(p) if err != nil { d.failed = err } d.sum.Write(p[:n]) d.written += int64(n) if d.report != nil { d.report(d.written, d.total) } return n, err } // checkArchive is the archive's own check: a zip of exactly the entries an // export has. func checkArchive(file *os.File, size int64) error { archive, err := zip.NewReader(file, size) if err != nil { return fmt.Errorf("the download is not a readable archive: %w", err) } var names []string for _, entry := range archive.File { names = append(names, entry.Name) } slices.Sort(names) if !slices.Equal(names, archiveEntries) { return fmt.Errorf("the archive holds %s, not %s", strings.Join(names, ", "), strings.Join(archiveEntries, ", ")) } return nil }