first commit
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
HTTP_ADDR=:8080
|
||||
APP_ENV=production
|
||||
DATABASE_PATH=./minecraft-auth.db
|
||||
MINECRAFT_SESSION_TTL=5m
|
||||
MINECRAFT_SERVER_TOKENS=survival=replace-with-a-long-random-token
|
||||
MINECRAFT_LOGIN_URL=https://minecraft.csui.dev/api/v1/minecraft/login
|
||||
CAS_LOGIN_URL=https://sso.ui.ac.id/cas2/login
|
||||
CAS_VALIDATE_URL=https://sso.ui.ac.id/cas2/serviceValidate
|
||||
CAS_SERVICE_URL=https://minecraft.csui.dev/web/sso
|
||||
@@ -0,0 +1,2 @@
|
||||
*.db*
|
||||
.env
|
||||
@@ -0,0 +1,22 @@
|
||||
module oauth-mc-web
|
||||
|
||||
go 1.27
|
||||
|
||||
require (
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
github.com/joho/godotenv v1.5.1
|
||||
modernc.org/sqlite v1.38.2
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/ncruces/go-strftime v0.1.9 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b // indirect
|
||||
golang.org/x/sys v0.34.0 // indirect
|
||||
modernc.org/libc v1.66.3 // indirect
|
||||
modernc.org/mathutil v1.7.1 // indirect
|
||||
modernc.org/memory v1.11.0 // indirect
|
||||
)
|
||||
@@ -0,0 +1,53 @@
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
|
||||
github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
|
||||
github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
|
||||
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b h1:M2rDM6z3Fhozi9O7NWsxAkg/yqS/lQJ6PmkyIV3YP+o=
|
||||
golang.org/x/exp v0.0.0-20250620022241-b7579e27df2b/go.mod h1:3//PLf8L/X+8b4vuAfHzxeRUl04Adcb341+IGKfnqS8=
|
||||
golang.org/x/mod v0.25.0 h1:n7a+ZbQKQA/Ysbyb0/6IbB1H/X41mKgbhfv7AfG/44w=
|
||||
golang.org/x/mod v0.25.0/go.mod h1:IXM97Txy2VM4PJ3gI61r1YEk/gAj6zAHN3AdZt6S9Ww=
|
||||
golang.org/x/sync v0.15.0 h1:KWH3jNZsfyT6xfAfKiz6MRNmd46ByHDYaZ7KSkCtdW8=
|
||||
golang.org/x/sync v0.15.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
|
||||
golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/tools v0.34.0 h1:qIpSLOxeCYGg9TrcJokLBG4KFA6d795g0xkBkiESGlo=
|
||||
golang.org/x/tools v0.34.0/go.mod h1:pAP9OwEaY1CAW3HOmg3hLZC5Z0CCmzjAF2UQMSqNARg=
|
||||
modernc.org/cc/v4 v4.26.2 h1:991HMkLjJzYBIfha6ECZdjrIYz2/1ayr+FL8GN+CNzM=
|
||||
modernc.org/cc/v4 v4.26.2/go.mod h1:uVtb5OGqUKpoLWhqwNQo/8LwvoiEBLvZXIQ/SmO6mL0=
|
||||
modernc.org/ccgo/v4 v4.28.0 h1:rjznn6WWehKq7dG4JtLRKxb52Ecv8OUGah8+Z/SfpNU=
|
||||
modernc.org/ccgo/v4 v4.28.0/go.mod h1:JygV3+9AV6SmPhDasu4JgquwU81XAKLd3OKTUDNOiKE=
|
||||
modernc.org/fileutil v1.3.8 h1:qtzNm7ED75pd1C7WgAGcK4edm4fvhtBsEiI/0NQ54YM=
|
||||
modernc.org/fileutil v1.3.8/go.mod h1:HxmghZSZVAz/LXcMNwZPA/DRrQZEVP9VX0V4LQGQFOc=
|
||||
modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
|
||||
modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
|
||||
modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
|
||||
modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
|
||||
modernc.org/libc v1.66.3 h1:cfCbjTUcdsKyyZZfEUKfoHcP3S0Wkvz3jgSzByEWVCQ=
|
||||
modernc.org/libc v1.66.3/go.mod h1:XD9zO8kt59cANKvHPXpx7yS2ELPheAey0vjIuZOhOU8=
|
||||
modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
|
||||
modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
|
||||
modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
|
||||
modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
|
||||
modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
|
||||
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
||||
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
||||
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
|
||||
modernc.org/sqlite v1.38.2 h1:Aclu7+tgjgcQVShZqim41Bbw9Cho0y/7WzYptXqkEek=
|
||||
modernc.org/sqlite v1.38.2/go.mod h1:cPTJYSlgg3Sfg046yBShXENNtPrWrDX8bsbAQBzgQ5E=
|
||||
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
|
||||
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
|
||||
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
||||
modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
|
||||
@@ -0,0 +1,72 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
AppEnv string
|
||||
DatabasePath string
|
||||
HTTPAddr string
|
||||
MinecraftLoginURL string
|
||||
CASLoginURL string
|
||||
CASValidateURL string
|
||||
CASServiceURL string
|
||||
MinecraftSessionTTL time.Duration
|
||||
MinecraftServerTokens string
|
||||
AllowHTTPService bool
|
||||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
if err := godotenv.Load(); err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return Config{}, fmt.Errorf("load .env: %w", err)
|
||||
}
|
||||
|
||||
cfg := Config{
|
||||
AppEnv: strings.TrimSpace(os.Getenv("APP_ENV")),
|
||||
DatabasePath: os.Getenv("DATABASE_PATH"),
|
||||
HTTPAddr: os.Getenv("HTTP_ADDR"),
|
||||
MinecraftLoginURL: strings.TrimSpace(os.Getenv("MINECRAFT_LOGIN_URL")),
|
||||
CASLoginURL: strings.TrimSpace(os.Getenv("CAS_LOGIN_URL")),
|
||||
CASValidateURL: strings.TrimSpace(os.Getenv("CAS_VALIDATE_URL")),
|
||||
CASServiceURL: strings.TrimSpace(os.Getenv("CAS_SERVICE_URL")),
|
||||
MinecraftServerTokens: os.Getenv("MINECRAFT_SERVER_TOKENS"),
|
||||
}
|
||||
if cfg.AppEnv == "" {
|
||||
cfg.AppEnv = "development"
|
||||
}
|
||||
if cfg.HTTPAddr == "" {
|
||||
cfg.HTTPAddr = ":8080"
|
||||
}
|
||||
if cfg.MinecraftLoginURL == "" {
|
||||
cfg.MinecraftLoginURL = "http://localhost:8080/api/v1/minecraft/login"
|
||||
}
|
||||
if cfg.CASLoginURL == "" {
|
||||
cfg.CASLoginURL = "https://sso.ui.ac.id/cas2/login"
|
||||
}
|
||||
if cfg.CASValidateURL == "" {
|
||||
cfg.CASValidateURL = "https://sso.ui.ac.id/cas2/serviceValidate"
|
||||
}
|
||||
cfg.AllowHTTPService = strings.EqualFold(cfg.AppEnv, "development")
|
||||
|
||||
cfg.MinecraftSessionTTL = 5 * time.Minute
|
||||
if value := strings.TrimSpace(os.Getenv("MINECRAFT_SESSION_TTL")); value != "" {
|
||||
ttl, err := time.ParseDuration(value)
|
||||
if err != nil || ttl <= 0 || ttl > 30*time.Minute {
|
||||
return Config{}, errors.New("invalid MINECRAFT_SESSION_TTL: expected a positive duration no greater than 30m")
|
||||
}
|
||||
cfg.MinecraftSessionTTL = ttl
|
||||
}
|
||||
|
||||
if strings.TrimSpace(cfg.MinecraftServerTokens) == "" {
|
||||
return Config{}, errors.New("missing MINECRAFT_SERVER_TOKENS: configure at least one server credential")
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
_ "embed"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"oauth-mc-web/internal/database/repository"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
type DB struct {
|
||||
sql *sql.DB
|
||||
Queries *repository.Queries
|
||||
}
|
||||
|
||||
type TransactionRunner interface {
|
||||
WithinTransaction(context.Context, func(repository.Querier) error) error
|
||||
}
|
||||
|
||||
//go:embed schema/schema.sql
|
||||
var schema string
|
||||
|
||||
func Open(ctx context.Context, path string) (*DB, error) {
|
||||
if path == "" {
|
||||
path = "minecraft-auth.db"
|
||||
}
|
||||
db, err := sql.Open("sqlite", path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open SQLite database: %w", err)
|
||||
}
|
||||
db.SetMaxOpenConns(1)
|
||||
if _, err := db.ExecContext(ctx, `PRAGMA journal_mode=WAL`); err != nil {
|
||||
return nil, closeWithError(db, fmt.Errorf("configure SQLite database: %w", err))
|
||||
}
|
||||
if _, err := db.ExecContext(ctx, schema); err != nil {
|
||||
return nil, closeWithError(db, fmt.Errorf("initialize SQLite schema: %w", err))
|
||||
}
|
||||
queries := repository.New(db)
|
||||
if err := queries.RestoreAccountBindings(ctx); err != nil {
|
||||
return nil, closeWithError(db, fmt.Errorf("restore existing Minecraft account bindings: %w", err))
|
||||
}
|
||||
return &DB{sql: db, Queries: queries}, nil
|
||||
}
|
||||
|
||||
func closeWithError(db *sql.DB, cause error) error {
|
||||
if err := db.Close(); err != nil {
|
||||
return errors.Join(cause, fmt.Errorf("close database after initialization failure: %w", err))
|
||||
}
|
||||
return cause
|
||||
}
|
||||
|
||||
func (db *DB) Close() error {
|
||||
if db == nil || db.sql == nil {
|
||||
return nil
|
||||
}
|
||||
return db.sql.Close()
|
||||
}
|
||||
|
||||
func (db *DB) WithinTransaction(ctx context.Context, workflow func(repository.Querier) error) error {
|
||||
tx, err := db.sql.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin database transaction: %w", err)
|
||||
}
|
||||
if err := workflow(repository.New(tx)); err != nil {
|
||||
if rollbackErr := tx.Rollback(); rollbackErr != nil {
|
||||
return fmt.Errorf("rollback database transaction after %v: %w", err, rollbackErr)
|
||||
}
|
||||
return err
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
return fmt.Errorf("commit database transaction: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
_ "embed"
|
||||
"errors"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"oauth-mc-web/internal/database/repository"
|
||||
)
|
||||
|
||||
//go:embed migrations/0002_uuid_account_bindings.sql
|
||||
var uuidAccountBindingsMigration string
|
||||
|
||||
func TestWithinTransaction(t *testing.T) {
|
||||
db, err := Open(context.Background(), filepath.Join(t.TempDir(), "test.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := db.Close(); err != nil {
|
||||
t.Errorf("close database: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
if err := db.WithinTransaction(context.Background(), func(queries repository.Querier) error {
|
||||
return queries.InsertAccountBinding(context.Background(), repository.InsertAccountBindingParams{
|
||||
MinecraftNameKey: "committed",
|
||||
MinecraftName: "Committed",
|
||||
AccountSubject: "subject-committed",
|
||||
CreatedAt: "2026-01-01T00:00:00Z",
|
||||
})
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Queries.GetBoundSubjectForName(context.Background(), "committed"); err != nil {
|
||||
t.Fatalf("read committed binding: %v", err)
|
||||
}
|
||||
|
||||
rollbackErr := errors.New("rollback transaction")
|
||||
err = db.WithinTransaction(context.Background(), func(queries repository.Querier) error {
|
||||
if err := queries.InsertAccountBinding(context.Background(), repository.InsertAccountBindingParams{
|
||||
MinecraftNameKey: "rolled-back",
|
||||
MinecraftName: "RolledBack",
|
||||
AccountSubject: "subject-rolled-back",
|
||||
CreatedAt: "2026-01-01T00:00:00Z",
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return rollbackErr
|
||||
})
|
||||
if !errors.Is(err, rollbackErr) {
|
||||
t.Fatalf("expected workflow error, got %v", err)
|
||||
}
|
||||
if _, err := db.Queries.GetBoundSubjectForName(context.Background(), "rolled-back"); !errors.Is(err, sql.ErrNoRows) {
|
||||
t.Fatalf("expected rolled back binding to be absent, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenDoesNotRestoreUnlinkedBindingFromOldSessions(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
path := filepath.Join(t.TempDir(), "test.db")
|
||||
db, err := Open(ctx, path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := db.Close(); err != nil {
|
||||
t.Errorf("close database: %v", err)
|
||||
}
|
||||
})
|
||||
if err := db.WithinTransaction(ctx, func(queries repository.Querier) error {
|
||||
if err := queries.InsertAccountBinding(ctx, repository.InsertAccountBindingParams{
|
||||
MinecraftNameKey: "playername",
|
||||
MinecraftName: "PlayerName",
|
||||
AccountSubject: "subject-1",
|
||||
CreatedAt: "2026-01-01T00:00:00Z",
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := queries.UpsertUUIDAccountBinding(ctx, repository.UpsertUUIDAccountBindingParams{
|
||||
ServerID: "server-a",
|
||||
MinecraftUuid: "123e4567-e89b-12d3-a456-426614174000",
|
||||
MinecraftNameKey: "playername",
|
||||
MinecraftName: "PlayerName",
|
||||
AccountSubject: "subject-1",
|
||||
CreatedAt: "2026-01-01T00:00:00Z",
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := queries.InsertSession(ctx, repository.InsertSessionParams{
|
||||
SessionID: "legacy-session",
|
||||
RequestID: "legacy-request",
|
||||
ServerID: "server-a",
|
||||
MinecraftUuid: "123e4567-e89b-12d3-a456-426614174000",
|
||||
MinecraftName: "PlayerName",
|
||||
Code: "legacy-code",
|
||||
LoginUrl: "https://minecraft.example/login?code=legacy-code",
|
||||
ExpiresAt: "2099-01-01T00:00:00Z",
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
updated, err := queries.ApproveSession(ctx, repository.ApproveSessionParams{
|
||||
AccountSubject: "subject-1",
|
||||
AccountDisplayName: "Player",
|
||||
SessionID: "legacy-session",
|
||||
ServerID: "server-a",
|
||||
ExpiresAt: "2026-01-01T00:00:00Z",
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if updated != 1 {
|
||||
return errors.New("legacy test session was not approved")
|
||||
}
|
||||
if _, err := queries.DeleteUUIDAccountBinding(ctx, repository.DeleteUUIDAccountBindingParams{
|
||||
ServerID: "server-a",
|
||||
MinecraftUuid: "123e4567-e89b-12d3-a456-426614174000",
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = queries.DeleteUnusedAccountBinding(ctx, repository.DeleteUnusedAccountBindingParams{MinecraftNameKey: "playername", AccountSubject: "subject-1"})
|
||||
return err
|
||||
}); err != nil {
|
||||
if closeErr := db.Close(); closeErr != nil {
|
||||
t.Errorf("close database after setup failure: %v", closeErr)
|
||||
}
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db, err = Open(ctx, path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := db.Queries.GetBoundSubjectForName(ctx, "playername"); !errors.Is(err, sql.ErrNoRows) {
|
||||
t.Fatalf("expected unlinked binding to stay removed after reopening, got %v", err)
|
||||
}
|
||||
if _, err := db.Queries.GetBoundSubjectForUUID(ctx, repository.GetBoundSubjectForUUIDParams{
|
||||
ServerID: "server-a",
|
||||
MinecraftUuid: "123e4567-e89b-12d3-a456-426614174000",
|
||||
}); !errors.Is(err, sql.ErrNoRows) {
|
||||
t.Fatalf("expected unlinked UUID binding to stay removed after reopening, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUUIDAccountBindingsMigrationBackfillsRetainedSessions(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, err := Open(ctx, filepath.Join(t.TempDir(), "test.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := db.Close(); err != nil {
|
||||
t.Errorf("close database: %v", err)
|
||||
}
|
||||
})
|
||||
if err := db.Queries.InsertAccountBinding(ctx, repository.InsertAccountBindingParams{
|
||||
MinecraftNameKey: "playername",
|
||||
MinecraftName: "PlayerName",
|
||||
AccountSubject: "subject-1",
|
||||
CreatedAt: "2026-01-01T00:00:00Z",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Queries.InsertSession(ctx, repository.InsertSessionParams{
|
||||
SessionID: "legacy-session",
|
||||
RequestID: "legacy-request",
|
||||
ServerID: "server-a",
|
||||
MinecraftUuid: "123e4567-e89b-12d3-a456-426614174000",
|
||||
MinecraftName: "PlayerName",
|
||||
Code: "legacy-code",
|
||||
LoginUrl: "https://minecraft.example/login?code=legacy-code",
|
||||
ExpiresAt: "2099-01-01T00:00:00Z",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
updated, err := db.Queries.ApproveSession(ctx, repository.ApproveSessionParams{
|
||||
AccountSubject: "subject-1",
|
||||
AccountDisplayName: "Player",
|
||||
SessionID: "legacy-session",
|
||||
ServerID: "server-a",
|
||||
ExpiresAt: "2026-01-01T00:00:00Z",
|
||||
})
|
||||
if err != nil || updated != 1 {
|
||||
t.Fatalf("approve legacy session: updated=%d err=%v", updated, err)
|
||||
}
|
||||
if _, err := db.sql.ExecContext(ctx, uuidAccountBindingsMigration); err != nil {
|
||||
t.Fatalf("apply data migration: %v", err)
|
||||
}
|
||||
if _, err := db.Queries.GetBoundAccountForUUID(ctx, repository.GetBoundAccountForUUIDParams{
|
||||
ServerID: "server-a",
|
||||
MinecraftUuid: "123e4567-e89b-12d3-a456-426614174000",
|
||||
}); err != nil {
|
||||
t.Fatalf("read migrated UUID account binding: %v", err)
|
||||
}
|
||||
request, err := db.Queries.GetLoginRequest(ctx, repository.GetLoginRequestParams{ServerID: "server-a", RequestID: "legacy-request"})
|
||||
if err != nil || request.SessionID != "legacy-session" {
|
||||
t.Fatalf("read migrated login request: session_id=%q err=%v", request.SessionID, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
INSERT OR IGNORE INTO minecraft_uuid_account_bindings(
|
||||
server_id,
|
||||
minecraft_uuid,
|
||||
minecraft_name_key,
|
||||
minecraft_name,
|
||||
account_subject,
|
||||
created_at
|
||||
)
|
||||
SELECT
|
||||
sessions.server_id,
|
||||
lower(trim(sessions.minecraft_uuid)),
|
||||
bindings.minecraft_name_key,
|
||||
sessions.minecraft_name,
|
||||
bindings.account_subject,
|
||||
bindings.created_at
|
||||
FROM minecraft_sessions AS sessions
|
||||
JOIN minecraft_account_bindings AS bindings
|
||||
ON bindings.minecraft_name_key = lower(trim(sessions.minecraft_name))
|
||||
AND bindings.account_subject = lower(trim(sessions.account_subject))
|
||||
WHERE sessions.status = 'approved'
|
||||
AND sessions.account_subject <> ''
|
||||
ORDER BY sessions.expires_at DESC;
|
||||
|
||||
INSERT OR IGNORE INTO minecraft_login_requests(
|
||||
server_id,
|
||||
request_id,
|
||||
minecraft_uuid,
|
||||
session_id,
|
||||
login_url,
|
||||
expires_at
|
||||
)
|
||||
SELECT
|
||||
server_id,
|
||||
request_id,
|
||||
minecraft_uuid,
|
||||
session_id,
|
||||
login_url,
|
||||
expires_at
|
||||
FROM minecraft_sessions
|
||||
ORDER BY expires_at DESC;
|
||||
@@ -0,0 +1,5 @@
|
||||
# Database data migrations
|
||||
|
||||
The application creates the current tables when it opens SQLite. Before upgrading an existing database to UUID-based Minecraft account links and durable login request deduplication, apply `0002_uuid_account_bindings.sql` once after the new tables have been created. Do not apply it automatically at startup.
|
||||
|
||||
The old schema associated accounts with Minecraft names. This migration can recover UUID links only from approved sessions that are still present and match an existing name binding. Links whose session history has already been pruned cannot be mapped reliably; those players need to run `/login` once to establish a UUID link before `/unlink` can remove it.
|
||||
@@ -0,0 +1,31 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
)
|
||||
|
||||
type DBTX interface {
|
||||
ExecContext(context.Context, string, ...interface{}) (sql.Result, error)
|
||||
PrepareContext(context.Context, string) (*sql.Stmt, error)
|
||||
QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error)
|
||||
QueryRowContext(context.Context, string, ...interface{}) *sql.Row
|
||||
}
|
||||
|
||||
func New(db DBTX) *Queries {
|
||||
return &Queries{db: db}
|
||||
}
|
||||
|
||||
type Queries struct {
|
||||
db DBTX
|
||||
}
|
||||
|
||||
func (q *Queries) WithTx(tx *sql.Tx) *Queries {
|
||||
return &Queries{
|
||||
db: tx,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package repository
|
||||
|
||||
import "database/sql"
|
||||
|
||||
var ErrNoRows = sql.ErrNoRows
|
||||
@@ -0,0 +1,52 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
|
||||
package repository
|
||||
|
||||
type MinecraftAccountBinding struct {
|
||||
MinecraftNameKey string
|
||||
MinecraftName string
|
||||
AccountSubject string
|
||||
CreatedAt string
|
||||
}
|
||||
|
||||
type MinecraftLoginRequest struct {
|
||||
ServerID string
|
||||
RequestID string
|
||||
MinecraftUuid string
|
||||
SessionID string
|
||||
LoginUrl string
|
||||
ExpiresAt string
|
||||
}
|
||||
|
||||
type MinecraftSession struct {
|
||||
SessionID string
|
||||
RequestID string
|
||||
ServerID string
|
||||
MinecraftUuid string
|
||||
MinecraftName string
|
||||
Code string
|
||||
LoginUrl string
|
||||
ExpiresAt string
|
||||
Status string
|
||||
AccountSubject string
|
||||
AccountDisplayName string
|
||||
}
|
||||
|
||||
type MinecraftUnlinkRequest struct {
|
||||
ServerID string
|
||||
RequestID string
|
||||
MinecraftUuid string
|
||||
Status string
|
||||
CreatedAt string
|
||||
}
|
||||
|
||||
type MinecraftUuidAccountBinding struct {
|
||||
ServerID string
|
||||
MinecraftUuid string
|
||||
MinecraftNameKey string
|
||||
MinecraftName string
|
||||
AccountSubject string
|
||||
CreatedAt string
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
type Querier interface {
|
||||
AcknowledgeSessionResult(ctx context.Context, arg AcknowledgeSessionResultParams) (int64, error)
|
||||
ApproveSession(ctx context.Context, arg ApproveSessionParams) (int64, error)
|
||||
CancelPendingSession(ctx context.Context, arg CancelPendingSessionParams) (int64, error)
|
||||
CountActivePendingSessions(ctx context.Context, arg CountActivePendingSessionsParams) (int64, error)
|
||||
DeleteClosedSessions(ctx context.Context, expiresAt string) error
|
||||
DeleteClosedSessionsForServer(ctx context.Context, arg DeleteClosedSessionsForServerParams) error
|
||||
DeletePendingSessionsForPlayer(ctx context.Context, arg DeletePendingSessionsForPlayerParams) error
|
||||
DeleteUUIDAccountBinding(ctx context.Context, arg DeleteUUIDAccountBindingParams) (int64, error)
|
||||
DeleteUnusedAccountBinding(ctx context.Context, arg DeleteUnusedAccountBindingParams) (int64, error)
|
||||
DenyPendingSession(ctx context.Context, sessionID string) (int64, error)
|
||||
ExpirePendingSession(ctx context.Context, sessionID string) error
|
||||
ExpirePendingSessions(ctx context.Context, expiresAt string) error
|
||||
ExpirePendingSessionsForServer(ctx context.Context, arg ExpirePendingSessionsForServerParams) error
|
||||
GetBoundAccountForUUID(ctx context.Context, arg GetBoundAccountForUUIDParams) (GetBoundAccountForUUIDRow, error)
|
||||
GetBoundNameForSubject(ctx context.Context, accountSubject string) (string, error)
|
||||
GetBoundSubjectForName(ctx context.Context, minecraftNameKey string) (string, error)
|
||||
GetBoundSubjectForUUID(ctx context.Context, arg GetBoundSubjectForUUIDParams) (string, error)
|
||||
GetBoundUUIDForSubject(ctx context.Context, arg GetBoundUUIDForSubjectParams) (string, error)
|
||||
GetLoginRequest(ctx context.Context, arg GetLoginRequestParams) (GetLoginRequestRow, error)
|
||||
GetPendingSessionByCode(ctx context.Context, code string) (GetPendingSessionByCodeRow, error)
|
||||
GetPendingSessionExpiry(ctx context.Context, code string) (string, error)
|
||||
GetSessionForReplay(ctx context.Context, arg GetSessionForReplayParams) (GetSessionForReplayRow, error)
|
||||
GetSessionResult(ctx context.Context, arg GetSessionResultParams) (GetSessionResultRow, error)
|
||||
GetSessionServerID(ctx context.Context, sessionID string) (string, error)
|
||||
GetUnlinkRequest(ctx context.Context, arg GetUnlinkRequestParams) (GetUnlinkRequestRow, error)
|
||||
InsertAccountBinding(ctx context.Context, arg InsertAccountBindingParams) error
|
||||
InsertLoginRequest(ctx context.Context, arg InsertLoginRequestParams) error
|
||||
InsertSession(ctx context.Context, arg InsertSessionParams) error
|
||||
InsertUnlinkRequest(ctx context.Context, arg InsertUnlinkRequestParams) error
|
||||
ListExpiredSessions(ctx context.Context) ([]ListExpiredSessionsRow, error)
|
||||
ListPendingSessionIDsForPlayer(ctx context.Context, arg ListPendingSessionIDsForPlayerParams) ([]string, error)
|
||||
RestoreAccountBindings(ctx context.Context) error
|
||||
UpsertUUIDAccountBinding(ctx context.Context, arg UpsertUUIDAccountBindingParams) error
|
||||
}
|
||||
|
||||
var _ Querier = (*Queries)(nil)
|
||||
@@ -0,0 +1,114 @@
|
||||
-- name: RestoreAccountBindings :exec
|
||||
INSERT OR IGNORE INTO minecraft_account_bindings(minecraft_name_key, minecraft_name, account_subject, created_at)
|
||||
SELECT minecraft_name_key, minecraft_name, account_subject, created_at FROM minecraft_uuid_account_bindings
|
||||
ORDER BY created_at DESC;
|
||||
|
||||
-- name: ExpirePendingSessions :exec
|
||||
UPDATE minecraft_sessions SET status='expired', code='closed-'||session_id
|
||||
WHERE status='pending' AND expires_at<=?;
|
||||
|
||||
-- name: ListExpiredSessions :many
|
||||
SELECT session_id, minecraft_uuid FROM minecraft_sessions WHERE status='expired';
|
||||
|
||||
-- name: DeleteClosedSessions :exec
|
||||
DELETE FROM minecraft_sessions WHERE status IN ('approved','denied','expired') AND expires_at<=?;
|
||||
|
||||
-- name: AcknowledgeSessionResult :execrows
|
||||
DELETE FROM minecraft_sessions WHERE session_id=? AND server_id=? AND status IN ('approved','denied','expired');
|
||||
|
||||
-- name: CountActivePendingSessions :one
|
||||
SELECT COUNT(*) FROM minecraft_sessions WHERE server_id=? AND minecraft_uuid<>? AND status='pending' AND expires_at>?;
|
||||
|
||||
-- name: ListPendingSessionIDsForPlayer :many
|
||||
SELECT session_id FROM minecraft_sessions WHERE server_id=? AND minecraft_uuid=? AND status='pending';
|
||||
|
||||
-- name: DeletePendingSessionsForPlayer :exec
|
||||
DELETE FROM minecraft_sessions WHERE server_id=? AND minecraft_uuid=? AND status='pending';
|
||||
|
||||
-- name: InsertSession :exec
|
||||
INSERT INTO minecraft_sessions(session_id, request_id, server_id, minecraft_uuid, minecraft_name, code, login_url, expires_at, status)
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?, 'pending');
|
||||
|
||||
-- name: GetLoginRequest :one
|
||||
SELECT minecraft_uuid, session_id, login_url, expires_at
|
||||
FROM minecraft_login_requests WHERE server_id=? AND request_id=?;
|
||||
|
||||
-- name: InsertLoginRequest :exec
|
||||
INSERT INTO minecraft_login_requests(server_id, request_id, minecraft_uuid, session_id, login_url, expires_at)
|
||||
VALUES(?, ?, ?, ?, ?, ?);
|
||||
|
||||
-- name: CancelPendingSession :execrows
|
||||
DELETE FROM minecraft_sessions WHERE session_id=? AND server_id=? AND minecraft_uuid=? AND status='pending';
|
||||
|
||||
-- name: GetSessionForReplay :one
|
||||
SELECT request_id, minecraft_uuid, minecraft_name, login_url, expires_at, status, account_subject, account_display_name
|
||||
FROM minecraft_sessions WHERE session_id=? AND server_id=?;
|
||||
|
||||
-- name: ExpirePendingSession :exec
|
||||
UPDATE minecraft_sessions SET status='expired', code='closed-'||session_id WHERE session_id=? AND status='pending';
|
||||
|
||||
-- name: ExpirePendingSessionsForServer :exec
|
||||
UPDATE minecraft_sessions SET status='expired', code='closed-'||session_id WHERE server_id=? AND status='pending' AND expires_at<=?;
|
||||
|
||||
-- name: DeleteClosedSessionsForServer :exec
|
||||
DELETE FROM minecraft_sessions WHERE server_id=? AND status IN ('approved','denied','expired') AND expires_at<=?;
|
||||
|
||||
-- name: GetSessionResult :one
|
||||
SELECT minecraft_uuid, status, account_subject, account_display_name FROM minecraft_sessions WHERE session_id=? AND server_id=?;
|
||||
|
||||
-- name: GetPendingSessionExpiry :one
|
||||
SELECT expires_at FROM minecraft_sessions WHERE code=? AND status='pending';
|
||||
|
||||
-- name: GetPendingSessionByCode :one
|
||||
SELECT session_id, server_id, minecraft_uuid, minecraft_name, expires_at FROM minecraft_sessions WHERE code=? AND status='pending';
|
||||
|
||||
-- name: DenyPendingSession :execrows
|
||||
UPDATE minecraft_sessions SET status='denied', code='closed-'||session_id WHERE session_id=? AND status='pending';
|
||||
|
||||
-- name: GetBoundSubjectForName :one
|
||||
SELECT account_subject FROM minecraft_account_bindings WHERE minecraft_name_key=?;
|
||||
|
||||
-- name: GetBoundNameForSubject :one
|
||||
SELECT minecraft_name_key FROM minecraft_account_bindings WHERE account_subject=?;
|
||||
|
||||
-- name: GetBoundAccountForUUID :one
|
||||
SELECT minecraft_name_key, account_subject FROM minecraft_uuid_account_bindings WHERE server_id=? AND minecraft_uuid=?;
|
||||
|
||||
-- name: GetBoundSubjectForUUID :one
|
||||
SELECT account_subject FROM minecraft_uuid_account_bindings WHERE server_id=? AND minecraft_uuid=?;
|
||||
|
||||
-- name: GetBoundUUIDForSubject :one
|
||||
SELECT minecraft_uuid FROM minecraft_uuid_account_bindings WHERE server_id=? AND account_subject=?;
|
||||
|
||||
-- name: InsertAccountBinding :exec
|
||||
INSERT INTO minecraft_account_bindings(minecraft_name_key, minecraft_name, account_subject, created_at) VALUES(?, ?, ?, ?);
|
||||
|
||||
-- name: UpsertUUIDAccountBinding :exec
|
||||
INSERT INTO minecraft_uuid_account_bindings(server_id, minecraft_uuid, minecraft_name_key, minecraft_name, account_subject, created_at)
|
||||
VALUES(?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(server_id, minecraft_uuid) DO UPDATE SET minecraft_name_key=excluded.minecraft_name_key, minecraft_name=excluded.minecraft_name, created_at=excluded.created_at;
|
||||
|
||||
-- name: DeleteUUIDAccountBinding :execrows
|
||||
DELETE FROM minecraft_uuid_account_bindings WHERE server_id=? AND minecraft_uuid=?;
|
||||
|
||||
-- name: DeleteUnusedAccountBinding :execrows
|
||||
DELETE FROM minecraft_account_bindings
|
||||
WHERE minecraft_account_bindings.minecraft_name_key=? AND minecraft_account_bindings.account_subject=?
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM minecraft_uuid_account_bindings
|
||||
WHERE minecraft_uuid_account_bindings.minecraft_name_key=minecraft_account_bindings.minecraft_name_key
|
||||
AND minecraft_uuid_account_bindings.account_subject=minecraft_account_bindings.account_subject
|
||||
);
|
||||
|
||||
-- name: GetUnlinkRequest :one
|
||||
SELECT minecraft_uuid, status FROM minecraft_unlink_requests WHERE server_id=? AND request_id=?;
|
||||
|
||||
-- name: InsertUnlinkRequest :exec
|
||||
INSERT INTO minecraft_unlink_requests(server_id, request_id, minecraft_uuid, status, created_at) VALUES(?, ?, ?, ?, ?);
|
||||
|
||||
-- name: ApproveSession :execrows
|
||||
UPDATE minecraft_sessions SET status='approved', code='closed-'||session_id, account_subject=?, account_display_name=?
|
||||
WHERE session_id=? AND server_id=? AND status='pending' AND expires_at>?;
|
||||
|
||||
-- name: GetSessionServerID :one
|
||||
SELECT server_id FROM minecraft_sessions WHERE session_id=?;
|
||||
@@ -0,0 +1,650 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: query.sql
|
||||
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
)
|
||||
|
||||
const acknowledgeSessionResult = `-- name: AcknowledgeSessionResult :execrows
|
||||
DELETE FROM minecraft_sessions WHERE session_id=? AND server_id=? AND status IN ('approved','denied','expired')
|
||||
`
|
||||
|
||||
type AcknowledgeSessionResultParams struct {
|
||||
SessionID string
|
||||
ServerID string
|
||||
}
|
||||
|
||||
func (q *Queries) AcknowledgeSessionResult(ctx context.Context, arg AcknowledgeSessionResultParams) (int64, error) {
|
||||
result, err := q.db.ExecContext(ctx, acknowledgeSessionResult, arg.SessionID, arg.ServerID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected()
|
||||
}
|
||||
|
||||
const approveSession = `-- name: ApproveSession :execrows
|
||||
UPDATE minecraft_sessions SET status='approved', code='closed-'||session_id, account_subject=?, account_display_name=?
|
||||
WHERE session_id=? AND server_id=? AND status='pending' AND expires_at>?
|
||||
`
|
||||
|
||||
type ApproveSessionParams struct {
|
||||
AccountSubject string
|
||||
AccountDisplayName string
|
||||
SessionID string
|
||||
ServerID string
|
||||
ExpiresAt string
|
||||
}
|
||||
|
||||
func (q *Queries) ApproveSession(ctx context.Context, arg ApproveSessionParams) (int64, error) {
|
||||
result, err := q.db.ExecContext(ctx, approveSession,
|
||||
arg.AccountSubject,
|
||||
arg.AccountDisplayName,
|
||||
arg.SessionID,
|
||||
arg.ServerID,
|
||||
arg.ExpiresAt,
|
||||
)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected()
|
||||
}
|
||||
|
||||
const cancelPendingSession = `-- name: CancelPendingSession :execrows
|
||||
DELETE FROM minecraft_sessions WHERE session_id=? AND server_id=? AND minecraft_uuid=? AND status='pending'
|
||||
`
|
||||
|
||||
type CancelPendingSessionParams struct {
|
||||
SessionID string
|
||||
ServerID string
|
||||
MinecraftUuid string
|
||||
}
|
||||
|
||||
func (q *Queries) CancelPendingSession(ctx context.Context, arg CancelPendingSessionParams) (int64, error) {
|
||||
result, err := q.db.ExecContext(ctx, cancelPendingSession, arg.SessionID, arg.ServerID, arg.MinecraftUuid)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected()
|
||||
}
|
||||
|
||||
const countActivePendingSessions = `-- name: CountActivePendingSessions :one
|
||||
SELECT COUNT(*) FROM minecraft_sessions WHERE server_id=? AND minecraft_uuid<>? AND status='pending' AND expires_at>?
|
||||
`
|
||||
|
||||
type CountActivePendingSessionsParams struct {
|
||||
ServerID string
|
||||
MinecraftUuid string
|
||||
ExpiresAt string
|
||||
}
|
||||
|
||||
func (q *Queries) CountActivePendingSessions(ctx context.Context, arg CountActivePendingSessionsParams) (int64, error) {
|
||||
row := q.db.QueryRowContext(ctx, countActivePendingSessions, arg.ServerID, arg.MinecraftUuid, arg.ExpiresAt)
|
||||
var count int64
|
||||
err := row.Scan(&count)
|
||||
return count, err
|
||||
}
|
||||
|
||||
const deleteClosedSessions = `-- name: DeleteClosedSessions :exec
|
||||
DELETE FROM minecraft_sessions WHERE status IN ('approved','denied','expired') AND expires_at<=?
|
||||
`
|
||||
|
||||
func (q *Queries) DeleteClosedSessions(ctx context.Context, expiresAt string) error {
|
||||
_, err := q.db.ExecContext(ctx, deleteClosedSessions, expiresAt)
|
||||
return err
|
||||
}
|
||||
|
||||
const deleteClosedSessionsForServer = `-- name: DeleteClosedSessionsForServer :exec
|
||||
DELETE FROM minecraft_sessions WHERE server_id=? AND status IN ('approved','denied','expired') AND expires_at<=?
|
||||
`
|
||||
|
||||
type DeleteClosedSessionsForServerParams struct {
|
||||
ServerID string
|
||||
ExpiresAt string
|
||||
}
|
||||
|
||||
func (q *Queries) DeleteClosedSessionsForServer(ctx context.Context, arg DeleteClosedSessionsForServerParams) error {
|
||||
_, err := q.db.ExecContext(ctx, deleteClosedSessionsForServer, arg.ServerID, arg.ExpiresAt)
|
||||
return err
|
||||
}
|
||||
|
||||
const deletePendingSessionsForPlayer = `-- name: DeletePendingSessionsForPlayer :exec
|
||||
DELETE FROM minecraft_sessions WHERE server_id=? AND minecraft_uuid=? AND status='pending'
|
||||
`
|
||||
|
||||
type DeletePendingSessionsForPlayerParams struct {
|
||||
ServerID string
|
||||
MinecraftUuid string
|
||||
}
|
||||
|
||||
func (q *Queries) DeletePendingSessionsForPlayer(ctx context.Context, arg DeletePendingSessionsForPlayerParams) error {
|
||||
_, err := q.db.ExecContext(ctx, deletePendingSessionsForPlayer, arg.ServerID, arg.MinecraftUuid)
|
||||
return err
|
||||
}
|
||||
|
||||
const deleteUUIDAccountBinding = `-- name: DeleteUUIDAccountBinding :execrows
|
||||
DELETE FROM minecraft_uuid_account_bindings WHERE server_id=? AND minecraft_uuid=?
|
||||
`
|
||||
|
||||
type DeleteUUIDAccountBindingParams struct {
|
||||
ServerID string
|
||||
MinecraftUuid string
|
||||
}
|
||||
|
||||
func (q *Queries) DeleteUUIDAccountBinding(ctx context.Context, arg DeleteUUIDAccountBindingParams) (int64, error) {
|
||||
result, err := q.db.ExecContext(ctx, deleteUUIDAccountBinding, arg.ServerID, arg.MinecraftUuid)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected()
|
||||
}
|
||||
|
||||
const deleteUnusedAccountBinding = `-- name: DeleteUnusedAccountBinding :execrows
|
||||
DELETE FROM minecraft_account_bindings
|
||||
WHERE minecraft_account_bindings.minecraft_name_key=? AND minecraft_account_bindings.account_subject=?
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM minecraft_uuid_account_bindings
|
||||
WHERE minecraft_uuid_account_bindings.minecraft_name_key=minecraft_account_bindings.minecraft_name_key
|
||||
AND minecraft_uuid_account_bindings.account_subject=minecraft_account_bindings.account_subject
|
||||
)
|
||||
`
|
||||
|
||||
type DeleteUnusedAccountBindingParams struct {
|
||||
MinecraftNameKey string
|
||||
AccountSubject string
|
||||
}
|
||||
|
||||
func (q *Queries) DeleteUnusedAccountBinding(ctx context.Context, arg DeleteUnusedAccountBindingParams) (int64, error) {
|
||||
result, err := q.db.ExecContext(ctx, deleteUnusedAccountBinding, arg.MinecraftNameKey, arg.AccountSubject)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected()
|
||||
}
|
||||
|
||||
const denyPendingSession = `-- name: DenyPendingSession :execrows
|
||||
UPDATE minecraft_sessions SET status='denied', code='closed-'||session_id WHERE session_id=? AND status='pending'
|
||||
`
|
||||
|
||||
func (q *Queries) DenyPendingSession(ctx context.Context, sessionID string) (int64, error) {
|
||||
result, err := q.db.ExecContext(ctx, denyPendingSession, sessionID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected()
|
||||
}
|
||||
|
||||
const expirePendingSession = `-- name: ExpirePendingSession :exec
|
||||
UPDATE minecraft_sessions SET status='expired', code='closed-'||session_id WHERE session_id=? AND status='pending'
|
||||
`
|
||||
|
||||
func (q *Queries) ExpirePendingSession(ctx context.Context, sessionID string) error {
|
||||
_, err := q.db.ExecContext(ctx, expirePendingSession, sessionID)
|
||||
return err
|
||||
}
|
||||
|
||||
const expirePendingSessions = `-- name: ExpirePendingSessions :exec
|
||||
UPDATE minecraft_sessions SET status='expired', code='closed-'||session_id
|
||||
WHERE status='pending' AND expires_at<=?
|
||||
`
|
||||
|
||||
func (q *Queries) ExpirePendingSessions(ctx context.Context, expiresAt string) error {
|
||||
_, err := q.db.ExecContext(ctx, expirePendingSessions, expiresAt)
|
||||
return err
|
||||
}
|
||||
|
||||
const expirePendingSessionsForServer = `-- name: ExpirePendingSessionsForServer :exec
|
||||
UPDATE minecraft_sessions SET status='expired', code='closed-'||session_id WHERE server_id=? AND status='pending' AND expires_at<=?
|
||||
`
|
||||
|
||||
type ExpirePendingSessionsForServerParams struct {
|
||||
ServerID string
|
||||
ExpiresAt string
|
||||
}
|
||||
|
||||
func (q *Queries) ExpirePendingSessionsForServer(ctx context.Context, arg ExpirePendingSessionsForServerParams) error {
|
||||
_, err := q.db.ExecContext(ctx, expirePendingSessionsForServer, arg.ServerID, arg.ExpiresAt)
|
||||
return err
|
||||
}
|
||||
|
||||
const getBoundAccountForUUID = `-- name: GetBoundAccountForUUID :one
|
||||
SELECT minecraft_name_key, account_subject FROM minecraft_uuid_account_bindings WHERE server_id=? AND minecraft_uuid=?
|
||||
`
|
||||
|
||||
type GetBoundAccountForUUIDParams struct {
|
||||
ServerID string
|
||||
MinecraftUuid string
|
||||
}
|
||||
|
||||
type GetBoundAccountForUUIDRow struct {
|
||||
MinecraftNameKey string
|
||||
AccountSubject string
|
||||
}
|
||||
|
||||
func (q *Queries) GetBoundAccountForUUID(ctx context.Context, arg GetBoundAccountForUUIDParams) (GetBoundAccountForUUIDRow, error) {
|
||||
row := q.db.QueryRowContext(ctx, getBoundAccountForUUID, arg.ServerID, arg.MinecraftUuid)
|
||||
var i GetBoundAccountForUUIDRow
|
||||
err := row.Scan(&i.MinecraftNameKey, &i.AccountSubject)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getBoundNameForSubject = `-- name: GetBoundNameForSubject :one
|
||||
SELECT minecraft_name_key FROM minecraft_account_bindings WHERE account_subject=?
|
||||
`
|
||||
|
||||
func (q *Queries) GetBoundNameForSubject(ctx context.Context, accountSubject string) (string, error) {
|
||||
row := q.db.QueryRowContext(ctx, getBoundNameForSubject, accountSubject)
|
||||
var minecraft_name_key string
|
||||
err := row.Scan(&minecraft_name_key)
|
||||
return minecraft_name_key, err
|
||||
}
|
||||
|
||||
const getBoundSubjectForName = `-- name: GetBoundSubjectForName :one
|
||||
SELECT account_subject FROM minecraft_account_bindings WHERE minecraft_name_key=?
|
||||
`
|
||||
|
||||
func (q *Queries) GetBoundSubjectForName(ctx context.Context, minecraftNameKey string) (string, error) {
|
||||
row := q.db.QueryRowContext(ctx, getBoundSubjectForName, minecraftNameKey)
|
||||
var account_subject string
|
||||
err := row.Scan(&account_subject)
|
||||
return account_subject, err
|
||||
}
|
||||
|
||||
const getBoundSubjectForUUID = `-- name: GetBoundSubjectForUUID :one
|
||||
SELECT account_subject FROM minecraft_uuid_account_bindings WHERE server_id=? AND minecraft_uuid=?
|
||||
`
|
||||
|
||||
type GetBoundSubjectForUUIDParams struct {
|
||||
ServerID string
|
||||
MinecraftUuid string
|
||||
}
|
||||
|
||||
func (q *Queries) GetBoundSubjectForUUID(ctx context.Context, arg GetBoundSubjectForUUIDParams) (string, error) {
|
||||
row := q.db.QueryRowContext(ctx, getBoundSubjectForUUID, arg.ServerID, arg.MinecraftUuid)
|
||||
var account_subject string
|
||||
err := row.Scan(&account_subject)
|
||||
return account_subject, err
|
||||
}
|
||||
|
||||
const getBoundUUIDForSubject = `-- name: GetBoundUUIDForSubject :one
|
||||
SELECT minecraft_uuid FROM minecraft_uuid_account_bindings WHERE server_id=? AND account_subject=?
|
||||
`
|
||||
|
||||
type GetBoundUUIDForSubjectParams struct {
|
||||
ServerID string
|
||||
AccountSubject string
|
||||
}
|
||||
|
||||
func (q *Queries) GetBoundUUIDForSubject(ctx context.Context, arg GetBoundUUIDForSubjectParams) (string, error) {
|
||||
row := q.db.QueryRowContext(ctx, getBoundUUIDForSubject, arg.ServerID, arg.AccountSubject)
|
||||
var minecraft_uuid string
|
||||
err := row.Scan(&minecraft_uuid)
|
||||
return minecraft_uuid, err
|
||||
}
|
||||
|
||||
const getLoginRequest = `-- name: GetLoginRequest :one
|
||||
SELECT minecraft_uuid, session_id, login_url, expires_at
|
||||
FROM minecraft_login_requests WHERE server_id=? AND request_id=?
|
||||
`
|
||||
|
||||
type GetLoginRequestParams struct {
|
||||
ServerID string
|
||||
RequestID string
|
||||
}
|
||||
|
||||
type GetLoginRequestRow struct {
|
||||
MinecraftUuid string
|
||||
SessionID string
|
||||
LoginUrl string
|
||||
ExpiresAt string
|
||||
}
|
||||
|
||||
func (q *Queries) GetLoginRequest(ctx context.Context, arg GetLoginRequestParams) (GetLoginRequestRow, error) {
|
||||
row := q.db.QueryRowContext(ctx, getLoginRequest, arg.ServerID, arg.RequestID)
|
||||
var i GetLoginRequestRow
|
||||
err := row.Scan(
|
||||
&i.MinecraftUuid,
|
||||
&i.SessionID,
|
||||
&i.LoginUrl,
|
||||
&i.ExpiresAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getPendingSessionByCode = `-- name: GetPendingSessionByCode :one
|
||||
SELECT session_id, server_id, minecraft_uuid, minecraft_name, expires_at FROM minecraft_sessions WHERE code=? AND status='pending'
|
||||
`
|
||||
|
||||
type GetPendingSessionByCodeRow struct {
|
||||
SessionID string
|
||||
ServerID string
|
||||
MinecraftUuid string
|
||||
MinecraftName string
|
||||
ExpiresAt string
|
||||
}
|
||||
|
||||
func (q *Queries) GetPendingSessionByCode(ctx context.Context, code string) (GetPendingSessionByCodeRow, error) {
|
||||
row := q.db.QueryRowContext(ctx, getPendingSessionByCode, code)
|
||||
var i GetPendingSessionByCodeRow
|
||||
err := row.Scan(
|
||||
&i.SessionID,
|
||||
&i.ServerID,
|
||||
&i.MinecraftUuid,
|
||||
&i.MinecraftName,
|
||||
&i.ExpiresAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getPendingSessionExpiry = `-- name: GetPendingSessionExpiry :one
|
||||
SELECT expires_at FROM minecraft_sessions WHERE code=? AND status='pending'
|
||||
`
|
||||
|
||||
func (q *Queries) GetPendingSessionExpiry(ctx context.Context, code string) (string, error) {
|
||||
row := q.db.QueryRowContext(ctx, getPendingSessionExpiry, code)
|
||||
var expires_at string
|
||||
err := row.Scan(&expires_at)
|
||||
return expires_at, err
|
||||
}
|
||||
|
||||
const getSessionForReplay = `-- name: GetSessionForReplay :one
|
||||
SELECT request_id, minecraft_uuid, minecraft_name, login_url, expires_at, status, account_subject, account_display_name
|
||||
FROM minecraft_sessions WHERE session_id=? AND server_id=?
|
||||
`
|
||||
|
||||
type GetSessionForReplayParams struct {
|
||||
SessionID string
|
||||
ServerID string
|
||||
}
|
||||
|
||||
type GetSessionForReplayRow struct {
|
||||
RequestID string
|
||||
MinecraftUuid string
|
||||
MinecraftName string
|
||||
LoginUrl string
|
||||
ExpiresAt string
|
||||
Status string
|
||||
AccountSubject string
|
||||
AccountDisplayName string
|
||||
}
|
||||
|
||||
func (q *Queries) GetSessionForReplay(ctx context.Context, arg GetSessionForReplayParams) (GetSessionForReplayRow, error) {
|
||||
row := q.db.QueryRowContext(ctx, getSessionForReplay, arg.SessionID, arg.ServerID)
|
||||
var i GetSessionForReplayRow
|
||||
err := row.Scan(
|
||||
&i.RequestID,
|
||||
&i.MinecraftUuid,
|
||||
&i.MinecraftName,
|
||||
&i.LoginUrl,
|
||||
&i.ExpiresAt,
|
||||
&i.Status,
|
||||
&i.AccountSubject,
|
||||
&i.AccountDisplayName,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getSessionResult = `-- name: GetSessionResult :one
|
||||
SELECT minecraft_uuid, status, account_subject, account_display_name FROM minecraft_sessions WHERE session_id=? AND server_id=?
|
||||
`
|
||||
|
||||
type GetSessionResultParams struct {
|
||||
SessionID string
|
||||
ServerID string
|
||||
}
|
||||
|
||||
type GetSessionResultRow struct {
|
||||
MinecraftUuid string
|
||||
Status string
|
||||
AccountSubject string
|
||||
AccountDisplayName string
|
||||
}
|
||||
|
||||
func (q *Queries) GetSessionResult(ctx context.Context, arg GetSessionResultParams) (GetSessionResultRow, error) {
|
||||
row := q.db.QueryRowContext(ctx, getSessionResult, arg.SessionID, arg.ServerID)
|
||||
var i GetSessionResultRow
|
||||
err := row.Scan(
|
||||
&i.MinecraftUuid,
|
||||
&i.Status,
|
||||
&i.AccountSubject,
|
||||
&i.AccountDisplayName,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getSessionServerID = `-- name: GetSessionServerID :one
|
||||
SELECT server_id FROM minecraft_sessions WHERE session_id=?
|
||||
`
|
||||
|
||||
func (q *Queries) GetSessionServerID(ctx context.Context, sessionID string) (string, error) {
|
||||
row := q.db.QueryRowContext(ctx, getSessionServerID, sessionID)
|
||||
var server_id string
|
||||
err := row.Scan(&server_id)
|
||||
return server_id, err
|
||||
}
|
||||
|
||||
const getUnlinkRequest = `-- name: GetUnlinkRequest :one
|
||||
SELECT minecraft_uuid, status FROM minecraft_unlink_requests WHERE server_id=? AND request_id=?
|
||||
`
|
||||
|
||||
type GetUnlinkRequestParams struct {
|
||||
ServerID string
|
||||
RequestID string
|
||||
}
|
||||
|
||||
type GetUnlinkRequestRow struct {
|
||||
MinecraftUuid string
|
||||
Status string
|
||||
}
|
||||
|
||||
func (q *Queries) GetUnlinkRequest(ctx context.Context, arg GetUnlinkRequestParams) (GetUnlinkRequestRow, error) {
|
||||
row := q.db.QueryRowContext(ctx, getUnlinkRequest, arg.ServerID, arg.RequestID)
|
||||
var i GetUnlinkRequestRow
|
||||
err := row.Scan(&i.MinecraftUuid, &i.Status)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const insertAccountBinding = `-- name: InsertAccountBinding :exec
|
||||
INSERT INTO minecraft_account_bindings(minecraft_name_key, minecraft_name, account_subject, created_at) VALUES(?, ?, ?, ?)
|
||||
`
|
||||
|
||||
type InsertAccountBindingParams struct {
|
||||
MinecraftNameKey string
|
||||
MinecraftName string
|
||||
AccountSubject string
|
||||
CreatedAt string
|
||||
}
|
||||
|
||||
func (q *Queries) InsertAccountBinding(ctx context.Context, arg InsertAccountBindingParams) error {
|
||||
_, err := q.db.ExecContext(ctx, insertAccountBinding,
|
||||
arg.MinecraftNameKey,
|
||||
arg.MinecraftName,
|
||||
arg.AccountSubject,
|
||||
arg.CreatedAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertLoginRequest = `-- name: InsertLoginRequest :exec
|
||||
INSERT INTO minecraft_login_requests(server_id, request_id, minecraft_uuid, session_id, login_url, expires_at)
|
||||
VALUES(?, ?, ?, ?, ?, ?)
|
||||
`
|
||||
|
||||
type InsertLoginRequestParams struct {
|
||||
ServerID string
|
||||
RequestID string
|
||||
MinecraftUuid string
|
||||
SessionID string
|
||||
LoginUrl string
|
||||
ExpiresAt string
|
||||
}
|
||||
|
||||
func (q *Queries) InsertLoginRequest(ctx context.Context, arg InsertLoginRequestParams) error {
|
||||
_, err := q.db.ExecContext(ctx, insertLoginRequest,
|
||||
arg.ServerID,
|
||||
arg.RequestID,
|
||||
arg.MinecraftUuid,
|
||||
arg.SessionID,
|
||||
arg.LoginUrl,
|
||||
arg.ExpiresAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertSession = `-- name: InsertSession :exec
|
||||
INSERT INTO minecraft_sessions(session_id, request_id, server_id, minecraft_uuid, minecraft_name, code, login_url, expires_at, status)
|
||||
VALUES(?, ?, ?, ?, ?, ?, ?, ?, 'pending')
|
||||
`
|
||||
|
||||
type InsertSessionParams struct {
|
||||
SessionID string
|
||||
RequestID string
|
||||
ServerID string
|
||||
MinecraftUuid string
|
||||
MinecraftName string
|
||||
Code string
|
||||
LoginUrl string
|
||||
ExpiresAt string
|
||||
}
|
||||
|
||||
func (q *Queries) InsertSession(ctx context.Context, arg InsertSessionParams) error {
|
||||
_, err := q.db.ExecContext(ctx, insertSession,
|
||||
arg.SessionID,
|
||||
arg.RequestID,
|
||||
arg.ServerID,
|
||||
arg.MinecraftUuid,
|
||||
arg.MinecraftName,
|
||||
arg.Code,
|
||||
arg.LoginUrl,
|
||||
arg.ExpiresAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const insertUnlinkRequest = `-- name: InsertUnlinkRequest :exec
|
||||
INSERT INTO minecraft_unlink_requests(server_id, request_id, minecraft_uuid, status, created_at) VALUES(?, ?, ?, ?, ?)
|
||||
`
|
||||
|
||||
type InsertUnlinkRequestParams struct {
|
||||
ServerID string
|
||||
RequestID string
|
||||
MinecraftUuid string
|
||||
Status string
|
||||
CreatedAt string
|
||||
}
|
||||
|
||||
func (q *Queries) InsertUnlinkRequest(ctx context.Context, arg InsertUnlinkRequestParams) error {
|
||||
_, err := q.db.ExecContext(ctx, insertUnlinkRequest,
|
||||
arg.ServerID,
|
||||
arg.RequestID,
|
||||
arg.MinecraftUuid,
|
||||
arg.Status,
|
||||
arg.CreatedAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const listExpiredSessions = `-- name: ListExpiredSessions :many
|
||||
SELECT session_id, minecraft_uuid FROM minecraft_sessions WHERE status='expired'
|
||||
`
|
||||
|
||||
type ListExpiredSessionsRow struct {
|
||||
SessionID string
|
||||
MinecraftUuid string
|
||||
}
|
||||
|
||||
func (q *Queries) ListExpiredSessions(ctx context.Context) ([]ListExpiredSessionsRow, error) {
|
||||
rows, err := q.db.QueryContext(ctx, listExpiredSessions)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []ListExpiredSessionsRow
|
||||
for rows.Next() {
|
||||
var i ListExpiredSessionsRow
|
||||
if err := rows.Scan(&i.SessionID, &i.MinecraftUuid); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listPendingSessionIDsForPlayer = `-- name: ListPendingSessionIDsForPlayer :many
|
||||
SELECT session_id FROM minecraft_sessions WHERE server_id=? AND minecraft_uuid=? AND status='pending'
|
||||
`
|
||||
|
||||
type ListPendingSessionIDsForPlayerParams struct {
|
||||
ServerID string
|
||||
MinecraftUuid string
|
||||
}
|
||||
|
||||
func (q *Queries) ListPendingSessionIDsForPlayer(ctx context.Context, arg ListPendingSessionIDsForPlayerParams) ([]string, error) {
|
||||
rows, err := q.db.QueryContext(ctx, listPendingSessionIDsForPlayer, arg.ServerID, arg.MinecraftUuid)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var items []string
|
||||
for rows.Next() {
|
||||
var session_id string
|
||||
if err := rows.Scan(&session_id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, session_id)
|
||||
}
|
||||
if err := rows.Close(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const restoreAccountBindings = `-- name: RestoreAccountBindings :exec
|
||||
INSERT OR IGNORE INTO minecraft_account_bindings(minecraft_name_key, minecraft_name, account_subject, created_at)
|
||||
SELECT minecraft_name_key, minecraft_name, account_subject, created_at FROM minecraft_uuid_account_bindings
|
||||
ORDER BY created_at DESC
|
||||
`
|
||||
|
||||
func (q *Queries) RestoreAccountBindings(ctx context.Context) error {
|
||||
_, err := q.db.ExecContext(ctx, restoreAccountBindings)
|
||||
return err
|
||||
}
|
||||
|
||||
const upsertUUIDAccountBinding = `-- name: UpsertUUIDAccountBinding :exec
|
||||
INSERT INTO minecraft_uuid_account_bindings(server_id, minecraft_uuid, minecraft_name_key, minecraft_name, account_subject, created_at)
|
||||
VALUES(?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(server_id, minecraft_uuid) DO UPDATE SET minecraft_name_key=excluded.minecraft_name_key, minecraft_name=excluded.minecraft_name, created_at=excluded.created_at
|
||||
`
|
||||
|
||||
type UpsertUUIDAccountBindingParams struct {
|
||||
ServerID string
|
||||
MinecraftUuid string
|
||||
MinecraftNameKey string
|
||||
MinecraftName string
|
||||
AccountSubject string
|
||||
CreatedAt string
|
||||
}
|
||||
|
||||
func (q *Queries) UpsertUUIDAccountBinding(ctx context.Context, arg UpsertUUIDAccountBindingParams) error {
|
||||
_, err := q.db.ExecContext(ctx, upsertUUIDAccountBinding,
|
||||
arg.ServerID,
|
||||
arg.MinecraftUuid,
|
||||
arg.MinecraftNameKey,
|
||||
arg.MinecraftName,
|
||||
arg.AccountSubject,
|
||||
arg.CreatedAt,
|
||||
)
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
CREATE TABLE IF NOT EXISTS minecraft_sessions (
|
||||
session_id TEXT PRIMARY KEY,
|
||||
request_id TEXT NOT NULL,
|
||||
server_id TEXT NOT NULL,
|
||||
minecraft_uuid TEXT NOT NULL,
|
||||
minecraft_name TEXT NOT NULL,
|
||||
code TEXT NOT NULL UNIQUE,
|
||||
login_url TEXT NOT NULL,
|
||||
expires_at TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
account_subject TEXT NOT NULL DEFAULT '',
|
||||
account_display_name TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS minecraft_sessions_server_player ON minecraft_sessions(server_id, minecraft_uuid, status);
|
||||
CREATE INDEX IF NOT EXISTS minecraft_sessions_server_status ON minecraft_sessions(server_id, status);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS minecraft_login_requests (
|
||||
server_id TEXT NOT NULL,
|
||||
request_id TEXT NOT NULL,
|
||||
minecraft_uuid TEXT NOT NULL,
|
||||
session_id TEXT NOT NULL,
|
||||
login_url TEXT NOT NULL,
|
||||
expires_at TEXT NOT NULL,
|
||||
PRIMARY KEY (server_id, request_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS minecraft_account_bindings (
|
||||
minecraft_name_key TEXT PRIMARY KEY,
|
||||
minecraft_name TEXT NOT NULL,
|
||||
account_subject TEXT NOT NULL UNIQUE,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS minecraft_uuid_account_bindings (
|
||||
server_id TEXT NOT NULL,
|
||||
minecraft_uuid TEXT NOT NULL,
|
||||
minecraft_name_key TEXT NOT NULL,
|
||||
minecraft_name TEXT NOT NULL,
|
||||
account_subject TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
PRIMARY KEY (server_id, minecraft_uuid),
|
||||
UNIQUE (server_id, account_subject)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS minecraft_unlink_requests (
|
||||
server_id TEXT NOT NULL,
|
||||
request_id TEXT NOT NULL,
|
||||
minecraft_uuid TEXT NOT NULL,
|
||||
status TEXT NOT NULL CHECK (status IN ('unlinked', 'not_linked')),
|
||||
created_at TEXT NOT NULL,
|
||||
PRIMARY KEY (server_id, request_id)
|
||||
);
|
||||
@@ -0,0 +1,96 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
func Logging(logger *slog.Logger) func(http.Handler) http.Handler {
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
started := time.Now()
|
||||
recorder := &responseRecorder{ResponseWriter: writer}
|
||||
|
||||
defer func() {
|
||||
panicValue := recover()
|
||||
if panicValue != nil && recorder.status == 0 {
|
||||
recorder.status = http.StatusInternalServerError
|
||||
}
|
||||
|
||||
attrs := []any{
|
||||
"method", request.Method,
|
||||
"path", request.URL.Path,
|
||||
"status", recorder.Status(),
|
||||
"bytes", recorder.bytes,
|
||||
"duration", time.Since(started),
|
||||
"remote_addr", request.RemoteAddr,
|
||||
}
|
||||
|
||||
if panicValue != nil {
|
||||
attrs = append(attrs, "panic", panicValue)
|
||||
logger.Error("http request", attrs...)
|
||||
panic(panicValue)
|
||||
}
|
||||
logger.Info("http request", attrs...)
|
||||
}()
|
||||
|
||||
next.ServeHTTP(recorder, request)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type responseRecorder struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
bytes int64
|
||||
}
|
||||
|
||||
func (r *responseRecorder) Unwrap() http.ResponseWriter {
|
||||
return r.ResponseWriter
|
||||
}
|
||||
|
||||
func (r *responseRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error) {
|
||||
hijacker, ok := r.ResponseWriter.(http.Hijacker)
|
||||
if !ok {
|
||||
return nil, nil, http.ErrNotSupported
|
||||
}
|
||||
r.status = http.StatusSwitchingProtocols
|
||||
return hijacker.Hijack()
|
||||
}
|
||||
|
||||
func (r *responseRecorder) Status() int {
|
||||
if r.status == 0 {
|
||||
return http.StatusOK
|
||||
}
|
||||
return r.status
|
||||
}
|
||||
|
||||
func (r *responseRecorder) WriteHeader(status int) {
|
||||
if status >= 100 && status < 200 && status != http.StatusSwitchingProtocols {
|
||||
r.ResponseWriter.WriteHeader(status)
|
||||
return
|
||||
}
|
||||
if r.status != 0 {
|
||||
return
|
||||
}
|
||||
|
||||
r.status = status
|
||||
r.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func (r *responseRecorder) Write(body []byte) (int, error) {
|
||||
if r.status == 0 {
|
||||
r.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
written, err := r.ResponseWriter.Write(body)
|
||||
r.bytes += int64(written)
|
||||
return written, err
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"log/slog"
|
||||
)
|
||||
|
||||
func TestLoggingRecordsResponse(t *testing.T) {
|
||||
var output bytes.Buffer
|
||||
logger := slog.New(slog.NewTextHandler(&output, nil))
|
||||
handler := Logging(logger)(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
if request.Method != http.MethodGet {
|
||||
writer.WriteHeader(http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
writer.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
response := httptest.NewRecorder()
|
||||
request := httptest.NewRequest(http.MethodGet, "/healthz", nil)
|
||||
|
||||
handler.ServeHTTP(response, request)
|
||||
|
||||
if response.Code != http.StatusNoContent {
|
||||
t.Fatalf("expected status %d, got %d", http.StatusNoContent, response.Code)
|
||||
}
|
||||
for _, field := range []string{"method=GET", "path=/healthz", "status=204", "bytes=0"} {
|
||||
if !strings.Contains(output.String(), field) {
|
||||
t.Errorf("request log did not contain %q: %s", field, output.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoggingPreservesHijacker(t *testing.T) {
|
||||
var output bytes.Buffer
|
||||
logger := slog.New(slog.NewTextHandler(&output, nil))
|
||||
handler := Logging(logger)(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
if request.Method != http.MethodGet {
|
||||
t.Errorf("unexpected request method %q", request.Method)
|
||||
return
|
||||
}
|
||||
hijacker, ok := writer.(http.Hijacker)
|
||||
if !ok {
|
||||
t.Error("logging response writer does not implement http.Hijacker")
|
||||
return
|
||||
}
|
||||
connection, _, err := hijacker.Hijack()
|
||||
if err != nil {
|
||||
t.Errorf("hijack connection: %v", err)
|
||||
return
|
||||
}
|
||||
if err := connection.Close(); err != nil {
|
||||
t.Errorf("close hijacked connection: %v", err)
|
||||
}
|
||||
}))
|
||||
writer := &hijackResponseWriter{header: make(http.Header)}
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/minecraft/ws", nil)
|
||||
|
||||
handler.ServeHTTP(writer, request)
|
||||
|
||||
if !strings.Contains(output.String(), "status=101") {
|
||||
t.Fatalf("request log did not record the protocol upgrade: %s", output.String())
|
||||
}
|
||||
}
|
||||
|
||||
type hijackResponseWriter struct {
|
||||
header http.Header
|
||||
status int
|
||||
}
|
||||
|
||||
func (writer *hijackResponseWriter) Header() http.Header {
|
||||
return writer.header
|
||||
}
|
||||
|
||||
func (writer *hijackResponseWriter) Write(body []byte) (int, error) {
|
||||
return len(body), nil
|
||||
}
|
||||
|
||||
func (writer *hijackResponseWriter) WriteHeader(status int) {
|
||||
writer.status = status
|
||||
}
|
||||
|
||||
func (writer *hijackResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
|
||||
connection, peer := net.Pipe()
|
||||
if err := peer.Close(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return connection, bufio.NewReadWriter(bufio.NewReader(connection), bufio.NewWriter(connection)), nil
|
||||
}
|
||||
@@ -0,0 +1,919 @@
|
||||
package minecraft
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"oauth-mc-web/internal/database/repository"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
const protocolVersion = 1
|
||||
|
||||
var errAccountBindingConflict = errors.New("minecraft account binding conflict")
|
||||
var errSessionNotApproved = errors.New("minecraft session was not approved")
|
||||
var errUnlinkRequestReuse = errors.New("unlink request ID was already used for another UUID")
|
||||
|
||||
type Config struct {
|
||||
Credentials map[string]string
|
||||
LoginURL string
|
||||
CASLoginURL string
|
||||
CASValidate string
|
||||
CASService string
|
||||
SessionTTL time.Duration
|
||||
AllowHTTPService bool
|
||||
}
|
||||
|
||||
type sessionQueries interface {
|
||||
AcknowledgeSessionResult(context.Context, repository.AcknowledgeSessionResultParams) (int64, error)
|
||||
ApproveSession(context.Context, repository.ApproveSessionParams) (int64, error)
|
||||
CancelPendingSession(context.Context, repository.CancelPendingSessionParams) (int64, error)
|
||||
CountActivePendingSessions(context.Context, repository.CountActivePendingSessionsParams) (int64, error)
|
||||
DeleteClosedSessions(context.Context, string) error
|
||||
DeleteClosedSessionsForServer(context.Context, repository.DeleteClosedSessionsForServerParams) error
|
||||
DeletePendingSessionsForPlayer(context.Context, repository.DeletePendingSessionsForPlayerParams) error
|
||||
DenyPendingSession(context.Context, string) (int64, error)
|
||||
DeleteUnusedAccountBinding(context.Context, repository.DeleteUnusedAccountBindingParams) (int64, error)
|
||||
DeleteUUIDAccountBinding(context.Context, repository.DeleteUUIDAccountBindingParams) (int64, error)
|
||||
ExpirePendingSession(context.Context, string) error
|
||||
ExpirePendingSessions(context.Context, string) error
|
||||
ExpirePendingSessionsForServer(context.Context, repository.ExpirePendingSessionsForServerParams) error
|
||||
GetBoundAccountForUUID(context.Context, repository.GetBoundAccountForUUIDParams) (repository.GetBoundAccountForUUIDRow, error)
|
||||
GetBoundNameForSubject(context.Context, string) (string, error)
|
||||
GetBoundSubjectForName(context.Context, string) (string, error)
|
||||
GetBoundSubjectForUUID(context.Context, repository.GetBoundSubjectForUUIDParams) (string, error)
|
||||
GetBoundUUIDForSubject(context.Context, repository.GetBoundUUIDForSubjectParams) (string, error)
|
||||
GetLoginRequest(context.Context, repository.GetLoginRequestParams) (repository.GetLoginRequestRow, error)
|
||||
GetPendingSessionByCode(context.Context, string) (repository.GetPendingSessionByCodeRow, error)
|
||||
GetPendingSessionExpiry(context.Context, string) (string, error)
|
||||
GetSessionForReplay(context.Context, repository.GetSessionForReplayParams) (repository.GetSessionForReplayRow, error)
|
||||
GetSessionResult(context.Context, repository.GetSessionResultParams) (repository.GetSessionResultRow, error)
|
||||
GetSessionServerID(context.Context, string) (string, error)
|
||||
GetUnlinkRequest(context.Context, repository.GetUnlinkRequestParams) (repository.GetUnlinkRequestRow, error)
|
||||
InsertAccountBinding(context.Context, repository.InsertAccountBindingParams) error
|
||||
InsertLoginRequest(context.Context, repository.InsertLoginRequestParams) error
|
||||
InsertSession(context.Context, repository.InsertSessionParams) error
|
||||
InsertUnlinkRequest(context.Context, repository.InsertUnlinkRequestParams) error
|
||||
ListExpiredSessions(context.Context) ([]repository.ListExpiredSessionsRow, error)
|
||||
ListPendingSessionIDsForPlayer(context.Context, repository.ListPendingSessionIDsForPlayerParams) ([]string, error)
|
||||
UpsertUUIDAccountBinding(context.Context, repository.UpsertUUIDAccountBindingParams) error
|
||||
}
|
||||
|
||||
type transactionRunner interface {
|
||||
WithinTransaction(context.Context, func(repository.Querier) error) error
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
queries sessionQueries
|
||||
transaction transactionRunner
|
||||
config Config
|
||||
logger *slog.Logger
|
||||
mu sync.Mutex
|
||||
clients map[string]*client
|
||||
serverRates map[string][]time.Time
|
||||
playerRates map[string][]time.Time
|
||||
}
|
||||
|
||||
type client struct {
|
||||
serverID string
|
||||
ctx context.Context
|
||||
conn *websocket.Conn
|
||||
mu sync.Mutex
|
||||
pending map[string]struct{}
|
||||
}
|
||||
|
||||
func New(queries sessionQueries, transaction transactionRunner, config Config, logger *slog.Logger) *Service {
|
||||
if config.SessionTTL <= 0 {
|
||||
config.SessionTTL = 5 * time.Minute
|
||||
}
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
return &Service{queries: queries, transaction: transaction, config: config, logger: logger, clients: map[string]*client{}, serverRates: map[string][]time.Time{}, playerRates: map[string][]time.Time{}}
|
||||
}
|
||||
|
||||
func (s *Service) CallbackPath() string {
|
||||
callbackPath := "/api/v1/minecraft/cas/callback"
|
||||
if callback, err := url.Parse(s.config.CASService); err == nil && strings.HasPrefix(callback.Path, "/") && callback.Path != "/" && callback.Path != "/api/v1/minecraft/ws" {
|
||||
callbackPath = callback.Path
|
||||
}
|
||||
return callbackPath
|
||||
}
|
||||
|
||||
func (s *Service) WebSocketHandler(w http.ResponseWriter, r *http.Request) {
|
||||
s.handleWebSocket(w, r)
|
||||
}
|
||||
|
||||
func (s *Service) LoginPageHandler(w http.ResponseWriter, r *http.Request) {
|
||||
s.handleLoginPage(w, r)
|
||||
}
|
||||
|
||||
func (s *Service) CASCallbackHandler(w http.ResponseWriter, r *http.Request) {
|
||||
s.handleCASCallback(w, r)
|
||||
}
|
||||
|
||||
func (s *Service) RunMaintenance(ctx context.Context) {
|
||||
ticker := time.NewTicker(30 * time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
s.expireSessions(ctx)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) expireSessions(ctx context.Context) {
|
||||
now := time.Now().UTC()
|
||||
if err := s.queries.ExpirePendingSessions(ctx, databaseTime(now)); err != nil {
|
||||
s.logger.Error("expire pending Minecraft sessions", "error", err)
|
||||
return
|
||||
}
|
||||
expired, err := s.queries.ListExpiredSessions(ctx)
|
||||
if err != nil {
|
||||
s.logger.Error("list expired Minecraft sessions", "error", err)
|
||||
return
|
||||
}
|
||||
for _, session := range expired {
|
||||
s.pushResult(ctx, session.SessionID, session.MinecraftUuid, "expired", "", "")
|
||||
}
|
||||
if err := s.queries.DeleteClosedSessions(ctx, databaseTime(now.Add(-s.config.SessionTTL))); err != nil {
|
||||
s.logger.Error("delete closed Minecraft sessions", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
type wireMessage struct {
|
||||
Type string `json:"type"`
|
||||
RequestID string `json:"request_id,omitempty"`
|
||||
ProtocolVersion int `json:"protocol_version,omitempty"`
|
||||
ServerID string `json:"server_id,omitempty"`
|
||||
PendingSessions []string `json:"pending_sessions,omitempty"`
|
||||
Player struct {
|
||||
UUID string `json:"minecraft_uuid"`
|
||||
Name string `json:"minecraft_name"`
|
||||
} `json:"player,omitempty"`
|
||||
SessionID string `json:"session_id,omitempty"`
|
||||
MinecraftUUID string `json:"minecraft_uuid,omitempty"`
|
||||
MinecraftName string `json:"minecraft_name,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Service) handleWebSocket(w http.ResponseWriter, r *http.Request) {
|
||||
serverID, ok := s.authenticate(r)
|
||||
if !ok {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
upgrader := websocket.Upgrader{ReadBufferSize: 4096, WriteBufferSize: 4096, CheckOrigin: func(request *http.Request) bool { return request != nil }}
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
s.logger.Error("upgrade Minecraft websocket", "error", err)
|
||||
return
|
||||
}
|
||||
c := &client{serverID: serverID, ctx: r.Context(), conn: conn, pending: map[string]struct{}{}}
|
||||
defer func() {
|
||||
s.mu.Lock()
|
||||
if s.clients[serverID] == c {
|
||||
delete(s.clients, serverID)
|
||||
}
|
||||
s.mu.Unlock()
|
||||
if err := conn.Close(); err != nil {
|
||||
s.logger.Warn("close Minecraft websocket", "error", err, "server_id", serverID)
|
||||
}
|
||||
}()
|
||||
conn.SetReadLimit(16 * 1024)
|
||||
if err := conn.SetReadDeadline(time.Now().Add(90 * time.Second)); err != nil {
|
||||
s.logger.Error("set Minecraft websocket read deadline", "error", err, "server_id", serverID)
|
||||
return
|
||||
}
|
||||
conn.SetPongHandler(func(string) error { return conn.SetReadDeadline(time.Now().Add(90 * time.Second)) })
|
||||
first := true
|
||||
for {
|
||||
_, data, err := conn.ReadMessage()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if !utf8.Valid(data) {
|
||||
s.protocolError(c, "invalid_request", "")
|
||||
return
|
||||
}
|
||||
if err := conn.SetReadDeadline(time.Now().Add(90 * time.Second)); err != nil {
|
||||
s.logger.Error("refresh Minecraft websocket read deadline", "error", err, "server_id", serverID)
|
||||
return
|
||||
}
|
||||
var msg wireMessage
|
||||
if err := json.Unmarshal(data, &msg); err != nil {
|
||||
s.protocolError(c, "invalid_request", "")
|
||||
return
|
||||
}
|
||||
if first {
|
||||
validSessions := len(msg.PendingSessions) <= 100
|
||||
for _, id := range msg.PendingSessions {
|
||||
if id == "" || len(id) > 128 {
|
||||
validSessions = false
|
||||
break
|
||||
}
|
||||
}
|
||||
if msg.Type != "hello" || msg.ProtocolVersion != protocolVersion || msg.ServerID != serverID || !validSessions {
|
||||
s.protocolError(c, "invalid_request", msg.RequestID)
|
||||
return
|
||||
}
|
||||
first = false
|
||||
for _, id := range msg.PendingSessions {
|
||||
c.pending[id] = struct{}{}
|
||||
}
|
||||
s.mu.Lock()
|
||||
if previous := s.clients[serverID]; previous != nil && previous != c {
|
||||
if err := previous.conn.Close(); err != nil {
|
||||
s.logger.Warn("close replaced Minecraft websocket", "error", err, "server_id", serverID)
|
||||
}
|
||||
}
|
||||
s.clients[serverID] = c
|
||||
s.mu.Unlock()
|
||||
if !s.write(c, map[string]any{"type": "ready", "protocol_version": protocolVersion}) {
|
||||
return
|
||||
}
|
||||
if !s.replay(r.Context(), c, msg.PendingSessions) {
|
||||
return
|
||||
}
|
||||
go s.keepalive(c)
|
||||
continue
|
||||
}
|
||||
if !s.handleMessage(r.Context(), c, msg) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) authenticate(r *http.Request) (string, bool) {
|
||||
value := strings.TrimSpace(strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer "))
|
||||
if value == "" {
|
||||
return "", false
|
||||
}
|
||||
|
||||
for id, token := range s.config.Credentials {
|
||||
if len(token) == len(value) && subtle.ConstantTimeCompare([]byte(token), []byte(value)) == 1 {
|
||||
return id, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
func (s *Service) handleMessage(ctx context.Context, c *client, msg wireMessage) bool {
|
||||
switch msg.Type {
|
||||
case "login_start":
|
||||
s.startLogin(ctx, c, msg)
|
||||
case "login_cancel":
|
||||
s.cancelLogin(ctx, c, msg)
|
||||
case "login_result_ack":
|
||||
_, err := s.queries.AcknowledgeSessionResult(ctx, repository.AcknowledgeSessionResultParams{SessionID: msg.SessionID, ServerID: c.serverID})
|
||||
if err != nil {
|
||||
s.logger.Error("acknowledge Minecraft login result", "error", err)
|
||||
return false
|
||||
}
|
||||
c.mu.Lock()
|
||||
delete(c.pending, msg.SessionID)
|
||||
c.mu.Unlock()
|
||||
case "unlink_account":
|
||||
s.unlinkAccount(ctx, c, msg)
|
||||
default:
|
||||
s.protocolError(c, "unknown_message_type", msg.RequestID)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Service) startLogin(ctx context.Context, c *client, msg wireMessage) {
|
||||
if msg.RequestID == "" || len(msg.RequestID) > 128 || !validUUID(msg.Player.UUID) || msg.Player.Name == "" || len(msg.Player.Name) > 64 {
|
||||
s.write(c, errorMessage(msg.RequestID, "invalid_request", 0))
|
||||
return
|
||||
}
|
||||
requestParams := repository.GetLoginRequestParams{ServerID: c.serverID, RequestID: msg.RequestID}
|
||||
request, err := s.queries.GetLoginRequest(ctx, requestParams)
|
||||
if err == nil {
|
||||
s.sendLoginStarted(c, msg.RequestID, msg.Player.UUID, request)
|
||||
return
|
||||
}
|
||||
if !errors.Is(err, repository.ErrNoRows) {
|
||||
s.logger.Error("check Minecraft login request", "error", err, "server_id", c.serverID)
|
||||
s.write(c, errorMessage(msg.RequestID, "unavailable", 0))
|
||||
return
|
||||
}
|
||||
if !s.allowRequest(c.serverID, msg.Player.UUID) {
|
||||
s.write(c, errorMessage(msg.RequestID, "rate_limited", 5))
|
||||
return
|
||||
}
|
||||
active, err := s.queries.CountActivePendingSessions(ctx, repository.CountActivePendingSessionsParams{ServerID: c.serverID, MinecraftUuid: msg.Player.UUID, ExpiresAt: databaseTime(time.Now())})
|
||||
if err != nil {
|
||||
s.logger.Error("count active Minecraft login sessions", "error", err, "server_id", c.serverID)
|
||||
s.write(c, errorMessage(msg.RequestID, "unavailable", 0))
|
||||
return
|
||||
}
|
||||
if active >= 100 {
|
||||
s.write(c, errorMessage(msg.RequestID, "rate_limited", 5))
|
||||
return
|
||||
}
|
||||
sessionID, err := randomToken(24)
|
||||
if err != nil {
|
||||
s.write(c, errorMessage(msg.RequestID, "unavailable", 0))
|
||||
return
|
||||
}
|
||||
code, err := randomToken(24)
|
||||
if err != nil {
|
||||
s.write(c, errorMessage(msg.RequestID, "unavailable", 0))
|
||||
return
|
||||
}
|
||||
loginURL, err := url.Parse(s.config.LoginURL)
|
||||
if err != nil || loginURL.Host == "" || (loginURL.Scheme != "https" && !(loginURL.Scheme == "http" && (loginURL.Hostname() == "localhost" || loginURL.Hostname() == "127.0.0.1"))) {
|
||||
s.write(c, errorMessage(msg.RequestID, "unavailable", 0))
|
||||
return
|
||||
}
|
||||
query := loginURL.Query()
|
||||
query.Set("code", code)
|
||||
loginURL.RawQuery = query.Encode()
|
||||
expires := time.Now().UTC().Add(s.config.SessionTTL)
|
||||
var existingRequest *repository.GetLoginRequestRow
|
||||
var oldIDs []string
|
||||
err = s.transaction.WithinTransaction(ctx, func(queries repository.Querier) error {
|
||||
storedRequest, queryErr := queries.GetLoginRequest(ctx, requestParams)
|
||||
if queryErr == nil {
|
||||
existingRequest = &storedRequest
|
||||
return nil
|
||||
}
|
||||
if !errors.Is(queryErr, repository.ErrNoRows) {
|
||||
return queryErr
|
||||
}
|
||||
oldIDs, err = queries.ListPendingSessionIDsForPlayer(ctx, repository.ListPendingSessionIDsForPlayerParams{ServerID: c.serverID, MinecraftUuid: msg.Player.UUID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = queries.DeletePendingSessionsForPlayer(ctx, repository.DeletePendingSessionsForPlayerParams{ServerID: c.serverID, MinecraftUuid: msg.Player.UUID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = queries.InsertSession(ctx, repository.InsertSessionParams{SessionID: sessionID, RequestID: msg.RequestID, ServerID: c.serverID, MinecraftUuid: msg.Player.UUID, MinecraftName: msg.Player.Name, Code: code, LoginUrl: loginURL.String(), ExpiresAt: databaseTime(expires)})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return queries.InsertLoginRequest(ctx, repository.InsertLoginRequestParams{ServerID: c.serverID, RequestID: msg.RequestID, MinecraftUuid: msg.Player.UUID, SessionID: sessionID, LoginUrl: loginURL.String(), ExpiresAt: databaseTime(expires)})
|
||||
})
|
||||
if err != nil {
|
||||
s.logger.Error("store Minecraft login session", "error", err)
|
||||
s.write(c, errorMessage(msg.RequestID, "unavailable", 0))
|
||||
return
|
||||
}
|
||||
if existingRequest != nil {
|
||||
s.sendLoginStarted(c, msg.RequestID, msg.Player.UUID, *existingRequest)
|
||||
return
|
||||
}
|
||||
c.mu.Lock()
|
||||
for _, oldID := range oldIDs {
|
||||
delete(c.pending, oldID)
|
||||
}
|
||||
c.pending[sessionID] = struct{}{}
|
||||
c.mu.Unlock()
|
||||
s.sendLoginStarted(c, msg.RequestID, msg.Player.UUID, repository.GetLoginRequestRow{MinecraftUuid: msg.Player.UUID, SessionID: sessionID, LoginUrl: loginURL.String(), ExpiresAt: databaseTime(expires)})
|
||||
}
|
||||
|
||||
func (s *Service) sendLoginStarted(c *client, requestID, minecraftUUID string, request repository.GetLoginRequestRow) {
|
||||
if !strings.EqualFold(request.MinecraftUuid, minecraftUUID) {
|
||||
s.write(c, errorMessage(requestID, "invalid_request", 0))
|
||||
return
|
||||
}
|
||||
if !s.write(c, map[string]any{"type": "login_started", "request_id": requestID, "session_id": request.SessionID, "minecraft_uuid": minecraftUUID, "login_url": request.LoginUrl, "expires_at": request.ExpiresAt}) {
|
||||
s.logger.Warn("write Minecraft login response", "request_id", requestID, "server_id", c.serverID)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) allowRequest(serverID, playerID string) bool {
|
||||
now := time.Now()
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.serverRates[serverID] = recent(s.serverRates[serverID], now)
|
||||
for key, times := range s.playerRates {
|
||||
times = recent(times, now)
|
||||
if len(times) == 0 {
|
||||
delete(s.playerRates, key)
|
||||
} else {
|
||||
s.playerRates[key] = times
|
||||
}
|
||||
}
|
||||
key := serverID + ":" + playerID
|
||||
s.playerRates[key] = recent(s.playerRates[key], now)
|
||||
if len(s.serverRates[serverID]) >= 120 || len(s.playerRates[key]) >= 10 {
|
||||
return false
|
||||
}
|
||||
s.serverRates[serverID] = append(s.serverRates[serverID], now)
|
||||
s.playerRates[key] = append(s.playerRates[key], now)
|
||||
return true
|
||||
}
|
||||
|
||||
func recent(times []time.Time, now time.Time) []time.Time {
|
||||
result := times[:0]
|
||||
for _, t := range times {
|
||||
if now.Sub(t) < time.Minute {
|
||||
result = append(result, t)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (s *Service) cancelLogin(ctx context.Context, c *client, msg wireMessage) {
|
||||
if msg.RequestID == "" || msg.SessionID == "" || msg.MinecraftUUID == "" {
|
||||
s.write(c, errorMessage(msg.RequestID, "invalid_request", 0))
|
||||
return
|
||||
}
|
||||
_, err := s.queries.CancelPendingSession(ctx, repository.CancelPendingSessionParams{SessionID: msg.SessionID, ServerID: c.serverID, MinecraftUuid: msg.MinecraftUUID})
|
||||
if err != nil {
|
||||
s.logger.Error("cancel Minecraft login", "error", err)
|
||||
s.write(c, errorMessage(msg.RequestID, "unavailable", 0))
|
||||
return
|
||||
}
|
||||
c.mu.Lock()
|
||||
delete(c.pending, msg.SessionID)
|
||||
c.mu.Unlock()
|
||||
s.write(c, map[string]any{"type": "login_cancelled", "request_id": msg.RequestID})
|
||||
}
|
||||
|
||||
func (s *Service) unlinkAccount(ctx context.Context, c *client, msg wireMessage) {
|
||||
if strings.TrimSpace(msg.RequestID) == "" || len(msg.RequestID) > 128 || !validUUID(msg.MinecraftUUID) {
|
||||
s.write(c, errorMessage(msg.RequestID, "invalid_request", 0))
|
||||
return
|
||||
}
|
||||
uuid := strings.ToLower(msg.MinecraftUUID)
|
||||
requestParams := repository.GetUnlinkRequestParams{ServerID: c.serverID, RequestID: msg.RequestID}
|
||||
previous, err := s.queries.GetUnlinkRequest(ctx, requestParams)
|
||||
if err == nil {
|
||||
if previous.MinecraftUuid != uuid {
|
||||
s.write(c, errorMessage(msg.RequestID, "invalid_request", 0))
|
||||
return
|
||||
}
|
||||
s.sendUnlinkResult(c, msg.RequestID, msg.MinecraftUUID, previous.Status)
|
||||
return
|
||||
}
|
||||
if !errors.Is(err, repository.ErrNoRows) {
|
||||
s.logger.Error("check Minecraft unlink request", "error", err, "server_id", c.serverID)
|
||||
s.write(c, errorMessage(msg.RequestID, "unavailable", 0))
|
||||
return
|
||||
}
|
||||
if !s.allowRequest(c.serverID, uuid) {
|
||||
s.write(c, errorMessage(msg.RequestID, "rate_limited", 5))
|
||||
return
|
||||
}
|
||||
status := ""
|
||||
err = s.transaction.WithinTransaction(ctx, func(queries repository.Querier) error {
|
||||
previous, err := queries.GetUnlinkRequest(ctx, requestParams)
|
||||
if err == nil {
|
||||
if previous.MinecraftUuid != uuid {
|
||||
return errUnlinkRequestReuse
|
||||
}
|
||||
status = previous.Status
|
||||
return nil
|
||||
}
|
||||
if !errors.Is(err, repository.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
binding, err := queries.GetBoundAccountForUUID(ctx, repository.GetBoundAccountForUUIDParams{ServerID: c.serverID, MinecraftUuid: uuid})
|
||||
if errors.Is(err, repository.ErrNoRows) {
|
||||
status = "not_linked"
|
||||
} else if err != nil {
|
||||
return err
|
||||
} else {
|
||||
deleted, err := queries.DeleteUUIDAccountBinding(ctx, repository.DeleteUUIDAccountBindingParams{ServerID: c.serverID, MinecraftUuid: uuid})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if deleted == 0 {
|
||||
status = "not_linked"
|
||||
} else {
|
||||
_, err := queries.DeleteUnusedAccountBinding(ctx, repository.DeleteUnusedAccountBindingParams{MinecraftNameKey: binding.MinecraftNameKey, AccountSubject: binding.AccountSubject})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
status = "unlinked"
|
||||
}
|
||||
}
|
||||
return queries.InsertUnlinkRequest(ctx, repository.InsertUnlinkRequestParams{ServerID: c.serverID, RequestID: msg.RequestID, MinecraftUuid: uuid, Status: status, CreatedAt: databaseTime(time.Now())})
|
||||
})
|
||||
if errors.Is(err, errUnlinkRequestReuse) {
|
||||
s.write(c, errorMessage(msg.RequestID, "invalid_request", 0))
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.logger.Error("unlink Minecraft account", "error", err, "server_id", c.serverID)
|
||||
s.write(c, errorMessage(msg.RequestID, "unavailable", 0))
|
||||
return
|
||||
}
|
||||
s.sendUnlinkResult(c, msg.RequestID, msg.MinecraftUUID, status)
|
||||
}
|
||||
|
||||
func (s *Service) sendUnlinkResult(c *client, requestID, uuid, status string) {
|
||||
if !s.write(c, map[string]any{"type": "unlink_result", "request_id": requestID, "minecraft_uuid": uuid, "status": status}) {
|
||||
s.logger.Warn("write Minecraft unlink result", "request_id", requestID, "server_id", c.serverID)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) replay(ctx context.Context, c *client, ids []string) bool {
|
||||
for _, id := range ids {
|
||||
c.mu.Lock()
|
||||
c.pending[id] = struct{}{}
|
||||
c.mu.Unlock()
|
||||
session, err := s.queries.GetSessionForReplay(ctx, repository.GetSessionForReplayParams{SessionID: id, ServerID: c.serverID})
|
||||
if errors.Is(err, repository.ErrNoRows) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if session.Status == "pending" && time.Now().UTC().After(parseTime(session.ExpiresAt)) {
|
||||
if err := s.queries.ExpirePendingSession(ctx, id); err != nil {
|
||||
s.logger.Error("expire Minecraft login session", "error", err, "session_id", id)
|
||||
return false
|
||||
}
|
||||
session.Status = "expired"
|
||||
}
|
||||
if session.Status == "pending" {
|
||||
if !s.write(c, map[string]any{"type": "login_started", "request_id": session.RequestID, "session_id": id, "minecraft_uuid": session.MinecraftUuid, "login_url": session.LoginUrl, "expires_at": session.ExpiresAt}) {
|
||||
return false
|
||||
}
|
||||
} else if session.Status == "approved" || session.Status == "denied" || session.Status == "expired" {
|
||||
if !s.sendResult(c, id, session.MinecraftUuid, session.Status, session.AccountSubject, session.AccountDisplayName) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Service) sendResult(c *client, id, uuid, status, subject, display string) bool {
|
||||
msg := map[string]any{"type": "login_result", "session_id": id, "minecraft_uuid": uuid, "status": status}
|
||||
if status == "approved" {
|
||||
msg["account"] = map[string]string{"subject": subject, "display_name": display}
|
||||
}
|
||||
return s.write(c, msg)
|
||||
}
|
||||
|
||||
func (s *Service) protocolError(c *client, code, requestID string) {
|
||||
message := map[string]any{"type": "error", "code": code}
|
||||
if requestID != "" {
|
||||
message["request_id"] = requestID
|
||||
}
|
||||
if !s.write(c, message) {
|
||||
s.logger.Warn("write Minecraft websocket protocol error", "server_id", c.serverID, "code", code)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) write(c *client, message any) bool {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if err := c.conn.SetWriteDeadline(time.Now().Add(10 * time.Second)); err != nil {
|
||||
s.logger.Error("set Minecraft websocket write deadline", "error", err, "server_id", c.serverID)
|
||||
return false
|
||||
}
|
||||
if err := c.conn.WriteJSON(message); err != nil {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Service) keepalive(c *client) {
|
||||
ticker := time.NewTicker(25 * time.Second)
|
||||
defer ticker.Stop()
|
||||
for range ticker.C {
|
||||
s.mu.Lock()
|
||||
active := s.clients[c.serverID] == c
|
||||
s.mu.Unlock()
|
||||
if !active {
|
||||
return
|
||||
}
|
||||
if !s.writeControl(c, websocket.PingMessage, []byte("ping")) {
|
||||
if err := c.conn.Close(); err != nil {
|
||||
s.logger.Warn("close inactive Minecraft websocket", "error", err, "server_id", c.serverID)
|
||||
}
|
||||
return
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
if err := s.queries.ExpirePendingSessionsForServer(c.ctx, repository.ExpirePendingSessionsForServerParams{ServerID: c.serverID, ExpiresAt: databaseTime(now)}); err != nil {
|
||||
s.logger.Error("expire server Minecraft sessions", "error", err, "server_id", c.serverID)
|
||||
}
|
||||
if err := s.queries.DeleteClosedSessionsForServer(c.ctx, repository.DeleteClosedSessionsForServerParams{ServerID: c.serverID, ExpiresAt: databaseTime(now.Add(-s.config.SessionTTL))}); err != nil {
|
||||
s.logger.Error("delete closed server Minecraft sessions", "error", err, "server_id", c.serverID)
|
||||
}
|
||||
c.mu.Lock()
|
||||
ids := make([]string, 0, len(c.pending))
|
||||
for id := range c.pending {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
c.mu.Unlock()
|
||||
for _, id := range ids {
|
||||
session, err := s.queries.GetSessionResult(c.ctx, repository.GetSessionResultParams{SessionID: id, ServerID: c.serverID})
|
||||
if err == nil && session.Status != "pending" {
|
||||
s.sendResult(c, id, session.MinecraftUuid, session.Status, session.AccountSubject, session.AccountDisplayName)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) writeControl(c *client, kind int, data []byte) bool {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.conn.WriteControl(kind, data, time.Now().Add(10*time.Second)) == nil
|
||||
}
|
||||
|
||||
func (s *Service) handleLoginPage(w http.ResponseWriter, r *http.Request) {
|
||||
code := r.URL.Query().Get("code")
|
||||
expiry, err := s.queries.GetPendingSessionExpiry(r.Context(), code)
|
||||
if err != nil || time.Now().UTC().After(parseTime(expiry)) {
|
||||
http.Error(w, "login session expired", http.StatusGone)
|
||||
return
|
||||
}
|
||||
if s.config.CASLoginURL == "" || s.config.CASService == "" {
|
||||
http.Error(w, "CAS login is not configured", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
callback, err := url.Parse(s.config.CASService)
|
||||
if err != nil || !s.validCASServiceURL(callback) {
|
||||
http.Error(w, "CAS_SERVICE_URL must be an absolute HTTPS URL; HTTP is allowed only in development", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
q := callback.Query()
|
||||
q.Set("code", code)
|
||||
callback.RawQuery = q.Encode()
|
||||
casURL, err := url.Parse(s.config.CASLoginURL)
|
||||
if err != nil {
|
||||
http.Error(w, "CAS login is unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
q = casURL.Query()
|
||||
q.Set("service", callback.String())
|
||||
casURL.RawQuery = q.Encode()
|
||||
http.Redirect(w, r, casURL.String(), http.StatusFound)
|
||||
}
|
||||
|
||||
func (s *Service) validCASServiceURL(callback *url.URL) bool {
|
||||
if callback == nil || callback.Host == "" || callback.User != nil || callback.Fragment != "" {
|
||||
return false
|
||||
}
|
||||
return callback.Scheme == "https" || (s.config.AllowHTTPService && callback.Scheme == "http")
|
||||
}
|
||||
|
||||
func (s *Service) handleCASCallback(w http.ResponseWriter, r *http.Request) {
|
||||
code, ticket := r.URL.Query().Get("code"), r.URL.Query().Get("ticket")
|
||||
if code == "" {
|
||||
http.Error(w, "invalid CAS response", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
session, err := s.queries.GetPendingSessionByCode(r.Context(), code)
|
||||
sessionID, uuid, minecraftName, expiry := session.SessionID, session.MinecraftUuid, session.MinecraftName, session.ExpiresAt
|
||||
if err != nil || time.Now().UTC().After(parseTime(expiry)) {
|
||||
http.Error(w, "login session expired", http.StatusGone)
|
||||
return
|
||||
}
|
||||
if ticket == "" && r.URL.Query().Get("error") != "" {
|
||||
_, err := s.queries.DenyPendingSession(r.Context(), sessionID)
|
||||
if err != nil {
|
||||
http.Error(w, "could not complete login", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
s.pushResult(r.Context(), sessionID, uuid, "denied", "", "")
|
||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
if _, err := w.Write([]byte("CAS authentication was not completed.")); err != nil {
|
||||
s.logger.Warn("write CAS cancellation response", "error", err, "session_id", sessionID)
|
||||
}
|
||||
return
|
||||
}
|
||||
if ticket == "" {
|
||||
http.Error(w, "invalid CAS response", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
serviceURL, err := url.Parse(s.config.CASService)
|
||||
if err != nil {
|
||||
http.Error(w, "CAS service is unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
q := serviceURL.Query()
|
||||
q.Set("code", code)
|
||||
serviceURL.RawQuery = q.Encode()
|
||||
validateURL, err := url.Parse(s.config.CASValidate)
|
||||
if err != nil {
|
||||
http.Error(w, "CAS service is unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
q = validateURL.Query()
|
||||
q.Set("service", serviceURL.String())
|
||||
q.Set("ticket", ticket)
|
||||
validateURL.RawQuery = q.Encode()
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
|
||||
defer cancel()
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, validateURL.String(), nil)
|
||||
if err != nil {
|
||||
http.Error(w, "CAS validation failed", http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
http.Error(w, "CAS validation failed", http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
defer func() {
|
||||
if err := resp.Body.Close(); err != nil {
|
||||
s.logger.Warn("close CAS validation response", "error", err)
|
||||
}
|
||||
}()
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
http.Error(w, "CAS validation failed", http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
var result casResponse
|
||||
if err := xml.NewDecoder(http.MaxBytesReader(w, resp.Body, 64*1024)).Decode(&result); err != nil {
|
||||
http.Error(w, "CAS validation failed", http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
if result.Success.User == "" {
|
||||
http.Error(w, "CAS authentication denied", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
display := result.Success.Attributes.DisplayName
|
||||
if display == "" {
|
||||
display = result.Success.User
|
||||
}
|
||||
approved, conflict, err := s.approveCASLogin(r.Context(), session.ServerID, uuid, sessionID, minecraftName, result.Success.User, display)
|
||||
if err != nil {
|
||||
s.logger.Error("approve Minecraft CAS login", "error", err, "session_id", sessionID)
|
||||
http.Error(w, "could not complete login", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if conflict {
|
||||
if _, err := s.queries.DenyPendingSession(r.Context(), sessionID); err != nil {
|
||||
s.logger.Error("deny conflicting Minecraft account binding session", "error", err)
|
||||
http.Error(w, "could not complete login", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
s.pushResult(r.Context(), sessionID, uuid, "denied", "", "")
|
||||
http.Error(w, "This Minecraft username or SSO account is already linked to another account.", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
if !approved {
|
||||
http.Error(w, "login session expired", http.StatusGone)
|
||||
return
|
||||
}
|
||||
s.pushResult(r.Context(), sessionID, uuid, "approved", result.Success.User, display)
|
||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
if _, err := w.Write([]byte("Minecraft account linked. You may return to the game.")); err != nil {
|
||||
s.logger.Warn("write Minecraft account link response", "error", err, "session_id", sessionID)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) approveCASLogin(ctx context.Context, serverID, minecraftUUID, sessionID, minecraftName, subject, display string) (bool, bool, error) {
|
||||
nameKey := strings.ToLower(strings.TrimSpace(minecraftName))
|
||||
minecraftUUID = strings.ToLower(minecraftUUID)
|
||||
subject = strings.ToLower(strings.TrimSpace(subject))
|
||||
if nameKey == "" || subject == "" {
|
||||
return false, false, errors.New("minecraft username and CAS subject are required for account binding")
|
||||
}
|
||||
err := s.transaction.WithinTransaction(ctx, func(queries repository.Querier) error {
|
||||
boundSubject, err := queries.GetBoundSubjectForName(ctx, nameKey)
|
||||
nameBound := err == nil
|
||||
if err != nil && !errors.Is(err, repository.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
boundName, err := queries.GetBoundNameForSubject(ctx, subject)
|
||||
subjectBound := err == nil
|
||||
if err != nil && !errors.Is(err, repository.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
boundSubjectForUUID, err := queries.GetBoundSubjectForUUID(ctx, repository.GetBoundSubjectForUUIDParams{ServerID: serverID, MinecraftUuid: minecraftUUID})
|
||||
uuidBound := err == nil
|
||||
if err != nil && !errors.Is(err, repository.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
boundUUIDForSubject, err := queries.GetBoundUUIDForSubject(ctx, repository.GetBoundUUIDForSubjectParams{ServerID: serverID, AccountSubject: subject})
|
||||
subjectBoundToUUID := err == nil
|
||||
if err != nil && !errors.Is(err, repository.ErrNoRows) {
|
||||
return err
|
||||
}
|
||||
if (nameBound && boundSubject != subject) || (subjectBound && boundName != nameKey) || (uuidBound && boundSubjectForUUID != subject) || (subjectBoundToUUID && boundUUIDForSubject != minecraftUUID) {
|
||||
return errAccountBindingConflict
|
||||
}
|
||||
if !nameBound && !subjectBound {
|
||||
if err := queries.InsertAccountBinding(ctx, repository.InsertAccountBindingParams{MinecraftNameKey: nameKey, MinecraftName: strings.TrimSpace(minecraftName), AccountSubject: subject, CreatedAt: databaseTime(time.Now())}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := queries.UpsertUUIDAccountBinding(ctx, repository.UpsertUUIDAccountBindingParams{ServerID: serverID, MinecraftUuid: minecraftUUID, MinecraftNameKey: nameKey, MinecraftName: strings.TrimSpace(minecraftName), AccountSubject: subject, CreatedAt: databaseTime(time.Now())}); err != nil {
|
||||
return err
|
||||
}
|
||||
updated, err := queries.ApproveSession(ctx, repository.ApproveSessionParams{AccountSubject: subject, AccountDisplayName: display, SessionID: sessionID, ServerID: serverID, ExpiresAt: databaseTime(time.Now())})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if updated == 0 {
|
||||
return errSessionNotApproved
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if errors.Is(err, errAccountBindingConflict) {
|
||||
return false, true, nil
|
||||
}
|
||||
if errors.Is(err, errSessionNotApproved) {
|
||||
return false, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, false, err
|
||||
}
|
||||
return true, false, nil
|
||||
}
|
||||
|
||||
type casResponse struct {
|
||||
Success struct {
|
||||
User string `xml:"user"`
|
||||
Attributes struct {
|
||||
DisplayName string `xml:"displayName"`
|
||||
} `xml:"attributes"`
|
||||
} `xml:"authenticationSuccess"`
|
||||
Failure struct {
|
||||
Code string `xml:"code,attr"`
|
||||
} `xml:"authenticationFailure"`
|
||||
}
|
||||
|
||||
func (s *Service) pushResult(ctx context.Context, id, uuid, status, subject, display string) {
|
||||
serverID, err := s.queries.GetSessionServerID(ctx, id)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
s.mu.Lock()
|
||||
c := s.clients[serverID]
|
||||
s.mu.Unlock()
|
||||
if c != nil {
|
||||
c.mu.Lock()
|
||||
_, subscribed := c.pending[id]
|
||||
c.mu.Unlock()
|
||||
if !subscribed {
|
||||
return
|
||||
}
|
||||
s.sendResult(c, id, uuid, status, subject, display)
|
||||
}
|
||||
}
|
||||
|
||||
func parseTime(value string) time.Time {
|
||||
parsed, err := time.Parse(time.RFC3339Nano, value)
|
||||
if err != nil {
|
||||
return time.Time{}
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
func databaseTime(t time.Time) string { return t.UTC().Format("2006-01-02T15:04:05.000000000Z") }
|
||||
|
||||
func validUUID(value string) bool {
|
||||
if len(value) != 36 || value[8] != '-' || value[13] != '-' || value[18] != '-' || value[23] != '-' {
|
||||
return false
|
||||
}
|
||||
compact := strings.ReplaceAll(value, "-", "")
|
||||
decoded := make([]byte, 16)
|
||||
_, err := hex.Decode(decoded, []byte(compact))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func randomToken(size int) (string, error) {
|
||||
b := make([]byte, size)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", fmt.Errorf("generate random token: %w", err)
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(b), nil
|
||||
}
|
||||
|
||||
func errorMessage(requestID, code string, retry int) map[string]any {
|
||||
msg := map[string]any{"type": "error", "request_id": requestID, "code": code}
|
||||
if retry > 0 {
|
||||
msg["retry_after_seconds"] = retry
|
||||
}
|
||||
return msg
|
||||
}
|
||||
|
||||
func ParseCredentials(value string) map[string]string {
|
||||
result := map[string]string{}
|
||||
for _, entry := range strings.Split(value, ";") {
|
||||
id, token, ok := strings.Cut(strings.TrimSpace(entry), "=")
|
||||
if ok && id != "" && token != "" {
|
||||
result[id] = token
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,376 @@
|
||||
package minecraft
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"oauth-mc-web/internal/database"
|
||||
"oauth-mc-web/internal/database/repository"
|
||||
)
|
||||
|
||||
func TestUnlinkAccountIsServerScopedAndIdempotent(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, err := database.Open(ctx, filepath.Join(t.TempDir(), "minecraft.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := db.Close(); err != nil {
|
||||
t.Errorf("close database: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
const uuid = "123e4567-e89b-12d3-a456-426614174000"
|
||||
if err := db.WithinTransaction(ctx, func(queries repository.Querier) error {
|
||||
if err := queries.InsertAccountBinding(ctx, repository.InsertAccountBindingParams{
|
||||
MinecraftNameKey: "playername",
|
||||
MinecraftName: "PlayerName",
|
||||
AccountSubject: "subject-1",
|
||||
CreatedAt: "2026-09-29T00:00:00Z",
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return queries.UpsertUUIDAccountBinding(ctx, repository.UpsertUUIDAccountBindingParams{
|
||||
ServerID: "server-a",
|
||||
MinecraftUuid: uuid,
|
||||
MinecraftNameKey: "playername",
|
||||
MinecraftName: "PlayerName",
|
||||
AccountSubject: "subject-1",
|
||||
CreatedAt: "2026-09-29T00:00:00Z",
|
||||
})
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
service := New(db.Queries, db, Config{Credentials: map[string]string{"server-a": "token-a", "server-b": "token-b"}}, slog.New(slog.NewTextHandler(io.Discard, nil)))
|
||||
|
||||
otherConnection := openMinecraftTestConnection(t, service, "server-b", "token-b")
|
||||
if result := sendUnlinkTestRequest(t, otherConnection, "request-b", uuid, "display-only"); result.Status != "not_linked" {
|
||||
t.Fatalf("expected other server to see no link, got %q", result.Status)
|
||||
}
|
||||
if _, err := db.Queries.GetBoundAccountForUUID(ctx, repository.GetBoundAccountForUUIDParams{ServerID: "server-a", MinecraftUuid: uuid}); err != nil {
|
||||
t.Fatalf("other server's request changed the link: %v", err)
|
||||
}
|
||||
connection := openMinecraftTestConnection(t, service, "server-a", "token-a")
|
||||
result := sendUnlinkTestRequest(t, connection, "request-a", uuid, "renamed-player")
|
||||
if result.Status != "unlinked" || result.UUID != uuid || result.RequestID != "request-a" {
|
||||
t.Fatalf("unexpected unlink result: %#v", result)
|
||||
}
|
||||
result = sendUnlinkTestRequest(t, connection, "request-a", uuid, "different-display-name")
|
||||
if result.Status != "unlinked" {
|
||||
t.Fatalf("duplicate request did not replay its original result: %#v", result)
|
||||
}
|
||||
if _, err := db.Queries.GetBoundAccountForUUID(ctx, repository.GetBoundAccountForUUIDParams{ServerID: "server-a", MinecraftUuid: uuid}); err == nil {
|
||||
t.Fatal("unlink left the UUID account binding in place")
|
||||
}
|
||||
if _, err := db.Queries.GetBoundSubjectForName(ctx, "playername"); err == nil {
|
||||
t.Fatal("unlink left an unused account binding in place")
|
||||
}
|
||||
|
||||
if err := connection.WriteJSON(wireMessage{Type: "unlink_account", RequestID: "request-a", MinecraftUUID: "223e4567-e89b-12d3-a456-426614174000"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, payload, err := connection.ReadMessage()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var response struct {
|
||||
Type string `json:"type"`
|
||||
Code string `json:"code"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
if err := json.Unmarshal(payload, &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Type != "error" || response.Code != "invalid_request" || response.RequestID != "request-a" {
|
||||
t.Fatalf("expected reused request ID to be rejected, got %#v", response)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApproveCASLoginCreatesServerScopedUUIDBinding(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, err := database.Open(ctx, filepath.Join(t.TempDir(), "minecraft.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := db.Close(); err != nil {
|
||||
t.Errorf("close database: %v", err)
|
||||
}
|
||||
})
|
||||
service := New(db.Queries, db, Config{}, slog.New(slog.NewTextHandler(io.Discard, nil)))
|
||||
const uuid = "123e4567-e89b-12d3-a456-426614174000"
|
||||
for _, session := range []struct {
|
||||
id string
|
||||
serverID string
|
||||
}{
|
||||
{id: "session-a", serverID: "server-a"},
|
||||
{id: "session-b", serverID: "server-b"},
|
||||
} {
|
||||
if err := db.Queries.InsertSession(ctx, repository.InsertSessionParams{
|
||||
SessionID: session.id,
|
||||
RequestID: "request-" + session.id,
|
||||
ServerID: session.serverID,
|
||||
MinecraftUuid: uuid,
|
||||
MinecraftName: "PlayerName",
|
||||
Code: "code-" + session.id,
|
||||
LoginUrl: "https://minecraft.example/login",
|
||||
ExpiresAt: databaseTime(time.Now().Add(time.Minute)),
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
approved, conflict, err := service.approveCASLogin(ctx, session.serverID, uuid, session.id, "PlayerName", "subject-1", "Player")
|
||||
if err != nil || !approved || conflict {
|
||||
t.Fatalf("approve login for %s: approved=%t conflict=%t err=%v", session.serverID, approved, conflict, err)
|
||||
}
|
||||
if _, err := db.Queries.GetBoundAccountForUUID(ctx, repository.GetBoundAccountForUUIDParams{ServerID: session.serverID, MinecraftUuid: uuid}); err != nil {
|
||||
t.Fatalf("read UUID binding for %s: %v", session.serverID, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginStartRequestIsIdempotent(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, err := database.Open(ctx, filepath.Join(t.TempDir(), "minecraft.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := db.Close(); err != nil {
|
||||
t.Errorf("close database: %v", err)
|
||||
}
|
||||
})
|
||||
service := New(db.Queries, db, Config{
|
||||
Credentials: map[string]string{"server-a": "token-a"},
|
||||
LoginURL: "https://minecraft.example/login",
|
||||
}, slog.New(slog.NewTextHandler(io.Discard, nil)))
|
||||
connection := openMinecraftTestConnection(t, service, "server-a", "token-a")
|
||||
first := sendLoginStartTestRequest(t, connection, "request-a", "123e4567-e89b-12d3-a456-426614174000", "PlayerName")
|
||||
second := sendLoginStartTestRequest(t, connection, "request-a", "123e4567-e89b-12d3-a456-426614174000", "ChangedDisplayName")
|
||||
if first.SessionID == "" || first.RequestID != "request-a" || first.UUID != "123e4567-e89b-12d3-a456-426614174000" || second.RequestID != first.RequestID || second.UUID != first.UUID || second.SessionID != first.SessionID || second.LoginURL != first.LoginURL || second.ExpiresAt != first.ExpiresAt {
|
||||
t.Fatalf("duplicate request did not return its original session: first=%#v second=%#v", first, second)
|
||||
}
|
||||
pending, err := db.Queries.ListPendingSessionIDsForPlayer(ctx, repository.ListPendingSessionIDsForPlayerParams{ServerID: "server-a", MinecraftUuid: "123e4567-e89b-12d3-a456-426614174000"})
|
||||
if err != nil || len(pending) != 1 || pending[0] != first.SessionID {
|
||||
t.Fatalf("duplicate request created additional sessions: pending=%v err=%v", pending, err)
|
||||
}
|
||||
if err := connection.WriteJSON(wireMessage{Type: "login_start", RequestID: "request-a", Player: struct {
|
||||
UUID string `json:"minecraft_uuid"`
|
||||
Name string `json:"minecraft_name"`
|
||||
}{UUID: "223e4567-e89b-12d3-a456-426614174000", Name: "AnotherPlayer"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, payload, err := connection.ReadMessage()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var response struct {
|
||||
Type string `json:"type"`
|
||||
Code string `json:"code"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
if err := json.Unmarshal(payload, &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Type != "error" || response.Code != "invalid_request" || response.RequestID != "request-a" {
|
||||
t.Fatalf("expected request ID reuse with another UUID to fail, got %#v", response)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnknownMessageTypeEchoesRequestID(t *testing.T) {
|
||||
db, err := database.Open(context.Background(), filepath.Join(t.TempDir(), "minecraft.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := db.Close(); err != nil {
|
||||
t.Errorf("close database: %v", err)
|
||||
}
|
||||
})
|
||||
service := New(db.Queries, db, Config{Credentials: map[string]string{"server-a": "token-a"}}, slog.New(slog.NewTextHandler(io.Discard, nil)))
|
||||
connection := openMinecraftTestConnection(t, service, "server-a", "token-a")
|
||||
if err := connection.WriteJSON(wireMessage{Type: "unsupported_request", RequestID: "request-unknown"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, payload, err := connection.ReadMessage()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var response struct {
|
||||
Type string `json:"type"`
|
||||
Code string `json:"code"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
if err := json.Unmarshal(payload, &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Type != "error" || response.Code != "unknown_message_type" || response.RequestID != "request-unknown" {
|
||||
t.Fatalf("unexpected protocol error: %#v", response)
|
||||
}
|
||||
}
|
||||
|
||||
func openMinecraftTestConnection(t *testing.T, service *Service, serverID, token string) *websocket.Conn {
|
||||
t.Helper()
|
||||
serverConn, clientConn := net.Pipe()
|
||||
writer := &pipeResponseWriter{header: make(http.Header), connection: serverConn}
|
||||
handlerDone := make(chan struct{})
|
||||
go func() {
|
||||
reader := bufio.NewReader(serverConn)
|
||||
request, err := http.ReadRequest(reader)
|
||||
if err != nil {
|
||||
close(handlerDone)
|
||||
return
|
||||
}
|
||||
writer.reader = reader
|
||||
request = request.WithContext(context.Background())
|
||||
service.handleWebSocket(writer, request)
|
||||
close(handlerDone)
|
||||
}()
|
||||
headers := make(http.Header)
|
||||
headers.Set("Authorization", "Bearer "+token)
|
||||
dialer := websocket.Dialer{
|
||||
HandshakeTimeout: 2 * time.Second,
|
||||
NetDialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if network != "tcp" || address == "" {
|
||||
return nil, errors.New("unexpected websocket dial target")
|
||||
}
|
||||
return clientConn, nil
|
||||
},
|
||||
}
|
||||
connection, response, err := dialer.Dial("ws://auth.local/api/v1/minecraft/ws", headers)
|
||||
if err != nil {
|
||||
if closeErr := clientConn.Close(); closeErr != nil {
|
||||
t.Errorf("close client pipe after failed handshake: %v", closeErr)
|
||||
}
|
||||
if closeErr := serverConn.Close(); closeErr != nil {
|
||||
t.Errorf("close server pipe after failed handshake: %v", closeErr)
|
||||
}
|
||||
<-handlerDone
|
||||
t.Fatalf("connect websocket: %v, HTTP status %d, body %q", err, writer.status, writer.body.String())
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := connection.Close(); err != nil {
|
||||
t.Errorf("close websocket: %v", err)
|
||||
}
|
||||
})
|
||||
if err := connection.WriteJSON(wireMessage{Type: "hello", ProtocolVersion: protocolVersion, ServerID: serverID, PendingSessions: []string{}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, payload, err := connection.ReadMessage()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var ready struct {
|
||||
Type string `json:"type"`
|
||||
}
|
||||
if err := json.Unmarshal(payload, &ready); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ready.Type != "ready" {
|
||||
t.Fatalf("expected ready message, got %q (HTTP %d)", ready.Type, response.StatusCode)
|
||||
}
|
||||
return connection
|
||||
}
|
||||
|
||||
type pipeResponseWriter struct {
|
||||
header http.Header
|
||||
connection net.Conn
|
||||
reader *bufio.Reader
|
||||
status int
|
||||
body bytes.Buffer
|
||||
}
|
||||
|
||||
func (writer *pipeResponseWriter) Header() http.Header {
|
||||
return writer.header
|
||||
}
|
||||
|
||||
func (writer *pipeResponseWriter) Write(body []byte) (int, error) {
|
||||
return writer.body.Write(body)
|
||||
}
|
||||
|
||||
func (writer *pipeResponseWriter) WriteHeader(status int) {
|
||||
writer.status = status
|
||||
}
|
||||
|
||||
func (writer *pipeResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
|
||||
return writer.connection, bufio.NewReadWriter(writer.reader, bufio.NewWriter(writer.connection)), nil
|
||||
}
|
||||
|
||||
func sendUnlinkTestRequest(t *testing.T, connection *websocket.Conn, requestID, uuid, name string) struct {
|
||||
RequestID string `json:"request_id"`
|
||||
UUID string `json:"minecraft_uuid"`
|
||||
Status string `json:"status"`
|
||||
} {
|
||||
t.Helper()
|
||||
if err := connection.WriteJSON(wireMessage{Type: "unlink_account", RequestID: requestID, MinecraftUUID: uuid, MinecraftName: name}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, payload, err := connection.ReadMessage()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var result struct {
|
||||
RequestID string `json:"request_id"`
|
||||
UUID string `json:"minecraft_uuid"`
|
||||
Status string `json:"status"`
|
||||
}
|
||||
if err := json.Unmarshal(payload, &result); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func sendLoginStartTestRequest(t *testing.T, connection *websocket.Conn, requestID, uuid, name string) struct {
|
||||
RequestID string `json:"request_id"`
|
||||
UUID string `json:"minecraft_uuid"`
|
||||
SessionID string `json:"session_id"`
|
||||
LoginURL string `json:"login_url"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
} {
|
||||
t.Helper()
|
||||
message := wireMessage{Type: "login_start", RequestID: requestID}
|
||||
message.Player.UUID = uuid
|
||||
message.Player.Name = name
|
||||
if err := connection.WriteJSON(message); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, payload, err := connection.ReadMessage()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var response struct {
|
||||
RequestID string `json:"request_id"`
|
||||
UUID string `json:"minecraft_uuid"`
|
||||
Type string `json:"type"`
|
||||
SessionID string `json:"session_id"`
|
||||
LoginURL string `json:"login_url"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
}
|
||||
if err := json.Unmarshal(payload, &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Type != "login_started" {
|
||||
t.Fatalf("expected login_started response, got %q", response.Type)
|
||||
}
|
||||
return struct {
|
||||
RequestID string `json:"request_id"`
|
||||
UUID string `json:"minecraft_uuid"`
|
||||
SessionID string `json:"session_id"`
|
||||
LoginURL string `json:"login_url"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
}{RequestID: response.RequestID, UUID: response.UUID, SessionID: response.SessionID, LoginURL: response.LoginURL, ExpiresAt: response.ExpiresAt}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"oauth-mc-web/internal/config"
|
||||
"oauth-mc-web/internal/database"
|
||||
"oauth-mc-web/internal/middleware"
|
||||
"oauth-mc-web/internal/minecraft"
|
||||
)
|
||||
|
||||
type routeHandler interface {
|
||||
Health(http.ResponseWriter, *http.Request)
|
||||
}
|
||||
|
||||
type healthRoutes struct {
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func (routes healthRoutes) Health(w http.ResponseWriter, request *http.Request) {
|
||||
if request.Method != http.MethodGet {
|
||||
http.NotFound(w, request)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
if _, err := w.Write([]byte(`{"status":"ok"}`)); err != nil && routes.logger != nil {
|
||||
routes.logger.Warn("write health response", "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
http *http.Server
|
||||
db *database.DB
|
||||
auth *minecraft.Service
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*Server, error) {
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
db, err := database.Open(ctx, cfg.DatabasePath)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open database: %w", err)
|
||||
}
|
||||
auth := minecraft.New(db.Queries, db, minecraft.Config{
|
||||
Credentials: minecraft.ParseCredentials(cfg.MinecraftServerTokens),
|
||||
LoginURL: cfg.MinecraftLoginURL,
|
||||
CASLoginURL: cfg.CASLoginURL,
|
||||
CASValidate: cfg.CASValidateURL,
|
||||
CASService: cfg.CASServiceURL,
|
||||
SessionTTL: cfg.MinecraftSessionTTL,
|
||||
AllowHTTPService: cfg.AllowHTTPService,
|
||||
}, logger)
|
||||
return &Server{db: db, auth: auth, logger: logger, http: &http.Server{Addr: cfg.HTTPAddr, Handler: middleware.Logging(logger)(route(healthRoutes{logger: logger}, auth)), ReadHeaderTimeout: 5 * time.Second}}, nil
|
||||
}
|
||||
|
||||
func route(routes routeHandler, auth *minecraft.Service) *http.ServeMux {
|
||||
r := http.NewServeMux()
|
||||
r.HandleFunc("GET /healthz", routes.Health)
|
||||
r.HandleFunc("GET /api/v1/minecraft/ws", auth.WebSocketHandler)
|
||||
r.HandleFunc("GET /api/v1/minecraft/login", auth.LoginPageHandler)
|
||||
r.HandleFunc("GET "+auth.CallbackPath(), auth.CASCallbackHandler)
|
||||
return r
|
||||
}
|
||||
|
||||
func (s *Server) Run(ctx context.Context) error {
|
||||
defer func() {
|
||||
if err := s.db.Close(); err != nil {
|
||||
s.logger.Error("close database", "error", err)
|
||||
}
|
||||
}()
|
||||
go s.auth.RunMaintenance(ctx)
|
||||
go func() {
|
||||
<-ctx.Done()
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := s.http.Shutdown(shutdownCtx); err != nil {
|
||||
s.logger.Error("shutdown HTTP server", "error", err)
|
||||
}
|
||||
}()
|
||||
s.logger.Info("HTTP server listening", "address", s.http.Addr)
|
||||
if err := s.http.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
return fmt.Errorf("http server: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"log/slog"
|
||||
"os"
|
||||
"os/signal"
|
||||
|
||||
"oauth-mc-web/internal/config"
|
||||
"oauth-mc-web/internal/server"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
log.Fatalf("load configuration: %v", err)
|
||||
}
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
|
||||
defer stop()
|
||||
logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
|
||||
srv, err := server.New(ctx, cfg, logger)
|
||||
if err != nil {
|
||||
log.Fatalf("initialize server: %v", err)
|
||||
}
|
||||
if err := srv.Run(ctx); err != nil {
|
||||
log.Fatalf("run server: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
version: "2"
|
||||
sql:
|
||||
- engine: "sqlite"
|
||||
schema: "internal/database/schema"
|
||||
queries: "internal/database/repository/query.sql"
|
||||
gen:
|
||||
go:
|
||||
package: "repository"
|
||||
out: "internal/database/repository"
|
||||
emit_json_tags: false
|
||||
emit_interface: true
|
||||
emit_exact_table_names: false
|
||||
Reference in New Issue
Block a user