Migrating hosting from Codeberg to git.kmalloc.org. Renames the module path in go.mod, every internal import, and the OCI image source label in the Dockerfile. Build and full test suite verified green after the rename.
330 lines
11 KiB
Go
330 lines
11 KiB
Go
package storage
|
|
|
|
import (
|
|
"context"
|
|
"crypto/ed25519"
|
|
"database/sql"
|
|
"encoding/base64"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/uptrace/bun"
|
|
|
|
"git.kmalloc.org/squid/sonda/internal/federation"
|
|
)
|
|
|
|
// Keys are stored as base64url text; an empty string means "no key yet".
|
|
var keyEnc = base64.RawURLEncoding
|
|
|
|
type federationSettingsRow struct {
|
|
bun.BaseModel `bun:"table:federation_settings"`
|
|
|
|
ID int `bun:"id,pk"`
|
|
Enabled bool `bun:"enabled,notnull"`
|
|
Name string `bun:"name,notnull"`
|
|
Address string `bun:"address,notnull"`
|
|
PublicKey string `bun:"public_key,notnull"`
|
|
PrivateKey string `bun:"private_key,notnull"`
|
|
UpdatedAt int64 `bun:"updated_at,notnull"`
|
|
|
|
MaxStreams int `bun:"max_streams,notnull"`
|
|
MaxKiBPerSec int `bun:"max_kib_per_sec,notnull"`
|
|
}
|
|
|
|
type federationRequestRow struct {
|
|
bun.BaseModel `bun:"table:federation_requests"`
|
|
|
|
ID int64 `bun:"id,pk,autoincrement"`
|
|
FriendID int64 `bun:"friend_id,notnull"`
|
|
At int64 `bun:"at,notnull"`
|
|
Route string `bun:"route,notnull"`
|
|
Status int `bun:"status,notnull"`
|
|
Bytes int64 `bun:"bytes,notnull"`
|
|
}
|
|
|
|
type federationInviteRow struct {
|
|
bun.BaseModel `bun:"table:federation_invites"`
|
|
|
|
ID int64 `bun:"id,pk,autoincrement"`
|
|
CodeHash string `bun:"code_hash,notnull"`
|
|
CreatedAt int64 `bun:"created_at,notnull"`
|
|
ExpiresAt int64 `bun:"expires_at,notnull"`
|
|
UsedAt *int64 `bun:"used_at"`
|
|
}
|
|
|
|
type federationFriendRow struct {
|
|
bun.BaseModel `bun:"table:federation_friends"`
|
|
|
|
ID int64 `bun:"id,pk,autoincrement"`
|
|
Name string `bun:"name,notnull"`
|
|
Address string `bun:"address,notnull"`
|
|
PublicKey string `bun:"public_key,notnull"`
|
|
State string `bun:"state,notnull"`
|
|
CreatedAt int64 `bun:"created_at,notnull"`
|
|
ApprovedAt *int64 `bun:"approved_at"`
|
|
}
|
|
|
|
func (r federationFriendRow) toFriend() (federation.Friend, error) {
|
|
key, err := keyEnc.DecodeString(r.PublicKey)
|
|
if err != nil || len(key) != ed25519.PublicKeySize {
|
|
return federation.Friend{}, fmt.Errorf("friend %d has a damaged key", r.ID)
|
|
}
|
|
f := federation.Friend{
|
|
ID: r.ID, Name: r.Name, Address: r.Address, PublicKey: key,
|
|
State: federation.State(r.State), CreatedAt: time.Unix(r.CreatedAt, 0),
|
|
}
|
|
if r.ApprovedAt != nil {
|
|
f.ApprovedAt = time.Unix(*r.ApprovedAt, 0)
|
|
}
|
|
return f, nil
|
|
}
|
|
|
|
// FederationRepo stores the keys, invites and friends of federation. It implements federation.Store.
|
|
type FederationRepo struct{ db *bun.DB }
|
|
|
|
// NewFederationRepo builds a FederationRepo.
|
|
func NewFederationRepo(db *bun.DB) *FederationRepo { return &FederationRepo{db: db} }
|
|
|
|
// Settings returns the stored settings, with found=false before the first save.
|
|
func (r *FederationRepo) Settings(ctx context.Context) (federation.Settings, bool, error) {
|
|
var row federationSettingsRow
|
|
err := r.db.NewSelect().Model(&row).Where("id = 1").Limit(1).Scan(ctx)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return federation.Settings{}, false, nil
|
|
}
|
|
if err != nil {
|
|
return federation.Settings{}, false, fmt.Errorf("select federation settings: %w", err)
|
|
}
|
|
s := federation.Settings{
|
|
Enabled: row.Enabled, Name: row.Name, Address: row.Address, UpdatedAt: time.Unix(row.UpdatedAt, 0),
|
|
MaxStreams: row.MaxStreams, MaxKiBPerSec: row.MaxKiBPerSec,
|
|
}
|
|
if row.PublicKey != "" || row.PrivateKey != "" {
|
|
pub, perr := keyEnc.DecodeString(row.PublicKey)
|
|
priv, serr := keyEnc.DecodeString(row.PrivateKey)
|
|
if perr != nil || serr != nil || len(pub) != ed25519.PublicKeySize || len(priv) != ed25519.PrivateKeySize {
|
|
return federation.Settings{}, false, errors.New("the federation key pair is damaged")
|
|
}
|
|
s.PublicKey, s.PrivateKey = pub, priv
|
|
}
|
|
return s, true, nil
|
|
}
|
|
|
|
// SaveSettings inserts or replaces the one row of settings.
|
|
func (r *FederationRepo) SaveSettings(ctx context.Context, s federation.Settings) error {
|
|
row := &federationSettingsRow{
|
|
ID: 1, Enabled: s.Enabled, Name: s.Name, Address: s.Address, UpdatedAt: s.UpdatedAt.Unix(),
|
|
MaxStreams: s.MaxStreams, MaxKiBPerSec: s.MaxKiBPerSec,
|
|
}
|
|
if s.PublicKey != nil {
|
|
row.PublicKey = keyEnc.EncodeToString(s.PublicKey)
|
|
}
|
|
if s.PrivateKey != nil {
|
|
row.PrivateKey = keyEnc.EncodeToString(s.PrivateKey)
|
|
}
|
|
_, err := r.db.NewInsert().Model(row).
|
|
On("CONFLICT (id) DO UPDATE").
|
|
Set("enabled = EXCLUDED.enabled").
|
|
Set("name = EXCLUDED.name").
|
|
Set("address = EXCLUDED.address").
|
|
Set("public_key = EXCLUDED.public_key").
|
|
Set("private_key = EXCLUDED.private_key").
|
|
Set("max_streams = EXCLUDED.max_streams").
|
|
Set("max_kib_per_sec = EXCLUDED.max_kib_per_sec").
|
|
Set("updated_at = EXCLUDED.updated_at").
|
|
Exec(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("save federation settings: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// AddInvite stores the hash of a new invite code.
|
|
func (r *FederationRepo) AddInvite(ctx context.Context, codeHash string, created, expires time.Time) error {
|
|
row := &federationInviteRow{CodeHash: codeHash, CreatedAt: created.Unix(), ExpiresAt: expires.Unix()}
|
|
if _, err := r.db.NewInsert().Model(row).Exec(ctx); err != nil {
|
|
return fmt.Errorf("insert federation invite: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// UseInvite marks an unused, unexpired invite as used. One statement does the check and the marking, so two
|
|
// requests with the same code cannot both succeed.
|
|
func (r *FederationRepo) UseInvite(ctx context.Context, codeHash string, now time.Time) (bool, error) {
|
|
res, err := r.db.NewUpdate().Model((*federationInviteRow)(nil)).
|
|
Set("used_at = ?", now.Unix()).
|
|
Where("code_hash = ?", codeHash).
|
|
Where("used_at IS NULL").
|
|
Where("expires_at > ?", now.Unix()).
|
|
Exec(ctx)
|
|
if err != nil {
|
|
return false, fmt.Errorf("use federation invite: %w", err)
|
|
}
|
|
n, err := res.RowsAffected()
|
|
if err != nil {
|
|
return false, fmt.Errorf("use federation invite: %w", err)
|
|
}
|
|
return n == 1, nil
|
|
}
|
|
|
|
// Friends lists every friend, oldest first.
|
|
func (r *FederationRepo) Friends(ctx context.Context) ([]federation.Friend, error) {
|
|
var rows []federationFriendRow
|
|
if err := r.db.NewSelect().Model(&rows).OrderExpr("created_at, id").Scan(ctx); err != nil {
|
|
return nil, fmt.Errorf("list federation friends: %w", err)
|
|
}
|
|
out := make([]federation.Friend, len(rows))
|
|
for i, row := range rows {
|
|
f, err := row.toFriend()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out[i] = f
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// Friend returns one friend.
|
|
func (r *FederationRepo) Friend(ctx context.Context, id int64) (federation.Friend, error) {
|
|
var row federationFriendRow
|
|
err := r.db.NewSelect().Model(&row).Where("id = ?", id).Limit(1).Scan(ctx)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return federation.Friend{}, federation.ErrFriendMissing
|
|
}
|
|
if err != nil {
|
|
return federation.Friend{}, fmt.Errorf("select federation friend: %w", err)
|
|
}
|
|
return row.toFriend()
|
|
}
|
|
|
|
// FriendByKey finds the friend that has a public key.
|
|
func (r *FederationRepo) FriendByKey(ctx context.Context, key ed25519.PublicKey) (federation.Friend, bool, error) {
|
|
var row federationFriendRow
|
|
err := r.db.NewSelect().Model(&row).Where("public_key = ?", keyEnc.EncodeToString(key)).Limit(1).Scan(ctx)
|
|
if errors.Is(err, sql.ErrNoRows) {
|
|
return federation.Friend{}, false, nil
|
|
}
|
|
if err != nil {
|
|
return federation.Friend{}, false, fmt.Errorf("select federation friend by key: %w", err)
|
|
}
|
|
f, err := row.toFriend()
|
|
return f, err == nil, err
|
|
}
|
|
|
|
// AddFriend stores a friend; a key that is already a friend's is ErrAlreadyFriend.
|
|
func (r *FederationRepo) AddFriend(ctx context.Context, f federation.Friend) (federation.Friend, error) {
|
|
row := &federationFriendRow{
|
|
Name: f.Name, Address: f.Address, PublicKey: keyEnc.EncodeToString(f.PublicKey),
|
|
State: string(f.State), CreatedAt: f.CreatedAt.Unix(),
|
|
}
|
|
if !f.ApprovedAt.IsZero() {
|
|
at := f.ApprovedAt.Unix()
|
|
row.ApprovedAt = &at
|
|
}
|
|
if _, err := r.db.NewInsert().Model(row).Exec(ctx); err != nil {
|
|
if isUniqueViolation(err) {
|
|
return federation.Friend{}, federation.ErrAlreadyFriend
|
|
}
|
|
return federation.Friend{}, fmt.Errorf("insert federation friend: %w", err)
|
|
}
|
|
f.ID = row.ID
|
|
return f, nil
|
|
}
|
|
|
|
// Approve turns an incoming friend into an active one.
|
|
func (r *FederationRepo) Approve(ctx context.Context, id int64, now time.Time) error {
|
|
res, err := r.db.NewUpdate().Model((*federationFriendRow)(nil)).
|
|
Set("state = ?", string(federation.Active)).
|
|
Set("approved_at = ?", now.Unix()).
|
|
Where("id = ?", id).
|
|
Where("state = ?", string(federation.Incoming)).
|
|
Exec(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("approve federation friend: %w", err)
|
|
}
|
|
if n, _ := res.RowsAffected(); n == 1 {
|
|
return nil
|
|
}
|
|
if _, err := r.Friend(ctx, id); err != nil {
|
|
return err
|
|
}
|
|
return federation.ErrWrongState
|
|
}
|
|
|
|
// DeleteFriend removes a friend: declining a request and revoking a friendship are the same thing.
|
|
func (r *FederationRepo) DeleteFriend(ctx context.Context, id int64) error {
|
|
res, err := r.db.NewDelete().Model((*federationFriendRow)(nil)).Where("id = ?", id).Exec(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("delete federation friend: %w", err)
|
|
}
|
|
if n, _ := res.RowsAffected(); n == 0 {
|
|
return federation.ErrFriendMissing
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Activate turns an outgoing friend into an active one.
|
|
func (r *FederationRepo) Activate(ctx context.Context, id int64, now time.Time) error {
|
|
res, err := r.db.NewUpdate().Model((*federationFriendRow)(nil)).
|
|
Set("state = ?", string(federation.Active)).
|
|
Set("approved_at = ?", now.Unix()).
|
|
Where("id = ?", id).
|
|
Where("state = ?", string(federation.Outgoing)).
|
|
Exec(ctx)
|
|
if err != nil {
|
|
return fmt.Errorf("activate federation friend: %w", err)
|
|
}
|
|
if n, _ := res.RowsAffected(); n == 1 {
|
|
return nil
|
|
}
|
|
if _, err := r.Friend(ctx, id); err != nil {
|
|
return err
|
|
}
|
|
return federation.ErrWrongState
|
|
}
|
|
|
|
// LogRequest keeps one request a friend made.
|
|
func (r *FederationRepo) LogRequest(ctx context.Context, q federation.FriendRequest) error {
|
|
row := &federationRequestRow{FriendID: q.FriendID, At: q.At.Unix(), Route: q.Route, Status: q.Status, Bytes: q.Bytes}
|
|
if _, err := r.db.NewInsert().Model(row).Exec(ctx); err != nil {
|
|
return fmt.Errorf("log federation request: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Requests lists the last requests, newest first, with the name of the friend.
|
|
func (r *FederationRepo) Requests(ctx context.Context, limit int) ([]federation.FriendRequest, error) {
|
|
var rows []struct {
|
|
At int64 `bun:"at"`
|
|
FriendID int64 `bun:"friend_id"`
|
|
Name string `bun:"name"`
|
|
Route string `bun:"route"`
|
|
Status int `bun:"status"`
|
|
Bytes int64 `bun:"bytes"`
|
|
}
|
|
err := r.db.NewSelect().
|
|
TableExpr("federation_requests AS q").
|
|
ColumnExpr("q.at AS at, q.friend_id AS friend_id, f.name AS name, q.route AS route, q.status AS status, q.bytes AS bytes").
|
|
Join("JOIN federation_friends AS f ON f.id = q.friend_id").
|
|
OrderExpr("q.at DESC, q.id DESC").Limit(int64(limit)).
|
|
Scan(ctx, &rows)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list federation requests: %w", err)
|
|
}
|
|
out := make([]federation.FriendRequest, len(rows))
|
|
for i, row := range rows {
|
|
out[i] = federation.FriendRequest{
|
|
At: time.Unix(row.At, 0), FriendID: row.FriendID, FriendName: row.Name, Route: row.Route, Status: row.Status, Bytes: row.Bytes,
|
|
}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// PruneRequests drops the requests older than before.
|
|
func (r *FederationRepo) PruneRequests(ctx context.Context, before time.Time) error {
|
|
if _, err := r.db.NewDelete().Model((*federationRequestRow)(nil)).Where("at < ?", before.Unix()).Exec(ctx); err != nil {
|
|
return fmt.Errorf("prune federation requests: %w", err)
|
|
}
|
|
return nil
|
|
}
|