feat(all): apply signed client database migrations before launch
Serve signed, versioned migration plans encrypted for the requesting client. Validate identity and schema, restrict SQL, serialize database access and record applied migrations. Run migrations before normal and secondary-instance launches; signing remains an independent local operation.
This commit is contained in:
1 parent
c1b8aa6cfa
commit
6f00e1a53e
18 files changed
+2112
-1
No files matched your search
@@ -12,6 +12,7 @@ import (
|
||||
clientinstance "bd2server/internal/client/instance"
|
||||
clientplugin "bd2server/internal/client/plugin"
|
||||
clientsetup "bd2server/internal/client/setup"
|
||||
clientupdate "bd2server/internal/client/update"
|
||||
"bd2server/internal/common/taskgraph"
|
||||
"bd2server/internal/common/versionconfig"
|
||||
)
|
||||
@@ -94,7 +95,11 @@ func (t task) runClient2(args []string) error {
|
||||
fmt.Println("BepInEx log:", filepath.Join(instance.GameDirectory, "BepInEx", "LogOutput.log"))
|
||||
return nil
|
||||
}},
|
||||
taskgraph.Task{Name: "runClient2", DependsOn: []string{"instance:launcher"}, Run: func(context.Context) error {
|
||||
taskgraph.Task{Name: "instance:database", DependsOn: []string{"instance:launcher"}, Run: func(ctx context.Context) error {
|
||||
manager := clientupdate.New(clientupdate.Options{Versions: versions, Development: true})
|
||||
return manager.PrepareLocalDatabase(ctx, nil, instance.GameDirectory, settings.ServerOrigin)
|
||||
}},
|
||||
taskgraph.Task{Name: "runClient2", DependsOn: []string{"instance:database"}, Run: func(context.Context) error {
|
||||
if t.target.goos == "windows" {
|
||||
return exec.CommandContext(t.ctx, "wscript.exe", "//nologo", launcher).Run()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
// Package dbpatch applies officially signed data migrations before the native
|
||||
// client can load and clean its encrypted ClientLocal database.
|
||||
package dbpatch
|
||||
|
||||
import (
|
||||
"bd2server/internal/common/util"
|
||||
"bytes"
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"bd2server/internal/common/clientpatch"
|
||||
"bd2server/internal/common/release"
|
||||
)
|
||||
|
||||
type Options struct {
|
||||
GameDirectory string
|
||||
Origin string
|
||||
GameVersion string
|
||||
Client *http.Client
|
||||
Logger *slog.Logger
|
||||
Running func() (bool, error)
|
||||
}
|
||||
|
||||
// Run fixes only the known ClientLocal database; packages cannot choose paths
|
||||
// or provide trusted keys. The signing private key never reaches the server.
|
||||
func Run(ctx context.Context, options Options) (Result, error) {
|
||||
path, err := LocalDatabasePath(options.GameDirectory)
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
return run(ctx, path, options, release.BuiltinChannel().TrustedKeys)
|
||||
}
|
||||
|
||||
func run(ctx context.Context, path string, options Options, keys []release.TrustedKey) (Result, error) {
|
||||
origin := strings.TrimSuffix(options.Origin, "/")
|
||||
if err := clientpatch.ValidateOrigin(origin); err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
if err := stopped(options.Running); err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
if _, err := os.Lstat(path); errors.Is(err, os.ErrNotExist) {
|
||||
return Result{}, nil
|
||||
} else if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 45*time.Second)
|
||||
defer cancel()
|
||||
private, err := clientpatch.GenerateRecipient()
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
requestBody, err := json.Marshal(map[string]string{"recipient_key": base64.StdEncoding.EncodeToString(private.PublicKey().Bytes())})
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodPost, origin+"/client/patches", bytes.NewReader(requestBody))
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
client := http.Client{}
|
||||
if options.Client != nil {
|
||||
client = *options.Client
|
||||
}
|
||||
client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
return Result{}, fmt.Errorf("dbpatch: download migration package: %w", err)
|
||||
}
|
||||
defer func() { _ = response.Body.Close() }()
|
||||
if response.StatusCode == http.StatusNotFound {
|
||||
// A server without published migrations can be used until this database
|
||||
// has participated in its migration channel. Losing that channel later
|
||||
// must not silently launch an unverified database.
|
||||
if err := missingCatalog(ctx, path, origin); err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
return Result{}, nil
|
||||
}
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return Result{}, fmt.Errorf("dbpatch: server refused the migration package: %w", util.ResponseError(response))
|
||||
}
|
||||
file, err := io.ReadAll(io.LimitReader(response.Body, clientpatch.MaxPlaintext+1025))
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
signed, err := clientpatch.Open(file, private)
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
plan, err := clientpatch.Verify(signed, keys)
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
if plan.Origin != origin || plan.GameVersion != options.GameVersion {
|
||||
return Result{}, errors.New("dbpatch: package targets a different server or game version")
|
||||
}
|
||||
result, err := apply(ctx, path, plan, options.Running)
|
||||
if err != nil {
|
||||
return Result{}, err
|
||||
}
|
||||
if len(result.Applied) != 0 {
|
||||
logger := options.Logger
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
logger.Info("client database migrations applied", "revision", result.Revision, "patches", result.Applied, "backup", result.Backup)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func missingCatalog(ctx context.Context, path, origin string) error {
|
||||
raw, err := readDatabase(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
db, conn, err := openDatabase(ctx, raw)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = conn.Close(); _ = db.Close() }()
|
||||
var count int
|
||||
if err := conn.QueryRowContext(ctx, "SELECT count(*) FROM sqlite_schema WHERE name='_bd2_patch_catalog'").Scan(&count); err != nil {
|
||||
return err
|
||||
}
|
||||
if count == 0 {
|
||||
return nil
|
||||
}
|
||||
var revision string
|
||||
err = conn.QueryRowContext(ctx, "SELECT revision FROM _bd2_patch_catalog WHERE origin=?", origin).Scan(&revision)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("dbpatch: server lost the migration catalog after revision %s", revision)
|
||||
}
|
||||
@@ -0,0 +1,529 @@
|
||||
package dbpatch
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
|
||||
"bd2server/internal/common/clientpatch"
|
||||
commonconfig "bd2server/internal/common/config"
|
||||
"bd2server/internal/common/dbcrypt"
|
||||
"bd2server/internal/common/util"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
const maxDatabase = 128 << 20
|
||||
|
||||
type memoryDatabase interface {
|
||||
Deserialize([]byte) error
|
||||
Serialize() ([]byte, error)
|
||||
}
|
||||
|
||||
type Result struct {
|
||||
Revision uint64
|
||||
Applied []string
|
||||
Backup string
|
||||
}
|
||||
|
||||
func openDatabase(ctx context.Context, raw []byte) (*sql.DB, *sql.Conn, error) {
|
||||
plain, err := dbcrypt.DecryptPages(raw)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if !bytes.HasPrefix(plain, dbcrypt.Header) {
|
||||
return nil, nil, errors.New("dbpatch: invalid encrypted ClientLocal database")
|
||||
}
|
||||
db, err := sql.Open("sqlite", ":memory:")
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
db.SetMaxOpenConns(1)
|
||||
conn, err := db.Conn(ctx)
|
||||
if err == nil {
|
||||
err = conn.Raw(func(driver any) error {
|
||||
memory, ok := driver.(memoryDatabase)
|
||||
if !ok {
|
||||
return errors.New("dbpatch: SQLite serialization is unavailable")
|
||||
}
|
||||
return memory.Deserialize(plain)
|
||||
})
|
||||
}
|
||||
if err == nil {
|
||||
_, err = conn.ExecContext(ctx, "PRAGMA trusted_schema=OFF; PRAGMA temp_store=MEMORY; PRAGMA foreign_keys=ON")
|
||||
}
|
||||
if err == nil {
|
||||
err = integrity(ctx, conn)
|
||||
}
|
||||
if err != nil {
|
||||
if conn != nil {
|
||||
_ = conn.Close()
|
||||
}
|
||||
_ = db.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
return db, conn, nil
|
||||
}
|
||||
|
||||
func integrity(ctx context.Context, conn *sql.Conn) error {
|
||||
var result string
|
||||
if err := conn.QueryRowContext(ctx, "PRAGMA integrity_check").Scan(&result); err != nil {
|
||||
return err
|
||||
}
|
||||
if result != "ok" {
|
||||
return fmt.Errorf("dbpatch: SQLite integrity check: %s", result)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func serialize(conn *sql.Conn) ([]byte, error) {
|
||||
var plain []byte
|
||||
err := conn.Raw(func(driver any) error {
|
||||
var err error
|
||||
plain, err = driver.(memoryDatabase).Serialize()
|
||||
return err
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(plain) > maxDatabase {
|
||||
return nil, errors.New("dbpatch: patched database exceeds size limit")
|
||||
}
|
||||
return dbcrypt.EncryptPages(plain)
|
||||
}
|
||||
|
||||
func readDatabase(path string) ([]byte, error) {
|
||||
info, err := os.Lstat(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !info.Mode().IsRegular() || info.Size() > maxDatabase {
|
||||
return nil, errors.New("dbpatch: database must be a bounded regular file")
|
||||
}
|
||||
for _, suffix := range []string{"-wal", "-journal"} {
|
||||
if entry, err := os.Stat(path + suffix); err == nil && entry.Size() > 0 {
|
||||
return nil, errors.New("dbpatch: database has an active SQLite journal; close the game before migrating")
|
||||
} else if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return os.ReadFile(path)
|
||||
}
|
||||
|
||||
func apply(ctx context.Context, path string, plan clientpatch.Plan, running func() (bool, error)) (Result, error) {
|
||||
result := Result{Revision: plan.Revision}
|
||||
if err := plan.Validate(); err != nil {
|
||||
return result, err
|
||||
}
|
||||
if err := stopped(running); err != nil {
|
||||
return result, err
|
||||
}
|
||||
lock, err := util.TryLockFile(path + ".patch-lock")
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("dbpatch: another launcher is migrating this database: %w", err)
|
||||
}
|
||||
defer func() { _ = lock.Close() }()
|
||||
raw, err := readDatabase(path)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
db, conn, err := openDatabase(ctx, raw)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
defer func() { _ = conn.Close(); _ = db.Close() }()
|
||||
tx, err := conn.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
if _, err := tx.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS _bd2_patch_history (
|
||||
origin TEXT NOT NULL, id TEXT NOT NULL, owner_uid INTEGER NOT NULL,
|
||||
digest TEXT NOT NULL, PRIMARY KEY(origin,id,owner_uid));
|
||||
CREATE TABLE IF NOT EXISTS _bd2_patch_catalog (
|
||||
origin TEXT PRIMARY KEY, revision TEXT NOT NULL, digest TEXT NOT NULL)`); err != nil {
|
||||
return result, err
|
||||
}
|
||||
planBytes, err := json.Marshal(plan)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
planDigest := digest(planBytes)
|
||||
var revisionText, oldDigest string
|
||||
err = tx.QueryRowContext(ctx, "SELECT revision,digest FROM _bd2_patch_catalog WHERE origin=?", plan.Origin).Scan(&revisionText, &oldDigest)
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
return result, err
|
||||
}
|
||||
var previous uint64
|
||||
if err == nil {
|
||||
if _, err := fmt.Sscan(revisionText, &previous); err != nil {
|
||||
return result, errors.New("dbpatch: invalid migration revision journal")
|
||||
}
|
||||
if previous > plan.Revision || previous == plan.Revision && oldDigest != planDigest {
|
||||
return result, errors.New("dbpatch: patch catalog rollback or revision reuse detected")
|
||||
}
|
||||
}
|
||||
tables, err := databaseTables(ctx, tx)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
owners, err := databaseOwners(ctx, tx, tables)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
for _, patch := range orderedPatches(plan.Patches) {
|
||||
if patch.OwnerUID != 0 && !owners[patch.OwnerUID] {
|
||||
continue
|
||||
}
|
||||
changed, err := applyPatch(ctx, tx, plan.Origin, patch, tables)
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("dbpatch: migration %s (UID %d): %w", patch.ID, patch.OwnerUID, err)
|
||||
}
|
||||
if changed {
|
||||
result.Applied = append(result.Applied, patch.ID)
|
||||
}
|
||||
}
|
||||
if previous == plan.Revision && len(result.Applied) == 0 {
|
||||
return result, nil
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "INSERT INTO _bd2_patch_catalog(origin,revision,digest) VALUES(?,?,?) ON CONFLICT(origin) DO UPDATE SET revision=excluded.revision,digest=excluded.digest", plan.Origin, fmt.Sprint(plan.Revision), planDigest); err != nil {
|
||||
return result, err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return result, err
|
||||
}
|
||||
if err := integrity(ctx, conn); err != nil {
|
||||
return result, err
|
||||
}
|
||||
updated, err := serialize(conn)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
if err := stopped(running); err != nil {
|
||||
return result, err
|
||||
}
|
||||
current, err := readDatabase(path)
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
if !bytes.Equal(current, raw) {
|
||||
return result, errors.New("dbpatch: game database changed during migration")
|
||||
}
|
||||
backup := filepath.Join(filepath.Dir(path), ".bd2-patch-backups", filepath.Base(path)+"-"+digest(raw)+".bak")
|
||||
if err := backupDatabase(backup, raw); err != nil {
|
||||
return result, err
|
||||
}
|
||||
saved, err := os.ReadFile(backup)
|
||||
if err != nil || !bytes.Equal(saved, raw) {
|
||||
return result, errors.New("dbpatch: backup verification failed")
|
||||
}
|
||||
if err := stopped(running); err != nil {
|
||||
return result, err
|
||||
}
|
||||
if err := commonconfig.WriteFile(path, updated); err != nil {
|
||||
return result, err
|
||||
}
|
||||
result.Backup = backup
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func digest(raw []byte) string { sum := sha256.Sum256(raw); return hex.EncodeToString(sum[:]) }
|
||||
|
||||
func backupDatabase(path string, raw []byte) error {
|
||||
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
staged, err := os.CreateTemp(filepath.Dir(path), ".backup-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = os.Remove(staged.Name()) }()
|
||||
if err = staged.Chmod(0o600); err == nil {
|
||||
_, err = staged.Write(raw)
|
||||
}
|
||||
if err == nil {
|
||||
err = staged.Sync()
|
||||
}
|
||||
if closeErr := staged.Close(); err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.Link(staged.Name(), path); err != nil && !errors.Is(err, os.ErrExist) {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func orderedPatches(patches []clientpatch.Patch) []clientpatch.Patch {
|
||||
byID := make(map[string]clientpatch.Patch, len(patches))
|
||||
for _, p := range patches {
|
||||
byID[p.ID] = p
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
var ordered []clientpatch.Patch
|
||||
var visit func(clientpatch.Patch)
|
||||
visit = func(p clientpatch.Patch) {
|
||||
if seen[p.ID] {
|
||||
return
|
||||
}
|
||||
seen[p.ID] = true
|
||||
for _, id := range p.Requires {
|
||||
visit(byID[id])
|
||||
}
|
||||
ordered = append(ordered, p)
|
||||
}
|
||||
for _, p := range patches {
|
||||
visit(p)
|
||||
}
|
||||
return ordered
|
||||
}
|
||||
|
||||
func stopped(running func() (bool, error)) error {
|
||||
if running == nil {
|
||||
return errors.New("dbpatch: game process check is required")
|
||||
}
|
||||
active, err := running()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if active {
|
||||
return errors.New("dbpatch: close the game before applying local database migrations")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func applyPatch(ctx context.Context, tx *sql.Tx, origin string, patch clientpatch.Patch, tables []localTable) (bool, error) {
|
||||
raw, err := json.Marshal(patch)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
checksum := digest(raw)
|
||||
var existing string
|
||||
err = tx.QueryRowContext(ctx, "SELECT digest FROM _bd2_patch_history WHERE origin=? AND id=? AND owner_uid=?", origin, patch.ID, patch.OwnerUID).Scan(&existing)
|
||||
if err == nil {
|
||||
if existing != checksum {
|
||||
return false, errors.New("applied migration ID was reused with different content")
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
if !errors.Is(err, sql.ErrNoRows) {
|
||||
return false, err
|
||||
}
|
||||
for _, id := range patch.Requires {
|
||||
var count int
|
||||
if err := tx.QueryRowContext(ctx, "SELECT count(*) FROM _bd2_patch_history WHERE origin=? AND id=? AND (owner_uid=0 OR owner_uid=?)", origin, id, patch.OwnerUID).Scan(&count); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if count == 0 {
|
||||
return false, fmt.Errorf("required migration %s is missing", id)
|
||||
}
|
||||
}
|
||||
if err := assertions(ctx, tx, patch.Before, patch.OwnerUID); err != nil {
|
||||
return false, fmt.Errorf("precondition: %w", err)
|
||||
}
|
||||
var untouched string
|
||||
if patch.OwnerUID != 0 {
|
||||
untouched, err = otherOwnersDigest(ctx, tx, tables, patch.OwnerUID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
for index, statement := range patch.Statements {
|
||||
if err := validateSQL(statement.SQL, false); err != nil {
|
||||
return false, fmt.Errorf("statement %d: %w", index+1, err)
|
||||
}
|
||||
args, err := parameters(statement.Args, patch.OwnerUID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, statement.SQL, args...); err != nil {
|
||||
return false, fmt.Errorf("statement %d: %w", index+1, err)
|
||||
}
|
||||
}
|
||||
if err := assertions(ctx, tx, patch.After, patch.OwnerUID); err != nil {
|
||||
return false, fmt.Errorf("postcondition: %w", err)
|
||||
}
|
||||
if patch.OwnerUID != 0 {
|
||||
actual, err := otherOwnersDigest(ctx, tx, tables, patch.OwnerUID)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if actual != untouched {
|
||||
return false, errors.New("scoped migration changed another UID or an unscoped table")
|
||||
}
|
||||
}
|
||||
_, err = tx.ExecContext(ctx, "INSERT INTO _bd2_patch_history(origin,id,owner_uid,digest) VALUES(?,?,?,?)", origin, patch.ID, patch.OwnerUID, checksum)
|
||||
return err == nil, err
|
||||
}
|
||||
|
||||
func assertions(ctx context.Context, tx *sql.Tx, checks []clientpatch.Assertion, owner int64) error {
|
||||
for index, check := range checks {
|
||||
if err := validateSQL(check.SQL, true); err != nil {
|
||||
return err
|
||||
}
|
||||
args, err := parameters(check.Args, owner)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
rows, err := tx.QueryContext(ctx, check.SQL, args...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("check %d: %w", index+1, err)
|
||||
}
|
||||
var actual int64
|
||||
err = func() error {
|
||||
defer func() { _ = rows.Close() }()
|
||||
columns, err := rows.Columns()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(columns) != 1 || !rows.Next() {
|
||||
return errors.New("assertion must return one integer row")
|
||||
}
|
||||
if err := rows.Scan(&actual); err != nil {
|
||||
return err
|
||||
}
|
||||
if rows.Next() {
|
||||
return errors.New("assertion returned multiple rows")
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if actual != check.Equals {
|
||||
return fmt.Errorf("check %d expected %d, got %d", index+1, check.Equals, actual)
|
||||
}
|
||||
return nil
|
||||
}()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type localTable struct {
|
||||
name string
|
||||
owner bool
|
||||
}
|
||||
|
||||
func quoteIdentifier(name string) string { return `"` + strings.ReplaceAll(name, `"`, `""`) + `"` }
|
||||
|
||||
func databaseTables(ctx context.Context, tx *sql.Tx) ([]localTable, error) {
|
||||
rows, err := tx.QueryContext(ctx, "SELECT name FROM sqlite_schema WHERE type='table' AND name NOT LIKE 'sqlite_%' AND name NOT LIKE '_bd2_%' ORDER BY name")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var tables []localTable
|
||||
for rows.Next() {
|
||||
var table localTable
|
||||
if err := rows.Scan(&table.name); err != nil {
|
||||
_ = rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
tables = append(tables, table)
|
||||
}
|
||||
err = rows.Err()
|
||||
_ = rows.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := range tables {
|
||||
var count int
|
||||
if err := tx.QueryRowContext(ctx, "SELECT count(*) FROM pragma_table_info(?) WHERE lower(name)='ownerindex'", tables[i].name).Scan(&count); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tables[i].owner = count != 0
|
||||
}
|
||||
return tables, nil
|
||||
}
|
||||
|
||||
func databaseOwners(ctx context.Context, tx *sql.Tx, tables []localTable) (map[int64]bool, error) {
|
||||
owners := map[int64]bool{}
|
||||
for _, table := range tables {
|
||||
if !table.owner {
|
||||
continue
|
||||
}
|
||||
rows, err := tx.QueryContext(ctx, "SELECT DISTINCT ownerIndex FROM "+quoteIdentifier(table.name)+" WHERE ownerIndex > 0")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for rows.Next() {
|
||||
var owner float64
|
||||
if err := rows.Scan(&owner); err != nil {
|
||||
_ = rows.Close()
|
||||
return nil, err
|
||||
}
|
||||
if float64(int64(owner)) != owner {
|
||||
_ = rows.Close()
|
||||
return nil, errors.New("dbpatch: invalid owner UID")
|
||||
}
|
||||
owners[int64(owner)] = true
|
||||
}
|
||||
err = rows.Err()
|
||||
_ = rows.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return owners, nil
|
||||
}
|
||||
|
||||
func otherOwnersDigest(ctx context.Context, tx *sql.Tx, tables []localTable, owner int64) (string, error) {
|
||||
hash := sha256.New()
|
||||
for _, table := range tables {
|
||||
query := "SELECT * FROM " + quoteIdentifier(table.name)
|
||||
var args []any
|
||||
if table.owner {
|
||||
query += " WHERE ownerIndex IS NULL OR ownerIndex != ?"
|
||||
args = append(args, owner)
|
||||
}
|
||||
rows, err := tx.QueryContext(ctx, query, args...)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var records []string
|
||||
err = func() error {
|
||||
defer func() { _ = rows.Close() }()
|
||||
columns, err := rows.Columns()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for rows.Next() {
|
||||
values := make([]any, len(columns))
|
||||
addresses := make([]any, len(columns))
|
||||
for i := range values {
|
||||
addresses[i] = &values[i]
|
||||
}
|
||||
if err := rows.Scan(addresses...); err != nil {
|
||||
return err
|
||||
}
|
||||
raw, err := json.Marshal(values)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
records = append(records, string(raw))
|
||||
}
|
||||
return rows.Err()
|
||||
}()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
slices.Sort(records)
|
||||
raw, err := json.Marshal([]any{table.name, records})
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
_, _ = hash.Write(raw)
|
||||
}
|
||||
return hex.EncodeToString(hash.Sum(nil)), nil
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
package dbpatch
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"database/sql"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"bd2server/internal/common/clientpatch"
|
||||
"bd2server/internal/common/release"
|
||||
)
|
||||
|
||||
// This schema and owner/instance distinction come from the native
|
||||
// ClientLocalPresetDTO and ClientLocalInfo.AddPresetItem/AlterRecallPresetPinData.
|
||||
// Old instance IDs must be replaced before native cleanup removes the pin.
|
||||
func presetDatabase(t *testing.T) string {
|
||||
t.Helper()
|
||||
db, err := sql.Open("sqlite", ":memory:")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = db.Close() }()
|
||||
conn, err := db.Conn(context.Background())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = conn.Close() }()
|
||||
_, err = conn.ExecContext(context.Background(), `PRAGMA page_size=4096;
|
||||
CREATE TABLE Preset(ownerIndex REAL,saveId INTEGER,charInvenIndex BIGINT,saveOrder INTEGER,
|
||||
packId INTEGER,contentsType INTEGER,saveIndex INTEGER NOT NULL DEFAULT 0,
|
||||
typeOrder INTEGER NOT NULL DEFAULT 0,classType INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY(ownerIndex,saveId,charInvenIndex));
|
||||
INSERT INTO Preset VALUES(30738202,1,920000076,0,0,0,0,0,0),
|
||||
(30738203,1,920000076,0,0,0,0,0,0);
|
||||
CREATE TABLE LocalOptions(name TEXT PRIMARY KEY,value INTEGER);
|
||||
INSERT INTO LocalOptions VALUES('volume',50)`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, err := serialize(conn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(t.TempDir(), "ClientLocal.encrypted")
|
||||
if err := os.WriteFile(path, raw, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func migrationPlan() clientpatch.Plan {
|
||||
return clientpatch.Plan{Schema: 1, Origin: "https://example.com", GameVersion: "2.36.7", Database: clientpatch.Database, Revision: 1,
|
||||
Patches: []clientpatch.Patch{{ID: "global-instance-ids-uid-30738202", OwnerUID: 30738202,
|
||||
Before: []clientpatch.Assertion{{SQL: "SELECT count(*) FROM Preset WHERE ownerIndex=:owner AND charInvenIndex=:old", Args: map[string]any{"old": int64(920000076)}, Equals: 1}},
|
||||
Statements: []clientpatch.Statement{{SQL: "UPDATE Preset SET charInvenIndex=:new WHERE ownerIndex=:owner AND charInvenIndex=:old", Args: map[string]any{"new": int64(4294968766), "old": int64(920000076)}}},
|
||||
After: []clientpatch.Assertion{{SQL: "SELECT count(*) FROM Preset WHERE ownerIndex=:owner AND charInvenIndex=:new", Args: map[string]any{"new": int64(4294968766)}, Equals: 1}},
|
||||
}},
|
||||
}
|
||||
}
|
||||
|
||||
func notRunning() (bool, error) { return false, nil }
|
||||
|
||||
func inspectPresets(t *testing.T, path string) map[int64]int64 {
|
||||
t.Helper()
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db, conn, err := openDatabase(context.Background(), raw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = conn.Close(); _ = db.Close() }()
|
||||
rows, err := conn.QueryContext(context.Background(), "SELECT CAST(ownerIndex AS INTEGER),charInvenIndex FROM Preset")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer func() { _ = rows.Close() }()
|
||||
result := map[int64]int64{}
|
||||
for rows.Next() {
|
||||
var owner, id int64
|
||||
if err := rows.Scan(&owner, &id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
result[owner] = id
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func TestEncryptedPresetMigrationSurvivesReopenAndIsIdempotent(t *testing.T) {
|
||||
path := presetDatabase(t)
|
||||
original, _ := os.ReadFile(path)
|
||||
plan := migrationPlan()
|
||||
result, err := apply(context.Background(), path, plan, notRunning)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(result.Applied) != 1 || result.Backup == "" {
|
||||
t.Fatalf("missing migration receipt or backup: %+v", result)
|
||||
}
|
||||
if backup, err := os.ReadFile(result.Backup); err != nil || !bytes.Equal(backup, original) {
|
||||
t.Fatal("backup did not preserve the original encrypted database", err)
|
||||
}
|
||||
actual := inspectPresets(t, path)
|
||||
if actual[30738202] != 4294968766 || actual[30738203] != 920000076 {
|
||||
t.Fatalf("owner-specific native quickslot references: %v", actual)
|
||||
}
|
||||
first, _ := os.ReadFile(path)
|
||||
result, err = apply(context.Background(), path, plan, notRunning)
|
||||
if err != nil || len(result.Applied) != 0 || result.Backup != "" {
|
||||
t.Fatalf("repeat reapplied a migration: %+v %v", result, err)
|
||||
}
|
||||
second, _ := os.ReadFile(path)
|
||||
if !bytes.Equal(first, second) {
|
||||
t.Fatal("idempotent launch rewrote database")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFailedSQLOrPostconditionLeavesOriginalDatabaseUnchanged(t *testing.T) {
|
||||
for _, failure := range []string{"sql", "postcondition", "owner scope", "unscoped table"} {
|
||||
t.Run(failure, func(t *testing.T) {
|
||||
path := presetDatabase(t)
|
||||
original, _ := os.ReadFile(path)
|
||||
plan := migrationPlan()
|
||||
switch failure {
|
||||
case "sql":
|
||||
plan.Patches[0].Statements = append(plan.Patches[0].Statements, clientpatch.Statement{SQL: "UPDATE Missing SET value=1"})
|
||||
case "postcondition":
|
||||
plan.Patches[0].After[0].Equals = 2
|
||||
case "owner scope":
|
||||
plan.Patches[0].Statements[0].SQL = "UPDATE Preset SET charInvenIndex=:new WHERE charInvenIndex=:old"
|
||||
case "unscoped table":
|
||||
plan.Patches[0].Statements = append(plan.Patches[0].Statements, clientpatch.Statement{SQL: "UPDATE LocalOptions SET value=0"})
|
||||
}
|
||||
if _, err := apply(context.Background(), path, plan, notRunning); err == nil {
|
||||
t.Fatal("invalid migration succeeded")
|
||||
}
|
||||
actual, _ := os.ReadFile(path)
|
||||
if !bytes.Equal(original, actual) {
|
||||
t.Fatal("failed migration changed encrypted database")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDatabaseStructureMismatchAndRunningGamePreventMigration(t *testing.T) {
|
||||
for _, scenario := range []string{"schema", "running", "starts before replacement"} {
|
||||
t.Run(scenario, func(t *testing.T) {
|
||||
path := presetDatabase(t)
|
||||
original, _ := os.ReadFile(path)
|
||||
plan := migrationPlan()
|
||||
calls := 0
|
||||
running := func() (bool, error) {
|
||||
calls++
|
||||
return scenario == "running" || scenario == "starts before replacement" && calls >= 2, nil
|
||||
}
|
||||
if scenario == "schema" {
|
||||
plan.Patches[0].Before[0].SQL = "SELECT absent_column FROM Preset LIMIT 1"
|
||||
}
|
||||
if _, err := apply(context.Background(), path, plan, running); err == nil {
|
||||
t.Fatal("unsafe migration accepted")
|
||||
}
|
||||
actual, _ := os.ReadFile(path)
|
||||
if !bytes.Equal(original, actual) {
|
||||
t.Fatal("precondition/process rejection changed database")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrationJournalRejectsRollbackAndReusedIDs(t *testing.T) {
|
||||
path := presetDatabase(t)
|
||||
plan := migrationPlan()
|
||||
plan.Revision = 2
|
||||
if _, err := apply(context.Background(), path, plan, notRunning); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, scenario := range []string{"rollback", "revision reuse", "ID reuse"} {
|
||||
t.Run(scenario, func(t *testing.T) {
|
||||
changed := migrationPlan()
|
||||
changed.Revision = 2
|
||||
switch scenario {
|
||||
case "rollback":
|
||||
changed.Revision = 1
|
||||
case "revision reuse":
|
||||
changed.Patches[0].After[0].Equals = 0
|
||||
case "ID reuse":
|
||||
changed.Revision = 3
|
||||
changed.Patches[0].After[0].Equals = 0
|
||||
}
|
||||
before, _ := os.ReadFile(path)
|
||||
if _, err := apply(context.Background(), path, changed, notRunning); err == nil {
|
||||
t.Fatal("migration journal accepted conflicting publication")
|
||||
}
|
||||
after, _ := os.ReadFile(path)
|
||||
if !bytes.Equal(before, after) {
|
||||
t.Fatal("rejected catalog changed database")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSQLRestrictionUnderstandsQuotedContentAndRejectsFileAndBatchOperations(t *testing.T) {
|
||||
for _, source := range []string{
|
||||
"UPDATE Preset SET charInvenIndex=1; ATTACH DATABASE '/tmp/other.db' AS ext",
|
||||
"UPDATE Preset SET charInvenIndex=1; DELETE FROM Preset",
|
||||
"UPDATE [Preset] SET saveId=load_extension('unsafe')",
|
||||
"UPDATE Preset SET saveId=(SELECT writefile('/tmp/a','b'))",
|
||||
"UPDATE \"_bd2_patch_history\" SET digest='forged'",
|
||||
"UPDATE Preset SET saveId=(SELECT * FROM pragma_user_version)",
|
||||
"PRAGMA writable_schema=ON", "DROP TABLE Preset", "ATTACH ':memory:' AS other",
|
||||
"UPDATE Preset SET saveId=(SELECT unknown_file_function('file'))",
|
||||
} {
|
||||
if err := validateSQL(source, false); err == nil {
|
||||
t.Errorf("accepted %s", source)
|
||||
}
|
||||
}
|
||||
if err := validateSQL("UPDATE LocalOptions SET name='DROP; ATTACH ''x''' /* ; */ WHERE name=:name;", false); err != nil {
|
||||
t.Fatal("SQL literal/comment incorrectly treated as executable", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSQLRestrictionAcceptsKeywordsBeforeParenthesesButStillChecksFunctions(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
source string
|
||||
assertion bool
|
||||
}{
|
||||
{"SELECT count(*) FROM (SELECT ownerIndex, charInvenIndex FROM Preset LIMIT 0)", true},
|
||||
{"SELECT count(*) FROM Preset p JOIN (SELECT ownerIndex FROM PresetTalent) t USING (ownerIndex)", true},
|
||||
{"SELECT count(*) FROM json_each(:decks)", true},
|
||||
{"DELETE FROM Preset WHERE ownerIndex IN (SELECT ownerIndex FROM PresetTalent)", false},
|
||||
{"INSERT INTO Preset(ownerIndex) VALUES (1)", false},
|
||||
{"UPDATE Preset SET charInvenIndex=1 WHERE NOT EXISTS (SELECT 1 FROM PresetTalent) AND (ownerIndex=1 OR ownerIndex=2)", false},
|
||||
} {
|
||||
if err := validateSQL(c.source, c.assertion); err != nil {
|
||||
t.Errorf("rejected %s: %v", c.source, err)
|
||||
}
|
||||
}
|
||||
for _, c := range []struct{ source, rejected string }{
|
||||
{"SELECT count(*) FROM (SELECT unknown_file_function('file'))", `"unknown_file_function"`},
|
||||
{"SELECT count(*) FROM unknown_table_function(1)", `"unknown_table_function"`},
|
||||
{"SELECT count(*) FROM Preset WHERE ownerIndex IN (SELECT y FROM (SELECT nested_function(1)))", `"nested_function"`},
|
||||
} {
|
||||
if err := validateSQL(c.source, true); err == nil || !strings.Contains(err.Error(), c.rejected) {
|
||||
t.Errorf("%s: got %v, want rejection of %s", c.source, err, c.rejected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLaunchFetchVerifiesBeforeDatabaseWriteAndFailsClosedAfterEnrollment(t *testing.T) {
|
||||
public, private, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
keys := []release.TrustedKey{{ID: release.KeyID(public), PublicKey: base64.StdEncoding.EncodeToString(public)}}
|
||||
path := presetDatabase(t)
|
||||
plan := migrationPlan()
|
||||
var signed []byte
|
||||
status := http.StatusOK
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if status != http.StatusOK {
|
||||
http.Error(w, "plan targets game 2.36.6", status)
|
||||
return
|
||||
}
|
||||
var request struct {
|
||||
RecipientKey string `json:"recipient_key"`
|
||||
}
|
||||
if r.Method != http.MethodPost || r.URL.Path != "/client/patches" {
|
||||
t.Errorf("unexpected request %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
|
||||
t.Error(err)
|
||||
w.WriteHeader(400)
|
||||
return
|
||||
}
|
||||
key, err := base64.StdEncoding.DecodeString(request.RecipientKey)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
file, err := clientpatch.Seal(signed, key)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
_, _ = w.Write(file)
|
||||
}))
|
||||
defer server.Close()
|
||||
plan.Origin = server.URL
|
||||
sign := func() {
|
||||
payload, err := json.Marshal(plan)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
signed, err = json.Marshal(clientpatch.Envelope{KeyID: keys[0].ID, Signature: base64.StdEncoding.EncodeToString(ed25519.Sign(private, append([]byte(clientpatch.SignatureDomain), payload...))), Plan: payload})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
sign()
|
||||
options := Options{Origin: server.URL, GameVersion: "2.36.7", Client: server.Client(), Running: notRunning}
|
||||
original, _ := os.ReadFile(path)
|
||||
signed = bytes.Replace(signed, []byte(`"revision":1`), []byte(`"revision":2`), 1)
|
||||
if _, err := run(context.Background(), path, options, keys); err == nil {
|
||||
t.Fatal("tampered package reached database execution")
|
||||
}
|
||||
actual, _ := os.ReadFile(path)
|
||||
if !bytes.Equal(original, actual) {
|
||||
t.Fatal("tampered download changed local database")
|
||||
}
|
||||
sign()
|
||||
if _, err := run(context.Background(), path, options, keys); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := inspectPresets(t, path)[30738202]; got != 4294968766 {
|
||||
t.Fatalf("downloaded migration left native quickslot at %d", got)
|
||||
}
|
||||
status = http.StatusServiceUnavailable
|
||||
if _, err := run(context.Background(), path, options, keys); err == nil || !strings.Contains(err.Error(), "503 Service Unavailable: plan targets game 2.36.6") {
|
||||
t.Fatalf("server refusal lost its reason: %v", err)
|
||||
}
|
||||
status = http.StatusNotFound
|
||||
if _, err := run(context.Background(), path, options, keys); err == nil || !strings.Contains(err.Error(), "lost the migration catalog") {
|
||||
t.Fatalf("missing enrolled migration source: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package dbpatch
|
||||
|
||||
import (
|
||||
"crypto/sha1"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
|
||||
clientlayout "bd2server/internal/client/layout"
|
||||
)
|
||||
|
||||
// LocalDatabasePath resolves the native or isolated instance database. A patch
|
||||
// cannot provide a filename or redirect this location.
|
||||
func LocalDatabasePath(game string) (string, error) {
|
||||
installation, err := clientlayout.Resolve(game)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
container := installation.Root
|
||||
if installation.Kind == clientlayout.MacOS {
|
||||
container = filepath.Dir(container)
|
||||
}
|
||||
parent := filepath.Dir(container)
|
||||
marker, err := os.ReadFile(filepath.Join(parent, "instance.json"))
|
||||
var persistent string
|
||||
if err == nil {
|
||||
var manifest struct {
|
||||
Schema int `json:"schema_version"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
if err := json.Unmarshal(marker, &manifest); err != nil || manifest.Schema != 1 || manifest.ID != filepath.Base(parent) || filepath.Base(container) != "game" {
|
||||
return "", errors.New("dbpatch: invalid client instance manifest")
|
||||
}
|
||||
persistent = filepath.Join(parent, "unity", "persistent")
|
||||
} else if !errors.Is(err, os.ErrNotExist) {
|
||||
return "", err
|
||||
} else {
|
||||
home, err := os.UserHomeDir()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
persistent = filepath.Join(home, "AppData", "LocalLow", "Gamfs", "BrownDust II")
|
||||
case "darwin":
|
||||
persistent = filepath.Join(home, "Library", "Application Support", "Gamfs", "BrownDust II")
|
||||
default:
|
||||
return "", fmt.Errorf("dbpatch: unsupported platform %s", runtime.GOOS)
|
||||
}
|
||||
}
|
||||
return filepath.Join(persistent, "Data", fmt.Sprintf("%X", sha1.Sum([]byte("ClientLocal_v1")))), nil
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
package dbpatch
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type token struct {
|
||||
text string
|
||||
kind byte
|
||||
}
|
||||
|
||||
// SQLite permits quoted identifiers and semicolons inside literals. Tokenize
|
||||
// those forms before enforcing a single data statement, rather than splitting SQL.
|
||||
func sqlTokens(source string) ([]token, error) {
|
||||
var out []token
|
||||
for i := 0; i < len(source); {
|
||||
c := source[i]
|
||||
switch {
|
||||
case c <= ' ':
|
||||
i++
|
||||
case c == '-' && i+1 < len(source) && source[i+1] == '-':
|
||||
for i < len(source) && source[i] != '\n' {
|
||||
i++
|
||||
}
|
||||
case c == '/' && i+1 < len(source) && source[i+1] == '*':
|
||||
end := strings.Index(source[i+2:], "*/")
|
||||
if end < 0 {
|
||||
return nil, errors.New("unterminated SQL comment")
|
||||
}
|
||||
i += end + 4
|
||||
case c == '\'' || c == '"' || c == '`' || c == '[':
|
||||
endQuote := c
|
||||
if c == '[' {
|
||||
endQuote = ']'
|
||||
}
|
||||
kind := byte('i')
|
||||
if c == '\'' {
|
||||
kind = 's'
|
||||
}
|
||||
i++
|
||||
var value strings.Builder
|
||||
closed := false
|
||||
for i < len(source) {
|
||||
if source[i] == endQuote {
|
||||
if endQuote != ']' && i+1 < len(source) && source[i+1] == endQuote {
|
||||
value.WriteByte(endQuote)
|
||||
i += 2
|
||||
continue
|
||||
}
|
||||
i++
|
||||
closed = true
|
||||
break
|
||||
}
|
||||
value.WriteByte(source[i])
|
||||
i++
|
||||
}
|
||||
if !closed {
|
||||
return nil, errors.New("unterminated SQL quote")
|
||||
}
|
||||
out = append(out, token{strings.ToLower(value.String()), kind})
|
||||
case c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c == '_':
|
||||
start := i
|
||||
for i < len(source) && (source[i] >= 'a' && source[i] <= 'z' || source[i] >= 'A' && source[i] <= 'Z' || source[i] >= '0' && source[i] <= '9' || source[i] == '_') {
|
||||
i++
|
||||
}
|
||||
out = append(out, token{strings.ToLower(source[start:i]), 'i'})
|
||||
default:
|
||||
if c == 0 || c >= 128 {
|
||||
return nil, errors.New("SQL uses an unsupported unquoted character")
|
||||
}
|
||||
out = append(out, token{string(c), 'p'})
|
||||
i++
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func validateSQL(source string, assertion bool) error {
|
||||
tokens, err := sqlTokens(source)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(tokens) == 0 {
|
||||
return errors.New("empty SQL statement")
|
||||
}
|
||||
if tokens[len(tokens)-1].text == ";" {
|
||||
tokens = tokens[:len(tokens)-1]
|
||||
}
|
||||
if len(tokens) == 0 {
|
||||
return errors.New("empty SQL statement")
|
||||
}
|
||||
verb := tokens[0].text
|
||||
if tokens[0].kind != 'i' || assertion && verb != "select" || !assertion && verb != "update" && verb != "insert" && verb != "delete" {
|
||||
return errors.New("patch SQL must be UPDATE, INSERT or DELETE; assertions must be SELECT")
|
||||
}
|
||||
for _, t := range tokens {
|
||||
if t.kind == 'p' && (t.text == ";" || t.text == "?" || t.text == "@" || t.text == "$") {
|
||||
return errors.New("multiple SQL statements and positional parameters are forbidden")
|
||||
}
|
||||
if t.kind != 'i' {
|
||||
continue
|
||||
}
|
||||
if strings.HasPrefix(t.text, "_bd2_") || strings.HasPrefix(t.text, "pragma_") || !assertion && strings.HasPrefix(t.text, "sqlite_") {
|
||||
return errors.New("patch SQL cannot access migration metadata, PRAGMA or SQLite internals")
|
||||
}
|
||||
switch t.text {
|
||||
case "attach", "detach", "pragma", "vacuum", "create", "alter", "drop", "reindex", "analyze", "begin", "commit", "rollback", "savepoint", "release", "with", "load_extension", "readfile", "writefile", "fts3_tokenizer", "eval":
|
||||
return fmt.Errorf("forbidden SQL operation %q", t.text)
|
||||
}
|
||||
}
|
||||
targetIndex := -1
|
||||
if !assertion {
|
||||
at := 1
|
||||
if verb == "insert" || verb == "update" {
|
||||
if at < len(tokens) && tokens[at].text == "or" {
|
||||
at += 2
|
||||
}
|
||||
}
|
||||
if verb == "insert" || verb == "delete" {
|
||||
keyword := "into"
|
||||
if verb == "delete" {
|
||||
keyword = "from"
|
||||
}
|
||||
if at >= len(tokens) || tokens[at].text != keyword {
|
||||
return errors.New("unsupported SQL target")
|
||||
}
|
||||
at++
|
||||
}
|
||||
if at >= len(tokens) || tokens[at].kind != 'i' {
|
||||
return errors.New("SQL table must be an identifier")
|
||||
}
|
||||
if at+1 < len(tokens) && tokens[at+1].text == "." && (at+2 >= len(tokens) || tokens[at+2].kind != 'i') {
|
||||
return errors.New("qualified SQL table must be an identifier")
|
||||
}
|
||||
targetIndex = at
|
||||
if at+1 < len(tokens) && tokens[at+1].text == "." {
|
||||
targetIndex = at + 2
|
||||
}
|
||||
}
|
||||
for i, t := range tokens {
|
||||
if t.kind != 'i' || i+1 >= len(tokens) || tokens[i+1].text != "(" {
|
||||
continue
|
||||
}
|
||||
// An INSERT table name is followed by its column list, not a function.
|
||||
if verb == "insert" && i == targetIndex {
|
||||
continue
|
||||
}
|
||||
switch t.text {
|
||||
// Keywords that open a subquery, row value or expression group.
|
||||
case "select", "from", "join", "using", "where", "and", "or", "not", "is", "like", "glob", "between", "case", "when", "then", "else", "on", "set", "by", "distinct", "all", "having", "limit", "offset", "filter", "over", "partition", "as", "values", "in", "exists":
|
||||
// Functions.
|
||||
case "cast", "count", "sum", "total", "avg", "min", "max", "abs", "coalesce", "ifnull", "nullif", "iif", "typeof", "length", "hex", "unhex", "lower", "upper", "substr", "substring", "trim", "ltrim", "rtrim", "replace", "round", "instr", "printf", "format", "quote", "unicode", "char", "changes", "json", "json_valid", "json_extract", "json_type", "json_array_length", "json_array", "json_object", "json_set", "json_insert", "json_replace", "json_remove", "json_patch", "json_each", "json_tree", "json_group_array", "json_group_object":
|
||||
default:
|
||||
return fmt.Errorf("SQL function %q is not allowed in data migrations", t.text)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func parameters(values map[string]any, owner int64) ([]any, error) {
|
||||
args := []any{sql.Named("owner", owner)}
|
||||
for name, value := range values {
|
||||
if name == "owner" || name == "" {
|
||||
return nil, errors.New("owner is a reserved SQL parameter")
|
||||
}
|
||||
for _, c := range name {
|
||||
valid := c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_'
|
||||
if !valid {
|
||||
return nil, errors.New("invalid SQL parameter name")
|
||||
}
|
||||
}
|
||||
switch v := value.(type) {
|
||||
case json.Number:
|
||||
integer, err := v.Int64()
|
||||
if err == nil {
|
||||
value = integer
|
||||
} else {
|
||||
if !strings.ContainsAny(v.String(), ".eE") {
|
||||
return nil, errors.New("integer parameter exceeds SQLite signed 64-bit range")
|
||||
}
|
||||
decimal, err := v.Float64()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
value = decimal
|
||||
}
|
||||
case nil, string, bool, int, int64, float64:
|
||||
default:
|
||||
return nil, fmt.Errorf("SQL parameter %s is not a scalar", name)
|
||||
}
|
||||
args = append(args, sql.Named(name, value))
|
||||
}
|
||||
return args, nil
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package update
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"bd2server/internal/client/dbpatch"
|
||||
)
|
||||
|
||||
// PrepareLocalDatabase is shared by the normal launcher and the independent
|
||||
// development instance entry point. It never starts the game itself.
|
||||
func (m *Manager) PrepareLocalDatabase(ctx context.Context, client *http.Client, game, origin string) error {
|
||||
if client == nil {
|
||||
client = m.options.Client
|
||||
}
|
||||
_, err := dbpatch.Run(ctx, dbpatch.Options{
|
||||
GameDirectory: game, Origin: origin, GameVersion: m.Runtime(game).GameVersion,
|
||||
Client: client, Logger: m.options.Logger, Running: func() (bool, error) { return m.localDatabaseRunning(game) },
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (m *Manager) localDatabaseRunning(game string) (bool, error) {
|
||||
target, err := dbpatch.LocalDatabasePath(game)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
processes, err := runningExecutables()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
for executable := range processes {
|
||||
name := filepath.Base(executable)
|
||||
if !strings.EqualFold(name, "BrownDust II.exe") && name != "BrownDust II" {
|
||||
continue
|
||||
}
|
||||
directory := filepath.Dir(executable)
|
||||
if name == "BrownDust II" {
|
||||
directory = filepath.Dir(filepath.Dir(directory))
|
||||
}
|
||||
path, err := dbpatch.LocalDatabasePath(directory)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if executableKey(target) == executableKey(path) {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
@@ -884,6 +884,9 @@ func (m *Manager) WithLaunch(ctx context.Context, client *http.Client, game, ori
|
||||
if err := m.ensurePlugins(game); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := m.PrepareLocalDatabase(ctx, client, game, origin); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return launch()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
package clientpatch
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ecdh"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"bd2server/internal/common/release"
|
||||
)
|
||||
|
||||
func signedFixture(t *testing.T, payload []byte, domain string) ([]byte, []release.TrustedKey) {
|
||||
t.Helper()
|
||||
public, private, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key := release.TrustedKey{ID: release.KeyID(public), PublicKey: base64.StdEncoding.EncodeToString(public)}
|
||||
raw, err := json.Marshal(Envelope{KeyID: key.ID, Signature: base64.StdEncoding.EncodeToString(ed25519.Sign(private, append([]byte(domain), payload...))), Plan: payload})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return raw, []release.TrustedKey{key}
|
||||
}
|
||||
|
||||
func TestOfficialSignatureBindsExactPayloadAndProtocolDomain(t *testing.T) {
|
||||
payload := []byte(`{"schema":1,"origin":"https://example.com","game_version":"2.36.7","database":"ClientLocal_v1","revision":1,"patches":[]}`)
|
||||
signed, keys := signedFixture(t, payload, SignatureDomain)
|
||||
if _, err := Verify(signed, keys); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
altered := bytes.Replace(signed, []byte(`"revision":1`), []byte(`"revision":2`), 1)
|
||||
if _, err := Verify(altered, keys); err == nil {
|
||||
t.Fatal("modified revision retained signature authority")
|
||||
}
|
||||
_, otherKeys := signedFixture(t, payload, SignatureDomain)
|
||||
if _, err := Verify(signed, otherKeys); err == nil {
|
||||
t.Fatal("a different server key authorized an official plan")
|
||||
}
|
||||
otherDomain, otherDomainKeys := signedFixture(t, payload, "bd2-release-manifest-v1\n")
|
||||
if _, err := Verify(otherDomain, otherDomainKeys); err == nil {
|
||||
t.Fatal("release-manifest signature crossed the client-patch domain")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEncryptedFileOnlyAuthenticatesForRecipientAndUnmodifiedHeader(t *testing.T) {
|
||||
recipient, err := GenerateRecipient()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
other, err := GenerateRecipient()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
payload := []byte("a signed plan with public identifier corrections")
|
||||
first, err := Seal(payload, recipient.PublicKey().Bytes())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
second, err := Seal(payload, recipient.PublicKey().Bytes())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if bytes.Equal(first, second) {
|
||||
t.Fatal("separate downloads reused the encrypted file")
|
||||
}
|
||||
for _, file := range [][]byte{first, second} {
|
||||
plain, err := Open(file, recipient)
|
||||
if err != nil || !bytes.Equal(plain, payload) {
|
||||
t.Fatalf("recipient could not recover plan: %v", err)
|
||||
}
|
||||
if _, err := Open(file, other); err == nil {
|
||||
t.Fatal("another launch recipient decrypted the plan")
|
||||
}
|
||||
}
|
||||
for _, offset := range []int{0, len(magic), len(magic) + 32, headerSize, len(first) - 1} {
|
||||
changed := bytes.Clone(first)
|
||||
changed[offset] ^= 1
|
||||
if _, err := Open(changed, recipient); err == nil {
|
||||
t.Fatalf("modified file at offset %d authenticated", offset)
|
||||
}
|
||||
}
|
||||
if _, err := Seal(payload, make([]byte, 32)); err == nil {
|
||||
t.Fatal("low-order X25519 recipient accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSignedArgumentsRetainSQLiteIntegerIdentityAndRejectUnsafeScope(t *testing.T) {
|
||||
payload := []byte(`{"schema":1,"origin":"https://example.com","game_version":"2.36.7","database":"ClientLocal_v1","revision":1,"patches":[{"id":"identity-v1","owner_uid":30738202,"requires":[],"before":[{"sql":"SELECT count(*) FROM sqlite_schema WHERE name = :table","args":{"table":"Character"},"equals":1}],"statements":[{"sql":"UPDATE Character SET InstanceID = :new_id WHERE OwnerUID = :owner","args":{"new_id":9007199254740993}}],"after":[{"sql":"SELECT count(*) FROM Character WHERE OwnerUID = :owner AND InstanceID = :new_id","args":{"new_id":9007199254740993},"equals":1}]}]}`)
|
||||
signed, keys := signedFixture(t, payload, SignatureDomain)
|
||||
plan, err := Verify(signed, keys)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
number, ok := plan.Patches[0].Statements[0].Args["new_id"].(json.Number)
|
||||
if !ok || number.String() != "9007199254740993" {
|
||||
t.Fatalf("64-bit instance identity rounded during verification: %v", number)
|
||||
}
|
||||
plan.Patches[0].Statements[0].Args["owner"] = int64(1)
|
||||
if err := plan.Validate(); err == nil {
|
||||
t.Fatal("caller overrode trusted account scope")
|
||||
}
|
||||
delete(plan.Patches[0].Statements[0].Args, "owner")
|
||||
other := plan.Patches[0]
|
||||
other.ID = "other-account"
|
||||
other.OwnerUID++
|
||||
plan.Patches = append(plan.Patches, other)
|
||||
plan.Patches[0].Requires = []string{other.ID}
|
||||
if err := plan.Validate(); err == nil {
|
||||
t.Fatal("account patch depended on another player's patch")
|
||||
}
|
||||
plan.Patches[1].OwnerUID = 0
|
||||
if err := plan.Validate(); err != nil {
|
||||
t.Fatalf("account patch cannot depend on a global prerequisite: %v", err)
|
||||
}
|
||||
plan.Patches[1].OwnerUID = plan.Patches[0].OwnerUID
|
||||
plan.Patches[1].Requires = []string{plan.Patches[0].ID}
|
||||
if err := plan.Validate(); err == nil {
|
||||
t.Fatal("cyclic dependencies accepted")
|
||||
}
|
||||
}
|
||||
|
||||
// Produced independently with Python cryptography's X25519, HKDF and AESGCM.
|
||||
func TestOpenInteroperatesWithIndependentEncryptionVector(t *testing.T) {
|
||||
recipientBytes, err := hex.DecodeString("0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
recipient, err := ecdh.X25519().NewPrivateKey(recipientBytes)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
file, err := hex.DecodeString("4244325041544348015869aff450549732cbaaed5e5df9b30a6da31cb0e5742bad5ad4a1a768f1a67b000102030405060708090a0b8c3af1692334c7c120059c22d38c3b0f68d4ddf161c98f003c395e9ab2c2b9db7c8412ceb15aa54df5ed3399f82c2e204d7f1b68108ef6560438a3958e343ba0a9fd97efd6")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
plain, err := Open(file, recipient)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(plain) != `{"official":"independent Python cryptography vector"}` {
|
||||
t.Fatalf("independent ciphertext decrypted incorrectly: %s", plain)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package clientpatch
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/aes"
|
||||
"crypto/cipher"
|
||||
"crypto/ecdh"
|
||||
"crypto/hkdf"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
const magic = "BD2PATCH\x01"
|
||||
const headerSize = len(magic) + 32 + 12
|
||||
const encryptionInfo = "bd2-client-patch-file-v1"
|
||||
|
||||
func GenerateRecipient() (*ecdh.PrivateKey, error) { return ecdh.X25519().GenerateKey(rand.Reader) }
|
||||
|
||||
func patchAEAD(private *ecdh.PrivateKey, public []byte) (cipher.AEAD, error) {
|
||||
peer, err := ecdh.X25519().NewPublicKey(public)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("clientpatch: invalid recipient key: %w", err)
|
||||
}
|
||||
secret, err := private.ECDH(peer)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("clientpatch: key agreement: %w", err)
|
||||
}
|
||||
defer clear(secret)
|
||||
key, err := hkdf.Key(sha256.New, secret, nil, encryptionInfo, 32)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer clear(key)
|
||||
block, err := aes.NewCipher(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cipher.NewGCM(block)
|
||||
}
|
||||
|
||||
func Seal(signed, recipientPublic []byte) ([]byte, error) {
|
||||
if len(signed) == 0 || len(signed) > MaxPlaintext {
|
||||
return nil, errors.New("clientpatch: plaintext size is invalid")
|
||||
}
|
||||
ephemeral, err := GenerateRecipient()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
aead, err := patchAEAD(ephemeral, recipientPublic)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
header := make([]byte, headerSize)
|
||||
copy(header, magic)
|
||||
copy(header[len(magic):], ephemeral.PublicKey().Bytes())
|
||||
nonce := header[len(magic)+32:]
|
||||
if _, err := rand.Read(nonce); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return aead.Seal(header, nonce, signed, header), nil
|
||||
}
|
||||
|
||||
func Open(file []byte, private *ecdh.PrivateKey) ([]byte, error) {
|
||||
if private == nil || private.Curve() != ecdh.X25519() || len(file) < headerSize+16 || len(file) > headerSize+MaxPlaintext+16 || !bytes.Equal(file[:len(magic)], []byte(magic)) {
|
||||
return nil, errors.New("clientpatch: invalid encrypted patch file")
|
||||
}
|
||||
header := file[:headerSize]
|
||||
aead, err := patchAEAD(private, header[len(magic):len(magic)+32])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
plain, err := aead.Open(nil, header[len(magic)+32:], file[headerSize:], header)
|
||||
if err != nil {
|
||||
return nil, errors.New("clientpatch: encrypted patch authentication failed")
|
||||
}
|
||||
if len(plain) == 0 {
|
||||
return nil, errors.New("clientpatch: empty encrypted patch")
|
||||
}
|
||||
return plain, nil
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
package clientpatch
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ed25519"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"math"
|
||||
"net"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"bd2server/internal/common/release"
|
||||
)
|
||||
|
||||
const (
|
||||
SignatureDomain = "bd2-client-patch-v1\n"
|
||||
MaxPlaintext = 16 << 20
|
||||
Database = "ClientLocal_v1"
|
||||
MaxPatches = 256
|
||||
)
|
||||
|
||||
type Plan struct {
|
||||
Schema int `json:"schema"`
|
||||
Origin string `json:"origin"`
|
||||
GameVersion string `json:"game_version"`
|
||||
Database string `json:"database"`
|
||||
Revision uint64 `json:"revision"`
|
||||
Patches []Patch `json:"patches"`
|
||||
}
|
||||
|
||||
type Patch struct {
|
||||
ID string `json:"id"`
|
||||
OwnerUID int64 `json:"owner_uid"`
|
||||
Requires []string `json:"requires"`
|
||||
Statements []Statement `json:"statements"`
|
||||
Before []Assertion `json:"before"`
|
||||
After []Assertion `json:"after"`
|
||||
}
|
||||
|
||||
type Statement struct {
|
||||
SQL string `json:"sql"`
|
||||
Args map[string]any `json:"args"`
|
||||
}
|
||||
|
||||
type Assertion struct {
|
||||
SQL string `json:"sql"`
|
||||
Args map[string]any `json:"args"`
|
||||
Equals int64 `json:"equals"`
|
||||
}
|
||||
|
||||
type Envelope struct {
|
||||
KeyID string `json:"key_id"`
|
||||
Signature string `json:"signature"`
|
||||
Plan json.RawMessage `json:"plan"`
|
||||
}
|
||||
|
||||
var identifier = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`)
|
||||
var argument = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]{0,63}$`)
|
||||
var gameVersion = regexp.MustCompile(`^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$`)
|
||||
|
||||
func ValidateOrigin(origin string) error {
|
||||
u, err := url.Parse(origin)
|
||||
if err != nil || len(origin) > 2048 || u.Host == "" || u.User != nil || u.Path != "" || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || u.Opaque != "" || u.String() != origin {
|
||||
return errors.New("clientpatch: invalid origin")
|
||||
}
|
||||
host := u.Hostname()
|
||||
if host == "" || host != strings.ToLower(host) || strings.HasSuffix(host, ".") || strings.ContainsAny(host, "%\\ \t\r\n") || strings.HasSuffix(u.Host, ":") {
|
||||
return errors.New("clientpatch: origin host is not canonical")
|
||||
}
|
||||
if port := u.Port(); port != "" {
|
||||
n, err := strconv.Atoi(port)
|
||||
if err != nil || n < 1 || n > 65535 || strconv.Itoa(n) != port || u.Scheme == "https" && n == 443 || u.Scheme == "http" && n == 80 {
|
||||
return errors.New("clientpatch: origin port is not canonical")
|
||||
}
|
||||
}
|
||||
ip := net.ParseIP(host)
|
||||
if ip != nil && ip.String() != host {
|
||||
return errors.New("clientpatch: origin IP is not canonical")
|
||||
}
|
||||
loopbackHTTP := u.Scheme == "http" && (host == "localhost" || ip != nil && ip.IsLoopback())
|
||||
if u.Scheme != "https" && !loopbackHTTP {
|
||||
return errors.New("clientpatch: origin requires HTTPS")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p Plan) Validate() error {
|
||||
if p.Schema != 1 || p.Database != Database || p.Revision == 0 || (len(p.GameVersion) > 32 || !gameVersion.MatchString(p.GameVersion)) {
|
||||
return errors.New("clientpatch: unsupported plan schema, database, revision or game version")
|
||||
}
|
||||
if err := ValidateOrigin(p.Origin); err != nil {
|
||||
return err
|
||||
}
|
||||
if p.Patches == nil || len(p.Patches) > MaxPatches {
|
||||
return errors.New("clientpatch: patches must be an array of at most 256 entries")
|
||||
}
|
||||
ids := make(map[string]int, len(p.Patches))
|
||||
total := 0
|
||||
for i, patch := range p.Patches {
|
||||
if !identifier.MatchString(patch.ID) || patch.OwnerUID < 0 {
|
||||
return fmt.Errorf("clientpatch: invalid patch identity at index %d", i)
|
||||
}
|
||||
if _, exists := ids[patch.ID]; exists {
|
||||
return fmt.Errorf("clientpatch: duplicate patch %q", patch.ID)
|
||||
}
|
||||
ids[patch.ID] = i
|
||||
if len(patch.Requires) > MaxPatches || len(patch.Statements) == 0 || len(patch.Statements) > 256 || len(patch.Before) == 0 || len(patch.Before) > 64 || len(patch.After) == 0 || len(patch.After) > 64 {
|
||||
return fmt.Errorf("clientpatch: patch %q exceeds operation limits or lacks statements/preconditions/postconditions", patch.ID)
|
||||
}
|
||||
total += len(patch.Statements) + len(patch.Before) + len(patch.After)
|
||||
if total > 4096 {
|
||||
return errors.New("clientpatch: plan exceeds operation limit")
|
||||
}
|
||||
for _, statement := range patch.Statements {
|
||||
if err := validateQuery(statement.SQL, statement.Args, false); err != nil {
|
||||
return fmt.Errorf("clientpatch: patch %q statement: %w", patch.ID, err)
|
||||
}
|
||||
}
|
||||
for _, assertions := range [][]Assertion{patch.Before, patch.After} {
|
||||
for _, assertion := range assertions {
|
||||
if err := validateQuery(assertion.SQL, assertion.Args, true); err != nil {
|
||||
return fmt.Errorf("clientpatch: patch %q assertion: %w", patch.ID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
state := make([]uint8, len(p.Patches))
|
||||
var visit func(int) error
|
||||
visit = func(i int) error {
|
||||
if state[i] == 1 {
|
||||
return errors.New("clientpatch: cyclic patch dependencies")
|
||||
}
|
||||
if state[i] == 2 {
|
||||
return nil
|
||||
}
|
||||
state[i] = 1
|
||||
seen := map[string]bool{}
|
||||
patch := p.Patches[i]
|
||||
for _, required := range patch.Requires {
|
||||
j, found := ids[required]
|
||||
if !found || required == patch.ID || seen[required] || p.Patches[j].OwnerUID != 0 && p.Patches[j].OwnerUID != patch.OwnerUID {
|
||||
return fmt.Errorf("clientpatch: patch %q has invalid dependency %q", patch.ID, required)
|
||||
}
|
||||
seen[required] = true
|
||||
if err := visit(j); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
state[i] = 2
|
||||
return nil
|
||||
}
|
||||
for i := range p.Patches {
|
||||
if err := visit(i); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateQuery(sql string, args map[string]any, assertion bool) error {
|
||||
if len(sql) == 0 || len(sql) > 64<<10 || strings.ContainsRune(sql, '\x00') || len(args) > 64 {
|
||||
return errors.New("invalid SQL or argument size")
|
||||
}
|
||||
words := strings.Fields(sql)
|
||||
if len(words) == 0 {
|
||||
return errors.New("empty SQL")
|
||||
}
|
||||
verb := strings.ToUpper(words[0])
|
||||
if assertion && verb != "SELECT" || !assertion && verb != "INSERT" && verb != "UPDATE" && verb != "DELETE" {
|
||||
return errors.New("only INSERT, UPDATE, DELETE data migrations and SELECT assertions are allowed")
|
||||
}
|
||||
for name, value := range args {
|
||||
if !argument.MatchString(name) || strings.EqualFold(name, "owner") {
|
||||
return fmt.Errorf("invalid or reserved argument %q", name)
|
||||
}
|
||||
switch v := value.(type) {
|
||||
case nil, bool, int64, int:
|
||||
case string:
|
||||
if len(v) > 64<<10 {
|
||||
return errors.New("argument string too large")
|
||||
}
|
||||
case json.Number:
|
||||
if _, err := v.Int64(); err != nil {
|
||||
if !strings.ContainsAny(v.String(), ".eE") {
|
||||
return errors.New("integer argument exceeds SQLite signed 64-bit range")
|
||||
}
|
||||
if f, err := v.Float64(); err != nil || math.IsInf(f, 0) || math.IsNaN(f) {
|
||||
return errors.New("invalid numeric argument")
|
||||
}
|
||||
}
|
||||
case float64:
|
||||
if math.IsNaN(v) || math.IsInf(v, 0) {
|
||||
return errors.New("invalid numeric argument")
|
||||
}
|
||||
default:
|
||||
return fmt.Errorf("argument %q is not a SQLite scalar", name)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func decode(raw []byte, value any) error {
|
||||
d := json.NewDecoder(bytes.NewReader(raw))
|
||||
d.DisallowUnknownFields()
|
||||
d.UseNumber()
|
||||
if err := d.Decode(value); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := d.Decode(new(any)); err != io.EOF {
|
||||
return errors.New("clientpatch: trailing JSON data")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func Verify(raw []byte, keys []release.TrustedKey) (Plan, error) {
|
||||
if len(raw) == 0 || len(raw) > MaxPlaintext {
|
||||
return Plan{}, errors.New("clientpatch: signed plan size is invalid")
|
||||
}
|
||||
var envelope Envelope
|
||||
if err := decode(raw, &envelope); err != nil {
|
||||
return Plan{}, fmt.Errorf("clientpatch: envelope: %w", err)
|
||||
}
|
||||
var public []byte
|
||||
for _, key := range keys {
|
||||
if key.ID != envelope.KeyID {
|
||||
continue
|
||||
}
|
||||
var err error
|
||||
public, err = base64.StdEncoding.DecodeString(key.PublicKey)
|
||||
if err != nil || len(public) != ed25519.PublicKeySize || release.KeyID(public) != key.ID {
|
||||
return Plan{}, errors.New("clientpatch: invalid trusted key")
|
||||
}
|
||||
break
|
||||
}
|
||||
if len(public) == 0 {
|
||||
return Plan{}, errors.New("clientpatch: untrusted signing key")
|
||||
}
|
||||
signature, err := base64.StdEncoding.DecodeString(envelope.Signature)
|
||||
if err != nil || !ed25519.Verify(public, append([]byte(SignatureDomain), envelope.Plan...), signature) {
|
||||
return Plan{}, errors.New("clientpatch: invalid signature")
|
||||
}
|
||||
var plan Plan
|
||||
if err := decode(envelope.Plan, &plan); err != nil {
|
||||
return Plan{}, fmt.Errorf("clientpatch: plan: %w", err)
|
||||
}
|
||||
if err := plan.Validate(); err != nil {
|
||||
return Plan{}, err
|
||||
}
|
||||
return plan, nil
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
//go:build !windows
|
||||
|
||||
package util
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"golang.org/x/sys/unix"
|
||||
)
|
||||
|
||||
// TryLockFile takes an exclusive process lock, released when the file closes.
|
||||
func TryLockFile(path string) (*os.File, error) {
|
||||
file, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := unix.Flock(int(file.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil {
|
||||
_ = file.Close()
|
||||
return nil, fmt.Errorf("lock %s: %w", path, err)
|
||||
}
|
||||
return file, nil
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
//go:build windows
|
||||
|
||||
package util
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"golang.org/x/sys/windows"
|
||||
)
|
||||
|
||||
// TryLockFile takes an exclusive process lock, released when the file closes.
|
||||
func TryLockFile(path string) (*os.File, error) {
|
||||
file, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0o600)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var overlapped windows.Overlapped
|
||||
if err := windows.LockFileEx(windows.Handle(file.Fd()), windows.LOCKFILE_EXCLUSIVE_LOCK|windows.LOCKFILE_FAIL_IMMEDIATELY, 0, 1, 0, &overlapped); err != nil {
|
||||
_ = file.Close()
|
||||
return nil, fmt.Errorf("lock %s: %w", path, err)
|
||||
}
|
||||
return file, nil
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package util
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const responseReasonLimit = 300
|
||||
|
||||
// ResponseError describes an unexpected HTTP response together with the
|
||||
// server's own explanation from its body, so the failure names its cause
|
||||
// rather than only a status code. It reads at most a few KiB of the body.
|
||||
func ResponseError(response *http.Response) error {
|
||||
status := response.Status
|
||||
if status == "" {
|
||||
status = fmt.Sprintf("%d %s", response.StatusCode, http.StatusText(response.StatusCode))
|
||||
}
|
||||
raw, _ := io.ReadAll(io.LimitReader(response.Body, 4<<10))
|
||||
if reason := responseReason(raw); reason != "" {
|
||||
return fmt.Errorf("HTTP %s: %s", status, reason)
|
||||
}
|
||||
return fmt.Errorf("HTTP %s (the server gave no reason)", status)
|
||||
}
|
||||
|
||||
func responseReason(raw []byte) string {
|
||||
var document struct {
|
||||
Error string `json:"error"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
text := string(raw)
|
||||
if json.Unmarshal(raw, &document) == nil {
|
||||
text = document.Error
|
||||
if text == "" {
|
||||
text = document.Message
|
||||
}
|
||||
}
|
||||
if !utf8.ValidString(text) || strings.Contains(strings.ToLower(text), "<html") {
|
||||
return ""
|
||||
}
|
||||
text = strings.Join(strings.Fields(text), " ")
|
||||
if utf8.RuneCountInString(text) > responseReasonLimit {
|
||||
text = string([]rune(text)[:responseReasonLimit]) + "…"
|
||||
}
|
||||
return text
|
||||
}
|
||||
@@ -3,12 +3,14 @@ package app
|
||||
import (
|
||||
commonconfig "bd2server/internal/common/config"
|
||||
"bd2server/internal/common/i18n"
|
||||
"bd2server/internal/common/release"
|
||||
"bd2server/internal/common/util"
|
||||
"bd2server/internal/common/versionconfig"
|
||||
"bd2server/internal/server/design/gamedata"
|
||||
"bd2server/internal/server/domain/events/calendar"
|
||||
"bd2server/internal/server/domain/notice"
|
||||
"bd2server/internal/server/gateway/auth"
|
||||
"bd2server/internal/server/gateway/clientpatch"
|
||||
"bd2server/internal/server/gateway/session"
|
||||
"bd2server/internal/server/gateway/transport"
|
||||
"bd2server/internal/server/platform/lifecycle"
|
||||
@@ -169,6 +171,7 @@ func Serve(args []string) (serveErr error) {
|
||||
CommerceManifest: func() any { return design.cashCatalog.Manifest() }, Availability: availability, InstanceID: instanceID, RealtimeTickets: realtimeTickets,
|
||||
StoryCheckpoints: storyCheckpoints{game: game, players: registry}, Console: console.Handler(),
|
||||
SpineRecordings: spineRecordings{players: registry},
|
||||
ClientPatches: clientpatch.New(clientpatch.Config{Root: filepath.Join(c.dataDir, "client-patches"), Origin: strings.TrimRight(consoleOrigin(c), "/"), GameVersion: c.versions.GameVersion, Keys: release.BuiltinChannel().TrustedKeys}),
|
||||
LoginsClosed: func() bool { return loginsClosed(0) != "" },
|
||||
Releases: releaseFiles(filepath.Join(c.dataDir, "releases")),
|
||||
ClientAllowed: compatibility.allowed,
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
package clientpatch
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
patch "bd2server/internal/common/clientpatch"
|
||||
"bd2server/internal/common/release"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Root string
|
||||
Origin string
|
||||
GameVersion string
|
||||
Keys []release.TrustedKey
|
||||
}
|
||||
|
||||
func New(config Config) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
if r.Method != http.MethodPost {
|
||||
w.Header().Set("Allow", http.MethodPost)
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
var request struct {
|
||||
RecipientKey string `json:"recipient_key"`
|
||||
}
|
||||
raw, err := io.ReadAll(io.LimitReader(r.Body, 2049))
|
||||
if err != nil || len(raw) > 2048 {
|
||||
http.Error(w, "invalid patch request size", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(raw))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(&request); err != nil {
|
||||
http.Error(w, "invalid patch request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := decoder.Decode(new(any)); err != io.EOF {
|
||||
http.Error(w, "invalid patch request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
public, err := base64.StdEncoding.DecodeString(request.RecipientKey)
|
||||
if err != nil || len(public) != 32 {
|
||||
http.Error(w, "invalid recipient key", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
file, err := os.Open(filepath.Join(config.Root, "plan.json"))
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
slog.Warn("client patch plan unavailable", "error", err)
|
||||
http.Error(w, "the server cannot open its client patch plan (data/client-patches/plan.json)", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
signed, readErr := io.ReadAll(io.LimitReader(file, patch.MaxPlaintext+1))
|
||||
closeErr := file.Close()
|
||||
if err := errors.Join(readErr, closeErr); err != nil {
|
||||
slog.Warn("client patch plan unreadable", "error", err)
|
||||
http.Error(w, "the server cannot read its client patch plan (data/client-patches/plan.json)", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
plan, err := patch.Verify(signed, config.Keys)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("the server's client patch plan failed signature verification: %w", err)
|
||||
} else if plan.Origin != config.Origin || plan.GameVersion != config.GameVersion {
|
||||
err = fmt.Errorf("the server's client patch plan targets game %s at %s, but this server runs game %s at %s; the operator must re-sign data/client-patches/plan.json",
|
||||
plan.GameVersion, plan.Origin, config.GameVersion, config.Origin)
|
||||
}
|
||||
if err != nil {
|
||||
slog.Warn("client patch plan rejected", "error", err)
|
||||
http.Error(w, err.Error(), http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
encrypted, err := patch.Seal(signed, public)
|
||||
if err != nil {
|
||||
http.Error(w, "recipient key cannot be used", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/vnd.bd2.client-patch")
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="client.bdpatch"`)
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
_, _ = w.Write(encrypted)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
package clientpatch
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
patch "bd2server/internal/common/clientpatch"
|
||||
"bd2server/internal/common/release"
|
||||
)
|
||||
|
||||
func TestDownloadRequiresOfficialAuthorityAndExactServerScope(t *testing.T) {
|
||||
public, private, err := ed25519.GenerateKey(rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key := release.TrustedKey{ID: release.KeyID(public), PublicKey: base64.StdEncoding.EncodeToString(public)}
|
||||
root := t.TempDir()
|
||||
config := Config{Root: root, Origin: "https://example.com", GameVersion: "2.36.7", Keys: []release.TrustedKey{key}}
|
||||
handler := New(config)
|
||||
recipient, err := patch.GenerateRecipient()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, err := json.Marshal(map[string]string{"recipient_key": base64.StdEncoding.EncodeToString(recipient.PublicKey().Bytes())})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
download := func() *httptest.ResponseRecorder {
|
||||
w := httptest.NewRecorder()
|
||||
handler.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/client/patches", bytes.NewReader(body)))
|
||||
return w
|
||||
}
|
||||
if w := download(); w.Code != http.StatusNotFound {
|
||||
t.Fatalf("missing publication was not distinguishable: %d", w.Code)
|
||||
}
|
||||
plan := patch.Plan{Schema: 1, Origin: config.Origin, GameVersion: config.GameVersion, Database: patch.Database, Revision: 1, Patches: []patch.Patch{}}
|
||||
publish := func() []byte {
|
||||
payload, err := json.Marshal(plan)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
signed, err := json.Marshal(patch.Envelope{KeyID: key.ID, Signature: base64.StdEncoding.EncodeToString(ed25519.Sign(private, append([]byte(patch.SignatureDomain), payload...))), Plan: payload})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(root, "plan.json"), signed, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return signed
|
||||
}
|
||||
signed := publish()
|
||||
first, second := download(), download()
|
||||
for _, w := range []*httptest.ResponseRecorder{first, second} {
|
||||
if w.Code != http.StatusOK || w.Header().Get("Cache-Control") != "no-store" || w.Header().Get("Content-Type") != "application/vnd.bd2.client-patch" {
|
||||
t.Fatalf("patch download failed: %d %s", w.Code, w.Body.String())
|
||||
}
|
||||
plain, err := patch.Open(w.Body.Bytes(), recipient)
|
||||
if err != nil || !bytes.Equal(plain, signed) {
|
||||
t.Fatalf("download did not preserve signed bytes: %v", err)
|
||||
}
|
||||
if _, err := patch.Verify(plain, config.Keys); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if bytes.Equal(first.Body.Bytes(), second.Body.Bytes()) {
|
||||
t.Fatal("downloads reused recipient ciphertext")
|
||||
}
|
||||
plan.Origin = "https://another-server.example"
|
||||
publish()
|
||||
if w := download(); w.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("plan for another origin served: %d", w.Code)
|
||||
}
|
||||
plan.Origin = config.Origin
|
||||
plan.GameVersion = "2.36.8"
|
||||
publish()
|
||||
if w := download(); w.Code != http.StatusServiceUnavailable || !strings.Contains(w.Body.String(), "targets game 2.36.8") || !strings.Contains(w.Body.String(), "runs game 2.36.7") {
|
||||
t.Fatalf("plan for another game served or unexplained: %d %q", w.Code, w.Body.String())
|
||||
}
|
||||
plan.GameVersion = config.GameVersion
|
||||
signed = publish()
|
||||
signed = bytes.Replace(signed, []byte(`"revision":1`), []byte(`"revision":2`), 1)
|
||||
if err := os.WriteFile(filepath.Join(root, "plan.json"), signed, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := download(); w.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("modified publication served: %d", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -143,6 +143,7 @@ type HTTP struct {
|
||||
RealtimeTickets http.Handler
|
||||
StoryCheckpoints http.Handler
|
||||
SpineRecordings http.Handler
|
||||
ClientPatches http.Handler
|
||||
// Console is the built-in administration website below /admin/.
|
||||
Console http.Handler
|
||||
// Compatibility is the launcher's view of what this server requires.
|
||||
@@ -163,6 +164,9 @@ func (h HTTP) Handler() http.Handler {
|
||||
mux.HandleFunc("/client/resources", h.clientResources)
|
||||
mux.HandleFunc("/client/runtime", h.clientRuntime)
|
||||
mux.HandleFunc("/client/commerce", h.clientCommerce)
|
||||
if h.ClientPatches != nil {
|
||||
mux.Handle("/client/patches", h.ClientPatches)
|
||||
}
|
||||
if h.UpdateFingerprint != nil {
|
||||
mux.HandleFunc("GET /client/update-fingerprint", func(w http.ResponseWriter, r *http.Request) {
|
||||
raw := h.UpdateFingerprint()
|
||||
|
||||
Reference in new issue
Block a user