Skip to content
go-libfossil Artifact [0221a9a61c]
Login

Artifact [0221a9a61c]

Artifact 0221a9a61c32a28ea0de11e72c26832ad4fe820e1fd72d7bf426a833861587d5:


package shun

import (
	"crypto/ed25519"
	"encoding/base64"
	"encoding/hex"
	"errors"
	"fmt"
	"strconv"
	"strings"

	"github.com/danmestas/go-libfossil/internal/hash"
)

// Signed erasures (draft-fossil-sync-protocol-00 §9.3.1): owner-signed
// statements carried in ordinary /shun rows whose SCOM begins with "e1:".
const (
	// SettingErasureKey is the scalar /config setting pinning the repository's
	// Ed25519 public key as 64 lowercase hex digits.
	SettingErasureKey = "erasure-key"

	// AppliedReason is the plain SCOM recorded once a signed erasure takes
	// effect so later erasure-key changes cannot undo it.
	AppliedReason = "erasure applied"

	// ErasurePrefix begins every signed erasure SCOM.
	ErasurePrefix = "e1:"

	// MaxScomLen bounds a signed erasure SCOM (matching zit's shun reason cap).
	MaxScomLen = 200

	// MaxProjectCodeLen bounds the project code in signed erasure messages.
	MaxProjectCodeLen = 255

	erasureDomain    = "zit-erasure-v1\n"
	signatureTextLen = 86 // unpadded base64url of 64-byte Ed25519 signature
)

// ErasureKind distinguishes a signed erase statement from its cancellation.
type ErasureKind string

const (
	KindErase  ErasureKind = "erase"
	KindCancel ErasureKind = "cancel"
)

// Form classifies a /shun row's SCOM syntactically.
type Form uint8

const (
	FormPlain Form = iota
	FormSigned
	FormMalformed
)

// Verdict is the verification result of one /shun row against an optional key.
type Verdict uint8

const (
	VerdictPlain Verdict = iota
	VerdictVerified
	VerdictUnverified
)

// Status is the folded erasure state of one artifact UUID.
type Status uint8

const (
	StatusInert Status = iota
	StatusShunned
	StatusPending
	StatusErased
)

// Statement is a syntactically valid e1: signed erasure statement.
type Statement struct {
	Signature [ed25519.SignatureSize]byte
	NotBefore int64
	Kind      ErasureKind
	Reason    string
}

// Row is one /shun row: its artifact UUID, Unix-seconds mtime, and SCOM.
type Row struct {
	UUID    string
	MTime   int64
	Comment string
}

// FoldResult is the folded status of one UUID under a pinned key and clock.
type FoldResult struct {
	Status    Status
	NotBefore int64
}

var (
	ErrBadErasureKey   = errors.New("shun: invalid erasure key")
	ErrBadErasureInput = errors.New("shun: invalid signed erasure input")
)

// Classify parses scom as a plain shun comment, a well-formed e1: statement,
// or a malformed e1: statement (§9.3.1).
func Classify(scom string) (Form, Statement) {
	if !strings.HasPrefix(scom, ErasurePrefix) {
		return FormPlain, Statement{}
	}
	rest := scom[len(ErasurePrefix):]
	if len(rest) < signatureTextLen+1 || rest[signatureTextLen] != ':' {
		return FormMalformed, Statement{}
	}
	sigBytes, err := base64.RawURLEncoding.Strict().DecodeString(rest[:signatureTextLen])
	if err != nil || len(sigBytes) != ed25519.SignatureSize {
		return FormMalformed, Statement{}
	}
	rest = rest[signatureTextLen+1:]
	colon := strings.IndexByte(rest, ':')
	if colon < 0 {
		return FormMalformed, Statement{}
	}
	notBefore, ok := parseEpoch(rest[:colon])
	if !ok {
		return FormMalformed, Statement{}
	}
	rest = rest[colon+1:]
	kindText, reason, _ := strings.Cut(rest, " ")
	kind := ErasureKind(kindText)
	if kind != KindErase && kind != KindCancel {
		return FormMalformed, Statement{}
	}
	var st Statement
	copy(st.Signature[:], sigBytes)
	st.NotBefore = notBefore
	st.Kind = kind
	st.Reason = reason
	return FormSigned, st
}

// parseEpoch reads unsigned decimal Unix seconds with no sign and no leading
// zero (except "0"), matching §9.3.1 and zit's erasure.zig.
func parseEpoch(s string) (int64, bool) {
	if len(s) == 0 || len(s) > 19 {
		return 0, false
	}
	if s[0] == '0' && len(s) > 1 {
		return 0, false
	}
	for i := 0; i < len(s); i++ {
		if s[i] < '0' || s[i] > '9' {
			return 0, false
		}
	}
	v, err := strconv.ParseInt(s, 10, 64)
	return v, err == nil && v >= 0
}

func erasureMessage(
	projectCode, uuid string, mtime, notBefore int64, kind ErasureKind, reason string,
) []byte {
	var b strings.Builder
	b.WriteString(erasureDomain)
	b.WriteString(projectCode)
	b.WriteByte('\n')
	b.WriteString(uuid)
	b.WriteByte('\n')
	b.WriteString(strconv.FormatInt(mtime, 10))
	b.WriteByte('\n')
	b.WriteString(strconv.FormatInt(notBefore, 10))
	b.WriteByte('\n')
	b.WriteString(string(kind))
	b.WriteByte('\n')
	b.WriteString(reason)
	return []byte(b.String())
}

// Sign signs a §9.3.1 erasure or cancel statement and returns its SCOM.
func Sign(
	priv ed25519.PrivateKey, projectCode, uuid string, mtime, notBefore int64,
	kind ErasureKind, reason string,
) (string, error) {
	if len(priv) != ed25519.PrivateKeySize {
		return "", fmt.Errorf("%w: private key length %d", ErrBadErasureKey, len(priv))
	}
	if len(projectCode) > MaxProjectCodeLen || !isLowerHash(uuid) {
		return "", fmt.Errorf("%w: project code or uuid", ErrBadErasureInput)
	}
	if mtime < 0 || notBefore < mtime {
		return "", fmt.Errorf("%w: epoch %d / not-before %d", ErrBadErasureInput, mtime, notBefore)
	}
	if kind != KindErase && kind != KindCancel {
		return "", fmt.Errorf("%w: kind %q", ErrBadErasureInput, kind)
	}
	msg := erasureMessage(projectCode, uuid, mtime, notBefore, kind, reason)
	sig := ed25519.Sign(priv, msg)
	sigText := base64.RawURLEncoding.EncodeToString(sig)
	out := ErasurePrefix + sigText + ":" + strconv.FormatInt(notBefore, 10) + ":" + string(kind)
	if reason != "" {
		out += " " + reason
	}
	if len(out) > MaxScomLen {
		return "", fmt.Errorf("%w: scom length %d exceeds %d", ErrBadErasureInput, len(out), MaxScomLen)
	}
	return out, nil
}

// Verify checks whether st verifies against pub for projectCode and row.
func Verify(pub ed25519.PublicKey, projectCode string, row Row, st Statement) bool {
	if len(pub) != ed25519.PublicKeySize || len(projectCode) > MaxProjectCodeLen {
		return false
	}
	if !isLowerHash(row.UUID) || row.MTime < 0 || len(st.Reason) > MaxScomLen {
		return false
	}
	msg := erasureMessage(projectCode, row.UUID, row.MTime, st.NotBefore, st.Kind, st.Reason)
	return ed25519.Verify(pub, msg, st.Signature[:])
}

// Judge classifies and verifies row against an optional pinned public key.
func Judge(pub ed25519.PublicKey, projectCode string, row Row) (Verdict, Statement) {
	form, st := Classify(row.Comment)
	switch form {
	case FormPlain:
		return VerdictPlain, Statement{}
	case FormSigned:
		if len(pub) == ed25519.PublicKeySize && Verify(pub, projectCode, row, st) {
			return VerdictVerified, st
		}
		return VerdictUnverified, Statement{}
	default:
		return VerdictUnverified, Statement{}
	}
}

// ParsePublicKey decodes a 64-lowercase-hex Ed25519 public key (§9.3.1).
func ParsePublicKey(text string) (ed25519.PublicKey, error) {
	if len(text) != 2*ed25519.PublicKeySize {
		return nil, fmt.Errorf("%w: length %d", ErrBadErasureKey, len(text))
	}
	for i := 0; i < len(text); i++ {
		c := text[i]
		if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')) {
			return nil, fmt.Errorf("%w: non-lowercase-hex", ErrBadErasureKey)
		}
	}
	raw, err := hex.DecodeString(text)
	if err != nil {
		return nil, fmt.Errorf("%w: %v", ErrBadErasureKey, err)
	}
	return ed25519.PublicKey(raw), nil
}

// FormatPublicKey encodes an Ed25519 public key as 64 lowercase hex digits.
func FormatPublicKey(pub ed25519.PublicKey) string {
	if len(pub) != ed25519.PublicKeySize {
		panic("shun.FormatPublicKey: bad public key length")
	}
	return hex.EncodeToString(pub)
}

func isLowerHash(s string) bool {
	if !hash.IsValidHash(s) {
		return false
	}
	for i := 0; i < len(s); i++ {
		if s[i] >= 'A' && s[i] <= 'F' {
			return false
		}
	}
	return true
}