diff --git a/cmd/ingestor/antenna_claims.go b/cmd/ingestor/antenna_claims.go index 71f46cf3a..f14f30eca 100644 --- a/cmd/ingestor/antenna_claims.go +++ b/cmd/ingestor/antenna_claims.go @@ -86,6 +86,8 @@ type antennaClaimRunner struct { limits antennaclaim.Limits auto autoApproval now func() time.Time + // photos are the station photo switch and caps (#1017 M5). + photos photoPolicy mu sync.Mutex // pending maps a public key to its pending claims: at most @@ -104,6 +106,7 @@ func newAntennaClaimRunner(store *Store, cfg *antennaclaim.Config) *antennaClaim queue: channelregistry.NewQueue(antennaclaim.QueueDir(store.path)), limits: cfg.Limits(), auto: autoApproval{proven: cfg.AutoApprove(), details: cfg.AutoApproveDetailsOn()}, + photos: photoPolicy{on: cfg.PhotosRequested(), limits: cfg.PhotoLimits()}, now: time.Now, pending: pendingCodes[pendingClaim]{}, } @@ -214,12 +217,17 @@ func (s *Store) proveAntennaClaim(ctx context.Context, id, hash string, lat, lon status, nowMs, hash, lat, lon, reviewedAt, approvedBy, id); err != nil { return "", err } + var dropped []string if status == antennaclaim.StatusApproved { - if err := putInForce(ctx, tx, pubkey, id, nowMs); err != nil { + if dropped, err = putInForce(ctx, tx, pubkey, id, nowMs); err != nil { return "", err } } - return status, tx.Commit() + if err := tx.Commit(); err != nil { + return "", err + } + s.unlinkPhotos(dropped) + return status, nil } // putInForce runs inside an approval's transaction, after the claim's status @@ -229,31 +237,44 @@ func (s *Store) proveAntennaClaim(ctx context.Context, id, hash string, lat, lon // flags are both 0 is superseded; one that still has a part in force stays // approved. Nothing is ever put back in force: a later revoke of this claim // leaves the node without the part (no resurrection, #898 T5). -func putInForce(ctx context.Context, tx *sql.Tx, pubkey, id string, nowMs int64) error { - var carriesHeight, carriesDetails bool +// +// #1017 M5: the photos of a claim whose details are replaced or cleared are +// deleted, and their ids returned for unlinking after the commit, unless +// this claim keeps them (keep_photos): then they move to this claim. +func putInForce(ctx context.Context, tx *sql.Tx, pubkey, id string, nowMs int64) (dropped []string, err error) { + var carriesHeight, carriesDetails, keepPhotos bool if err := tx.QueryRowContext(ctx, `UPDATE node_antenna_claims SET height_in_force = (height_op IS NOT NULL), details_in_force = (details_op IS NOT NULL) - WHERE request_id = ? RETURNING height_in_force, details_in_force`, id).Scan(&carriesHeight, &carriesDetails); err != nil { - return err + WHERE request_id = ? RETURNING height_in_force, details_in_force, keep_photos`, id).Scan(&carriesHeight, &carriesDetails, &keepPhotos); err != nil { + return nil, err } const others = ` WHERE pubkey = ? AND status = 'approved' AND request_id != ?` if carriesHeight { if _, err := tx.ExecContext(ctx, `UPDATE node_antenna_claims SET height_in_force = 0`+others+` AND height_in_force = 1`, pubkey, id); err != nil { - return err + return nil, err } } if carriesDetails { if _, err := tx.ExecContext(ctx, `DELETE FROM node_claim_admin_contacts WHERE request_id IN (SELECT request_id FROM node_antenna_claims`+others+` AND details_in_force = 1)`, pubkey, id); err != nil { - return err + return nil, err + } + replaced := `(SELECT request_id FROM node_antenna_claims` + others + ` AND details_in_force = 1)` + if keepPhotos { + _, err = tx.ExecContext(ctx, `UPDATE node_claim_photos SET request_id = ? WHERE request_id IN `+replaced, id, pubkey, id) + } else { + dropped, err = deletePhotos(ctx, tx, `request_id IN `+replaced, pubkey, id) + } + if err != nil { + return nil, err } if _, err := tx.ExecContext(ctx, `UPDATE node_antenna_claims SET details_in_force = 0, contact_public = NULL`+others+` AND details_in_force = 1`, pubkey, id); err != nil { - return err + return nil, err } } - _, err := tx.ExecContext(ctx, `UPDATE node_antenna_claims SET status = 'superseded', reviewed_at = ?`+others+` + _, err = tx.ExecContext(ctx, `UPDATE node_antenna_claims SET status = 'superseded', reviewed_at = ?`+others+` AND height_in_force = 0 AND details_in_force = 0`, nowMs, pubkey, id) - return err + return dropped, err } // dropContacts deletes the contacts of claim id, inside a transition out of @@ -322,12 +343,12 @@ func (s *Store) insertAntennaClaim(ctx context.Context, cmd antennaclaim.Command if _, err := tx.ExecContext(ctx, `INSERT INTO node_antenna_claims (request_id, pubkey, height_m, height_op, details_op, antenna_type, gain_dbi, power_mask, installation, contact_public, hardware, hardware_model, tx_power_dbm, cable_loss_db, azimuth_deg, beamwidth_deg, battery_wh, solar_w, - code, status, needs_review, created_at, expires_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?)`, + keep_photos, code, status, needs_review, created_at, expires_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?)`, cmd.RequestID, cmd.PubKey, cmd.HeightM, nullString(parts.Height), nullString(parts.Details), antennaType, d.GainDBi, powerMask, installation, contactPublic, hardware, hardwareModel, d.TxPowerDbm, d.CableLossDb, d.AzimuthDeg, d.BeamwidthDeg, d.BatteryWh, d.SolarW, - cmd.Code, cmd.NeedsReview, created, created+l.RequestTTL.Milliseconds()); err != nil { + cmd.KeepPhotos && cmd.Details != nil, cmd.Code, cmd.NeedsReview, created, created+l.RequestTTL.Milliseconds()); err != nil { return "", err } if contactAdmin.Valid { @@ -347,7 +368,8 @@ func nullString(s string) sql.NullString { return sql.NullString{String: s, Vali // older than an approved claim that carries one of its parts is refused // (ErrNewerApproved): the newest proof by the key holder wins, whatever order // an administrator reviews them in. A reject or revoke deletes the claim's -// contacts, and a revoke takes its parts out of force. +// contacts and its photos (#1017 M5), and a revoke takes its parts out of +// force. func (s *Store) reviewAntennaClaim(ctx context.Context, id string, sources []string, target string, nowMs int64) (string, error) { tx, err := s.db.BeginTx(ctx, nil) if err != nil { @@ -390,9 +412,10 @@ func (s *Store) reviewAntennaClaim(ctx context.Context, id string, sources []str WHERE request_id = ? AND status = ?`, target, nowMs, approvedBy, id, status); err != nil { return "", err } + var dropped []string switch target { case antennaclaim.StatusApproved: - if err := putInForce(ctx, tx, pubkey, id, nowMs); err != nil { + if dropped, err = putInForce(ctx, tx, pubkey, id, nowMs); err != nil { return "", err } case antennaclaim.StatusRevoked: @@ -404,8 +427,15 @@ func (s *Store) reviewAntennaClaim(ctx context.Context, id string, sources []str if err := dropContacts(ctx, tx, id); err != nil { return "", err } + if dropped, err = deletePhotos(ctx, tx, `request_id = ?`, id); err != nil { + return "", err + } } - return target, tx.Commit() + if err := tx.Commit(); err != nil { + return "", err + } + s.unlinkPhotos(dropped) + return target, nil } // PruneAntennaClaims deletes finished claims decided before cutoffMs and @@ -568,6 +598,13 @@ func (r *antennaClaimRunner) apply(ctx context.Context, data []byte) antennaclai case antennaclaim.OpRevoke: res.ClaimID = cmd.ClaimID status, err = r.store.reviewAntennaClaim(ctx, cmd.ClaimID, []string{antennaclaim.StatusApproved}, antennaclaim.StatusRevoked, nowMs) + case antennaclaim.OpPhotoSubmit: + res.ClaimID = cmd.ClaimID + status, err = r.store.submitPhoto(ctx, cmd, r.photos, nowMs) + case antennaclaim.OpPhotoApprove: + status, err = r.store.approvePhoto(ctx, cmd.PhotoID, r.photos, nowMs) + case antennaclaim.OpPhotoReject: + status, err = r.store.rejectPhoto(ctx, cmd.PhotoID) } if err != nil { if cmd.Op == antennaclaim.OpClaim { @@ -586,7 +623,7 @@ func userFacingClaimError(err error) string { switch { case errors.As(err, &conflict), errors.Is(err, errTooManyClaims), errors.Is(err, errTooManyNodeClaims), errors.Is(err, errClaimNotFound), errors.Is(err, errClaimExpired), errors.Is(err, antennaclaim.ErrInvalidCommand), - errors.Is(err, antennaclaim.ErrNewerApproved): + errors.Is(err, antennaclaim.ErrNewerApproved), isPhotoRefusal(err): return err.Error() } log.Printf("[antenna-claims] command failed: %v", err) @@ -605,6 +642,7 @@ func (r *antennaClaimRunner) Prune(ctx context.Context) { if _, err := r.queue.Prune(now, r.limits.RequestTTL, r.limits.MaxResults); err != nil { log.Printf("[antenna-claims] queue prune failed: %v", err) } + r.store.sweepPhotos(ctx, now) } // Start runs RunOnce every tick and Prune every pruneEvery. The returned func diff --git a/cmd/ingestor/config.go b/cmd/ingestor/config.go index 1c1b72679..1325d1bc9 100644 --- a/cmd/ingestor/config.go +++ b/cmd/ingestor/config.go @@ -514,6 +514,7 @@ func LoadConfig(path string) (*Config, error) { // read the same way as the server reads them (#884, #888). keys := configkey.New(data, log.Printf) cfg.AntennaClaims.ApplyGates(keys.On) + cfg.AntennaClaims.ApplyPhotoGate(keys.Bool) cfg.Accounts.ApplyGates(keys.On) cfg.ChannelProposals.ApplyGates(keys.On) if cfg.ClientRxCoverage != nil { diff --git a/cmd/ingestor/station_photos.go b/cmd/ingestor/station_photos.go new file mode 100644 index 000000000..573aec124 --- /dev/null +++ b/cmd/ingestor/station_photos.go @@ -0,0 +1,443 @@ +package main + +// Station photos (#1017 M5) — the writer side. +// +// The read-only server re-encodes an upload and writes the two JPEG files +// to antennaclaim.PhotoDir/inbox//, then queues OpPhotoSubmit. This +// file owns everything after that: it re-checks the claim, the files and the +// caps, moves the directory to PhotoDir// and inserts the row; it +// applies the administrator's decisions; and it deletes rows and files. +// +// A photo is never approved automatically: OpPhotoSubmit always inserts +// 'pending', whatever autoApproveProven and autoApproveDetails say, and only +// OpPhotoApprove moves it on. +// +// Files are deleted after the transaction that deleted their rows commits. +// A crash in between leaves a directory without a row; the sweep at every +// prune removes those, rows whose files are gone, rows whose claim is no +// longer live, and inbox entries older than antennaclaim.PhotoInboxTTL. + +import ( + "bytes" + "context" + "crypto/sha256" + "database/sql" + "encoding/hex" + "errors" + "image/jpeg" + "io" + "log" + "os" + "path/filepath" + "strings" + "time" + + "github.com/meshcore-analyzer/channelregistry/antennaclaim" +) + +// photoPolicy is the operator's photo switch and caps, resolved once. +type photoPolicy struct { + on bool + limits antennaclaim.PhotoLimits +} + +// photoRefusal is a photo command refused for a reason the owner or the +// administrator can act on; its text is returned verbatim. +type photoRefusal string + +func (e photoRefusal) Error() string { return string(e) } + +func isPhotoRefusal(err error) bool { + var r photoRefusal + return errors.As(err, &r) +} + +// User-facing photo outcomes. +var ( + errPhotosDisabled = photoRefusal("station photos are disabled") + errPhotoClaim = photoRefusal("a photo can be added only to a proven or approved claim that sets station details, within the upload window after its proof") + errPhotoNotServed = photoRefusal("approve the claim before its photo: a photo is shown only with approved station details") + errPhotoFiles = photoRefusal("the photo could not be verified") + errPhotosPending = photoRefusal("too many photos are waiting for review, please try again later") + errPhotoStoreFull = photoRefusal("photo storage is full") + errPhotoNotFound = photoRefusal("photo not found") + errPhotoNotPending = photoRefusal("photo is not waiting for review") +) + +// photoRoot is the photo store next to the database. +func (s *Store) photoRoot() string { return antennaclaim.PhotoDir(s.path) } + +// photoInbox is the inbox entry of a photo id (already validated). +func (s *Store) photoInbox(id string) string { + return filepath.Join(s.photoRoot(), antennaclaim.PhotoInboxName, id) +} + +// photoStored is the stored directory of a photo id (already validated). +func (s *Store) photoStored(id string) string { return filepath.Join(s.photoRoot(), id) } + +// unlinkPhotos removes the stored directories of photos whose rows a +// committed transaction deleted. An error is logged: the sweep removes what +// is left. +func (s *Store) unlinkPhotos(ids []string) { + for _, id := range ids { + if !antennaclaim.ValidPhotoID(id) { + continue + } + if err := os.RemoveAll(s.photoStored(id)); err != nil { + log.Printf("[antenna-claims] removing photo %s failed (the sweep retries): %v", id, err) + } + } +} + +// deletePhotos deletes the photo rows matching where (args bound in order) +// inside tx and returns their ids, to be unlinked after the commit. +func deletePhotos(ctx context.Context, tx *sql.Tx, where string, args ...interface{}) ([]string, error) { + rows, err := tx.QueryContext(ctx, `DELETE FROM node_claim_photos WHERE `+where+` RETURNING photo_id`, args...) + if err != nil { + return nil, err + } + defer rows.Close() + var ids []string + for rows.Next() { + var id string + if err := rows.Scan(&id); err != nil { + return nil, err + } + ids = append(ids, id) + } + return ids, rows.Err() +} + +// verifyPhotoFiles re-reads the inbox files of photo id and checks them +// against what the server announced: sizes, hashes, a JPEG header and the +// dimensions. The server is trusted no more than the queue file is. +func (s *Store) verifyPhotoFiles(id string, f antennaclaim.PhotoFiles) error { + dir := s.photoInbox(id) + for _, want := range []struct { + name string + size int + sum string + width, height int + }{ + {antennaclaim.PhotoFullName, f.FullBytes, f.FullSHA256, f.Width, f.Height}, + {antennaclaim.PhotoThumbName, f.ThumbBytes, f.ThumbSHA256, f.ThumbWidth, f.ThumbHeight}, + } { + b, err := readBounded(filepath.Join(dir, want.name), antennaclaim.MaxPhotoStoredBytes) + if err != nil || len(b) != want.size { + return errPhotoFiles + } + sum := sha256.Sum256(b) + if hex.EncodeToString(sum[:]) != want.sum { + return errPhotoFiles + } + cfg, err := jpeg.DecodeConfig(bytes.NewReader(b)) + if err != nil || cfg.Width != want.width || cfg.Height != want.height { + return errPhotoFiles + } + } + return nil +} + +// readBounded reads at most limit bytes of a regular file; a larger file, +// a directory or a symlink is an error. +func readBounded(path string, limit int) ([]byte, error) { + info, err := os.Lstat(path) + if err != nil { + return nil, err + } + if !info.Mode().IsRegular() || info.Size() > int64(limit) { + return nil, errPhotoFiles + } + f, err := os.Open(path) + if err != nil { + return nil, err + } + defer f.Close() + return io.ReadAll(io.LimitReader(f, int64(limit)+1)) +} + +// submitPhoto applies OpPhotoSubmit: the photo becomes the pending photo of +// its claim's node, replacing the node's previous pending photo. A replayed +// command reports the stored status. Any refusal removes the inbox entry. +func (s *Store) submitPhoto(ctx context.Context, cmd antennaclaim.Command, p photoPolicy, nowMs int64) (string, error) { + var status string + err := s.db.QueryRowContext(ctx, `SELECT status FROM node_claim_photos WHERE photo_id = ?`, cmd.PhotoID).Scan(&status) + if err == nil { + return status, nil + } + if err != sql.ErrNoRows { + return "", err + } + status, dropped, err := s.insertPhoto(ctx, cmd, p, nowMs) + if err != nil { + if rmErr := os.RemoveAll(s.photoInbox(cmd.PhotoID)); rmErr != nil { + log.Printf("[antenna-claims] removing refused inbox photo %s failed: %v", cmd.PhotoID, rmErr) + } + return "", err + } + s.unlinkPhotos(dropped) + return status, nil +} + +func (s *Store) insertPhoto(ctx context.Context, cmd antennaclaim.Command, p photoPolicy, nowMs int64) (string, []string, error) { + if !p.on { + return "", nil, errPhotosDisabled + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return "", nil, err + } + defer tx.Rollback() + var pubkey string + err = tx.QueryRowContext(ctx, `SELECT pubkey FROM node_antenna_claims WHERE request_id = ? AND `+antennaclaim.PhotoUploadSQL, + cmd.ClaimID, nowMs-p.limits.UploadWindow.Milliseconds()).Scan(&pubkey) + if err == sql.ErrNoRows { + return "", nil, errPhotoClaim + } + if err != nil { + return "", nil, err + } + f := *cmd.Photo + if err := s.verifyPhotoFiles(cmd.PhotoID, f); err != nil { + return "", nil, err + } + // The node's pending photo is replaced, so it counts against neither + // cap. + var otherPending, otherBytes int64 + if err := tx.QueryRowContext(ctx, `SELECT COALESCE(SUM(status = 'pending' AND pubkey != ?), 0), + COALESCE(SUM(CASE WHEN status = 'pending' AND pubkey = ? THEN 0 ELSE bytes END), 0) FROM node_claim_photos`, + pubkey, pubkey).Scan(&otherPending, &otherBytes); err != nil { + return "", nil, err + } + size := int64(f.FullBytes + f.ThumbBytes) + if otherPending >= int64(p.limits.MaxPending) { + return "", nil, errPhotosPending + } + if otherBytes+size > p.limits.MaxStoreBytes { + return "", nil, errPhotoStoreFull + } + dropped, err := deletePhotos(ctx, tx, `pubkey = ? AND status = 'pending'`, pubkey) + if err != nil { + return "", nil, err + } + created := cmd.CreatedAt + if created <= 0 { + created = nowMs + } + if _, err := tx.ExecContext(ctx, `INSERT INTO node_claim_photos + (photo_id, request_id, pubkey, status, sha256, thumb_sha256, bytes, width, height, created_at) + VALUES (?, ?, ?, 'pending', ?, ?, ?, ?, ?, ?)`, + cmd.PhotoID, cmd.ClaimID, pubkey, f.FullSHA256, f.ThumbSHA256, size, f.Width, f.Height, created); err != nil { + return "", nil, err + } + // Move, then commit: a crash in between leaves a directory without a + // row, which the sweep removes. + stored := s.photoStored(cmd.PhotoID) + if err := os.Rename(s.photoInbox(cmd.PhotoID), stored); err != nil { + return "", nil, err + } + syncPhotoDir(s.photoRoot()) + if err := tx.Commit(); err != nil { + os.RemoveAll(stored) + return "", nil, err + } + return antennaclaim.PhotoPending, dropped, nil +} + +// approvePhoto applies OpPhotoApprove. Only a pending photo of a claim whose +// details are approved and in force can be approved. When the node already +// has MaxApprovedPerNode approved photos, the oldest is replaced: deleted in +// the same transaction. +func (s *Store) approvePhoto(ctx context.Context, id string, p photoPolicy, nowMs int64) (string, error) { + if !p.on { + return "", errPhotosDisabled + } + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return "", err + } + defer tx.Rollback() + var status, pubkey string + var servable bool + err = tx.QueryRowContext(ctx, `SELECT p.status, p.pubkey, COALESCE((SELECT 1 FROM node_antenna_claims + WHERE request_id = p.request_id AND `+antennaclaim.PhotoServableSQL+`), 0) + FROM node_claim_photos p WHERE p.photo_id = ?`, id).Scan(&status, &pubkey, &servable) + if err == sql.ErrNoRows { + return "", errPhotoNotFound + } + if err != nil { + return "", err + } + if status == antennaclaim.PhotoApproved { + return status, nil + } + if !servable { + return "", errPhotoNotServed + } + dropped, err := deletePhotos(ctx, tx, `photo_id IN (SELECT photo_id FROM node_claim_photos + WHERE pubkey = ? AND status = 'approved' ORDER BY reviewed_at DESC, photo_id DESC LIMIT -1 OFFSET ?)`, + pubkey, p.limits.MaxApprovedPerNode-1) + if err != nil { + return "", err + } + if _, err := tx.ExecContext(ctx, `UPDATE node_claim_photos SET status = 'approved', reviewed_at = ? + WHERE photo_id = ? AND status = 'pending'`, nowMs, id); err != nil { + return "", err + } + if err := tx.Commit(); err != nil { + return "", err + } + s.unlinkPhotos(dropped) + return antennaclaim.PhotoApproved, nil +} + +// rejectPhoto applies OpPhotoReject: a pending or approved photo is +// deleted, row and files. It works with photos switched off, so an +// administrator can always take one down. +func (s *Store) rejectPhoto(ctx context.Context, id string) (string, error) { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return "", err + } + defer tx.Rollback() + dropped, err := deletePhotos(ctx, tx, `photo_id = ?`, id) + if err != nil { + return "", err + } + if len(dropped) == 0 { + return "", errPhotoNotFound + } + if err := tx.Commit(); err != nil { + return "", err + } + s.unlinkPhotos(dropped) + return antennaclaim.PhotoRejected, nil +} + +// sweepPhotos is the orphan sweep, run at every prune. It deletes the rows +// whose claim is no longer live (antennaclaim.PhotoLiveSQL) and the rows +// whose files are gone (a database restored without the photo directory), +// then the stored directories without a row (a crash between a commit and +// its unlink, or a pruned claim's cascade) and the inbox entries older than +// antennaclaim.PhotoInboxTTL. It removes only entries named like ours. +func (s *Store) sweepPhotos(ctx context.Context, now time.Time) { + if err := s.sweepPhotoRows(ctx); err != nil { + log.Printf("[antenna-claims] photo sweep failed: %v", err) + return + } + known := map[string]bool{} + rows, err := s.db.QueryContext(ctx, `SELECT photo_id FROM node_claim_photos`) + if err != nil { + log.Printf("[antenna-claims] photo sweep failed: %v", err) + return + } + for rows.Next() { + var id string + if rows.Scan(&id) == nil { + known[id] = true + } + } + err = rows.Err() + rows.Close() + if err != nil { + log.Printf("[antenna-claims] photo sweep failed: %v", err) + return + } + root := s.photoRoot() + entries, err := os.ReadDir(root) + if err != nil && !os.IsNotExist(err) { + log.Printf("[antenna-claims] photo sweep failed: %v", err) + return + } + removed := 0 + for _, e := range entries { + if e.IsDir() && antennaclaim.ValidPhotoID(e.Name()) && !known[e.Name()] { + if os.RemoveAll(filepath.Join(root, e.Name())) == nil { + removed++ + } + } + } + inbox := filepath.Join(root, antennaclaim.PhotoInboxName) + entries, err = os.ReadDir(inbox) + if err != nil && !os.IsNotExist(err) { + log.Printf("[antenna-claims] photo inbox sweep failed: %v", err) + } + for _, e := range entries { + name := strings.TrimPrefix(e.Name(), photoTmpPrefix) + if !antennaclaim.ValidPhotoID(name) { + continue + } + info, err := e.Info() + if err == nil && now.Sub(info.ModTime()) > antennaclaim.PhotoInboxTTL && os.RemoveAll(filepath.Join(inbox, e.Name())) == nil { + removed++ + } + } + if removed > 0 { + log.Printf("[antenna-claims] photo sweep removed %d orphaned file set(s)", removed) + } +} + +// photoTmpPrefix is the server's in-flight inbox directory prefix +// (cmd/server writes .tmp- and renames it into place). +const photoTmpPrefix = ".tmp-" + +// sweepPhotoRows deletes the rows of claims that are no longer live and the +// rows whose files are missing, in one transaction; their directories go in +// the directory pass that follows. +func (s *Store) sweepPhotoRows(ctx context.Context) error { + tx, err := s.db.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + if _, err := deletePhotos(ctx, tx, `request_id NOT IN (SELECT request_id FROM node_antenna_claims WHERE `+antennaclaim.PhotoLiveSQL+`)`); err != nil { + return err + } + rows, err := tx.QueryContext(ctx, `SELECT photo_id FROM node_claim_photos`) + if err != nil { + return err + } + var missing []string + for rows.Next() { + var id string + if err := rows.Scan(&id); err != nil { + rows.Close() + return err + } + if !antennaclaim.ValidPhotoID(id) || !s.photoFilesPresent(id) { + missing = append(missing, id) + } + } + err = rows.Err() + rows.Close() + if err != nil { + return err + } + for _, id := range missing { + if _, err := tx.ExecContext(ctx, `DELETE FROM node_claim_photos WHERE photo_id = ?`, id); err != nil { + return err + } + } + return tx.Commit() +} + +func (s *Store) photoFilesPresent(id string) bool { + for _, name := range []string{antennaclaim.PhotoFullName, antennaclaim.PhotoThumbName} { + info, err := os.Lstat(filepath.Join(s.photoStored(id), name)) + if err != nil || !info.Mode().IsRegular() { + return false + } + } + return true +} + +// syncPhotoDir fsyncs a directory so a rename into it survives a power +// loss; best effort, as for the queue. +func syncPhotoDir(dir string) { + d, err := os.Open(dir) + if err != nil { + return + } + d.Sync() + d.Close() +} diff --git a/cmd/ingestor/station_photos_1017_m5_test.go b/cmd/ingestor/station_photos_1017_m5_test.go new file mode 100644 index 000000000..b1ce54f79 --- /dev/null +++ b/cmd/ingestor/station_photos_1017_m5_test.go @@ -0,0 +1,585 @@ +package main + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/hex" + "fmt" + "image" + "image/color" + "image/jpeg" + "image/png" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/meshcore-analyzer/channelregistry/antennaclaim" +) + +// #1017 M5 — station photos, the writer side: the submit re-checks the +// claim, the files and the caps and moves the inbox entry; photos are never +// approved automatically; every deletion trigger removes the row and the +// files; the sweep heals a crash between a commit and its unlink. + +func photosOn(mod func(*antennaclaim.Config)) *antennaclaim.Config { + on := true + c := &antennaclaim.Config{Enabled: &on, DetailsEnabled: true} + if mod != nil { + mod(c) + } + return c +} + +// testJPEG encodes a w×h JPEG with no metadata. +func testJPEG(t *testing.T, w, h int, c color.RGBA) []byte { + t.Helper() + img := image.NewRGBA(image.Rect(0, 0, w, h)) + for i := 0; i < len(img.Pix); i += 4 { + img.Pix[i], img.Pix[i+1], img.Pix[i+2], img.Pix[i+3] = c.R, c.G, c.B, 255 + } + var buf bytes.Buffer + if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: 80}); err != nil { + t.Fatal(err) + } + return buf.Bytes() +} + +func sum256(b []byte) string { + s := sha256.Sum256(b) + return hex.EncodeToString(s[:]) +} + +// inboxPhoto writes a photo's two files into the inbox as the server does +// and returns what the server would announce. +func (r *claimRig) inboxPhoto(id string) antennaclaim.PhotoFiles { + r.t.Helper() + full, thumb := testJPEG(r.t, 160, 120, color.RGBA{200, 40, 40, 255}), testJPEG(r.t, 48, 36, color.RGBA{200, 40, 40, 255}) + dir := r.store.photoInbox(id) + if err := os.MkdirAll(dir, 0o700); err != nil { + r.t.Fatal(err) + } + for name, b := range map[string][]byte{antennaclaim.PhotoFullName: full, antennaclaim.PhotoThumbName: thumb} { + if err := os.WriteFile(filepath.Join(dir, name), b, 0o600); err != nil { + r.t.Fatal(err) + } + } + return antennaclaim.PhotoFiles{FullSHA256: sum256(full), ThumbSHA256: sum256(thumb), FullBytes: len(full), ThumbBytes: len(thumb), + Width: 160, Height: 120, ThumbWidth: 48, ThumbHeight: 36} +} + +// submitPhoto queues OpPhotoSubmit for files already in the inbox. +func (r *claimRig) submitPhoto(id, claimID string, f antennaclaim.PhotoFiles) antennaclaim.Result { + r.t.Helper() + r.enqueue(antennaclaim.Command{RequestID: id, Op: antennaclaim.OpPhotoSubmit, PhotoID: id, ClaimID: claimID, Photo: &f}) + r.runner.RunOnce(context.Background()) + r.clock = r.clock.Add(time.Second) + return r.result(id) +} + +func (r *claimRig) uploadPhoto(id, claimID string) antennaclaim.Result { + r.t.Helper() + return r.submitPhoto(id, claimID, r.inboxPhoto(id)) +} + +func (r *claimRig) decidePhoto(op, photoID string) antennaclaim.Result { + r.t.Helper() + r.ts++ + id := fmt.Sprintf("f%015x", r.ts) + r.enqueue(antennaclaim.Command{RequestID: id, Op: op, PhotoID: photoID}) + r.runner.RunOnce(context.Background()) + r.clock = r.clock.Add(time.Second) + return r.result(id) +} + +// photoState is a photo's row status ("" when there is none), its claim, +// and whether its stored and inbox directories exist. +type photoState struct { + status, claim string + stored, inbox bool +} + +func (r *claimRig) photo(id string) photoState { + r.t.Helper() + var p photoState + err := r.store.db.QueryRow(`SELECT status, request_id FROM node_claim_photos WHERE photo_id = ?`, id).Scan(&p.status, &p.claim) + if err != nil && !strings.Contains(err.Error(), "no rows") { + r.t.Fatal(err) + } + _, err = os.Stat(r.store.photoStored(id)) + p.stored = err == nil + _, err = os.Stat(r.store.photoInbox(id)) + p.inbox = err == nil + return p +} + +func (r *claimRig) wantGone(what, id string) { + r.t.Helper() + if p := r.photo(id); p.status != "" || p.stored || p.inbox { + r.t.Fatalf("%s: photo %s still there: %+v", what, id, p) + } +} + +// provenDetails issues and proves a details claim. +func (r *claimRig) provenDetails(id, code string, mod func(*antennaclaim.Command)) { + r.t.Helper() + r.claim898(id, code, func(c *antennaclaim.Command) { + setDetails(c) + if mod != nil { + mod(c) + } + }) + r.prove898(code, true) +} + +// approvedDetails issues, proves and approves a details claim. +func (r *claimRig) approvedDetails(id, code string, mod func(*antennaclaim.Command)) { + r.t.Helper() + r.provenDetails(id, code, mod) + if r.parts898(id).status != antennaclaim.StatusApproved { + if res := r.decide898(antennaclaim.OpApprove, id); res.Status != antennaclaim.StatusApproved { + r.t.Fatalf("approve %s: %+v", id, res) + } + } +} + +const ( + photo1 = "1000000000000001" + photo2 = "2000000000000002" + photo3 = "3000000000000003" + photo4 = "4000000000000004" + photo5 = "5000000000000005" + codeB = "8KX9QM" + codeC = "9KX9QM" +) + +func TestPhoto1017M5_SubmitMovesInboxAndInsertsPending(t *testing.T) { + r := newClaimRig(t, photosOn(nil)) + r.provenDetails(claimA, claimCode, nil) + res := r.uploadPhoto(photo1, claimA) + if res.Status != antennaclaim.PhotoPending || res.ClaimID != claimA || res.Error != "" { + t.Fatalf("submit: %+v", res) + } + p := r.photo(photo1) + if p.status != antennaclaim.PhotoPending || p.claim != claimA || !p.stored || p.inbox { + t.Fatalf("after submit: %+v, want pending, moved out of the inbox", p) + } + for _, name := range []string{antennaclaim.PhotoFullName, antennaclaim.PhotoThumbName} { + if _, err := os.Stat(filepath.Join(r.store.photoStored(photo1), name)); err != nil { + t.Fatalf("%s not stored: %v", name, err) + } + } + var bytesStored, w, h int + if err := r.store.db.QueryRow(`SELECT bytes, width, height FROM node_claim_photos WHERE photo_id = ?`, photo1).Scan(&bytesStored, &w, &h); err != nil { + t.Fatal(err) + } + if w != 160 || h != 120 || bytesStored <= 0 { + t.Fatalf("row: bytes=%d %dx%d", bytesStored, w, h) + } + // A replayed command (the result was lost) reports the stored status. + r.enqueue(antennaclaim.Command{RequestID: photo1, Op: antennaclaim.OpPhotoSubmit, PhotoID: photo1, ClaimID: claimA, + Photo: &antennaclaim.PhotoFiles{FullSHA256: strings.Repeat("a", 64), ThumbSHA256: strings.Repeat("a", 64), FullBytes: 1, ThumbBytes: 1, Width: 1, Height: 1, ThumbWidth: 1, ThumbHeight: 1}}) + r.runner.RunOnce(context.Background()) + if res := r.result(photo1); res.Status != antennaclaim.PhotoPending { + t.Fatalf("replay: %+v", res) + } +} + +// Owner decision: a photo is never approved automatically, whatever the +// switches say (4 combinations), even on an auto-approved claim. +func TestPhoto1017M5_NeverAutoApproved(t *testing.T) { + for _, tc := range []struct{ proven, details bool }{{false, false}, {true, false}, {false, true}, {true, true}} { + t.Run(fmt.Sprintf("autoApproveProven=%v,autoApproveDetails=%v", tc.proven, tc.details), func(t *testing.T) { + r := newClaimRig(t, photosOn(func(c *antennaclaim.Config) { + c.AutoApproveProven, c.AutoApproveDetails = tc.proven, tc.details + })) + r.provenDetails(claimA, claimCode, nil) + if res := r.uploadPhoto(photo1, claimA); res.Status != antennaclaim.PhotoPending { + t.Fatalf("submit: %+v", res) + } + // Further runs, a re-sent advert and an auto-approved claim + // change nothing. + r.advert(r.pub, r.priv, "Roof "+claimCode, true) + r.runner.RunOnce(context.Background()) + r.runner.Prune(context.Background()) + if p := r.photo(photo1); p.status != antennaclaim.PhotoPending { + t.Fatalf("photo is %q, want pending", p.status) + } + var approved int + if err := r.store.db.QueryRow(`SELECT COUNT(*) FROM node_claim_photos WHERE status = 'approved'`).Scan(&approved); err != nil || approved != 0 { + t.Fatalf("approved photos: %d (%v)", approved, err) + } + }) + } +} + +func TestPhoto1017M5_SubmitRefusals(t *testing.T) { + no := false + for name, tc := range map[string]struct { + cfg *antennaclaim.Config + setup func(r *claimRig) // leaves claimA in some state + tamper func(r *claimRig, f *antennaclaim.PhotoFiles) + wantErr string + }{ + "photos off": { + cfg: photosOn(func(c *antennaclaim.Config) { c.Photos = &antennaclaim.PhotoConfig{Enabled: &no} }), + setup: func(r *claimRig) { r.provenDetails(claimA, claimCode, nil) }, + wantErr: errPhotosDisabled.Error(), + }, + "details off": { + cfg: &antennaclaim.Config{Enabled: photosOn(nil).Enabled}, + setup: func(r *claimRig) { r.claim(claimA, 10, claimCode); r.prove898(claimCode, true) }, + wantErr: errPhotosDisabled.Error(), + }, + "claim not proven": { + setup: func(r *claimRig) { r.claim898(claimA, claimCode, setDetails) }, + wantErr: errPhotoClaim.Error(), + }, + "height-only claim": { + setup: func(r *claimRig) { r.claim(claimA, 10, claimCode); r.prove898(claimCode, true) }, + wantErr: errPhotoClaim.Error(), + }, + "rejected claim": { + setup: func(r *claimRig) { + r.provenDetails(claimA, claimCode, nil) + r.decide898(antennaclaim.OpReject, claimA) + }, + wantErr: errPhotoClaim.Error(), + }, + "outside the upload window": { + setup: func(r *claimRig) { + r.provenDetails(claimA, claimCode, nil) + r.clock = r.clock.Add(7*24*time.Hour + time.Minute) + }, + wantErr: errPhotoClaim.Error(), + }, + "unknown claim": { + setup: func(r *claimRig) {}, + wantErr: errPhotoClaim.Error(), + }, + "hash differs": { + setup: func(r *claimRig) { r.provenDetails(claimA, claimCode, nil) }, + tamper: func(r *claimRig, f *antennaclaim.PhotoFiles) { f.FullSHA256 = strings.Repeat("0", 64) }, + wantErr: errPhotoFiles.Error(), + }, + "size differs": { + setup: func(r *claimRig) { r.provenDetails(claimA, claimCode, nil) }, + tamper: func(r *claimRig, f *antennaclaim.PhotoFiles) { f.ThumbBytes++ }, + wantErr: errPhotoFiles.Error(), + }, + "dimensions differ": { + setup: func(r *claimRig) { r.provenDetails(claimA, claimCode, nil) }, + tamper: func(r *claimRig, f *antennaclaim.PhotoFiles) { f.Width = 161 }, + wantErr: errPhotoFiles.Error(), + }, + "not a JPEG": { + setup: func(r *claimRig) { r.provenDetails(claimA, claimCode, nil) }, + tamper: func(r *claimRig, f *antennaclaim.PhotoFiles) { + var buf bytes.Buffer + png.Encode(&buf, image.NewRGBA(image.Rect(0, 0, 160, 120))) + os.WriteFile(filepath.Join(r.store.photoInbox(photo1), antennaclaim.PhotoFullName), buf.Bytes(), 0o600) + f.FullSHA256, f.FullBytes = sum256(buf.Bytes()), buf.Len() + }, + wantErr: errPhotoFiles.Error(), + }, + "symlinked file": { + setup: func(r *claimRig) { r.provenDetails(claimA, claimCode, nil) }, + tamper: func(r *claimRig, f *antennaclaim.PhotoFiles) { + p := filepath.Join(r.store.photoInbox(photo1), antennaclaim.PhotoThumbName) + target := filepath.Join(r.t.TempDir(), "elsewhere.jpg") + b, _ := os.ReadFile(p) + os.WriteFile(target, b, 0o600) + os.Remove(p) + if err := os.Symlink(target, p); err != nil { + r.t.Skip("no symlinks here") + } + }, + wantErr: errPhotoFiles.Error(), + }, + "files missing": { + setup: func(r *claimRig) { r.provenDetails(claimA, claimCode, nil) }, + tamper: func(r *claimRig, f *antennaclaim.PhotoFiles) { os.RemoveAll(r.store.photoInbox(photo1)) }, + wantErr: errPhotoFiles.Error(), + }, + } { + t.Run(name, func(t *testing.T) { + cfg := tc.cfg + if cfg == nil { + cfg = photosOn(nil) + } + r := newClaimRig(t, cfg) + tc.setup(r) + f := r.inboxPhoto(photo1) + if tc.tamper != nil { + tc.tamper(r, &f) + } + res := r.submitPhoto(photo1, claimA, f) + if res.Status != antennaclaim.RequestError || res.Error != tc.wantErr { + t.Fatalf("result %+v, want error %q", res, tc.wantErr) + } + r.wantGone("refused", photo1) + }) + } +} + +func TestPhoto1017M5_Caps(t *testing.T) { + t.Run("pending in all", func(t *testing.T) { + r := newClaimRig(t, photosOn(func(c *antennaclaim.Config) { c.Photos = &antennaclaim.PhotoConfig{MaxPending: 1} })) + r.provenDetails(claimA, claimCode, nil) + if res := r.uploadPhoto(photo1, claimA); res.Status != antennaclaim.PhotoPending { + t.Fatalf("first: %+v", res) + } + // Another node's upload is refused while the cap is reached … + other := r.pk + r.pub, r.priv = testKey(3) + r.pk = hex.EncodeToString(r.pub) + r.provenDetails(claimB, codeB, nil) + if res := r.uploadPhoto(photo2, claimB); res.Error != errPhotosPending.Error() { + t.Fatalf("over the cap: %+v", res) + } + r.wantGone("over the cap", photo2) + // … but the same node replaces its own pending photo. + r.pub, r.priv = testKey(1) + r.pk = other + if res := r.uploadPhoto(photo3, claimA); res.Status != antennaclaim.PhotoPending { + t.Fatalf("replacement under the cap: %+v", res) + } + }) + t.Run("store bytes", func(t *testing.T) { + r := newClaimRig(t, photosOn(func(c *antennaclaim.Config) { c.Photos = &antennaclaim.PhotoConfig{MaxStoreMiB: 1} })) + r.provenDetails(claimA, claimCode, nil) + if _, err := r.store.db.Exec(`INSERT INTO node_claim_photos (photo_id, request_id, pubkey, status, sha256, thumb_sha256, bytes, width, height, created_at, reviewed_at) + VALUES (?, ?, ?, 'approved', ?, ?, ?, 10, 10, 1, 1)`, photo5, claimA, r.pk, strings.Repeat("a", 64), strings.Repeat("a", 64), 1<<20-100); err != nil { + t.Fatal(err) + } + if res := r.uploadPhoto(photo1, claimA); res.Error != errPhotoStoreFull.Error() { + t.Fatalf("over the store cap: %+v", res) + } + r.wantGone("store full", photo1) + }) +} + +// ── Deletion triggers: each removes the row and the files ────────────────── + +func TestPhoto1017M5_DeletionTriggers(t *testing.T) { + t.Run("replaced pending", func(t *testing.T) { + r := newClaimRig(t, photosOn(nil)) + r.provenDetails(claimA, claimCode, nil) + r.uploadPhoto(photo1, claimA) + r.uploadPhoto(photo2, claimA) + r.wantGone("replaced by a newer upload", photo1) + if p := r.photo(photo2); p.status != antennaclaim.PhotoPending || !p.stored { + t.Fatalf("new photo: %+v", p) + } + }) + t.Run("replaced approved beyond the per-node cap", func(t *testing.T) { + r := newClaimRig(t, photosOn(nil)) + r.approvedDetails(claimA, claimCode, nil) + for _, id := range []string{photo1, photo2, photo3, photo4} { + r.uploadPhoto(id, claimA) + if res := r.decidePhoto(antennaclaim.OpPhotoApprove, id); res.Status != antennaclaim.PhotoApproved { + t.Fatalf("approve %s: %+v", id, res) + } + } + r.wantGone("oldest of 4 approved", photo1) + for _, id := range []string{photo2, photo3, photo4} { + if p := r.photo(id); p.status != antennaclaim.PhotoApproved || !p.stored { + t.Fatalf("%s: %+v", id, p) + } + } + }) + t.Run("photo rejected, pending and approved", func(t *testing.T) { + r := newClaimRig(t, photosOn(nil)) + r.approvedDetails(claimA, claimCode, nil) + r.uploadPhoto(photo1, claimA) + r.decidePhoto(antennaclaim.OpPhotoApprove, photo1) + r.uploadPhoto(photo2, claimA) + for _, id := range []string{photo2, photo1} { + if res := r.decidePhoto(antennaclaim.OpPhotoReject, id); res.Status != antennaclaim.PhotoRejected { + t.Fatalf("reject %s: %+v", id, res) + } + r.wantGone("rejected", id) + } + if res := r.decidePhoto(antennaclaim.OpPhotoReject, photo1); res.Error != errPhotoNotFound.Error() { + t.Fatalf("reject again: %+v", res) + } + }) + t.Run("claim revoked", func(t *testing.T) { + r := newClaimRig(t, photosOn(nil)) + r.approvedDetails(claimA, claimCode, nil) + r.uploadPhoto(photo1, claimA) + r.decidePhoto(antennaclaim.OpPhotoApprove, photo1) + r.uploadPhoto(photo2, claimA) + r.decide898(antennaclaim.OpRevoke, claimA) + r.wantGone("claim revoked (approved photo)", photo1) + r.wantGone("claim revoked (pending photo)", photo2) + }) + t.Run("claim rejected", func(t *testing.T) { + r := newClaimRig(t, photosOn(nil)) + r.provenDetails(claimA, claimCode, nil) + r.uploadPhoto(photo1, claimA) + r.decide898(antennaclaim.OpReject, claimA) + r.wantGone("claim rejected", photo1) + }) + t.Run("details cleared by an approved clear", func(t *testing.T) { + r := newClaimRig(t, photosOn(nil)) + r.approvedDetails(claimA, claimCode, nil) + r.uploadPhoto(photo1, claimA) + r.decidePhoto(antennaclaim.OpPhotoApprove, photo1) + // A clear-only claim takes effect at its proof (approved by the owner). + r.claim898(claimB, codeB, func(c *antennaclaim.Command) { c.ClearDetails = true }) + r.prove898(codeB, true) + if p := r.parts898(claimB); p.status != antennaclaim.StatusApproved { + t.Fatalf("clear claim: %+v", p) + } + r.wantGone("details cleared", photo1) + }) + t.Run("superseded by a newer details set", func(t *testing.T) { + r := newClaimRig(t, photosOn(nil)) + r.approvedDetails(claimA, claimCode, nil) + r.uploadPhoto(photo1, claimA) + r.decidePhoto(antennaclaim.OpPhotoApprove, photo1) + r.approvedDetails(claimB, codeB, nil) + r.wantGone("superseded without keep", photo1) + }) + t.Run("a height-only claim keeps them", func(t *testing.T) { + r := newClaimRig(t, photosOn(nil)) + r.approvedDetails(claimA, claimCode, nil) + r.uploadPhoto(photo1, claimA) + r.decidePhoto(antennaclaim.OpPhotoApprove, photo1) + r.claim898(claimB, codeB, setHeight(12)) + r.prove898(codeB, true) + r.decide898(antennaclaim.OpApprove, claimB) + if p := r.photo(photo1); p.status != antennaclaim.PhotoApproved || p.claim != claimA || !p.stored { + t.Fatalf("after a height-only claim: %+v", p) + } + }) + t.Run("pruned claim: cascade, then the sweep", func(t *testing.T) { + r := newClaimRig(t, photosOn(nil)) + r.provenDetails(claimA, claimCode, nil) + r.uploadPhoto(photo1, claimA) + r.clock = r.clock.Add(31 * 24 * time.Hour) + r.runner.Prune(context.Background()) + var n int + if err := r.store.db.QueryRow(`SELECT COUNT(*) FROM node_antenna_claims WHERE request_id = ?`, claimA).Scan(&n); err != nil || n != 0 { + t.Fatalf("claim not pruned: %d (%v)", n, err) + } + r.wantGone("claim pruned", photo1) + }) +} + +// "photo: keep" (open question 12): the approval moves the photos to the +// new claim in the same transaction; the files stay. +func TestPhoto1017M5_KeepMovesPhotos(t *testing.T) { + r := newClaimRig(t, photosOn(nil)) + r.approvedDetails(claimA, claimCode, nil) + r.uploadPhoto(photo1, claimA) + r.decidePhoto(antennaclaim.OpPhotoApprove, photo1) + r.uploadPhoto(photo2, claimA) + r.approvedDetails(claimB, codeB, func(c *antennaclaim.Command) { c.KeepPhotos = true }) + if p := r.photo(photo1); p.status != antennaclaim.PhotoApproved || p.claim != claimB || !p.stored { + t.Fatalf("approved photo with keep: %+v", p) + } + if p := r.photo(photo2); p.status != antennaclaim.PhotoPending || p.claim != claimB || !p.stored { + t.Fatalf("pending photo with keep: %+v", p) + } + // The sweep leaves them: claim B is in force. + r.runner.Prune(context.Background()) + if p := r.photo(photo1); p.status != antennaclaim.PhotoApproved || !p.stored { + t.Fatalf("after the sweep: %+v", p) + } + // keepPhotos is stored only with details. + var keep bool + if err := r.store.db.QueryRow(`SELECT keep_photos FROM node_antenna_claims WHERE request_id = ?`, claimB).Scan(&keep); err != nil || !keep { + t.Fatalf("keep_photos = %v (%v)", keep, err) + } +} + +// A photo is approved only once its claim's details are approved and in +// force, so every approved photo belongs to the claim that is shown. +func TestPhoto1017M5_ApproveNeedsServableClaim(t *testing.T) { + r := newClaimRig(t, photosOn(nil)) + r.provenDetails(claimA, claimCode, nil) + r.uploadPhoto(photo1, claimA) + if res := r.decidePhoto(antennaclaim.OpPhotoApprove, photo1); res.Error != errPhotoNotServed.Error() { + t.Fatalf("approve on a proven claim: %+v", res) + } + r.decide898(antennaclaim.OpApprove, claimA) + if res := r.decidePhoto(antennaclaim.OpPhotoApprove, photo1); res.Status != antennaclaim.PhotoApproved { + t.Fatalf("approve on an approved claim: %+v", res) + } + if res := r.decidePhoto(antennaclaim.OpPhotoApprove, photo1); res.Status != antennaclaim.PhotoApproved { + t.Fatalf("approve again: %+v", res) + } + if res := r.decidePhoto(antennaclaim.OpPhotoApprove, photo5); res.Error != errPhotoNotFound.Error() { + t.Fatalf("approve unknown: %+v", res) + } +} + +// ── The sweep ───────────────────────────────────────────────────────────── + +// A crash between a commit and its unlink (or between the move and the +// insert) leaves a directory without a row; a database restored without +// the photo directory leaves rows without files. The next prune heals both +// and removes stale inbox entries, and touches nothing it does not own. +func TestPhoto1017M5_SweepHeals(t *testing.T) { + r := newClaimRig(t, photosOn(nil)) + r.approvedDetails(claimA, claimCode, nil) + r.uploadPhoto(photo1, claimA) // its row is deleted below, files left: commit, then crash + r.uploadPhoto(photo2, claimA) // replaces photo1 (pending); re-create photo1's files below + r.decidePhoto(antennaclaim.OpPhotoApprove, photo2) + r.uploadPhoto(photo3, claimA) // its files are deleted below: a restored database + // Commit, then crash before the unlink: the row is gone, the files stay. + if err := os.MkdirAll(r.store.photoStored(photo1), 0o700); err != nil { + t.Fatal(err) + } + os.WriteFile(filepath.Join(r.store.photoStored(photo1), antennaclaim.PhotoFullName), []byte("x"), 0o600) + // Moved, then crash before the commit: a directory, no row. + os.MkdirAll(r.store.photoStored(photo4), 0o700) + // A restored database: a row, no files. + os.RemoveAll(r.store.photoStored(photo3)) + // Inbox: one stale entry, one fresh, one stale temp directory. + stale, fresh := r.store.photoInbox(photo5), r.store.photoInbox("6000000000000006") + tmp := filepath.Join(r.store.photoRoot(), antennaclaim.PhotoInboxName, ".tmp-7000000000000007") + for _, d := range []string{stale, fresh, tmp} { + os.MkdirAll(d, 0o700) + } + old := time.Now().Add(-25 * time.Hour) + os.Chtimes(stale, old, old) + os.Chtimes(tmp, old, old) + // Not ours: left alone. + foreign := filepath.Join(r.store.photoRoot(), "README.txt") + os.WriteFile(foreign, []byte("operator note"), 0o600) + foreignDir := filepath.Join(r.store.photoRoot(), "backup-2026") + os.MkdirAll(foreignDir, 0o700) + + r.clock = time.Now() // the inbox age is measured on the real clock + r.runner.Prune(context.Background()) + + r.wantGone("directory without a row (crash after commit)", photo1) + r.wantGone("directory without a row (crash before commit)", photo4) + r.wantGone("row without files", photo3) + if p := r.photo(photo2); p.status != antennaclaim.PhotoApproved || !p.stored { + t.Fatalf("a healthy photo was swept: %+v", p) + } + for path, want := range map[string]bool{stale: false, tmp: false, fresh: true, foreign: true, foreignDir: true} { + if _, err := os.Stat(path); (err == nil) != want { + t.Errorf("%s exists=%v, want %v", path, err == nil, want) + } + } +} + +// Defence in depth: a row whose claim left the live states without its +// transition deleting it (an older ingestor, a manual edit) is swept. +func TestPhoto1017M5_SweepDropsPhotosOfDeadClaims(t *testing.T) { + r := newClaimRig(t, photosOn(nil)) + r.approvedDetails(claimA, claimCode, nil) + r.uploadPhoto(photo1, claimA) + if _, err := r.store.db.Exec(`UPDATE node_antenna_claims SET status = 'revoked', details_in_force = 0 WHERE request_id = ?`, claimA); err != nil { + t.Fatal(err) + } + r.runner.Prune(context.Background()) + r.wantGone("photo of a revoked claim", photo1) +} diff --git a/cmd/server/antenna_claims.go b/cmd/server/antenna_claims.go index cc3c7eed3..8c1832105 100644 --- a/cmd/server/antenna_claims.go +++ b/cmd/server/antenna_claims.go @@ -63,24 +63,34 @@ const ( // Height part: at most one of heightM (0–100 m, 0.1 m steps) or clear:true // (clear keeps its meaning, clear the height). Details part (#898): at most // one of details or clearDetails:true. At least one part. +// +// Photo (#1017 M5) is "keep" or absent, and only with details: when these +// details replace the ones in force, the node's photos move to this claim +// instead of being deleted. type AntennaClaimRequest struct { HeightM *float64 `json:"heightM,omitempty"` Clear bool `json:"clear,omitempty"` Details *antennaclaim.DetailsInput `json:"details,omitempty"` ClearDetails bool `json:"clearDetails,omitempty"` + Photo string `json:"photo,omitempty"` } +// photoKeep is AntennaClaimRequest.Photo's one value. +const photoKeep = "keep" + // AntennaClaimConfigResponse is GET /api/antenna-claims/config: whether // owners can claim a height right now (the submit route's own gate), whether // they can set station details (#898), and the operator's settings for the // owner page and the admin queue (#789 M3). AutoApproveDetails is whether // the ingestor approves a proven, unflagged claim that sets station details // without an administrator (#1007): antennaClaims.autoApproveDetails with -// detailsEnabled. +// detailsEnabled. PhotosEnabled is whether owners can add station photos +// (#1017 M5): antennaClaims.photos.enabled (on by default) with details. type AntennaClaimConfigResponse struct { Enabled bool `json:"enabled"` DetailsEnabled bool `json:"detailsEnabled"` AutoApproveDetails bool `json:"autoApproveDetails"` + PhotosEnabled bool `json:"photosEnabled"` antennaclaim.ClientSettings } @@ -88,11 +98,14 @@ type AntennaClaimConfigResponse struct { // Details is null when the node has none, they were cleared, the node moved // more than staleMoveM from where they were proven (Stale), or station // details are off. It never carries contactAdmin: StationDetails has no -// field for it. +// field for it. Photos (#1017 M5) are the approved photos of those details, +// only while photos are on; each is served at +// /api/nodes/{pubkey}/photo/{id}.jpg. type NodeStationResponse struct { Details *antennaclaim.StationDetails `json:"details"` ApprovedAt *int64 `json:"approvedAt,omitempty"` Stale bool `json:"stale,omitempty"` + Photos []antennaclaim.StationPhoto `json:"photos,omitempty"` } // NodeAntennaResponse is GET /api/nodes/{pubkey}/antenna (#789 M3): the @@ -165,6 +178,9 @@ type AdminAntennaClaim struct { // ContactAdmin is admin only: listed for proven and approved claims // (an unproven contact is anyone's text, Q5), never in a public route. ContactAdmin string `json:"contactAdmin,omitempty"` + // KeepPhotos: the claim moves the node's photos to itself when it is + // approved (#1017 M5). + KeepPhotos bool `json:"keepPhotos,omitempty"` } // AdminAntennaClaimListResponse is GET /api/admin/antenna-claims. @@ -205,6 +221,7 @@ type antennaClaimService struct { owners claimSnapshot[ownerHeight] stations claimSnapshot[ownerStation] unknownHW unknownHardwareLog + photos photoService // #1017 M5 } // maxUnknownHardwareLogged bounds the keys unknownHardwareLog remembers. @@ -286,9 +303,11 @@ func (s *claimSnapshot[V]) invalidate() { func newAntennaClaimService(cfg *Config, db *sql.DB, queueDir string) *antennaClaimService { var cc *antennaclaim.Config strongKey := false + var trusted []string if cfg != nil { cc = cfg.AntennaClaims strongKey = cfg.APIKey != "" && !IsWeakAPIKey(cfg.APIKey) + trusted = cfg.WSTrustedProxies() } svc := &antennaClaimService{ limits: cc.Limits(), @@ -303,6 +322,7 @@ func newAntennaClaimService(cfg *Config, db *sql.DB, queueDir string) *antennaCl } svc.enabled = cc.SubmissionsRequested() && strongKey && svc.queue != nil && db != nil svc.detailsEnabled = svc.enabled && cc.DetailsRequested() + svc.photos.init(cc, svc.detailsEnabled, queueDir, trusted) if cc.SubmissionsRequested() && !svc.enabled { log.Printf("[antenna-claims] WARNING: antennaClaims.enabled is set but owner claims stay closed: " + "they need a strong apiKey (16+ characters, not a placeholder) and a database") @@ -356,6 +376,7 @@ func (c *antennaClaimService) ownerStations(ctx context.Context) map[string]owne func (c *antennaClaimService) invalidateOwners() { c.owners.invalidate() c.stations.invalidate() + c.photos.set.invalidate() } // readOwnerHeights is one indexed SELECT of the heights in force with a @@ -462,7 +483,8 @@ func (s *Server) attachOwnerHeights(ctx context.Context, ends *[2]terrainEnd) { func (s *Server) handleAntennaClaimConfig(w http.ResponseWriter, r *http.Request) { noStore(w) c := s.antennaClaims() - writeJSON(w, AntennaClaimConfigResponse{Enabled: c.enabled, DetailsEnabled: c.detailsEnabled, AutoApproveDetails: c.autoDetails, ClientSettings: c.client}) + writeJSON(w, AntennaClaimConfigResponse{Enabled: c.enabled, DetailsEnabled: c.detailsEnabled, AutoApproveDetails: c.autoDetails, + PhotosEnabled: c.photos.enabled, ClientSettings: c.client}) } // GET /api/nodes/{pubkey}/station (#898): the node's approved station @@ -490,6 +512,7 @@ func (s *Server) handleNodeStation(w http.ResponseWriter, r *http.Request) { } else { d, at := st.details, st.approvedAt resp.Details, resp.ApprovedAt = &d, &at + resp.Photos = c.nodePhotos(r.Context(), pk, end.pt) } } } @@ -544,6 +567,10 @@ func (s *Server) handleAntennaClaimSubmit(w http.ResponseWriter, r *http.Request writeError(w, http.StatusBadRequest, "give either details or clearDetails:true, not both") return } + if body.Photo != "" && (body.Photo != photoKeep || body.Details == nil) { + writeError(w, http.StatusBadRequest, `photo must be "keep", and only with details`) + return + } if body.HeightM == nil && !body.Clear && body.Details == nil && !body.ClearDetails { writeError(w, http.StatusBadRequest, "give heightM, clear:true, details or clearDetails:true") return @@ -595,6 +622,7 @@ func (s *Server) handleAntennaClaimSubmit(w http.ResponseWriter, r *http.Request Clear: body.Clear, Details: body.Details, ClearDetails: body.ClearDetails, + KeepPhotos: body.Photo == photoKeep, Code: code, CreatedAt: now.UnixMilli(), } @@ -669,7 +697,7 @@ const ( COALESCE(n.name, ''), COALESCE(n.role, ''), n.lat, n.lon, COALESCE(c.height_op, ''), COALESCE(c.details_op, ''), c.height_in_force, c.details_in_force, c.antenna_type, c.gain_dbi, c.power_mask, c.installation, c.contact_public, c.hardware, c.hardware_model, - c.tx_power_dbm, c.cable_loss_db, c.azimuth_deg, c.beamwidth_deg, c.battery_wh, c.solar_w` + c.tx_power_dbm, c.cable_loss_db, c.azimuth_deg, c.beamwidth_deg, c.battery_wh, c.solar_w, c.keep_photos` claimFrom = ` FROM node_antenna_claims c LEFT JOIN nodes n ON n.public_key = c.pubkey` claimSelect = `SELECT ` + claimColumns + claimFrom // adminClaimSelect is the admin list's read, the only one that joins @@ -692,6 +720,7 @@ func scanClaim(sc interface{ Scan(...interface{}) error }, l antennaclaim.Limits &proven, &r.ProofHash, &plat, &plon, &reviewed, &r.ApprovedBy, &r.Name, &r.Role, &r.nodeLat, &r.nodeLon, &r.HeightOp, &r.DetailsOp, &r.HeightInForce, &r.DetailsInForce, &typ, &gain, &mask, &inst, &contactPublic, &hw, &hwModel} dest = append(dest, sf.dest()...) + dest = append(dest, &r.KeepPhotos) if withAdminContact { dest = append(dest, &contactAdmin) } diff --git a/cmd/server/antenna_claims_898_test.go b/cmd/server/antenna_claims_898_test.go index eeb473646..28ba87114 100644 --- a/cmd/server/antenna_claims_898_test.go +++ b/cmd/server/antenna_claims_898_test.go @@ -435,9 +435,16 @@ func TestAntennaClaims898_PerPartConflict(t *testing.T) { // claim. func TestAntennaClaims898_NoPerPartDecisionRoute(t *testing.T) { env := newClaim789Env(t, claimAdminKey, nil, nil) - var got []string + var got, photos []string env.router.Walk(func(route *mux.Route, _ *mux.Router, _ []*mux.Route) error { - if tpl, err := route.GetPathTemplate(); err == nil && strings.HasPrefix(tpl, "/api/admin/antenna-claims/") { + tpl, err := route.GetPathTemplate() + switch { + case err != nil: + case strings.HasPrefix(tpl, "/api/admin/antenna-claims/photos"): + // #1017 M5: station photos are their own resource, decided + // photo by photo; they decide no part of a claim. + photos = append(photos, tpl) + case strings.HasPrefix(tpl, "/api/admin/antenna-claims/"): got = append(got, tpl) } return nil @@ -447,6 +454,12 @@ func TestAntennaClaims898_NoPerPartDecisionRoute(t *testing.T) { if !reflect.DeepEqual(got, want) { t.Fatalf("admin decision routes %v, want exactly %v", got, want) } + sort.Strings(photos) + wantPhotos := []string{"/api/admin/antenna-claims/photos", "/api/admin/antenna-claims/photos/{photoId}", + "/api/admin/antenna-claims/photos/{photoId}/approve", "/api/admin/antenna-claims/photos/{photoId}/reject"} + if !reflect.DeepEqual(photos, wantPhotos) { + t.Fatalf("admin photo routes %v, want exactly %v", photos, wantPhotos) + } } // The admin list carries the parts, the in-force flags and the details. diff --git a/cmd/server/config.go b/cmd/server/config.go index c94616c84..e10661fdc 100644 --- a/cmd/server/config.go +++ b/cmd/server/config.go @@ -1258,6 +1258,7 @@ func (c *Config) applyCanonicalKeys(keys *configkey.Doc) error { c.Share.Packets.Enabled = keys.On("share", "packets", "enabled") c.Share.Areas.Enabled = keys.On("share", "areas", "enabled") c.AntennaClaims.ApplyGates(keys.On) + c.AntennaClaims.ApplyPhotoGate(keys.Bool) c.Accounts.ApplyGates(keys.On) c.ChannelProposals.ApplyGates(keys.On) if c.Privacy != nil { diff --git a/cmd/server/ip_rate_limit.go b/cmd/server/ip_rate_limit.go index 08c47102b..afec77dc9 100644 --- a/cmd/server/ip_rate_limit.go +++ b/cmd/server/ip_rate_limit.go @@ -144,15 +144,21 @@ type ipRateLimiter struct { // newIPRateLimiter returns nil when perMin ≤ 0 (off). func newIPRateLimiter(tag, what string, perMin int, trusted []*net.IPNet, logf func(string, ...interface{})) *ipRateLimiter { - if perMin <= 0 { + return newIPRateLimiterPer(tag, what, perMin, time.Minute, trusted, logf) +} + +// newIPRateLimiterPer is newIPRateLimiter for n requests per period (the +// station photos' uploads per hour, #1017 M5); nil when n ≤ 0 or period ≤ 0. +func newIPRateLimiterPer(tag, what string, n int, period time.Duration, trusted []*net.IPNet, logf func(string, ...interface{})) *ipRateLimiter { + if n <= 0 || period <= 0 { return nil } if logf == nil { logf = log.Printf } - interval := time.Minute / time.Duration(perMin) + interval := period / time.Duration(n) return &ipRateLimiter{ - tag: tag, what: what, interval: interval, burst: interval * time.Duration(perMin), + tag: tag, what: what, interval: interval, burst: interval * time.Duration(n), trusted: trusted, logf: logf, now: time.Now, maxClients: ipLimiterMaxClients, clients: make(map[string]time.Time), } diff --git a/cmd/server/openapi.go b/cmd/server/openapi.go index 678fac0e1..550d7e2f3 100644 --- a/cmd/server/openapi.go +++ b/cmd/server/openapi.go @@ -410,21 +410,28 @@ func routeDescriptions() map[string]routeMeta { // Owner antenna-height claims (#789 M2a). The server only queues // claims and decisions; the ingestor stores them and proves claims at // advert ingest. Timestamps are Unix ms. - "POST /api/nodes/{pubkey}/antenna-claims": {Summary: "Claim a node's antenna height", Description: "One JSON object without other fields, at most 1 KiB, carrying a height part, a station-details part (#898) or both. Height part: heightM (0-100 m in 0.1 m steps) or clear:true (clear always means: remove the height). Details part: details {antennaType: omni|yagi|panel|other, gainDbi: -5 to 20 dBi in 0.1 dBi steps, power: 1-3 of mains|solar|battery, installation: roof|mast|indoor|portable, hardware, hardwareModel, txPowerDbm, cableLossDb, azimuthDeg, beamwidthDeg, batteryWh, solarW, contactPublic, contactAdmin}, at least one field, or clearDetails:true. hardware is a key of GET /api/hardware (#1017; retired keys are accepted, an unknown key is refused). hardwareModel is a short free-text model name, allowed only with hardware other: 1-32 letters, digits, single spaces or . _ - + / ( ) (no @ or #), at most 64 bytes, with no leading or trailing space. #1017 M3: txPowerDbm is the TX power at the antenna port, after any amplifier (not the firmware's set tx value), -9 to 37 dBm in 0.1 dBm steps; cableLossDb is 0-20 dB in 0.1 dB steps; azimuthDeg (0-359, a whole number of degrees from true north, clockwise) is allowed only with antennaType yagi or panel, and beamwidthDeg (10-180 whole degrees, the horizontal -3 dB width) only with azimuthDeg; batteryWh (0.1-5000 Wh in 0.1 steps) only with power battery, and solarW (0.1-500 W in 0.1 steps, the panel) only with power solar. A value off its grid or range is refused, never rounded; none of these fields flags the claim for review (no EIRP check). Both contacts are optional, 1-32 letters, digits, single spaces or . _ - @ # + / with no leading or trailing space, and are refused, never rewritten; contactPublic is shown to everyone on GET /api/nodes/{pubkey}/station once approved; contactAdmin is admin only and never in a public response. A details part replaces all fourteen fields of the node's previous details. Open only when antennaClaims.enabled is set and a strong apiKey is configured (403 otherwise); setting details also needs antennaClaims.detailsEnabled (403), clearing them does not. Returns 202 {requestId, code, expiresAt, nameBudgetBytes, suggestedName}: put the 6-character code into the node's advert name as a whole space-separated word within the first nameBudgetBytes (23) bytes, appended after the name, and send an advert. A new advert with a valid signature from that public key proves the claim; the code is single-use and expires after 24 h. A proven claim that only clears takes effect at once; any other proven claim is approved by an administrator, or automatically unless it is flagged for review (a gain outside 0-15 dBi is flagged too, and a hardwareModel always is: free text is never auto-approved): a claim that sets details with antennaClaims.autoApproveDetails (and detailsEnabled), any other with antennaClaims.autoApproveProven. A switch turned on later does not approve claims already proven. One approval decides the whole claim, and replaces only the parts it carries. Hidden, unknown and unpositioned nodes all answer the same 404. A bad body costs no budget.", Tag: "nodes", + "POST /api/nodes/{pubkey}/antenna-claims": {Summary: "Claim a node's antenna height", Description: "One JSON object without other fields, at most 1 KiB, carrying a height part, a station-details part (#898) or both. Height part: heightM (0-100 m in 0.1 m steps) or clear:true (clear always means: remove the height). Details part: details {antennaType: omni|yagi|panel|other, gainDbi: -5 to 20 dBi in 0.1 dBi steps, power: 1-3 of mains|solar|battery, installation: roof|mast|indoor|portable, hardware, hardwareModel, txPowerDbm, cableLossDb, azimuthDeg, beamwidthDeg, batteryWh, solarW, contactPublic, contactAdmin}, at least one field, or clearDetails:true. photo:\"keep\" (#1017 M5, only with details) moves the node's station photos to this claim when it replaces the details in force; without it they are deleted then. hardware is a key of GET /api/hardware (#1017; retired keys are accepted, an unknown key is refused). hardwareModel is a short free-text model name, allowed only with hardware other: 1-32 letters, digits, single spaces or . _ - + / ( ) (no @ or #), at most 64 bytes, with no leading or trailing space. #1017 M3: txPowerDbm is the TX power at the antenna port, after any amplifier (not the firmware's set tx value), -9 to 37 dBm in 0.1 dBm steps; cableLossDb is 0-20 dB in 0.1 dB steps; azimuthDeg (0-359, a whole number of degrees from true north, clockwise) is allowed only with antennaType yagi or panel, and beamwidthDeg (10-180 whole degrees, the horizontal -3 dB width) only with azimuthDeg; batteryWh (0.1-5000 Wh in 0.1 steps) only with power battery, and solarW (0.1-500 W in 0.1 steps, the panel) only with power solar. A value off its grid or range is refused, never rounded; none of these fields flags the claim for review (no EIRP check). Both contacts are optional, 1-32 letters, digits, single spaces or . _ - @ # + / with no leading or trailing space, and are refused, never rewritten; contactPublic is shown to everyone on GET /api/nodes/{pubkey}/station once approved; contactAdmin is admin only and never in a public response. A details part replaces all fourteen fields of the node's previous details. Open only when antennaClaims.enabled is set and a strong apiKey is configured (403 otherwise); setting details also needs antennaClaims.detailsEnabled (403), clearing them does not. Returns 202 {requestId, code, expiresAt, nameBudgetBytes, suggestedName}: put the 6-character code into the node's advert name as a whole space-separated word within the first nameBudgetBytes (23) bytes, appended after the name, and send an advert. A new advert with a valid signature from that public key proves the claim; the code is single-use and expires after 24 h. A proven claim that only clears takes effect at once; any other proven claim is approved by an administrator, or automatically unless it is flagged for review (a gain outside 0-15 dBi is flagged too, and a hardwareModel always is: free text is never auto-approved): a claim that sets details with antennaClaims.autoApproveDetails (and detailsEnabled), any other with antennaClaims.autoApproveProven. A switch turned on later does not approve claims already proven. One approval decides the whole claim, and replaces only the parts it carries. Hidden, unknown and unpositioned nodes all answer the same 404. A bad body costs no budget.", Tag: "nodes", Errors: []routeError{ {Status: "403", Description: "Owner claims are disabled, or the body sets details while antennaClaims.detailsEnabled is off."}, {Status: "429", Description: "Global budget of antennaClaims.submissionsPerHour (default 20) exceeded; Retry-After gives the seconds to wait."}, {Status: "503", Description: "The claim queue is full (antennaClaims.maxQueuedRequests); Retry-After is set. The budget is refunded."}, }}, - "GET /api/hardware": {Summary: "The station hardware catalogue", Description: "#1017: {version, source, entries: [{key, name, maker, group, mcu?, radio?, repeaterCapable, retired?, aliases?}]}, one entry per device of the official MeshCore flasher device list (source credits it) plus `other` (last). group is esp, nrf or other; mcu and radio come from the flasher name or the reviewed firmware variant. repeaterCapable marks the entries a claim offers; a retired entry left the flasher list and its key stays valid. aliases are the observer model strings that map to the key (GET /api/observers hardware). Built into the server; Cache-Control public, max-age=86400, and an ETag of the version (If-None-Match gives 304).", Tag: "config"}, - "GET /api/nodes/{pubkey}/station": {Summary: "A node's owner-confirmed station details", Description: "Returns {details, approvedAt, stale}: the station details of the node's approved claim (#898): antennaType, gainDbi, power (canonical order mains, solar, battery), installation, hardware (a key of GET /api/hardware, #1017; left out when this server's catalogue does not know it), hardwareModel (a short free-text model name under hardware other, always reviewed by an administrator), the #1017 M3 radio, direction and power fields txPowerDbm (at the antenna port), cableLossDb, azimuthDeg, beamwidthDeg (absent when the owner gave none; no default is filled in), batteryWh and solarW, and the owner's optional contactPublic, each absent when not given (a zero is a value). details is null when there are none, they were removed, station details are off (antennaClaims.detailsEnabled), or the node moved more than antennaClaims.staleMoveM metres from where they were proven (then stale is true). The administrator contact is never returned. Served from a snapshot refreshed every 30 s; it does not need the terrain profile. Hidden, unknown and unpositioned nodes all answer the same 404.", Tag: "nodes"}, - "GET /api/antenna-claims/config": {Summary: "Antenna height claim availability", Description: "Returns {enabled, detailsEnabled, autoApproveDetails, pollInitialMs, pollBackoff, pollMaxMs, pollMaxAttempts, adminDefaultFilter}: whether owners can claim a node's antenna height (requires antennaClaims.enabled and a strong apiKey), the same gate as POST /api/nodes/{pubkey}/antenna-claims, whether they can also set station details (antennaClaims.detailsEnabled on top of that), whether a proven, unflagged claim that sets details is approved without an administrator (antennaClaims.autoApproveDetails with detailsEnabled, #1007), and the operator's antennaClaims settings for the claim status polling (first delay, growth factor, cap per delay, number of checks) and the admin queue's first filter.", Tag: "nodes"}, - "GET /api/nodes/{pubkey}/antenna": {Summary: "A node's current antenna height", Description: "Returns {antennaM, antennaSource, assumed, estimatePending}: the antenna height a terrain profile uses for the node and its source, by the profile's precedence (operator-node, owner, dsm-estimate, operator-role, role-default). It never measures the surface: estimatePending is true while no surface estimate is cached, and a profile may then still raise a default to one. Hidden, unknown and unpositioned nodes all answer the same 404; 503 while the terrain profile is off.", Tag: "nodes"}, - "GET /api/antenna-claims/requests/{requestId}": {Summary: "Status of an antenna height claim", Description: "Returns {status: queued|pending|proven|approved|rejected|revoked|expired|superseded|error, expiresAt, error}. The request id is the capability; the code is never returned here. A claim whose node is hidden answers like an unknown one (404).", Tag: "nodes"}, - "GET /api/admin/antenna-claims": {Summary: "List antenna height claims", Description: "Returns {claims, enabled, autoApprove, autoApproveDetails} (autoApprove is antennaClaims.autoApproveProven; autoApproveDetails is antennaClaims.autoApproveDetails with detailsEnabled), newest first, at most 1000. Each claim has id, pubkey, name, role, heightOp and detailsOp (set or clear; absent for a part the claim does not carry), heightM (set only when heightOp is set), details (station details, when detailsOp is set), heightInForce and detailsInForce (which parts of an approved claim are still served; a part a newer approved claim replaced is not), contactAdmin (admin only; never in a public response; listed for proven and approved claims only), status, needsReview (the height is more than antennaClaims.reviewDeltaM metres above the cached surface estimate + 2 m, or more than 2 m below the surface; or the gain is outside 0-15 dBi; or the details carry a free-text hardwareModel, #1017), createdAt, expiresAt, provenAt, proofHash, proofLat, proofLon, reviewedAt, approvedBy (auto, admin or owner), movedM and stale (the node moved more than antennaClaims.staleMoveM metres from the proof position; its height is then not used). Codes are never listed. Claims of hidden nodes are left out. Optional status filter.", Tag: "admin", Auth: true, QueryParams: []paramMeta{{Name: "status", Description: "pending, proven, approved, rejected, revoked, expired or superseded", Type: "string"}}}, - "POST /api/admin/antenna-claims/{id}/approve": {Summary: "Approve a proven antenna height claim", Description: "Queues the approval of the whole claim and returns 202 {requestId}; 409 unless the claim is proven, or when an approved claim proven later already carries one of its parts. The approved height becomes the node's owner antenna height in terrain profiles (below the operator's per-node height, above the surface-model estimate) and the approved details the node's station details; each replaces only the same part of the node's previous claims (a replaced details part loses its contacts).", Tag: "admin", Auth: true}, - "POST /api/admin/antenna-claims/{id}/reject": {Summary: "Reject an antenna height claim", Description: "Queues the rejection of the whole claim and returns 202 {requestId}; 409 unless the claim is pending or proven. Its contacts are deleted.", Tag: "admin", Auth: true}, - "POST /api/admin/antenna-claims/{id}/revoke": {Summary: "Revoke an approved antenna height claim", Description: "Queues the revocation of the whole claim and returns 202 {requestId}; 409 unless the claim is approved. Its contacts are deleted and nothing older comes back: profiles fall back to the next antenna source and the node has no station details, within 30 s.", Tag: "admin", Auth: true}, + "GET /api/hardware": {Summary: "The station hardware catalogue", Description: "#1017: {version, source, entries: [{key, name, maker, group, mcu?, radio?, repeaterCapable, retired?, aliases?}]}, one entry per device of the official MeshCore flasher device list (source credits it) plus `other` (last). group is esp, nrf or other; mcu and radio come from the flasher name or the reviewed firmware variant. repeaterCapable marks the entries a claim offers; a retired entry left the flasher list and its key stays valid. aliases are the observer model strings that map to the key (GET /api/observers hardware). Built into the server; Cache-Control public, max-age=86400, and an ETag of the version (If-None-Match gives 304).", Tag: "config"}, + "GET /api/nodes/{pubkey}/station": {Summary: "A node's owner-confirmed station details", Description: "Returns {details, approvedAt, stale, photos}: the station details of the node's approved claim (#898): antennaType, gainDbi, power (canonical order mains, solar, battery), installation, hardware (a key of GET /api/hardware, #1017; left out when this server's catalogue does not know it), hardwareModel (a short free-text model name under hardware other, always reviewed by an administrator), the #1017 M3 radio, direction and power fields txPowerDbm (at the antenna port), cableLossDb, azimuthDeg, beamwidthDeg (absent when the owner gave none; no default is filled in), batteryWh and solarW, and the owner's optional contactPublic, each absent when not given (a zero is a value). details is null when there are none, they were removed, station details are off (antennaClaims.detailsEnabled), or the node moved more than antennaClaims.staleMoveM metres from where they were proven (then stale is true). photos (#1017 M5) lists the approved photos of those details, {id, width, height, approvedAt} in approval order, served at GET /api/nodes/{pubkey}/photo/{id}.jpg; absent while photos are off. The administrator contact is never returned. Served from a snapshot refreshed every 30 s; it does not need the terrain profile. Hidden, unknown and unpositioned nodes all answer the same 404.", Tag: "nodes"}, + "GET /api/antenna-claims/config": {Summary: "Antenna height claim availability", Description: "Returns {enabled, detailsEnabled, autoApproveDetails, photosEnabled, pollInitialMs, pollBackoff, pollMaxMs, pollMaxAttempts, adminDefaultFilter}: whether owners can claim a node's antenna height (requires antennaClaims.enabled and a strong apiKey), the same gate as POST /api/nodes/{pubkey}/antenna-claims, whether they can also set station details (antennaClaims.detailsEnabled on top of that), whether a proven, unflagged claim that sets details is approved without an administrator (antennaClaims.autoApproveDetails with detailsEnabled, #1007), whether owners can add station photos (antennaClaims.photos.enabled, on by default, with detailsEnabled; #1017 M5), and the operator's antennaClaims settings for the claim status polling (first delay, growth factor, cap per delay, number of checks) and the admin queue's first filter.", Tag: "nodes"}, + "GET /api/nodes/{pubkey}/antenna": {Summary: "A node's current antenna height", Description: "Returns {antennaM, antennaSource, assumed, estimatePending}: the antenna height a terrain profile uses for the node and its source, by the profile's precedence (operator-node, owner, dsm-estimate, operator-role, role-default). It never measures the surface: estimatePending is true while no surface estimate is cached, and a profile may then still raise a default to one. Hidden, unknown and unpositioned nodes all answer the same 404; 503 while the terrain profile is off.", Tag: "nodes"}, + "GET /api/antenna-claims/requests/{requestId}": {Summary: "Status of an antenna height claim", Description: "Returns {status: queued|pending|proven|approved|rejected|revoked|expired|superseded|error, expiresAt, error}. The request id is the capability; the code is never returned here. A claim whose node is hidden answers like an unknown one (404).", Tag: "nodes"}, + "GET /api/admin/antenna-claims": {Summary: "List antenna height claims", Description: "Returns {claims, enabled, autoApprove, autoApproveDetails} (autoApprove is antennaClaims.autoApproveProven; autoApproveDetails is antennaClaims.autoApproveDetails with detailsEnabled), newest first, at most 1000. Each claim has id, pubkey, name, role, heightOp and detailsOp (set or clear; absent for a part the claim does not carry), heightM (set only when heightOp is set), details (station details, when detailsOp is set), heightInForce and detailsInForce (which parts of an approved claim are still served; a part a newer approved claim replaced is not), contactAdmin (admin only; never in a public response; listed for proven and approved claims only), status, needsReview (the height is more than antennaClaims.reviewDeltaM metres above the cached surface estimate + 2 m, or more than 2 m below the surface; or the gain is outside 0-15 dBi; or the details carry a free-text hardwareModel, #1017), createdAt, expiresAt, provenAt, proofHash, proofLat, proofLon, reviewedAt, approvedBy (auto, admin or owner), keepPhotos (#1017 M5: the claim keeps the node's photos when approved), movedM and stale (the node moved more than antennaClaims.staleMoveM metres from the proof position; its height is then not used). Codes are never listed. Claims of hidden nodes are left out. Optional status filter.", Tag: "admin", Auth: true, QueryParams: []paramMeta{{Name: "status", Description: "pending, proven, approved, rejected, revoked, expired or superseded", Type: "string"}}}, + "POST /api/admin/antenna-claims/{id}/approve": {Summary: "Approve a proven antenna height claim", Description: "Queues the approval of the whole claim and returns 202 {requestId}; 409 unless the claim is proven, or when an approved claim proven later already carries one of its parts. The approved height becomes the node's owner antenna height in terrain profiles (below the operator's per-node height, above the surface-model estimate) and the approved details the node's station details; each replaces only the same part of the node's previous claims (a replaced details part loses its contacts).", Tag: "admin", Auth: true}, + "POST /api/admin/antenna-claims/{id}/reject": {Summary: "Reject an antenna height claim", Description: "Queues the rejection of the whole claim and returns 202 {requestId}; 409 unless the claim is pending or proven. Its contacts and station photos are deleted.", Tag: "admin", Auth: true}, + "POST /api/antenna-claims/requests/{requestId}/photo": {Summary: "Add a station photo to a claim (#1017 M5)", Description: "The body is the image itself, Content-Type image/jpeg or image/png (sniffed from its bytes too; anything else is 415), at most antennaClaims.photos.maxUploadMiB (default 8 MiB; 413). The request id of the claim is the capability: the claim must set station details and be proven, or approved with its details in force, and have been proven within antennaClaims.photos.uploadWindowDays (default 7) days (409 otherwise). The header is checked before any pixel is decoded: at most antennaClaims.photos.maxMegapixels (default 16 MP), 8192 px a side, and what the decoder would allocate at most 4 bytes per allowed pixel (413). The server re-encodes the photo as JPEG (at most 1600 px on the long edge, quality 80, and a 480 px thumbnail, together at most 1 MiB), turned upright from the EXIF orientation and with no metadata at all (no EXIF, XMP, GPS, ICC or comment), and stores nothing else. Returns 202 {photoId, status: queued, width, height}; poll GET /api/antenna-claims/photos/{photoId}. A photo is never approved automatically: an administrator reviews every one. A new photo replaces the node's photo waiting for review. At most two uploads are processed at once (503 with Retry-After beyond that); antennaClaims.photos.uploadsPerHourPerIP (default 10) per client (429), refunded when an upload is refused. 403 while photos are off (antennaClaims.photos.enabled, on by default, needs detailsEnabled). Hidden and unknown claims answer 404.", Tag: "nodes"}, + "GET /api/antenna-claims/photos/{photoId}": {Summary: "Status of a station photo upload", Description: "Returns {status: queued|pending|approved|error, error}. The photo id is the capability. A photo that was rejected or replaced, or whose node is hidden, answers 404.", Tag: "nodes"}, + "GET /api/nodes/{pubkey}/photo/{file}": {Summary: "An approved station photo", Description: "file is {photoId}.jpg; size is thumb (480 px) or full (1600 px, the default). Served as image/jpeg with Cache-Control: public, max-age=31536000, immutable (the URL changes with the photo) and an ETag. Only an approved photo of the node's approved, in-force station details, while photos are on and the node has not moved more than antennaClaims.staleMoveM metres from where its claim was proven; hidden, unknown, stale, pending, rejected and switched-off all answer the same 404. The ids are listed by GET /api/nodes/{pubkey}/station (photos). Never in OG tags, node cards, /api/nodes or exports.", Tag: "nodes", QueryParams: []paramMeta{{Name: "size", Description: "thumb or full (default)", Type: "string"}}}, + "GET /api/admin/antenna-claims/photos": {Summary: "List station photos", Description: "Returns {photos, enabled}, newest first, at most 1000: id, claimId, pubkey, name, role, status (pending or approved), claimStatus, servable (the claim's details are approved and in force, so approving the photo shows it), bytes (both files), width, height, createdAt, reviewedAt. Photos of hidden nodes are left out. Review checklist: reject anything showing people or faces, house numbers, number plates, screens, or text other than the equipment.", Tag: "admin", Auth: true, QueryParams: []paramMeta{{Name: "status", Description: "pending or approved", Type: "string"}}}, + "GET /api/admin/antenna-claims/photos/{photoId}": {Summary: "A station photo for review", Description: "The image itself (image/jpeg, no-store), pending or approved, for review; size is thumb or full (default). Fetch it with the X-API-Key header as a blob; the key never goes in a URL.", Tag: "admin", Auth: true, QueryParams: []paramMeta{{Name: "size", Description: "thumb or full (default)", Type: "string"}}}, + "POST /api/admin/antenna-claims/photos/{photoId}/approve": {Summary: "Approve a station photo", Description: "Queues the approval and returns 202 {requestId}; 409 unless the photo is pending and its claim's details are approved and in force, 403 while photos are off. A node shows at most antennaClaims.photos.maxApprovedPerNode (default 3) photos: approving one more deletes the oldest.", Tag: "admin", Auth: true}, + "POST /api/admin/antenna-claims/photos/{photoId}/reject": {Summary: "Reject a station photo", Description: "Queues the deletion of a pending or approved photo, row and files, and returns 202 {requestId}. Works while photos are off, so a photo can always be taken down.", Tag: "admin", Auth: true}, + "POST /api/admin/antenna-claims/{id}/revoke": {Summary: "Revoke an approved antenna height claim", Description: "Queues the revocation of the whole claim and returns 202 {requestId}; 409 unless the claim is approved. Its contacts and station photos are deleted and nothing older comes back: profiles fall back to the next antenna source and the node has no station details, within 30 s.", Tag: "admin", Auth: true}, // Owner accounts (#1018 M1) "GET /api/account/config": {Summary: "Owner account availability", Description: "Returns {enabled, available, sessionDays, loginCodeMinutes, maxMyNodes}. enabled: sign-in is open (accounts.enabled with a strong apiKey and a database); available: the ingestor has also created the session key, so a sign-in can complete now.", Tag: "account"}, "POST /api/account/login": {Summary: "Start a sign-in with a companion", Description: "Body {pubkey}, at most 1 KiB. Same-origin JSON only: an Origin naming this site is required and a cross-site Sec-Fetch-Site is refused (403). Only a known companion (an ADV_TYPE_CHAT advert) may sign in; an unknown node, any other role and a blacklisted key all answer the same 404, while a name hidden only by a hidden-name prefix may sign in. Returns 202 {requestId, code, redeemSecret, expiresAt, nameBudgetBytes, suggestedName}: put the 6-character code in the companion's name as a whole space-separated word within the first nameBudgetBytes bytes (31 without a shared position, 23 with one) and send a flood advert. The code is single-use, bound to that key and expires after accounts.loginCodeMinutes (15). Keep redeemSecret: only its holder can turn the proven sign-in into a session (POST /api/account/session). Bounded by a global accounts.loginsPerHour window (429) and accounts.loginsPerMinutePerIP behind webSocket.trustedProxies; 503 while the queue is full or the session key does not exist yet; 403 while sign-in is closed.", Tag: "account"}, diff --git a/cmd/server/readonly_invariant_test.go b/cmd/server/readonly_invariant_test.go index 86cd39721..4d0e2fb39 100644 --- a/cmd/server/readonly_invariant_test.go +++ b/cmd/server/readonly_invariant_test.go @@ -3,6 +3,9 @@ package main import ( "database/sql" "fmt" + "go/ast" + "go/parser" + "go/token" "os" "path/filepath" "reflect" @@ -216,9 +219,10 @@ func nodeTableWritePattern(verb, trailer string) *regexp.Regexp { // hung off them, in the shapes nodeTableWritePattern covers, plus the owner // antenna-height claims (#789 M2a) and their admin contacts (#898), and the // owner-account tables (#1018 M1, and the node links, notices and -// objections of M2a), which only the ingestor writes. +// objections of M2a), and the station photos (#1017 M5), which only the +// ingestor writes. func txTableWritePattern(verb string) *regexp.Regexp { - const table = "[\"`\\[]?(transmissions|observations|observers|dropped_packets|ping_triggers|route_mask_changes|node_antenna_claims|node_claim_admin_contacts|accounts|account_proofs|account_my_nodes|account_node_links|account_notices|link_objections)[\"`\\]]?" + const table = "[\"`\\[]?(transmissions|observations|observers|dropped_packets|ping_triggers|route_mask_changes|node_antenna_claims|node_claim_admin_contacts|accounts|account_proofs|account_my_nodes|account_node_links|account_notices|link_objections|node_claim_photos)[\"`\\]]?" return regexp.MustCompile(`(?i)` + verb + `\s+` + table + `\b`) } @@ -327,6 +331,9 @@ func TestServerHasNoPacketTableWritesIsSensitive(t *testing.T) { `INSERT INTO link_objections (objection_id) VALUES (?)`, `UPDATE link_objections SET status = 'upheld'`, `DELETE FROM link_objections WHERE link_id = ?`, + `INSERT INTO node_claim_photos (photo_id) VALUES (?)`, + `UPDATE node_claim_photos SET status = 'approved'`, + `DELETE FROM node_claim_photos WHERE photo_id = ?`, } { if !matches(stmt) { t.Errorf("the guard does not match %q", stmt) @@ -345,6 +352,7 @@ func TestServerHasNoPacketTableWritesIsSensitive(t *testing.T) { `FROM account_node_links l LEFT JOIN nodes n ON n.public_key = l.pubkey`, `SELECT COUNT(*) FROM link_objections WHERE objection_id = ?`, `FROM account_notices x LEFT JOIN nodes n ON n.public_key = x.pubkey`, + `FROM node_claim_photos p JOIN node_antenna_claims c ON c.request_id = p.request_id`, `tx_inserted`, } { if matches(stmt) { @@ -352,3 +360,65 @@ func TestServerHasNoPacketTableWritesIsSensitive(t *testing.T) { } } } + +// fileWriteFuncs are the os calls that create, change or remove files. +var fileWriteFuncs = map[string]bool{ + "WriteFile": true, "Create": true, "CreateTemp": true, "OpenFile": true, "Mkdir": true, "MkdirAll": true, + "MkdirTemp": true, "Rename": true, "Remove": true, "RemoveAll": true, "Symlink": true, "Link": true, + "Chmod": true, "Chtimes": true, "Truncate": true, "Chown": true, "Lchown": true, +} + +// photoInboxWriters are the only functions that may write under the photo +// store, and they write only under its inbox (#1017 M5). +var photoInboxWriters = map[string]bool{"writePhotoInbox": true, "removePhotoInbox": true, "writeSyncedFile": true} + +// TestServerPhotoWritesOnlyInbox keeps the station photo store read-only +// for the server except its inbox (#1017 M5, #1283): in the station photo +// files every file-writing os call sits in one of photoInboxWriters, and no +// other server file names the photo store at all. The behaviour is pinned +// by TestStationPhotos1017M5_UploadWritesOnlyTheInbox. +func TestServerPhotoWritesOnlyInbox(t *testing.T) { + entries, err := os.ReadDir(".") + if err != nil { + t.Fatal(err) + } + fset := token.NewFileSet() + sawWriter := map[string]bool{} + for _, e := range entries { + name := e.Name() + if e.IsDir() || !strings.HasSuffix(name, ".go") || strings.HasSuffix(name, "_test.go") { + continue + } + f, err := parser.ParseFile(fset, name, nil, 0) + if err != nil { + t.Fatal(err) + } + photoFile := strings.HasPrefix(name, "station_photo") + for _, decl := range f.Decls { + fn, _ := decl.(*ast.FuncDecl) + ast.Inspect(decl, func(n ast.Node) bool { + switch x := n.(type) { + case *ast.SelectorExpr: + pkg, ok := x.X.(*ast.Ident) + if !ok { + return true + } + if pkg.Name == "antennaclaim" && (x.Sel.Name == "PhotoDirName" || x.Sel.Name == "PhotoDir" || x.Sel.Name == "PhotoInboxName") && !photoFile { + t.Errorf("%s names the photo store (%s): only station_photos.go may", fset.Position(x.Pos()), x.Sel.Name) + } + if pkg.Name == "os" && fileWriteFuncs[x.Sel.Name] && photoFile { + if fn == nil || !photoInboxWriters[fn.Name.Name] { + t.Errorf("%s: os.%s outside the inbox writers", fset.Position(x.Pos()), x.Sel.Name) + } else { + sawWriter[fn.Name.Name] = true + } + } + } + return true + }) + } + } + if !sawWriter["writePhotoInbox"] { + t.Fatal("writePhotoInbox has no os write: the scan is not looking at the right code") + } +} diff --git a/cmd/server/routes.go b/cmd/server/routes.go index 49b637023..6f37c4647 100644 --- a/cmd/server/routes.go +++ b/cmd/server/routes.go @@ -433,6 +433,11 @@ func (s *Server) RegisterRoutes(r *mux.Router) { r.Handle("/api/admin/channel-proposals/{id}/reject", s.requireAPIKey(s.handleAdminChannelProposalDecision(channelregistry.OpReject))).Methods("POST") r.Handle("/api/admin/channel-proposals/{id}/revoke", s.requireAPIKey(http.HandlerFunc(s.handleAdminChannelProposalRevoke))).Methods("POST") r.Handle("/api/admin/antenna-claims", s.requireAPIKey(http.HandlerFunc(s.handleAdminAntennaClaims))).Methods("GET") + // Station photos (#1017 M5): review, queued for the ingestor. + r.Handle("/api/admin/antenna-claims/photos", s.requireAPIKey(http.HandlerFunc(s.handleAdminStationPhotos))).Methods("GET") + r.Handle("/api/admin/antenna-claims/photos/{photoId}", s.requireAPIKey(http.HandlerFunc(s.handleAdminStationPhotoImage))).Methods("GET") + r.Handle("/api/admin/antenna-claims/photos/{photoId}/approve", s.requireAPIKey(s.handleAdminStationPhotoDecision(antennaclaim.OpPhotoApprove))).Methods("POST") + r.Handle("/api/admin/antenna-claims/photos/{photoId}/reject", s.requireAPIKey(s.handleAdminStationPhotoDecision(antennaclaim.OpPhotoReject))).Methods("POST") r.Handle("/api/admin/antenna-claims/{id}/approve", s.requireAPIKey(s.handleAdminAntennaClaimDecision(antennaclaim.OpApprove))).Methods("POST") r.Handle("/api/admin/antenna-claims/{id}/reject", s.requireAPIKey(s.handleAdminAntennaClaimDecision(antennaclaim.OpReject))).Methods("POST") r.Handle("/api/admin/antenna-claims/{id}/revoke", s.requireAPIKey(s.handleAdminAntennaClaimDecision(antennaclaim.OpRevoke))).Methods("POST") @@ -527,6 +532,11 @@ func (s *Server) RegisterRoutes(r *mux.Router) { r.HandleFunc("/api/nodes/{pubkey}/station", s.handleNodeStation).Methods("GET") r.HandleFunc("/api/hardware", s.handleHardwareCatalogue).Methods("GET") r.HandleFunc("/api/antenna-claims/requests/{requestId}", s.handleAntennaClaimRequest).Methods("GET") + // Station photos (#1017 M5): the owner's upload and its status, and the + // public approved photo. + r.HandleFunc("/api/antenna-claims/requests/{requestId}/photo", s.handleStationPhotoUpload).Methods("POST") + r.HandleFunc("/api/antenna-claims/photos/{photoId}", s.handleStationPhotoStatus).Methods("GET") + r.HandleFunc("/api/nodes/{pubkey}/photo/{file}", s.handleStationPhotoPublic).Methods("GET") // Owner accounts (#1018 M1). r.HandleFunc("/api/account/config", s.handleAccountConfig).Methods("GET") r.HandleFunc("/api/account/login", s.handleAccountLogin).Methods("POST") diff --git a/cmd/server/station_photo_image.go b/cmd/server/station_photo_image.go new file mode 100644 index 000000000..93c65db14 --- /dev/null +++ b/cmd/server/station_photo_image.go @@ -0,0 +1,487 @@ +package main + +// Station photos (#1017 M5) — the image side: probe an upload's header, +// refuse what is too large BEFORE any pixel is decoded, then decode, +// downscale, apply the EXIF orientation and re-encode as plain JPEGs. +// +// Stripping holds by construction: image/jpeg writes no metadata at all (no +// APP1 Exif or XMP, no GPS, no ICC, no comment), and the output is encoded +// from decoded pixels only. The orientation tag is the one value read from +// the metadata, by a bounded parse of the APP1 segment. +// +// Memory: probePhoto estimates what the decoder will allocate from the +// header (dimensions, components, subsampling, progressive coefficients, +// PNG bit depth and interlacing) and refuses an upload above +// photoDecodeBudget, so a decompression bomb or a header-only 30000×30000 +// JPEG is refused at the header. Downscaling is an area average over one +// source row at a time: it holds a row and two output rows, never a second +// full-size copy. + +import ( + "bytes" + "encoding/binary" + "errors" + "image" + "image/color" + "image/draw" + "image/jpeg" + "image/png" + "math" + + "github.com/meshcore-analyzer/channelregistry/antennaclaim" +) + +// Upload formats. +const ( + photoFormatJPEG = "image/jpeg" + photoFormatPNG = "image/png" +) + +// Photo refusals, answered verbatim. +var ( + errPhotoFormat = errors.New("the photo must be a JPEG or PNG image, sent as image/jpeg or image/png") + errPhotoTooLarge = errors.New("the photo is too large: at most the configured megapixels and 8192 px a side") + errPhotoUnread = errors.New("the photo could not be read") + errPhotoDetailed = errors.New("the photo could not be made small enough; try a smaller or less detailed photo") +) + +// sniffPhoto returns the format of b from its magic bytes alone, or "". +func sniffPhoto(b []byte) string { + switch { + case len(b) >= 3 && b[0] == 0xFF && b[1] == 0xD8 && b[2] == 0xFF: + return photoFormatJPEG + case len(b) >= 8 && bytes.Equal(b[:8], []byte("\x89PNG\r\n\x1a\n")): + return photoFormatPNG + } + return "" +} + +// photoProbe is what the header says about an upload. +type photoProbe struct { + format string + width, height int + orientation int // EXIF 1–8; 1 when absent or unreadable + decodeBytes int64 // estimated decoder allocation +} + +// probePhoto reads the header of an upload whose magic bytes said format +// and checks it against maxPixels, MaxPhotoSidePx and the decode budget +// (4 bytes per allowed pixel: an 8-bit RGBA image at the pixel cap). It +// never decodes pixel data. +func probePhoto(b []byte, format string, maxPixels int) (photoProbe, error) { + p := photoProbe{format: format, orientation: 1} + var err error + switch format { + case photoFormatJPEG: + err = probeJPEG(b, &p) + case photoFormatPNG: + err = probePNG(b, &p) + default: + return p, errPhotoFormat + } + if err != nil { + return p, err + } + if p.width < 1 || p.height < 1 { + return p, errPhotoUnread + } + if p.width > antennaclaim.MaxPhotoSidePx || p.height > antennaclaim.MaxPhotoSidePx || + int64(p.width)*int64(p.height) > int64(maxPixels) || p.decodeBytes > photoDecodeBudget(maxPixels) { + return p, errPhotoTooLarge + } + // The standard library's own header read must agree. + var cfg image.Config + if format == photoFormatJPEG { + cfg, err = jpeg.DecodeConfig(bytes.NewReader(b)) + } else { + cfg, err = png.DecodeConfig(bytes.NewReader(b)) + } + if err != nil || cfg.Width != p.width || cfg.Height != p.height { + return p, errPhotoUnread + } + return p, nil +} + +// photoDecodeBudget is the most a decode may allocate: an 8-bit RGBA image +// at the pixel cap. +func photoDecodeBudget(maxPixels int) int64 { return int64(maxPixels) * 4 } + +// probeJPEG walks the JPEG markers up to the first scan: the frame header +// gives the size, components, subsampling and whether it is progressive (the +// decoder then also holds every coefficient, 4 bytes per sample); APP1 Exif +// gives the orientation. +func probeJPEG(b []byte, p *photoProbe) error { + i := 2 + sawFrame := false + for { + for i < len(b) && b[i] == 0xFF && i+1 < len(b) && b[i+1] == 0xFF { + i++ // fill bytes + } + if i+4 > len(b) || b[i] != 0xFF { + return errPhotoUnread + } + marker := b[i+1] + if marker == 0xD8 || marker == 0x01 || (marker >= 0xD0 && marker <= 0xD7) { + i += 2 + continue + } + if marker == 0xD9 { + return errPhotoUnread + } + n := int(binary.BigEndian.Uint16(b[i+2:])) + if n < 2 || i+2+n > len(b) { + return errPhotoUnread + } + seg := b[i+4 : i+2+n] + switch { + case marker == 0xDA: // start of scan: the header is over + if !sawFrame { + return errPhotoUnread + } + return nil + case marker == 0xE1: + if o := exifOrientation(seg); o != 0 && p.orientation == 1 { + p.orientation = o + } + case marker == 0xC0 || marker == 0xC1 || marker == 0xC2: + if sawFrame || jpegFrame(seg, marker == 0xC2, p) != nil { + return errPhotoUnread + } + sawFrame = true + case marker >= 0xC3 && marker <= 0xCF && marker != 0xC4 && marker != 0xC8 && marker != 0xCC: + return errPhotoFormat // lossless, hierarchical or arithmetic: Go cannot decode it + } + i += 2 + n + } +} + +// jpegFrame reads a baseline or progressive frame header. +func jpegFrame(seg []byte, progressive bool, p *photoProbe) error { + if len(seg) < 6 { + return errPhotoUnread + } + p.height, p.width = int(binary.BigEndian.Uint16(seg[1:])), int(binary.BigEndian.Uint16(seg[3:])) + nc := int(seg[5]) + if (nc != 1 && nc != 3 && nc != 4) || len(seg) < 6+3*nc { + return errPhotoUnread + } + hMax, vMax := 1, 1 + type samp struct{ h, v int } + comps := make([]samp, nc) + for c := 0; c < nc; c++ { + hv := seg[6+3*c+1] + comps[c] = samp{int(hv >> 4), int(hv & 0x0F)} + if comps[c].h < 1 || comps[c].h > 4 || comps[c].v < 1 || comps[c].v > 4 { + return errPhotoUnread + } + hMax, vMax = max(hMax, comps[c].h), max(vMax, comps[c].v) + } + // Each component plane, rounded up to whole 8×8 blocks of its MCUs. + mcuW, mcuH := 8*hMax, 8*vMax + mx, my := int64((p.width+mcuW-1)/mcuW), int64((p.height+mcuH-1)/mcuH) + var samples int64 + for _, s := range comps { + samples += mx * int64(8*s.h) * my * int64(8*s.v) + } + p.decodeBytes = samples + if nc == 4 { + p.decodeBytes += 4 * int64(p.width) * int64(p.height) // the CMYK image + } + if progressive { + p.decodeBytes += 4 * samples // int32 coefficients per sample + } + return nil +} + +// exifOrientation returns the orientation tag (1–8) of an APP1 Exif +// segment's first IFD, or 0. Every read is bounds-checked; the segment is +// at most 64 KiB by the JPEG format. +func exifOrientation(seg []byte) int { + if len(seg) < 14 || string(seg[:6]) != "Exif\x00\x00" { + return 0 + } + t := seg[6:] + var bo binary.ByteOrder + switch string(t[:4]) { + case "II*\x00": + bo = binary.LittleEndian + case "MM\x00*": + bo = binary.BigEndian + default: + return 0 + } + off := int(bo.Uint32(t[4:])) + if off < 8 || off+2 > len(t) { + return 0 + } + n := int(bo.Uint16(t[off:])) + for k := 0; k < n; k++ { + e := off + 2 + 12*k + if e+12 > len(t) { + return 0 + } + if bo.Uint16(t[e:]) == 0x0112 && bo.Uint16(t[e+2:]) == 3 && bo.Uint32(t[e+4:]) == 1 { + if o := int(bo.Uint16(t[e+8:])); o >= 1 && o <= 8 { + return o + } + return 0 + } + } + return 0 +} + +// probePNG reads IHDR: the size, and the bytes per pixel of the image the +// decoder returns (16-bit images take 8, paletted and gray 1–2); an +// interlaced image is decoded pass by pass, roughly twice the memory. PNG +// carries no orientation the server applies. +func probePNG(b []byte, p *photoProbe) error { + if len(b) < 33 || string(b[12:16]) != "IHDR" || binary.BigEndian.Uint32(b[8:]) != 13 { + return errPhotoUnread + } + w, h := binary.BigEndian.Uint32(b[16:]), binary.BigEndian.Uint32(b[20:]) + if w > math.MaxInt32 || h > math.MaxInt32 { + return errPhotoTooLarge + } + p.width, p.height = int(w), int(h) + depth, ctype, interlace := b[24], b[25], b[28] + var bpp int64 + switch ctype { + case 0: // gray + bpp = 1 + if depth == 16 { + bpp = 2 + } + case 3: // paletted + bpp = 1 + case 2, 4, 6: // RGB, gray+alpha, RGBA + bpp = 4 + if depth == 16 { + bpp = 8 + } + default: + return errPhotoUnread + } + p.decodeBytes = bpp * int64(p.width) * int64(p.height) + if interlace == 1 { + p.decodeBytes *= 2 + } + return nil +} + +// photoOutput is the re-encoded photo. +type photoOutput struct { + full, thumb []byte + width, height int + thumbWidth, thumbH int +} + +// decodePhoto decodes the pixels of an upload that passed probePhoto. A +// test swaps it to count decodes. +var decodePhoto = func(b []byte, format string) (image.Image, error) { + if format == photoFormatPNG { + return png.Decode(bytes.NewReader(b)) + } + return jpeg.Decode(bytes.NewReader(b)) +} + +// reencodePhoto decodes the upload, scales it to at most PhotoFullMaxPx on +// the long edge (never up), turns it upright, and encodes the full image +// and a PhotoThumbMaxPx thumbnail as JPEG. When the two files exceed +// MaxPhotoStoredBytes it steps the quality down to PhotoMinQuality, then +// refuses. +func reencodePhoto(b []byte, p photoProbe) (photoOutput, error) { + src, err := decodePhoto(b, p.format) + if err != nil { + return photoOutput{}, errPhotoUnread + } + if sb := src.Bounds(); sb.Dx() != p.width || sb.Dy() != p.height { + return photoOutput{}, errPhotoUnread + } + full := orient(scaleDown(src, antennaclaim.PhotoFullMaxPx), p.orientation) + src = nil // the decoded upload is the largest allocation: let it go + thumb := scaleDown(full, antennaclaim.PhotoThumbMaxPx) + out := photoOutput{width: full.Rect.Dx(), height: full.Rect.Dy(), thumbWidth: thumb.Rect.Dx(), thumbH: thumb.Rect.Dy()} + for q := antennaclaim.PhotoFullQuality; q >= antennaclaim.PhotoMinQuality; q -= 10 { + tq := min(q, antennaclaim.PhotoThumbQuality) + if out.full, err = encodeJPEG(full, q); err != nil { + return photoOutput{}, err + } + if out.thumb, err = encodeJPEG(thumb, tq); err != nil { + return photoOutput{}, err + } + if len(out.full)+len(out.thumb) <= antennaclaim.MaxPhotoStoredBytes { + return out, nil + } + } + return photoOutput{}, errPhotoDetailed +} + +func encodeJPEG(img image.Image, quality int) ([]byte, error) { + var buf bytes.Buffer + if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: quality}); err != nil { + return nil, err + } + return buf.Bytes(), nil +} + +// photoBackground is what transparent pixels are composed onto: JPEG has no +// alpha. A stored photo's pixels, not a theme colour. +var photoBackground = image.NewUniform(color.RGBA{255, 255, 255, 255}) + +// scaleDown returns src as an opaque RGBA image scaled by area averaging so +// its long edge is at most maxPx; a smaller image keeps its size. It reads +// src one row at a time (through image/draw's fast paths) and keeps two +// output rows of float accumulators, so it never holds a second full-size +// copy of src. Transparent pixels are composed onto photoBackground. +func scaleDown(src image.Image, maxPx int) *image.RGBA { + sb := src.Bounds() + sw, sh := sb.Dx(), sb.Dy() + dw, dh := sw, sh + if long := max(sw, sh); long > maxPx { + dw = max(1, int(math.Round(float64(sw)*float64(maxPx)/float64(long)))) + dh = max(1, int(math.Round(float64(sh)*float64(maxPx)/float64(long)))) + } + dst := image.NewRGBA(image.Rect(0, 0, dw, dh)) + row := image.NewRGBA(image.Rect(0, 0, sw, 1)) + // Horizontal weights: each source column's share of output column + // o/3 and the next one. hrow has a spare column, so the second share + // (0 when the column falls in one output column) needs no branch. + type share struct { + o int // 3 × the first output column + w0, w1 float32 // weight into it and into the next + } + xs := make([]share, sw) + fx := float64(dw) / float64(sw) + for x := 0; x < sw; x++ { + a, b := float64(x)*fx, float64(x+1)*fx + c := min(int(a), dw-1) + if b <= float64(c+1) || c+1 >= dw { + xs[x] = share{3 * c, float32(b - a), 0} + } else { + xs[x] = share{3 * c, float32(float64(c+1) - a), float32(b - float64(c+1))} + } + } + acc := [2][]float32{make([]float32, dw*3), make([]float32, dw*3)} + hrow := make([]float32, (dw+1)*3) + fy := float64(dh) / float64(sh) + // The weights are overlaps in output pixels, so the ones that reach an + // output pixel sum to 1 and its accumulator is already the average. + cur := 0 // the output row acc[0] belongs to + flush := func() { + o := dst.Pix[cur*dst.Stride : cur*dst.Stride+4*dw] + a := acc[0] + for i := 0; i < dw; i++ { + for k := 0; k < 3; k++ { + v := a[3*i+k] + 0.5 + switch { + case v >= 255: + o[4*i+k] = 255 + case v > 0: + o[4*i+k] = uint8(v) + default: + o[4*i+k] = 0 + } + } + o[4*i+3] = 255 + } + acc[0], acc[1] = acc[1], acc[0] + clear(acc[1]) + cur++ + } + opaque := photoOpaque(src) + for y := 0; y < sh; y++ { + if opaque { + draw.Draw(row, row.Rect, src, image.Pt(sb.Min.X, sb.Min.Y+y), draw.Src) + } else { + draw.Draw(row, row.Rect, photoBackground, image.Point{}, draw.Src) + draw.Draw(row, row.Rect, src, image.Pt(sb.Min.X, sb.Min.Y+y), draw.Over) + } + clear(hrow) + pix := row.Pix + for x, s := range xs { + p := pix[4*x : 4*x+3 : 4*x+3] + r, g, b := float32(p[0]), float32(p[1]), float32(p[2]) + h := hrow[s.o : s.o+6 : s.o+6] + h[0] += r * s.w0 + h[1] += g * s.w0 + h[2] += b * s.w0 + h[3] += r * s.w1 + h[4] += g * s.w1 + h[5] += b * s.w1 + } + a, b := float64(y)*fy, float64(y+1)*fy + r := min(int(a), dh-1) + for r > cur { + flush() + } + hv := hrow[:dw*3] + if b > float64(r+1) && r+1 < dh { + w0, w1 := float32(float64(r+1)-a), float32(b-float64(r+1)) + a0, a1 := acc[0][:len(hv)], acc[1][:len(hv)] + for i, v := range hv { + a0[i] += v * w0 + a1[i] += v * w1 + } + } else { + w0 := float32(b - a) + a0 := acc[0][:len(hv)] + for i, v := range hv { + a0[i] += v * w0 + } + } + } + for cur < dh { + flush() + } + return dst +} + +// photoOpaque reports whether every pixel of img is opaque, so it needs no +// background: always for the JPEG decoder's types, by a scan otherwise. +func photoOpaque(img image.Image) bool { + switch m := img.(type) { + case *image.YCbCr, *image.Gray, *image.Gray16, *image.CMYK: + return true + case interface{ Opaque() bool }: + return m.Opaque() + } + return false +} + +// orient turns img upright for an EXIF orientation (1–8): 2 mirrors, 3 +// turns 180°, 4 flips, 5 transposes, 6 turns 90° clockwise, 7 transverses, +// 8 turns 90° counter-clockwise. +func orient(img *image.RGBA, o int) *image.RGBA { + if o <= 1 || o > 8 { + return img + } + w, h := img.Rect.Dx(), img.Rect.Dy() + dw, dh := w, h + if o >= 5 { + dw, dh = h, w + } + dst := image.NewRGBA(image.Rect(0, 0, dw, dh)) + for y := 0; y < h; y++ { + for x := 0; x < w; x++ { + var nx, ny int + switch o { + case 2: + nx, ny = w-1-x, y + case 3: + nx, ny = w-1-x, h-1-y + case 4: + nx, ny = x, h-1-y + case 5: + nx, ny = y, x + case 6: + nx, ny = h-1-y, x + case 7: + nx, ny = h-1-y, w-1-x + case 8: + nx, ny = y, w-1-x + } + copy(dst.Pix[ny*dst.Stride+4*nx:ny*dst.Stride+4*nx+4], img.Pix[y*img.Stride+4*x:y*img.Stride+4*x+4]) + } + } + return dst +} diff --git a/cmd/server/station_photo_image_1017_m5_test.go b/cmd/server/station_photo_image_1017_m5_test.go new file mode 100644 index 000000000..d3440cee2 --- /dev/null +++ b/cmd/server/station_photo_image_1017_m5_test.go @@ -0,0 +1,559 @@ +package main + +import ( + "bytes" + "compress/zlib" + "encoding/binary" + "hash/crc32" + "image" + "image/color" + "image/jpeg" + "image/png" + "runtime" + "runtime/metrics" + "sync/atomic" + "testing" + "time" + + "github.com/meshcore-analyzer/channelregistry/antennaclaim" +) + +// #1017 M5 — station photos, the image side: metadata is gone by +// construction, the orientation is applied, oversize and decompression +// bombs are refused at the header before any decode, and the 16 MP worst +// case stays within its time and memory budget. + +const photoTestMaxPixels = 16_000_000 + +var ( + quadRed = color.RGBA{220, 20, 20, 255} + quadBlue = color.RGBA{20, 20, 220, 255} +) + +// quadImage is w×h blue with a red top-left quadrant, so every orientation +// moves the red corner somewhere else. +func quadImage(w, h int) *image.RGBA { + img := image.NewRGBA(image.Rect(0, 0, w, h)) + for y := 0; y < h; y++ { + for x := 0; x < w; x++ { + c := quadBlue + if x < w/2 && y < h/2 { + c = quadRed + } + img.SetRGBA(x, y, c) + } + } + return img +} + +func encodeTestJPEG(t testing.TB, img image.Image) []byte { + t.Helper() + var buf bytes.Buffer + if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: 90}); err != nil { + t.Fatal(err) + } + return buf.Bytes() +} + +// The metadata a phone writes: EXIF with a camera make, the orientation and +// a GPS IFD, an XMP packet and a comment, each with a marker the output +// must not contain. +const ( + exifMakeMarker = "SECRETCAM-MAKE" + xmpMarker = "SECRET-XMP-CREATOR" + commentMarker = "SECRET-COMMENT" +) + +// exifSegment builds an APP1 Exif payload (little endian): IFD0 with Make, +// Orientation and a GPS IFD pointer; the GPS IFD with a latitude. +func exifSegment(orientation uint16) []byte { + le := binary.LittleEndian + var t bytes.Buffer + t.WriteString("II*\x00") + binary.Write(&t, le, uint32(8)) + // IFD0: 3 entries at 8; data after. + const ifd0 = 8 + const n0 = 3 + makeOff := uint32(ifd0 + 2 + 12*n0 + 4) + makeVal := exifMakeMarker + "\x00" + gpsOff := makeOff + uint32(len(makeVal)) + binary.Write(&t, le, uint16(n0)) + entry := func(tag, typ uint16, count, value uint32) { + binary.Write(&t, le, tag) + binary.Write(&t, le, typ) + binary.Write(&t, le, count) + binary.Write(&t, le, value) + } + entry(0x010F, 2, uint32(len(makeVal)), makeOff) // Make + entry(0x0112, 3, 1, uint32(orientation)) // Orientation + entry(0x8825, 4, 1, gpsOff) // GPSInfo + binary.Write(&t, le, uint32(0)) // no next IFD + t.WriteString(makeVal) + // GPS IFD: LatitudeRef "N", Latitude 55/1 40/1 3036/100. + latOff := gpsOff + 2 + 12*2 + 4 + binary.Write(&t, le, uint16(2)) + entry(0x0001, 2, 2, uint32('N')) + entry(0x0002, 5, 3, latOff) + binary.Write(&t, le, uint32(0)) + for _, r := range [][2]uint32{{55, 1}, {40, 1}, {3036, 100}} { + binary.Write(&t, le, r[0]) + binary.Write(&t, le, r[1]) + } + return append([]byte("Exif\x00\x00"), t.Bytes()...) +} + +func jpegSegment(marker byte, payload []byte) []byte { + out := []byte{0xFF, marker, 0, 0} + binary.BigEndian.PutUint16(out[2:], uint16(len(payload)+2)) + return append(out, payload...) +} + +// withMetadata splices EXIF, XMP and a comment in after SOI. +func withMetadata(j []byte, orientation uint16) []byte { + xmp := append([]byte("http://ns.adobe.com/xap/1.0/\x00"), + []byte(``+xmpMarker+``)...) + out := append([]byte{}, j[:2]...) + out = append(out, jpegSegment(0xE1, exifSegment(orientation))...) + out = append(out, jpegSegment(0xE1, xmp)...) + out = append(out, jpegSegment(0xFE, []byte(commentMarker))...) + return append(out, j[2:]...) +} + +// jpegMarkers lists the markers of a JPEG up to its first scan. +func jpegMarkers(t *testing.T, b []byte) []byte { + t.Helper() + var out []byte + for i := 2; i+4 <= len(b); { + if b[i] != 0xFF { + t.Fatalf("bad marker at %d", i) + } + m := b[i+1] + out = append(out, m) + if m == 0xDA { + return out + } + i += 2 + int(binary.BigEndian.Uint16(b[i+2:])) + } + return out +} + +func assertClean(t *testing.T, what string, b []byte) { + t.Helper() + for _, needle := range []string{"Exif", "http://ns.adobe.com", "xmpmeta", exifMakeMarker, xmpMarker, commentMarker, "SECRET", "eXIf", "tEXt"} { + if bytes.Contains(b, []byte(needle)) { + t.Errorf("%s still contains %q", what, needle) + } + } + for _, m := range jpegMarkers(t, b) { + // Only tables, the frame and the scan: no APPn, no COM. + if m != 0xDB && m != 0xC0 && m != 0xC4 && m != 0xDA { + t.Errorf("%s has marker FF%02X", what, m) + } + } +} + +func process(t *testing.T, b []byte) photoOutput { + t.Helper() + format := sniffPhoto(b) + p, err := probePhoto(b, format, photoTestMaxPixels) + if err != nil { + t.Fatalf("probe: %v", err) + } + out, err := reencodePhoto(b, p) + if err != nil { + t.Fatalf("reencode: %v", err) + } + return out +} + +func decodeOut(t *testing.T, b []byte) image.Image { + t.Helper() + img, err := jpeg.Decode(bytes.NewReader(b)) + if err != nil { + t.Fatal(err) + } + return img +} + +func isRed(c color.Color) bool { + r, g, b, _ := c.RGBA() + return r>>8 > 150 && g>>8 < 90 && b>>8 < 90 +} + +func isBlue(c color.Color) bool { + r, g, b, _ := c.RGBA() + return b>>8 > 150 && r>>8 < 90 && g>>8 < 90 +} + +// EXIF (camera make, GPS IFD), XMP and a comment go in; none comes out, and +// orientation 6 comes out upright: a 200×100 image with its red corner top +// left becomes 100×200 with the red corner top right. +func TestStationPhoto1017M5_StripsMetadataAndAppliesOrientation(t *testing.T) { + in := withMetadata(encodeTestJPEG(t, quadImage(200, 100)), 6) + p, err := probePhoto(in, photoFormatJPEG, photoTestMaxPixels) + if err != nil || p.orientation != 6 { + t.Fatalf("probe: %+v %v, want orientation 6", p, err) + } + out := process(t, in) + assertClean(t, "full", out.full) + assertClean(t, "thumb", out.thumb) + if out.width != 100 || out.height != 200 { + t.Fatalf("full is %dx%d, want 100x200 (turned)", out.width, out.height) + } + img := decodeOut(t, out.full) + if b := img.Bounds(); b.Dx() != 100 || b.Dy() != 200 { + t.Fatalf("decoded %v", b) + } + if !isRed(img.At(75, 40)) || !isBlue(img.At(25, 40)) || !isBlue(img.At(75, 160)) { + t.Fatalf("not upright: (75,40)=%v (25,40)=%v (75,160)=%v", img.At(75, 40), img.At(25, 40), img.At(75, 160)) + } + if len(out.full)+len(out.thumb) > antennaclaim.MaxPhotoStoredBytes { + t.Fatalf("output %d bytes", len(out.full)+len(out.thumb)) + } +} + +// Every orientation maps the red corner where EXIF says it belongs. +func TestStationPhoto1017M5_OrientAllEight(t *testing.T) { + src := quadImage(4, 2) // red at (0,0),(1,0) + // Where the source's top-left pixel (0,0) lands, and the output size. + want := map[int]struct{ x, y, w, h int }{ + 1: {0, 0, 4, 2}, 2: {3, 0, 4, 2}, 3: {3, 1, 4, 2}, 4: {0, 1, 4, 2}, + 5: {0, 0, 2, 4}, 6: {1, 0, 2, 4}, 7: {1, 3, 2, 4}, 8: {0, 3, 2, 4}, + } + for o, w := range want { + got := orient(src, o) + if got.Rect.Dx() != w.w || got.Rect.Dy() != w.h { + t.Errorf("orientation %d: %v, want %dx%d", o, got.Rect, w.w, w.h) + continue + } + if got.RGBAAt(w.x, w.y) != quadRed { + t.Errorf("orientation %d: (%d,%d) = %v, want red", o, w.x, w.y, got.RGBAAt(w.x, w.y)) + } + red := 0 + for i := 0; i < len(got.Pix); i += 4 { + if got.Pix[i] == quadRed.R { + red++ + } + } + if red != 2 { + t.Errorf("orientation %d: %d red pixels, want 2", o, red) + } + } +} + +func TestStationPhoto1017M5_ExifOrientationParse(t *testing.T) { + for o := uint16(1); o <= 8; o++ { + if got := exifOrientation(exifSegment(o)); got != int(o) { + t.Errorf("orientation %d read as %d", o, got) + } + } + seg := exifSegment(6) + big := append([]byte{}, seg...) + copy(big[6:], "MM\x00*") // wrong byte order for the data: no valid tag + for name, b := range map[string][]byte{ + "empty": nil, + "not exif": []byte("XMP\x00\x00\x00 something long enough"), + "truncated": seg[:20], + "bad order": big, + "value 9": exifSegment(9), + "offset beyond": append([]byte("Exif\x00\x00II*\x00"), 0xFF, 0xFF, 0, 0), + } { + if got := exifOrientation(b); got != 0 { + t.Errorf("%s: %d, want 0", name, got) + } + } +} + +// pngChunk builds one PNG chunk with its CRC. +func pngChunk(typ string, data []byte) []byte { + out := make([]byte, 8, 12+len(data)) + binary.BigEndian.PutUint32(out, uint32(len(data))) + copy(out[4:], typ) + out = append(out, data...) + crc := crc32.ChecksumIEEE(append([]byte(typ), data...)) + return binary.BigEndian.AppendUint32(out, crc) +} + +// A PNG with tEXt and eXIf chunks comes out as a clean JPEG. +func TestStationPhoto1017M5_PNGChunksStripped(t *testing.T) { + var buf bytes.Buffer + if err := png.Encode(&buf, quadImage(120, 80)); err != nil { + t.Fatal(err) + } + b := buf.Bytes() + // After the signature and IHDR (8 + 25 bytes). + in := append([]byte{}, b[:33]...) + in = append(in, pngChunk("tEXt", []byte("Comment\x00"+commentMarker))...) + in = append(in, pngChunk("eXIf", exifSegment(6)[6:])...) + in = append(in, b[33:]...) + out := process(t, in) + assertClean(t, "full", out.full) + if out.width != 120 || out.height != 80 { + t.Fatalf("PNG output %dx%d: an eXIf orientation must not be applied", out.width, out.height) + } + if !isRed(decodeOut(t, out.full).At(20, 20)) { + t.Fatal("PNG content lost") + } +} + +// Transparent PNG pixels are composed onto white, not black. +func TestStationPhoto1017M5_TransparentPNGOnWhite(t *testing.T) { + img := image.NewNRGBA(image.Rect(0, 0, 40, 40)) + var buf bytes.Buffer + png.Encode(&buf, img) + c := decodeOut(t, process(t, buf.Bytes()).full).At(20, 20) + if r, g, b, _ := c.RGBA(); r>>8 < 240 || g>>8 < 240 || b>>8 < 240 { + t.Fatalf("transparent pixel came out %v, want white", c) + } +} + +// Downscaling: the long edge becomes 1600 (full) and 480 (thumb), the +// aspect is kept, nothing is scaled up, and the area average keeps colours. +func TestStationPhoto1017M5_ScaleDown(t *testing.T) { + out := process(t, encodeTestJPEG(t, quadImage(3200, 1800))) + if out.width != 1600 || out.height != 900 || out.thumbWidth != 480 || out.thumbH != 270 { + t.Fatalf("sizes %dx%d / %dx%d", out.width, out.height, out.thumbWidth, out.thumbH) + } + img := decodeOut(t, out.full) + if !isRed(img.At(400, 200)) || !isBlue(img.At(1200, 700)) { + t.Fatalf("colours: %v %v", img.At(400, 200), img.At(1200, 700)) + } + small := process(t, encodeTestJPEG(t, quadImage(300, 200))) + if small.width != 300 || small.height != 200 || small.thumbWidth != 300 { + t.Fatalf("small image scaled: %dx%d thumb %d", small.width, small.height, small.thumbWidth) + } + // A 2:1 average: two columns of 0 and 200 make 100. + src := image.NewRGBA(image.Rect(0, 0, 4, 2)) + for y := 0; y < 2; y++ { + for x := 0; x < 4; x++ { + v := uint8(0) + if x%2 == 1 { + v = 200 + } + src.SetRGBA(x, y, color.RGBA{v, v, v, 255}) + } + } + got := scaleDown(src, 2) + if got.Rect.Dx() != 2 || got.Rect.Dy() != 1 || got.Pix[0] != 100 || got.Pix[4] != 100 || got.Pix[3] != 255 { + t.Fatalf("2:1 average: %v %v", got.Rect, got.Pix) + } +} + +// ── Refused at the header, before any decode ────────────────────────────── + +// jpegHeaderOnly is a JPEG that claims w×h: SOI, a frame header, an empty +// scan header and EOI. Decoding it would allocate the full frame. +func jpegHeaderOnly(w, h int, sof byte, sampling byte) []byte { + out := []byte{0xFF, 0xD8} + frame := []byte{8, byte(h >> 8), byte(h), byte(w >> 8), byte(w), 3, + 1, sampling, 0, 2, 0x11, 1, 3, 0x11, 1} + out = append(out, jpegSegment(sof, frame)...) + out = append(out, jpegSegment(0xDA, []byte{3, 1, 0, 2, 0x11, 3, 0x11, 0, 63, 0})...) + return append(out, 0xFF, 0xD9) +} + +// pngHeader is a PNG that claims w×h at depth and colour type, with a tiny +// zlib stream of zeros: a decompression bomb would inflate it to the frame. +func pngHeader(w, h uint32, depth, ctype, interlace byte) []byte { + out := []byte("\x89PNG\r\n\x1a\n") + ihdr := make([]byte, 13) + binary.BigEndian.PutUint32(ihdr, w) + binary.BigEndian.PutUint32(ihdr[4:], h) + ihdr[8], ihdr[9], ihdr[12] = depth, ctype, interlace + out = append(out, pngChunk("IHDR", ihdr)...) + var z bytes.Buffer + zw := zlib.NewWriter(&z) + zw.Write(make([]byte, 1<<16)) + zw.Close() + out = append(out, pngChunk("IDAT", z.Bytes())...) + return append(out, pngChunk("IEND", nil)...) +} + +// countDecodes swaps decodePhoto for one that counts, for the test's life. +func countDecodes(t *testing.T) *atomic.Int32 { + t.Helper() + var n atomic.Int32 + orig := decodePhoto + decodePhoto = func(b []byte, f string) (image.Image, error) { + n.Add(1) + return orig(b, f) + } + t.Cleanup(func() { decodePhoto = orig }) + return &n +} + +func TestStationPhoto1017M5_BombsRefusedBeforeDecode(t *testing.T) { + decodes := countDecodes(t) + for name, tc := range map[string]struct { + b []byte + want error + }{ + "30000x30000 header-only JPEG": {jpegHeaderOnly(30000, 30000, 0xC0, 0x22), errPhotoTooLarge}, + "8193 px a side JPEG (under 16 MP)": {jpegHeaderOnly(8193, 1000, 0xC0, 0x22), errPhotoTooLarge}, + "4001x4000 JPEG (just over 16 MP)": {jpegHeaderOnly(4001, 4000, 0xC0, 0x22), errPhotoTooLarge}, + "progressive 4:4:4 4000x4000 (coeffs)": {jpegHeaderOnly(4000, 4000, 0xC2, 0x11), errPhotoTooLarge}, + "lossless JPEG": {jpegHeaderOnly(100, 100, 0xC3, 0x11), errPhotoFormat}, + "30000x30000 PNG bomb": {pngHeader(30000, 30000, 8, 6, 0), errPhotoTooLarge}, + "16-bit RGBA PNG 4000x4000 (128 MB)": {pngHeader(4000, 4000, 16, 6, 0), errPhotoTooLarge}, + "interlaced RGBA PNG 4000x4000 (2 passes)": {pngHeader(4000, 4000, 8, 6, 1), errPhotoTooLarge}, + "huge PNG width": {pngHeader(0xFFFFFFFF, 1, 8, 6, 0), errPhotoTooLarge}, + "zero-size PNG": {pngHeader(0, 10, 8, 6, 0), errPhotoUnread}, + "truncated JPEG": {[]byte{0xFF, 0xD8, 0xFF, 0xC0, 0x00}, errPhotoUnread}, + "JPEG without a frame": {append([]byte{0xFF, 0xD8}, jpegSegment(0xDA, []byte{0})...), errPhotoUnread}, + } { + _, err := probePhoto(tc.b, sniffPhoto(tc.b), photoTestMaxPixels) + if err != tc.want { + t.Errorf("%s: %v, want %v", name, err, tc.want) + } + } + if n := decodes.Load(); n != 0 { + t.Fatalf("%d decodes ran", n) + } + // Inside every bound: accepted at the header. + for name, b := range map[string][]byte{ + "4000x4000 baseline 4:2:0": jpegHeaderOnly(4000, 4000, 0xC0, 0x22), + "8192x1953 baseline": jpegHeaderOnly(8192, 1953, 0xC0, 0x22), + "16-bit RGBA PNG 2000²": pngHeader(2000, 2000, 16, 6, 0), + "RGBA PNG 4000x4000": pngHeader(4000, 4000, 8, 6, 0), + } { + if p, err := probePhoto(b, sniffPhoto(b), photoTestMaxPixels); err != nil && err != errPhotoUnread { + t.Errorf("%s refused: %v (%+v)", name, err, p) + } + } +} + +// The operator's lower megapixel cap is the one applied. +func TestStationPhoto1017M5_ConfiguredPixelCap(t *testing.T) { + b := encodeTestJPEG(t, quadImage(2100, 1000)) // 2.1 MP + if _, err := probePhoto(b, photoFormatJPEG, 2_000_000); err != errPhotoTooLarge { + t.Fatalf("2.1 MP under a 2 MP cap: %v", err) + } + if _, err := probePhoto(b, photoFormatJPEG, 3_000_000); err != nil { + t.Fatalf("2.1 MP under a 3 MP cap: %v", err) + } +} + +func TestStationPhoto1017M5_Sniff(t *testing.T) { + for name, tc := range map[string]struct { + b []byte + want string + }{ + "jpeg": {[]byte{0xFF, 0xD8, 0xFF, 0xE0}, photoFormatJPEG}, + "png": {[]byte("\x89PNG\r\n\x1a\nrest"), photoFormatPNG}, + "gif": {[]byte("GIF89a......"), ""}, + "svg": {[]byte(``), ""}, + "html": {[]byte(""), http.StatusUnsupportedMediaType}, + "jpeg declared, svg sent": {"image/jpeg", []byte(``), http.StatusUnsupportedMediaType}, + "30000x30000 header JPEG": {"image/jpeg", jpegHeaderOnly(30000, 30000, 0xC0, 0x22), http.StatusRequestEntityTooLarge}, + "PNG decompression bomb": {"image/png", pngHeader(30000, 30000, 8, 6, 0), http.StatusRequestEntityTooLarge}, + "garbage after JPEG magic": {"image/jpeg", []byte{0xFF, 0xD8, 0xFF, 0x00, 0x01, 0x02}, http.StatusBadRequest}, + "over 8 MiB, chunked": {"image/jpeg", append(append([]byte{}, jpg...), make([]byte, 8<<20)...), http.StatusRequestEntityTooLarge}, + } { + req := httptest.NewRequest("POST", "/api/antenna-claims/requests/"+photoClaim+"/photo", io.MultiReader(bytes.NewReader(tc.body))) + req.ContentLength = -1 // chunked: only the reader's cap stops it + if tc.ct != "" { + req.Header.Set("Content-Type", tc.ct) + } + w := httptest.NewRecorder() + env.router.ServeHTTP(w, req) + if w.Code != tc.want { + t.Errorf("%s: %d %s, want %d", name, w.Code, w.Body, tc.want) + } + } + // A declared Content-Length over the cap is refused before the body is + // read at all. + req := httptest.NewRequest("POST", "/api/antenna-claims/requests/"+photoClaim+"/photo", readerThatFails{t}) + req.Header.Set("Content-Type", "image/jpeg") + req.ContentLength = 8<<20 + 1 + w := httptest.NewRecorder() + env.router.ServeHTTP(w, req) + if w.Code != http.StatusRequestEntityTooLarge { + t.Fatalf("Content-Length over the cap: %d", w.Code) + } + if n := decodes.Load(); n != 0 { + t.Fatalf("%d decodes ran for refused uploads", n) + } + if n := len(env.queued(t)); n != 0 { + t.Fatalf("%d commands queued", n) + } + // None of the refusals spent the per-IP budget of 2: two uploads pass, + // the third is limited. + for i, want := range []int{http.StatusAccepted, http.StatusAccepted, http.StatusTooManyRequests} { + if w := env.upload(photoClaim, "image/jpeg", jpg); w.Code != want { + t.Fatalf("upload %d: %d %s, want %d", i+1, w.Code, w.Body, want) + } + } +} + +func inList(list []string, s string) bool { + for _, v := range list { + if v == s { + return true + } + } + return false +} + +type readerThatFails struct{ t *testing.T } + +func (r readerThatFails) Read([]byte) (int, error) { + r.t.Error("the body was read") + return 0, io.EOF +} + +func pngEncode(t *testing.T, w io.Writer) { + t.Helper() + if err := png.Encode(w, quadImage(64, 48)); err != nil { + t.Fatal(err) + } +} + +// Perf: at most photoDecodeSlots (2) uploads decode at once; the third gets +// 503 with Retry-After at once, without waiting and without spending its +// per-IP budget; a freed slot is reused. +func TestStationPhotos1017M5_DecodeSemaphoreAtTwo(t *testing.T) { + if photoDecodeSlots != 2 { + t.Fatalf("photoDecodeSlots = %d, want 2", photoDecodeSlots) + } + env := photosEnv(t, func(c *antennaclaim.Config) { c.Photos = &antennaclaim.PhotoConfig{UploadsPerHourPerIP: 3} }) + pk := pk789("a") + env.addNode(t, pk, "Roof", "repeater", est789Lat, est789Lon) + env.approvedStation(t, photoClaim, pk) + entered, release := make(chan struct{}, 4), make(chan struct{}) + orig := decodePhoto + decodePhoto = func(b []byte, f string) (image.Image, error) { + entered <- struct{}{} + <-release + return orig(b, f) + } + t.Cleanup(func() { decodePhoto = orig }) + jpg := encodeTestJPEG(t, quadImage(64, 48)) + post := func() *httptest.ResponseRecorder { + req := httptest.NewRequest("POST", "/api/antenna-claims/requests/"+photoClaim+"/photo", bytes.NewReader(jpg)) + req.Header.Set("Content-Type", "image/jpeg") + w := httptest.NewRecorder() + env.router.ServeHTTP(w, req) + return w + } + var wg sync.WaitGroup + codes := make([]int, 2) + for i := range codes { + wg.Add(1) + go func(i int) { + defer wg.Done() + codes[i] = post().Code + }(i) + } + for i := 0; i < 2; i++ { + select { + case <-entered: + case <-time.After(30 * time.Second): + t.Fatal("the first two uploads did not both reach the decoder") + } + } + var once sync.Once + free := func() { once.Do(func() { close(release) }) } + t.Cleanup(free) + start := time.Now() + third := make(chan *httptest.ResponseRecorder, 1) + go func() { third <- post() }() + var w *httptest.ResponseRecorder + select { + case w = <-third: + case <-entered: + free() + t.Fatal("a third upload reached the decoder while two held it") + case <-time.After(30 * time.Second): + free() + t.Fatal("the third upload waited for a slot instead of answering 503") + } + if w.Code != http.StatusServiceUnavailable || w.Header().Get("Retry-After") != "5" { + t.Fatalf("third concurrent upload: %d Retry-After=%q, want 503 and 5", w.Code, w.Header().Get("Retry-After")) + } + if d := time.Since(start); d > 5*time.Second { + t.Fatalf("the busy answer waited %v", d) + } + free() + wg.Wait() + if codes[0] != http.StatusAccepted || codes[1] != http.StatusAccepted { + t.Fatalf("held uploads: %v", codes) + } + // The slot is free again, and the 503 cost no budget (3 per hour: 2 + // used, the third is this one). + if w := post(); w.Code != http.StatusAccepted { + t.Fatalf("after release: %d %s", w.Code, w.Body) + } +} + +// ── Owner status ────────────────────────────────────────────────────────── + +func TestStationPhotos1017M5_Status(t *testing.T) { + env := photosEnv(t, nil) + pk := pk789("a") + env.addNode(t, pk, "Roof", "repeater", est789Lat, est789Lon) + env.approvedStation(t, photoClaim, pk) + w := env.upload(photoClaim, "image/jpeg", encodeTestJPEG(t, quadImage(64, 48))) + id := decode[StationPhotoUploadResponse](t, w).PhotoID + get := func(id string) *httptest.ResponseRecorder { + return env.do("GET", "/api/antenna-claims/photos/"+id, "", "") + } + if got := decode[StationPhotoStatusResponse](t, get(id)); got.Status != antennaclaim.RequestQueued { + t.Fatalf("queued: %+v", got) + } + env.queue.CompleteValue(id, antennaclaim.Result{RequestID: id, Status: antennaclaim.RequestError, Error: "photo storage is full"}) + if got := decode[StationPhotoStatusResponse](t, get(id)); got.Status != antennaclaim.RequestError || got.Error != "photo storage is full" { + t.Fatalf("refused: %+v", got) + } + env.storePhoto(t, photoIDTest, photoClaim, pk, antennaclaim.PhotoPending) + if got := decode[StationPhotoStatusResponse](t, get(photoIDTest)); got.Status != antennaclaim.PhotoPending { + t.Fatalf("stored: %+v", got) + } + for name, path := range map[string]string{"unknown": photoIDOther, "bad id": "0123", "long id": photoIDTest + "00"} { + if w := get(path); w.Code != http.StatusNotFound && w.Code != http.StatusBadRequest { + t.Errorf("%s: %d", name, w.Code) + } + } + // Accepted once, gone now: 404, never which. + env.queue.CompleteValue(photoIDOther, antennaclaim.Result{RequestID: photoIDOther, Status: antennaclaim.PhotoPending}) + if w := get(photoIDOther); w.Code != http.StatusNotFound { + t.Fatalf("gone: %d", w.Code) + } + env.srv.cfg.SetHiddenNamePrefixes([]string{"Roo"}) + if w := get(photoIDTest); w.Code != http.StatusNotFound { + t.Fatalf("hidden: %d", w.Code) + } +} + +// ── Public ──────────────────────────────────────────────────────────────── + +func photoURL(pk, id, size string) string { + u := "/api/nodes/" + pk + "/photo/" + id + ".jpg" + if size != "" { + u += "?size=" + size + } + return u +} + +func TestStationPhotos1017M5_PublicServesImmutable(t *testing.T) { + env := photosEnv(t, nil) + pk := pk789("a") + env.addNode(t, pk, "Roof", "repeater", est789Lat, est789Lon) + env.approvedStation(t, photoClaim, pk) + full, thumb := env.storePhoto(t, photoIDTest, photoClaim, pk, antennaclaim.PhotoApproved) + for size, want := range map[string][]byte{"": full, "full": full, "thumb": thumb} { + w := env.do("GET", photoURL(pk, photoIDTest, size), "", "") + if w.Code != http.StatusOK || !bytes.Equal(w.Body.Bytes(), want) { + t.Fatalf("size %q: %d, %d bytes", size, w.Code, w.Body.Len()) + } + h := w.Header() + if h.Get("Cache-Control") != "public, max-age=31536000, immutable" || h.Get("Content-Type") != "image/jpeg" || + h.Get("X-Content-Type-Options") != "nosniff" || h.Get("ETag") == "" { + t.Fatalf("size %q headers: %v", size, h) + } + req := httptest.NewRequest("GET", photoURL(pk, photoIDTest, size), nil) + req.Header.Set("If-None-Match", h.Get("ETag")) + w2 := httptest.NewRecorder() + env.router.ServeHTTP(w2, req) + if w2.Code != http.StatusNotModified || w2.Body.Len() != 0 { + t.Fatalf("size %q revalidation: %d", size, w2.Code) + } + } + // /station lists it; the pending one is not listed. + env.storePhoto(t, photoIDOther, photoClaim, pk, antennaclaim.PhotoPending) + st := env.station(t, pk) + if len(st.Photos) != 1 || st.Photos[0].ID != photoIDTest || st.Photos[0].Width != 160 || st.Photos[0].Height != 120 || st.Photos[0].ApprovedAt == 0 { + t.Fatalf("/station photos: %+v", st.Photos) + } +} + +// Every case that does not serve a photo answers exactly the 404 of an +// unknown node: status, headers and body (#743). +func TestStationPhotos1017M5_Public404Identical(t *testing.T) { + no := false + type variant struct { + mod func(*antennaclaim.Config) + setup func(e *claim789Env, pk string) + path func(pk string) string + } + approved := func(e *claim789Env, pk string) { + e.approvedStation(t, photoClaim, pk) + e.storePhoto(t, photoIDTest, photoClaim, pk, antennaclaim.PhotoApproved) + } + std := func(pk string) string { return photoURL(pk, photoIDTest, "") } + cases := map[string]variant{ + "unknown node": {setup: func(e *claim789Env, pk string) {}, path: func(string) string { return photoURL(pk789("b"), photoIDTest, "") }}, + "hidden node": {setup: func(e *claim789Env, pk string) { approved(e, pk); e.srv.cfg.SetHiddenNamePrefixes([]string{"Roo"}) }, path: std}, + "stale": {setup: func(e *claim789Env, pk string) { approved(e, pk); e.move(t, pk, est789Lat+60/111320.0, est789Lon) }, path: std}, + "pending photo": {setup: func(e *claim789Env, pk string) { + e.approvedStation(t, photoClaim, pk) + e.storePhoto(t, photoIDTest, photoClaim, pk, antennaclaim.PhotoPending) + }, path: std}, + "photos off": {mod: func(c *antennaclaim.Config) { c.Photos = &antennaclaim.PhotoConfig{Enabled: &no} }, setup: approved, path: std}, + "details off": {mod: func(c *antennaclaim.Config) { c.DetailsEnabled = false }, setup: approved, path: std}, + "claim not in force": {setup: func(e *claim789Env, pk string) { + r := stationRow(photoClaim, pk) + r.dIn = false + e.insert898(t, r) + e.storePhoto(t, photoIDTest, photoClaim, pk, antennaclaim.PhotoApproved) + }, path: std}, + "files gone": {setup: func(e *claim789Env, pk string) { + approved(e, pk) + os.RemoveAll(filepath.Join(e.svc.photos.root, photoIDTest)) + }, path: std}, + "unknown photo": {setup: approved, path: func(pk string) string { return photoURL(pk, photoIDOther, "") }}, + "another node's": {setup: approved, path: func(string) string { return photoURL(pk789("c"), photoIDTest, "") }}, + "bad size": {setup: approved, path: func(pk string) string { return photoURL(pk, photoIDTest, "original") }}, + "png extension": {setup: approved, path: func(pk string) string { return "/api/nodes/" + pk + "/photo/" + photoIDTest + ".png" }}, + "no extension": {setup: approved, path: func(pk string) string { return "/api/nodes/" + pk + "/photo/" + photoIDTest }}, + "upper-case id": {setup: approved, path: func(pk string) string { return photoURL(pk, strings.ToUpper("abcdef0123456789"), "") }}, + "backslash traversal": {setup: approved, path: func(pk string) string { return "/api/nodes/" + pk + "/photo/..%5c..%5cetc%5cpasswd.jpg" }}, + "dot-dot id": {setup: approved, path: func(pk string) string { return "/api/nodes/" + pk + "/photo/...........jpg" }}, + "inbox name": {setup: approved, path: func(pk string) string { return "/api/nodes/" + pk + "/photo/inbox.jpg" }}, + "bad pubkey": {setup: approved, path: func(string) string { return photoURL("zz", photoIDTest, "") }}, + } + type answer struct { + code int + ct, cache, nosni string + body string + } + var ref *answer + refName := "" + names := make([]string, 0, len(cases)) + for n := range cases { + names = append(names, n) + } + sort.Strings(names) + // The pass case proves the fixture serves at all. + { + env := photosEnv(t, nil) + pk := pk789("a") + env.addNode(t, pk, "Roof", "repeater", est789Lat, est789Lon) + approved(env, pk) + if w := env.do("GET", std(pk), "", ""); w.Code != http.StatusOK { + t.Fatalf("the approved photo is not served (%d): the 404s prove nothing", w.Code) + } + } + for _, name := range names { + tc := cases[name] + env := photosEnv(t, tc.mod) + if tc.mod != nil && !env.svc.photos.enabled && name != "photos off" && name != "details off" { + t.Fatalf("%s: photos off", name) + } + pk := pk789("a") + env.addNode(t, pk, "Roof", "repeater", est789Lat, est789Lon) + env.addNode(t, pk789("c"), "Hill", "repeater", est789Lat, est789Lon) + tc.setup(env, pk) + w := env.do("GET", tc.path(pk), "", "") + got := answer{w.Code, w.Header().Get("Content-Type"), w.Header().Get("Cache-Control"), w.Header().Get("X-Content-Type-Options"), w.Body.String()} + if got.code != http.StatusNotFound { + t.Errorf("%s: %d %s, want 404", name, got.code, got.body) + continue + } + if ref == nil { + ref, refName = &got, name + continue + } + if got != *ref { + t.Errorf("%s answers %+v, %s answers %+v: not identical", name, got, refName, *ref) + } + } + if ref == nil || ref.cache != "no-store" { + t.Fatalf("reference 404: %+v", ref) + } + // A slash, encoded or not, never reaches the handler: the router + // cleans the path and redirects, so no file outside the store is read. + env := photosEnv(t, nil) + pk := pk789("a") + env.addNode(t, pk, "Roof", "repeater", est789Lat, est789Lon) + approved(env, pk) + for _, p := range []string{"/api/nodes/" + pk + "/photo/..%2f..%2f..%2fetc%2fpasswd.jpg", "/api/nodes/" + pk + "/photo/../../../../etc/passwd"} { + if w := env.do("GET", p, "", ""); w.Code == http.StatusOK || strings.Contains(w.Body.String(), "root:") { + t.Errorf("%s: %d", p, w.Code) + } + } +} + +func TestStationPhotos1017M5_StationPhotosGate(t *testing.T) { + no := false + for name, tc := range map[string]struct { + mod func(*antennaclaim.Config) + move bool + want int + }{ + "on": {nil, false, 1}, + "off": {func(c *antennaclaim.Config) { c.Photos = &antennaclaim.PhotoConfig{Enabled: &no} }, false, 0}, + "stale": {nil, true, 0}, + } { + env := photosEnv(t, tc.mod) + pk := pk789("a") + env.addNode(t, pk, "Roof", "repeater", est789Lat, est789Lon) + env.approvedStation(t, photoClaim, pk) + env.storePhoto(t, photoIDTest, photoClaim, pk, antennaclaim.PhotoApproved) + if tc.move { + env.move(t, pk, est789Lat+60/111320.0, est789Lon) + } + st := env.station(t, pk) + if len(st.Photos) != tc.want { + t.Errorf("%s: %d photos, want %d", name, len(st.Photos), tc.want) + } + if raw := env.do("GET", "/api/nodes/"+pk+"/station", "", "").Body.String(); tc.want == 0 && strings.Contains(raw, "photos") { + t.Errorf("%s: the body names photos: %s", name, raw) + } + } + // The config route reports the switch. + env := photosEnv(t, nil) + var cfg AntennaClaimConfigResponse + json.Unmarshal(env.do("GET", "/api/antenna-claims/config", "", "").Body.Bytes(), &cfg) + if !cfg.PhotosEnabled { + t.Fatal("config: photosEnabled false with details on (default on)") + } +} + +// ── Admin ───────────────────────────────────────────────────────────────── + +func TestStationPhotos1017M5_AdminRoutes(t *testing.T) { + env := photosEnv(t, nil) + pk, hidden := pk789("a"), pk789("d") + env.addNode(t, pk, "Roof", "repeater", est789Lat, est789Lon) + env.addNode(t, hidden, "private-mast", "repeater", est789Lat, est789Lon) + env.srv.cfg.SetHiddenNamePrefixes([]string{"private-"}) + env.approvedStation(t, photoClaim, pk) + env.approvedStation(t, "a000000000000009", hidden) + full, _ := env.storePhoto(t, photoIDTest, photoClaim, pk, antennaclaim.PhotoPending) + env.storePhoto(t, photoIDOther, photoClaim, pk, antennaclaim.PhotoApproved) + env.storePhoto(t, "1111111111111111", "a000000000000009", hidden, antennaclaim.PhotoPending) + + for _, path := range []string{"/api/admin/antenna-claims/photos", "/api/admin/antenna-claims/photos/" + photoIDTest} { + if w := env.do("GET", path, "", ""); w.Code == http.StatusOK { + t.Fatalf("%s without the key: 200", path) + } + } + for _, path := range []string{"approve", "reject"} { + if w := env.do("POST", "/api/admin/antenna-claims/photos/"+photoIDTest+"/"+path, "", ""); w.Code == http.StatusAccepted { + t.Fatalf("%s without the key: 202", path) + } + } + list := decode[AdminClaimPhotoListResponse](t, env.do("GET", "/api/admin/antenna-claims/photos", "", claimAdminKey)) + if !list.Enabled || len(list.Photos) != 2 { + t.Fatalf("list: %+v (the hidden node's photo must be left out)", list) + } + pending := decode[AdminClaimPhotoListResponse](t, env.do("GET", "/api/admin/antenna-claims/photos?status=pending", "", claimAdminKey)) + if len(pending.Photos) != 1 || pending.Photos[0].ID != photoIDTest || !pending.Photos[0].Servable || pending.Photos[0].ClaimID != photoClaim || pending.Photos[0].Name != "Roof" { + t.Fatalf("pending list: %+v", pending.Photos) + } + if w := env.do("GET", "/api/admin/antenna-claims/photos?status=rejected", "", claimAdminKey); w.Code != http.StatusBadRequest { + t.Fatalf("bad filter: %d", w.Code) + } + img := env.do("GET", "/api/admin/antenna-claims/photos/"+photoIDTest, "", claimAdminKey) + if img.Code != http.StatusOK || !bytes.Equal(img.Body.Bytes(), full) || img.Header().Get("Cache-Control") != "no-store" || img.Header().Get("Content-Type") != "image/jpeg" { + t.Fatalf("admin image: %d %v", img.Code, img.Header()) + } + if w := env.do("GET", "/api/admin/antenna-claims/photos/1111111111111111", "", claimAdminKey); w.Code != http.StatusNotFound { + t.Fatalf("hidden node's image: %d", w.Code) + } + // Decisions. + if w := env.do("POST", "/api/admin/antenna-claims/photos/"+photoIDOther+"/approve", "", claimAdminKey); w.Code != http.StatusConflict { + t.Fatalf("approve an approved photo: %d", w.Code) + } + if w := env.do("POST", "/api/admin/antenna-claims/photos/"+photoIDTest+"/approve", "", claimAdminKey); w.Code != http.StatusAccepted { + t.Fatalf("approve: %d %s", w.Code, w.Body) + } + if w := env.do("POST", "/api/admin/antenna-claims/photos/"+photoIDOther+"/reject", "", claimAdminKey); w.Code != http.StatusAccepted { + t.Fatalf("reject an approved photo: %d", w.Code) + } + if w := env.do("POST", "/api/admin/antenna-claims/photos/1111111111111111/reject", "", claimAdminKey); w.Code != http.StatusNotFound { + t.Fatalf("reject a hidden node's photo: %d", w.Code) + } + byOp := map[string]string{} + for _, c := range env.queued(t) { + byOp[c.Op] = c.PhotoID + } + if len(byOp) != 2 || byOp[antennaclaim.OpPhotoApprove] != photoIDTest || byOp[antennaclaim.OpPhotoReject] != photoIDOther { + t.Fatalf("queued: %+v", byOp) + } +} + +func TestStationPhotos1017M5_AdminApproveNeedsServableClaim(t *testing.T) { + no := false + env := photosEnv(t, nil) + pk := pk789("a") + env.addNode(t, pk, "Roof", "repeater", est789Lat, est789Lon) + r := stationRow(photoClaim, pk) + r.status, r.dIn = antennaclaim.StatusProven, false + env.insert898(t, r) + env.storePhoto(t, photoIDTest, photoClaim, pk, antennaclaim.PhotoPending) + if w := env.do("POST", "/api/admin/antenna-claims/photos/"+photoIDTest+"/approve", "", claimAdminKey); w.Code != http.StatusConflict { + t.Fatalf("approve on a proven claim: %d", w.Code) + } + off := photosEnv(t, func(c *antennaclaim.Config) { c.Photos = &antennaclaim.PhotoConfig{Enabled: &no} }) + off.addNode(t, pk, "Roof", "repeater", est789Lat, est789Lon) + off.approvedStation(t, photoClaim, pk) + off.storePhoto(t, photoIDTest, photoClaim, pk, antennaclaim.PhotoPending) + if w := off.do("POST", "/api/admin/antenna-claims/photos/"+photoIDTest+"/approve", "", claimAdminKey); w.Code != http.StatusForbidden { + t.Fatalf("approve while off: %d", w.Code) + } + if w := off.do("POST", "/api/admin/antenna-claims/photos/"+photoIDTest+"/reject", "", claimAdminKey); w.Code != http.StatusAccepted { + t.Fatalf("reject while off: %d (a photo can always be taken down)", w.Code) + } +} + +// photo:"keep" rides the claim; it needs details. +func TestStationPhotos1017M5_ClaimKeepPhotos(t *testing.T) { + env := photosEnv(t, nil) + pk := pk789("a") + env.addNode(t, pk, "Roof", "repeater", est789Lat, est789Lon) + for body, want := range map[string]int{ + `{"details":{"installation":"mast"},"photo":"keep"}`: http.StatusAccepted, + `{"heightM":12,"photo":"keep"}`: http.StatusBadRequest, + `{"clearDetails":true,"photo":"keep"}`: http.StatusBadRequest, + `{"details":{"installation":"mast"},"photo":"drop"}`: http.StatusBadRequest, + } { + if w := env.post(pk, body); w.Code != want { + t.Errorf("%s: %d %s, want %d", body, w.Code, w.Body, want) + } + } + cmds := env.queued(t) + if len(cmds) != 1 || !cmds[0].KeepPhotos { + t.Fatalf("queued: %+v", cmds) + } +} + +// The station photo response types join the public types the contact +// reflection test walks. +func init() { + publicResponseTypes = append(publicResponseTypes, + StationPhotoUploadResponse{}, StationPhotoStatusResponse{}, antennaclaim.StationPhoto{}) +} diff --git a/config.example.json b/config.example.json index 3f2e093ee..f1f0cc2c4 100644 --- a/config.example.json +++ b/config.example.json @@ -492,9 +492,19 @@ "pollBackoff": 1.5, "pollMaxMs": 30000, "pollMaxAttempts": 60, - "adminDefaultFilter": "proven" + "adminDefaultFilter": "proven", + "photos": { + "enabled": true, + "maxApprovedPerNode": 3, + "maxPending": 32, + "maxStoreMiB": 512, + "maxUploadMiB": 8, + "maxMegapixels": 16, + "uploadsPerHourPerIP": 10, + "uploadWindowDays": 7 + } }, - "_comment_antennaClaims": "Owner antenna heights (#789): a node's owner claims its antenna height with POST /api/nodes/{pubkey}/antenna-claims, gets a 6-character code, puts it into the node's advert name (appended, within the first 23 bytes) and sends an advert. A new advert with a valid signature from that key proves the claim; the code is single-use and expires after 24 h. Claims open only when enabled is true AND apiKey is strong. A proven height waits for an administrator (GET/POST /api/admin/antenna-claims) unless autoApproveProven is true, and even then a height far from the surface estimate waits. Only repeater and room claims with a cached surface estimate can be flagged, so with autoApproveProven on every companion and sensor claim, and every claim whose surface is not cached yet, is approved without review at any height from 0 to 100 m. An approval of a proof older than the node's claim already in force is refused (409). A proven clear removes the owner's height at once. detailsEnabled (#898, default false; needs enabled) also lets owners set station details in the same claim: antenna type, gain (-5 to 20 dBi), power, installation and two optional contacts, contactPublic (shown to everyone on the node page and by GET /api/nodes/{pubkey}/station) and contactAdmin (admin queue only, never public, never logged). A claim that sets details waits for an administrator unless autoApproveDetails is true (#1007, default false; needs detailsEnabled): then a proven claim that sets details is approved without an administrator, height, details and both contacts included, unless it is flagged for review (a flagged claim always waits). WARNING: with autoApproveDetails on, the contactPublic free text goes public without review; revoke is the only remedy. autoApproveProven and autoApproveDetails are independent: autoApproveProven covers claims without details, autoApproveDetails claims with them, so both must be true for every unflagged claim to be approved without an administrator. Turning a switch on does not approve claims that are already proven. One approval decides the whole claim. Both contacts are deleted when the details are removed, replaced, rejected, revoked or expire, and when retention deletes the claim; admin database backups (GET /api/backup, scripts/backup-sqlite.sh) and SQLite free pages can still hold a deleted contact, because deletion is logical. With detailsEnabled off, setting details is refused (403) but removing them still works. All four switches are read by their exact spelling. Approved heights rank below radio.antennaHeightsM per node and above the surface estimate, and are ignored once the node moves more than staleMoveM (default 50 m, at most 5000) from where the height was proven. reviewDeltaM (default 60 m, at most 1000) is how far above the surface estimate + 2 m a height may be before it is flagged for review (more than 2 m below the surface is always flagged). Limits: maxPending (all nodes) and maxPendingPerNode bound unproven claims (a claim over a limit is refused, never evicts another), maxQueuedRequests bounds the request queue next to the database, submissionsPerHour is a global sliding window, and finished claims are deleted after retentionDays (the approved one is kept). Read by both server and ingestor; changing this policy requires an ingestor restart. Owner page and admin queue (server only, sent to the browser by GET /api/antenna-claims/config): the claim status is checked after pollInitialMs (default 2000, 500-60000), each later wait grows by pollBackoff (default 1.5, 1-4) up to pollMaxMs (default 30000, at most 600000) per wait, for at most pollMaxAttempts checks (default 60, at most 1000) before the page offers Check again; adminDefaultFilter (default proven; pending, approved, rejected, revoked, expired or superseded) is the admin queue's first view. A value out of its range is the default. Owner guide: docs/user-guide/antenna-height-claims.md.", + "_comment_antennaClaims": "Owner antenna heights (#789): a node's owner claims its antenna height with POST /api/nodes/{pubkey}/antenna-claims, gets a 6-character code, puts it into the node's advert name (appended, within the first 23 bytes) and sends an advert. A new advert with a valid signature from that key proves the claim; the code is single-use and expires after 24 h. Claims open only when enabled is true AND apiKey is strong. A proven height waits for an administrator (GET/POST /api/admin/antenna-claims) unless autoApproveProven is true, and even then a height far from the surface estimate waits. Only repeater and room claims with a cached surface estimate can be flagged, so with autoApproveProven on every companion and sensor claim, and every claim whose surface is not cached yet, is approved without review at any height from 0 to 100 m. An approval of a proof older than the node's claim already in force is refused (409). A proven clear removes the owner's height at once. detailsEnabled (#898, default false; needs enabled) also lets owners set station details in the same claim: antenna type, gain (-5 to 20 dBi), power, installation and two optional contacts, contactPublic (shown to everyone on the node page and by GET /api/nodes/{pubkey}/station) and contactAdmin (admin queue only, never public, never logged). A claim that sets details waits for an administrator unless autoApproveDetails is true (#1007, default false; needs detailsEnabled): then a proven claim that sets details is approved without an administrator, height, details and both contacts included, unless it is flagged for review (a flagged claim always waits). WARNING: with autoApproveDetails on, the contactPublic free text goes public without review; revoke is the only remedy. autoApproveProven and autoApproveDetails are independent: autoApproveProven covers claims without details, autoApproveDetails claims with them, so both must be true for every unflagged claim to be approved without an administrator. Turning a switch on does not approve claims that are already proven. One approval decides the whole claim. Both contacts are deleted when the details are removed, replaced, rejected, revoked or expire, and when retention deletes the claim; admin database backups (GET /api/backup, scripts/backup-sqlite.sh) and SQLite free pages can still hold a deleted contact, because deletion is logical. With detailsEnabled off, setting details is refused (403) but removing them still works. All four switches are read by their exact spelling. Approved heights rank below radio.antennaHeightsM per node and above the surface estimate, and are ignored once the node moves more than staleMoveM (default 50 m, at most 5000) from where the height was proven. reviewDeltaM (default 60 m, at most 1000) is how far above the surface estimate + 2 m a height may be before it is flagged for review (more than 2 m below the surface is always flagged). Limits: maxPending (all nodes) and maxPendingPerNode bound unproven claims (a claim over a limit is refused, never evicts another), maxQueuedRequests bounds the request queue next to the database, submissionsPerHour is a global sliding window, and finished claims are deleted after retentionDays (the approved one is kept). Read by both server and ingestor; changing this policy requires an ingestor restart. Owner page and admin queue (server only, sent to the browser by GET /api/antenna-claims/config): the claim status is checked after pollInitialMs (default 2000, 500-60000), each later wait grows by pollBackoff (default 1.5, 1-4) up to pollMaxMs (default 30000, at most 600000) per wait, for at most pollMaxAttempts checks (default 60, at most 1000) before the page offers Check again; adminDefaultFilter (default proven; pending, approved, rejected, revoked, expired or superseded) is the admin queue's first view. A value out of its range is the default. Owner guide: docs/user-guide/antenna-height-claims.md. Station photos (#1017 M5, photos): with detailsEnabled, an owner can add a photo of the installation to a claim that sets details, within uploadWindowDays (default 7, at most 90) of its proof, with the claim's request id (POST /api/antenna-claims/requests/{requestId}/photo, the image as the body). A photo is NEVER approved automatically, whatever autoApproveProven and autoApproveDetails say: an administrator reviews every one (GET/POST /api/admin/antenna-claims/photos). photos.enabled is on by default once detailsEnabled is (only a canonical false turns it off). The server re-encodes each upload (no EXIF, XMP, GPS or other metadata, turned upright, at most 1600 px and 1 MiB) and writes it only to station-photos/inbox/ next to the database; the ingestor moves it into station-photos/ and owns every deletion. Caps: maxApprovedPerNode (default 3, at most 10; approving one more deletes the oldest), one photo per node waiting for review (a new upload replaces it), maxPending in all (default 32), maxStoreMiB stored in all (default 512), maxUploadMiB per upload (default 8, at most 16), maxMegapixels per upload (default 16, at most 16; and 8192 px a side), uploadsPerHourPerIP (default 10; needs webSocket.trustedProxies behind a proxy). A value out of its range is the default. Photos are deleted, rows and files, when rejected, replaced, or when their claim is rejected, revoked, cleared, replaced by newer details (unless the new claim says photo: keep) or pruned. Back up station-photos/ together with the database: GET /api/backup and scripts/backup-sqlite.sh copy only the database. Read by both server and ingestor.", "accounts": { "enabled": false, "sessionDays": 30, diff --git a/docs/deployment.md b/docs/deployment.md index ea50762e2..f86748739 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -1510,6 +1510,10 @@ With `antennaClaims.detailsEnabled` (see [Owner antenna heights](user-guide/conf - Queued requests in `antenna-claim-requests/` carry both contacts until the ingestor next runs: command files are never pruned by age, so while the ingestor is down they stay. A request older than 24 hours is then refused without being applied, and its file is removed. The directory is `0700` and the files `0600`, owned by the service user (see [Running the Go services without root](#running-the-go-services-without-root-opt-in)). Copies of the data directory keep whatever access you give them. - The contacts are never written to the logs. +### Station photos in backups + +With station photos (`antennaClaims.photos`, on by default with `detailsEnabled`; see [Station photos](user-guide/configuration.md#station-photos)), the photo files live in `station-photos/` next to the database, not in it. `GET /api/backup` and `scripts/backup-sqlite.sh` copy the database only. Back up `station-photos/` at the same time; a volume backup of `/app/data` already holds both. A database restored without its photo directory heals itself: at the next retention run the ingestor removes the rows whose files are gone, and owners upload again. Photo directories without a row are removed the same way. A photo is personal data if it shows people or an address, so the same retention thinking as for [owner contacts](#owner-contacts-in-backups) applies. + ### Restore Restore both databases from **one complete, trusted backup directory**, with diff --git a/docs/user-guide/antenna-height-claims.md b/docs/user-guide/antenna-height-claims.md index 16352f4c3..8bf7648e8 100644 --- a/docs/user-guide/antenna-height-claims.md +++ b/docs/user-guide/antenna-height-claims.md @@ -179,6 +179,18 @@ Deletion is **logical**, not a wipe of the disk: This is the operator's own storage. Other visitors never see it. +## Station photos + +If the site has station details on, you can add a photo of the installation (the mast, the antenna, the view) to a claim that sets station details. Up to three approved photos are shown per node; the operator may set another number. + +- **When.** After the claim is proven (the advert with the code arrived), within 7 days of the proof. The request id of your claim is what lets you upload: nobody else can attach a photo to your node. +- **How.** Send the photo as the body of `POST /api/antenna-claims/requests/{requestId}/photo`, with `Content-Type: image/jpeg` or `image/png`, at most 8 MB and 16 megapixels. The answer is a photo id; `GET /api/antenna-claims/photos/{photoId}` tells you whether it is queued, waiting for review or approved. +- **Review.** An administrator looks at every photo before it is shown. That never happens automatically. Photos that show people or faces, house numbers, number plates, screens, or text other than the equipment are rejected. +- **What is kept.** The site makes a new JPEG from your photo: at most 1600 px wide or tall, turned the right way up, without any of the camera's data (no location, no camera model, no date). The file you sent is not stored. +- **One waiting at a time.** A new upload replaces your photo that is still waiting for review. +- **When it is deleted.** When it is rejected, when a newer approved photo replaces it (the oldest goes first), and when the claim's details are deleted for any of the reasons above. A new claim that sets details deletes the photos of the details it replaces, unless it says `"photo": "keep"`: then they move to the new claim. +- **Caches.** An approved photo is served with a long cache lifetime. After it is deleted it is gone from this site, but a browser or proxy that already loaded it may keep its copy. + ## Privacy The site stores the node's public key, the height, the station details you set, the code, and the time and position of the proving advert. The public contact is shown to everyone and the administrator contact only to administrators. Finished claims are deleted after a retention period set by the operator; the approved one is kept while it is in force. Nothing about you as a person is asked for, and both contacts are optional. diff --git a/docs/user-guide/configuration.md b/docs/user-guide/configuration.md index 869ff2cc2..c5905a49c 100644 --- a/docs/user-guide/configuration.md +++ b/docs/user-guide/configuration.md @@ -212,6 +212,7 @@ An administrator can also revoke a previously approved channel (see [Channels](c | `pollMaxMs` | `30000` | The longest single wait. Never below `pollInitialMs`; at most 600000. | | `pollMaxAttempts` | `60` | Status checks before the page stops and offers **Check again**. At most 1000. | | `adminDefaultFilter` | `proven` | The admin queue's first view (`#/tools/antenna-claims`): `proven`, `pending`, `approved`, `rejected`, `revoked`, `expired` or `superseded`. | +| `photos` | see below | Station photos (#1017): an object with the keys below. See [Station photos](#station-photos). | A value outside its range falls back to its default. The page reads the last five from `GET /api/antenna-claims/config`, so they need only a server restart. @@ -236,6 +237,30 @@ With `detailsEnabled`, a claim can carry station details next to the height, und An approved height ranks below a per-node height in `radio.antennaHeightsM` and above the surface estimate and the role heights in `radio.antennaHeightsM`. In full, a profile takes the first of: the request (a typed height or a link), the operator's height for the node, the owner's approved height, the surface estimate (only where it is above the role height), the operator's height for the role, the built-in role default. A height a viewer types or opens from a link still wins for that viewer, and each viewer can turn **Prefer owner heights** off in the customizer (see [Customization](customization.md#terrain-profile-display-tab)). +### Station photos + +With `detailsEnabled`, an owner can add a photo of the installation (the mast, the antenna, the view) to a claim that sets station details. Owners follow [Station photos](antenna-height-claims.md#station-photos). The keys live in `antennaClaims.photos`; the server and the ingestor read them, and a change needs a restart of both. They are operator settings, not customizer settings. + +| Field | Default | Description | +|-------|---------|-------------| +| `photos.enabled` | `true` | On once `detailsEnabled` is (and `enabled` with a strong `apiKey`). Only a canonical `false` turns it off; `Enabled` is ignored and logged like the other gates. Off, uploads and approvals are refused, no photo is shown, and an administrator can still reject (delete) photos. | +| `photos.maxApprovedPerNode` | `3` | Approved photos shown per node. Approving one more deletes the oldest. At most 10. | +| `photos.maxPending` | `32` | Photos waiting for review, over all nodes. Each node has at most one: a new upload replaces it. At most 1024. | +| `photos.maxStoreMiB` | `512` | Stored photo bytes in all (both files of every photo). An upload over it is refused with "photo storage is full". | +| `photos.maxUploadMiB` | `8` | The largest upload accepted. At most 16. | +| `photos.maxMegapixels` | `16` | The most pixels an upload may have; each side is also at most 8192 px. Checked from the header before any decoding. At most 16. | +| `photos.uploadsPerHourPerIP` | `10` | Uploads per client and hour; a refused upload is refunded. Behind a reverse proxy it needs `webSocket.trustedProxies`. | +| `photos.uploadWindowDays` | `7` | How long after the claim's proof the owner may add photos. At most 90. | + +A value outside its range falls back to its default. + +- **Never automatic.** Every photo waits for an administrator, whatever `autoApproveProven` and `autoApproveDetails` say. The admin queue lists photos (`GET /api/admin/antenna-claims/photos`) and serves each one for review with the API key. A photo can be approved only once its claim is approved. Reject anything that shows people or faces, house numbers, number plates, screens, or text other than the equipment. +- **No metadata.** The server decodes the upload and encodes a new JPEG (at most 1600 px on the long edge and a 480 px thumbnail, together at most 1 MiB), turned upright from the EXIF orientation. EXIF, XMP, GPS, ICC profiles and comments are not copied. The raw upload is never written to disk. At most two uploads are decoded at once; a third gets 503 with `Retry-After`. +- **Where the files are.** In `station-photos/` next to the database. The server writes only to `station-photos/inbox/`; the ingestor checks each photo again, moves it into `station-photos//`, and owns every deletion. Directories are `0700` and files `0600`. +- **Deletion.** A photo is deleted, row and files, when an administrator rejects it, when a newer approved photo replaces it, and when its claim is rejected, revoked, has its details removed or replaced (unless the new claim keeps the photos, `"photo": "keep"`), or is deleted by retention. At every retention run the ingestor also removes files without a row, rows without files, and uploads that waited more than 24 hours. +- **Public.** An approved photo is served at `GET /api/nodes/{pubkey}/photo/{id}.jpg` with a one-year immutable cache, only while the claim's details are shown. It is not in node cards, link previews, `/api/nodes` or exports. Because browsers and CDNs may keep a served photo, a rejection removes it from this site, not from caches that already hold it. +- **Backups.** `GET /api/backup` and `scripts/backup-sqlite.sh` copy only the database. Back up `station-photos/` together with it (a volume backup of the data directory has both). After restoring only the database, the ingestor removes the rows whose files are missing and the owners upload again. See [Deployment → Station photos in backups](../deployment.md#station-photos-in-backups). + ## Owner accounts `accounts` lets an owner sign in with their companion radio and keep **My Mesh** on every device (#1018 M1). There is no password and no e-mail: the owner gets a 6-character code on `#/account`, puts it in the companion's name and sends a **flood** advert; a new advert with a valid signature from that companion proves the sign-in. Only a companion (an `ADV_TYPE_CHAT` advert) can sign in; a repeater, room or sensor cannot. A blacklisted key is refused like an unknown node; a node hidden only by a `hiddenNamePrefixes` prefix may sign in. Owners follow [Your owner account](owner-account.md). The server and the ingestor read the same block; changing it requires a restart of both. diff --git a/internal/channelregistry/antennaclaim/antennaclaim.go b/internal/channelregistry/antennaclaim/antennaclaim.go index 1619cf062..233feecff 100644 --- a/internal/channelregistry/antennaclaim/antennaclaim.go +++ b/internal/channelregistry/antennaclaim/antennaclaim.go @@ -248,6 +248,14 @@ type Command struct { NeedsReview bool `json:"needsReview,omitempty"` ClaimID string `json:"claimId,omitempty"` CreatedAt int64 `json:"createdAt"` + // KeepPhotos (#1017 M5, with Details only): when this claim's details + // replace the details in force, the photos of the replaced claim move + // to this one instead of being deleted. + KeepPhotos bool `json:"keepPhotos,omitempty"` + // PhotoID names the photo of the photo ops; for OpPhotoSubmit it is + // also the request id, ClaimID the claim and Photo its files. + PhotoID string `json:"photoId,omitempty"` + Photo *PhotoFiles `json:"photo,omitempty"` } // ErrInvalidCommand is a command that breaks the shared rules. @@ -322,10 +330,21 @@ func (c Command) Validate() error { if c.Details != nil && c.Details.Validate() != nil { return ErrInvalidCommand } + if c.KeepPhotos && c.Details == nil { + return ErrInvalidCommand + } case OpApprove, OpReject, OpRevoke: if !validID(c.ClaimID) { return ErrInvalidCommand } + case OpPhotoSubmit: + if c.RequestID != c.PhotoID || !ValidPhotoID(c.PhotoID) || !validID(c.ClaimID) || c.Photo == nil || !c.Photo.Valid() { + return ErrInvalidCommand + } + case OpPhotoApprove, OpPhotoReject: + if !ValidPhotoID(c.PhotoID) { + return ErrInvalidCommand + } default: return ErrInvalidCommand } @@ -428,6 +447,9 @@ type Config struct { PollMaxMs int `json:"pollMaxMs,omitempty"` PollMaxAttempts int `json:"pollMaxAttempts,omitempty"` AdminDefaultFilter string `json:"adminDefaultFilter,omitempty"` + // Photos configures station photos (#1017 M5); on by default with + // detailsEnabled. + Photos *PhotoConfig `json:"photos,omitempty"` } // SubmissionsRequested reports whether the operator switched claims on. diff --git a/internal/channelregistry/antennaclaim/photo.go b/internal/channelregistry/antennaclaim/photo.go new file mode 100644 index 000000000..aa7c47f19 --- /dev/null +++ b/internal/channelregistry/antennaclaim/photo.go @@ -0,0 +1,234 @@ +package antennaclaim + +// Station photos (#1017 M5): an owner adds up to MaxApprovedPerNode photos +// of the installation to a claim that sets station details. Photos are +// never approved automatically, whatever the switches say: only an +// administrator's decision shows one. +// +// Who writes what (#1283): +// - the read-only server decodes and re-encodes the upload in memory and +// writes the two JPEG files only under PhotoDir/inbox//, then +// queues an OpPhotoSubmit command in the claim queue; +// - the ingestor re-checks the claim, the files and the caps, moves the +// directory to PhotoDir// and owns the node_claim_photos row, +// every deletion and the orphan sweep. +// +// Paths are never built from user input: a photo id is server-generated, +// exactly 16 lowercase hex characters (ValidPhotoID), and the file names are +// the constants below. + +import ( + "path/filepath" + "time" +) + +// PhotoDirName is the photo store next to the database; PhotoInboxName the +// server's only writable directory inside it. +const ( + PhotoDirName = "station-photos" + PhotoInboxName = "inbox" + PhotoFullName = "full.jpg" + PhotoThumbName = "thumb.jpg" +) + +// PhotoDir returns the photo store for a database path. +func PhotoDir(dbPath string) string { + return filepath.Join(filepath.Dir(dbPath), PhotoDirName) +} + +// Photo operations, in the claim queue. OpPhotoSubmit's request id is the +// photo id, so the owner polls one id. +const ( + OpPhotoSubmit = "photo-submit" // server: files are in the inbox + OpPhotoApprove = "photo-approve" // admin: pending → approved + OpPhotoReject = "photo-reject" // admin: pending or approved → deleted +) + +// Photo statuses, as stored in node_claim_photos.status. A rejected photo +// is deleted; PhotoRejected is only a command result. +const ( + PhotoPending = "pending" + PhotoApproved = "approved" + PhotoRejected = "rejected" +) + +// PhotoStatuses lists the stored photo statuses. +var PhotoStatuses = []string{PhotoPending, PhotoApproved} + +// Bounds of a stored photo: the server's re-encode output, re-checked by the +// ingestor and by the table's CHECKs. +const ( + // PhotoFullMaxPx and PhotoThumbMaxPx bound the long edge. + PhotoFullMaxPx = 1600 + PhotoThumbMaxPx = 480 + // PhotoFullQuality and PhotoThumbQuality are the first JPEG qualities + // tried; PhotoMinQuality the lowest the server steps down to before it + // refuses a photo that does not fit MaxPhotoStoredBytes. + PhotoFullQuality = 80 + PhotoThumbQuality = 75 + PhotoMinQuality = 50 + // MaxPhotoStoredBytes bounds both files of one photo together. + MaxPhotoStoredBytes = 1 << 20 + // MaxPhotoSidePx bounds each side of an upload, before decoding. + MaxPhotoSidePx = 8192 + // PhotoInboxTTL is how long an inbox entry may wait before the sweep + // removes it. + PhotoInboxTTL = 24 * time.Hour + // MaxPendingPhotosPerNode: a new upload replaces the node's pending + // photo (owner decision 14 of 2026-11-29: "plus 1 pending"). + MaxPendingPhotosPerNode = 1 +) + +// ValidPhotoID accepts a photo id: exactly 16 lowercase hex characters, as +// channelregistry.NewID makes them. +func ValidPhotoID(id string) bool { return len(id) == 16 && validID(id) } + +// PhotoFiles describes the two files of one photo, as the server wrote them +// to the inbox. The ingestor re-reads the files and refuses the photo when +// anything differs. +type PhotoFiles struct { + FullSHA256 string `json:"fullSha256"` + ThumbSHA256 string `json:"thumbSha256"` + FullBytes int `json:"fullBytes"` + ThumbBytes int `json:"thumbBytes"` + Width int `json:"width"` + Height int `json:"height"` + ThumbWidth int `json:"thumbWidth"` + ThumbHeight int `json:"thumbHeight"` +} + +// Valid checks f against the stored-photo bounds. +func (f PhotoFiles) Valid() bool { + return validSHA256(f.FullSHA256) && validSHA256(f.ThumbSHA256) && + f.FullBytes > 0 && f.ThumbBytes > 0 && f.FullBytes+f.ThumbBytes <= MaxPhotoStoredBytes && + validPhotoDims(f.Width, f.Height, PhotoFullMaxPx) && validPhotoDims(f.ThumbWidth, f.ThumbHeight, PhotoThumbMaxPx) +} + +func validPhotoDims(w, h, maxPx int) bool { return w >= 1 && h >= 1 && w <= maxPx && h <= maxPx } + +func validSHA256(s string) bool { return len(s) == 64 && validID(s) } + +// StationPhoto is the public face of an approved photo, served by +// GET /api/nodes/{pubkey}/station. It is filled by the server's snapshot, +// never part of DetailsInput. The files are +// /api/nodes/{pubkey}/photo/{id}.jpg?size=thumb|full. +type StationPhoto struct { + ID string `json:"id"` + Width int `json:"width"` + Height int `json:"height"` + ApprovedAt int64 `json:"approvedAt"` +} + +// PhotoLiveSQL is true for a claim whose photos may exist: one that sets +// details and is proven, or approved with its details in force. Every other +// claim's photos are deleted, by the transition that ended it and by the +// sweep at every prune. +const PhotoLiveSQL = `(details_op = 'set' AND (status = 'proven' OR (status = 'approved' AND details_in_force = 1)))` + +// PhotoServableSQL is true for the claim whose photos can be approved and +// shown: approved, its details set and in force. +const PhotoServableSQL = `(details_op = 'set' AND status = 'approved' AND details_in_force = 1)` + +// PhotoUploadSQL is true for a claim an owner may add a photo to: live, and +// proven at or after the one argument (now minus the upload window, ms). +const PhotoUploadSQL = `(` + PhotoLiveSQL + ` AND proven_at IS NOT NULL AND proven_at >= ?)` + +// Photo defaults (owner decisions 14 and 16 of 2026-11-29) and the bounds +// an operator value must stay within; a value outside is the default. +const ( + DefaultPhotoMaxApprovedPerNode = 3 + MaxPhotoMaxApprovedPerNode = 10 + DefaultPhotoMaxPending = 32 + MaxPhotoMaxPending = 1024 + DefaultPhotoMaxStoreMiB = 512 + MaxPhotoMaxStoreMiB = 65536 + DefaultPhotoMaxUploadMiB = 8 + MaxPhotoMaxUploadMiB = 16 + DefaultPhotoMaxMegapixels = 16 + MaxPhotoMaxMegapixels = 16 + DefaultPhotoUploadsPerHourPerIP = 10 + MaxPhotoUploadsPerHourPerIP = 1000 + DefaultPhotoUploadWindowDays = 7 + MaxPhotoUploadWindowDays = 90 +) + +// PhotoConfig is antennaClaims.photos in config.json, read by the server and +// the ingestor. Operator config only, not the customizer. +type PhotoConfig struct { + // Enabled is on by default (owner decision 16); it takes effect only + // with enabled, detailsEnabled and a strong apiKey. Every photo is + // still reviewed by an administrator. + Enabled *bool `json:"enabled,omitempty"` + MaxApprovedPerNode int `json:"maxApprovedPerNode,omitempty"` + MaxPending int `json:"maxPending,omitempty"` + MaxStoreMiB int `json:"maxStoreMiB,omitempty"` + MaxUploadMiB int `json:"maxUploadMiB,omitempty"` + MaxMegapixels int `json:"maxMegapixels,omitempty"` + UploadsPerHourPerIP int `json:"uploadsPerHourPerIP,omitempty"` + UploadWindowDays int `json:"uploadWindowDays,omitempty"` +} + +// PhotoLimits are the resolved photo limits. +type PhotoLimits struct { + MaxApprovedPerNode int + MaxPending int + MaxStoreBytes int64 + MaxUploadBytes int64 + MaxPixels int + UploadsPerHourPerIP int + UploadWindow time.Duration +} + +// PhotoLimits resolves the photo limits. Safe on a nil *Config. +func (c *Config) PhotoLimits() PhotoLimits { + var in PhotoConfig + if c != nil && c.Photos != nil { + in = *c.Photos + } + return PhotoLimits{ + MaxApprovedPerNode: bounded(in.MaxApprovedPerNode, MaxPhotoMaxApprovedPerNode, DefaultPhotoMaxApprovedPerNode), + MaxPending: bounded(in.MaxPending, MaxPhotoMaxPending, DefaultPhotoMaxPending), + MaxStoreBytes: int64(bounded(in.MaxStoreMiB, MaxPhotoMaxStoreMiB, DefaultPhotoMaxStoreMiB)) << 20, + MaxUploadBytes: int64(bounded(in.MaxUploadMiB, MaxPhotoMaxUploadMiB, DefaultPhotoMaxUploadMiB)) << 20, + MaxPixels: bounded(in.MaxMegapixels, MaxPhotoMaxMegapixels, DefaultPhotoMaxMegapixels) * 1_000_000, + UploadsPerHourPerIP: bounded(in.UploadsPerHourPerIP, MaxPhotoUploadsPerHourPerIP, DefaultPhotoUploadsPerHourPerIP), + UploadWindow: time.Duration(bounded(in.UploadWindowDays, MaxPhotoUploadWindowDays, DefaultPhotoUploadWindowDays)) * 24 * time.Hour, + } +} + +// bounded is v when 0 < v <= hi, else def. +func bounded(v, hi, def int) int { + if v <= 0 || v > hi { + return def + } + return v +} + +// PhotosRequested reports whether the operator left station photos on: +// claims and details switched on, and antennaClaims.photos.enabled not +// false. Callers must additionally require a strong admin API key. +func (c *Config) PhotosRequested() bool { + if !c.SubmissionsRequested() || !c.DetailsRequested() { + return false + } + return c.Photos == nil || c.Photos.Enabled == nil || *c.Photos.Enabled +} + +// ApplyPhotoGate sets antennaClaims.photos.enabled from get, which returns +// the JSON boolean at a path of canonical, exact-case keys or nil when it is +// missing (configkey.Doc.Bool). The gate is on by default, so only a +// canonical false turns it off; `Enabled: false` is ignored like the other +// gates' case variants (#884). +func (c *Config) ApplyPhotoGate(get func(path ...string) *bool) { + if c == nil { + return + } + b := get("antennaClaims", "photos", "enabled") + if c.Photos == nil { + if b == nil { + return + } + c.Photos = &PhotoConfig{} + } + c.Photos.Enabled = b +} diff --git a/internal/channelregistry/antennaclaim/photo_1017_m5_test.go b/internal/channelregistry/antennaclaim/photo_1017_m5_test.go new file mode 100644 index 000000000..5077933a7 --- /dev/null +++ b/internal/channelregistry/antennaclaim/photo_1017_m5_test.go @@ -0,0 +1,258 @@ +package antennaclaim + +import ( + "encoding/json" + "os" + "reflect" + "strings" + "testing" + "time" +) + +// #1017 M5 — station photos, the shared rules: ids, files, commands, the +// operator config and its defaults (owner decisions 14 and 16 of +// 2026-11-29). + +func validPhotoFiles() *PhotoFiles { + return &PhotoFiles{ + FullSHA256: strings.Repeat("a", 64), ThumbSHA256: strings.Repeat("b", 64), + FullBytes: 200_000, ThumbBytes: 20_000, Width: 1600, Height: 1200, ThumbWidth: 480, ThumbHeight: 360, + } +} + +func TestPhoto1017M5_ValidPhotoID(t *testing.T) { + for id, want := range map[string]bool{ + "0123456789abcdef": true, + "0123456789abcde": false, // 15 + "0123456789abcdef0": false, // 17: a request id, not a photo id + "0123456789ABCDEF": false, + "../../etc/passwd": false, + "0123456789abcde/": false, + "": false, + "0123456789abcdef0123456789abcdef": false, + } { + if got := ValidPhotoID(id); got != want { + t.Errorf("ValidPhotoID(%q) = %v, want %v", id, got, want) + } + } +} + +func TestPhoto1017M5_PhotoFilesBounds(t *testing.T) { + if !validPhotoFiles().Valid() { + t.Fatal("a valid photo was refused") + } + for name, mod := range map[string]func(*PhotoFiles){ + "short sha": func(f *PhotoFiles) { f.FullSHA256 = "abc" }, + "upper sha": func(f *PhotoFiles) { f.ThumbSHA256 = strings.Repeat("A", 64) }, + "no bytes": func(f *PhotoFiles) { f.FullBytes = 0 }, + "no thumb bytes": func(f *PhotoFiles) { f.ThumbBytes = 0 }, + "over 1 MiB in all": func(f *PhotoFiles) { f.FullBytes, f.ThumbBytes = MaxPhotoStoredBytes, 1 }, + "full too wide": func(f *PhotoFiles) { f.Width = PhotoFullMaxPx + 1 }, + "full too tall": func(f *PhotoFiles) { f.Height = PhotoFullMaxPx + 1 }, + "zero height": func(f *PhotoFiles) { f.Height = 0 }, + "thumb too wide": func(f *PhotoFiles) { f.ThumbWidth = PhotoThumbMaxPx + 1 }, + "thumb zero": func(f *PhotoFiles) { f.ThumbHeight = 0 }, + } { + f := validPhotoFiles() + mod(f) + if f.Valid() { + t.Errorf("%s: accepted", name) + } + } + f := validPhotoFiles() + f.FullBytes, f.ThumbBytes = MaxPhotoStoredBytes-1, 1 + if !f.Valid() { + t.Error("exactly 1 MiB in all was refused") + } +} + +func TestPhoto1017M5_CommandValidate(t *testing.T) { + const photo = "0123456789abcdef" + const claim = "aaaaaaaaaaaaaaaa" + ok := []Command{ + {RequestID: photo, Op: OpPhotoSubmit, PhotoID: photo, ClaimID: claim, Photo: validPhotoFiles()}, + {RequestID: "bbbbbbbbbbbbbbbb", Op: OpPhotoApprove, PhotoID: photo}, + {RequestID: "bbbbbbbbbbbbbbbb", Op: OpPhotoReject, PhotoID: photo}, + } + for _, c := range ok { + if err := c.Validate(); err != nil { + t.Errorf("%s refused: %v", c.Op, err) + } + } + bad := map[string]Command{ + "submit: request id is not the photo id": {RequestID: "cccccccccccccccc", Op: OpPhotoSubmit, PhotoID: photo, ClaimID: claim, Photo: validPhotoFiles()}, + "submit: no files": {RequestID: photo, Op: OpPhotoSubmit, PhotoID: photo, ClaimID: claim}, + "submit: bad files": {RequestID: photo, Op: OpPhotoSubmit, PhotoID: photo, ClaimID: claim, Photo: &PhotoFiles{}}, + "submit: no claim": {RequestID: photo, Op: OpPhotoSubmit, PhotoID: photo, Photo: validPhotoFiles()}, + "submit: traversal id": {RequestID: "../../../../x", Op: OpPhotoSubmit, PhotoID: "../../../../x", ClaimID: claim, Photo: validPhotoFiles()}, + "approve: no photo": {RequestID: "bbbbbbbbbbbbbbbb", Op: OpPhotoApprove}, + "reject: long id": {RequestID: "bbbbbbbbbbbbbbbb", Op: OpPhotoReject, PhotoID: photo + "0"}, + } + for name, c := range bad { + if c.Validate() == nil { + t.Errorf("%s: accepted", name) + } + } +} + +func TestPhoto1017M5_KeepPhotosNeedsDetails(t *testing.T) { + h := 10.0 + base := Command{RequestID: "aaaaaaaaaaaaaaaa", Op: OpClaim, PubKey: strings.Repeat("a", 64), Code: "7KX9QM"} + withDetails := base + withDetails.Details = &DetailsInput{StationDetails: StationDetails{Installation: "mast"}} + withDetails.KeepPhotos = true + if err := withDetails.Validate(); err != nil { + t.Fatalf("keepPhotos with details refused: %v", err) + } + for name, c := range map[string]Command{ + "height only": func() Command { c := base; c.HeightM = &h; c.KeepPhotos = true; return c }(), + "clear details": func() Command { c := base; c.ClearDetails = true; c.KeepPhotos = true; return c }(), + } { + if c.Validate() == nil { + t.Errorf("%s: keepPhotos accepted", name) + } + } +} + +func TestPhoto1017M5_LimitsDefaultsAndBounds(t *testing.T) { + want := PhotoLimits{ + MaxApprovedPerNode: 3, MaxPending: 32, MaxStoreBytes: 512 << 20, MaxUploadBytes: 8 << 20, + MaxPixels: 16_000_000, UploadsPerHourPerIP: 10, UploadWindow: 7 * 24 * time.Hour, + } + var nilCfg *Config + for name, c := range map[string]*Config{"nil": nilCfg, "empty": {}, "no photos": {Photos: nil}, "zero photos": {Photos: &PhotoConfig{}}} { + if got := c.PhotoLimits(); got != want { + t.Errorf("%s: %+v, want %+v", name, got, want) + } + } + over := &Config{Photos: &PhotoConfig{MaxApprovedPerNode: 11, MaxPending: -1, MaxStoreMiB: 65537, + MaxUploadMiB: 17, MaxMegapixels: 17, UploadsPerHourPerIP: 1001, UploadWindowDays: 91}} + if got := over.PhotoLimits(); got != want { + t.Errorf("out of range: %+v, want the defaults", got) + } + in := &Config{Photos: &PhotoConfig{MaxApprovedPerNode: 1, MaxPending: 4, MaxStoreMiB: 64, + MaxUploadMiB: 2, MaxMegapixels: 4, UploadsPerHourPerIP: 3, UploadWindowDays: 1}} + got := in.PhotoLimits() + if got.MaxApprovedPerNode != 1 || got.MaxPending != 4 || got.MaxStoreBytes != 64<<20 || got.MaxUploadBytes != 2<<20 || + got.MaxPixels != 4_000_000 || got.UploadsPerHourPerIP != 3 || got.UploadWindow != 24*time.Hour { + t.Errorf("in range: %+v", got) + } + edge := &Config{Photos: &PhotoConfig{MaxApprovedPerNode: 10, MaxMegapixels: 16, MaxUploadMiB: 16}} + if g := edge.PhotoLimits(); g.MaxApprovedPerNode != 10 || g.MaxPixels != 16_000_000 || g.MaxUploadBytes != 16<<20 { + t.Errorf("upper bounds: %+v", g) + } +} + +// Owner decision 16: photos are on by default once details are; only a +// canonical false turns them off. +func TestPhoto1017M5_GateDefaultsOn(t *testing.T) { + yes, no := true, false + off := func(c *Config) bool { return c.PhotosRequested() } + for name, tc := range map[string]struct { + c *Config + want bool + }{ + "nil": {nil, false}, + "claims off": {&Config{DetailsEnabled: true}, false}, + "details off": {&Config{Enabled: &yes}, false}, + "details on": {&Config{Enabled: &yes, DetailsEnabled: true}, true}, + "details on, block": {&Config{Enabled: &yes, DetailsEnabled: true, Photos: &PhotoConfig{}}, true}, + "details on, true": {&Config{Enabled: &yes, DetailsEnabled: true, Photos: &PhotoConfig{Enabled: &yes}}, true}, + "details on, false": {&Config{Enabled: &yes, DetailsEnabled: true, Photos: &PhotoConfig{Enabled: &no}}, false}, + "claims false, photos": {&Config{Enabled: &no, DetailsEnabled: true, Photos: &PhotoConfig{Enabled: &yes}}, false}, + } { + if got := off(tc.c); got != tc.want { + t.Errorf("%s: PhotosRequested = %v, want %v", name, got, tc.want) + } + } +} + +// The gate is read by its exact spelling: a case variant decoded by +// encoding/json does not turn photos off, a canonical false does. +func TestPhoto1017M5_ApplyPhotoGateExactKeys(t *testing.T) { + yes, no := true, false + get := func(v *bool) func(path ...string) *bool { + return func(path ...string) *bool { + if strings.Join(path, ".") != "antennaClaims.photos.enabled" { + t.Fatalf("read %v", path) + } + return v + } + } + var c Config + if err := json.Unmarshal([]byte(`{"enabled":true,"detailsEnabled":true,"photos":{"Enabled":false}}`), &c); err != nil { + t.Fatal(err) + } + c.Enabled = &yes + c.ApplyPhotoGate(get(nil)) + if !c.PhotosRequested() { + t.Error("a case-variant false turned photos off") + } + c.ApplyPhotoGate(get(&no)) + if c.PhotosRequested() { + t.Error("a canonical false left photos on") + } + bare := Config{Enabled: &yes, DetailsEnabled: true} + bare.ApplyPhotoGate(get(nil)) + if bare.Photos != nil || !bare.PhotosRequested() { + t.Errorf("no key: %+v", bare.Photos) + } + bare.ApplyPhotoGate(get(&no)) + if bare.PhotosRequested() { + t.Error("a canonical false without a photos block left photos on") + } + var nilCfg *Config + nilCfg.ApplyPhotoGate(get(&yes)) // must not panic +} + +func TestPhoto1017M5_PhotoDir(t *testing.T) { + if got := PhotoDir("/data/meshcore.db"); got != "/data/station-photos" { + t.Errorf("PhotoDir = %q", got) + } +} + +// Every antennaClaims.photos key ships with its example and its row in the +// configuration guide (rule 8), and the example is the default. +func TestPhoto1017M5_ExampleAndGuideListEveryPhotoKey(t *testing.T) { + raw, err := os.ReadFile("../../../config.example.json") + if err != nil { + t.Fatal(err) + } + var doc struct { + AntennaClaims struct { + Photos map[string]json.RawMessage `json:"photos"` + } `json:"antennaClaims"` + } + if err := json.Unmarshal(raw, &doc); err != nil { + t.Fatal(err) + } + guide, err := os.ReadFile("../../../docs/user-guide/configuration.md") + if err != nil { + t.Fatal(err) + } + typ := reflect.TypeOf(PhotoConfig{}) + for i := 0; i < typ.NumField(); i++ { + k, _, _ := strings.Cut(typ.Field(i).Tag.Get("json"), ",") + if _, ok := doc.AntennaClaims.Photos[k]; !ok { + t.Errorf("config.example.json antennaClaims.photos has no %q", k) + } + if !strings.Contains(string(guide), "| `photos."+k+"` |") { + t.Errorf("docs/user-guide/configuration.md has no row for photos.%s", k) + } + } + if len(doc.AntennaClaims.Photos) != typ.NumField() { + t.Errorf("config.example.json antennaClaims.photos has %d keys, PhotoConfig %d", len(doc.AntennaClaims.Photos), typ.NumField()) + } + var ex struct { + AntennaClaims Config `json:"antennaClaims"` + } + if err := json.Unmarshal(raw, &ex); err != nil { + t.Fatal(err) + } + if got, want := ex.AntennaClaims.PhotoLimits(), (&Config{}).PhotoLimits(); got != want { + t.Errorf("the example's photo limits %+v are not the defaults %+v", got, want) + } + if ex.AntennaClaims.PhotosRequested() { + t.Error("the example switches photos on (claims and details are off in it)") + } +} diff --git a/internal/dbschema/antenna_claim_photos_test.go b/internal/dbschema/antenna_claim_photos_test.go new file mode 100644 index 000000000..d686dcdb2 --- /dev/null +++ b/internal/dbschema/antenna_claim_photos_test.go @@ -0,0 +1,199 @@ +package dbschema + +import ( + "database/sql" + "fmt" + "strings" + "testing" +) + +// #1017 M5 — station photos: node_claim_photos and keep_photos, created by +// the ingestor's Apply (the server stays read-only, #1283), their CHECKs +// (an insert that bypasses Go fails), the cascade from a pruned claim, +// old rows unchanged, idempotent, and AssertReady. + +func TestAntennaClaimPhotos1017M5_MigrationKeepsOldRows(t *testing.T) { + db := pre1017ClaimsDB(t) + before := dumpClaims(t, db, pre1017Cols) + var logs []string + logf := Logger(func(f string, a ...interface{}) { logs = append(logs, fmt.Sprintf(f, a...)) }) + if err := Apply(db, logf); err != nil { + t.Fatalf("Apply: %v", err) + } + if after := dumpClaims(t, db, pre1017Cols); fmt.Sprint(after) != fmt.Sprint(before) { + t.Fatalf("old rows changed:\n%v\n→\n%v", before, after) + } + var n int + if err := db.QueryRow(`SELECT COUNT(*) FROM node_antenna_claims WHERE keep_photos != 0`).Scan(&n); err != nil || n != 0 { + t.Fatalf("keep_photos on old rows: %d (%v), want all 0", n, err) + } + if countLogs(logs, "#1017 M5") != 1 { + t.Fatalf("migration log lines: %v", logs) + } + if err := AssertReady(db); err != nil { + t.Fatalf("AssertReady: %v", err) + } + logs = nil + if err := Apply(db, logf); err != nil { + t.Fatal(err) + } + if countLogs(logs, "#1017 M5") != 0 { + t.Fatalf("second Apply logged the migration: %v", logs) + } + var recorded int + if err := db.QueryRow(`SELECT COUNT(*) FROM _migrations WHERE name = ?`, AntennaClaimPhotosMigration).Scan(&recorded); err != nil || recorded != 1 { + t.Fatalf("migration recorded %d times (%v)", recorded, err) + } + for _, idx := range []string{"idx_node_claim_photos_pubkey", "idx_node_claim_photos_request"} { + var k int + if err := db.QueryRow(`SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = ?`, idx).Scan(&k); err != nil || k != 1 { + t.Fatalf("index %s: %d (%v)", idx, k, err) + } + } + // The test-only entry point builds the same tables. + fresh := minimalDB(t) + defer fresh.Close() + if err := EnsureNodeAntennaClaims(fresh); err != nil { + t.Fatal(err) + } + if has, err := TableHasColumn(fresh, "node_antenna_claims", "keep_photos"); err != nil || !has { + t.Fatalf("EnsureNodeAntennaClaims lacks keep_photos (%v)", err) + } + if _, err := fresh.Exec(`SELECT photo_id FROM node_claim_photos`); err != nil { + t.Fatalf("EnsureNodeAntennaClaims lacks node_claim_photos: %v", err) + } +} + +// The CHECKs refuse what antennaclaim.PhotoFiles.Valid refuses, for an +// insert that bypasses Go. +func TestAntennaClaimPhotos1017M5_Checks(t *testing.T) { + db := minimalDB(t) + defer db.Close() + if err := Apply(db, nil); err != nil { + t.Fatal(err) + } + foreignKeysOn(t, db) + mustExec(t, db, `INSERT INTO node_antenna_claims (request_id, pubkey, code, status, created_at, expires_at, details_op, installation) + VALUES ('aaaaaaaaaaaaaaaa', '`+strings.Repeat("a", 64)+`', '7KX9QM', 'approved', 1, 2, 'set', 'mast')`) + sha := strings.Repeat("c", 64) + ins := func(over map[string]string) error { + v := map[string]string{ + "photo_id": "'0123456789abcdef'", "request_id": "'aaaaaaaaaaaaaaaa'", "pubkey": "'" + strings.Repeat("a", 64) + "'", + "status": "'pending'", "sha256": "'" + sha + "'", "thumb_sha256": "'" + sha + "'", "bytes": "1000", + "width": "1600", "height": "1200", "created_at": "1", "reviewed_at": "NULL", + } + for k, x := range over { + v[k] = x + } + var cols, vals []string + for k, x := range v { + cols = append(cols, k) + vals = append(vals, x) + } + _, err := db.Exec(`INSERT INTO node_claim_photos (` + strings.Join(cols, ",") + `) VALUES (` + strings.Join(vals, ",") + `)`) + if err == nil { + mustExec(t, db, `DELETE FROM node_claim_photos`) + } + return err + } + for name, tc := range map[string]struct { + over map[string]string + ok bool + }{ + "valid pending": {nil, true}, + "valid approved": {map[string]string{"status": "'approved'", "reviewed_at": "5"}, true}, + "approved without review": {map[string]string{"status": "'approved'"}, false}, + "pending with review": {map[string]string{"reviewed_at": "5"}, false}, + "status rejected": {map[string]string{"status": "'rejected'"}, false}, + "id 15": {map[string]string{"photo_id": "'0123456789abcde'"}, false}, + "id 17": {map[string]string{"photo_id": "'0123456789abcdef0'"}, false}, + "id upper": {map[string]string{"photo_id": "'0123456789ABCDEF'"}, false}, + "id traversal": {map[string]string{"photo_id": "'../../../etc/pa'"}, false}, + "bytes 0": {map[string]string{"bytes": "0"}, false}, + "bytes 1 MiB": {map[string]string{"bytes": "1048576"}, true}, + "bytes over 1 MiB": {map[string]string{"bytes": "1048577"}, false}, + "width 1601": {map[string]string{"width": "1601"}, false}, + "height 0": {map[string]string{"height": "0"}, false}, + "short sha": {map[string]string{"sha256": "'abc'"}, false}, + "short pubkey": {map[string]string{"pubkey": "'ab'"}, false}, + "unknown claim (FK)": {map[string]string{"request_id": "'bbbbbbbbbbbbbbbb'"}, false}, + } { + if err := ins(tc.over); (err == nil) != tc.ok { + t.Errorf("%s: err = %v, want ok=%v", name, err, tc.ok) + } + } + // keep_photos only on a details set. + for name, tc := range map[string]struct { + vals string + ok bool + }{ + "keep on a set": {"'set', 1", true}, + "keep on a clear": {"'clear', 1", false}, + "keep, no details": {"NULL, 1", false}, + "keep 2": {"'set', 2", false}, + } { + _, err := db.Exec(`INSERT INTO node_antenna_claims (request_id, pubkey, code, status, created_at, expires_at, height_m, height_op, details_op, keep_photos) + VALUES (lower(hex(randomblob(8))), 'ab', '7KX9QM', 'pending', 1, 2, 3, 'set', ` + tc.vals + `)`) + if (err == nil) != tc.ok { + t.Errorf("%s: err = %v, want ok=%v", name, err, tc.ok) + } + } +} + +// Deleting a claim drops its photo rows (the ingestor opens SQLite with +// foreign_keys on); the sweep removes the files. +func TestAntennaClaimPhotos1017M5_CascadeOnClaimDelete(t *testing.T) { + db := minimalDB(t) + defer db.Close() + if err := Apply(db, nil); err != nil { + t.Fatal(err) + } + foreignKeysOn(t, db) + mustExec(t, db, `INSERT INTO node_antenna_claims (request_id, pubkey, code, status, created_at, expires_at, details_op, installation) + VALUES ('aaaaaaaaaaaaaaaa', '`+strings.Repeat("a", 64)+`', '7KX9QM', 'approved', 1, 2, 'set', 'mast')`) + sha := strings.Repeat("c", 64) + mustExec(t, db, `INSERT INTO node_claim_photos (photo_id, request_id, pubkey, status, sha256, thumb_sha256, bytes, width, height, created_at) + VALUES ('0123456789abcdef', 'aaaaaaaaaaaaaaaa', '`+strings.Repeat("a", 64)+`', 'pending', '`+sha+`', '`+sha+`', 10, 10, 10, 1)`) + mustExec(t, db, `DELETE FROM node_antenna_claims WHERE request_id = 'aaaaaaaaaaaaaaaa'`) + var n int + if err := db.QueryRow(`SELECT COUNT(*) FROM node_claim_photos`).Scan(&n); err != nil || n != 0 { + t.Fatalf("photo rows after the claim was deleted: %d (%v)", n, err) + } +} + +// AssertReady: a claims table with the M3 columns but not the photo +// migration is the migration still to come (transient); a recorded +// migration with the table gone is permanent. +func TestAntennaClaimPhotos1017M5_AssertReady(t *testing.T) { + db := minimalDB(t) + defer db.Close() + if err := Apply(db, nil); err != nil { + t.Fatal(err) + } + mustExec(t, db, `DROP TABLE node_claim_photos`) + mustExec(t, db, `ALTER TABLE node_antenna_claims DROP COLUMN keep_photos`) + mustExec(t, db, `DELETE FROM _migrations WHERE name = '`+AntennaClaimPhotosMigration+`'`) + nr := notReady(t, AssertReady(db)) + if len(nr.Missing) != 1 || nr.Missing[0] != AntennaClaimPhotosItem || !nr.Transient() { + t.Fatalf("M3 claims table: missing=%v transient=%v, want only %s, transient", nr.Missing, nr.Transient(), AntennaClaimPhotosItem) + } + if err := Apply(db, nil); err != nil { + t.Fatal(err) + } + if err := AssertReady(db); err != nil { + t.Fatalf("after Apply: %v", err) + } + mustExec(t, db, `DROP TABLE node_claim_photos`) + nr = notReady(t, AssertReady(db)) + if !strings.Contains(strings.Join(nr.Missing, ","), "node_claim_photos") || nr.Transient() { + t.Fatalf("recorded migration, table gone: missing=%v transient=%v, want permanent", nr.Missing, nr.Transient()) + } +} + +// foreignKeysOn pins db to one connection with foreign keys on, as the +// ingestor's DSN sets them on every connection. +func foreignKeysOn(t *testing.T, db *sql.DB) { + t.Helper() + db.SetMaxOpenConns(1) + mustExec(t, db, `PRAGMA foreign_keys = ON`) +} diff --git a/internal/dbschema/dbschema.go b/internal/dbschema/dbschema.go index 6dc702ca4..2ae8cfa31 100644 --- a/internal/dbschema/dbschema.go +++ b/internal/dbschema/dbschema.go @@ -153,6 +153,9 @@ func Apply(rw *sql.DB, logf Logger) error { if err := ensureAntennaClaimStationFields(rw, logf); err != nil { return fmt.Errorf("ensure node_antenna_claims station fields: %w", err) } + if err := ensureAntennaClaimPhotos(rw, logf); err != nil { + return fmt.Errorf("ensure node_claim_photos: %w", err) + } if err := EnsureAccounts(rw); err != nil { return fmt.Errorf("ensure accounts: %w", err) } @@ -222,7 +225,8 @@ func (e *NotReadyError) Transient() bool { } for _, m := range e.Missing { switch { - case m == AntennaClaimPartsItem, m == AntennaClaimHardwareItem, m == AntennaClaimStationFieldsItem: + case m == AntennaClaimPartsItem, m == AntennaClaimHardwareItem, m == AntennaClaimStationFieldsItem, + m == AntennaClaimPhotosItem: // The ingestor runs them at start-up, each in one transaction. case m == "table:route_mask_changes": case m == "transmissions.route_mask" && tableUnknown: @@ -454,6 +458,19 @@ func assertReady(ro *sql.DB, probed func(item string)) error { for _, c := range antennaClaimStationFieldColumns { mustCol("node_antenna_claims", c.name) } + // #1017 M5: the photo table and keep_photos, added + // after the station fields. + ph, err := migrationRecorded(tx, AntennaClaimPhotosMigration) + if err != nil { + probeFailed(AntennaClaimPhotosItem, err) + } else if !ph { + missing = append(missing, AntennaClaimPhotosItem) + } else { + for _, c := range antennaClaimPhotoColumns { + mustCol("node_antenna_claims", c.name) + } + mustTable("node_claim_photos") + } } } var partless bool @@ -1498,7 +1515,10 @@ func EnsureNodeAntennaClaims(rw *sql.DB) error { if err := ensureAntennaClaimHardware(rw, func(string, ...interface{}) {}); err != nil { return err } - return ensureAntennaClaimStationFields(rw, func(string, ...interface{}) {}) + if err := ensureAntennaClaimStationFields(rw, func(string, ...interface{}) {}); err != nil { + return err + } + return ensureAntennaClaimPhotos(rw, func(string, ...interface{}) {}) } // AccountTables are the owner-account tables (#1018 M1), in creation order. @@ -1795,11 +1815,59 @@ func ensureAntennaClaimStationFields(rw *sql.DB, logf Logger) error { return addAntennaClaimColumns(rw, logf, AntennaClaimStationFieldsMigration, antennaClaimStationFieldColumns, "#1017 M3 station-field") } -// addAntennaClaimColumns adds cols to node_antenna_claims in one transaction -// and records migration. Each column is guarded by tableHasColumn, so it is -// idempotent and also repairs a table that was rebuilt under a recorded -// migration. It logs only when it added a column. -func addAntennaClaimColumns(rw *sql.DB, logf Logger, migration string, cols []struct{ name, ddl string }, what string) error { +// AntennaClaimPhotosMigration records the #1017 M5 station photos: the +// node_claim_photos table and node_antenna_claims.keep_photos. +const AntennaClaimPhotosMigration = "antenna_claim_photos_v1" + +// AntennaClaimPhotosItem is AssertReady's item for a claims table the +// ingestor has not given the photo table yet: transient. +const AntennaClaimPhotosItem = "migration:" + AntennaClaimPhotosMigration + +// antennaClaimPhotoColumns: keep_photos is the claim's "photo: keep" +// (antennaclaim.Command.KeepPhotos), only on a details set. +var antennaClaimPhotoColumns = []struct{ name, ddl string }{ + {"keep_photos", `keep_photos INTEGER NOT NULL DEFAULT 0 CHECK(keep_photos IN (0,1) AND (keep_photos = 0 OR details_op IS 'set'))`}, +} + +// CreateNodeClaimPhotosSQL is the station photo table (#1017 M5). The +// ingestor is its only writer; the files live in antennaclaim.PhotoDir under +// the photo id. A photo is pending or approved: a rejected one is deleted, +// row and files. The CHECKs mirror antennaclaim.PhotoFiles.Valid: the id is +// exactly 16 lowercase hex characters (it names a directory), bytes counts +// both files, and the dimensions are the full image's. The cascade drops +// the rows of a pruned claim; the ingestor's sweep then removes the files. +const CreateNodeClaimPhotosSQL = `CREATE TABLE IF NOT EXISTS node_claim_photos ( + photo_id TEXT PRIMARY KEY CHECK(length(photo_id) = 16 AND photo_id NOT GLOB '*[^0-9a-f]*'), + request_id TEXT NOT NULL REFERENCES node_antenna_claims(request_id) ON DELETE CASCADE, + pubkey TEXT NOT NULL CHECK(length(pubkey) = 64), + status TEXT NOT NULL CHECK(status IN ('pending','approved')), + sha256 TEXT NOT NULL CHECK(length(sha256) = 64), + thumb_sha256 TEXT NOT NULL CHECK(length(thumb_sha256) = 64), + bytes INTEGER NOT NULL CHECK(bytes BETWEEN 1 AND 1048576), + width INTEGER NOT NULL CHECK(width BETWEEN 1 AND 1600), + height INTEGER NOT NULL CHECK(height BETWEEN 1 AND 1600), + created_at INTEGER NOT NULL, + reviewed_at INTEGER NULL, + CHECK((status = 'approved') = (reviewed_at IS NOT NULL)) + )` + +// ensureAntennaClaimPhotos adds keep_photos and the photo table in one +// transaction and records AntennaClaimPhotosMigration. +func ensureAntennaClaimPhotos(rw *sql.DB, logf Logger) error { + return addAntennaClaimColumns(rw, logf, AntennaClaimPhotosMigration, antennaClaimPhotoColumns, "#1017 M5 photo", + CreateNodeClaimPhotosSQL, + // PREFLIGHT: async=false reason="index on node_claim_photos, a new table bounded by the photo caps; no scan of existing data" + `CREATE INDEX IF NOT EXISTS idx_node_claim_photos_pubkey ON node_claim_photos(pubkey, status)`, + // PREFLIGHT: async=false reason="index on node_claim_photos, a new table bounded by the photo caps; no scan of existing data" + `CREATE INDEX IF NOT EXISTS idx_node_claim_photos_request ON node_claim_photos(request_id)`) +} + +// addAntennaClaimColumns adds cols to node_antenna_claims in one transaction, +// runs the idempotent statements extra (CREATE … IF NOT EXISTS) in the same +// transaction, and records migration. Each column is guarded by +// tableHasColumn, so it is idempotent and also repairs a table that was +// rebuilt under a recorded migration. It logs only when it added a column. +func addAntennaClaimColumns(rw *sql.DB, logf Logger, migration string, cols []struct{ name, ddl string }, what string, extra ...string) error { if err := ensureMigrationsTable(rw); err != nil { return err } @@ -1823,6 +1891,11 @@ func addAntennaClaimColumns(rw *sql.DB, logf Logger, migration string, cols []st } added++ } + for _, q := range extra { + if _, err := tx.Exec(q); err != nil { + return fmt.Errorf("%s: %w", what, err) + } + } if _, err := tx.Exec(`INSERT OR IGNORE INTO _migrations (name) VALUES (?)`, migration); err != nil { return fmt.Errorf("record %s: %w", migration, err) }