feat: 3 account limit
This commit is contained in:
@@ -4,15 +4,20 @@ go 1.27
|
||||
|
||||
require (
|
||||
github.com/a-h/templ v0.3.960
|
||||
github.com/golang-migrate/migrate/v4 v4.18.3
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
github.com/jackc/pgx/v5 v5.7.6
|
||||
github.com/joho/godotenv v1.5.1
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/hashicorp/errwrap v1.1.0 // indirect
|
||||
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/lib/pq v1.10.9 // indirect
|
||||
go.uber.org/atomic v1.7.0 // indirect
|
||||
golang.org/x/crypto v0.37.0 // indirect
|
||||
golang.org/x/sync v0.16.0 // indirect
|
||||
golang.org/x/text v0.24.0 // indirect
|
||||
|
||||
@@ -1,12 +1,41 @@
|
||||
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161 h1:L/gRVlceqvL25UVaW/CKtUDjefjrs0SPonmDGUVOYP0=
|
||||
github.com/Azure/go-ansiterm v0.0.0-20230124172434-306776ec8161/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
|
||||
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
|
||||
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
||||
github.com/a-h/templ v0.3.960 h1:trshEpGa8clF5cdI39iY4ZrZG8Z/QixyzEyUnA7feTM=
|
||||
github.com/a-h/templ v0.3.960/go.mod h1:oCZcnKRf5jjsGpf2yELzQfodLphd2mwecwG4Crk5HBo=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dhui/dktest v0.4.5 h1:uUfYBIVREmj/Rw6MvgmqNAYzTiKOHJak+enB5Di73MM=
|
||||
github.com/dhui/dktest v0.4.5/go.mod h1:tmcyeHDKagvlDrz7gDKq4UAJOLIfVZYkfD5OnHDwcCo=
|
||||
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
|
||||
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
|
||||
github.com/docker/docker v27.2.0+incompatible h1:Rk9nIVdfH3+Vz4cyI/uhbINhEZ/oLmc+CBXmH6fbNk4=
|
||||
github.com/docker/docker v27.2.0+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
|
||||
github.com/docker/go-connections v0.5.0 h1:USnMq7hx7gwdVZq1L49hLXaFtUdTADjXGp+uj1Br63c=
|
||||
github.com/docker/go-connections v0.5.0/go.mod h1:ov60Kzw0kKElRwhNs9UlUHAE/F9Fe6GLaXnqyDdmEXc=
|
||||
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
|
||||
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
|
||||
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
|
||||
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
||||
github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY=
|
||||
github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
|
||||
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
|
||||
github.com/golang-migrate/migrate/v4 v4.18.3 h1:EYGkoOsvgHHfm5U/naS1RP/6PL/Xv3S4B/swMiAmDLs=
|
||||
github.com/golang-migrate/migrate/v4 v4.18.3/go.mod h1:99BKpIi6ruaaXRM1A77eqZ+FWPQ3cfRa+ZVy5bmWMaY=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
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/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
|
||||
github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I=
|
||||
github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
|
||||
github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=
|
||||
github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
@@ -17,6 +46,20 @@ github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
|
||||
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
|
||||
github.com/moby/term v0.5.0 h1:xt8Q1nalod/v7BqbG21f8mQPqH+xAaC9C3N3wfWbVP0=
|
||||
github.com/moby/term v0.5.0/go.mod h1:8FzsFHVUBGZdbDsJw/ot+X+d5HLUbvklYLJ9uGfcI3Y=
|
||||
github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=
|
||||
github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=
|
||||
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
|
||||
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
|
||||
github.com/opencontainers/image-spec v1.1.0 h1:8SG7/vwALn54lVB/0yZ/MMwhFrPYtpEHQb2IpWsCzug=
|
||||
github.com/opencontainers/image-spec v1.1.0/go.mod h1:W4s4sFTMaBeK1BQLXbG4AdM2szdn85PY75RI83NrTrM=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
@@ -24,10 +67,22 @@ github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UV
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.54.0 h1:TT4fX+nBOA/+LUkobKGW1ydGcn+G3vRw9+g5HwCphpk=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.54.0/go.mod h1:L7UH0GbB0p47T4Rri3uHjbpCFYrVrwc1I25QhNPiGK8=
|
||||
go.opentelemetry.io/otel v1.29.0 h1:PdomN/Al4q/lN6iBJEN3AwPvUiHPMlt93c8bqTG5Llw=
|
||||
go.opentelemetry.io/otel v1.29.0/go.mod h1:N/WtXPs1CNCUEx+Agz5uouwCba+i+bJGFicT8SR4NP8=
|
||||
go.opentelemetry.io/otel/metric v1.29.0 h1:vPf/HFWTNkPu1aYeIsc98l4ktOQaL6LeSoeV2g+8YLc=
|
||||
go.opentelemetry.io/otel/metric v1.29.0/go.mod h1:auu/QWieFVWx+DmQOUMgj0F8LHWdgalxXqvp7BII/W8=
|
||||
go.opentelemetry.io/otel/trace v1.29.0 h1:J/8ZNK4XgR7a21DZUAsbF8pZ5Jcw1VhACmnYt39JTi4=
|
||||
go.opentelemetry.io/otel/trace v1.29.0/go.mod h1:eHl3w0sp3paPkYstJOmAimxhiFXPg+MMTlEh3nsQgWQ=
|
||||
go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw=
|
||||
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
|
||||
golang.org/x/crypto v0.37.0 h1:kJNSjF/Xp7kU0iB2Z+9viTPMW4EqqsrywMXLJOOsXSE=
|
||||
golang.org/x/crypto v0.37.0/go.mod h1:vg+k43peMZ0pUMhYmVAWysMK35e6ioLh3wB8ZCAfbVc=
|
||||
golang.org/x/sync v0.16.0 h1:ycBJEhp9p4vXvUZNszeOq0kGTPghopOL8q0fq3vstxw=
|
||||
golang.org/x/sync v0.16.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA=
|
||||
golang.org/x/sys v0.34.0 h1:H5Y5sJ2L2JRdyv7ROF1he/lPdvFsd0mJHFw2ThKHxLA=
|
||||
golang.org/x/sys v0.34.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k=
|
||||
golang.org/x/text v0.24.0 h1:dd5Bzh4yt5KYA8f9CJHCP4FB4D51c2c6JvN37xJJkJ0=
|
||||
golang.org/x/text v0.24.0/go.mod h1:L8rBsPeo2pSS+xqN0d5u2ikmjtmoJbDBT1b7nHvFCdU=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
|
||||
@@ -3,13 +3,15 @@ package database
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
_ "embed"
|
||||
"embed"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"oauth-mc-web/internal/database/repository"
|
||||
|
||||
"github.com/golang-migrate/migrate/v4"
|
||||
_ "github.com/golang-migrate/migrate/v4/database/postgres"
|
||||
"github.com/golang-migrate/migrate/v4/source/iofs"
|
||||
_ "github.com/jackc/pgx/v5/stdlib"
|
||||
)
|
||||
|
||||
@@ -22,8 +24,8 @@ type TransactionRunner interface {
|
||||
WithinTransaction(context.Context, func(repository.Querier) error) error
|
||||
}
|
||||
|
||||
//go:embed schema/schema.sql
|
||||
var schema string
|
||||
//go:embed migrations/*.sql
|
||||
var migrationFiles embed.FS
|
||||
|
||||
func Open(ctx context.Context, databaseURL string) (*DB, error) {
|
||||
if databaseURL == "" {
|
||||
@@ -33,13 +35,21 @@ func Open(ctx context.Context, databaseURL string) (*DB, error) {
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open PostgreSQL database: %w", err)
|
||||
}
|
||||
for _, statement := range strings.Split(schema, ";") {
|
||||
if strings.TrimSpace(statement) == "" {
|
||||
continue
|
||||
}
|
||||
if _, err := db.ExecContext(ctx, statement); err != nil {
|
||||
return nil, closeWithError(db, fmt.Errorf("initialize PostgreSQL schema: %w", err))
|
||||
}
|
||||
source, err := iofs.New(migrationFiles, "migrations")
|
||||
if err != nil {
|
||||
return nil, closeWithError(db, fmt.Errorf("open database migrations: %w", err))
|
||||
}
|
||||
migrator, err := migrate.NewWithSourceInstance("iofs", source, databaseURL)
|
||||
if err != nil {
|
||||
return nil, closeWithError(db, fmt.Errorf("create database migrator: %w", err))
|
||||
}
|
||||
if err := migrator.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) {
|
||||
sourceErr, databaseErr := migrator.Close()
|
||||
migrationErr := errors.Join(fmt.Errorf("apply database migrations: %w", err), sourceErr, databaseErr)
|
||||
return nil, closeWithError(db, migrationErr)
|
||||
}
|
||||
if _, err := migrator.Close(); err != nil {
|
||||
return nil, closeWithError(db, fmt.Errorf("close database migrator: %w", err))
|
||||
}
|
||||
queries := repository.New(db)
|
||||
if err := queries.RestoreAccountBindings(ctx); err != nil {
|
||||
|
||||
@@ -12,9 +12,12 @@ import (
|
||||
"oauth-mc-web/internal/database/testutil"
|
||||
)
|
||||
|
||||
//go:embed migrations/0002_uuid_account_bindings.sql
|
||||
//go:embed migrations/0002_uuid_account_bindings.up.sql
|
||||
var uuidAccountBindingsMigration string
|
||||
|
||||
//go:embed migrations/0003_three_minecraft_accounts_per_sso.up.sql
|
||||
var threeMinecraftAccountsMigration string
|
||||
|
||||
func TestWithinTransaction(t *testing.T) {
|
||||
db, err := Open(context.Background(), testutil.URL(t))
|
||||
if err != nil {
|
||||
@@ -81,7 +84,7 @@ func TestOpenDoesNotRestoreUnlinkedBindingFromOldSessions(t *testing.T) {
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := queries.UpsertUUIDAccountBinding(ctx, repository.UpsertUUIDAccountBindingParams{
|
||||
if _, err := queries.UpsertUUIDAccountBinding(ctx, repository.UpsertUUIDAccountBindingParams{
|
||||
ServerID: "server-a",
|
||||
MinecraftUuid: "123e4567-e89b-12d3-a456-426614174000",
|
||||
MinecraftNameKey: "playername",
|
||||
@@ -208,3 +211,70 @@ func TestUUIDAccountBindingsMigrationBackfillsRetainedSessions(t *testing.T) {
|
||||
t.Fatalf("read migrated login request: session_id=%q err=%v", request.SessionID, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestThreeMinecraftAccountsMigrationPreservesExistingBindings(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, err := Open(ctx, testutil.URL(t))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if err := db.Close(); err != nil {
|
||||
t.Errorf("close database: %v", err)
|
||||
}
|
||||
})
|
||||
for _, statement := range []string{
|
||||
"ALTER TABLE minecraft_account_bindings ADD CONSTRAINT minecraft_account_bindings_account_subject_key UNIQUE (account_subject)",
|
||||
"ALTER TABLE minecraft_uuid_account_bindings ADD CONSTRAINT minecraft_uuid_account_bindings_server_id_account_subject_key UNIQUE (server_id, account_subject)",
|
||||
} {
|
||||
if _, err := db.sql.ExecContext(ctx, statement); err != nil {
|
||||
t.Fatalf("restore legacy constraint: %v", err)
|
||||
}
|
||||
}
|
||||
if err := db.Queries.InsertAccountBinding(ctx, repository.InsertAccountBindingParams{
|
||||
MinecraftNameKey: "legacyplayer",
|
||||
MinecraftName: "LegacyPlayer",
|
||||
AccountSubject: "subject-legacy",
|
||||
CreatedAt: "2026-01-01T00:00:00Z",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for index, uuid := range []string{
|
||||
"123e4567-e89b-12d3-a456-426614174001",
|
||||
"123e4567-e89b-12d3-a456-426614174002",
|
||||
} {
|
||||
if _, err := db.Queries.UpsertUUIDAccountBinding(ctx, repository.UpsertUUIDAccountBindingParams{
|
||||
ServerID: "server-" + string(rune('a'+index)),
|
||||
MinecraftUuid: uuid,
|
||||
MinecraftNameKey: "legacyplayer",
|
||||
MinecraftName: "LegacyPlayer",
|
||||
AccountSubject: "subject-legacy",
|
||||
CreatedAt: "2026-01-01T00:00:00Z",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
for _, statement := range strings.Split(threeMinecraftAccountsMigration, ";") {
|
||||
if strings.TrimSpace(statement) == "" {
|
||||
continue
|
||||
}
|
||||
if _, err := db.sql.ExecContext(ctx, statement); err != nil {
|
||||
t.Fatalf("apply three-account migration: %v", err)
|
||||
}
|
||||
}
|
||||
var existing int
|
||||
if err := db.sql.QueryRowContext(ctx, "SELECT COUNT(*) FROM minecraft_uuid_account_bindings WHERE account_subject = $1", "subject-legacy").Scan(&existing); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if existing != 2 {
|
||||
t.Fatalf("migration changed existing bindings: got %d, want 2", existing)
|
||||
}
|
||||
if err := db.Queries.InsertAccountBinding(ctx, repository.InsertAccountBindingParams{
|
||||
MinecraftNameKey: "anotherplayer",
|
||||
MinecraftName: "AnotherPlayer",
|
||||
AccountSubject: "subject-legacy",
|
||||
CreatedAt: "2026-01-01T00:00:00Z",
|
||||
}); err != nil {
|
||||
t.Fatalf("allow multiple legacy names for subject: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
DROP TABLE IF EXISTS minecraft_unlink_requests;
|
||||
DROP TABLE IF EXISTS minecraft_uuid_account_bindings;
|
||||
DROP TABLE IF EXISTS minecraft_account_bindings;
|
||||
DROP TABLE IF EXISTS minecraft_login_requests;
|
||||
DROP TABLE IF EXISTS minecraft_sessions;
|
||||
+2
-3
@@ -28,7 +28,7 @@ CREATE TABLE IF NOT EXISTS minecraft_login_requests (
|
||||
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,
|
||||
account_subject TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL
|
||||
);
|
||||
|
||||
@@ -39,8 +39,7 @@ CREATE TABLE IF NOT EXISTS minecraft_uuid_account_bindings (
|
||||
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)
|
||||
PRIMARY KEY (server_id, minecraft_uuid)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS minecraft_unlink_requests (
|
||||
@@ -0,0 +1 @@
|
||||
SELECT 1;
|
||||
@@ -0,0 +1,5 @@
|
||||
ALTER TABLE minecraft_account_bindings
|
||||
ADD CONSTRAINT minecraft_account_bindings_account_subject_key UNIQUE (account_subject);
|
||||
|
||||
ALTER TABLE minecraft_uuid_account_bindings
|
||||
ADD CONSTRAINT minecraft_uuid_account_bindings_server_id_account_subject_key UNIQUE (server_id, account_subject);
|
||||
@@ -0,0 +1,5 @@
|
||||
ALTER TABLE minecraft_account_bindings
|
||||
DROP CONSTRAINT IF EXISTS minecraft_account_bindings_account_subject_key;
|
||||
|
||||
ALTER TABLE minecraft_uuid_account_bindings
|
||||
DROP CONSTRAINT IF EXISTS minecraft_uuid_account_bindings_server_id_account_subject_key;
|
||||
@@ -1,5 +1,22 @@
|
||||
# Database data migrations
|
||||
# Database migrations
|
||||
|
||||
The application creates the current tables when it opens PostgreSQL. When upgrading an older 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.
|
||||
Migrations use [golang-migrate](https://github.com/golang-migrate/migrate) naming and numbering. `Open` applies pending migrations at startup. The migration files are embedded in the Go binary.
|
||||
|
||||
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.
|
||||
For manual operation, install the CLI and run it from the project root:
|
||||
|
||||
```sh
|
||||
go install -tags 'postgres' github.com/golang-migrate/migrate/v4/cmd/migrate@v4.18.3
|
||||
migrate -path internal/database/migrations -database "$DATABASE_URL" up
|
||||
```
|
||||
|
||||
`0001_initial_schema` creates the current schema. `0002_uuid_account_bindings` backfills UUID account bindings and durable login requests from retained sessions. `0003_three_minecraft_accounts_per_sso` removes the old uniqueness limits so an SSO subject can link up to three distinct Minecraft UUIDs.
|
||||
|
||||
To roll back one migration, run:
|
||||
|
||||
```sh
|
||||
migrate -path internal/database/migrations -database "$DATABASE_URL" down 1
|
||||
```
|
||||
|
||||
Rolling back `0003` restores the previous uniqueness constraints and will fail if current data violates them. Rolling back `0002` preserves migrated rows because deleting them could destroy account links and request history. Rolling back `0001` drops the application tables and their data.
|
||||
|
||||
The old schema associated accounts with Minecraft names. Migration `0002` 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.
|
||||
|
||||
@@ -13,6 +13,7 @@ type Querier interface {
|
||||
ApproveSession(ctx context.Context, arg ApproveSessionParams) (int64, error)
|
||||
CancelPendingSession(ctx context.Context, arg CancelPendingSessionParams) (int64, error)
|
||||
CountActivePendingSessions(ctx context.Context, arg CountActivePendingSessionsParams) (int64, error)
|
||||
CountMinecraftAccountsForSubject(ctx context.Context, accountSubject string) (int64, error)
|
||||
DeleteClosedSessions(ctx context.Context, expiresAt string) error
|
||||
DeleteClosedSessionsForServer(ctx context.Context, arg DeleteClosedSessionsForServerParams) error
|
||||
DeletePendingSessionsForPlayer(ctx context.Context, arg DeletePendingSessionsForPlayerParams) error
|
||||
@@ -40,8 +41,10 @@ type Querier interface {
|
||||
InsertUnlinkRequest(ctx context.Context, arg InsertUnlinkRequestParams) error
|
||||
ListExpiredSessions(ctx context.Context) ([]ListExpiredSessionsRow, error)
|
||||
ListPendingSessionIDsForPlayer(ctx context.Context, arg ListPendingSessionIDsForPlayerParams) ([]string, error)
|
||||
LockMinecraftAccountSubject(ctx context.Context, accountSubject string) error
|
||||
RestoreAccountBindings(ctx context.Context) error
|
||||
UpsertUUIDAccountBinding(ctx context.Context, arg UpsertUUIDAccountBindingParams) error
|
||||
SubjectOwnsMinecraftUUID(ctx context.Context, arg SubjectOwnsMinecraftUUIDParams) (bool, error)
|
||||
UpsertUUIDAccountBinding(ctx context.Context, arg UpsertUUIDAccountBindingParams) (int64, error)
|
||||
}
|
||||
|
||||
var _ Querier = (*Queries)(nil)
|
||||
|
||||
@@ -81,13 +81,28 @@ SELECT account_subject FROM minecraft_uuid_account_bindings WHERE server_id=$1 A
|
||||
-- name: GetBoundUUIDForSubject :one
|
||||
SELECT minecraft_uuid FROM minecraft_uuid_account_bindings WHERE server_id=$1 AND account_subject=$2;
|
||||
|
||||
-- name: LockMinecraftAccountSubject :exec
|
||||
SELECT pg_advisory_xact_lock(hashtextextended(@account_subject::text, 0));
|
||||
|
||||
-- name: CountMinecraftAccountsForSubject :one
|
||||
SELECT COUNT(DISTINCT minecraft_uuid)
|
||||
FROM minecraft_uuid_account_bindings
|
||||
WHERE account_subject=$1;
|
||||
|
||||
-- name: SubjectOwnsMinecraftUUID :one
|
||||
SELECT EXISTS(
|
||||
SELECT 1 FROM minecraft_uuid_account_bindings
|
||||
WHERE account_subject=$1 AND minecraft_uuid=$2
|
||||
);
|
||||
|
||||
-- name: InsertAccountBinding :exec
|
||||
INSERT INTO minecraft_account_bindings(minecraft_name_key, minecraft_name, account_subject, created_at) VALUES($1, $2, $3, $4);
|
||||
|
||||
-- name: UpsertUUIDAccountBinding :exec
|
||||
-- name: UpsertUUIDAccountBinding :execrows
|
||||
INSERT INTO minecraft_uuid_account_bindings(server_id, minecraft_uuid, minecraft_name_key, minecraft_name, account_subject, created_at)
|
||||
VALUES($1, $2, $3, $4, $5, $6)
|
||||
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;
|
||||
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
|
||||
WHERE minecraft_uuid_account_bindings.account_subject=excluded.account_subject;
|
||||
|
||||
-- name: DeleteUUIDAccountBinding :execrows
|
||||
DELETE FROM minecraft_uuid_account_bindings WHERE server_id=$1 AND minecraft_uuid=$2;
|
||||
|
||||
@@ -88,6 +88,19 @@ func (q *Queries) CountActivePendingSessions(ctx context.Context, arg CountActiv
|
||||
return count, err
|
||||
}
|
||||
|
||||
const countMinecraftAccountsForSubject = `-- name: CountMinecraftAccountsForSubject :one
|
||||
SELECT COUNT(DISTINCT minecraft_uuid)
|
||||
FROM minecraft_uuid_account_bindings
|
||||
WHERE account_subject=$1
|
||||
`
|
||||
|
||||
func (q *Queries) CountMinecraftAccountsForSubject(ctx context.Context, accountSubject string) (int64, error) {
|
||||
row := q.db.QueryRowContext(ctx, countMinecraftAccountsForSubject, accountSubject)
|
||||
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<=$1
|
||||
`
|
||||
@@ -611,6 +624,15 @@ func (q *Queries) ListPendingSessionIDsForPlayer(ctx context.Context, arg ListPe
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const lockMinecraftAccountSubject = `-- name: LockMinecraftAccountSubject :exec
|
||||
SELECT pg_advisory_xact_lock(hashtextextended($1::text, 0))
|
||||
`
|
||||
|
||||
func (q *Queries) LockMinecraftAccountSubject(ctx context.Context, accountSubject string) error {
|
||||
_, err := q.db.ExecContext(ctx, lockMinecraftAccountSubject, accountSubject)
|
||||
return err
|
||||
}
|
||||
|
||||
const restoreAccountBindings = `-- name: RestoreAccountBindings :exec
|
||||
INSERT 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
|
||||
@@ -623,10 +645,30 @@ func (q *Queries) RestoreAccountBindings(ctx context.Context) error {
|
||||
return err
|
||||
}
|
||||
|
||||
const upsertUUIDAccountBinding = `-- name: UpsertUUIDAccountBinding :exec
|
||||
const subjectOwnsMinecraftUUID = `-- name: SubjectOwnsMinecraftUUID :one
|
||||
SELECT EXISTS(
|
||||
SELECT 1 FROM minecraft_uuid_account_bindings
|
||||
WHERE account_subject=$1 AND minecraft_uuid=$2
|
||||
)
|
||||
`
|
||||
|
||||
type SubjectOwnsMinecraftUUIDParams struct {
|
||||
AccountSubject string
|
||||
MinecraftUuid string
|
||||
}
|
||||
|
||||
func (q *Queries) SubjectOwnsMinecraftUUID(ctx context.Context, arg SubjectOwnsMinecraftUUIDParams) (bool, error) {
|
||||
row := q.db.QueryRowContext(ctx, subjectOwnsMinecraftUUID, arg.AccountSubject, arg.MinecraftUuid)
|
||||
var exists bool
|
||||
err := row.Scan(&exists)
|
||||
return exists, err
|
||||
}
|
||||
|
||||
const upsertUUIDAccountBinding = `-- name: UpsertUUIDAccountBinding :execrows
|
||||
INSERT INTO minecraft_uuid_account_bindings(server_id, minecraft_uuid, minecraft_name_key, minecraft_name, account_subject, created_at)
|
||||
VALUES($1, $2, $3, $4, $5, $6)
|
||||
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
|
||||
WHERE minecraft_uuid_account_bindings.account_subject=excluded.account_subject
|
||||
`
|
||||
|
||||
type UpsertUUIDAccountBindingParams struct {
|
||||
@@ -638,8 +680,8 @@ type UpsertUUIDAccountBindingParams struct {
|
||||
CreatedAt string
|
||||
}
|
||||
|
||||
func (q *Queries) UpsertUUIDAccountBinding(ctx context.Context, arg UpsertUUIDAccountBindingParams) error {
|
||||
_, err := q.db.ExecContext(ctx, upsertUUIDAccountBinding,
|
||||
func (q *Queries) UpsertUUIDAccountBinding(ctx context.Context, arg UpsertUUIDAccountBindingParams) (int64, error) {
|
||||
result, err := q.db.ExecContext(ctx, upsertUUIDAccountBinding,
|
||||
arg.ServerID,
|
||||
arg.MinecraftUuid,
|
||||
arg.MinecraftNameKey,
|
||||
@@ -647,5 +689,8 @@ func (q *Queries) UpsertUUIDAccountBinding(ctx context.Context, arg UpsertUUIDAc
|
||||
arg.AccountSubject,
|
||||
arg.CreatedAt,
|
||||
)
|
||||
return err
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected()
|
||||
}
|
||||
|
||||
@@ -31,6 +31,7 @@ const (
|
||||
)
|
||||
|
||||
var errAccountBindingConflict = errors.New("minecraft account binding conflict")
|
||||
var errMinecraftAccountLimitReached = errors.New("SSO account already has three Minecraft accounts")
|
||||
var errSessionNotApproved = errors.New("minecraft session was not approved")
|
||||
var errUnlinkRequestReuse = errors.New("unlink request ID was already used for another UUID")
|
||||
|
||||
@@ -59,10 +60,8 @@ type sessionQueries interface {
|
||||
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)
|
||||
CountMinecraftAccountsForSubject(context.Context, string) (int64, error)
|
||||
GetLoginRequest(context.Context, repository.GetLoginRequestParams) (repository.GetLoginRequestRow, error)
|
||||
GetPendingSessionByCode(context.Context, string) (repository.GetPendingSessionByCodeRow, error)
|
||||
GetPendingSessionExpiry(context.Context, string) (string, error)
|
||||
@@ -70,13 +69,14 @@ type sessionQueries interface {
|
||||
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
|
||||
LockMinecraftAccountSubject(context.Context, string) 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
|
||||
SubjectOwnsMinecraftUUID(context.Context, repository.SubjectOwnsMinecraftUUIDParams) (bool, error)
|
||||
UpsertUUIDAccountBinding(context.Context, repository.UpsertUUIDAccountBindingParams) (int64, error)
|
||||
}
|
||||
|
||||
type transactionRunner interface {
|
||||
@@ -830,6 +830,22 @@ func (s *Service) handleCASCallback(w http.ResponseWriter, r *http.Request) {
|
||||
display = result.Success.User
|
||||
}
|
||||
approved, conflict, err := s.approveCASLogin(r.Context(), session.ServerID, uuid, sessionID, minecraftName, result.Success.User, display)
|
||||
if errors.Is(err, errMinecraftAccountLimitReached) {
|
||||
updated, denyErr := s.queries.DenyPendingSession(r.Context(), sessionID)
|
||||
if denyErr != nil {
|
||||
s.logger.Error("deny Minecraft login after reaching account link limit", "error", denyErr, "session_id", sessionID)
|
||||
redirectLoginResult(w, r, false)
|
||||
return
|
||||
}
|
||||
if updated == 0 {
|
||||
s.logger.Warn("Minecraft login session was no longer pending after reaching account link limit", "session_id", sessionID)
|
||||
redirectLoginResult(w, r, false)
|
||||
return
|
||||
}
|
||||
s.pushResult(r.Context(), sessionID, uuid, "denied", "", "")
|
||||
redirectLoginFailureReason(w, r, "account_limit")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
s.logger.Error("approve Minecraft CAS login", "error", err, "session_id", sessionID)
|
||||
redirectLoginResult(w, r, false)
|
||||
@@ -861,6 +877,10 @@ func redirectLoginResult(w http.ResponseWriter, r *http.Request, success bool) {
|
||||
http.Redirect(w, r, path, http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func redirectLoginFailureReason(w http.ResponseWriter, r *http.Request, reason string) {
|
||||
http.Redirect(w, r, LoginFailurePath+"?reason="+url.QueryEscape(reason), http.StatusSeeOther)
|
||||
}
|
||||
|
||||
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)
|
||||
@@ -869,14 +889,15 @@ func (s *Service) approveCASLogin(ctx context.Context, serverID, minecraftUUID,
|
||||
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 := queries.LockMinecraftAccountSubject(ctx, subject); err != nil {
|
||||
return err
|
||||
}
|
||||
linkedAccounts, err := queries.CountMinecraftAccountsForSubject(ctx, subject)
|
||||
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) {
|
||||
subjectOwnsUUID, err := queries.SubjectOwnsMinecraftUUID(ctx, repository.SubjectOwnsMinecraftUUIDParams{AccountSubject: subject, MinecraftUuid: minecraftUUID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
boundSubjectForUUID, err := queries.GetBoundSubjectForUUID(ctx, repository.GetBoundSubjectForUUIDParams{ServerID: serverID, MinecraftUuid: minecraftUUID})
|
||||
@@ -884,23 +905,20 @@ func (s *Service) approveCASLogin(ctx context.Context, serverID, minecraftUUID,
|
||||
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) {
|
||||
if uuidBound && boundSubjectForUUID != subject {
|
||||
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 linkedAccounts >= 3 && !subjectOwnsUUID {
|
||||
return errMinecraftAccountLimitReached
|
||||
}
|
||||
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 {
|
||||
updated, err := queries.UpsertUUIDAccountBinding(ctx, repository.UpsertUUIDAccountBindingParams{ServerID: serverID, MinecraftUuid: minecraftUUID, MinecraftNameKey: nameKey, MinecraftName: strings.TrimSpace(minecraftName), AccountSubject: subject, CreatedAt: databaseTime(time.Now())})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
updated, err := queries.ApproveSession(ctx, repository.ApproveSessionParams{AccountSubject: subject, AccountDisplayName: display, SessionID: sessionID, ServerID: serverID, ExpiresAt: databaseTime(time.Now())})
|
||||
if updated == 0 {
|
||||
return errAccountBindingConflict
|
||||
}
|
||||
updated, err = queries.ApproveSession(ctx, repository.ApproveSessionParams{AccountSubject: subject, AccountDisplayName: display, SessionID: sessionID, ServerID: serverID, ExpiresAt: databaseTime(time.Now())})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -6,10 +6,12 @@ import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -41,7 +43,7 @@ func TestUnlinkAccountIsServerScopedAndIdempotent(t *testing.T) {
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return queries.UpsertUUIDAccountBinding(ctx, repository.UpsertUUIDAccountBindingParams{
|
||||
_, err := queries.UpsertUUIDAccountBinding(ctx, repository.UpsertUUIDAccountBindingParams{
|
||||
ServerID: "server-a",
|
||||
MinecraftUuid: uuid,
|
||||
MinecraftNameKey: "playername",
|
||||
@@ -49,6 +51,7 @@ func TestUnlinkAccountIsServerScopedAndIdempotent(t *testing.T) {
|
||||
AccountSubject: "subject-1",
|
||||
CreatedAt: "2026-09-29T00:00:00Z",
|
||||
})
|
||||
return err
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -140,6 +143,138 @@ func TestApproveCASLoginCreatesServerScopedUUIDBinding(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestApproveCASLoginAllowsThreeDistinctMinecraftAccountsAcrossServers(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, err := database.Open(ctx, testutil.URL(t))
|
||||
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 subject = "subject-multi"
|
||||
accounts := []struct {
|
||||
serverID string
|
||||
uuid string
|
||||
}{
|
||||
{"server-a", "123e4567-e89b-12d3-a456-426614174001"},
|
||||
{"server-b", "123e4567-e89b-12d3-a456-426614174002"},
|
||||
{"server-c", "123e4567-e89b-12d3-a456-426614174003"},
|
||||
}
|
||||
for index, account := range accounts {
|
||||
sessionID := fmt.Sprintf("multi-session-%d", index)
|
||||
insertPendingLoginSession(t, ctx, db.Queries, sessionID, account.serverID, account.uuid)
|
||||
approved, conflict, err := service.approveCASLogin(ctx, account.serverID, account.uuid, sessionID, fmt.Sprintf("Player%d", index), subject, "Player")
|
||||
if err != nil || !approved || conflict {
|
||||
t.Fatalf("approve account %d: approved=%t conflict=%t err=%v", index+1, approved, conflict, err)
|
||||
}
|
||||
}
|
||||
|
||||
const firstUUID = "123e4567-e89b-12d3-a456-426614174001"
|
||||
insertPendingLoginSession(t, ctx, db.Queries, "same-account-on-another-server", "server-d", firstUUID)
|
||||
approved, conflict, err := service.approveCASLogin(ctx, "server-d", firstUUID, "same-account-on-another-server", "RenamedPlayer", subject, "Player")
|
||||
if err != nil || !approved || conflict {
|
||||
t.Fatalf("allow same Minecraft account on another server: approved=%t conflict=%t err=%v", approved, conflict, err)
|
||||
}
|
||||
|
||||
const fourthUUID = "123e4567-e89b-12d3-a456-426614174004"
|
||||
insertPendingLoginSession(t, ctx, db.Queries, "fourth-minecraft-account", "server-d", fourthUUID)
|
||||
approved, conflict, err = service.approveCASLogin(ctx, "server-d", fourthUUID, "fourth-minecraft-account", "Player4", subject, "Player")
|
||||
if approved || conflict || !errors.Is(err, errMinecraftAccountLimitReached) {
|
||||
t.Fatalf("expected fourth distinct account to be rejected by limit: approved=%t conflict=%t err=%v", approved, conflict, err)
|
||||
}
|
||||
if _, err := db.Queries.GetBoundSubjectForUUID(ctx, repository.GetBoundSubjectForUUIDParams{ServerID: "server-d", MinecraftUuid: fourthUUID}); !errors.Is(err, repository.ErrNoRows) {
|
||||
t.Fatalf("fourth account was linked despite rejection: %v", err)
|
||||
}
|
||||
count, err := db.Queries.CountMinecraftAccountsForSubject(ctx, subject)
|
||||
if err != nil || count != 3 {
|
||||
t.Fatalf("expected three distinct linked accounts, count=%d err=%v", count, err)
|
||||
}
|
||||
|
||||
insertPendingLoginSession(t, ctx, db.Queries, "reauth-existing-account", "server-a", firstUUID)
|
||||
approved, conflict, err = service.approveCASLogin(ctx, "server-a", firstUUID, "reauth-existing-account", "Player0", subject, "Player")
|
||||
if err != nil || !approved || conflict {
|
||||
t.Fatalf("allow reauthentication at account limit: approved=%t conflict=%t err=%v", approved, conflict, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentMinecraftAccountApprovalsRespectLimit(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, err := database.Open(ctx, testutil.URL(t))
|
||||
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 subject = "subject-concurrent"
|
||||
uuids := []string{
|
||||
"223e4567-e89b-12d3-a456-426614174001",
|
||||
"223e4567-e89b-12d3-a456-426614174002",
|
||||
"223e4567-e89b-12d3-a456-426614174003",
|
||||
"223e4567-e89b-12d3-a456-426614174004",
|
||||
}
|
||||
for index, uuid := range uuids {
|
||||
insertPendingLoginSession(t, ctx, db.Queries, fmt.Sprintf("concurrent-session-%d", index), "server-a", uuid)
|
||||
}
|
||||
type result struct {
|
||||
approved bool
|
||||
err error
|
||||
}
|
||||
results := make(chan result, len(uuids))
|
||||
var wait sync.WaitGroup
|
||||
for index, uuid := range uuids {
|
||||
wait.Add(1)
|
||||
go func(index int, uuid string) {
|
||||
defer wait.Done()
|
||||
approved, _, err := service.approveCASLogin(ctx, "server-a", uuid, fmt.Sprintf("concurrent-session-%d", index), fmt.Sprintf("Player%d", index), subject, "Player")
|
||||
results <- result{approved: approved, err: err}
|
||||
}(index, uuid)
|
||||
}
|
||||
wait.Wait()
|
||||
close(results)
|
||||
approvedCount, limitedCount := 0, 0
|
||||
for outcome := range results {
|
||||
switch {
|
||||
case outcome.err == nil && outcome.approved:
|
||||
approvedCount++
|
||||
case errors.Is(outcome.err, errMinecraftAccountLimitReached):
|
||||
limitedCount++
|
||||
default:
|
||||
t.Fatalf("unexpected concurrent approval result: %#v", outcome)
|
||||
}
|
||||
}
|
||||
if approvedCount != 3 || limitedCount != 1 {
|
||||
t.Fatalf("expected three approvals and one limit rejection, got approved=%d limited=%d", approvedCount, limitedCount)
|
||||
}
|
||||
count, err := db.Queries.CountMinecraftAccountsForSubject(ctx, subject)
|
||||
if err != nil || count != 3 {
|
||||
t.Fatalf("expected concurrent links to stop at three, count=%d err=%v", count, err)
|
||||
}
|
||||
}
|
||||
|
||||
func insertPendingLoginSession(t *testing.T, ctx context.Context, queries repository.Querier, sessionID, serverID, uuid string) {
|
||||
t.Helper()
|
||||
if err := queries.InsertSession(ctx, repository.InsertSessionParams{
|
||||
SessionID: sessionID,
|
||||
RequestID: "request-" + sessionID,
|
||||
ServerID: serverID,
|
||||
MinecraftUuid: uuid,
|
||||
MinecraftName: sessionID,
|
||||
Code: "code-" + sessionID,
|
||||
LoginUrl: "https://minecraft.example/login",
|
||||
ExpiresAt: databaseTime(time.Now().Add(time.Minute)),
|
||||
}); err != nil {
|
||||
t.Fatalf("insert pending login session %s: %v", sessionID, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginStartRequestIsIdempotent(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
db, err := database.Open(ctx, testutil.URL(t))
|
||||
|
||||
@@ -19,7 +19,13 @@ func LoginSuccessPage() http.Handler {
|
||||
}
|
||||
|
||||
func LoginFailurePage() http.Handler {
|
||||
return renderPage(LoginFailure())
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
accountLimit := r.URL.Query().Get("reason") == "account_limit"
|
||||
if err := LoginFailure(accountLimit).Render(r.Context(), w); err != nil {
|
||||
http.Error(w, "failed to render page", http.StatusInternalServerError)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func LoginCodePage(status int, message, value string) http.Handler {
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLoginFailurePageShowsAccountLimitGuidance(t *testing.T) {
|
||||
request := httptest.NewRequest("GET", "/login/failed?reason=account_limit", nil)
|
||||
response := httptest.NewRecorder()
|
||||
LoginFailurePage().ServeHTTP(response, request)
|
||||
|
||||
if response.Code != 200 {
|
||||
t.Fatalf("unexpected status: %d", response.Code)
|
||||
}
|
||||
body := response.Body.String()
|
||||
for _, expected := range []string{"sudah menautkan 3 akun Minecraft", "/unlink", "/login", "di setiap server"} {
|
||||
if !strings.Contains(body, expected) {
|
||||
t.Errorf("account limit page does not contain %q", expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginFailurePageKeepsGenericGuidanceForOtherReasons(t *testing.T) {
|
||||
request := httptest.NewRequest("GET", "/login/failed?reason=other", nil)
|
||||
response := httptest.NewRecorder()
|
||||
LoginFailurePage().ServeHTTP(response, request)
|
||||
|
||||
if strings.Contains(response.Body.String(), "sudah menautkan 3 akun Minecraft") {
|
||||
t.Fatal("generic failure page showed account limit guidance")
|
||||
}
|
||||
}
|
||||
@@ -47,9 +47,6 @@ func LoginCodeForm(message, value string) templ.Component {
|
||||
}
|
||||
var templ_7745c5c3_Var2 string
|
||||
templ_7745c5c3_Var2 = templ.EscapeString(value)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/login-code.templ`, Line: 22, Col: 173}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var2)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
package web
|
||||
|
||||
|
||||
templ LoginFailure() {
|
||||
templ LoginFailure(accountLimit bool) {
|
||||
@templ.Raw(`<!DOCTYPE html>
|
||||
|
||||
<html lang="id">
|
||||
@@ -42,10 +42,16 @@ templ LoginFailure() {
|
||||
|
||||
<h1 class="font-display text-[#373737] text-lg sm:text-xl md:text-2xl leading-relaxed sm:leading-loose mb-5 outline-none drop-shadow-[1px_1px_0px_#FFFFFF]" id="success-heading" tabindex="-1">Login Gagal</h1>
|
||||
|
||||
<p class="font-body text-[#373737] text-lg sm:text-xl md:text-[22px] font-semibold leading-relaxed mb-4">Autentikasi tidak berhasil, jadi kamu belum terautentikasi di Minecraft.</p>
|
||||
|
||||
<p class="font-body text-[#4A4A4A] text-base sm:text-lg leading-normal mb-3">Silakan tutup halaman ini, lalu coba login lagi dari Minecraft.</p><p class="font-body text-[#555555] text-xs sm:text-sm leading-normal">Jika masalah terus berlanjut, hubungi admin server.</p>
|
||||
</div>
|
||||
`)
|
||||
if accountLimit {
|
||||
@templ.Raw(`<p class="font-body text-[#373737] text-lg sm:text-xl md:text-[22px] font-semibold leading-relaxed mb-4">Akun SSO ini sudah menautkan 3 akun Minecraft.</p>
|
||||
<p class="font-body text-[#4A4A4A] text-base sm:text-lg leading-normal mb-3">Untuk menautkan akun lain, jalankan <code>/unlink</code> di setiap server tempat akun Minecraft tersebut tertaut, lalu coba <code>/login</code> lagi.</p>
|
||||
<p class="font-body text-[#555555] text-xs sm:text-sm leading-normal">Tautan akun yang sudah ada tidak berubah.</p>`)
|
||||
} else {
|
||||
@templ.Raw(`<p class="font-body text-[#373737] text-lg sm:text-xl md:text-[22px] font-semibold leading-relaxed mb-4">Autentikasi tidak berhasil, jadi kamu belum terautentikasi di Minecraft.</p>
|
||||
<p class="font-body text-[#4A4A4A] text-base sm:text-lg leading-normal mb-3">Silakan tutup halaman ini, lalu coba login lagi dari Minecraft.</p><p class="font-body text-[#555555] text-xs sm:text-sm leading-normal">Jika masalah terus berlanjut, hubungi admin server.</p>`)
|
||||
}
|
||||
@templ.Raw(`</div>
|
||||
</main>
|
||||
|
||||
<div aria-hidden="true" class="strata-divider"></div>
|
||||
|
||||
@@ -8,7 +8,7 @@ package web
|
||||
import "github.com/a-h/templ"
|
||||
import templruntime "github.com/a-h/templ/runtime"
|
||||
|
||||
func LoginFailure() templ.Component {
|
||||
func LoginFailure(accountLimit bool) templ.Component {
|
||||
return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) {
|
||||
templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context
|
||||
if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil {
|
||||
@@ -78,10 +78,25 @@ func LoginFailure() templ.Component {
|
||||
|
||||
<h1 class="font-display text-[#373737] text-lg sm:text-xl md:text-2xl leading-relaxed sm:leading-loose mb-5 outline-none drop-shadow-[1px_1px_0px_#FFFFFF]" id="success-heading" tabindex="-1">Login Gagal</h1>
|
||||
|
||||
<p class="font-body text-[#373737] text-lg sm:text-xl md:text-[22px] font-semibold leading-relaxed mb-4">Autentikasi tidak berhasil, jadi kamu belum terautentikasi di Minecraft.</p>
|
||||
|
||||
<p class="font-body text-[#4A4A4A] text-base sm:text-lg leading-normal mb-3">Silakan tutup halaman ini, lalu coba login lagi dari Minecraft.</p><p class="font-body text-[#555555] text-xs sm:text-sm leading-normal">Jika masalah terus berlanjut, hubungi admin server.</p>
|
||||
</div>
|
||||
`).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
if accountLimit {
|
||||
templ_7745c5c3_Err = templ.Raw(`<p class="font-body text-[#373737] text-lg sm:text-xl md:text-[22px] font-semibold leading-relaxed mb-4">Akun SSO ini sudah menautkan 3 akun Minecraft.</p>
|
||||
<p class="font-body text-[#4A4A4A] text-base sm:text-lg leading-normal mb-3">Untuk menautkan akun lain, jalankan <code>/unlink</code> di setiap server tempat akun Minecraft tersebut tertaut, lalu coba <code>/login</code> lagi.</p>
|
||||
<p class="font-body text-[#555555] text-xs sm:text-sm leading-normal">Tautan akun yang sudah ada tidak berubah.</p>`).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
} else {
|
||||
templ_7745c5c3_Err = templ.Raw(`<p class="font-body text-[#373737] text-lg sm:text-xl md:text-[22px] font-semibold leading-relaxed mb-4">Autentikasi tidak berhasil, jadi kamu belum terautentikasi di Minecraft.</p>
|
||||
<p class="font-body text-[#4A4A4A] text-base sm:text-lg leading-normal mb-3">Silakan tutup halaman ini, lalu coba login lagi dari Minecraft.</p><p class="font-body text-[#555555] text-xs sm:text-sm leading-normal">Jika masalah terus berlanjut, hubungi admin server.</p>`).Render(ctx, templ_7745c5c3_Buffer)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templ.Raw(`</div>
|
||||
</main>
|
||||
|
||||
<div aria-hidden="true" class="strata-divider"></div>
|
||||
|
||||
Reference in New Issue
Block a user