Files
2026-12-03 22:33:06 +01:00

273 lines
8.6 KiB
Go

package dbcopy
import (
"context"
"sort"
"strings"
"github.com/google/uuid"
"github.com/phishingclub/phishingclub/app"
"github.com/phishingclub/phishingclub/database"
"github.com/phishingclub/phishingclub/database/dbengine"
"github.com/phishingclub/phishingclub/utils"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
// baselineTextBudget caps the cleaned text kept for Bait Box baselines. A
// resource whose text does not fit keeps its baseline.
const baselineTextBudget = 256 << 20
// baselineSkipTables are the Bait Box bookkeeping tables. Their rows name the
// installed resources but are not part of their content.
var baselineSkipTables = map[string]bool{
database.INSTALLED_RESOURCE_TABLE: true,
database.INSTALLED_PACKAGE_TABLE: true,
database.INSTALLED_PACKAGE_MEMBER_TABLE: true,
database.REGISTRY_PACKAGE_TAG_TABLE: true,
database.REGISTRY_TABLE: true,
}
// Bait Box records a baseline, the fingerprint of an installed entity as the
// install stored it, and compares it with the entity and with a new version
// of the package. On sqlite the fingerprint hashes the text as it is; the
// copy stores text with a NUL or bytes that are not UTF-8 cleaned, and on
// postgres both the entity and the package text are hashed cleaned. A
// baseline of such text would then match neither, and the next update would
// show an unchanged entity as edited and changed upstream. So for every
// installed resource whose rows had cleaned text, the copy works out the
// fingerprint sqlite would compute now, from the cleaned entity with its
// text mapped back, and when it equals the baseline (the entity was not
// edited since the install) the baseline becomes the postgres fingerprint.
// An edited entity keeps its baseline: the next update may ask the operator
// to keep or replace it, but never overwrites an edit without asking.
// rawText maps each cleaned text of one resource back to its sqlite text
type rawText struct {
text map[string]string
ambiguous map[string]bool
tooLarge bool
}
// baselineText is the cleaned text of the installed Bait Box resources,
// collected by the first pass
type baselineText struct {
resources map[string]bool
owners map[string]*rawText
size int
}
// newBaselineText tracks the resources of the ids
func newBaselineText(resources map[string]bool) *baselineText {
return &baselineText{resources: resources, owners: map[string]*rawText{}}
}
// tracks is true when rows of the table can be content of a resource
func (b *baselineText) tracks(table string) bool {
return len(b.resources) > 0 && !baselineSkipTables[table]
}
// addRow keeps the cleaned text of a row for each installed resource the row
// names in a uuid column: its own id, or the parent of a header row
func (b *baselineText) addRow(t *table, values []any, pairs [][2]string) {
for i, c := range t.read {
if c.kind != kindUUID {
continue
}
id, ok := values[i].(string)
if !ok || !b.resources[id] {
continue
}
owner := b.owners[id]
if owner == nil {
owner = &rawText{text: map[string]string{}, ambiguous: map[string]bool{}}
b.owners[id] = owner
}
for _, p := range pairs {
b.add(owner, p[0], p[1])
// the value objects of the application trim text when read
if tc, tr := strings.TrimSpace(p[0]), strings.TrimSpace(p[1]); tc != p[0] || tr != p[1] {
b.add(owner, tc, tr)
}
}
}
}
// add maps one cleaned text to its source. Two sources that clean to the
// same text can not be told apart, such a text is mapped to neither.
func (b *baselineText) add(owner *rawText, cleaned, raw string) {
if owner.tooLarge || owner.ambiguous[cleaned] {
return
}
if prev, ok := owner.text[cleaned]; ok {
if prev != raw {
delete(owner.text, cleaned)
owner.ambiguous[cleaned] = true
}
return
}
if b.size+len(cleaned)+len(raw) > baselineTextBudget {
owner.tooLarge = true
owner.text = nil
return
}
b.size += len(cleaned) + len(raw)
owner.text[cleaned] = raw
}
// installedResourceIDs returns the ids of the entities of the installed Bait
// Box resources of the source
func installedResourceIDs(srcTx *gorm.DB) (map[string]bool, error) {
rows, err := srcTx.Raw("SELECT +resource_id FROM installed_resources").Rows()
if err != nil {
return nil, err
}
defer rows.Close()
ids := map[string]bool{}
for rows.Next() {
var v any
if err := rows.Scan(&v); err != nil {
return nil, err
}
if cv := convertUUID(v); cv.invalid == "" {
ids[cv.value.(string)] = true
}
}
return ids, rows.Err()
}
// installedResourceRow is a row of installed_resources in the target
type installedResourceRow struct {
ID string
ResourceType string
ResourceID string
InstalledContentHash string
}
// rebaseBaselines gives each copied resource with cleaned text the baseline
// postgres computes, when sqlite would still compute its old baseline. It
// runs in a savepoint of the copy transaction with the services of the
// application on that transaction; a failure there keeps every baseline.
func (r *runner) rebaseBaselines(ctx context.Context, tx *gorm.DB) error {
if len(r.baselines.owners) == 0 {
return nil
}
var rows []installedResourceRow
err := tx.Table(database.INSTALLED_RESOURCE_TABLE).
Select("id", "resource_type", "resource_id", "installed_content_hash").
Order("id").
Find(&rows).Error
if err != nil {
return err
}
rebased := 0
var kept []BaselineItem
err = tx.Transaction(func(stx *gorm.DB) error {
repos := app.NewRepositories(stx)
services := app.NewServices(
stx, repos, r.opts.Logger, r.opts.Logger, app.NewUtils(),
r.opts.AssetPath, "", "", app.MODE_PRODUCTION, nil, nil,
r.opts.FilePath, utils.IPTrust{}, "", "", false,
)
for _, row := range rows {
raw := r.baselines.owners[row.ResourceID]
if raw == nil {
continue
}
keep := func(reason string) {
kept = append(kept, BaselineItem{ResourceType: row.ResourceType, ResourceID: row.ResourceID, Reason: reason})
}
if raw.tooLarge {
keep("too much cleaned text to compare")
continue
}
id, err := uuid.Parse(row.ResourceID)
if err != nil {
keep("the resource id is not a uuid")
continue
}
sqliteHash, postgresHash := services.ContentRegistry.CopiedBaseline(ctx, row.ResourceType, &id, raw.text)
switch {
case sqliteHash == "" || postgresHash == "":
keep("it has no fingerprint of its text, or it could not be read")
case sqliteHash != row.InstalledContentHash:
keep("it was edited after the install, or its fingerprint can not be made from the sqlite text")
case postgresHash == row.InstalledContentHash:
default:
err := stx.Table(database.INSTALLED_RESOURCE_TABLE).
Where("id = ?", row.ID).
Update("installed_content_hash", postgresHash).Error
if err != nil {
return err
}
rebased++
}
}
// a read that failed in a service aborted the transaction, which
// this shows, so the savepoint is rolled back
return stx.Exec("SELECT 1").Error
})
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
rebased = 0
kept = kept[:0]
for _, row := range rows {
if r.baselines.owners[row.ResourceID] != nil {
kept = append(kept, BaselineItem{ResourceType: row.ResourceType, ResourceID: row.ResourceID, Reason: "the baselines could not be computed"})
}
}
}
r.report.BaselinesRebased = rebased
r.report.BaselinesKept = kept
return nil
}
// packagesNotClean lists the installed Bait Box packages with a resource
// whose rows had text with a NUL or bytes that are not UTF-8. On postgres an
// install or update refuses such text (packageTextErr), so the next update
// of these packages fails until the author publishes a UTF-8 version.
func (r *runner) packagesNotClean(tx *gorm.DB) error {
if len(r.baselines.owners) == 0 {
return nil
}
ids := make([]string, 0, len(r.baselines.owners))
for id := range r.baselines.owners {
ids = append(ids, id)
}
sort.Strings(ids)
var packageIDs []string
err := tx.Table(database.INSTALLED_RESOURCE_TABLE).
Where(dbengine.AnyOf(clause.Column{Name: "resource_id"}, toAny(ids))).
Distinct().
Pluck("installed_package_id", &packageIDs).Error
if err != nil {
return err
}
if len(packageIDs) == 0 {
return nil
}
var rows []PackageItem
err = tx.Table(database.INSTALLED_PACKAGE_TABLE).
Select("package_id", "version").
Where(dbengine.AnyOf(clause.Column{Name: "id"}, toAny(packageIDs))).
Order("package_id").
Order("version").
Find(&rows).Error
if err != nil {
return err
}
r.report.PackagesNotClean = rows
return nil
}
// toAny returns the strings as values for a query
func toAny(values []string) []any {
out := make([]any, len(values))
for i, v := range values {
out[i] = v
}
return out
}