214 lines
9.0 KiB
Go
214 lines
9.0 KiB
Go
package store
|
|
|
|
import (
|
|
"context"
|
|
"crypto/ed25519"
|
|
"crypto/sha256"
|
|
"database/sql"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
type CampusManifestPayload struct {
|
|
SchemaVersion int `json:"schema_version"`
|
|
Revision int64 `json:"revision"`
|
|
Campus Campus `json:"campus"`
|
|
Domains []Domain `json:"domains"`
|
|
DomainEntries map[string]DomainEntrySettings `json:"domain_entries,omitempty"`
|
|
}
|
|
|
|
type SignedCampusManifest struct {
|
|
CampusManifestPayload
|
|
ControllerPublicKey string `json:"controller_public_key"`
|
|
ControllerFingerprint string `json:"controller_fingerprint"`
|
|
Signature string `json:"signature"`
|
|
}
|
|
|
|
func (s *Store) federationSigningKey() ed25519.PrivateKey {
|
|
seed := s.authKey
|
|
if len(seed) != ed25519.SeedSize {
|
|
sum := sha256.Sum256(seed)
|
|
seed = sum[:]
|
|
}
|
|
return ed25519.NewKeyFromSeed(seed)
|
|
}
|
|
|
|
func (s *Store) BuildSignedCampusManifest(campus Campus, domains []Domain) (_ SignedCampusManifest, resultErr error) {
|
|
defer func() { resultErr = s.sqlError("BuildSignedCampusManifest", resultErr) }()
|
|
if s.ReadOnly {
|
|
return SignedCampusManifest{}, ErrReadOnly
|
|
}
|
|
if campus.AuthorityMode != "controller" || campus.UUID == "" {
|
|
return SignedCampusManifest{}, namespaceValidationError("Campus is not a controller")
|
|
}
|
|
filtered := make([]Domain, 0, len(domains))
|
|
seen := make(map[string]bool, len(domains))
|
|
for _, domain := range domains {
|
|
if domain.CampusUUID == campus.UUID {
|
|
if domain.UUID == "" || seen[domain.UUID] {
|
|
return SignedCampusManifest{}, namespaceValidationError("duplicate or missing Domain identity in Campus manifest")
|
|
}
|
|
seen[domain.UUID] = true
|
|
filtered = append(filtered, domain)
|
|
}
|
|
}
|
|
sort.Slice(filtered, func(i, j int) bool { return filtered[i].UUID < filtered[j].UUID })
|
|
entries, err := s.ListDomainEntrySettings()
|
|
if err != nil {
|
|
return SignedCampusManifest{}, err
|
|
}
|
|
for id := range entries {
|
|
if !seen[id] {
|
|
delete(entries, id)
|
|
}
|
|
}
|
|
content, err := json.Marshal(struct {
|
|
Campus Campus `json:"campus"`
|
|
Domains []Domain `json:"domains"`
|
|
Entries map[string]DomainEntrySettings `json:"domain_entries,omitempty"`
|
|
}{campus, filtered, entries})
|
|
if err != nil {
|
|
return SignedCampusManifest{}, err
|
|
}
|
|
hash := sha256.Sum256(content)
|
|
hashText := hex.EncodeToString(hash[:])
|
|
var revision int64
|
|
// Allocate against the current row inside one write statement. A separate
|
|
// SELECT/UPSERT can sign different payloads with the same revision.
|
|
err = s.DB.QueryRow(`INSERT INTO federation_manifest_versions(campus_uuid,revision,manifest_hash,updated_at)
|
|
VALUES(`+s.sqlParam(1)+`,1,`+s.sqlParam(2)+`,`+s.sqlParam(3)+`) ON CONFLICT(campus_uuid) DO UPDATE SET
|
|
revision=CASE WHEN federation_manifest_versions.manifest_hash=excluded.manifest_hash
|
|
THEN federation_manifest_versions.revision ELSE federation_manifest_versions.revision+1 END,
|
|
manifest_hash=excluded.manifest_hash,
|
|
updated_at=CASE WHEN federation_manifest_versions.manifest_hash=excluded.manifest_hash
|
|
THEN federation_manifest_versions.updated_at ELSE excluded.updated_at END
|
|
WHERE federation_manifest_versions.revision<9223372036854775807 OR federation_manifest_versions.manifest_hash=excluded.manifest_hash
|
|
RETURNING revision`, campus.UUID, hashText, time.Now().Unix()).Scan(&revision)
|
|
if err != nil {
|
|
return SignedCampusManifest{}, err
|
|
}
|
|
payload := CampusManifestPayload{SchemaVersion: 1, Revision: revision, Campus: campus, Domains: filtered}
|
|
if len(entries) > 0 {
|
|
payload.SchemaVersion = 2
|
|
payload.DomainEntries = entries
|
|
}
|
|
encoded, err := json.Marshal(payload)
|
|
if err != nil {
|
|
return SignedCampusManifest{}, err
|
|
}
|
|
privateKey := s.federationSigningKey()
|
|
publicKey := privateKey.Public().(ed25519.PublicKey)
|
|
fingerprint := sha256.Sum256(publicKey)
|
|
return SignedCampusManifest{
|
|
CampusManifestPayload: payload,
|
|
ControllerPublicKey: base64.RawStdEncoding.EncodeToString(publicKey),
|
|
ControllerFingerprint: "sha256:" + hex.EncodeToString(fingerprint[:]),
|
|
Signature: base64.RawStdEncoding.EncodeToString(ed25519.Sign(privateKey, encoded)),
|
|
}, nil
|
|
}
|
|
|
|
func verifyCampusManifest(manifest SignedCampusManifest) ([]byte, error) {
|
|
if (manifest.SchemaVersion != 1 && manifest.SchemaVersion != 2) || manifest.Revision < 1 || manifest.Campus.UUID == "" || (manifest.SchemaVersion == 1 && len(manifest.DomainEntries) > 0) {
|
|
return nil, namespaceValidationError("invalid Campus manifest metadata")
|
|
}
|
|
publicKey, err := base64.RawStdEncoding.DecodeString(manifest.ControllerPublicKey)
|
|
if err != nil || len(publicKey) != ed25519.PublicKeySize {
|
|
return nil, namespaceValidationError("invalid controller public key")
|
|
}
|
|
fingerprint := sha256.Sum256(publicKey)
|
|
if manifest.ControllerFingerprint != "sha256:"+hex.EncodeToString(fingerprint[:]) {
|
|
return nil, namespaceValidationError("controller fingerprint does not match public key")
|
|
}
|
|
signature, err := base64.RawStdEncoding.DecodeString(manifest.Signature)
|
|
if err != nil {
|
|
return nil, namespaceValidationError("invalid Campus manifest signature")
|
|
}
|
|
payload, err := json.Marshal(manifest.CampusManifestPayload)
|
|
if err != nil || !ed25519.Verify(ed25519.PublicKey(publicKey), payload, signature) {
|
|
return nil, namespaceValidationError("Campus manifest signature verification failed")
|
|
}
|
|
seen := make(map[string]bool, len(manifest.Domains))
|
|
for _, domain := range manifest.Domains {
|
|
if domain.UUID == "" || seen[domain.UUID] || domain.CampusUUID != manifest.Campus.UUID || strings.ContainsAny(domain.Domain, "/:\\") || strings.ContainsAny(domain.InstanceFQDN, "/:\\") {
|
|
return nil, namespaceValidationError("Campus manifest contains an invalid Domain hostname")
|
|
}
|
|
seen[domain.UUID] = true
|
|
}
|
|
for id, e := range manifest.DomainEntries {
|
|
if !seen[id] || !e.valid() {
|
|
return nil, namespaceValidationError("invalid Domain entry settings")
|
|
}
|
|
}
|
|
return payload, nil
|
|
}
|
|
|
|
func (s *Store) ApplySignedManagedCampusManifest(manifest SignedCampusManifest, expectedCampusUUID, localInstanceFQDN, transport string) (resultErr error) {
|
|
defer func() { resultErr = s.sqlError("ApplySignedManagedCampusManifest", resultErr) }()
|
|
if s.ReadOnly {
|
|
return ErrReadOnly
|
|
}
|
|
payload, err := verifyCampusManifest(manifest)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if expectedCampusUUID != "" && manifest.Campus.UUID != expectedCampusUUID {
|
|
return namespaceValidationError("Campus controller identity changed")
|
|
}
|
|
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
|
defer cancel()
|
|
tx, err := s.DB.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback()
|
|
if err = s.lockFederationWrite(ctx, tx); err != nil {
|
|
return err
|
|
}
|
|
// Reserve SQLite's writer before checking the pin/checkpoint, even when the
|
|
// Campus has no state yet. Concurrent first pins and duplicate deliveries
|
|
// then serialize without a stale read-to-write upgrade or unchecked retry.
|
|
if _, err := tx.Exec(`UPDATE federation_manifest_state SET applied_at=applied_at WHERE campus_uuid=`+s.sqlParam(1)+``, manifest.Campus.UUID); err != nil {
|
|
return err
|
|
}
|
|
var pinnedFingerprint, previousPayload string
|
|
var appliedRevision int64
|
|
err = tx.QueryRow(`SELECT controller_fingerprint,applied_revision,manifest_json FROM federation_manifest_state WHERE campus_uuid=`+s.sqlParam(1)+``, manifest.Campus.UUID).Scan(&pinnedFingerprint, &appliedRevision, &previousPayload)
|
|
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
|
return err
|
|
}
|
|
if err == nil {
|
|
if pinnedFingerprint != manifest.ControllerFingerprint {
|
|
return namespaceValidationError("Campus controller signing identity changed")
|
|
}
|
|
if manifest.Revision < appliedRevision {
|
|
return namespaceValidationError("Campus manifest replay rejected")
|
|
}
|
|
if manifest.Revision == appliedRevision {
|
|
if previousPayload == string(payload) {
|
|
return nil
|
|
}
|
|
return namespaceValidationError("Campus manifest revision was reused with different content")
|
|
}
|
|
}
|
|
if err := s.applyManagedCampusSnapshotTx(tx, manifest.Campus, manifest.Domains, localInstanceFQDN, transport); err != nil {
|
|
return err
|
|
}
|
|
for _, d := range manifest.Domains {
|
|
if e, ok := manifest.DomainEntries[d.UUID]; ok {
|
|
if err := s.saveDomainEntryTx(tx, d.UUID, e, normalizeDomainHost(d.InstanceFQDN) == normalizeDomainHost(localInstanceFQDN)); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
_, err = tx.Exec(`INSERT INTO federation_manifest_state(campus_uuid,controller_public_key,controller_fingerprint,applied_revision,manifest_json,applied_at) VALUES(`+s.sqlParam(1)+`,`+s.sqlParam(2)+`,`+s.sqlParam(3)+`,`+s.sqlParam(4)+`,`+s.sqlParam(5)+`,`+s.sqlParam(6)+`) ON CONFLICT(campus_uuid) DO UPDATE SET controller_public_key=excluded.controller_public_key,controller_fingerprint=excluded.controller_fingerprint,applied_revision=excluded.applied_revision,manifest_json=excluded.manifest_json,applied_at=excluded.applied_at`, manifest.Campus.UUID, manifest.ControllerPublicKey, manifest.ControllerFingerprint, manifest.Revision, string(payload), time.Now().Unix())
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return tx.Commit()
|
|
}
|