绑定设备身份并分发一次性 MLS 密钥包
This commit is contained in:
1 parent
f30f01b699
commit
0b17dd07c5
11 files changed
+286
-11
No files matched your search
@@ -0,0 +1,13 @@
|
||||
CREATE TABLE device_key_packages (
|
||||
device_id uuid NOT NULL REFERENCES devices(id) ON DELETE CASCADE,
|
||||
package_hash bytea NOT NULL CHECK (octet_length(package_hash)=32),
|
||||
package bytea NOT NULL CHECK (octet_length(package) BETWEEN 32 AND 8192),
|
||||
signature bytea NOT NULL CHECK (octet_length(signature)=64),
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
claimed_at timestamptz,
|
||||
PRIMARY KEY (device_id, package_hash)
|
||||
);
|
||||
|
||||
CREATE INDEX device_key_packages_available ON device_key_packages(device_id, created_at)
|
||||
WHERE claimed_at IS NULL;
|
||||
CREATE INDEX device_key_packages_expiry ON device_key_packages(created_at);
|
||||
@@ -16,6 +16,9 @@ var contactsMigration string
|
||||
//go:embed 003_delivery.sql
|
||||
var deliveryMigration string
|
||||
|
||||
//go:embed 004_key_packages.sql
|
||||
var keyPackagesMigration string
|
||||
|
||||
func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
tx, err := pool.Begin(ctx)
|
||||
if err != nil {
|
||||
@@ -28,7 +31,7 @@ func Migrate(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
if _, err = tx.Exec(ctx, "CREATE TABLE IF NOT EXISTS schema_migrations (version integer PRIMARY KEY)"); err != nil {
|
||||
return err
|
||||
}
|
||||
for index, migration := range []string{identityMigration, contactsMigration, deliveryMigration} {
|
||||
for index, migration := range []string{identityMigration, contactsMigration, deliveryMigration, keyPackagesMigration} {
|
||||
version := index + 1
|
||||
var applied bool
|
||||
if err = tx.QueryRow(ctx, "SELECT EXISTS (SELECT 1 FROM schema_migrations WHERE version=$1)", version).Scan(&applied); err != nil {
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
package delivery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
type DirectoryDevice struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
PublicKey []byte `json:"publicKey"`
|
||||
}
|
||||
|
||||
type KeyPackage struct {
|
||||
Package []byte `json:"package"`
|
||||
Signature []byte `json:"signature"`
|
||||
}
|
||||
|
||||
var ErrSignature = errors.New("invalid key package device signature")
|
||||
var ErrPackageLimit = errors.New("device key package limit reached")
|
||||
|
||||
const acceptedContact = `
|
||||
EXISTS (SELECT 1 FROM contact_relationships
|
||||
WHERE first_user=LEAST($1::uuid,$2::uuid) AND second_user=GREATEST($1::uuid,$2::uuid)
|
||||
AND status='accepted')
|
||||
`
|
||||
|
||||
func (s *Store) Directory(ctx context.Context, owner, contact string) ([]DirectoryDevice, error) {
|
||||
rows, err := s.db.Query(ctx, `
|
||||
SELECT id,name,public_key FROM devices
|
||||
WHERE user_id=$2 AND revoked_at IS NULL AND `+acceptedContact+`
|
||||
ORDER BY id LIMIT 128`, owner, contact)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
result := make([]DirectoryDevice, 0)
|
||||
for rows.Next() {
|
||||
var device DirectoryDevice
|
||||
if err := rows.Scan(&device.ID, &device.Name, &device.PublicKey); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, device)
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) PublishPackage(ctx context.Context, owner, device string, item KeyPackage) error {
|
||||
tx, err := s.db.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
var public []byte
|
||||
err = tx.QueryRow(ctx, "SELECT public_key FROM devices WHERE id=$1 AND user_id=$2 AND revoked_at IS NULL FOR UPDATE", device, owner).Scan(&public)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return ErrUnavailable
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
binding := append([]byte("XHChat MLS KeyPackage v1\n"+owner+"\n"+device+"\n"), item.Package...)
|
||||
if !ed25519.Verify(public, binding, item.Signature) {
|
||||
return ErrSignature
|
||||
}
|
||||
hash := sha256.Sum256(item.Package)
|
||||
var known bool
|
||||
var available int
|
||||
err = tx.QueryRow(ctx, `
|
||||
SELECT count(*) FILTER (WHERE claimed_at IS NULL AND created_at > now() - interval '24 hours'),
|
||||
COALESCE(bool_or(package_hash=$2),false)
|
||||
FROM device_key_packages WHERE device_id=$1
|
||||
`, device, hash[:]).Scan(&available, &known)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if known {
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
if available >= 32 {
|
||||
return ErrPackageLimit
|
||||
}
|
||||
if _, err := tx.Exec(ctx, "INSERT INTO device_key_packages(device_id,package_hash,package,signature) VALUES($1,$2,$3,$4)",
|
||||
device, hash[:], item.Package, item.Signature); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (s *Store) ClaimPackage(ctx context.Context, owner, requester, contact, device string) (KeyPackage, error) {
|
||||
var item KeyPackage
|
||||
tx, err := s.db.Begin(ctx)
|
||||
if err != nil {
|
||||
return item, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
if _, err := tx.Exec(ctx, "SELECT id FROM users WHERE id IN ($1,$2) ORDER BY id FOR UPDATE", owner, contact); err != nil {
|
||||
return item, err
|
||||
}
|
||||
var friends bool
|
||||
err = tx.QueryRow(ctx, "SELECT "+acceptedContact, owner, contact).Scan(&friends)
|
||||
if err != nil {
|
||||
return item, err
|
||||
}
|
||||
if !friends {
|
||||
return item, ErrUnavailable
|
||||
}
|
||||
var active int
|
||||
err = tx.QueryRow(ctx, `
|
||||
SELECT count(*) FROM (
|
||||
SELECT id FROM devices WHERE ((id=$1 AND user_id=$2) OR (id=$3 AND user_id=$4))
|
||||
AND revoked_at IS NULL ORDER BY id FOR UPDATE
|
||||
) AS active_devices
|
||||
`, requester, owner, device, contact).Scan(&active)
|
||||
if err != nil {
|
||||
return item, err
|
||||
}
|
||||
if active != 2 {
|
||||
return item, ErrUnavailable
|
||||
}
|
||||
err = tx.QueryRow(ctx, `
|
||||
UPDATE device_key_packages SET claimed_at=now()
|
||||
WHERE (device_id, package_hash)=(
|
||||
SELECT device_id, package_hash FROM device_key_packages
|
||||
WHERE device_id=$1 AND claimed_at IS NULL AND created_at > now() - interval '24 hours'
|
||||
ORDER BY created_at, package_hash LIMIT 1
|
||||
)
|
||||
RETURNING package, signature
|
||||
`, device).Scan(&item.Package, &item.Signature)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return item, ErrUnavailable
|
||||
}
|
||||
if err != nil {
|
||||
return item, err
|
||||
}
|
||||
return item, tx.Commit(ctx)
|
||||
}
|
||||
@@ -67,11 +67,7 @@ func (s *Store) Send(ctx context.Context, sender, recipient, message string, cip
|
||||
// This direct-message endpoint only connects accepted contacts.
|
||||
// A separate authorization flow is needed for same-account device transfers.
|
||||
var friends bool
|
||||
err = tx.QueryRow(ctx, `
|
||||
SELECT EXISTS (SELECT 1 FROM contact_relationships
|
||||
WHERE first_user=LEAST($1::uuid,$2::uuid) AND second_user=GREATEST($1::uuid,$2::uuid)
|
||||
AND status='accepted')
|
||||
`, senderUser, recipientUser).Scan(&friends)
|
||||
err = tx.QueryRow(ctx, "SELECT "+acceptedContact, senderUser, recipientUser).Scan(&friends)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
@@ -126,6 +122,10 @@ func (s *Store) Inbox(ctx context.Context, recipient string, after int64) ([]Env
|
||||
}
|
||||
|
||||
func (s *Store) Cleanup(ctx context.Context, retention time.Duration) error {
|
||||
_, err := s.db.Exec(ctx, "DELETE FROM device_envelopes WHERE created_at < $1", time.Now().Add(-retention))
|
||||
if _, err := s.db.Exec(ctx, "DELETE FROM device_envelopes WHERE created_at < $1", time.Now().Add(-retention)); err != nil {
|
||||
return err
|
||||
}
|
||||
// Keep issued package hashes past the validity window of an individual upload.
|
||||
_, err := s.db.Exec(ctx, "DELETE FROM device_key_packages WHERE created_at < now() - interval '90 days'")
|
||||
return err
|
||||
}
|
||||
@@ -50,6 +50,9 @@ func New(accounts *account.Store, contactStore *contacts.Store, envelopeStore *d
|
||||
mux.HandleFunc("POST /api/v1/contacts/{id}", a.authorized(a.changeContact))
|
||||
mux.HandleFunc("GET /api/v1/inbox", a.authorized(a.inbox))
|
||||
mux.HandleFunc("POST /api/v1/inbox", a.authorized(a.sendEnvelope))
|
||||
mux.HandleFunc("GET /api/v1/contacts/{id}/devices", a.authorized(a.contactDevices))
|
||||
mux.HandleFunc("POST /api/v1/contacts/{id}/devices/{device}/claim", a.authorized(a.claimPackage))
|
||||
mux.HandleFunc("POST /api/v1/key-packages", a.authorized(a.publishPackage))
|
||||
return a.boundary(mux)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"xhchat/server/internal/account"
|
||||
"xhchat/server/internal/delivery"
|
||||
)
|
||||
|
||||
func (a *API) contactDevices(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
|
||||
id := strings.ToLower(r.PathValue("id"))
|
||||
if !uuidPattern.MatchString(id) {
|
||||
problem(w, 404, "contact_not_found", "找不到该联系人")
|
||||
return
|
||||
}
|
||||
result, err := a.delivery.Directory(r.Context(), identity.User.ID, id)
|
||||
if err != nil {
|
||||
unavailable(w, err)
|
||||
return
|
||||
}
|
||||
respond(w, 200, result)
|
||||
}
|
||||
|
||||
func (a *API) publishPackage(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
|
||||
var item delivery.KeyPackage
|
||||
if !parseLimit(w, r, &item, 12<<10) {
|
||||
return
|
||||
}
|
||||
wire := item.Package
|
||||
if len(wire) < 32 || len(wire) > 8192 || wire[0] != 0 || wire[1] != 1 || wire[2] != 0 || wire[3] != 5 || len(item.Signature) != 64 {
|
||||
problem(w, 400, "invalid_package", "密钥包格式无效")
|
||||
return
|
||||
}
|
||||
if !a.limit(w, r, "package-publish:"+identity.Device.ID, 48) {
|
||||
return
|
||||
}
|
||||
err := a.delivery.PublishPackage(r.Context(), identity.User.ID, identity.Device.ID, item)
|
||||
switch {
|
||||
case errors.Is(err, delivery.ErrSignature):
|
||||
problem(w, 400, "invalid_package_signature", "密钥包设备签名无效")
|
||||
case errors.Is(err, delivery.ErrPackageLimit):
|
||||
problem(w, 409, "package_limit", "当前已有足够的未使用密钥包")
|
||||
case errors.Is(err, delivery.ErrUnavailable):
|
||||
problem(w, 404, "device_not_found", "设备不可用")
|
||||
case err != nil:
|
||||
unavailable(w, err)
|
||||
default:
|
||||
w.WriteHeader(204)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *API) claimPackage(w http.ResponseWriter, r *http.Request, _ string, identity account.Identity) {
|
||||
id, device := strings.ToLower(r.PathValue("id")), strings.ToLower(r.PathValue("device"))
|
||||
if !uuidPattern.MatchString(id) || !uuidPattern.MatchString(device) {
|
||||
problem(w, 404, "package_unavailable", "密钥包不可用")
|
||||
return
|
||||
}
|
||||
if !a.limit(w, r, "package-claim:"+identity.Device.ID, 24) {
|
||||
return
|
||||
}
|
||||
item, err := a.delivery.ClaimPackage(r.Context(), identity.User.ID, identity.Device.ID, id, device)
|
||||
if errors.Is(err, delivery.ErrUnavailable) {
|
||||
problem(w, 404, "package_unavailable", "密钥包不可用")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
unavailable(w, err)
|
||||
return
|
||||
}
|
||||
respond(w, 200, item)
|
||||
}
|
||||
Reference in new issue
Block a user