536 lines
18 KiB
Go
536 lines
18 KiB
Go
package server
|
|
|
|
import (
|
|
"archive/tar"
|
|
"bytes"
|
|
"compress/gzip"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
"path"
|
|
"path/filepath"
|
|
"regexp"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"git.breakpilot.com/platform/tenant-registry/internal/store"
|
|
)
|
|
|
|
// Staff import of a document store bundle (POST /v1/admin/tenants/{id}/store/import):
|
|
// a .tar.gz in the layout of the Factory's serving and chunk runs —
|
|
//
|
|
// LANE_B_INDEX_V1.json the documents (id, digest, title, folder)
|
|
// objects/<sha256>.(pdf|html|txt) the originals
|
|
// presentation/CONSENT_BANNER_CAPTURES_V1.json which document has which capture
|
|
// presentation/consent_banner/<sha256>.json the captures
|
|
// chunks/<tenant_document_id>.json the prepared versions (LANE_B_UNIFIED_V5)
|
|
// figure_assets/sources/sha256/<sha256>.<ext> their images
|
|
// LANE_B_UNIFIED_V5_RETURN_MANIFEST_V1.json optional: pin (its digest) and revision
|
|
//
|
|
// Every file is checked against the digest it is named by; a document whose
|
|
// original does not match is rejected, a prepared version with a missing or
|
|
// wrong image is not taken (the original still is). The import is keyed on
|
|
// the Factory's tenant_document_id, so it can run again: what is there and
|
|
// unchanged is skipped. The answer lists each document's outcome, never its
|
|
// content.
|
|
|
|
const (
|
|
importDefaultMaxBytes = 2 << 30
|
|
importMaxFiles = 20000
|
|
)
|
|
|
|
var (
|
|
importObjectRe = regexp.MustCompile(`^objects/([0-9a-f]{64})\.(pdf|html|txt)$`)
|
|
importConsentRe = regexp.MustCompile(`^presentation/consent_banner/([0-9a-f]{64})\.json$`)
|
|
importIDRe = regexp.MustCompile(`^[A-Za-z0-9._-]{1,120}$`)
|
|
importExtTypes = map[string]string{".pdf": "application/pdf", ".html": "text/html; charset=utf-8", ".txt": "text/plain; charset=utf-8"}
|
|
assetExtTypes = map[string]string{".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp"}
|
|
)
|
|
|
|
type importIndex struct {
|
|
Documents []struct {
|
|
TenantDocumentID string `json:"tenant_document_id"`
|
|
ContentDigest string `json:"content_digest"`
|
|
Title string `json:"title"`
|
|
ObjectKey string `json:"object_key"`
|
|
DocumentClass string `json:"document_class"`
|
|
LegalKind string `json:"legal_kind"`
|
|
} `json:"documents"`
|
|
}
|
|
|
|
type importCaptures struct {
|
|
Artifact string `json:"artifact"`
|
|
Captures []struct {
|
|
TenantDocumentID string `json:"tenant_document_id"`
|
|
ObjectKey string `json:"object_key"`
|
|
Digest string `json:"digest"`
|
|
} `json:"captures"`
|
|
}
|
|
|
|
// ImportOutcome is what happened to one document of the bundle.
|
|
type ImportOutcome struct {
|
|
ExternalID string `json:"external_id"`
|
|
Title string `json:"title"`
|
|
Area string `json:"area,omitempty"`
|
|
LegalKind string `json:"legal_kind,omitempty"`
|
|
DocumentID string `json:"document_id,omitempty"`
|
|
Original string `json:"original"` // imported | exists | rejected
|
|
Prepared string `json:"prepared"` // imported | unchanged | absent | rejected
|
|
Consent string `json:"consent"` // imported | unchanged | absent | rejected
|
|
Assets int `json:"assets"`
|
|
Reason string `json:"reason,omitempty"`
|
|
}
|
|
|
|
type importResp struct {
|
|
Documents []ImportOutcome `json:"documents"`
|
|
Counts map[string]int `json:"counts"`
|
|
Pin string `json:"pin,omitempty"`
|
|
Revision int `json:"revision,omitempty"`
|
|
}
|
|
|
|
// importStore is POST /v1/admin/tenants/{id}/store/import; the body is the
|
|
// .tar.gz itself. Staff only (a named staff member).
|
|
func (s *Server) importStore(w http.ResponseWriter, r *http.Request) {
|
|
if !s.documentsReady(w) {
|
|
return
|
|
}
|
|
_, staffEmail, ok := s.staffActor(r)
|
|
if !ok {
|
|
writeError(w, http.StatusForbidden, "staff_only", "an import needs a staff member (X-Staff-Subject)")
|
|
return
|
|
}
|
|
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Minute)
|
|
defer cancel()
|
|
t, err := s.Store.GetTenant(ctx, r.PathValue("id"))
|
|
if err != nil {
|
|
if mapStoreError(w, err) {
|
|
return
|
|
}
|
|
writeError(w, http.StatusInternalServerError, "internal", err.Error())
|
|
return
|
|
}
|
|
dir, err := os.MkdirTemp("", "store-import-*")
|
|
if err != nil {
|
|
writeError(w, http.StatusInternalServerError, "internal", "no temporary space")
|
|
return
|
|
}
|
|
defer func() { _ = os.RemoveAll(dir) }()
|
|
max := s.cfg().StoreImportMaxBytes
|
|
if max <= 0 {
|
|
max = importDefaultMaxBytes
|
|
}
|
|
root, err := extractBundle(http.MaxBytesReader(w, r.Body, max), dir, max)
|
|
if err != nil {
|
|
code := http.StatusBadRequest
|
|
if isTooLarge(err) || errors.Is(err, errBundleTooLarge) {
|
|
code = http.StatusRequestEntityTooLarge
|
|
}
|
|
writeError(w, code, "invalid_bundle", err.Error())
|
|
return
|
|
}
|
|
var idx importIndex
|
|
if err := readJSONFile(filepath.Join(root, "LANE_B_INDEX_V1.json"), &idx); err != nil || len(idx.Documents) == 0 {
|
|
writeError(w, http.StatusBadRequest, "invalid_bundle", "LANE_B_INDEX_V1.json is missing, unreadable or lists no documents")
|
|
return
|
|
}
|
|
var caps importCaptures
|
|
if err := readJSONFile(filepath.Join(root, "presentation", "CONSENT_BANNER_CAPTURES_V1.json"), &caps); err != nil && !errors.Is(err, os.ErrNotExist) {
|
|
writeError(w, http.StatusBadRequest, "invalid_bundle", "CONSENT_BANNER_CAPTURES_V1.json is unreadable")
|
|
return
|
|
}
|
|
pin, revision := bundleManifest(filepath.Join(root, "LANE_B_UNIFIED_V5_RETURN_MANIFEST_V1.json"))
|
|
|
|
imp := &importer{s: s, root: root, tenantID: t.ID, by: firstNonEmpty(staffEmail, "staff"), pin: pin, revision: revision, caps: caps}
|
|
out := importResp{Documents: []ImportOutcome{}, Counts: map[string]int{}, Pin: pin, Revision: revision}
|
|
for _, d := range idx.Documents {
|
|
o := imp.document(ctx, d.TenantDocumentID, d.ContentDigest, d.Title, d.ObjectKey, d.DocumentClass, d.LegalKind)
|
|
out.Documents = append(out.Documents, o)
|
|
out.Counts["original_"+o.Original]++
|
|
out.Counts["prepared_"+o.Prepared]++
|
|
out.Counts["consent_"+o.Consent]++
|
|
}
|
|
s.emitAudit(ctx, r, store.AuditEvent{
|
|
TenantID: t.ID, Action: "store.imported", TargetID: t.ID, TargetType: "tenant", TargetName: t.Slug,
|
|
ActorType: "staff", ActorName: imp.by,
|
|
Metadata: map[string]interface{}{"documents": len(out.Documents), "counts": out.Counts, "pin": pin, "revision": revision},
|
|
})
|
|
writeJSON(w, http.StatusOK, out)
|
|
}
|
|
|
|
var errBundleTooLarge = errors.New("the bundle is larger than the import limit")
|
|
|
|
// extractBundle unpacks the .tar.gz into dir: regular files and directories
|
|
// only, no absolute paths, no "..", no links, at most importMaxFiles files and
|
|
// max bytes. It returns the bundle root: dir, or its only directory when the
|
|
// archive wraps everything in one.
|
|
func extractBundle(r io.Reader, dir string, max int64) (string, error) {
|
|
gz, err := gzip.NewReader(r)
|
|
if err != nil {
|
|
return "", errors.New("not a .tar.gz")
|
|
}
|
|
tr := tar.NewReader(gz)
|
|
var files int
|
|
var total int64
|
|
for {
|
|
h, err := tr.Next()
|
|
if err == io.EOF {
|
|
break
|
|
}
|
|
if err != nil {
|
|
if isTooLarge(err) {
|
|
return "", err
|
|
}
|
|
return "", fmt.Errorf("the archive is broken: %w", err)
|
|
}
|
|
name := path.Clean(strings.TrimPrefix(h.Name, "./"))
|
|
if name == "." {
|
|
continue
|
|
}
|
|
if path.IsAbs(name) || name == ".." || strings.HasPrefix(name, "../") {
|
|
return "", fmt.Errorf("refused path %q", h.Name)
|
|
}
|
|
target := filepath.Join(dir, filepath.FromSlash(name))
|
|
switch h.Typeflag {
|
|
case tar.TypeDir:
|
|
if err := os.MkdirAll(target, 0o700); err != nil {
|
|
return "", err
|
|
}
|
|
case tar.TypeReg:
|
|
if files++; files > importMaxFiles {
|
|
return "", fmt.Errorf("more than %d files", importMaxFiles)
|
|
}
|
|
if err := os.MkdirAll(filepath.Dir(target), 0o700); err != nil {
|
|
return "", err
|
|
}
|
|
f, err := os.OpenFile(target, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
|
|
if err != nil {
|
|
return "", fmt.Errorf("refused path %q", h.Name)
|
|
}
|
|
n, err := io.Copy(f, io.LimitReader(tr, max-total+1))
|
|
_ = f.Close()
|
|
if err != nil {
|
|
if isTooLarge(err) {
|
|
return "", err
|
|
}
|
|
return "", fmt.Errorf("the archive is broken: %w", err)
|
|
}
|
|
if total += n; total > max {
|
|
return "", errBundleTooLarge
|
|
}
|
|
default:
|
|
// Links and devices could point outside the bundle.
|
|
return "", fmt.Errorf("refused entry %q (only files and directories)", h.Name)
|
|
}
|
|
}
|
|
if _, err := os.Stat(filepath.Join(dir, "LANE_B_INDEX_V1.json")); err == nil {
|
|
return dir, nil
|
|
}
|
|
entries, _ := os.ReadDir(dir)
|
|
if len(entries) == 1 && entries[0].IsDir() {
|
|
return filepath.Join(dir, entries[0].Name()), nil
|
|
}
|
|
return dir, nil
|
|
}
|
|
|
|
func readJSONFile(p string, into any) error {
|
|
b, err := os.ReadFile(p) //nolint:gosec // inside the import's temp dir
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return json.Unmarshal(b, into)
|
|
}
|
|
|
|
// bundleManifest: the pin is the manifest file's digest; the revision its
|
|
// "revision" field when there is one.
|
|
func bundleManifest(p string) (string, int) {
|
|
b, err := os.ReadFile(p) //nolint:gosec // inside the import's temp dir
|
|
if err != nil {
|
|
return "", 0
|
|
}
|
|
sum := sha256.Sum256(b)
|
|
var m struct {
|
|
Revision int `json:"revision"`
|
|
}
|
|
_ = json.Unmarshal(b, &m)
|
|
return hex.EncodeToString(sum[:]), m.Revision
|
|
}
|
|
|
|
type importer struct {
|
|
s *Server
|
|
root string
|
|
tenantID string
|
|
by string
|
|
pin string
|
|
revision int
|
|
caps importCaptures
|
|
}
|
|
|
|
// fileWithDigest reads rel inside the bundle and checks it hashes to want.
|
|
func (im *importer) fileWithDigest(rel, want string) ([]byte, error) {
|
|
b, err := os.ReadFile(filepath.Join(im.root, filepath.FromSlash(rel))) //nolint:gosec // inside the import's temp dir
|
|
if err != nil {
|
|
return nil, fmt.Errorf("%s is missing", rel)
|
|
}
|
|
sum := sha256.Sum256(b)
|
|
if hex.EncodeToString(sum[:]) != want {
|
|
return nil, fmt.Errorf("%s does not match its digest", rel)
|
|
}
|
|
return b, nil
|
|
}
|
|
|
|
func (im *importer) document(ctx context.Context, id, digest, title, objectKey, class, legalKind string) ImportOutcome {
|
|
o := ImportOutcome{ExternalID: id, Title: title, Original: "rejected", Prepared: "absent", Consent: "absent"}
|
|
if !importIDRe.MatchString(id) {
|
|
o.Reason = "invalid tenant_document_id"
|
|
return o
|
|
}
|
|
m := importObjectRe.FindStringSubmatch(objectKey)
|
|
if m == nil || digest != "sha256:"+m[1] {
|
|
o.Reason = "object_key and content_digest do not agree"
|
|
return o
|
|
}
|
|
o.Area = store.AreaProductPublic
|
|
if class == "LEGAL" {
|
|
o.Area, o.LegalKind = store.AreaLegalWeb, legalKind
|
|
if !store.ValidLegalKind(legalKind) {
|
|
o.Reason = fmt.Sprintf("unknown legal_kind %q", legalKind)
|
|
return o
|
|
}
|
|
}
|
|
doc, err := im.s.Store.GetDocumentByExternalID(ctx, im.tenantID, id)
|
|
switch {
|
|
case err == nil && doc.SHA256 != m[1]:
|
|
o.DocumentID = doc.ID
|
|
o.Reason = "a different original is already stored under this id"
|
|
return o
|
|
case err == nil:
|
|
o.Original, o.DocumentID = "exists", doc.ID
|
|
case errors.Is(err, store.ErrNotFound):
|
|
body, ferr := im.fileWithDigest(objectKey, m[1])
|
|
if ferr != nil {
|
|
o.Reason = ferr.Error()
|
|
return o
|
|
}
|
|
if doc, err = im.createDocument(ctx, id, title, o.Area, o.LegalKind, m[1], "."+m[2], body); err != nil {
|
|
o.Reason = "could not be stored: " + err.Error()
|
|
return o
|
|
}
|
|
o.Original, o.DocumentID = "imported", doc.ID
|
|
default:
|
|
o.Reason = err.Error()
|
|
return o
|
|
}
|
|
im.preparation(ctx, doc, &o)
|
|
return o
|
|
}
|
|
|
|
func (im *importer) createDocument(ctx context.Context, id, title, area, legalKind, sum, ext string, body []byte) (*store.Document, error) {
|
|
name := safeFilename(strings.TrimSpace(title) + ext)
|
|
if name == "" || name == ext {
|
|
name = id + ext
|
|
}
|
|
t := strings.Join(strings.Fields(title), " ")
|
|
if t == "" {
|
|
t = id
|
|
}
|
|
if len([]rune(t)) > 200 {
|
|
t = string([]rune(t)[:200])
|
|
}
|
|
d := store.Document{
|
|
ID: uuid.NewString(), TenantID: im.tenantID, Title: t, Filename: name, ContentType: importExtTypes[ext],
|
|
SizeBytes: int64(len(body)), SHA256: sum, Status: store.DocumentPublished, OwnDocument: true,
|
|
UploadedBy: im.by, Area: area, LegalKind: legalKind, ProcessingStatus: store.ProcessingPending, ExternalID: id,
|
|
}
|
|
d.ObjectKey = storeKey(im.tenantID, d.ID, "original/"+name)
|
|
if err := im.s.Objects.Put(ctx, d.ObjectKey, bytes.NewReader(body), int64(len(body)), d.ContentType); err != nil {
|
|
return nil, err
|
|
}
|
|
created, err := im.s.Store.CreateDocument(ctx, d)
|
|
if err != nil {
|
|
_ = im.s.Objects.Delete(context.WithoutCancel(ctx), d.ObjectKey)
|
|
return nil, err
|
|
}
|
|
return created, nil
|
|
}
|
|
|
|
// preparation takes the document's chunk file (with its images) and its
|
|
// cookie-banner capture, where the bundle has them.
|
|
func (im *importer) preparation(ctx context.Context, doc *store.Document, o *ImportOutcome) {
|
|
cur, err := im.s.Store.GetDocumentPreparation(ctx, doc.ID)
|
|
if err != nil && !errors.Is(err, store.ErrNotFound) {
|
|
o.Prepared, o.Reason = "rejected", err.Error()
|
|
return
|
|
}
|
|
next := store.Preparation{DocumentID: doc.ID, DeliveredBy: im.by}
|
|
|
|
chunkPath := filepath.Join(im.root, "chunks", o.ExternalID+".json")
|
|
if b, rerr := os.ReadFile(chunkPath); rerr == nil { //nolint:gosec // inside the import's temp dir
|
|
sum := sha256.Sum256(b)
|
|
hexSum := hex.EncodeToString(sum[:])
|
|
switch count, digests, verr := checkChunkFile(b); {
|
|
case verr != nil:
|
|
o.Prepared, o.Reason = "rejected", verr.Error()
|
|
case cur != nil && cur.ChunkSHA256 == hexSum:
|
|
o.Prepared, o.Assets = "unchanged", len(cur.AssetDigests)
|
|
default:
|
|
if aerr := im.assets(ctx, digests); aerr != nil {
|
|
o.Prepared, o.Reason = "rejected", aerr.Error()
|
|
break
|
|
}
|
|
key := storeKey(im.tenantID, doc.ID, "prepared/chunks-"+hexSum+".json")
|
|
if perr := im.s.Objects.Put(ctx, key, bytes.NewReader(b), int64(len(b)), "application/json"); perr != nil {
|
|
o.Prepared, o.Reason = "rejected", "could not be stored"
|
|
break
|
|
}
|
|
next.Format, next.Revision, next.Pin = "LANE_B_UNIFIED_V5", im.revision, im.pin
|
|
next.ChunkObjectKey, next.ChunkSHA256, next.ChunkBytes, next.ChunkCount = key, hexSum, int64(len(b)), count
|
|
next.AssetDigests = digests
|
|
o.Prepared, o.Assets = "imported", len(digests)
|
|
}
|
|
}
|
|
|
|
for _, c := range im.caps.Captures {
|
|
if c.TenantDocumentID != o.ExternalID {
|
|
continue
|
|
}
|
|
m := importConsentRe.FindStringSubmatch(c.ObjectKey)
|
|
if m == nil || c.Digest != "sha256:"+m[1] {
|
|
o.Consent, o.Reason = "rejected", "capture object_key and digest do not agree"
|
|
break
|
|
}
|
|
if cur != nil && cur.ConsentSHA256 == m[1] {
|
|
o.Consent = "unchanged"
|
|
break
|
|
}
|
|
b, ferr := im.fileWithDigest(c.ObjectKey, m[1])
|
|
var head struct {
|
|
Artifact string `json:"artifact"`
|
|
}
|
|
if ferr == nil && (json.Unmarshal(b, &head) != nil || head.Artifact != "CONSENT_BANNER_CAPTURE_V1") {
|
|
ferr = errors.New("the capture is not a CONSENT_BANNER_CAPTURE_V1")
|
|
}
|
|
if ferr != nil {
|
|
o.Consent, o.Reason = "rejected", ferr.Error()
|
|
break
|
|
}
|
|
key := storeKey(im.tenantID, doc.ID, "prepared/consent-"+m[1]+".json")
|
|
if perr := im.s.Objects.Put(ctx, key, bytes.NewReader(b), int64(len(b)), "application/json"); perr != nil {
|
|
o.Consent, o.Reason = "rejected", "could not be stored"
|
|
break
|
|
}
|
|
next.ConsentObjectKey, next.ConsentSHA256 = key, m[1]
|
|
o.Consent = "imported"
|
|
break
|
|
}
|
|
|
|
if next.HasChunks() || next.HasConsent() {
|
|
if _, err := im.s.Store.SaveDocumentPreparation(ctx, next); err != nil {
|
|
o.Prepared, o.Consent, o.Reason = "rejected", "rejected", err.Error()
|
|
}
|
|
}
|
|
}
|
|
|
|
// assets stores every image the chunk file refers to (taken from the bundle,
|
|
// digest-checked); one the tenant already holds is not stored again.
|
|
func (im *importer) assets(ctx context.Context, digests []string) error {
|
|
dir := filepath.Join(im.root, "figure_assets", "sources", "sha256")
|
|
for _, sum := range digests {
|
|
if _, err := im.s.Store.GetStoreAsset(ctx, im.tenantID, sum); err == nil {
|
|
continue
|
|
}
|
|
var rel, ext string
|
|
for e := range assetExtTypes {
|
|
if _, err := os.Stat(filepath.Join(dir, sum+e)); err == nil {
|
|
rel, ext = "figure_assets/sources/sha256/"+sum+e, e
|
|
break
|
|
}
|
|
}
|
|
if rel == "" {
|
|
return fmt.Errorf("image %s… is missing from the bundle", sum[:12])
|
|
}
|
|
b, err := im.fileWithDigest(rel, sum)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
key := assetKey(im.tenantID, sum, ext)
|
|
if err := im.s.Objects.Put(ctx, key, bytes.NewReader(b), int64(len(b)), assetExtTypes[ext]); err != nil {
|
|
return errors.New("an image could not be stored")
|
|
}
|
|
if _, err := im.s.Store.PutStoreAsset(ctx, store.StoreAsset{
|
|
TenantID: im.tenantID, SHA256: sum, ObjectKey: key, ContentType: assetExtTypes[ext], SizeBytes: int64(len(b)),
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// checkChunkFile checks the outline of a LANE_B_UNIFIED_V5 chunk file — an
|
|
// object with a "chunk_list" and a "pages" list — and returns its unit count
|
|
// and every image digest it refers to ("asset_digest", with or without the
|
|
// "sha256:" prefix), sorted and without repeats.
|
|
func checkChunkFile(b []byte) (int, []string, error) {
|
|
var v map[string]any
|
|
if err := json.Unmarshal(b, &v); err != nil || v == nil {
|
|
return 0, nil, errors.New("the chunk file is not a JSON object")
|
|
}
|
|
units, ok := v["chunk_list"].([]any)
|
|
if !ok {
|
|
return 0, nil, errors.New("the chunk file has no chunk_list")
|
|
}
|
|
if _, ok := v["pages"].([]any); !ok {
|
|
return 0, nil, errors.New("the chunk file has no pages")
|
|
}
|
|
seen := map[string]bool{}
|
|
var bad error
|
|
var walk func(x any)
|
|
walk = func(x any) {
|
|
switch t := x.(type) {
|
|
case map[string]any:
|
|
for k, val := range t {
|
|
if s, ok := val.(string); ok && k == "asset_digest" && s != "" {
|
|
d := strings.TrimPrefix(s, "sha256:")
|
|
if !hexDigest(d) {
|
|
bad = fmt.Errorf("asset_digest %q is not a SHA-256", s)
|
|
continue
|
|
}
|
|
seen[d] = true
|
|
continue
|
|
}
|
|
walk(val)
|
|
}
|
|
case []any:
|
|
for _, e := range t {
|
|
walk(e)
|
|
}
|
|
}
|
|
}
|
|
walk(v)
|
|
if bad != nil {
|
|
return 0, nil, bad
|
|
}
|
|
out := make([]string, 0, len(seen))
|
|
for d := range seen {
|
|
out = append(out, d)
|
|
}
|
|
sort.Strings(out)
|
|
return len(units), out, nil
|
|
}
|
|
|
|
func hexDigest(s string) bool {
|
|
if len(s) != 64 {
|
|
return false
|
|
}
|
|
_, err := hex.DecodeString(s)
|
|
return err == nil && strings.ToLower(s) == s
|
|
}
|