From 6a67fd9afeb1471ff4b468ec561324702f31763e Mon Sep 17 00:00:00 2001 From: Anya Tokugawa Date: Mon, 30 Nov 2026 23:03:24 +0900 Subject: [PATCH] feat(storage): add native MySQL namespace and identity pilots Add resumable checked migrations and explicit schema administration commands. Port ML budgets, namespaces, identity and group persistence with three-backend contracts. Keep MySQL unavailable as the full application backend. --- cmd/pageswiki/main.go | 18 + cmd/pageswiki/mysql_ml_schema.go | 99 +++++ cmd/pageswiki/mysql_ml_schema_test.go | 109 ++++++ go.mod | 2 + go.sum | 4 + internal/db/mysql.go | 59 +++ internal/db/mysql_migration.go | 303 +++++++++++++++ internal/db/mysql_migration_test.go | 41 ++ internal/db/mysql_test.go | 20 + internal/store/auth.go | 46 ++- internal/store/auth_accounts_backend.go | 4 +- internal/store/auth_accounts_backend_test.go | 89 ++++- internal/store/auth_external.go | 41 +- internal/store/auth_mysql.go | 174 +++++++++ internal/store/auth_mysql_schema.go | 99 +++++ internal/store/auth_mysql_test.go | 298 ++++++++++++++ internal/store/auth_totp.go | 11 +- internal/store/campuses.go | 27 +- internal/store/config.go | 18 +- internal/store/domain_write.go | 26 +- internal/store/domains.go | 12 +- internal/store/groups.go | 84 ++-- internal/store/groups_backend_test.go | 25 +- internal/store/groups_general_backend_test.go | 7 + internal/store/groups_inheritance.go | 36 +- internal/store/groups_mysql.go | 97 +++++ internal/store/machine_learning.go | 99 +++++ internal/store/machine_learning_budget.go | 163 ++++++++ .../store/machine_learning_budget_test.go | 100 +++++ internal/store/machine_learning_mysql.go | 54 +++ .../store/machine_learning_mysql_schema.go | 56 +++ internal/store/machine_learning_mysql_test.go | 82 ++++ internal/store/machine_learning_test.go | 90 +++++ internal/store/mysql_migration_test.go | 166 ++++++++ internal/store/mysql_ml_schema.sql | 25 ++ internal/store/namespace_mysql.go | 114 ++++++ internal/store/namespace_mysql_schema.go | 68 ++++ internal/store/namespace_mysql_test.go | 364 ++++++++++++++++++ internal/store/schema_modules.go | 13 +- internal/store/sql_backend.go | 38 ++ 40 files changed, 3087 insertions(+), 94 deletions(-) create mode 100644 cmd/pageswiki/mysql_ml_schema.go create mode 100644 cmd/pageswiki/mysql_ml_schema_test.go create mode 100644 internal/db/mysql.go create mode 100644 internal/db/mysql_migration.go create mode 100644 internal/db/mysql_migration_test.go create mode 100644 internal/db/mysql_test.go create mode 100644 internal/store/auth_mysql.go create mode 100644 internal/store/auth_mysql_schema.go create mode 100644 internal/store/auth_mysql_test.go create mode 100644 internal/store/groups_mysql.go create mode 100644 internal/store/machine_learning.go create mode 100644 internal/store/machine_learning_budget.go create mode 100644 internal/store/machine_learning_budget_test.go create mode 100644 internal/store/machine_learning_mysql.go create mode 100644 internal/store/machine_learning_mysql_schema.go create mode 100644 internal/store/machine_learning_mysql_test.go create mode 100644 internal/store/machine_learning_test.go create mode 100644 internal/store/mysql_migration_test.go create mode 100644 internal/store/mysql_ml_schema.sql create mode 100644 internal/store/namespace_mysql.go create mode 100644 internal/store/namespace_mysql_schema.go create mode 100644 internal/store/namespace_mysql_test.go diff --git a/cmd/pageswiki/main.go b/cmd/pageswiki/main.go index 1f2483e..a0eb509 100644 --- a/cmd/pageswiki/main.go +++ b/cmd/pageswiki/main.go @@ -15,6 +15,24 @@ import ( ) func main() { + if len(os.Args) > 1 && os.Args[1] == "mysql-identity-schema" { + if err := runMySQLSchemaCommand(os.Args[2:], os.Stdout, "identity"); err != nil { + log.Fatal(err) + } + return + } + if len(os.Args) > 1 && os.Args[1] == "mysql-namespace-schema" { + if err := runMySQLComponentSchema(os.Args[2:], os.Stdout, true); err != nil { + log.Fatal(err) + } + return + } + if len(os.Args) > 1 && os.Args[1] == "mysql-ml-schema" { + if err := runMySQLMLSchema(os.Args[2:], os.Stdout); err != nil { + log.Fatal(err) + } + return + } if len(os.Args) > 1 && os.Args[1] == "migrate-postgres" { if err := runPostgreSQLMigration(os.Args[2:], os.Stdout); err != nil { log.Fatal(err) diff --git a/cmd/pageswiki/mysql_ml_schema.go b/cmd/pageswiki/mysql_ml_schema.go new file mode 100644 index 0000000..f411e04 --- /dev/null +++ b/cmd/pageswiki/mysql_ml_schema.go @@ -0,0 +1,99 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "os" + "time" + + "pageswiki/internal/db" + "pageswiki/internal/store" +) + +func runMySQLMLSchema(args []string, out io.Writer) error { + return runMySQLComponentSchema(args, out, false) +} + +func runMySQLComponentSchema(args []string, out io.Writer, namespace bool) error { + component := "ml" + if namespace { + component = "namespace" + } + return runMySQLSchemaCommand(args, out, component) +} +func runMySQLSchemaCommand(args []string, out io.Writer, component string) error { + command, scope, label := "mysql-ml-schema", "ml-only", "ML component ONLY" + if component == "namespace" { + command, scope, label = "mysql-namespace-schema", "namespace-pilot", "Namespace pilot ONLY (includes shared config/ML schema; no Domain mutations or authentication)" + } else if component == "identity" { + command, scope, label = "mysql-identity-schema", "identity-pilot", "Identity/group persistence pilot ONLY; not a complete authentication server" + } else if component != "ml" { + return errors.New("unknown MySQL component") + } + usage := "pageswiki " + command + " {status|check|apply|resume} [--timeout 2m] [--allow-insecure]\nUses PAGESWIKI_MYSQL_DSN. " + label + "; does not make Pages serve from MySQL. status/check are read-only. apply refuses interrupted migrations; resume explicitly verifies and continues." + if len(args) == 0 || args[0] == "--help" { + _, e := fmt.Fprintln(out, usage) + return e + } + mode := args[0] + if mode != "status" && mode != "check" && mode != "apply" && mode != "resume" { + return errors.New("invalid MySQL component schema action") + } + f := flag.NewFlagSet(command, flag.ContinueOnError) + f.SetOutput(out) + timeout := f.Duration("timeout", 2*time.Minute, "operation deadline") + insecure := f.Bool("allow-insecure", false, "isolated disposable database tests only") + if e := f.Parse(args[1:]); e != nil { + if errors.Is(e, flag.ErrHelp) { + return nil + } + return e + } + if f.NArg() != 0 || *timeout <= 0 { + return errors.New("invalid MySQL component schema arguments") + } + ctx, cancel := context.WithTimeout(context.Background(), *timeout) + defer cancel() + database, e := db.OpenMySQL(ctx, db.MySQLOptions{DSN: os.Getenv("PAGESWIKI_MYSQL_DSN"), AllowInsecure: *insecure}) + if e != nil { + return e + } + defer database.Close() + var repo interface { + PrepareSchema(context.Context) error + InspectSchema(context.Context) (db.MySQLMigrationStatus, error) + ResumeSchema(context.Context) error + } = store.NewMySQLMLRepository(database) + if component == "namespace" { + repo = store.NewMySQLNamespaceRepository(database) + } else if component == "identity" { + repo = store.NewMySQLIdentityRepository(database) + } + switch mode { + case "apply": + e = repo.PrepareSchema(ctx) + case "resume": + e = repo.ResumeSchema(ctx) + } + if e != nil { + return e + } + status, e := repo.InspectSchema(ctx) + if e != nil { + return e + } + if e = json.NewEncoder(out).Encode(struct { + Scope string `json:"scope"` + db.MySQLMigrationStatus + }{scope, status}); e != nil { + return e + } + if mode == "check" && (status.Dirty || status.Pending > 0) { + return errors.New("MySQL component schema is pending or interrupted") + } + return nil +} diff --git a/cmd/pageswiki/mysql_ml_schema_test.go b/cmd/pageswiki/mysql_ml_schema_test.go new file mode 100644 index 0000000..a29e514 --- /dev/null +++ b/cmd/pageswiki/mysql_ml_schema_test.go @@ -0,0 +1,109 @@ +package main + +import ( + "bytes" + "context" + "os" + "strings" + "testing" + "time" + + "github.com/go-sql-driver/mysql" + "github.com/google/uuid" + "pageswiki/internal/db" +) + +func TestMySQLMLSchemaArguments(t *testing.T) { + t.Setenv("PAGESWIKI_MYSQL_DSN", "") + for _, args := range [][]string{{"bad"}, {"apply", "--timeout", "0s"}, {"resume", "unexpected"}, {"status"}} { + var out bytes.Buffer + if runMySQLMLSchema(args, &out) == nil { + t.Fatal("accepted invalid arguments", args) + } + } + var out bytes.Buffer + if e := runMySQLMLSchema([]string{"--help"}, &out); e != nil || !strings.Contains(out.String(), "ML component ONLY") { + t.Fatal(e) + } +} + +func TestMySQLMLSchemaCommand(t *testing.T) { + for _, component := range []string{"ml", "namespace", "identity"} { + t.Run(component, func(t *testing.T) { testMySQLSchemaCommand(t, component) }) + } +} + +func testMySQLSchemaCommand(t *testing.T, component string) { + dsn := os.Getenv("PAGESWIKI_TEST_MYSQL_DSN") + if dsn == "" { + t.Skip("set disposable MySQL DSN") + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + admin, e := db.OpenMySQL(ctx, db.MySQLOptions{DSN: dsn, AllowInsecure: true}) + if e != nil { + t.Fatal(e) + } + defer admin.Close() + name := "pages_ml_cmd_" + strings.ReplaceAll(uuid.NewString(), "-", "") + if _, e = admin.ExecContext(ctx, "CREATE DATABASE "+name+" CHARACTER SET utf8mb4 COLLATE utf8mb4_bin"); e != nil { + t.Fatal(e) + } + defer func() { + if _, e := admin.Exec("DROP DATABASE " + name); e != nil { + t.Error(e) + } + }() + c, e := mysql.ParseDSN(dsn) + if e != nil { + t.Fatal(e) + } + c.DBName = name + t.Setenv("PAGESWIKI_MYSQL_DSN", c.FormatDSN()) + var out bytes.Buffer + run := func(action string) error { + return runMySQLSchemaCommand([]string{action, "--allow-insecure"}, &out, component) + } + pending := `"pending":2` + if component == "namespace" { + pending = `"pending":3` + } else if component == "identity" { + pending = `"pending":5` + } + if e = run("status"); e != nil || !strings.Contains(out.String(), pending) { + t.Fatal(out.String(), e) + } + var count int + if e = admin.QueryRowContext(ctx, `SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=?`, name).Scan(&count); e != nil || count != 0 { + t.Fatal("status wrote schema", count, e) + } + if e = run("check"); e == nil { + t.Fatal("pending check succeeded") + } + if e = run("apply"); e != nil { + t.Fatal(e) + } + if e = run("check"); e != nil { + t.Fatal(e) + } + if component != "ml" { + if e = admin.QueryRowContext(ctx, "SELECT COUNT(*) FROM "+name+".domains").Scan(&count); e != nil || count != 0 { + t.Fatal("schema command created unauthorized Domain data", count, e) + } + } + ledger, version := "machine-learning", 2 + if component == "namespace" { + ledger, version = "store-namespaces", 1 + } else if component == "identity" { + ledger, version = "store-auth-core", 2 + } + if _, e = admin.ExecContext(ctx, "UPDATE "+name+".schema_mysql_migrations SET state='running',next_operation=1 WHERE component=? AND version=?", ledger, version); e != nil { + t.Fatal(e) + } + if e = run("apply"); e == nil { + t.Fatal("dirty apply succeeded") + } + if e = run("resume"); e != nil { + t.Fatal(e) + } +} diff --git a/go.mod b/go.mod index b5697c3..f8611a1 100644 --- a/go.mod +++ b/go.mod @@ -14,6 +14,8 @@ require ( ) require ( + filippo.io/edwards25519 v1.1.0 // indirect + github.com/go-sql-driver/mysql v1.9.3 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.3 // indirect diff --git a/go.sum b/go.sum index f7c59c0..0aecaa1 100644 --- a/go.sum +++ b/go.sum @@ -1,3 +1,5 @@ +filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= +filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358/go.mod h1:chxPXzSsl7ZWRAuOIE23GDNzjWuZquvFlgA8xmpunjU= github.com/Azure/go-ntlmssp v0.1.1 h1:l+FM/EEMb0U9QZE7mKNEDw5Mu3mFiaa2GKOoTSsNDPw= github.com/Azure/go-ntlmssp v0.1.1/go.mod h1:NYqdhxd/8aAct/s4qSYZEerdPuH1liG2/X9DiVTbhpk= @@ -23,6 +25,8 @@ github.com/go-asn1-ber/asn1-ber v1.5.8 h1:H9AZkK22UOmfX8J84ubyaZxKJZ3FMHVwn8swoM github.com/go-asn1-ber/asn1-ber v1.5.8/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0= github.com/go-ldap/ldap/v3 v3.4.8 h1:loKJyspcRezt2Q3ZRMq2p/0v8iOurlmeXDPw6fikSvQ= github.com/go-ldap/ldap/v3 v3.4.8/go.mod h1:qS3Sjlu76eHfHGpUdWkAXQTw4beih+cHsco2jXlIXrk= +github.com/go-sql-driver/mysql v1.9.3 h1:U/N249h2WzJ3Ukj8SowVFjdtZKfu9vlLZxjPXV1aweo= +github.com/go-sql-driver/mysql v1.9.3/go.mod h1:qn46aNg1333BRMNU69Lq93t8du/dwxI64Gl8i5p1WMU= github.com/golang-jwt/jwt/v5 v5.2.1 h1:OuVbFODueb089Lh128TAcimifWaLhJwVflnrgM17wHk= github.com/golang-jwt/jwt/v5 v5.2.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/gomarkdown/markdown v0.0.0-20260417124207-7d523f7318df h1:Mwihr/o+v4L5h56rwHLOE20+hh7Okhwno5BHz3zDuao= diff --git a/internal/db/mysql.go b/internal/db/mysql.go new file mode 100644 index 0000000..6f531b0 --- /dev/null +++ b/internal/db/mysql.go @@ -0,0 +1,59 @@ +package db + +import ( + "context" + "database/sql" + "errors" + "io" + "log" + "time" + + "github.com/go-sql-driver/mysql" +) + +// MySQL is currently a component-pilot backend, not a Pages serving backend. +// Credentials are instance configuration and must never be logged. +type MySQLOptions struct { + DSN string + AllowInsecure bool +} + +func OpenMySQL(ctx context.Context, options MySQLOptions) (*sql.DB, error) { + c, e := mysql.ParseDSN(options.DSN) + if e != nil || options.DSN == "" { + return nil, errors.New("invalid MySQL configuration") + } + if c.DBName == "" || c.Net != "tcp" || c.MultiStatements || c.AllowAllFiles || c.AllowCleartextPasswords || c.AllowFallbackToPlaintext || len(c.Params) != 0 { + return nil, errors.New("unsupported MySQL configuration") + } + if !options.AllowInsecure && c.TLSConfig != "true" { + return nil, errors.New("MySQL requires verified TLS (tls=true)") + } + c.Timeout = 10 * time.Second + c.ReadTimeout = 30 * time.Second + c.WriteTimeout = 30 * time.Second + c.Collation = "utf8mb4_bin" + // Set on EVERY new pooled connection. Relying on a server's permissive + // sql_mode can silently truncate identifiers or coerce invalid values. + // User-supplied session variables remain rejected above. + c.Params = map[string]string{"sql_mode": "'STRICT_ALL_TABLES,ONLY_FULL_GROUP_BY,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION'"} + c.Logger = log.New(io.Discard, "", 0) + connector, e := mysql.NewConnector(c) + if e != nil { + return nil, errors.New("invalid MySQL connector configuration") + } + database := sql.OpenDB(connector) + database.SetMaxOpenConns(8) + database.SetMaxIdleConns(2) + database.SetConnMaxLifetime(10 * time.Minute) + ping, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + if e = database.PingContext(ping); e != nil { + database.Close() + if ctx.Err() != nil { + return nil, ctx.Err() + } + return nil, errors.New("MySQL connection failed") + } + return database, nil +} diff --git a/internal/db/mysql_migration.go b/internal/db/mysql_migration.go new file mode 100644 index 0000000..f2f671a --- /dev/null +++ b/internal/db/mysql_migration.go @@ -0,0 +1,303 @@ +package db + +import ( + "context" + "crypto/sha256" + "database/sql" + "database/sql/driver" + "encoding/hex" + "encoding/json" + "errors" + "fmt" + "regexp" + "strings" + "time" +) + +// MySQLOperation is owned SQL, never user input. Check must return exactly one +// boolean describing the operation's postcondition. ReplaySafe permits explicit +// resume when Check is false; never mark non-idempotent data updates replay-safe. +type MySQLOperation struct { + SQL, Check string + ReplaySafe bool +} +type MySQLMigration struct { + Version int + Name string + Operations []MySQLOperation + Assertions []string +} +type MySQLMigrationStatus struct { + Applied int `json:"applied"` + Pending int `json:"pending"` + Dirty bool `json:"dirty"` + NextOperation int `json:"next_operation"` + DirtyComponent string `json:"dirty_component,omitempty"` +} + +var ErrMySQLMigrationDirty = errors.New("MySQL migration interrupted; inspect and explicitly resume") +var ErrMySQLMigrationMismatch = errors.New("MySQL migration history or schema mismatch") + +func mysqlMigrationHash(m MySQLMigration) string { + b, _ := json.Marshal(m) + h := sha256.Sum256(b) + return hex.EncodeToString(h[:]) +} +func validateMySQLPlan(component string, steps []MySQLMigration) error { + if !regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,63}$`).MatchString(component) { + return errors.New("invalid MySQL migration component") + } + for i, s := range steps { + if s.Version != i+1 || s.Name == "" || len(s.Name) > 128 || len(s.Operations) == 0 || len(s.Assertions) == 0 { + return errors.New("invalid MySQL migration plan") + } + for _, op := range s.Operations { + if strings.TrimSpace(op.SQL) == "" || strings.TrimSpace(op.Check) == "" { + return errors.New("missing MySQL operation postcondition") + } + } + for _, assertion := range s.Assertions { + if strings.TrimSpace(assertion) == "" { + return errors.New("missing MySQL schema assertion") + } + } + } + return nil +} + +// Every operation, including GET_LOCK/RELEASE_LOCK, uses this one connection. +// MySQL DDL commits implicitly: a transaction cannot replace this lock/journal. +func mysqlMigrationConnection(ctx context.Context, database *sql.DB) (*sql.Conn, func(), error) { + c, e := database.Conn(ctx) + if e != nil { + return nil, nil, errors.New("MySQL migration connection failed") + } + var name string + if e = c.QueryRowContext(ctx, `SELECT DATABASE()`).Scan(&name); e != nil || name == "" { + c.Close() + return nil, nil, errors.New("MySQL migration database required") + } + h := sha256.Sum256([]byte(name)) + key := "pages:migration:" + hex.EncodeToString(h[:20]) + var locked sql.NullInt64 + if e = c.QueryRowContext(ctx, `SELECT GET_LOCK(?,10)`, key).Scan(&locked); e != nil || !locked.Valid || locked.Int64 != 1 { + // An interrupted lock request may have acquired the session lock. + _ = c.Raw(func(any) error { return driver.ErrBadConn }) + c.Close() + return nil, nil, errors.New("MySQL migration lock unavailable") + } + release := func() { + releaseCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + var released sql.NullInt64 + if e := c.QueryRowContext(releaseCtx, `SELECT RELEASE_LOCK(?)`, key).Scan(&released); e != nil || !released.Valid || released.Int64 != 1 { + _ = c.Raw(func(any) error { return driver.ErrBadConn }) + } + c.Close() + } + return c, release, nil +} + +func mysqlCheck(ctx context.Context, c *sql.Conn, q string) (bool, error) { + rows, e := c.QueryContext(ctx, q) + if e != nil { + return false, errors.New("MySQL schema check failed") + } + defer rows.Close() + var yes bool + if !rows.Next() { + return false, errors.New("MySQL schema check returned no result") + } + if rows.Scan(&yes) != nil || rows.Next() || rows.Err() != nil { + return false, errors.New("invalid MySQL schema check result") + } + return yes, nil +} + +func inspectMySQLLocked(ctx context.Context, c *sql.Conn, component string, steps []MySQLMigration) (MySQLMigrationStatus, error) { + status := MySQLMigrationStatus{Pending: len(steps)} + var exists int + if e := c.QueryRowContext(ctx, `SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='schema_mysql_migrations'`).Scan(&exists); e != nil { + return status, errors.New("MySQL migration inspection failed") + } + if exists == 0 { + return status, nil + } + // The journal itself must remain durable and uniquely keyed. Do not repair + // a damaged journal automatically, or trust history read from a view. + valid, e := mysqlCheck(ctx, c, `SELECT + (SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='schema_mysql_migrations' AND engine='InnoDB' AND table_type='BASE TABLE')=1 + AND COALESCE((SELECT GROUP_CONCAT(column_name ORDER BY seq_in_index SEPARATOR ',') FROM information_schema.statistics WHERE table_schema=DATABASE() AND table_name='schema_mysql_migrations' AND index_name='PRIMARY'),'')='component,version' + AND (SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='schema_mysql_migrations' AND is_nullable='NO' AND column_name IN ('component','version','name','checksum','state','next_operation','updated_ms'))=7`) + if e != nil { + return status, e + } + if !valid { + return status, ErrMySQLMigrationMismatch + } + rows, e := c.QueryContext(ctx, `SELECT version,name,checksum,state,next_operation FROM schema_mysql_migrations WHERE component=? ORDER BY version`, component) + if e != nil { + return status, errors.New("MySQL migration history unavailable") + } + seen := 0 + for rows.Next() { + var version, next int + var name, hash, state string + if rows.Scan(&version, &name, &hash, &state, &next) != nil { + rows.Close() + return status, ErrMySQLMigrationMismatch + } + if version != seen+1 || version > len(steps) || status.Dirty { + rows.Close() + return status, ErrMySQLMigrationMismatch + } + s := steps[version-1] + if name != s.Name || hash != mysqlMigrationHash(s) || next < 0 || next > len(s.Operations) { + rows.Close() + return status, ErrMySQLMigrationMismatch + } + switch state { + case "applied": + if next != len(s.Operations) { + rows.Close() + return status, ErrMySQLMigrationMismatch + } + status.Applied++ + case "running": + status.Dirty = true + status.DirtyComponent = component + status.NextOperation = next + default: + rows.Close() + return status, ErrMySQLMigrationMismatch + } + seen++ + } + e = rows.Err() + rows.Close() + if e != nil { + return status, errors.New("MySQL migration history read failed") + } + status.Pending = len(steps) - status.Applied + // Later migrations may intentionally replace an older schema. Validate only + // the latest clean contract, not intermediate versions of a dirty migration. + if !status.Dirty && status.Applied > 0 { + for _, q := range steps[status.Applied-1].Assertions { + ok, e := mysqlCheck(ctx, c, q) + if e != nil { + return status, e + } + if !ok { + return status, ErrMySQLMigrationMismatch + } + } + } + return status, nil +} + +// Inspect is read-only: it never creates the ledger or adopts an existing table. +func InspectMySQLMigrations(ctx context.Context, database *sql.DB, component string, steps []MySQLMigration) (MySQLMigrationStatus, error) { + if e := validateMySQLPlan(component, steps); e != nil { + return MySQLMigrationStatus{}, e + } + c, release, e := mysqlMigrationConnection(ctx, database) + if e != nil { + return MySQLMigrationStatus{}, e + } + defer release() + return inspectMySQLLocked(ctx, c, component, steps) +} + +func ApplyMySQLMigrations(ctx context.Context, database *sql.DB, component string, steps []MySQLMigration) error { + return applyMySQLMigrations(ctx, database, component, steps, false) +} + +// Resume is explicitly separate from normal startup. It does not blindly repeat +// a statement: the postcondition must prove success, or ReplaySafe must be set. +func ResumeMySQLMigrations(ctx context.Context, database *sql.DB, component string, steps []MySQLMigration) error { + return applyMySQLMigrations(ctx, database, component, steps, true) +} +func applyMySQLMigrations(ctx context.Context, database *sql.DB, component string, steps []MySQLMigration, resume bool) error { + if e := validateMySQLPlan(component, steps); e != nil { + return e + } + c, release, e := mysqlMigrationConnection(ctx, database) + if e != nil { + return e + } + defer release() + status, e := inspectMySQLLocked(ctx, c, component, steps) + if e != nil { + return e + } + if status.Dirty && !resume { + return ErrMySQLMigrationDirty + } + _, e = c.ExecContext(ctx, `CREATE TABLE IF NOT EXISTS schema_mysql_migrations(component VARCHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,version BIGINT NOT NULL,name VARCHAR(128) NOT NULL,checksum CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,state VARCHAR(16) NOT NULL,next_operation BIGINT NOT NULL,updated_ms BIGINT NOT NULL,PRIMARY KEY(component,version)) ENGINE=InnoDB`) + if e != nil { + return errors.New("MySQL migration ledger creation failed") + } + for _, s := range steps[status.Applied:] { + resuming := status.Dirty + cursor := 0 + if resuming { + cursor = status.NextOperation + } else { + // Do not implicitly adopt an already-existing schema with no history. + for _, op := range s.Operations { + ok, e := mysqlCheck(ctx, c, op.Check) + if e != nil { + return e + } + if ok { + return ErrMySQLMigrationMismatch + } + } + _, e = c.ExecContext(ctx, `INSERT INTO schema_mysql_migrations(component,version,name,checksum,state,next_operation,updated_ms) VALUES(?,?,?,?,'running',0,?)`, component, s.Version, s.Name, mysqlMigrationHash(s), time.Now().UnixMilli()) + if e != nil { + return errors.New("MySQL migration journal failed") + } + } + for i := cursor; i < len(s.Operations); i++ { + op := s.Operations[i] + ok, e := mysqlCheck(ctx, c, op.Check) + if e != nil { + return e + } + if !ok { + if resuming && i == cursor && !op.ReplaySafe { + return ErrMySQLMigrationDirty + } + if _, e = c.ExecContext(ctx, op.SQL); e != nil { + return fmt.Errorf("MySQL migration operation %d failed; journal retained", i+1) + } + ok, e = mysqlCheck(ctx, c, op.Check) + if e != nil { + return e + } + if !ok { + return ErrMySQLMigrationMismatch + } + } + _, e = c.ExecContext(ctx, `UPDATE schema_mysql_migrations SET next_operation=?,updated_ms=? WHERE component=? AND version=?`, i+1, time.Now().UnixMilli(), component, s.Version) + if e != nil { + return errors.New("MySQL migration progress failed") + } + } + for _, q := range s.Assertions { + ok, e := mysqlCheck(ctx, c, q) + if e != nil { + return e + } + if !ok { + return ErrMySQLMigrationMismatch + } + } + _, e = c.ExecContext(ctx, `UPDATE schema_mysql_migrations SET state='applied',updated_ms=? WHERE component=? AND version=?`, time.Now().UnixMilli(), component, s.Version) + if e != nil { + return errors.New("MySQL migration completion failed") + } + status.Dirty = false + } + return nil +} diff --git a/internal/db/mysql_migration_test.go b/internal/db/mysql_migration_test.go new file mode 100644 index 0000000..24b8856 --- /dev/null +++ b/internal/db/mysql_migration_test.go @@ -0,0 +1,41 @@ +package db + +import "testing" + +func TestMySQLMigrationPlanValidation(t *testing.T) { + valid := func() MySQLMigration { + return MySQLMigration{Version: 1, Name: "initial", Operations: []MySQLOperation{{SQL: "CREATE TABLE example(id BIGINT)", Check: "SELECT 0", ReplaySafe: true}}, Assertions: []string{"SELECT 1"}} + } + if e := validateMySQLPlan("machine-learning", []MySQLMigration{valid()}); e != nil { + t.Fatal(e) + } + for _, component := range []string{"", "../schema", "has space", "MixedCase"} { + if e := validateMySQLPlan(component, []MySQLMigration{valid()}); e == nil { + t.Fatal("invalid component accepted", component) + } + } + for _, mutate := range []func(*MySQLMigration){ + func(m *MySQLMigration) { m.Version = 2 }, + func(m *MySQLMigration) { m.Name = "" }, + func(m *MySQLMigration) { m.Operations = nil }, + func(m *MySQLMigration) { m.Operations[0].SQL = " " }, + func(m *MySQLMigration) { m.Operations[0].Check = " " }, + func(m *MySQLMigration) { m.Assertions = nil }, + func(m *MySQLMigration) { m.Assertions[0] = " " }, + } { + m := valid() + mutate(&m) + if e := validateMySQLPlan("test", []MySQLMigration{m}); e == nil { + t.Fatal("invalid plan accepted", m) + } + } + before := valid() + after := valid() + after.Operations[0].ReplaySafe = false + if mysqlMigrationHash(before) == mysqlMigrationHash(after) { + t.Fatal("replay policy not covered by checksum") + } + if mysqlMigrationHash(before) != mysqlMigrationHash(valid()) { + t.Fatal("unstable checksum") + } +} diff --git a/internal/db/mysql_test.go b/internal/db/mysql_test.go new file mode 100644 index 0000000..839a24b --- /dev/null +++ b/internal/db/mysql_test.go @@ -0,0 +1,20 @@ +package db + +import ( + "context" + "strings" + "testing" +) + +func TestMySQLRejectsUnsafeConfiguration(t *testing.T) { + for _, dsn := range []string{"", "private-secret@bad", "u:private-secret@tcp(localhost:3306)/pages", "u:p@tcp(localhost:3306)/pages?tls=skip-verify", "u:p@tcp(localhost:3306)/pages?tls=preferred", "u:p@tcp(localhost:3306)/pages?tls=true&multiStatements=true", "u:p@tcp(localhost:3306)/pages?tls=true&allowAllFiles=true", "u:p@tcp(localhost:3306)/pages?tls=true&sql_mode=bad"} { + connection, err := OpenMySQL(context.Background(), MySQLOptions{DSN: dsn}) + if connection != nil { + connection.Close() + t.Fatal("unexpected connection") + } + if err == nil || strings.Contains(err.Error(), "private-secret") { + t.Fatalf("configuration not safely rejected: %v", err) + } + } +} diff --git a/internal/store/auth.go b/internal/store/auth.go index d7b9827..eebed6f 100644 --- a/internal/store/auth.go +++ b/internal/store/auth.go @@ -188,43 +188,58 @@ func (s *Store) RevokeAuthSession(token string) error { } func (s *Store) ListDomainPrincipals(domainUUID string) ([]Principal, error) { - rows, err := s.DB.Query(`SELECT p.uuid,p.display_name,p.email,p.state FROM domain_memberships m JOIN principals p ON p.uuid=m.principal_uuid WHERE m.domain_uuid=`+s.sqlParam(1)+` ORDER BY lower(p.display_name),p.uuid`, domainUUID) + return s.ListDomainPrincipalsContext(context.Background(), domainUUID) +} +func (s *Store) ListDomainPrincipalsContext(ctx context.Context, domainUUID string) ([]Principal, error) { + rows, err := s.DB.QueryContext(ctx, `SELECT p.uuid,p.display_name,p.email,p.state FROM domain_memberships m JOIN principals p ON p.uuid=m.principal_uuid WHERE m.domain_uuid=`+s.sqlParam(1)+` ORDER BY lower(p.display_name),p.uuid`, domainUUID) if err != nil { - return nil, err + return nil, s.sqlError("list principals", err) } defer rows.Close() var out []Principal for rows.Next() { var p Principal if err := rows.Scan(&p.UUID, &p.DisplayName, &p.Email, &p.State); err != nil { - return nil, err + return nil, s.sqlError("decode principal", err) } out = append(out, p) } - return out, rows.Err() + return out, s.sqlError("list principals", rows.Err()) } func (s *Store) ListAuthSessions(domainUUID string) ([]AuthSessionInfo, error) { - rows, err := s.DB.Query(fmt.Sprintf(`SELECT s.uuid,s.principal_uuid,p.display_name,s.auth_time_ms,s.expires_at_ms,s.last_seen_at_ms,s.mfa_level FROM auth_sessions s JOIN principals p ON p.uuid=s.principal_uuid WHERE s.domain_uuid=%s AND s.revoked_at_ms=0 AND s.expires_at_ms>%s ORDER BY s.last_seen_at_ms DESC,s.uuid`, s.sqlParam(1), s.sqlParam(2)), domainUUID, time.Now().UnixMilli()) + return s.ListAuthSessionsContext(context.Background(), domainUUID) +} +func (s *Store) ListAuthSessionsContext(ctx context.Context, domainUUID string) ([]AuthSessionInfo, error) { + rows, err := s.DB.QueryContext(ctx, fmt.Sprintf(`SELECT s.uuid,s.principal_uuid,p.display_name,s.auth_time_ms,s.expires_at_ms,s.last_seen_at_ms,s.mfa_level FROM auth_sessions s JOIN principals p ON p.uuid=s.principal_uuid WHERE s.domain_uuid=%s AND s.revoked_at_ms=0 AND s.expires_at_ms>%s ORDER BY s.last_seen_at_ms DESC,s.uuid`, s.sqlParam(1), s.sqlParam(2)), domainUUID, time.Now().UnixMilli()) if err != nil { - return nil, err + return nil, s.sqlError("list sessions", err) } defer rows.Close() var out []AuthSessionInfo for rows.Next() { var item AuthSessionInfo if err := rows.Scan(&item.UUID, &item.PrincipalUUID, &item.DisplayName, &item.AuthTimeMS, &item.ExpiresAtMS, &item.LastSeenAtMS, &item.MFALevel); err != nil { - return nil, err + return nil, s.sqlError("decode session", err) } out = append(out, item) } - return out, rows.Err() + return out, s.sqlError("list sessions", rows.Err()) } func (s *Store) RevokeAuthSessionByID(domainUUID, sessionUUID string) error { - result, err := s.DB.Exec(fmt.Sprintf(`UPDATE auth_sessions SET revoked_at_ms=%s WHERE domain_uuid=%s AND uuid=%s AND revoked_at_ms=0`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), time.Now().UnixMilli(), domainUUID, sessionUUID) + return s.RevokeAuthSessionByIDContext(context.Background(), domainUUID, sessionUUID) +} +func (s *Store) RevokeAuthSessionByIDContext(ctx context.Context, domainUUID, sessionUUID string) error { + if s.ReadOnly { + return ErrReadOnly + } + result, err := s.DB.ExecContext(ctx, fmt.Sprintf(`UPDATE auth_sessions SET revoked_at_ms=%s WHERE domain_uuid=%s AND uuid=%s AND revoked_at_ms=0`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), time.Now().UnixMilli(), domainUUID, sessionUUID) if err != nil { return s.sqlError("revoke session by ID", err) } - count, _ := result.RowsAffected() + count, err := result.RowsAffected() + if err != nil { + return s.sqlError("revoke session result", err) + } if count == 0 { return sql.ErrNoRows } @@ -239,6 +254,12 @@ func (s *Store) SetPrincipalStateContext(ctx context.Context, domainUUID, princi return errors.New("invalid principal state") } return s.groupWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { + if s.sqlBackend == storeMySQL { + var found string + if err := tx.QueryRowContext(ctx, `SELECT p.uuid FROM principals p JOIN domain_memberships m ON m.principal_uuid=p.uuid WHERE p.uuid=? AND m.domain_uuid=?`, principalUUID, domainUUID).Scan(&found); err != nil { + return err + } + } result, err := tx.ExecContext(ctx, fmt.Sprintf(`UPDATE principals SET state=%s,updated_at_ms=%s WHERE uuid=%s AND EXISTS(SELECT 1 FROM domain_memberships WHERE domain_uuid=%s AND principal_uuid=%s)`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3), s.sqlParam(4), s.sqlParam(5)), state, time.Now().UnixMilli(), principalUUID, domainUUID, principalUUID) if err != nil { return err @@ -247,7 +268,7 @@ func (s *Store) SetPrincipalStateContext(ctx context.Context, domainUUID, princi if err != nil { return err } - if count == 0 { + if count == 0 && s.sqlBackend != storeMySQL { return sql.ErrNoRows } if state != "active" { @@ -274,6 +295,9 @@ func (s *Store) CreatePasswordAccount(domainUUID, username, password, displayNam } func (s *Store) EnsureAuthSchema() error { + if s.sqlBackend == storeMySQL { + return ErrBackendFeatureUnavailable + } if s.sqlBackend == storePostgreSQL { if err := s.ensurePostgreSQLAuthFoundation(context.Background()); err != nil { return err diff --git a/internal/store/auth_accounts_backend.go b/internal/store/auth_accounts_backend.go index 6933f11..cc793a3 100644 --- a/internal/store/auth_accounts_backend.go +++ b/internal/store/auth_accounts_backend.go @@ -40,9 +40,9 @@ func (s *Store) createPasswordAccountContext(ctx context.Context, domain, userna } // PostgreSQL cannot bootstrap into a nonexistent or disabled namespace. // SQLite retains its historical authentication-only fixture support. - if s.sqlBackend == storePostgreSQL { + if s.sqlBackend != storeSQLite { var present bool - if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM domains WHERE uuid=$1 AND enabled=1 AND placement='local')`, domain).Scan(&present); err != nil { + if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM domains WHERE uuid=`+s.sqlParam(1)+` AND enabled=1 AND placement='local')`, domain).Scan(&present); err != nil { return err } if !present { diff --git a/internal/store/auth_accounts_backend_test.go b/internal/store/auth_accounts_backend_test.go index 920ac9b..a3aeaf6 100644 --- a/internal/store/auth_accounts_backend_test.go +++ b/internal/store/auth_accounts_backend_test.go @@ -123,7 +123,7 @@ func TestAccountBackendCLIHandoff(t *testing.T) { } func TestAccountBackendExternalIdentity(t *testing.T) { - for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL} { + for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL, storeMySQL} { t.Run(fmt.Sprint(b), func(t *testing.T) { s, d := accountBackendStore(t, b) s.authKey = make([]byte, 32) @@ -135,6 +135,13 @@ func TestAccountBackendExternalIdentity(t *testing.T) { if err != nil || !provider.Enabled || provider.LDAPBindPassword != config.LDAPBindPassword { t.Fatal("provider configuration mismatch", err) } + var encoded, sealed string + if err := s.DB.QueryRow(`SELECT config_json,secret_encrypted FROM auth_providers WHERE domain_uuid=`+s.sqlParam(1)+` AND kind='ldap'`, d).Scan(&encoded, &sealed); err != nil { + t.Fatal(err) + } + if sealed == "" || strings.Contains(encoded, config.LDAPBindPassword) || strings.Contains(sealed, config.LDAPBindPassword) { + t.Fatal("provider secret stored in plaintext") + } config.LDAPBindPassword = "" config.LDAPSearchFilter = "(mail={{username}})" if err = s.SetAuthProviderConfig(d, config); err != nil { @@ -180,6 +187,11 @@ func TestAccountBackendExternalIdentity(t *testing.T) { if err = s.BindExternalIdentity(second.UUID, "ldap", provider.UUID, "", "immutable-id", nil); !errors.Is(err, ErrAccessDenied) { t.Fatal("identity owner replaced", err) } + for i := 0; i < 2; i++ { + if err = s.BindExternalIdentity(p.UUID, "ldap", provider.UUID, "", "immutable-id", nil); err != nil { + t.Fatal("identical owner binding must be idempotent", err) + } + } if _, err = s.ProvisionExternalAccount(d, "rollback-ext", "", "", "ldap", provider.UUID, "", "immutable-id", nil); !errors.Is(err, ErrAccessDenied) { t.Fatal("duplicate identity provisioned", err) } @@ -222,8 +234,51 @@ func TestAccountBackendExternalIdentity(t *testing.T) { } } +func TestAccountBackendProviderSecrets(t *testing.T) { + for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL, storeMySQL} { + t.Run(fmt.Sprint(b), func(t *testing.T) { + s, d := accountBackendStore(t, b) + s.authKey = make([]byte, 32) + for _, config := range []AuthProviderConfig{ + {Kind: "oidc", Enabled: true, Issuer: "https://issuer.example.test", ClientID: "synthetic", ClientSecret: "private-oidc-secret", OIDCMatchBy: "preferred_username"}, + {Kind: "smtp", Enabled: true, SMTPAddress: "smtp.example.test:587", SMTPPassword: "private-smtp-secret"}, + validLDAPProviderConfig(), + } { + t.Run(config.Kind, func(t *testing.T) { + if err := s.SetAuthProviderConfig(d, config); err != nil { + t.Fatal(err) + } + before, err := s.AuthProviderConfig(d, config.Kind) + if err != nil || before.UUID == "" || before.ClientSecret != config.ClientSecret || before.SMTPPassword != config.SMTPPassword || before.LDAPBindPassword != config.LDAPBindPassword { + t.Fatal("provider secret round trip", err) + } + config.ClientSecret, config.SMTPPassword, config.LDAPBindPassword = "", "", "" + config.Enabled = false + if err := s.SetAuthProviderConfig(d, config); err != nil { + t.Fatal(err) + } + after, err := s.AuthProviderConfig(d, config.Kind) + if err != nil || after.Enabled || after.UUID != before.UUID || after.ClientSecret != before.ClientSecret || after.SMTPPassword != before.SMTPPassword || after.LDAPBindPassword != before.LDAPBindPassword { + t.Fatal("provider secret preservation", err) + } + if config.Kind == "oidc" && after.OIDCMatchBy != "preferred_username" { + t.Fatal("account match mode lost") + } + s.ReadOnly = true + config.Enabled = true + err = s.SetAuthProviderConfig(d, config) + s.ReadOnly = false + if !errors.Is(err, ErrReadOnly) { + t.Fatal("read-only provider write", err) + } + }) + } + }) + } +} + func TestAccountBackendTOTP(t *testing.T) { - for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL} { + for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL, storeMySQL} { t.Run(fmt.Sprint(b), func(t *testing.T) { s, d := accountBackendStore(t, b) s.authKey = make([]byte, 32) // Synthetic credential encryption key. @@ -238,6 +293,12 @@ func TestAccountBackendTOTP(t *testing.T) { if s.HasTOTP(p.UUID) || s.PendingTOTPSecret(p.UUID) != secret { t.Fatal("pending enrollment mismatch") } + // Reopening enrollment replaces only the pending secret. + previous := secret + secret, err = s.BeginTOTPEnrollment(p.UUID) + if err != nil || secret == previous || s.PendingTOTPSecret(p.UUID) != secret { + t.Fatal("pending enrollment replacement", err) + } code, err := totpCode(secret, time.Now().Unix()/30) if err != nil { t.Fatal(err) @@ -293,6 +354,15 @@ func TestAccountBackendTOTP(t *testing.T) { if _, e := s.CompleteTOTPLoginChallenge(d, challenge, "invalid"); !errors.Is(e, ErrAccessDenied) { t.Fatal(e) } + var attempts int + var consumed int64 + if err := s.DB.QueryRow(`SELECT attempt_count,consumed_at_ms FROM auth_challenges WHERE token_hash=`+s.sqlParam(1), hashAuthToken(challenge)).Scan(&attempts, &consumed); err != nil { + t.Fatal(err) + } + want := min(i+1, 5) + if attempts != want || (consumed > 0) != (want == 5) { + t.Fatal("TOTP attempt limit", attempts, consumed, "want", want) + } } if err = s.PurgeExpiredAuthArtifacts(); err != nil { t.Fatal(err) @@ -312,7 +382,7 @@ func TestAccountBackendTOTP(t *testing.T) { } func TestAccountBackendProfileAndSessionManagement(t *testing.T) { - for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL} { + for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL, storeMySQL} { t.Run(fmt.Sprint(b), func(t *testing.T) { s, d := accountBackendStore(t, b) p, err := s.BootstrapOwner(d, "owner", "synthetic password for backend tests", "Owner", "") @@ -382,7 +452,7 @@ func TestAccountBackendProfileAndSessionManagement(t *testing.T) { } func TestAccountBackendBootstrapProjectionFailureIsAtomic(t *testing.T) { - for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL} { + for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL, storeMySQL} { t.Run(fmt.Sprint(b), func(t *testing.T) { s, d := accountBackendStore(t, b) if _, err := s.DB.Exec(`ALTER TABLE campus_admin_grants RENAME COLUMN source TO missing_source`); err != nil { @@ -403,7 +473,12 @@ func TestAccountBackendBootstrapProjectionFailureIsAtomic(t *testing.T) { func accountBackendStore(t *testing.T, b storeSQLBackend) (*Store, string) { t.Helper() - s := testNamespaceStore(t, b) + s := testNamespaceCoreStore(t, b) + if b == storeMySQL { + if err := s.ensureMySQLAuthFoundation(context.Background()); err != nil { + t.Fatal(err) + } + } if b == storePostgreSQL { if err := s.ensurePostgreSQLAuthFoundation(context.Background()); err != nil { t.Fatal(err) @@ -417,7 +492,7 @@ func accountBackendStore(t *testing.T, b storeSQLBackend) (*Store, string) { } func TestAccountBackendLoginAndSession(t *testing.T) { - for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL} { + for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL, storeMySQL} { t.Run(fmt.Sprint(b), func(t *testing.T) { s, d := accountBackendStore(t, b) const password = "synthetic password for backend tests" @@ -500,7 +575,7 @@ func TestAccountBackendLoginAndSession(t *testing.T) { } func TestAccountBackendConcurrentBootstrap(t *testing.T) { - for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL} { + for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL, storeMySQL} { t.Run(fmt.Sprint(b), func(t *testing.T) { s, d := accountBackendStore(t, b) var wg sync.WaitGroup diff --git a/internal/store/auth_external.go b/internal/store/auth_external.go index 808c2f9..43d8374 100644 --- a/internal/store/auth_external.go +++ b/internal/store/auth_external.go @@ -168,9 +168,9 @@ func (s *Store) ProvisionExternalAccount(domainUUID, username, displayName, emai p.DisplayName = username } err = s.groupWrite(context.Background(), func(ctx context.Context, tx *sql.Tx) error { - if s.sqlBackend == storePostgreSQL { + if s.sqlBackend != storeSQLite { var present bool - if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM domains WHERE uuid=$1 AND enabled=1 AND placement='local')`, domainUUID).Scan(&present); err != nil { + if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM domains WHERE uuid=`+s.sqlParam(1)+` AND enabled=1 AND placement='local')`, domainUUID).Scan(&present); err != nil { return err } if !present { @@ -214,6 +214,9 @@ func (s *Store) ProvisionExternalAccount(domainUUID, username, displayName, emai } func (s *Store) SetAuthProviderConfig(domainUUID string, config AuthProviderConfig) error { + if s.ReadOnly { + return ErrReadOnly + } config.Kind = strings.ToLower(strings.TrimSpace(config.Kind)) if config.Kind != "oidc" && config.Kind != "smtp" && config.Kind != "ldap" { return errors.New("unsupported authentication provider") @@ -256,7 +259,11 @@ func (s *Store) SetAuthProviderConfig(domainUUID string, config AuthProviderConf enabled = 1 } // Preserve the current secret inside the UPSERT, not via a stale pre-read. - _, err = s.DB.Exec(`INSERT INTO auth_providers(uuid,domain_uuid,kind,config_json,secret_encrypted,enabled,created_at_ms,updated_at_ms) VALUES(`+s.sqlValues(8)+`) ON CONFLICT(domain_uuid,kind) DO UPDATE SET config_json=excluded.config_json,secret_encrypted=CASE WHEN excluded.secret_encrypted='' THEN auth_providers.secret_encrypted ELSE excluded.secret_encrypted END,enabled=excluded.enabled,updated_at_ms=excluded.updated_at_ms`, uuid.NewString(), domainUUID, config.Kind, string(payload), encrypted, enabled, time.Now().UnixMilli(), time.Now().UnixMilli()) + suffix := ` ON CONFLICT(domain_uuid,kind) DO UPDATE SET config_json=excluded.config_json,secret_encrypted=CASE WHEN excluded.secret_encrypted='' THEN auth_providers.secret_encrypted ELSE excluded.secret_encrypted END,enabled=excluded.enabled,updated_at_ms=excluded.updated_at_ms` + if s.sqlBackend == storeMySQL { + suffix = ` AS incoming ON DUPLICATE KEY UPDATE config_json=incoming.config_json,secret_encrypted=CASE WHEN incoming.secret_encrypted='' THEN auth_providers.secret_encrypted ELSE incoming.secret_encrypted END,enabled=incoming.enabled,updated_at_ms=incoming.updated_at_ms` + } + _, err = s.DB.Exec(`INSERT INTO auth_providers(uuid,domain_uuid,kind,config_json,secret_encrypted,enabled,created_at_ms,updated_at_ms) VALUES(`+s.sqlValues(8)+`)`+suffix, uuid.NewString(), domainUUID, config.Kind, string(payload), encrypted, enabled, time.Now().UnixMilli(), time.Now().UnixMilli()) return s.sqlError("auth provider update", err) } @@ -405,14 +412,38 @@ func (s *Store) PrincipalByDisplayName(domainUUID, displayName string) (*Princip } func (s *Store) BindExternalIdentity(principalUUID, providerType, providerUUID, issuer, subject string, attributes any) error { + if s.ReadOnly { + return ErrReadOnly + } if strings.TrimSpace(subject) == "" || strings.TrimSpace(principalUUID) == "" { return ErrAccessDenied } - payload, err := json.Marshal(attributes) + payload, err := externalIdentityPayload(attributes) if err != nil { return err } now := time.Now().UnixMilli() + if s.sqlBackend == storeMySQL { + // Serialize with provisioning and first-login binding. MySQL reports + // changed rows, so a repeated identical binding must not be mistaken + // for a denied rebind; test ownership explicitly under the same lock. + return s.groupWrite(context.Background(), func(ctx context.Context, tx *sql.Tx) error { + var owner, id string + err := tx.QueryRowContext(ctx, `SELECT uuid,principal_uuid FROM principal_identities WHERE provider_type=? AND provider_uuid=? AND issuer=? AND subject=?`, providerType, providerUUID, issuer, subject).Scan(&id, &owner) + if errors.Is(err, sql.ErrNoRows) { + _, err = tx.ExecContext(ctx, `INSERT INTO principal_identities(uuid,principal_uuid,provider_type,provider_uuid,issuer,subject,attributes_json,created_at_ms) VALUES(?,?,?,?,?,?,?,?)`, uuid.NewString(), principalUUID, providerType, providerUUID, issuer, subject, payload, now) + return err + } + if err != nil { + return err + } + if owner != principalUUID { + return ErrAccessDenied + } + _, err = tx.ExecContext(ctx, `UPDATE principal_identities SET attributes_json=? WHERE uuid=?`, payload, id) + return err + }) + } result, err := s.DB.Exec(`INSERT INTO principal_identities(uuid,principal_uuid,provider_type,provider_uuid,issuer,subject,attributes_json,created_at_ms) VALUES(`+s.sqlValues(8)+`) ON CONFLICT(provider_type,provider_uuid,issuer,subject) DO UPDATE SET attributes_json=excluded.attributes_json WHERE principal_identities.principal_uuid=excluded.principal_uuid`, uuid.NewString(), principalUUID, providerType, providerUUID, issuer, subject, string(payload), now) if err != nil { return err @@ -430,7 +461,7 @@ func (s *Store) BindExternalIdentity(principalUUID, providerType, providerUUID, func (s *Store) PrincipalByExternalIdentity(domainUUID, providerType, providerUUID, issuer, subject string) (*Principal, error) { var p Principal err := s.DB.QueryRow(`SELECT p.uuid,COALESCE((SELECT subject FROM principal_identities x WHERE x.principal_uuid=p.uuid AND x.provider_type='password' ORDER BY subject,uuid LIMIT 1),p.uuid),p.display_name,p.email,p.state,length(p.avatar)>0 FROM principal_identities i JOIN principals p ON p.uuid=i.principal_uuid JOIN domain_memberships m ON m.principal_uuid=p.uuid AND m.domain_uuid=`+s.sqlParam(1)+` AND m.state='active' WHERE i.provider_type=`+s.sqlParam(2)+` AND i.provider_uuid=`+s.sqlParam(3)+` AND i.issuer=`+s.sqlParam(4)+` AND i.subject=`+s.sqlParam(5)+` AND p.state IN ('active','readonly')`, domainUUID, providerType, providerUUID, issuer, subject).Scan(&p.UUID, &p.Username, &p.DisplayName, &p.Email, &p.State, &p.HasAvatar) - return &p, err + return &p, s.sqlError("external identity lookup", err) } func (s *Store) CreateAuthChallenge(domainUUID, principalUUID, kind string, payload any, lifetime time.Duration) (string, error) { diff --git a/internal/store/auth_mysql.go b/internal/store/auth_mysql.go new file mode 100644 index 0000000..6264172 --- /dev/null +++ b/internal/store/auth_mysql.go @@ -0,0 +1,174 @@ +package store + +import ( + "context" + "database/sql" + + "pageswiki/internal/db" +) + +// This is a persistence pilot, not a server/authentication endpoint. The caller +// MUST authenticate and authorize every administrator mutation. It intentionally +// exposes neither *Store nor grant-only checks as a complete authorization API. +// MFA/provider persistence is internally tested but not exposed as a login API. +// Audit/locality policy, CLI handoff and Domain deletion remain unported. +type MySQLIdentityRepository struct{ store *Store } + +func NewMySQLIdentityRepository(database *sql.DB) *MySQLIdentityRepository { + return &MySQLIdentityRepository{store: &Store{DB: database, sqlBackend: storeMySQL}} +} +func (r *MySQLIdentityRepository) PrepareSchema(ctx context.Context) error { + return r.store.ensureMySQLAuthFoundation(ctx) +} +func (r *MySQLIdentityRepository) InspectSchema(ctx context.Context) (db.MySQLMigrationStatus, error) { + base, err := NewMySQLNamespaceRepository(r.store.DB).InspectSchema(ctx) + if err != nil { + return base, err + } + auth, err := db.InspectMySQLMigrations(ctx, r.store.DB, "store-auth-core", mysqlAuthMigrations()) + if err != nil { + return auth, err + } + result := db.MySQLMigrationStatus{Applied: base.Applied + auth.Applied, Pending: base.Pending + auth.Pending, Dirty: base.Dirty || auth.Dirty} + if base.Dirty { + result.DirtyComponent, result.NextOperation = base.DirtyComponent, base.NextOperation + } else if auth.Dirty { + result.DirtyComponent, result.NextOperation = auth.DirtyComponent, auth.NextOperation + } + return result, nil +} +func (r *MySQLIdentityRepository) ResumeSchema(ctx context.Context) error { + base, err := NewMySQLNamespaceRepository(r.store.DB).InspectSchema(ctx) + if err != nil { + return err + } + if base.Dirty || base.Pending != 0 { + return db.ErrMySQLMigrationMismatch + } + return db.ResumeMySQLMigrations(ctx, r.store.DB, "store-auth-core", mysqlAuthMigrations()) +} +func mysqlIdentityIDs(ids ...string) error { + for _, id := range ids { + if err := mysqlNamespaceUUID(id); err != nil { + return err + } + } + return nil +} +func (r *MySQLIdentityRepository) BootstrapOwner(ctx context.Context, domain, username, password, displayName, email string) (*Principal, error) { + if err := mysqlIdentityIDs(domain); err != nil { + return nil, err + } + return r.store.BootstrapOwnerContext(ctx, domain, username, password, displayName, email) +} +func (r *MySQLIdentityRepository) CreateAccount(ctx context.Context, domain, username, password, displayName, email string) (*Principal, error) { + if err := mysqlIdentityIDs(domain); err != nil { + return nil, err + } + return r.store.CreatePasswordAccountContext(ctx, domain, username, password, displayName, email) +} +func (r *MySQLIdentityRepository) Principals(ctx context.Context, domain string) ([]Principal, error) { + if err := mysqlIdentityIDs(domain); err != nil { + return nil, err + } + return r.store.ListDomainPrincipalsContext(ctx, domain) +} +func (r *MySQLIdentityRepository) Sessions(ctx context.Context, domain string) ([]AuthSessionInfo, error) { + if err := mysqlIdentityIDs(domain); err != nil { + return nil, err + } + return r.store.ListAuthSessionsContext(ctx, domain) +} +func (r *MySQLIdentityRepository) RevokeSession(ctx context.Context, domain, session string) error { + if err := mysqlIdentityIDs(domain, session); err != nil { + return err + } + return r.store.RevokeAuthSessionByIDContext(ctx, domain, session) +} +func (r *MySQLIdentityRepository) SetPrincipalState(ctx context.Context, domain, principal, state string) error { + if err := mysqlIdentityIDs(domain, principal); err != nil { + return err + } + return r.store.SetPrincipalStateContext(ctx, domain, principal, state) +} +func (r *MySQLIdentityRepository) CreateGroup(ctx context.Context, domain, owner, name, title, description, visibility string) (*Group, error) { + if err := mysqlIdentityIDs(domain, owner); err != nil { + return nil, err + } + return r.store.CreateGroupContext(ctx, domain, owner, name, title, description, visibility) +} +func (r *MySQLIdentityRepository) Groups(ctx context.Context, domain, principal string) ([]Group, error) { + if err := mysqlIdentityIDs(domain); err != nil { + return nil, err + } + if principal != "" { + if err := mysqlIdentityIDs(principal); err != nil { + return nil, err + } + } + return r.store.ListGroupsContext(ctx, domain, principal) +} +func (r *MySQLIdentityRepository) Group(ctx context.Context, domain, name string) (*Group, error) { + if err := mysqlIdentityIDs(domain); err != nil { + return nil, err + } + return r.store.GroupByNameContext(ctx, domain, name) +} +func (r *MySQLIdentityRepository) Members(ctx context.Context, domain, group string) ([]GroupMember, error) { + if err := r.groupScope(ctx, domain, group); err != nil { + return nil, err + } + return r.store.ListGroupMembersContext(ctx, group) +} +func (r *MySQLIdentityRepository) groupScope(ctx context.Context, domain, group string) error { + if err := mysqlIdentityIDs(domain, group); err != nil { + return err + } + _, err := r.store.GroupByUUIDContext(ctx, domain, group) + return err +} +func (r *MySQLIdentityRepository) AddMember(ctx context.Context, domain, group, username, role string) error { + if err := mysqlIdentityIDs(domain, group); err != nil { + return err + } + return r.store.AddGroupMemberByUsernameContext(ctx, domain, group, username, role) +} +func (r *MySQLIdentityRepository) RemoveMember(ctx context.Context, domain, group, membership string, ownerAuthority bool) error { + if err := mysqlIdentityIDs(membership); err != nil { + return err + } + if err := r.groupScope(ctx, domain, group); err != nil { + return err + } + return r.store.RemoveGroupMemberWithAuthorityContext(ctx, group, membership, ownerAuthority) +} +func (r *MySQLIdentityRepository) SetPermission(ctx context.Context, domain, group, path, permission string) error { + if err := r.groupScope(ctx, domain, group); err != nil { + return err + } + return r.store.SetGroupPermissionContext(ctx, group, path, permission) +} +func (r *MySQLIdentityRepository) SetInheritance(ctx context.Context, domain, group string, enabled bool) error { + if err := r.groupScope(ctx, domain, group); err != nil { + return err + } + return r.store.SetCampusAdminInheritanceContext(ctx, group, enabled) +} +func (r *MySQLIdentityRepository) IsBuiltinAdmin(ctx context.Context, domain, principal, key string) (bool, error) { + if err := mysqlIdentityIDs(domain, principal); err != nil { + return false, err + } + return r.store.IsBuiltinGroupAdminContext(ctx, domain, principal, key) +} +func (r *MySQLIdentityRepository) CreateLocalDomain(ctx context.Context, campus, name, title, host string, enabled bool) error { + if err := mysqlIdentityIDs(campus); err != nil { + return err + } + return r.store.writeDomain(ctx, 0, false, campus, name, title, host, "local", "", "", enabled) +} +func (r *MySQLIdentityRepository) UpdateLocalDomain(ctx context.Context, id int64, campus, name, title, host string, enabled bool) error { + if err := mysqlIdentityIDs(campus); err != nil { + return err + } + return r.store.writeDomain(ctx, id, true, campus, name, title, host, "local", "", "", enabled) +} diff --git a/internal/store/auth_mysql_schema.go b/internal/store/auth_mysql_schema.go new file mode 100644 index 0000000..21b9b63 --- /dev/null +++ b/internal/store/auth_mysql_schema.go @@ -0,0 +1,99 @@ +package store + +import ( + "context" + "fmt" + "strings" + + "pageswiki/internal/db" +) + +// These definitions are owned native MySQL DDL, not translations of SQLite +// migrations. NO PAD binary collation keeps identifiers and Path scopes exact. +type mysqlAuthColumn struct{ name, kind, defaultSQL string } +type mysqlAuthTable struct { + name string + columns []mysqlAuthColumn + keys []string // first is primary; remaining keys are unique + indexes []string +} + +func mysqlAuthMigrations() []db.MySQLMigration { + const id = "varchar(36)" + const text = "longtext" + const state = "varchar(32)" + const number = "bigint" + tables := []mysqlAuthTable{ + {"principals", []mysqlAuthColumn{{"uuid", id, ""}, {"display_name", text, "('')"}, {"email", text, "('')"}, {"state", state, "'active'"}, {"avatar", "longblob", "(X'')"}, {"avatar_content_type", "varchar(128)", "''"}, {"created_at_ms", number, ""}, {"updated_at_ms", number, ""}}, []string{"uuid"}, nil}, + {"principal_identities", []mysqlAuthColumn{{"uuid", id, ""}, {"principal_uuid", id, ""}, {"provider_type", "varchar(32)", ""}, {"provider_uuid", id, "''"}, {"issuer", "varchar(255)", "''"}, {"subject", "varchar(255)", ""}, {"attributes_json", text, "('{}')"}, {"created_at_ms", number, ""}}, []string{"uuid", "provider_type,provider_uuid,issuer,subject"}, []string{"principal_uuid,provider_type,subject"}}, + {"domain_memberships", []mysqlAuthColumn{{"uuid", id, ""}, {"domain_uuid", id, ""}, {"principal_uuid", id, ""}, {"state", state, "'active'"}, {"created_at_ms", number, ""}}, []string{"uuid", "domain_uuid,principal_uuid"}, []string{"principal_uuid,domain_uuid"}}, + {"auth_roles", []mysqlAuthColumn{{"uuid", id, ""}, {"domain_uuid", id, ""}, {"name", "varchar(128)", ""}, {"description", text, "('')"}, {"created_at_ms", number, ""}}, []string{"uuid", "domain_uuid,name"}, nil}, + {"auth_role_bindings", []mysqlAuthColumn{{"membership_uuid", id, ""}, {"role_uuid", id, ""}, {"created_at_ms", number, ""}}, []string{"membership_uuid,role_uuid"}, nil}, + {"auth_capability_grants", []mysqlAuthColumn{{"uuid", id, ""}, {"role_uuid", id, ""}, {"capability", "varchar(32)", ""}, {"target_type", "varchar(32)", ""}, {"target_id", "varchar(512)", "'*'"}, {"created_at_ms", number, ""}}, []string{"uuid", "role_uuid,capability,target_type,target_id"}, nil}, + {"groups", []mysqlAuthColumn{{"uuid", id, ""}, {"domain_uuid", id, ""}, {"name", "varchar(64)", ""}, {"display_name", text, "('')"}, {"description", text, "('')"}, {"visibility", "varchar(32)", "'members'"}, {"state", state, "'active'"}, {"builtin_key", "varchar(32)", "''"}, {"inherit_members", "int", "0"}, {"created_at_ms", number, ""}, {"updated_at_ms", number, ""}}, []string{"uuid", "domain_uuid,name"}, nil}, + {"group_members", []mysqlAuthColumn{{"group_uuid", id, ""}, {"membership_uuid", id, ""}, {"member_role", "varchar(32)", "'member'"}, {"source", "varchar(128)", "'local'"}, {"created_at_ms", number, ""}}, []string{"group_uuid,membership_uuid"}, []string{"membership_uuid,group_uuid"}}, + {"campus_admin_grants", []mysqlAuthColumn{{"group_uuid", id, ""}, {"membership_uuid", id, ""}, {"source", "varchar(128)", ""}, {"member_role", "varchar(32)", ""}, {"created_at_ms", number, ""}}, []string{"group_uuid,membership_uuid,source"}, []string{"membership_uuid"}}, + {"campus_admin_membership_origins", []mysqlAuthColumn{{"membership_uuid", id, ""}, {"domain_uuid", id, ""}, {"principal_uuid", id, ""}}, []string{"membership_uuid", "domain_uuid,principal_uuid"}, nil}, + {"campus_admin_migrations", []mysqlAuthColumn{{"key", "varchar(128)", ""}}, []string{"key"}, nil}, + {"auth_sessions", []mysqlAuthColumn{{"uuid", id, ""}, {"token_hash", "varchar(128)", ""}, {"principal_uuid", id, ""}, {"domain_uuid", id, ""}, {"auth_time_ms", number, ""}, {"expires_at_ms", number, ""}, {"last_seen_at_ms", number, ""}, {"mfa_level", "int", "0"}, {"revoked_at_ms", number, "0"}}, []string{"uuid", "token_hash"}, []string{"domain_uuid,principal_uuid,revoked_at_ms"}}, + {"group_permissions", []mysqlAuthColumn{{"uuid", id, ""}, {"group_uuid", id, ""}, {"scope_path", "varchar(512)", ""}, {"permission", "varchar(32)", ""}, {"created_at_ms", number, ""}}, []string{"uuid", "group_uuid,scope_path"}, nil}, + {"auth_credentials", []mysqlAuthColumn{{"uuid", id, ""}, {"principal_uuid", id, ""}, {"kind", "varchar(32)", ""}, {"identifier", "varchar(255)", "''"}, {"secret_hash", text, ""}, {"parameters_json", text, "('{}')"}, {"enabled", "int", "1"}, {"created_at_ms", number, ""}, {"updated_at_ms", number, ""}}, []string{"uuid", "kind,identifier"}, nil}, + } + steps := []db.MySQLMigration{ + mysqlAuthTableMigration(1, "identity membership and group foundation", tables), + mysqlAuthTableMigration(2, "authentication challenges and provider configuration", []mysqlAuthTable{ + {"auth_challenges", []mysqlAuthColumn{{"uuid", id, ""}, {"domain_uuid", id, ""}, {"principal_uuid", id, "''"}, {"kind", state, ""}, {"token_hash", "varchar(128)", ""}, {"payload_json", text, "('{}')"}, {"expires_at_ms", number, ""}, {"consumed_at_ms", number, "0"}, {"attempt_count", "int", "0"}, {"created_at_ms", number, ""}}, []string{"uuid", "token_hash"}, []string{"expires_at_ms"}}, + {"auth_providers", []mysqlAuthColumn{{"uuid", id, ""}, {"domain_uuid", id, ""}, {"kind", state, ""}, {"config_json", text, "('{}')"}, {"secret_encrypted", text, "('')"}, {"enabled", "int", "0"}, {"created_at_ms", number, ""}, {"updated_at_ms", number, ""}}, []string{"uuid", "domain_uuid,kind"}, nil}, + }), + } + // Inspect validates the latest contract only, since later versions may + // replace older columns. This additive version must retain all v1 checks. + steps[1].Assertions = append(append([]string{}, steps[0].Assertions...), steps[1].Assertions...) + return steps +} + +// Keep generated version 1 operations/assertions byte-identical: deployed +// journals checksum the plan. Extend with new versions, never rewrite history. +func mysqlAuthTableMigration(version int, name string, tables []mysqlAuthTable) db.MySQLMigration { + var ops []db.MySQLOperation + var checks []string + for _, table := range tables { + var definitions, signature []string + for _, col := range table.columns { + definition := "`" + col.name + "` " + col.kind + " NOT NULL" + if col.defaultSQL != "" { + definition += " DEFAULT " + col.defaultSQL + } + definitions = append(definitions, definition) + collation := "" + if strings.Contains(col.kind, "char") || strings.Contains(col.kind, "text") { + collation = "utf8mb4_0900_bin" + } + signature = append(signature, col.name+":"+col.kind+":NO:"+collation) + } + definitions = append(definitions, "PRIMARY KEY("+mysqlAuthIdentifiers(table.keys[0])+")") + check := mysqlMLTableCheck(table.name, strings.Join(signature, "|"), table.keys[0], 0) + for i, key := range table.keys[1:] { + name := fmt.Sprintf("uq_%d", i) + definitions = append(definitions, "UNIQUE KEY "+name+"("+mysqlAuthIdentifiers(key)+")") + check += fmt.Sprintf(` AND (SELECT GROUP_CONCAT(column_name ORDER BY seq_in_index SEPARATOR ',') FROM information_schema.statistics WHERE table_schema=DATABASE() AND table_name='%s' AND index_name='%s' AND non_unique=0)='%s'`, table.name, name, key) + } + for i, key := range table.indexes { + definitions = append(definitions, fmt.Sprintf("INDEX ix_%d(%s)", i, mysqlAuthIdentifiers(key))) + } + statement := "CREATE TABLE `" + table.name + "`(" + strings.Join(definitions, ",") + ") ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin" + ops = append(ops, db.MySQLOperation{SQL: statement, Check: check, ReplaySafe: true}) + checks = append(checks, check) + } + return db.MySQLMigration{Version: version, Name: name, Operations: ops, Assertions: checks} +} +func mysqlAuthIdentifiers(names string) string { + return "`" + strings.ReplaceAll(names, ",", "`,`") + "`" +} + +func (s *Store) ensureMySQLAuthFoundation(ctx context.Context) error { + if err := NewMySQLNamespaceRepository(s.DB).PrepareSchema(ctx); err != nil { + return err + } + return db.ApplyMySQLMigrations(ctx, s.DB, "store-auth-core", mysqlAuthMigrations()) +} diff --git a/internal/store/auth_mysql_test.go b/internal/store/auth_mysql_test.go new file mode 100644 index 0000000..1a5b795 --- /dev/null +++ b/internal/store/auth_mysql_test.go @@ -0,0 +1,298 @@ +package store + +import ( + "context" + "database/sql" + "errors" + "strings" + "testing" + + "pageswiki/internal/db" +) + +func TestMySQLIdentityDomainLifecycle(t *testing.T) { + database := mysqlTestDatabase(t) + r := NewMySQLIdentityRepository(database) + ns := NewMySQLNamespaceRepository(database) + ctx := context.Background() + if e := r.PrepareSchema(ctx); e != nil { + t.Fatal(e) + } + if e := ns.CreateCampus(ctx, "home", "キャンパス", "ja", "standalone", "home.example.test", true); e != nil { + t.Fatal(e) + } + campuses, e := ns.Campuses(ctx) + if e != nil || len(campuses) != 1 { + t.Fatal(campuses, e) + } + campus := campuses[0] + if e := r.CreateLocalDomain(ctx, campus.UUID, "default", "ドメイン", "", true); e != nil { + t.Fatal(e) + } + domain, e := ns.ResolveHost(ctx, "home.example.test") + if e != nil { + t.Fatal(e) + } + const password = "synthetic password for identity pilot" + owner, e := r.BootstrapOwner(ctx, domain.UUID, "owner", password, "所有者", "owner@example.test") + if e != nil { + t.Fatal(e) + } + member, e := r.CreateAccount(ctx, domain.UUID, "member", password, "利用者", "member@example.test") + if e != nil { + t.Fatal(e) + } + if _, e := r.CreateAccount(ctx, domain.UUID, "member", password, "private duplicate title", ""); e == nil || strings.Contains(e.Error(), "private duplicate title") { + t.Fatal("duplicate account handling", e) + } + people, e := r.Principals(ctx, domain.UUID) + if e != nil || len(people) != 2 { + t.Fatal(people, e) + } + g, e := r.CreateGroup(ctx, domain.UUID, owner.UUID, "team", "チーム", "説明", "members") + if e != nil { + t.Fatal(e) + } + for i := 0; i < 2; i++ { + if e := r.AddMember(ctx, domain.UUID, g.UUID, "member", "member"); e != nil { + t.Fatal("repeat add", e) + } + if e := r.SetPermission(ctx, domain.UUID, g.UUID, "/literal%_", "read_write"); e != nil { + t.Fatal("repeat permission", e) + } + if e := r.SetPrincipalState(ctx, domain.UUID, member.UUID, "active"); e != nil { + t.Fatal("repeat state", e) + } + } + members, e := r.Members(ctx, domain.UUID, g.UUID) + if e != nil || len(members) != 2 { + t.Fatal(members, e) + } + if e := r.AddMember(ctx, domain.UUID, g.UUID, "owner", "member"); e == nil { + t.Fatal("owner downgraded") + } + for _, m := range members { + if m.PrincipalUUID == member.UUID { + if e := r.RemoveMember(ctx, domain.UUID, g.UUID, m.MembershipUUID, false); e != nil { + t.Fatal(e) + } + } + } + if e := r.CreateLocalDomain(ctx, campus.UUID, "child", "Child", "child", true); e != nil { + t.Fatal(e) + } + results := make(chan error, 2) + for _, name := range []string{"race-one", "race-two"} { + go func(name string) { results <- r.CreateLocalDomain(ctx, campus.UUID, name, "Race", "same-host", true) }(name) + } + success := 0 + for i := 0; i < 2; i++ { + if <-results == nil { + success++ + } + } + if success != 1 { + t.Fatal("Domain host concurrency", success) + } + child, e := ns.ResolveHost(ctx, "child.home.example.test") + if e != nil { + t.Fatal(e) + } + if got, e := ns.Config(ctx, child.UUID, "locale"); e != nil || got != "ja" { + t.Fatal("locale inheritance", got, e) + } + if allowed, e := r.IsBuiltinAdmin(ctx, child.UUID, owner.UUID, "campus_admin"); e != nil || !allowed { + t.Fatal("admin inheritance", e) + } + if _, e := r.Members(ctx, child.UUID, g.UUID); !errors.Is(e, sql.ErrNoRows) { + t.Fatal("cross-domain group", e) + } + root, e := r.Group(ctx, domain.UUID, "campus_admin") + if e != nil { + t.Fatal(e) + } + for i := 0; i < 2; i++ { + if e := r.SetInheritance(ctx, domain.UUID, root.UUID, true); e != nil { + t.Fatal("repeat inheritance", e) + } + } + token, e := r.store.CreateBrowserAuthSession(child.UUID, owner.UUID, 1) + if e != nil { + t.Fatal(e) + } + sessions, e := r.Sessions(ctx, child.UUID) + if e != nil || len(sessions) != 1 { + t.Fatal("session administration", sessions, e) + } + if e := r.RevokeSession(ctx, domain.UUID, sessions[0].UUID); !errors.Is(e, sql.ErrNoRows) { + t.Fatal("cross-domain session revocation", e) + } + if e := r.RevokeSession(ctx, child.UUID, sessions[0].UUID); e != nil { + t.Fatal(e) + } + if _, e := r.store.PrincipalForSession(child.UUID, token); !errors.Is(e, ErrAccessDenied) { + t.Fatal("administratively revoked session accepted", e) + } + token, e = r.store.CreateBrowserAuthSession(child.UUID, owner.UUID, 1) + if e != nil { + t.Fatal(e) + } + if e := ns.CreateCampus(ctx, "other", "Other", "en", "standalone", "other.example.test", true); e != nil { + t.Fatal(e) + } + campuses, e = ns.Campuses(ctx) + if e != nil { + t.Fatal(e) + } + var other string + for _, c := range campuses { + if c.UUID != campus.UUID { + other = c.UUID + } + } + if e := r.UpdateLocalDomain(ctx, child.ID, other, child.Name, "Moved", child.Domain, true); e != nil { + t.Fatal(e) + } + if allowed, e := r.IsBuiltinAdmin(ctx, child.UUID, owner.UUID, "campus_admin"); e != nil || allowed { + t.Fatal("stale inherited admin", e) + } + if _, e := r.store.PrincipalForSession(child.UUID, token); !errors.Is(e, ErrAccessDenied) { + t.Fatal("stale session", e) + } + if _, e := database.Exec(`UPDATE domains SET placement='remote' WHERE uuid=?`, child.UUID); e != nil { + t.Fatal(e) + } + if e := r.UpdateLocalDomain(ctx, child.ID, other, child.Name, "Must not change", child.Domain, true); !errors.Is(e, ErrBackendFeatureUnavailable) { + t.Fatal("remote Domain adopted locally", e) + } + if _, e := database.Exec(`UPDATE domains SET placement='local' WHERE uuid=?`, child.UUID); e != nil { + t.Fatal(e) + } + if e := r.CreateLocalDomain(ctx, campus.UUID, "collision", "Collision", "", true); e == nil { + t.Fatal("host collision") + } + if e := ns.CreateCampus(ctx, "controller", "Controller", "en", "controller", "controller.example.test", true); e != nil { + t.Fatal(e) + } + campuses, e = ns.Campuses(ctx) + if e != nil { + t.Fatal(e) + } + for _, c := range campuses { + if c.Name == "controller" { + if e := r.CreateLocalDomain(ctx, c.UUID, "remote", "Remote", "remote", true); !errors.Is(e, ErrBackendFeatureUnavailable) { + t.Fatal("federation bypass", e) + } + } + } + // A failing inheritance write must roll back Domain, locale and built-ins. + before, e := ns.Domains(ctx) + if e != nil { + t.Fatal(e) + } + if _, e := database.Exec(`ALTER TABLE campus_admin_grants RENAME COLUMN source TO missing_source`); e != nil { + t.Fatal(e) + } + if e := r.CreateLocalDomain(ctx, campus.UUID, "rollback", "Rollback", "rollback", true); e == nil { + t.Fatal("partial Domain accepted") + } + after, e := ns.Domains(ctx) + if e != nil || len(before) != len(after) { + t.Fatal("partial Domain remains", e) + } +} + +func TestMySQLIdentitySchemaAndCancellation(t *testing.T) { + database := mysqlTestDatabase(t) + r := NewMySQLIdentityRepository(database) + ctx := context.Background() + if status, e := r.InspectSchema(ctx); e != nil || status.Pending != 5 { + t.Fatal(status, e) + } + if e := r.PrepareSchema(ctx); e != nil { + t.Fatal(e) + } + if e := r.PrepareSchema(ctx); e != nil { + t.Fatal("repeat prepare", e) + } + if _, e := database.Exec(`UPDATE schema_mysql_migrations SET state='running',next_operation=1 WHERE component='store-auth-core' AND version=2`); e != nil { + t.Fatal(e) + } + if e := r.PrepareSchema(ctx); !errors.Is(e, db.ErrMySQLMigrationDirty) { + t.Fatal(e) + } + if e := r.ResumeSchema(ctx); e != nil { + t.Fatal(e) + } + if status, e := r.InspectSchema(ctx); e != nil || status.Pending != 0 || status.Dirty { + t.Fatal(status, e) + } + cancelled, cancel := context.WithCancel(ctx) + cancel() + if _, e := r.store.ListDomainPrincipalsContext(cancelled, "unused"); !errors.Is(e, context.Canceled) { + t.Fatal(e) + } + const validID = "00000000-0000-4000-a000-000000000001" + if _, e := r.Sessions(cancelled, validID); !errors.Is(e, context.Canceled) { + t.Fatal("cancel session list", e) + } + if e := r.RevokeSession(cancelled, validID, validID); !errors.Is(e, context.Canceled) { + t.Fatal("cancel session revocation", e) + } + r.store.ReadOnly = true + if e := r.RevokeSession(ctx, validID, validID); !errors.Is(e, ErrReadOnly) { + t.Fatal("read-only session revocation", e) + } + r.store.ReadOnly = false + if e := r.CreateLocalDomain(cancelled, "00000000-0000-4000-a000-000000000001", "cancelled", "Cancelled", "cancelled", true); !errors.Is(e, context.Canceled) { + t.Fatal(e) + } + if _, e := database.Exec(`ALTER TABLE group_permissions MODIFY scope_path VARCHAR(256) NOT NULL`); e != nil { + t.Fatal(e) + } + if _, e := r.InspectSchema(ctx); e == nil { + t.Fatal("schema drift accepted") + } +} + +func TestMySQLIdentitySchemaUpgradePreservesAccounts(t *testing.T) { + database := mysqlTestDatabase(t) + ctx := context.Background() + if err := NewMySQLNamespaceRepository(database).PrepareSchema(ctx); err != nil { + t.Fatal(err) + } + plan := mysqlAuthMigrations() + if err := db.ApplyMySQLMigrations(ctx, database, "store-auth-core", plan[:1]); err != nil { + t.Fatal(err) + } + var before string + if err := database.QueryRow(`SELECT checksum FROM schema_mysql_migrations WHERE component='store-auth-core' AND version=1`).Scan(&before); err != nil { + t.Fatal(err) + } + if _, err := database.Exec(`INSERT INTO principals(uuid,display_name,created_at_ms,updated_at_ms) VALUES('upgrade-user','既存の利用者',1,1)`); err != nil { + t.Fatal(err) + } + r := NewMySQLIdentityRepository(database) + if status, err := r.InspectSchema(ctx); err != nil || status.Pending != 1 || status.Applied != 4 { + t.Fatal(status, err) + } + if err := r.PrepareSchema(ctx); err != nil { + t.Fatal(err) + } + var after, title string + if err := database.QueryRow(`SELECT checksum FROM schema_mysql_migrations WHERE component='store-auth-core' AND version=1`).Scan(&after); err != nil || after != before { + t.Fatal("historical checksum changed", err) + } + if err := database.QueryRow(`SELECT display_name FROM principals WHERE uuid='upgrade-user'`).Scan(&title); err != nil || title != "既存の利用者" { + t.Fatal("existing principal changed", err) + } + if status, err := r.InspectSchema(ctx); err != nil || status.Pending != 0 || status.Applied != 5 { + t.Fatal(status, err) + } + if _, err := database.Exec(`ALTER TABLE auth_providers DROP INDEX uq_0`); err != nil { + t.Fatal(err) + } + if _, err := r.InspectSchema(ctx); err == nil { + t.Fatal("provider uniqueness drift accepted") + } +} diff --git a/internal/store/auth_totp.go b/internal/store/auth_totp.go index b8ca297..a70880c 100644 --- a/internal/store/auth_totp.go +++ b/internal/store/auth_totp.go @@ -66,7 +66,11 @@ func (s *Store) BeginTOTPEnrollment(principalUUID string) (string, error) { } now := time.Now().UnixMilli() err = s.groupWrite(context.Background(), func(ctx context.Context, tx *sql.Tx) error { - _, err := tx.ExecContext(ctx, `INSERT INTO auth_credentials(uuid,principal_uuid,kind,identifier,secret_hash,parameters_json,enabled,created_at_ms,updated_at_ms) VALUES(`+s.sqlValues(9)+`) ON CONFLICT(kind,identifier) DO UPDATE SET secret_hash=excluded.secret_hash,parameters_json='{}',enabled=0,updated_at_ms=excluded.updated_at_ms`, uuid.NewString(), principalUUID, "totp-pending", principalUUID, encrypted, "{}", 0, now, now) + suffix := ` ON CONFLICT(kind,identifier) DO UPDATE SET secret_hash=excluded.secret_hash,parameters_json='{}',enabled=0,updated_at_ms=excluded.updated_at_ms` + if s.sqlBackend == storeMySQL { + suffix = ` AS incoming ON DUPLICATE KEY UPDATE secret_hash=incoming.secret_hash,parameters_json='{}',enabled=0,updated_at_ms=incoming.updated_at_ms` + } + _, err := tx.ExecContext(ctx, `INSERT INTO auth_credentials(uuid,principal_uuid,kind,identifier,secret_hash,parameters_json,enabled,created_at_ms,updated_at_ms) VALUES(`+s.sqlValues(9)+`)`+suffix, uuid.NewString(), principalUUID, "totp-pending", principalUUID, encrypted, "{}", 0, now, now) return err }) if err != nil { @@ -229,7 +233,10 @@ func (s *Store) CompleteTOTPLoginChallengeForLogin(domainUUID, token, code strin return "", false, ErrAccessDenied } if err = s.VerifyTOTP(principalUUID, code); err != nil { - _, _ = s.DB.Exec(fmt.Sprintf(`UPDATE auth_challenges SET attempt_count=attempt_count+1,consumed_at_ms=CASE WHEN attempt_count+1>=5 THEN %s ELSE consumed_at_ms END WHERE uuid=%s AND consumed_at_ms=0`, s.sqlParam(1), s.sqlParam(2)), time.Now().UnixMilli(), challengeUUID) + // MySQL evaluates single-table UPDATE assignments left-to-right. Test + // the old counter before incrementing, or the fifth-attempt limit + // becomes four attempts on that backend. + _, _ = s.DB.Exec(fmt.Sprintf(`UPDATE auth_challenges SET consumed_at_ms=CASE WHEN attempt_count+1>=5 THEN %s ELSE consumed_at_ms END,attempt_count=attempt_count+1 WHERE uuid=%s AND consumed_at_ms=0`, s.sqlParam(1), s.sqlParam(2)), time.Now().UnixMilli(), challengeUUID) return "", false, err } result, err := s.DB.Exec(fmt.Sprintf(`UPDATE auth_challenges SET consumed_at_ms=%s WHERE uuid=%s AND consumed_at_ms=0 AND attempt_count<5 AND expires_at_ms>%s`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), time.Now().UnixMilli(), challengeUUID, time.Now().UnixMilli()) diff --git a/internal/store/campuses.go b/internal/store/campuses.go index 7df8a62..5fe7098 100644 --- a/internal/store/campuses.go +++ b/internal/store/campuses.go @@ -26,6 +26,9 @@ type Campus struct { } func (s *Store) EnsureCampusesSchema() error { + if s.sqlBackend == storeMySQL { + return ErrBackendFeatureUnavailable + } if s.sqlBackend == storePostgreSQL { return s.ensurePostgreSQLCampusDefaults(context.Background()) } @@ -249,6 +252,13 @@ func (s *Store) CreateCampus( fqdn string, enabled bool, ) error { + return s.CreateCampusContext(context.Background(), name, title, defaultLang, authorityMode, fqdn, enabled) +} + +func (s *Store) CreateCampusContext(ctx context.Context, name, title, defaultLang, authorityMode, fqdn string, enabled bool) error { + if s.ReadOnly { + return ErrReadOnly + } name = normalizeCampusName(name) title = strings.TrimSpace(title) if name == "" { @@ -282,7 +292,7 @@ func (s *Store) CreateCampus( enabledValue = 1 } - return s.namespaceWrite(context.Background(), func(ctx context.Context, tx *sql.Tx) error { + return s.namespaceWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { if err := s.ensureCampusFQDNAvailableFrom(ctx, tx, 0, fqdn); err != nil { return err } @@ -300,10 +310,17 @@ func (s *Store) UpdateCampus( fqdn string, enabled bool, ) error { + return s.UpdateCampusContext(context.Background(), id, name, title, defaultLang, authorityMode, fqdn, enabled) +} + +func (s *Store) UpdateCampusContext(ctx context.Context, id int64, name, title, defaultLang, authorityMode, fqdn string, enabled bool) error { + if s.ReadOnly { + return ErrReadOnly + } if id <= 0 { return namespaceValidationError("campus id is required") } - ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + ctx, cancel := context.WithTimeout(ctx, 15*time.Second) defer cancel() var existingMode string if err := s.DB.QueryRowContext(ctx, ` @@ -412,6 +429,9 @@ func (s *Store) UpdateCampus( func (s *Store) DeleteCampus( id int64, ) error { + if s.sqlBackend == storeMySQL { + return ErrBackendFeatureUnavailable + } if s.ReadOnly { return ErrReadOnly } @@ -558,8 +578,7 @@ func (s *Store) ensureCampusFQDNAvailableFrom(ctx context.Context, q interface { WHEN d.domain = '' THEN CASE WHEN c.id = `+s.sqlParam(1)+` THEN `+s.sqlParam(2)+` ELSE c.fqdn END WHEN `+s.sqlHasDot("d.domain")+` THEN d.domain - ELSE d.domain || '.' || - CASE WHEN c.id = `+s.sqlParam(3)+` THEN `+s.sqlParam(4)+` ELSE c.fqdn END + ELSE `+s.sqlConcat("d.domain", "'.'", "CASE WHEN c.id = "+s.sqlParam(3)+" THEN "+s.sqlParam(4)+" ELSE c.fqdn END")+` END ) AS host FROM domains d diff --git a/internal/store/config.go b/internal/store/config.go index 982d02e..1f207b5 100644 --- a/internal/store/config.go +++ b/internal/store/config.go @@ -7,6 +7,9 @@ import ( ) func (s *Store) EnsureConfigTable() error { + if s.sqlBackend == storeMySQL { + return ErrBackendFeatureUnavailable + } if s.sqlBackend == storePostgreSQL { return s.ensurePostgreSQLNamespaces(context.Background()) } @@ -112,7 +115,7 @@ func (s *Store) GetConfigInDomainContext(ctx context.Context, domainUUID, key st var value string err := s.DB.QueryRowContext(ctx, ` SELECT value FROM config - WHERE domain_uuid = `+s.sqlParam(1)+` AND key = `+s.sqlParam(2)+` + WHERE domain_uuid = `+s.sqlParam(1)+` AND `+s.sqlConfigKey()+` = `+s.sqlParam(2)+` `, domainUUID, key).Scan(&value) if err == sql.ErrNoRows { return "", nil @@ -133,7 +136,18 @@ func (s *Store) SetConfigInDomain(domainUUID, key, value string) error { } func (s *Store) SetConfigInDomainContext(ctx context.Context, domainUUID, key, value string) error { - _, err := s.DB.ExecContext(ctx, ` + return s.setConfigWith(ctx, s.DB, domainUUID, key, value) +} + +func (s *Store) setConfigWith(ctx context.Context, q interface { + ExecContext(context.Context, string, ...any) (sql.Result, error) +}, domainUUID, key, value string) error { + if s.sqlBackend == storeMySQL { + now := time.Now().Unix() + _, err := q.ExecContext(ctx, "INSERT INTO config(domain_uuid,`key`,value,updated_at) VALUES(?,?,?,?) ON DUPLICATE KEY UPDATE value=?,updated_at=?", domainUUID, key, value, now, value, now) + return s.sqlError("write configuration", err) + } + _, err := q.ExecContext(ctx, ` INSERT INTO config (domain_uuid, key, value, updated_at) VALUES (`+s.sqlValues(4)+`) ON CONFLICT(domain_uuid, key) diff --git a/internal/store/domain_write.go b/internal/store/domain_write.go index 33e8546..9583521 100644 --- a/internal/store/domain_write.go +++ b/internal/store/domain_write.go @@ -12,6 +12,9 @@ import ( // transaction. A second connection must never observe a Domain without its // built-in groups, or retain Campus privileges after a Domain moves. func (s *Store) writeDomain(ctx context.Context, id int64, update bool, campus, name, title, host, placement, instance, fingerprint string, enabled bool) error { + if s.sqlBackend == storeMySQL && (strings.TrimSpace(placement) != "local" || instance != "" || fingerprint != "") { + return ErrBackendFeatureUnavailable + } if s.ReadOnly { return ErrReadOnly } @@ -33,6 +36,15 @@ func (s *Store) writeDomain(ctx context.Context, id int64, update bool, campus, return err } return s.namespaceWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { + if s.sqlBackend == storeMySQL { + var mode string + if err := tx.QueryRowContext(ctx, `SELECT authority_mode FROM campuses WHERE uuid=?`, campus).Scan(&mode); err != nil { + return err + } + if mode != "standalone" { + return ErrBackendFeatureUnavailable + } + } if err := s.ensureCampusExists(ctx, tx, campus); err != nil { return err } @@ -45,6 +57,15 @@ func (s *Store) writeDomain(ctx context.Context, id int64, update bool, campus, } key := uuid.NewString() if update { + if s.sqlBackend == storeMySQL { + var existingPlacement string + if err := tx.QueryRowContext(ctx, `SELECT placement FROM domains WHERE id=?`, id).Scan(&existingPlacement); err != nil { + return err + } + if existingPlacement != "local" { + return ErrBackendFeatureUnavailable + } + } var mode string if err := tx.QueryRowContext(ctx, `SELECT d.uuid,c.authority_mode FROM domains d JOIN campuses c ON c.uuid=d.campus_uuid WHERE d.id=`+s.sqlParam(1), id).Scan(&key, &mode); err != nil { return err @@ -52,6 +73,9 @@ func (s *Store) writeDomain(ctx context.Context, id int64, update bool, campus, if mode == "managed" { return namespaceValidationError("managed campus topology is read-only") } + if s.sqlBackend == storeMySQL && mode != "standalone" { + return ErrBackendFeatureUnavailable + } if placement == "remote" { var used bool if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM paths WHERE domain_uuid=`+s.sqlParam(1)+`)`, key).Scan(&used); err != nil { @@ -83,7 +107,7 @@ func (s *Store) writeDomain(ctx context.Context, id int64, update bool, campus, } } if !update && hasConfig { - _, err = tx.ExecContext(ctx, `INSERT INTO config(domain_uuid,key,value,updated_at) SELECT `+s.sqlParam(1)+`,'locale',CASE WHEN lower(default_lang) LIKE 'ja%' THEN 'ja' ELSE 'en' END,`+s.sqlParam(2)+` FROM campuses WHERE uuid=`+s.sqlParam(3)+` ON CONFLICT(domain_uuid,key) DO NOTHING`, key, now, campus) + _, err = tx.ExecContext(ctx, `INSERT INTO config(domain_uuid,`+s.sqlConfigKey()+`,value,updated_at) SELECT `+s.sqlParam(1)+`,'locale',CASE WHEN lower(default_lang) LIKE 'ja%' THEN 'ja' ELSE 'en' END,`+s.sqlParam(2)+` FROM campuses WHERE uuid=`+s.sqlParam(3)+s.sqlConflictDoNothing("config", "key", "domain_uuid,key"), key, now, campus) if err != nil { return err } diff --git a/internal/store/domains.go b/internal/store/domains.go index d00cd69..03b097c 100644 --- a/internal/store/domains.go +++ b/internal/store/domains.go @@ -25,6 +25,9 @@ type Domain struct { } func (s *Store) EnsureDomainsSchema() error { + if s.sqlBackend == storeMySQL { + return ErrBackendFeatureUnavailable + } if s.sqlBackend == storePostgreSQL { if err := s.ensurePostgreSQLNamespaces(context.Background()); err != nil { return err @@ -193,7 +196,7 @@ func (s *Store) GetDomainByHostContext(ctx context.Context, host string) (*Domai CASE WHEN d.domain = '' THEN c.fqdn WHEN `+s.sqlHasDot("d.domain")+` THEN d.domain - ELSE d.domain || '.' || c.fqdn + ELSE `+s.sqlConcat("d.domain", "'.'", "c.fqdn")+` END ) = `+s.sqlParam(1)+` ORDER BY d.id @@ -235,7 +238,7 @@ func (s *Store) GetDomainEffectiveHostContext(ctx context.Context, domainUUID st CASE WHEN d.domain = '' THEN c.fqdn WHEN `+s.sqlHasDot("d.domain")+` THEN d.domain - ELSE d.domain || '.' || c.fqdn + ELSE `+s.sqlConcat("d.domain", "'.'", "c.fqdn")+` END ) FROM domains d @@ -342,6 +345,9 @@ func (s *Store) CountDomainsContext(ctx context.Context) (int, error) { func (s *Store) DeleteDomain( id int64, ) error { + if s.sqlBackend == storeMySQL { + return ErrBackendFeatureUnavailable + } if s.ReadOnly { return ErrReadOnly } @@ -623,7 +629,7 @@ func (s *Store) ensureDomainUnique( CASE WHEN d.domain = '' THEN c.fqdn WHEN `+s.sqlHasDot("d.domain")+` THEN d.domain - ELSE d.domain || '.' || c.fqdn + ELSE `+s.sqlConcat("d.domain", "'.'", "c.fqdn")+` END ) = `+s.sqlParam(3)+` ) diff --git a/internal/store/groups.go b/internal/store/groups.go index 580a6e8..f158a45 100644 --- a/internal/store/groups.go +++ b/internal/store/groups.go @@ -59,6 +59,9 @@ func (s *Store) EnsureBuiltinAdminGroupsContext(ctx context.Context) error { // The caller holds the namespace writer lock, including when creating a Domain. func (s *Store) ensureBuiltinAdminGroupsContext(ctx context.Context, tx *sql.Tx) error { + if s.sqlBackend == storeMySQL { + return s.ensureMySQLBuiltinGroups(ctx, tx) + } now := time.Now().UnixMilli() rows, err := tx.QueryContext(ctx, `SELECT uuid FROM domains ORDER BY uuid`) if err != nil { @@ -86,14 +89,14 @@ func (s *Store) ensureBuiltinAdminGroupsContext(ctx context.Context, tx *sql.Tx) if key == "campus_admin" { inherit = 1 } - _, err = tx.ExecContext(ctx, fmt.Sprintf(`INSERT INTO groups(uuid,domain_uuid,name,display_name,description,visibility,state,builtin_key,inherit_members,created_at_ms,updated_at_ms) VALUES(%s,%s,%s,%s,%s,'members','active',%s,%s,%s,%s) ON CONFLICT(domain_uuid,name) DO UPDATE SET builtin_key=excluded.builtin_key`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3), s.sqlParam(4), s.sqlParam(5), s.sqlParam(6), s.sqlParam(7), s.sqlParam(8), s.sqlParam(9)), uuid.NewString(), domainUUID, key, strings.ReplaceAll(key, "_", " "), "Built-in administrative group", key, inherit, now, now) + _, err = tx.ExecContext(ctx, fmt.Sprintf(`INSERT INTO `+s.sqlGroupTable()+`(uuid,domain_uuid,name,display_name,description,visibility,state,builtin_key,inherit_members,created_at_ms,updated_at_ms) VALUES(%s,%s,%s,%s,%s,'members','active',%s,%s,%s,%s) ON CONFLICT(domain_uuid,name) DO UPDATE SET builtin_key=excluded.builtin_key`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3), s.sqlParam(4), s.sqlParam(5), s.sqlParam(6), s.sqlParam(7), s.sqlParam(8), s.sqlParam(9)), uuid.NewString(), domainUUID, key, strings.ReplaceAll(key, "_", " "), "Built-in administrative group", key, inherit, now, now) if err != nil { return err } } _, err = tx.ExecContext(ctx, fmt.Sprintf(`INSERT INTO group_members (group_uuid,membership_uuid,member_role,source,created_at_ms) - SELECT g.uuid,m.uuid,'owner','migration',%s FROM groups g + SELECT g.uuid,m.uuid,'owner','migration',%s FROM `+s.sqlGroupTable()+` g JOIN domain_memberships m ON m.domain_uuid=g.domain_uuid JOIN auth_role_bindings b ON b.membership_uuid=m.uuid JOIN auth_roles r ON r.uuid=b.role_uuid AND r.domain_uuid=m.domain_uuid @@ -124,7 +127,7 @@ func (s *Store) IsBuiltinGroupAdminContext(ctx context.Context, domainUUID, prin return false, nil } var allowed bool - err := s.DB.QueryRowContext(ctx, fmt.Sprintf(`SELECT EXISTS(SELECT 1 FROM groups g JOIN domains d ON d.uuid=g.domain_uuid AND d.enabled=1 JOIN group_members gm ON gm.group_uuid=g.uuid JOIN domain_memberships m ON m.uuid=gm.membership_uuid AND m.domain_uuid=g.domain_uuid JOIN principals p ON p.uuid=m.principal_uuid WHERE g.domain_uuid=%s AND g.builtin_key=%s AND g.state='active' AND m.principal_uuid=%s AND m.state='active' AND p.state='active' AND gm.member_role IN ('owner','manager'))`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), domainUUID, key, principalUUID).Scan(&allowed) + err := s.DB.QueryRowContext(ctx, fmt.Sprintf(`SELECT EXISTS(SELECT 1 FROM `+s.sqlGroupTable()+` g JOIN domains d ON d.uuid=g.domain_uuid AND d.enabled=1 JOIN group_members gm ON gm.group_uuid=g.uuid JOIN domain_memberships m ON m.uuid=gm.membership_uuid AND m.domain_uuid=g.domain_uuid JOIN principals p ON p.uuid=m.principal_uuid WHERE g.domain_uuid=%s AND g.builtin_key=%s AND g.state='active' AND m.principal_uuid=%s AND m.state='active' AND p.state='active' AND gm.member_role IN ('owner','manager'))`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), domainUUID, key, principalUUID).Scan(&allowed) return err == nil && allowed, s.sqlError("builtin group authorization", err) } @@ -138,7 +141,7 @@ func (s *Store) IsCampusAdminContext(ctx context.Context, campusUUID, principalU return false, nil } var allowed bool - err := s.DB.QueryRowContext(ctx, fmt.Sprintf(`SELECT EXISTS(SELECT 1 FROM groups g JOIN domains d ON d.uuid=g.domain_uuid AND d.enabled=1 JOIN group_members gm ON gm.group_uuid=g.uuid JOIN domain_memberships m ON m.uuid=gm.membership_uuid AND m.domain_uuid=g.domain_uuid JOIN principals p ON p.uuid=m.principal_uuid WHERE d.campus_uuid=%s AND g.builtin_key='campus_admin' AND g.state='active' AND m.principal_uuid=%s AND m.state='active' AND p.state='active' AND gm.member_role IN ('owner','manager'))`, s.sqlParam(1), s.sqlParam(2)), campusUUID, principalUUID).Scan(&allowed) + err := s.DB.QueryRowContext(ctx, fmt.Sprintf(`SELECT EXISTS(SELECT 1 FROM `+s.sqlGroupTable()+` g JOIN domains d ON d.uuid=g.domain_uuid AND d.enabled=1 JOIN group_members gm ON gm.group_uuid=g.uuid JOIN domain_memberships m ON m.uuid=gm.membership_uuid AND m.domain_uuid=g.domain_uuid JOIN principals p ON p.uuid=m.principal_uuid WHERE d.campus_uuid=%s AND g.builtin_key='campus_admin' AND g.state='active' AND m.principal_uuid=%s AND m.state='active' AND p.state='active' AND gm.member_role IN ('owner','manager'))`, s.sqlParam(1), s.sqlParam(2)), campusUUID, principalUUID).Scan(&allowed) return err == nil && allowed, s.sqlError("campus authorization", err) } @@ -152,7 +155,13 @@ func (s *Store) SetCampusAdminInheritanceContext(ctx context.Context, groupUUID value = 1 } return s.groupWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { - result, err := tx.ExecContext(ctx, fmt.Sprintf(`UPDATE groups SET inherit_members=%s,updated_at_ms=%s WHERE uuid=%s AND builtin_key='campus_admin'`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), value, time.Now().UnixMilli(), groupUUID) + if s.sqlBackend == storeMySQL { + var found string + if err := tx.QueryRowContext(ctx, "SELECT uuid FROM `groups` WHERE uuid=? AND builtin_key='campus_admin'", groupUUID).Scan(&found); err != nil { + return err + } + } + result, err := tx.ExecContext(ctx, fmt.Sprintf(`UPDATE `+s.sqlGroupTable()+` SET inherit_members=%s,updated_at_ms=%s WHERE uuid=%s AND builtin_key='campus_admin'`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), value, time.Now().UnixMilli(), groupUUID) if err != nil { return err } @@ -160,7 +169,7 @@ func (s *Store) SetCampusAdminInheritanceContext(ctx context.Context, groupUUID if err != nil { return err } - if changed != 1 { + if changed != 1 && s.sqlBackend != storeMySQL { return namespaceValidationError("campus_admin group not found") } return s.projectCampusAdminMembershipsContext(ctx, tx) @@ -189,7 +198,7 @@ func (s *Store) CreateGroupContext(ctx context.Context, domainUUID, ownerPrincip if err := tx.QueryRowContext(ctx, fmt.Sprintf(`SELECT m.uuid FROM domain_memberships m JOIN principals p ON p.uuid=m.principal_uuid AND p.state='active' WHERE m.domain_uuid=%s AND m.principal_uuid=%s AND m.state='active'`, s.sqlParam(1), s.sqlParam(2)), domainUUID, ownerPrincipalUUID).Scan(&membershipUUID); err != nil { return err } - if _, err := tx.ExecContext(ctx, `INSERT INTO groups(uuid,domain_uuid,name,display_name,description,visibility,state,created_at_ms,updated_at_ms) VALUES(`+s.sqlValues(9)+`)`, group.UUID, domainUUID, group.Name, group.DisplayName, group.Description, group.Visibility, group.State, now, now); err != nil { + if _, err := tx.ExecContext(ctx, `INSERT INTO `+s.sqlGroupTable()+`(uuid,domain_uuid,name,display_name,description,visibility,state,created_at_ms,updated_at_ms) VALUES(`+s.sqlValues(9)+`)`, group.UUID, domainUUID, group.Name, group.DisplayName, group.Description, group.Visibility, group.State, now, now); err != nil { return err } if _, err := tx.ExecContext(ctx, fmt.Sprintf(`INSERT INTO group_members(group_uuid,membership_uuid,member_role,source,created_at_ms) VALUES(%s,%s,'owner','local',%s)`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), group.UUID, membershipUUID, now); err != nil { @@ -211,7 +220,7 @@ func (s *Store) GroupByName(domainUUID, name string) (*Group, error) { func (s *Store) GroupByNameContext(ctx context.Context, domainUUID, name string) (*Group, error) { var group Group - err := s.DB.QueryRowContext(ctx, fmt.Sprintf(`SELECT uuid,domain_uuid,name,display_name,description,visibility,state,builtin_key,inherit_members,created_at_ms,updated_at_ms FROM groups WHERE domain_uuid=%s AND name=%s AND state!='archived'`, s.sqlParam(1), s.sqlParam(2)), domainUUID, strings.ToLower(strings.TrimSpace(name))).Scan(&group.UUID, &group.DomainUUID, &group.Name, &group.DisplayName, &group.Description, &group.Visibility, &group.State, &group.BuiltinKey, &group.InheritMembers, &group.CreatedAtMS, &group.UpdatedAtMS) + err := s.DB.QueryRowContext(ctx, fmt.Sprintf(`SELECT uuid,domain_uuid,name,display_name,description,visibility,state,builtin_key,inherit_members,created_at_ms,updated_at_ms FROM `+s.sqlGroupTable()+` WHERE domain_uuid=%s AND name=%s AND state!='archived'`, s.sqlParam(1), s.sqlParam(2)), domainUUID, strings.ToLower(strings.TrimSpace(name))).Scan(&group.UUID, &group.DomainUUID, &group.Name, &group.DisplayName, &group.Description, &group.Visibility, &group.State, &group.BuiltinKey, &group.InheritMembers, &group.CreatedAtMS, &group.UpdatedAtMS) return &group, s.sqlError("read group by name", err) } @@ -221,7 +230,7 @@ func (s *Store) GroupByUUID(domainUUID, groupUUID string) (*Group, error) { func (s *Store) GroupByUUIDContext(ctx context.Context, domainUUID, groupUUID string) (*Group, error) { var group Group - err := s.DB.QueryRowContext(ctx, fmt.Sprintf(`SELECT uuid,domain_uuid,name,display_name,description,visibility,state,builtin_key,inherit_members,created_at_ms,updated_at_ms FROM groups WHERE domain_uuid=%s AND uuid=%s`, s.sqlParam(1), s.sqlParam(2)), domainUUID, groupUUID).Scan(&group.UUID, &group.DomainUUID, &group.Name, &group.DisplayName, &group.Description, &group.Visibility, &group.State, &group.BuiltinKey, &group.InheritMembers, &group.CreatedAtMS, &group.UpdatedAtMS) + err := s.DB.QueryRowContext(ctx, fmt.Sprintf(`SELECT uuid,domain_uuid,name,display_name,description,visibility,state,builtin_key,inherit_members,created_at_ms,updated_at_ms FROM `+s.sqlGroupTable()+` WHERE domain_uuid=%s AND uuid=%s`, s.sqlParam(1), s.sqlParam(2)), domainUUID, groupUUID).Scan(&group.UUID, &group.DomainUUID, &group.Name, &group.DisplayName, &group.Description, &group.Visibility, &group.State, &group.BuiltinKey, &group.InheritMembers, &group.CreatedAtMS, &group.UpdatedAtMS) return &group, s.sqlError("read group by UUID", err) } @@ -233,7 +242,7 @@ func (s *Store) ListGroupsContext(ctx context.Context, domainUUID, principalUUID // EXISTS avoids duplicate rows and PostgreSQL's DISTINCT/ORDER BY mismatch. // A nonempty global Principal UUID alone is not Domain membership. rows, err := s.DB.QueryContext(ctx, fmt.Sprintf(`SELECT g.uuid,g.domain_uuid,g.name,g.display_name,g.description,g.visibility,g.state,g.builtin_key,g.inherit_members,g.created_at_ms,g.updated_at_ms - FROM groups g WHERE g.domain_uuid=%s AND g.state!='archived' + FROM `+s.sqlGroupTable()+` g WHERE g.domain_uuid=%s AND g.state!='archived' AND (g.visibility='public' OR EXISTS( SELECT 1 FROM domain_memberships m JOIN principals p ON p.uuid=m.principal_uuid WHERE m.domain_uuid=g.domain_uuid AND m.principal_uuid=%s AND m.state='active' @@ -257,13 +266,13 @@ func (s *Store) ListGroupsContext(ctx context.Context, domainUUID, principalUUID func (s *Store) GroupMemberRole(groupUUID, principalUUID string) string { var role string - _ = s.DB.QueryRow(fmt.Sprintf(`SELECT gm.member_role FROM group_members gm JOIN groups g ON g.uuid=gm.group_uuid JOIN domain_memberships m ON m.uuid=gm.membership_uuid AND m.domain_uuid=g.domain_uuid WHERE gm.group_uuid=%s AND m.principal_uuid=%s AND m.state='active'`, s.sqlParam(1), s.sqlParam(2)), groupUUID, principalUUID).Scan(&role) + _ = s.DB.QueryRow(fmt.Sprintf(`SELECT gm.member_role FROM group_members gm JOIN `+s.sqlGroupTable()+` g ON g.uuid=gm.group_uuid JOIN domain_memberships m ON m.uuid=gm.membership_uuid AND m.domain_uuid=g.domain_uuid WHERE gm.group_uuid=%s AND m.principal_uuid=%s AND m.state='active'`, s.sqlParam(1), s.sqlParam(2)), groupUUID, principalUUID).Scan(&role) return role } func (s *Store) GroupMemberRoleByMembership(groupUUID, membershipUUID string) string { var role string - _ = s.DB.QueryRow(fmt.Sprintf(`SELECT gm.member_role FROM group_members gm JOIN groups g ON g.uuid=gm.group_uuid JOIN domain_memberships m ON m.uuid=gm.membership_uuid AND m.domain_uuid=g.domain_uuid WHERE gm.group_uuid=%s AND gm.membership_uuid=%s`, s.sqlParam(1), s.sqlParam(2)), groupUUID, membershipUUID).Scan(&role) + _ = s.DB.QueryRow(fmt.Sprintf(`SELECT gm.member_role FROM group_members gm JOIN `+s.sqlGroupTable()+` g ON g.uuid=gm.group_uuid JOIN domain_memberships m ON m.uuid=gm.membership_uuid AND m.domain_uuid=g.domain_uuid WHERE gm.group_uuid=%s AND gm.membership_uuid=%s`, s.sqlParam(1), s.sqlParam(2)), groupUUID, membershipUUID).Scan(&role) return role } @@ -272,7 +281,7 @@ func (s *Store) ListGroupMembers(groupUUID string) ([]GroupMember, error) { } func (s *Store) ListGroupMembersContext(ctx context.Context, groupUUID string) ([]GroupMember, error) { - rows, err := s.DB.QueryContext(ctx, `SELECT m.uuid,p.uuid,COALESCE((SELECT subject FROM principal_identities i WHERE i.principal_uuid=p.uuid AND i.provider_type='password' ORDER BY i.subject,i.uuid LIMIT 1),p.uuid),p.display_name,gm.member_role,gm.source FROM group_members gm JOIN groups g ON g.uuid=gm.group_uuid JOIN domain_memberships m ON m.uuid=gm.membership_uuid AND m.domain_uuid=g.domain_uuid JOIN principals p ON p.uuid=m.principal_uuid WHERE gm.group_uuid=`+s.sqlParam(1)+` ORDER BY CASE gm.member_role WHEN 'owner' THEN 0 WHEN 'manager' THEN 1 ELSE 2 END,lower(p.display_name),m.uuid`, groupUUID) + rows, err := s.DB.QueryContext(ctx, `SELECT m.uuid,p.uuid,COALESCE((SELECT subject FROM principal_identities i WHERE i.principal_uuid=p.uuid AND i.provider_type='password' ORDER BY i.subject,i.uuid LIMIT 1),p.uuid),p.display_name,gm.member_role,gm.source FROM group_members gm JOIN `+s.sqlGroupTable()+` g ON g.uuid=gm.group_uuid JOIN domain_memberships m ON m.uuid=gm.membership_uuid AND m.domain_uuid=g.domain_uuid JOIN principals p ON p.uuid=m.principal_uuid WHERE gm.group_uuid=`+s.sqlParam(1)+` ORDER BY CASE gm.member_role WHEN 'owner' THEN 0 WHEN 'manager' THEN 1 ELSE 2 END,lower(p.display_name),m.uuid`, groupUUID) if err != nil { return nil, s.sqlError("list group members", err) } @@ -298,24 +307,30 @@ func (s *Store) AddGroupMemberByUsernameContext(ctx context.Context, domainUUID, } return s.groupWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { // Serialize before the identity lookup as well as the ownership check. - if _, err := tx.ExecContext(ctx, fmt.Sprintf(`UPDATE groups SET updated_at_ms=updated_at_ms WHERE uuid=%s AND domain_uuid=%s`, s.sqlParam(1), s.sqlParam(2)), groupUUID, domainUUID); err != nil { + if _, err := tx.ExecContext(ctx, fmt.Sprintf(`UPDATE `+s.sqlGroupTable()+` SET updated_at_ms=updated_at_ms WHERE uuid=%s AND domain_uuid=%s`, s.sqlParam(1), s.sqlParam(2)), groupUUID, domainUUID); err != nil { return err } var membershipUUID, builtinKey string - err := tx.QueryRowContext(ctx, fmt.Sprintf(`SELECT m.uuid,g.builtin_key FROM domain_memberships m JOIN principal_identities i ON i.principal_uuid=m.principal_uuid AND i.provider_type='password' JOIN groups g ON g.uuid=%s AND g.domain_uuid=m.domain_uuid WHERE m.domain_uuid=%s AND i.subject=%s AND m.state='active'`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), groupUUID, domainUUID, strings.ToLower(strings.TrimSpace(username))).Scan(&membershipUUID, &builtinKey) + err := tx.QueryRowContext(ctx, fmt.Sprintf(`SELECT m.uuid,g.builtin_key FROM domain_memberships m JOIN principal_identities i ON i.principal_uuid=m.principal_uuid AND i.provider_type='password' JOIN `+s.sqlGroupTable()+` g ON g.uuid=%s AND g.domain_uuid=m.domain_uuid WHERE m.domain_uuid=%s AND i.subject=%s AND m.state='active'`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), groupUUID, domainUUID, strings.ToLower(strings.TrimSpace(username))).Scan(&membershipUUID, &builtinKey) if err != nil { return err } // Ordinary add/update is not an ownership-transfer API. Keep this check in // the write itself, including when another request just promoted the member. - result, err := tx.ExecContext(ctx, fmt.Sprintf(`INSERT INTO group_members(group_uuid,membership_uuid,member_role,source,created_at_ms) VALUES(%s,%s,%s,'local',%s) ON CONFLICT(group_uuid,membership_uuid) DO UPDATE SET member_role=excluded.member_role,source=excluded.source WHERE group_members.member_role!='owner' OR excluded.member_role='owner'`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3), s.sqlParam(4)), groupUUID, membershipUUID, role, time.Now().UnixMilli()) - if err != nil { - return err - } - if count, err := result.RowsAffected(); err != nil { - return err - } else if count == 0 { - return namespaceValidationError("owner role cannot be downgraded by a member update") + if s.sqlBackend == storeMySQL { + if err := mysqlAddGroupMember(ctx, tx, groupUUID, membershipUUID, role); err != nil { + return err + } + } else { + result, err := tx.ExecContext(ctx, fmt.Sprintf(`INSERT INTO group_members(group_uuid,membership_uuid,member_role,source,created_at_ms) VALUES(%s,%s,%s,'local',%s) ON CONFLICT(group_uuid,membership_uuid) DO UPDATE SET member_role=excluded.member_role,source=excluded.source WHERE group_members.member_role!='owner' OR excluded.member_role='owner'`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3), s.sqlParam(4)), groupUUID, membershipUUID, role, time.Now().UnixMilli()) + if err != nil { + return err + } + if count, err := result.RowsAffected(); err != nil { + return err + } else if count == 0 { + return namespaceValidationError("owner role cannot be downgraded by a member update") + } } if builtinKey == "campus_admin" { if _, err = tx.ExecContext(ctx, fmt.Sprintf(`DELETE FROM campus_admin_grants WHERE group_uuid=%s AND membership_uuid=%s AND substr(source,1,21)!='campus_admin_inherit:'`, s.sqlParam(1), s.sqlParam(2)), groupUUID, membershipUUID); err != nil { @@ -346,11 +361,11 @@ func (s *Store) RemoveGroupMemberWithAuthority(groupUUID, membershipUUID string, func (s *Store) RemoveGroupMemberWithAuthorityContext(ctx context.Context, groupUUID, membershipUUID string, ownerAuthority bool) error { return s.groupWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { - if _, err := tx.ExecContext(ctx, `UPDATE groups SET updated_at_ms=updated_at_ms WHERE uuid=`+s.sqlParam(1), groupUUID); err != nil { + if _, err := tx.ExecContext(ctx, `UPDATE `+s.sqlGroupTable()+` SET updated_at_ms=updated_at_ms WHERE uuid=`+s.sqlParam(1), groupUUID); err != nil { return err } var builtinKey string - if err := tx.QueryRowContext(ctx, `SELECT builtin_key FROM groups WHERE uuid=`+s.sqlParam(1), groupUUID).Scan(&builtinKey); err != nil { + if err := tx.QueryRowContext(ctx, `SELECT builtin_key FROM `+s.sqlGroupTable()+` WHERE uuid=`+s.sqlParam(1), groupUUID).Scan(&builtinKey); err != nil { return err } if builtinKey == "campus_admin" { @@ -366,7 +381,7 @@ func (s *Store) RemoveGroupMemberWithAuthorityContext(ctx context.Context, group AND mine.membership_uuid=gr.membership_uuid AND mine.member_role='owner' AND substr(mine.source,1,21)!='campus_admin_inherit:') OR EXISTS(SELECT 1 FROM campus_admin_grants other - JOIN groups og ON og.uuid=other.group_uuid + JOIN `+s.sqlGroupTable()+` og ON og.uuid=other.group_uuid JOIN domain_memberships om ON om.uuid=other.membership_uuid AND om.domain_uuid=og.domain_uuid WHERE other.group_uuid=gr.group_uuid AND other.membership_uuid!=gr.membership_uuid AND other.member_role='owner' @@ -384,10 +399,13 @@ func (s *Store) RemoveGroupMemberWithAuthorityContext(ctx context.Context, group } // A single SQLite write serializes the check and deletion. A manager cannot // delete a member concurrently promoted to owner/manager by another request. + if s.sqlBackend == storeMySQL { + return mysqlRemoveGroupMember(ctx, tx, groupUUID, membershipUUID, ownerAuthority) + } result, err := tx.ExecContext(ctx, fmt.Sprintf(`DELETE FROM group_members WHERE group_uuid=%s AND membership_uuid=%s AND (%s OR member_role='member') AND (member_role!='owner' OR EXISTS ( - SELECT 1 FROM group_members other JOIN groups og ON og.uuid=other.group_uuid + SELECT 1 FROM group_members other JOIN `+s.sqlGroupTable()+` og ON og.uuid=other.group_uuid JOIN domain_memberships om ON om.uuid=other.membership_uuid AND om.domain_uuid=og.domain_uuid WHERE other.group_uuid=%s AND other.membership_uuid!=%s AND other.member_role='owner' ))`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3), s.sqlParam(4), s.sqlParam(5)), groupUUID, membershipUUID, ownerAuthority, groupUUID, membershipUUID) @@ -417,8 +435,16 @@ func (s *Store) SetGroupPermissionContext(ctx context.Context, groupUUID, scopeP scopePath = "/" } return s.groupWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { + if s.sqlBackend == storeMySQL { + var found string + if err := tx.QueryRowContext(ctx, "SELECT uuid FROM `groups` WHERE uuid=?", groupUUID).Scan(&found); err != nil { + return err + } + _, err := tx.ExecContext(ctx, `INSERT INTO group_permissions(uuid,group_uuid,scope_path,permission,created_at_ms) VALUES(?,?,?,?,?) ON DUPLICATE KEY UPDATE permission=?`, uuid.NewString(), groupUUID, scopePath, permission, time.Now().UnixMilli(), permission) + return err + } result, err := tx.ExecContext(ctx, fmt.Sprintf(`INSERT INTO group_permissions(uuid,group_uuid,scope_path,permission,created_at_ms) - SELECT %s,uuid,%s,%s,%s FROM groups WHERE uuid=%s + SELECT %s,uuid,%s,%s,%s FROM `+s.sqlGroupTable()+` WHERE uuid=%s ON CONFLICT(group_uuid,scope_path) DO UPDATE SET permission=excluded.permission`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3), s.sqlParam(4), s.sqlParam(5)), uuid.NewString(), scopePath, permission, time.Now().UnixMilli(), groupUUID) if err != nil { return err @@ -464,7 +490,7 @@ type groupPermissionQueryer interface { } func (s *Store) groupPermissionAllowsContext(ctx context.Context, q groupPermissionQueryer, domainUUID, principalUUID, capability, targetPath string) (bool, error) { - rows, err := q.QueryContext(ctx, fmt.Sprintf(`SELECT gp.scope_path,gp.permission FROM group_permissions gp JOIN groups g ON g.uuid=gp.group_uuid AND g.domain_uuid=%s AND g.state='active' JOIN group_members gm ON gm.group_uuid=g.uuid JOIN domain_memberships m ON m.uuid=gm.membership_uuid AND m.domain_uuid=g.domain_uuid AND m.principal_uuid=%s AND m.state='active' JOIN principals p ON p.uuid=m.principal_uuid AND (p.state='active' OR (p.state='readonly' AND %s='read'))`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), domainUUID, principalUUID, capability) + rows, err := q.QueryContext(ctx, fmt.Sprintf(`SELECT gp.scope_path,gp.permission FROM group_permissions gp JOIN `+s.sqlGroupTable()+` g ON g.uuid=gp.group_uuid AND g.domain_uuid=%s AND g.state='active' JOIN group_members gm ON gm.group_uuid=g.uuid JOIN domain_memberships m ON m.uuid=gm.membership_uuid AND m.domain_uuid=g.domain_uuid AND m.principal_uuid=%s AND m.state='active' JOIN principals p ON p.uuid=m.principal_uuid AND (p.state='active' OR (p.state='readonly' AND %s='read'))`, s.sqlParam(1), s.sqlParam(2), s.sqlParam(3)), domainUUID, principalUUID, capability) if err != nil { return false, s.sqlError("group permission evaluation", err) } diff --git a/internal/store/groups_backend_test.go b/internal/store/groups_backend_test.go index 16d7e39..7c7cf32 100644 --- a/internal/store/groups_backend_test.go +++ b/internal/store/groups_backend_test.go @@ -18,7 +18,12 @@ type adminBackendFixture struct { func newAdminBackendFixture(t *testing.T, backend storeSQLBackend) *adminBackendFixture { t.Helper() - s := testNamespaceStore(t, backend) + s := testNamespaceCoreStore(t, backend) + if backend == storeMySQL { + if err := s.ensureMySQLAuthFoundation(context.Background()); err != nil { + t.Fatal(err) + } + } if backend == storePostgreSQL { if err := s.ensurePostgreSQLAuthFoundation(context.Background()); err != nil { t.Fatal(err) @@ -64,6 +69,10 @@ func newAdminBackendFixture(t *testing.T, backend storeSQLBackend) *adminBackend // Test fixture SQL is owned and uses explicit format slots; production queries // do not run through a SQL string rewriting layer. func (f *adminBackendFixture) query(query string, n int) string { + if f.s.sqlBackend == storeMySQL { + // Only owned fixture SQL. Production statements compose identifiers. + query = strings.ReplaceAll(query, " groups ", " `groups` ") + } p := make([]any, n) for i := range p { p[i] = f.s.sqlParam(i + 1) @@ -81,9 +90,15 @@ func (f *adminBackendFixture) row(query string, args ...any) *sql.Row { } func (f *adminBackendFixture) local(domain, user string) string { f.t.Helper() - f.exec(`INSERT INTO principals(uuid,display_name,created_at_ms,updated_at_ms) VALUES(%s,%s,1,1) ON CONFLICT DO NOTHING`, user, user) - f.exec(`INSERT INTO principal_identities(uuid,principal_uuid,provider_type,subject,created_at_ms) VALUES(%s,%s,'password',%s,1) ON CONFLICT DO NOTHING`, user, user, user) - f.exec(`INSERT INTO domain_memberships(uuid,domain_uuid,principal_uuid,created_at_ms) VALUES(%s,%s,%s,1) ON CONFLICT DO NOTHING`, domain+":"+user, f.domains[domain], user) + if f.s.sqlBackend == storeMySQL { + f.exec(`INSERT INTO principals(uuid,display_name,created_at_ms,updated_at_ms) VALUES(%s,%s,1,1) ON DUPLICATE KEY UPDATE uuid=principals.uuid`, user, user) + f.exec(`INSERT INTO principal_identities(uuid,principal_uuid,provider_type,subject,created_at_ms) VALUES(%s,%s,'password',%s,1) ON DUPLICATE KEY UPDATE uuid=principal_identities.uuid`, user, user, user) + f.exec(`INSERT INTO domain_memberships(uuid,domain_uuid,principal_uuid,created_at_ms) VALUES(%s,%s,%s,1) ON DUPLICATE KEY UPDATE uuid=domain_memberships.uuid`, domain+":"+user, f.domains[domain], user) + } else { + f.exec(`INSERT INTO principals(uuid,display_name,created_at_ms,updated_at_ms) VALUES(%s,%s,1,1) ON CONFLICT DO NOTHING`, user, user) + f.exec(`INSERT INTO principal_identities(uuid,principal_uuid,provider_type,subject,created_at_ms) VALUES(%s,%s,'password',%s,1) ON CONFLICT DO NOTHING`, user, user, user) + f.exec(`INSERT INTO domain_memberships(uuid,domain_uuid,principal_uuid,created_at_ms) VALUES(%s,%s,%s,1) ON CONFLICT DO NOTHING`, domain+":"+user, f.domains[domain], user) + } var id string if err := f.row(`SELECT uuid FROM domain_memberships WHERE domain_uuid=%s AND principal_uuid=%s`, f.domains[domain], user).Scan(&id); err != nil { f.t.Fatal(err) @@ -111,7 +126,7 @@ func (f *adminBackendFixture) membership(domain, user string, want bool) { } } func forAdminBackends(t *testing.T, fn func(*testing.T, *adminBackendFixture)) { - for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL} { + for _, b := range []storeSQLBackend{storeSQLite, storePostgreSQL, storeMySQL} { t.Run(fmt.Sprint(b), func(t *testing.T) { fn(t, newAdminBackendFixture(t, b)) }) } } diff --git a/internal/store/groups_general_backend_test.go b/internal/store/groups_general_backend_test.go index f52734e..8b5e523 100644 --- a/internal/store/groups_general_backend_test.go +++ b/internal/store/groups_general_backend_test.go @@ -265,6 +265,13 @@ func TestGeneralGroupBackendCancellationAndErrorBoundary(t *testing.T) { t.Fatalf("unsafe PostgreSQL error: %v", err) } } + if f.s.sqlBackend == storeMySQL { + f.exec(`ALTER TABLE groups ADD CONSTRAINT synthetic_title_check CHECK(display_name!='private-test-title')`) + _, err := f.s.CreateGroup(f.domains["a"], "alice", "rejected", "private-test-title", "", "public") + if err == nil || strings.Contains(err.Error(), "private-test-title") { + t.Fatalf("unsafe MySQL error: %v", err) + } + } }) } diff --git a/internal/store/groups_inheritance.go b/internal/store/groups_inheritance.go index 54e918f..062e8a3 100644 --- a/internal/store/groups_inheritance.go +++ b/internal/store/groups_inheritance.go @@ -39,7 +39,7 @@ func (s *Store) ensureCampusAdminInheritanceSchema() error { if _, err = tx.Exec(`INSERT OR IGNORE INTO campus_admin_grants (group_uuid,membership_uuid,source,member_role,created_at_ms) SELECT gm.group_uuid,gm.membership_uuid,gm.source,gm.member_role,gm.created_at_ms - FROM group_members gm JOIN groups g ON g.uuid=gm.group_uuid + FROM group_members gm JOIN ` + s.sqlGroupTable() + ` g ON g.uuid=gm.group_uuid WHERE g.builtin_key='campus_admin' AND substr(gm.source,1,21)!='campus_admin_inherit:' AND NOT EXISTS(SELECT 1 FROM campus_admin_migrations WHERE key='direct-grants-v1')`); err != nil { return err @@ -54,8 +54,8 @@ func (s *Store) ensureCampusAdminInheritanceSchema() error { // Domain administrator binding. A later explicit group removal must not be // undone by restarting the server or creating another Domain. func (s *Store) seedCampusAdminRoleGrantsContext(ctx context.Context, tx *sql.Tx, now int64) error { - const candidates = `SELECT DISTINCT g.uuid AS group_uuid,m.uuid AS membership_uuid - FROM groups g JOIN domain_memberships m ON m.domain_uuid=g.domain_uuid + candidates := `SELECT DISTINCT g.uuid AS group_uuid,m.uuid AS membership_uuid + FROM ` + s.sqlGroupTable() + ` g JOIN domain_memberships m ON m.domain_uuid=g.domain_uuid JOIN auth_role_bindings b ON b.membership_uuid=m.uuid JOIN auth_roles r ON r.uuid=b.role_uuid AND r.domain_uuid=m.domain_uuid JOIN auth_capability_grants c ON c.role_uuid=r.uuid @@ -66,11 +66,11 @@ func (s *Store) seedCampusAdminRoleGrantsContext(ctx context.Context, tx *sql.Tx (group_uuid,membership_uuid,source,member_role,created_at_ms) SELECT group_uuid,membership_uuid,'migration','owner',%s FROM (`+candidates+`) AS candidates WHERE NOT EXISTS(SELECT 1 FROM campus_admin_migrations - WHERE key='role:'||group_uuid||':'||membership_uuid) ON CONFLICT(group_uuid,membership_uuid,source) DO NOTHING`, s.sqlParam(1)), now); err != nil { + WHERE `+s.sqlConfigKey()+`=`+s.sqlConcat("'role:'", "group_uuid", "':'", "membership_uuid")+`)`+s.sqlConflictDoNothing("campus_admin_grants", "group_uuid", "group_uuid,membership_uuid,source"), s.sqlParam(1)), now); err != nil { return err } - _, err := tx.ExecContext(ctx, `INSERT INTO campus_admin_migrations(key) - SELECT 'role:'||group_uuid||':'||membership_uuid FROM (`+candidates+`) AS candidates WHERE 1=1 ON CONFLICT(key) DO NOTHING`) + _, err := tx.ExecContext(ctx, `INSERT INTO campus_admin_migrations(`+s.sqlConfigKey()+`) + SELECT `+s.sqlConcat("'role:'", "group_uuid", "':'", "membership_uuid")+` FROM (`+candidates+`) AS candidates WHERE 1=1`+s.sqlConflictDoNothing("campus_admin_migrations", "key", "key")) return err } @@ -103,12 +103,12 @@ func (s *Store) projectCampusAdminMembershipsContext(ctx context.Context, tx *sq if _, err := tx.ExecContext(ctx, `DELETE FROM campus_admin_grants WHERE substr(source,1,21)='campus_admin_inherit:'`); err != nil { return err } - const roots = `SELECT src.uuid AS source_group_uuid,origin.uuid AS source_domain_uuid, + roots := `SELECT src.uuid AS source_group_uuid,origin.uuid AS source_domain_uuid, origin.campus_uuid,srcm.principal_uuid,MIN(gr.created_at_ms) AS created_at_ms, CASE MAX(CASE gr.member_role WHEN 'owner' THEN 3 WHEN 'manager' THEN 2 ELSE 1 END) WHEN 3 THEN 'owner' WHEN 2 THEN 'manager' ELSE 'member' END AS member_role FROM campus_admin_grants gr - JOIN groups src ON src.uuid=gr.group_uuid AND src.builtin_key='campus_admin' + JOIN ` + s.sqlGroupTable() + ` src ON src.uuid=gr.group_uuid AND src.builtin_key='campus_admin' AND src.state='active' AND src.inherit_members=1 JOIN domains origin ON origin.uuid=src.domain_uuid AND origin.enabled=1 JOIN domain_memberships srcm ON srcm.uuid=gr.membership_uuid @@ -121,35 +121,37 @@ func (s *Store) projectCampusAdminMembershipsContext(ctx context.Context, tx *sq newUUID := `lower(hex(randomblob(4)))||'-'||lower(hex(randomblob(2)))||'-4'||substr(lower(hex(randomblob(2))),2)||'-a'||substr(lower(hex(randomblob(2))),2)||'-'||lower(hex(randomblob(6)))` if s.sqlBackend == storePostgreSQL { newUUID = `gen_random_uuid()::text` + } else if s.sqlBackend == storeMySQL { + newUUID = `UUID()` } if _, err := tx.ExecContext(ctx, `INSERT INTO campus_admin_membership_origins (membership_uuid,domain_uuid,principal_uuid) SELECT `+newUUID+`,domain_uuid,principal_uuid FROM ( SELECT DISTINCT dst.uuid AS domain_uuid,root.principal_uuid FROM (`+roots+`) root JOIN domains dst ON dst.campus_uuid=root.campus_uuid AND dst.uuid!=root.source_domain_uuid AND dst.enabled=1 - JOIN groups dstg ON dstg.domain_uuid=dst.uuid AND dstg.builtin_key='campus_admin' AND dstg.state='active' + JOIN `+s.sqlGroupTable()+` dstg ON dstg.domain_uuid=dst.uuid AND dstg.builtin_key='campus_admin' AND dstg.state='active' WHERE NOT EXISTS(SELECT 1 FROM domain_memberships m - WHERE m.domain_uuid=dst.uuid AND m.principal_uuid=root.principal_uuid)) AS missing_memberships WHERE 1=1 ON CONFLICT(domain_uuid,principal_uuid) DO NOTHING`); err != nil { + WHERE m.domain_uuid=dst.uuid AND m.principal_uuid=root.principal_uuid)) AS missing_memberships WHERE 1=1`+s.sqlConflictDoNothing("campus_admin_membership_origins", "membership_uuid", "domain_uuid,principal_uuid")); err != nil { return err } if _, err := tx.ExecContext(ctx, `INSERT INTO domain_memberships (uuid,domain_uuid,principal_uuid,state,created_at_ms) SELECT membership_uuid,domain_uuid,principal_uuid,'active',`+s.sqlParam(1)+` - FROM campus_admin_membership_origins WHERE 1=1 ON CONFLICT(domain_uuid,principal_uuid) DO NOTHING`, now); err != nil { + FROM campus_admin_membership_origins WHERE 1=1`+s.sqlConflictDoNothing("domain_memberships", "uuid", "domain_uuid,principal_uuid"), now); err != nil { return err } if _, err := tx.ExecContext(ctx, `INSERT INTO campus_admin_grants (group_uuid,membership_uuid,source,member_role,created_at_ms) - SELECT dstg.uuid,dstm.uuid,'campus_admin_inherit:'||root.source_group_uuid,root.member_role,root.created_at_ms + SELECT dstg.uuid,dstm.uuid,`+s.sqlConcat("'campus_admin_inherit:'", "root.source_group_uuid")+`,root.member_role,root.created_at_ms FROM (`+roots+`) root JOIN domains dst ON dst.campus_uuid=root.campus_uuid AND dst.uuid!=root.source_domain_uuid AND dst.enabled=1 - JOIN groups dstg ON dstg.domain_uuid=dst.uuid AND dstg.builtin_key='campus_admin' AND dstg.state='active' + JOIN `+s.sqlGroupTable()+` dstg ON dstg.domain_uuid=dst.uuid AND dstg.builtin_key='campus_admin' AND dstg.state='active' JOIN domain_memberships dstm ON dstm.domain_uuid=dst.uuid AND dstm.principal_uuid=root.principal_uuid AND dstm.state='active'`); err != nil { return err } if _, err := tx.ExecContext(ctx, `DELETE FROM group_members WHERE - group_uuid IN (SELECT uuid FROM groups WHERE builtin_key='campus_admin') + group_uuid IN (SELECT uuid FROM `+s.sqlGroupTable()+` WHERE builtin_key='campus_admin') OR substr(source,1,21)='campus_admin_inherit:'`); err != nil { return err } @@ -160,11 +162,11 @@ func (s *Store) projectCampusAdminMembershipsContext(ctx context.Context, tx *sq SELECT gr.*,ROW_NUMBER() OVER(PARTITION BY gr.group_uuid,gr.membership_uuid ORDER BY CASE gr.member_role WHEN 'owner' THEN 3 WHEN 'manager' THEN 2 ELSE 1 END DESC, CASE WHEN substr(gr.source,1,21)='campus_admin_inherit:' THEN 1 ELSE 0 END, - gr.source) AS rank - FROM campus_admin_grants gr JOIN groups g ON g.uuid=gr.group_uuid + gr.source) AS grant_rank + FROM campus_admin_grants gr JOIN `+s.sqlGroupTable()+` g ON g.uuid=gr.group_uuid JOIN domains d ON d.uuid=g.domain_uuid JOIN domain_memberships m ON m.uuid=gr.membership_uuid AND m.domain_uuid=g.domain_uuid - ) AS ranked_grants WHERE rank=1`); err != nil { + ) AS ranked_grants WHERE grant_rank=1`); err != nil { return err } // A newly added independent group/role grant adopts an inherited membership diff --git a/internal/store/groups_mysql.go b/internal/store/groups_mysql.go new file mode 100644 index 0000000..e129a38 --- /dev/null +++ b/internal/store/groups_mysql.go @@ -0,0 +1,97 @@ +package store + +import ( + "context" + "database/sql" + "errors" + "strings" + "time" + + "github.com/google/uuid" +) + +// All helpers are called under the same transactional administrative lock as +// SQLite/PostgreSQL. Never use MySQL RowsAffected to infer existence on UPSERT: +// unchanged/update/insert can report 0/2/1 respectively. +func (s *Store) ensureMySQLBuiltinGroups(ctx context.Context, tx *sql.Tx) error { + rows, err := tx.QueryContext(ctx, `SELECT uuid FROM domains ORDER BY uuid`) + if err != nil { + return err + } + var domains []string + for rows.Next() { + var id string + if err := rows.Scan(&id); err != nil { + rows.Close() + return err + } + domains = append(domains, id) + } + err = rows.Err() + rows.Close() + if err != nil { + return err + } + now := time.Now().UnixMilli() + for _, domain := range domains { + for _, key := range []string{"campus_admin", "domain_admin"} { + inherit := 0 + if key == "campus_admin" { + inherit = 1 + } + _, err := tx.ExecContext(ctx, "INSERT INTO `groups`(uuid,domain_uuid,name,display_name,description,visibility,state,builtin_key,inherit_members,created_at_ms,updated_at_ms) VALUES(?,?,?,?,?,'members','active',?,?,?,?) ON DUPLICATE KEY UPDATE builtin_key=?", uuid.NewString(), domain, key, strings.ReplaceAll(key, "_", " "), "Built-in administrative group", key, inherit, now, now, key) + if err != nil { + return err + } + } + _, err := tx.ExecContext(ctx, `INSERT INTO group_members(group_uuid,membership_uuid,member_role,source,created_at_ms) + SELECT g.uuid,m.uuid,'owner','migration',? FROM `+"`groups`"+` g + JOIN domain_memberships m ON m.domain_uuid=g.domain_uuid + JOIN auth_role_bindings b ON b.membership_uuid=m.uuid + JOIN auth_roles r ON r.uuid=b.role_uuid AND r.domain_uuid=m.domain_uuid + JOIN auth_capability_grants c ON c.role_uuid=r.uuid AND c.capability='manage' AND c.target_type='domain' AND (c.target_id=m.domain_uuid OR c.target_id='*') + WHERE g.domain_uuid=? AND g.builtin_key='domain_admin' + ON DUPLICATE KEY UPDATE group_uuid=group_members.group_uuid`, now, domain) + if err != nil { + return err + } + } + if err := s.seedCampusAdminRoleGrantsContext(ctx, tx, now); err != nil { + return err + } + return s.projectCampusAdminMembershipsContext(ctx, tx) +} + +func mysqlAddGroupMember(ctx context.Context, tx *sql.Tx, group, member, role string) error { + var previous string + err := tx.QueryRowContext(ctx, `SELECT member_role FROM group_members WHERE group_uuid=? AND membership_uuid=?`, group, member).Scan(&previous) + if err != nil && !errors.Is(err, sql.ErrNoRows) { + return err + } + if previous == "owner" && role != "owner" { + return namespaceValidationError("owner role cannot be downgraded by a member update") + } + _, err = tx.ExecContext(ctx, `INSERT INTO group_members(group_uuid,membership_uuid,member_role,source,created_at_ms) VALUES(?,?,?,'local',?) ON DUPLICATE KEY UPDATE member_role=?,source='local'`, group, member, role, time.Now().UnixMilli(), role) + return err +} + +func mysqlRemoveGroupMember(ctx context.Context, tx *sql.Tx, group, member string, authority bool) error { + var role string + if err := tx.QueryRowContext(ctx, `SELECT member_role FROM group_members WHERE group_uuid=? AND membership_uuid=?`, group, member).Scan(&role); err != nil { + return err + } + if !authority && role != "member" { + return namespaceValidationError("member removal requires sufficient authority") + } + if role == "owner" { + var other bool + if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM group_members gm JOIN `+"`groups`"+` g ON g.uuid=gm.group_uuid JOIN domain_memberships m ON m.uuid=gm.membership_uuid AND m.domain_uuid=g.domain_uuid WHERE gm.group_uuid=? AND gm.membership_uuid!=? AND gm.member_role='owner')`, group, member).Scan(&other); err != nil { + return err + } + if !other { + return namespaceValidationError("member removal requires at least one remaining owner") + } + } + _, err := tx.ExecContext(ctx, `DELETE FROM group_members WHERE group_uuid=? AND membership_uuid=?`, group, member) + return err +} diff --git a/internal/store/machine_learning.go b/internal/store/machine_learning.go new file mode 100644 index 0000000..a846727 --- /dev/null +++ b/internal/store/machine_learning.go @@ -0,0 +1,99 @@ +package store + +import ( + "context" + "encoding/json" + "errors" + "time" + + "github.com/google/uuid" + "pageswiki/internal/machinelearning" +) + +const machineLearningConfigKey = "machine_learning_policy_v1" + +var ErrMachineLearningConflict = errors.New("machine learning configuration changed; reload before saving") + +// MachineLearningPolicy returns disabled-by-default configuration. Invalid +// persisted data fails closed; it must not silently become a usable default. +func (s *Store) MachineLearningPolicy(ctx context.Context, domain string) (machinelearning.Policy, error) { + raw, err := s.mlConfig(ctx, domain) + if err != nil { + return machinelearning.Policy{}, err + } + if raw == "" { + return machinelearning.Policy{}, nil + } + var p machinelearning.Policy + if json.Unmarshal([]byte(raw), &p) != nil || p.Validate() != nil { + return machinelearning.Policy{}, machinelearning.ErrPolicy + } + return p, nil +} + +// SaveMachineLearningPolicy is an internal persistence primitive. Its caller +// must authorize Domain administration (enforced by the settings API). +// Generation is server-assigned and updates use an atomic compare-and-swap. +func (s *Store) SaveMachineLearningPolicy(ctx context.Context, domain, baseGeneration string, p machinelearning.Policy) (machinelearning.Policy, error) { + id, err := uuid.Parse(domain) + if err != nil || id.String() != domain { + return machinelearning.Policy{}, machinelearning.ErrPolicy + } + raw, err := s.mlConfig(ctx, domain) + if err != nil { + return machinelearning.Policy{}, err + } + if raw == "" { + if baseGeneration != "" { + return machinelearning.Policy{}, ErrMachineLearningConflict + } + } else { + var old machinelearning.Policy + if json.Unmarshal([]byte(raw), &old) != nil || old.Validate() != nil { + return machinelearning.Policy{}, machinelearning.ErrPolicy + } + if old.Generation != baseGeneration { + return machinelearning.Policy{}, ErrMachineLearningConflict + } + } + p.Generation = uuid.NewString() + if err = p.Validate(); err != nil { + return machinelearning.Policy{}, err + } + data, err := json.Marshal(p) + if err != nil { + return machinelearning.Policy{}, err + } + var affected int64 + if raw == "" { + query := `INSERT INTO config(domain_uuid,` + s.sqlConfigKey() + `,value,updated_at) VALUES (` + s.sqlValues(4) + `) ON CONFLICT(domain_uuid,key) DO NOTHING` + if s.sqlBackend == storeMySQL { + query = `INSERT INTO config(domain_uuid,` + s.sqlConfigKey() + `,value,updated_at) VALUES (?,?,?,?)` + } + result, e := s.DB.ExecContext(ctx, query, domain, machineLearningConfigKey, string(data), time.Now().Unix()) + if e != nil { + if s.sqlBackend == storeMySQL && mysqlDuplicate(e) { + return machinelearning.Policy{}, ErrMachineLearningConflict + } + return machinelearning.Policy{}, s.sqlError("create ML policy", e) + } + affected, err = result.RowsAffected() + } else { + comparison := `value=` + s.sqlParam(5) + if s.sqlBackend == storeMySQL { + comparison = `BINARY value=BINARY ?` + } + result, e := s.DB.ExecContext(ctx, `UPDATE config SET value=`+s.sqlParam(1)+`,updated_at=`+s.sqlParam(2)+` WHERE domain_uuid=`+s.sqlParam(3)+` AND `+s.sqlConfigKey()+`=`+s.sqlParam(4)+` AND `+comparison, string(data), time.Now().Unix(), domain, machineLearningConfigKey, raw) + if e != nil { + return machinelearning.Policy{}, s.sqlError("update ML policy", e) + } + affected, err = result.RowsAffected() + } + if err != nil { + return machinelearning.Policy{}, err + } + if affected != 1 { + return machinelearning.Policy{}, ErrMachineLearningConflict + } + return p, nil +} diff --git a/internal/store/machine_learning_budget.go b/internal/store/machine_learning_budget.go new file mode 100644 index 0000000..90b1f0f --- /dev/null +++ b/internal/store/machine_learning_budget.go @@ -0,0 +1,163 @@ +package store + +import ( + "context" + "crypto/sha256" + "database/sql" + "encoding/hex" + "encoding/json" + "errors" + "time" + + "github.com/google/uuid" + "pageswiki/internal/db" + "pageswiki/internal/machinelearning" +) + +var ErrMLBudget = errors.New("machine learning daily input budget exhausted or not configured") +var ErrMLAlreadyReserved = errors.New("machine learning request already reserved; do not resend") + +var mlBudgetStatements = []string{ + `CREATE TABLE ml_daily_budget(domain_uuid TEXT NOT NULL,day TEXT NOT NULL,reserved_bytes BIGINT NOT NULL CHECK(reserved_bytes>=0),PRIMARY KEY(domain_uuid,day))`, + `CREATE TABLE ml_budget_receipts(domain_uuid TEXT NOT NULL,request_uuid TEXT NOT NULL,day TEXT NOT NULL,input_hash TEXT NOT NULL,generation TEXT NOT NULL,reserved_bytes BIGINT NOT NULL CHECK(reserved_bytes>0),state TEXT NOT NULL CHECK(state IN ('reserved','completed','unknown')),actual_tokens BIGINT NOT NULL DEFAULT 0 CHECK(actual_tokens>=0),PRIMARY KEY(domain_uuid,request_uuid))`, +} + +var mlBudgetMigrations = []db.SQLMigration{{Version: 1, Name: "ML daily reservations", Statements: mlBudgetStatements, Assertions: []string{ + schemaColumns("ml_daily_budget", "domain_uuid,day,reserved_bytes"), + schemaUnique("ml_daily_budget", "domain_uuid,day"), + schemaColumns("ml_budget_receipts", "domain_uuid,request_uuid,day,input_hash,generation,reserved_bytes,state,actual_tokens"), + schemaUnique("ml_budget_receipts", "domain_uuid,request_uuid"), +}}} + +// Explicit preparation for the future worker. Not called by ordinary settings +// reads/writes, and not automatically applied to production on this change. +func (s *Store) EnsureMLBudgetSchema(ctx context.Context) error { + if s.sqlBackend == storeMySQL { + return errors.New("use isolated MySQL ML schema preparation") + } + if s.sqlBackend == storePostgreSQL { + return db.ApplyPostgreSQLMigrations(ctx, s.DB, "machine-learning-budget", []db.PostgreSQLMigration{{Version: 1, Name: "ML daily reservations", Statements: mlBudgetStatements}}) + } + return db.ApplySQLiteMigrations(ctx, s.DB, "machine-learning-budget", mlBudgetMigrations) +} + +// ReserveMLInput prepares a request from CURRENT settings and reserves its byte +// cost atomically. Caller must authorize the document and learning cohort first. +// A returned request is permission for ONE attempt, never a retry receipt. +func (s *Store) ReserveMLInput(ctx context.Context, domain, requestID, logicalPath, generation string, inputs []machinelearning.Input) (machinelearning.Request, error) { + return s.reserveMLInputAt(ctx, domain, requestID, logicalPath, generation, inputs, time.Now()) +} + +func (s *Store) reserveMLInputAt(ctx context.Context, domain, requestID, logicalPath, generation string, inputs []machinelearning.Input, now time.Time) (machinelearning.Request, error) { + var empty machinelearning.Request + id, e := uuid.Parse(requestID) + if e != nil || id.String() != requestID { + return empty, machinelearning.ErrPolicy + } + var options *sql.TxOptions + if s.sqlBackend != storeSQLite { + options = &sql.TxOptions{Isolation: sql.LevelReadCommitted} + } + tx, e := s.DB.BeginTx(ctx, options) + if e != nil { + return empty, e + } + defer tx.Rollback() + // Lock the same configuration row that settings updates modify. This also + // serializes budget writers across processes, including policy generations. + if s.sqlBackend == storeSQLite { + if _, e = tx.ExecContext(ctx, `UPDATE config SET value=value WHERE domain_uuid=? AND key=?`, domain, machineLearningConfigKey); e != nil { + return empty, e + } + } + var raw string + lockQuery := `SELECT value FROM config WHERE domain_uuid=` + s.sqlParam(1) + ` AND ` + s.sqlConfigKey() + `=` + s.sqlParam(2) + if s.sqlBackend != storeSQLite { + lockQuery += ` FOR UPDATE` + } + if e = tx.QueryRowContext(ctx, lockQuery, domain, machineLearningConfigKey).Scan(&raw); e != nil { + if errors.Is(e, sql.ErrNoRows) { + return empty, machinelearning.ErrNotAllowed + } + return empty, e + } + var p machinelearning.Policy + if json.Unmarshal([]byte(raw), &p) != nil { + return empty, machinelearning.ErrPolicy + } + req, e := p.Prepare(domain, logicalPath, generation, inputs) + if e != nil { + return empty, e + } + if p.DailyInputBytes <= 0 { + return empty, ErrMLBudget + } + var oldHash string + e = tx.QueryRowContext(ctx, `SELECT input_hash FROM ml_budget_receipts WHERE domain_uuid=`+s.sqlParam(1)+` AND request_uuid=`+s.sqlParam(2), domain, requestID).Scan(&oldHash) + if e == nil { + return empty, ErrMLAlreadyReserved + } + if !errors.Is(e, sql.ErrNoRows) { + return empty, e + } + day := now.UTC().Format("2006-01-02") + var used int64 + e = tx.QueryRowContext(ctx, `SELECT reserved_bytes FROM ml_daily_budget WHERE domain_uuid=`+s.sqlParam(1)+` AND day=`+s.sqlParam(2), domain, day).Scan(&used) + if e != nil && !errors.Is(e, sql.ErrNoRows) { + return empty, e + } + var cost int64 + for _, input := range req.Inputs { + cost += int64(len(input.Text)) + } + if used > p.DailyInputBytes || cost > p.DailyInputBytes-used { + return empty, ErrMLBudget + } + budgetQuery := `INSERT INTO ml_daily_budget(domain_uuid,day,reserved_bytes) VALUES (` + s.sqlValues(3) + `) ON CONFLICT(domain_uuid,day) DO UPDATE SET reserved_bytes=excluded.reserved_bytes` + args := []any{domain, day, used + cost} + if s.sqlBackend == storeMySQL { + budgetQuery = `INSERT INTO ml_daily_budget(domain_uuid,day,reserved_bytes) VALUES (?,?,?) ON DUPLICATE KEY UPDATE reserved_bytes=?` + args = append(args, used+cost) + } + _, e = tx.ExecContext(ctx, budgetQuery, args...) + if e != nil { + return empty, e + } + encoded, e := json.Marshal(req) + if e != nil { + return empty, e + } + hash := sha256.Sum256(encoded) + _, e = tx.ExecContext(ctx, `INSERT INTO ml_budget_receipts(domain_uuid,request_uuid,day,input_hash,generation,reserved_bytes,state) VALUES (`+s.sqlValues(7)+`)`, domain, requestID, day, hex.EncodeToString(hash[:]), generation, cost, "reserved") + if e != nil { + return empty, e + } + if e = tx.Commit(); e != nil { + return empty, e + } + return req, nil +} + +// FinishMLInput does not release reservations, including on timeout/crash. +// Actual token usage is informational and never increases the byte allowance. +func (s *Store) FinishMLInput(ctx context.Context, domain, requestID string, completed bool, actualTokens int64) error { + if actualTokens < 0 { + return machinelearning.ErrPolicy + } + state := "unknown" + if completed { + state = "completed" + } + r, e := s.DB.ExecContext(ctx, `UPDATE ml_budget_receipts SET state=`+s.sqlParam(1)+`,actual_tokens=`+s.sqlParam(2)+` WHERE domain_uuid=`+s.sqlParam(3)+` AND request_uuid=`+s.sqlParam(4)+` AND state='reserved'`, state, actualTokens, domain, requestID) + if e != nil { + return e + } + n, e := r.RowsAffected() + if e != nil { + return e + } + if n != 1 { + return ErrMLAlreadyReserved + } + return nil +} diff --git a/internal/store/machine_learning_budget_test.go b/internal/store/machine_learning_budget_test.go new file mode 100644 index 0000000..d88028a --- /dev/null +++ b/internal/store/machine_learning_budget_test.go @@ -0,0 +1,100 @@ +package store + +import ( + "context" + "errors" + "fmt" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "pageswiki/internal/machinelearning" +) + +func TestMLBudget(t *testing.T) { + for _, backend := range []storeSQLBackend{storeSQLite, storePostgreSQL, storeMySQL} { + t.Run(fmt.Sprint(backend), func(t *testing.T) { + s, d := mlTestStore(t, backend) + ctx := context.Background() + if backend != storeMySQL { + if e := s.EnsureMLBudgetSchema(ctx); e != nil { + t.Fatal(e) + } + if e := s.EnsureMLBudgetSchema(ctx); e != nil { + t.Fatal("migration rerun", e) + } + } + p, e := s.SaveMachineLearningPolicy(ctx, d.UUID, "", machinelearning.Policy{Enabled: true, ScopeUUID: uuid.NewString(), Provider: "doc2vec", Model: strings.Repeat("a", 64), Dimensions: 8, Prefixes: []string{"/lab"}, MaxBatchBytes: 6000, DailyInputBytes: 10}) + if e != nil { + t.Fatal(e) + } + day := time.Date(2026, 11, 28, 23, 59, 0, 0, time.UTC) + inputs := []machinelearning.Input{{ID: "chunk", Text: "abcdef"}} + reserve := func(id string, at time.Time) error { + _, err := s.reserveMLInputAt(ctx, d.UUID, id, "/lab/doc", p.Generation, inputs, at) + return err + } + id := uuid.NewString() + if e = reserve(id, day); e != nil { + t.Fatal(e) + } + if e = reserve(id, day); !errors.Is(e, ErrMLAlreadyReserved) { + t.Fatal("duplicate", e) + } + if e = s.FinishMLInput(ctx, d.UUID, id, false, 0); e != nil { + t.Fatal(e) + } + if e = s.FinishMLInput(ctx, d.UUID, id, true, 1); !errors.Is(e, ErrMLAlreadyReserved) { + t.Fatal("settled receipt changed", e) + } + if e = reserve(uuid.NewString(), day); !errors.Is(e, ErrMLBudget) { + t.Fatal("unknown refunded", e) + } + // New UTC day resets allowance, not idempotency receipts. + if e = reserve(id, day.Add(time.Minute)); !errors.Is(e, ErrMLAlreadyReserved) { + t.Fatal("old ID reused", e) + } + start := make(chan struct{}) + results := make(chan error, 2) + for i := 0; i < 2; i++ { + go func() { <-start; results <- reserve(uuid.NewString(), day.Add(time.Minute)) }() + } + close(start) + wins := 0 + for i := 0; i < 2; i++ { + e = <-results + if e == nil { + wins++ + } else if !errors.Is(e, ErrMLBudget) { + t.Fatal(e) + } + } + if wins != 1 { + t.Fatal("concurrent overspend", wins) + } + // Policy generations never reset usage. Reducing limits fails closed. + old := p.Generation + p.DailyInputBytes = 5 + p, e = s.SaveMachineLearningPolicy(ctx, d.UUID, old, p) + if e != nil { + t.Fatal(e) + } + if e = reserve(uuid.NewString(), day); !errors.Is(e, ErrMLBudget) { + t.Fatal("policy reset budget", e) + } + _, e = s.reserveMLInputAt(ctx, d.UUID, uuid.NewString(), "/lab/doc", old, inputs, day) + if !errors.Is(e, machinelearning.ErrNotAllowed) { + t.Fatal("old consent", e) + } + p.DailyInputBytes = 0 + p, e = s.SaveMachineLearningPolicy(ctx, d.UUID, p.Generation, p) + if e != nil { + t.Fatal(e) + } + if e = reserve(uuid.NewString(), day.Add(48*time.Hour)); !errors.Is(e, ErrMLBudget) { + t.Fatal("zero allows execution", e) + } + }) + } +} diff --git a/internal/store/machine_learning_mysql.go b/internal/store/machine_learning_mysql.go new file mode 100644 index 0000000..82cde26 --- /dev/null +++ b/internal/store/machine_learning_mysql.go @@ -0,0 +1,54 @@ +package store + +import ( + "context" + "database/sql" + "errors" + + "github.com/go-sql-driver/mysql" + "pageswiki/internal/machinelearning" +) + +func mysqlDuplicate(err error) bool { + var e *mysql.MySQLError + return errors.As(err, &e) && e.Number == 1062 +} +func (s *Store) mlConfig(ctx context.Context, domain string) (string, error) { + return s.GetConfigInDomainContext(ctx, domain, machineLearningConfigKey) +} + +// MySQLMLRepository deliberately exposes ONLY the ported ML component. Returning +// *Store would allow unported methods to silently execute SQLite-specific SQL. +// Caller supplies a separately prepared MySQL 8.4+ InnoDB pilot database. +// This is not a Pages server constructor, whole-app migration or deployment option. +type MySQLMLRepository struct{ store *Store } + +func NewMySQLMLRepository(database *sql.DB) *MySQLMLRepository { + return &MySQLMLRepository{store: &Store{DB: database, sqlBackend: storeMySQL}} +} +func mlMySQLError(err error) error { + if err == nil { + return nil + } + for _, known := range []error{ErrMachineLearningConflict, ErrMLAlreadyReserved, ErrMLBudget, machinelearning.ErrNotAllowed, machinelearning.ErrPolicy, context.Canceled, context.DeadlineExceeded} { + if errors.Is(err, known) { + return known + } + } + return errors.New("MySQL ML operation failed") +} +func (r *MySQLMLRepository) Policy(ctx context.Context, domain string) (machinelearning.Policy, error) { + p, e := r.store.MachineLearningPolicy(ctx, domain) + return p, mlMySQLError(e) +} +func (r *MySQLMLRepository) SavePolicy(ctx context.Context, domain, base string, p machinelearning.Policy) (machinelearning.Policy, error) { + p, e := r.store.SaveMachineLearningPolicy(ctx, domain, base, p) + return p, mlMySQLError(e) +} +func (r *MySQLMLRepository) Reserve(ctx context.Context, domain, id, path, generation string, inputs []machinelearning.Input) (machinelearning.Request, error) { + q, e := r.store.ReserveMLInput(ctx, domain, id, path, generation, inputs) + return q, mlMySQLError(e) +} +func (r *MySQLMLRepository) Finish(ctx context.Context, domain, id string, completed bool, tokens int64) error { + return mlMySQLError(r.store.FinishMLInput(ctx, domain, id, completed, tokens)) +} diff --git a/internal/store/machine_learning_mysql_schema.go b/internal/store/machine_learning_mysql_schema.go new file mode 100644 index 0000000..5095d3e --- /dev/null +++ b/internal/store/machine_learning_mysql_schema.go @@ -0,0 +1,56 @@ +package store + +import ( + "context" + _ "embed" + "fmt" + "strings" + + "pageswiki/internal/db" +) + +//go:embed mysql_ml_schema.sql +var mysqlMLSchema string + +// All identifiers/signatures are owned constants. Check column shape, PK order, +// engine and CHECK count. This is not a comparison of all constraint semantics. +func mysqlMLTableCheck(table, columns, pk string, checks int) string { + return fmt.Sprintf(`SELECT + (SELECT COUNT(*) FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='%s' AND engine='InnoDB')=1 + AND (SELECT GROUP_CONCAT(CONCAT(column_name,':',column_type,':',is_nullable,':',COALESCE(collation_name,'')) ORDER BY ordinal_position SEPARATOR '|') FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='%s')='%s' + AND (SELECT GROUP_CONCAT(column_name ORDER BY seq_in_index SEPARATOR ',') FROM information_schema.statistics WHERE table_schema=DATABASE() AND table_name='%s' AND index_name='PRIMARY')='%s' + AND (SELECT COUNT(*) FROM information_schema.table_constraints WHERE constraint_schema=DATABASE() AND table_name='%s' AND constraint_type='CHECK')=%d`, table, table, columns, table, pk, table, checks) +} + +var mysqlMLChecks = []string{ + mysqlMLTableCheck("config", "domain_uuid:varchar(36):NO:ascii_bin|key:varchar(128):NO:ascii_bin|value:longtext:NO:utf8mb4_bin|updated_at:bigint:NO:", "domain_uuid,key", 0), + mysqlMLTableCheck("ml_daily_budget", "domain_uuid:varchar(36):NO:ascii_bin|day:char(10):NO:ascii_bin|reserved_bytes:bigint:NO:", "domain_uuid,day", 1), + mysqlMLTableCheck("ml_budget_receipts", "domain_uuid:varchar(36):NO:ascii_bin|request_uuid:varchar(36):NO:ascii_bin|day:char(10):NO:ascii_bin|input_hash:char(64):NO:ascii_bin|generation:varchar(36):NO:ascii_bin|reserved_bytes:bigint:NO:|state:varchar(16):NO:ascii_bin|actual_tokens:bigint:NO:", "domain_uuid,request_uuid", 3), +} + +func mysqlMLMigrations() []db.MySQLMigration { + var ops []db.MySQLOperation + // This owned bundle contains three CREATE TABLE statements without stored + // procedures or semicolon-containing literals. Not a general SQL parser. + for _, statement := range strings.Split(mysqlMLSchema, ";") { + if strings.TrimSpace(statement) != "" { + ops = append(ops, db.MySQLOperation{SQL: strings.TrimSpace(statement), Check: mysqlMLChecks[len(ops)], ReplaySafe: true}) + } + } + // Preserve the v1 checksum. Core configuration needs Unicode keys and + // NO PAD comparisons ("key" and "key " must remain distinct). + configV2 := mysqlMLTableCheck("config", "domain_uuid:varchar(36):NO:ascii_bin|key:varchar(255):NO:utf8mb4_0900_bin|value:longtext:NO:utf8mb4_bin|updated_at:bigint:NO:", "domain_uuid,key", 0) + return []db.MySQLMigration{ + {Version: 1, Name: "ML configuration and reservations", Operations: ops, Assertions: mysqlMLChecks}, + {Version: 2, Name: "Unicode exact configuration keys", Operations: []db.MySQLOperation{{SQL: "ALTER TABLE config MODIFY COLUMN `key` VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin NOT NULL", Check: configV2, ReplaySafe: true}}, Assertions: []string{configV2, mysqlMLChecks[1], mysqlMLChecks[2]}}, + } +} +func (r *MySQLMLRepository) PrepareSchema(ctx context.Context) error { + return db.ApplyMySQLMigrations(ctx, r.store.DB, "machine-learning", mysqlMLMigrations()) +} +func (r *MySQLMLRepository) InspectSchema(ctx context.Context) (db.MySQLMigrationStatus, error) { + return db.InspectMySQLMigrations(ctx, r.store.DB, "machine-learning", mysqlMLMigrations()) +} +func (r *MySQLMLRepository) ResumeSchema(ctx context.Context) error { + return db.ResumeMySQLMigrations(ctx, r.store.DB, "machine-learning", mysqlMLMigrations()) +} diff --git a/internal/store/machine_learning_mysql_test.go b/internal/store/machine_learning_mysql_test.go new file mode 100644 index 0000000..e0d798f --- /dev/null +++ b/internal/store/machine_learning_mysql_test.go @@ -0,0 +1,82 @@ +package store + +import ( + "context" + "database/sql" + "os" + "strings" + "testing" + "time" + + "github.com/go-sql-driver/mysql" + "github.com/google/uuid" + "pageswiki/internal/db" +) + +func mlTestStore(t *testing.T, backend storeSQLBackend) (*Store, *Domain) { + t.Helper() + if backend != storeMySQL { + s := testNamespaceStore(t, backend) + d, e := s.GetDefaultDomain() + if e != nil { + t.Fatal(e) + } + return s, d + } + database := mysqlTestDatabase(t) + ctx := context.Background() + repo := NewMySQLMLRepository(database) + status, e := repo.InspectSchema(ctx) + if e != nil || status.Applied != 0 || status.Pending != len(mysqlMLMigrations()) { + t.Fatal("fresh inspection", status, e) + } + if e = repo.PrepareSchema(ctx); e != nil { + t.Fatal(e) + } + if e = repo.PrepareSchema(ctx); e != nil { + t.Fatal("repeat migration", e) + } + status, e = repo.InspectSchema(ctx) + if e != nil || status.Applied != len(mysqlMLMigrations()) || status.Dirty { + t.Fatal("applied inspection", status, e) + } + return repo.store, &Domain{UUID: uuid.NewString()} +} + +func mysqlTestDatabase(t *testing.T) *sql.DB { + t.Helper() + dsn := os.Getenv("PAGESWIKI_TEST_MYSQL_DSN") + if dsn == "" { + t.Skip("set PAGESWIKI_TEST_MYSQL_DSN to a disposable MySQL server") + } + c, e := mysql.ParseDSN(dsn) + if e != nil { + t.Fatal("invalid test DSN") + } + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + admin, e := db.OpenMySQL(ctx, db.MySQLOptions{DSN: dsn, AllowInsecure: true}) + if e != nil { + t.Fatal(e) + } + name := "pages_ml_test_" + strings.ReplaceAll(uuid.NewString(), "-", "") + if _, e = admin.ExecContext(ctx, "CREATE DATABASE "+name+" CHARACTER SET utf8mb4 COLLATE utf8mb4_bin"); e != nil { + admin.Close() + t.Fatal("create isolated MySQL database failed") + } + t.Cleanup(func() { + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + if _, e := admin.ExecContext(ctx, "DROP DATABASE "+name); e != nil { + t.Error("remove test database failed") + } + admin.Close() + }) + c.DBName = name + database, e := db.OpenMySQL(ctx, db.MySQLOptions{DSN: c.FormatDSN(), AllowInsecure: true}) + if e != nil { + t.Fatal(e) + } + t.Cleanup(func() { database.Close() }) + return database +} diff --git a/internal/store/machine_learning_test.go b/internal/store/machine_learning_test.go new file mode 100644 index 0000000..a8533b5 --- /dev/null +++ b/internal/store/machine_learning_test.go @@ -0,0 +1,90 @@ +package store + +import ( + "context" + "errors" + "fmt" + "strings" + "testing" + + "github.com/google/uuid" + "pageswiki/internal/machinelearning" +) + +func TestMachineLearningPolicyPersistence(t *testing.T) { + for _, backend := range []storeSQLBackend{storeSQLite, storePostgreSQL, storeMySQL} { + t.Run(fmt.Sprint(backend), func(t *testing.T) { testMachineLearningPolicyPersistence(t, backend) }) + } +} + +func testMachineLearningPolicyPersistence(t *testing.T, backend storeSQLBackend) { + s, domain := mlTestStore(t, backend) + ctx := context.Background() + empty, err := s.MachineLearningPolicy(ctx, domain.UUID) + if err != nil || empty.Enabled || empty.Generation != "" { + t.Fatal("not disabled by default", err) + } + p := machinelearning.Policy{Enabled: true, ScopeUUID: uuid.NewString(), Provider: "doc2vec", Model: strings.Repeat("a", 64), Dimensions: 8, Prefixes: []string{"/lab"}, MaxBatchBytes: 6000} + saved, err := s.SaveMachineLearningPolicy(ctx, domain.UUID, "", p) + if err != nil { + t.Fatal(err) + } + if saved.Generation == "" || saved.Generation == p.Generation { + t.Fatal("generation not assigned") + } + if _, err = s.SaveMachineLearningPolicy(ctx, domain.UUID, "", p); !errors.Is(err, ErrMachineLearningConflict) { + t.Fatal("lost update", err) + } + loaded, err := s.MachineLearningPolicy(ctx, domain.UUID) + if err != nil || loaded.Generation != saved.Generation { + t.Fatal("roundtrip", err) + } + other, err := s.MachineLearningPolicy(ctx, uuid.NewString()) + if err != nil || other.Enabled { + t.Fatal("cross domain leak", err) + } + p.Enabled = false + disabled, err := s.SaveMachineLearningPolicy(ctx, domain.UUID, saved.Generation, p) + if err != nil { + t.Fatal(err) + } + if disabled.Generation == saved.Generation || disabled.Allows("/lab", saved.Generation) { + t.Fatal("disable did not invalidate") + } + p.Enabled = true + reenabled, err := s.SaveMachineLearningPolicy(ctx, domain.UUID, disabled.Generation, p) + if err != nil { + t.Fatal(err) + } + if reenabled.Allows("/lab", saved.Generation) { + t.Fatal("old consent resurrected") + } + start := make(chan struct{}) + results := make(chan error, 2) + for i := 0; i < 2; i++ { + go func() { + <-start + _, err := s.SaveMachineLearningPolicy(ctx, domain.UUID, reenabled.Generation, p) + results <- err + }() + } + close(start) + winners := 0 + for i := 0; i < 2; i++ { + err := <-results + if err == nil { + winners++ + } else if !errors.Is(err, ErrMachineLearningConflict) { + t.Fatal(err) + } + } + if winners != 1 { + t.Fatal("concurrent configuration lost update", winners) + } + if _, err = s.DB.ExecContext(ctx, `UPDATE config SET value=`+s.sqlParam(1)+` WHERE domain_uuid=`+s.sqlParam(2)+` AND `+s.sqlConfigKey()+`=`+s.sqlParam(3), `{"enabled":true}`, domain.UUID, machineLearningConfigKey); err != nil { + t.Fatal(err) + } + if _, err = s.MachineLearningPolicy(ctx, domain.UUID); !errors.Is(err, machinelearning.ErrPolicy) { + t.Fatal("corrupt policy did not fail closed", err) + } +} diff --git a/internal/store/mysql_migration_test.go b/internal/store/mysql_migration_test.go new file mode 100644 index 0000000..da07df1 --- /dev/null +++ b/internal/store/mysql_migration_test.go @@ -0,0 +1,166 @@ +package store + +import ( + "context" + "errors" + "strings" + "testing" + + "pageswiki/internal/db" +) + +func mysqlProbe(name string) db.MySQLOperation { + return db.MySQLOperation{SQL: "CREATE TABLE " + name + "(id BIGINT PRIMARY KEY) ENGINE=InnoDB", Check: "SELECT COUNT(*)=1 FROM information_schema.tables WHERE table_schema=DATABASE() AND table_name='" + name + "'", ReplaySafe: true} +} + +func TestMySQLMigrationRecovery(t *testing.T) { + s, _ := mlTestStore(t, storeMySQL) + ctx := context.Background() + a, b := mysqlProbe("migration_a"), mysqlProbe("migration_b") + // Second operation fails until an operator repairs the missing prerequisite. + b.SQL = "CREATE TABLE migration_b(id BIGINT PRIMARY KEY, parent BIGINT, FOREIGN KEY(parent) REFERENCES migration_parent(id)) ENGINE=InnoDB" + steps := []db.MySQLMigration{{Version: 1, Name: "recovery", Operations: []db.MySQLOperation{a, b}, Assertions: []string{a.Check, b.Check}}} + status, e := db.InspectMySQLMigrations(ctx, s.DB, "recovery", steps) + if e != nil || status.Applied != 0 || status.Pending != 1 { + t.Fatal(status, e) + } + var count int + if e = s.DB.QueryRow(`SELECT COUNT(*) FROM schema_mysql_migrations WHERE component='recovery'`).Scan(&count); e != nil || count != 0 { + t.Fatal("inspection wrote history", e) + } + if e = db.ApplyMySQLMigrations(ctx, s.DB, "recovery", steps); e == nil { + t.Fatal("expected DDL failure") + } + status, e = db.InspectMySQLMigrations(ctx, s.DB, "recovery", steps) + if e != nil || !status.Dirty || status.NextOperation != 1 { + t.Fatal("missing dirty progress", status, e) + } + if e = db.ApplyMySQLMigrations(ctx, s.DB, "recovery", steps); !errors.Is(e, db.ErrMySQLMigrationDirty) { + t.Fatal("silent retry", e) + } + if _, e = s.DB.Exec(`CREATE TABLE migration_parent(id BIGINT PRIMARY KEY) ENGINE=InnoDB`); e != nil { + t.Fatal(e) + } + if e = db.ResumeMySQLMigrations(ctx, s.DB, "recovery", steps); e != nil { + t.Fatal(e) + } + if e = db.ApplyMySQLMigrations(ctx, s.DB, "recovery", steps); e != nil { + t.Fatal("repeat apply", e) + } + // Simulate loss of journal acknowledgement after DDL committed. Resume must + // verify the postcondition and skip CREATE, not blindly replay it. + if _, e = s.DB.Exec(`UPDATE schema_mysql_migrations SET state='running',next_operation=0 WHERE component='recovery'`); e != nil { + t.Fatal(e) + } + if e = db.ResumeMySQLMigrations(ctx, s.DB, "recovery", steps); e != nil { + t.Fatal("DDL-before-journal recovery", e) + } + changed := append([]db.MySQLMigration(nil), steps...) + changed[0].Name = "changed" + if e = db.ApplyMySQLMigrations(ctx, s.DB, "recovery", changed); !errors.Is(e, db.ErrMySQLMigrationMismatch) { + t.Fatal("checksum mismatch accepted", e) + } + // Unknown future version must not be silently downgraded. + if _, e = s.DB.Exec(`UPDATE schema_mysql_migrations SET version=9 WHERE component='recovery'`); e != nil { + t.Fatal(e) + } + if _, e = db.InspectMySQLMigrations(ctx, s.DB, "recovery", steps); !errors.Is(e, db.ErrMySQLMigrationMismatch) { + t.Fatal("future version accepted", e) + } +} + +func TestMySQLMigrationConcurrencyAndDrift(t *testing.T) { + s, _ := mlTestStore(t, storeMySQL) + ctx := context.Background() + op := mysqlProbe("migration_concurrent") + steps := []db.MySQLMigration{{Version: 1, Name: "concurrent", Operations: []db.MySQLOperation{op}, Assertions: []string{op.Check}}} + start := make(chan struct{}) + results := make(chan error, 2) + for i := 0; i < 2; i++ { + go func() { <-start; results <- db.ApplyMySQLMigrations(ctx, s.DB, "concurrent", steps) }() + } + close(start) + for i := 0; i < 2; i++ { + if e := <-results; e != nil { + t.Fatal("concurrent apply", e) + } + } + if _, e := s.DB.Exec(`ALTER TABLE config DROP PRIMARY KEY`); e != nil { + t.Fatal(e) + } + if _, e := NewMySQLMLRepository(s.DB).InspectSchema(ctx); e == nil { + t.Fatal("schema drift accepted") + } + // Error responses must not include full SQL/driver data. + bad := mysqlProbe("secret_probe") + bad.SQL = "INVALID SQL private-secret" + broken := []db.MySQLMigration{{Version: 1, Name: "bad", Operations: []db.MySQLOperation{bad}, Assertions: []string{bad.Check}}} + if e := db.ApplyMySQLMigrations(ctx, s.DB, "bad", broken); e == nil || strings.Contains(e.Error(), "private-secret") { + t.Fatal("unsafe error", e) + } +} + +func TestMySQLMigrationRefusesUnsafeResumeAndAdoption(t *testing.T) { + s, _ := mlTestStore(t, storeMySQL) + ctx := context.Background() + op := mysqlProbe("migration_existing") + steps := []db.MySQLMigration{{Version: 1, Name: "existing", Operations: []db.MySQLOperation{op}, Assertions: []string{op.Check}}} + if _, e := s.DB.Exec(op.SQL); e != nil { + t.Fatal(e) + } + if e := db.ApplyMySQLMigrations(ctx, s.DB, "adopt", steps); !errors.Is(e, db.ErrMySQLMigrationMismatch) { + t.Fatal("implicit adoption", e) + } + unsafe := mysqlProbe("migration_unsafe") + unsafe.SQL = "INVALID SQL" + unsafe.ReplaySafe = false + steps = []db.MySQLMigration{{Version: 1, Name: "unsafe", Operations: []db.MySQLOperation{unsafe}, Assertions: []string{unsafe.Check}}} + if e := db.ApplyMySQLMigrations(ctx, s.DB, "unsafe", steps); e == nil { + t.Fatal("expected failure") + } + if e := db.ResumeMySQLMigrations(ctx, s.DB, "unsafe", steps); !errors.Is(e, db.ErrMySQLMigrationDirty) { + t.Fatal("unsafe replay", e) + } + cancelCtx, cancel := context.WithCancel(ctx) + cancel() + if e := db.ApplyMySQLMigrations(cancelCtx, s.DB, "unsafe", steps); e == nil { + t.Fatal("cancel ignored") + } + // A canceled caller must not retain the session lock in the connection pool. + if _, e := db.InspectMySQLMigrations(ctx, s.DB, "unsafe", steps); e != nil { + t.Fatal("lock not released", e) + } +} + +func TestMySQLMigrationVersionUpgrade(t *testing.T) { + s, _ := mlTestStore(t, storeMySQL) + ctx := context.Background() + op := mysqlProbe("migration_versioned") + firstCheck := `SELECT COUNT(*)=1 FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='migration_versioned'` + steps := []db.MySQLMigration{{Version: 1, Name: "initial", Operations: []db.MySQLOperation{op}, Assertions: []string{firstCheck}}} + if e := db.ApplyMySQLMigrations(ctx, s.DB, "versioned", steps); e != nil { + t.Fatal(e) + } + added := db.MySQLOperation{SQL: `ALTER TABLE migration_versioned ADD COLUMN label VARCHAR(64) NOT NULL DEFAULT ''`, Check: `SELECT COUNT(*)=1 FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='migration_versioned' AND column_name='label'`, ReplaySafe: true} + steps = append(steps, db.MySQLMigration{Version: 2, Name: "label", Operations: []db.MySQLOperation{added}, Assertions: []string{op.Check, added.Check}}) + if e := db.ApplyMySQLMigrations(ctx, s.DB, "versioned", steps); e != nil { + t.Fatal(e) + } + // Version 1's shape assertion is intentionally obsolete after the upgrade. + status, e := db.InspectMySQLMigrations(ctx, s.DB, "versioned", steps) + if e != nil || status.Applied != 2 || status.Pending != 0 || status.Dirty { + t.Fatal(status, e) + } + if e := db.ApplyMySQLMigrations(ctx, s.DB, "versioned", steps); e != nil { + t.Fatal(e) + } + if _, e := db.InspectMySQLMigrations(ctx, s.DB, "versioned", steps[:1]); !errors.Is(e, db.ErrMySQLMigrationMismatch) { + t.Fatal("downgrade accepted", e) + } + if _, e := s.DB.Exec(`ALTER TABLE schema_mysql_migrations DROP PRIMARY KEY`); e != nil { + t.Fatal(e) + } + if _, e := db.InspectMySQLMigrations(ctx, s.DB, "versioned", steps); !errors.Is(e, db.ErrMySQLMigrationMismatch) { + t.Fatal("damaged journal accepted", e) + } +} diff --git a/internal/store/mysql_ml_schema.sql b/internal/store/mysql_ml_schema.sql new file mode 100644 index 0000000..58c3975 --- /dev/null +++ b/internal/store/mysql_ml_schema.sql @@ -0,0 +1,25 @@ +-- Native MySQL ML component schema. Applied only by the journaled runner. +CREATE TABLE config ( + domain_uuid VARCHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + `key` VARCHAR(128) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + value LONGTEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL, + updated_at BIGINT NOT NULL, + PRIMARY KEY(domain_uuid,`key`) +) ENGINE=InnoDB; +CREATE TABLE ml_daily_budget ( + domain_uuid VARCHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + day CHAR(10) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + reserved_bytes BIGINT NOT NULL CHECK(reserved_bytes>=0), + PRIMARY KEY(domain_uuid,day) +) ENGINE=InnoDB; +CREATE TABLE ml_budget_receipts ( + domain_uuid VARCHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + request_uuid VARCHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + day CHAR(10) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + input_hash CHAR(64) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + generation VARCHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + reserved_bytes BIGINT NOT NULL CHECK(reserved_bytes>0), + state VARCHAR(16) CHARACTER SET ascii COLLATE ascii_bin NOT NULL CHECK(state IN ('reserved','completed','unknown')), + actual_tokens BIGINT NOT NULL DEFAULT 0 CHECK(actual_tokens>=0), + PRIMARY KEY(domain_uuid,request_uuid) +) ENGINE=InnoDB; diff --git a/internal/store/namespace_mysql.go b/internal/store/namespace_mysql.go new file mode 100644 index 0000000..55d06cd --- /dev/null +++ b/internal/store/namespace_mysql.go @@ -0,0 +1,114 @@ +package store + +import ( + "context" + "database/sql" + "errors" + "strings" + "unicode/utf8" + + "github.com/google/uuid" +) + +// MySQLNamespaceRepository exposes only the ported subset. In particular Domain +// mutations and Campus deletion require auth/federation repositories which are +// not ported yet. No *Store escapes and no server backend is enabled here. +type MySQLNamespaceRepository struct{ store *Store } + +func NewMySQLNamespaceRepository(database *sql.DB) *MySQLNamespaceRepository { + return &MySQLNamespaceRepository{store: &Store{DB: database, sqlBackend: storeMySQL}} +} + +func mysqlStoreError(operation string, err error) error { + if err == nil { + return nil + } + for _, known := range []error{sql.ErrNoRows, context.Canceled, context.DeadlineExceeded, ErrReadOnly, ErrBackendFeatureUnavailable, ErrAccessDenied} { + if errors.Is(err, known) { + return known + } + } + var validation namespaceValidationError + if errors.As(err, &validation) { + return validation + } + // Duplicate/truncation/encoding errors may contain private names or values. + // operation is an owned constant, not a request parameter. + return errors.New("MySQL " + operation + " failed") +} + +func (r *MySQLNamespaceRepository) Campuses(ctx context.Context) ([]Campus, error) { + return r.store.ListCampusesContext(ctx) +} +func (r *MySQLNamespaceRepository) Domains(ctx context.Context) ([]Domain, error) { + return r.store.ListDomainsContext(ctx) +} +func (r *MySQLNamespaceRepository) ResolveHost(ctx context.Context, host string) (*Domain, error) { + return r.store.GetDomainByHostContext(ctx, host) +} +func (r *MySQLNamespaceRepository) EffectiveHost(ctx context.Context, domain string) (string, error) { + if err := mysqlNamespaceUUID(domain); err != nil { + return "", err + } + return r.store.GetDomainEffectiveHostContext(ctx, domain) +} +func (r *MySQLNamespaceRepository) CreateCampus(ctx context.Context, name, title, language, mode, fqdn string, enabled bool) error { + if utf8.RuneCountInString(normalizeCampusName(name)) > 255 { + return namespaceValidationError("campus name too long") + } + return r.store.CreateCampusContext(ctx, name, title, language, mode, fqdn, enabled) +} +func (r *MySQLNamespaceRepository) UpdateCampus(ctx context.Context, id int64, name, title, language, mode, fqdn string, enabled bool) error { + if strings.EqualFold(strings.TrimSpace(mode), "managed") { + return namespaceValidationError("managed campus must be added through controller enrollment") + } + if utf8.RuneCountInString(normalizeCampusName(name)) > 255 { + return namespaceValidationError("campus name too long") + } + return r.store.UpdateCampusContext(ctx, id, name, title, language, mode, fqdn, enabled) +} +func mysqlNamespaceUUID(value string) error { + id, err := uuid.Parse(value) + if err != nil || id.String() != value { + return namespaceValidationError("canonical domain UUID required") + } + return nil +} +func mysqlNamespaceConfigKey(domain, key string) error { + if err := mysqlNamespaceUUID(domain); err != nil { + return err + } + if !utf8.ValidString(key) || utf8.RuneCountInString(key) > 255 { + return namespaceValidationError("configuration key invalid or too long") + } + return nil +} +func (r *MySQLNamespaceRepository) Config(ctx context.Context, domain, key string) (string, error) { + if err := mysqlNamespaceConfigKey(domain, key); err != nil { + return "", err + } + if _, err := r.store.GetDomainByUUIDContext(ctx, domain); err != nil { + return "", err + } + return r.store.GetConfigInDomainContext(ctx, domain, key) +} +func (r *MySQLNamespaceRepository) SetConfig(ctx context.Context, domain, key, value string) error { + if r.store.ReadOnly { + return ErrReadOnly + } + if err := mysqlNamespaceConfigKey(domain, key); err != nil { + return err + } + // ML policy writes must retain generation CAS; the generic config API is + // not a second way to overwrite an active reservation's policy. + if key == machineLearningConfigKey { + return namespaceValidationError("use ML policy compare-and-swap") + } + return r.store.namespaceWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { + var found int + if err := tx.QueryRowContext(ctx, `SELECT 1 FROM domains WHERE uuid=?`, domain).Scan(&found); err != nil { + return err + } + return r.store.setConfigWith(ctx, tx, domain, key, value) + }) +} diff --git a/internal/store/namespace_mysql_schema.go b/internal/store/namespace_mysql_schema.go new file mode 100644 index 0000000..dcb7b70 --- /dev/null +++ b/internal/store/namespace_mysql_schema.go @@ -0,0 +1,68 @@ +package store + +import ( + "context" + + "pageswiki/internal/db" +) + +func mysqlNamespaceMigrations() []db.MySQLMigration { + // config remains owned by the existing machine-learning migration ledger; + // do not adopt it into a second history or change the published v1 checksum. + statements := []string{ + `CREATE TABLE campuses(id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,uuid VARCHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL UNIQUE,name VARCHAR(255) NOT NULL UNIQUE,title LONGTEXT NOT NULL,default_lang VARCHAR(64) NOT NULL DEFAULT 'en',authority_mode VARCHAR(32) NOT NULL DEFAULT 'standalone',fqdn VARCHAR(253) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT 'localhost',controller_transport VARCHAR(8) NOT NULL DEFAULT 'https',last_contact_at BIGINT NOT NULL DEFAULT 0,last_contact_error TEXT NOT NULL DEFAULT (''),enabled INTEGER NOT NULL DEFAULT 1,created_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin`, + `CREATE TABLE domains(id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,uuid VARCHAR(36) CHARACTER SET ascii COLLATE ascii_bin NOT NULL UNIQUE,name VARCHAR(255) NOT NULL UNIQUE,title LONGTEXT NOT NULL,domain VARCHAR(253) CHARACTER SET ascii COLLATE ascii_bin NOT NULL DEFAULT '',enabled INTEGER NOT NULL DEFAULT 1,created_at BIGINT NOT NULL,campus_uuid VARCHAR(36) CHARACTER SET ascii COLLATE ascii_bin,placement VARCHAR(32) NOT NULL DEFAULT 'local',instance_fqdn VARCHAR(253) NOT NULL DEFAULT '',instance_fingerprint VARCHAR(255) NOT NULL DEFAULT '',INDEX idx_domains_campus_uuid(campus_uuid)) ENGINE=InnoDB DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_bin`, + `CREATE TABLE namespace_write_lock(id INTEGER NOT NULL PRIMARY KEY,CHECK(id=1)) ENGINE=InnoDB`, + } + // The postconditions cover columns, keys, identities and the lock table. + checks := []string{ + mysqlNamespaceTableCheck("campuses", "id:bigint:NO:|uuid:varchar(36):NO:ascii_bin|name:varchar(255):NO:utf8mb4_0900_bin|title:longtext:NO:utf8mb4_0900_bin|default_lang:varchar(64):NO:utf8mb4_0900_bin|authority_mode:varchar(32):NO:utf8mb4_0900_bin|fqdn:varchar(253):NO:ascii_bin|controller_transport:varchar(8):NO:utf8mb4_0900_bin|last_contact_at:bigint:NO:|last_contact_error:text:NO:utf8mb4_0900_bin|enabled:int:NO:|created_at:bigint:NO:"), + mysqlNamespaceTableCheck("domains", "id:bigint:NO:|uuid:varchar(36):NO:ascii_bin|name:varchar(255):NO:utf8mb4_0900_bin|title:longtext:NO:utf8mb4_0900_bin|domain:varchar(253):NO:ascii_bin|enabled:int:NO:|created_at:bigint:NO:|campus_uuid:varchar(36):YES:ascii_bin|placement:varchar(32):NO:utf8mb4_0900_bin|instance_fqdn:varchar(253):NO:utf8mb4_0900_bin|instance_fingerprint:varchar(255):NO:utf8mb4_0900_bin"), + mysqlMLTableCheck("namespace_write_lock", "id:int:NO:", "id", 1), + } + var ops []db.MySQLOperation + for i, statement := range statements { + ops = append(ops, db.MySQLOperation{SQL: statement, Check: checks[i], ReplaySafe: true}) + } + return []db.MySQLMigration{{Version: 1, Name: "Campus and Domain read model", Operations: ops, Assertions: checks}} +} + +// Owned identifiers only. No user SQL is interpolated here. +func mysqlNamespaceTableCheck(table, columns string) string { + return mysqlMLTableCheck(table, columns, "id", 0) + ` AND (SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=DATABASE() AND table_name='` + table + `' AND column_name='id' AND extra='auto_increment')=1 + AND (SELECT COUNT(*) FROM (SELECT index_name FROM information_schema.statistics WHERE table_schema=DATABASE() AND table_name='` + table + `' AND non_unique=0 GROUP BY index_name HAVING COUNT(*)=1 AND MAX(column_name) IN ('uuid','name')) AS unique_keys)=2` +} +func (r *MySQLNamespaceRepository) PrepareSchema(ctx context.Context) error { + if err := NewMySQLMLRepository(r.store.DB).PrepareSchema(ctx); err != nil { + return err + } + return db.ApplyMySQLMigrations(ctx, r.store.DB, "store-namespaces", mysqlNamespaceMigrations()) +} +func (r *MySQLNamespaceRepository) InspectSchema(ctx context.Context) (db.MySQLMigrationStatus, error) { + base, err := NewMySQLMLRepository(r.store.DB).InspectSchema(ctx) + if err != nil { + return db.MySQLMigrationStatus{}, err + } + namespace, err := db.InspectMySQLMigrations(ctx, r.store.DB, "store-namespaces", mysqlNamespaceMigrations()) + if err != nil { + return namespace, err + } + // Counts include dependencies; identify the first component to repair. + combined := db.MySQLMigrationStatus{Applied: base.Applied + namespace.Applied, Pending: base.Pending + namespace.Pending, Dirty: base.Dirty || namespace.Dirty} + if base.Dirty { + combined.DirtyComponent, combined.NextOperation = base.DirtyComponent, base.NextOperation + } else if namespace.Dirty { + combined.DirtyComponent, combined.NextOperation = namespace.DirtyComponent, namespace.NextOperation + } + return combined, nil +} +func (r *MySQLNamespaceRepository) ResumeSchema(ctx context.Context) error { + status, err := NewMySQLMLRepository(r.store.DB).InspectSchema(ctx) + if err != nil { + return err + } + if status.Dirty || status.Pending != 0 { + return db.ErrMySQLMigrationMismatch + } + return db.ResumeMySQLMigrations(ctx, r.store.DB, "store-namespaces", mysqlNamespaceMigrations()) +} diff --git a/internal/store/namespace_mysql_test.go b/internal/store/namespace_mysql_test.go new file mode 100644 index 0000000..c4ba63e --- /dev/null +++ b/internal/store/namespace_mysql_test.go @@ -0,0 +1,364 @@ +package store + +import ( + "context" + "database/sql" + "errors" + "fmt" + "strings" + "testing" + "time" + + "github.com/google/uuid" + "pageswiki/internal/db" +) + +// Bootstrap is fixture-only. The public facade intentionally cannot create a +// Domain until built-in groups and inherited permissions are ported together. +func testNamespaceCoreStore(t *testing.T, backend storeSQLBackend) *Store { + t.Helper() + if backend != storeMySQL { + return testNamespaceStore(t, backend) + } + s, _ := mlTestStore(t, backend) + r := &MySQLNamespaceRepository{store: s} + ctx := context.Background() + if e := r.PrepareSchema(ctx); e != nil { + t.Fatal(e) + } + if e := r.PrepareSchema(ctx); e != nil { + t.Fatal("repeat prepare", e) + } + if status, e := r.InspectSchema(ctx); e != nil || status.Pending != 0 || status.Dirty { + t.Fatal("inspect", status, e) + } + if e := r.CreateCampus(ctx, "default", "Default Campus", "en", "standalone", "localhost", true); e != nil { + t.Fatal(e) + } + campus, e := s.GetDefaultCampus() + if e != nil { + t.Fatal(e) + } + seedNamespaceDomain(t, s, campus.UUID, "default", "") + return s +} + +func TestNamespaceCoreThreeBackendContract(t *testing.T) { + for _, backend := range []storeSQLBackend{storeSQLite, storePostgreSQL, storeMySQL} { + t.Run(fmt.Sprint(backend), func(t *testing.T) { + s := testNamespaceCoreStore(t, backend) + ctx := context.Background() + create, update := s.CreateCampusContext, s.UpdateCampusContext + read, write := s.GetConfigInDomainContext, s.SetConfigInDomainContext + resolve, effective := s.GetDomainByHostContext, s.GetDomainEffectiveHostContext + if backend == storeMySQL { + r := &MySQLNamespaceRepository{store: s} + create, update, read, write, resolve, effective = r.CreateCampus, r.UpdateCampus, r.Config, r.SetConfig, r.ResolveHost, r.EffectiveHost + } + campus, e := s.GetDefaultCampus() + if e != nil { + t.Fatal(e) + } + domain, e := s.GetDefaultDomain() + if e != nil { + t.Fatal(e) + } + if e := update(ctx, campus.ID, "default", "キャンパス 🏫", "ja", "standalone", "pages.example.test", true); e != nil { + t.Fatal(e) + } + if e := create(ctx, "OTHER", "別キャンパス", "en", "standalone", "other.example.test", true); e != nil { + t.Fatal(e) + } + campuses, e := s.ListCampusesContext(ctx) + if e != nil || len(campuses) != 2 { + t.Fatal(campuses, e) + } + var other Campus + for _, c := range campuses { + if c.UUID != campus.UUID { + other = c + } + } + short := seedNamespaceDomain(t, s, campus.UUID, "short", "www") + absolute := seedNamespaceDomain(t, s, other.UUID, "absolute", "www.example.test") + for host, want := range map[string]string{"PAGES.EXAMPLE.TEST:443": domain.UUID, "www.pages.example.test": short.UUID, "www.example.test": absolute.UUID} { + got, e := resolve(ctx, host) + if e != nil || got.UUID != want { + t.Fatal("host resolution", host, e) + } + } + if got, e := effective(ctx, short.UUID); e != nil || got != "www.pages.example.test" { + t.Fatal(got, e) + } + if _, e := resolve(ctx, "absent.example.test"); !errors.Is(e, sql.ErrNoRows) { + t.Fatal("fallback", e) + } + if e := update(ctx, campus.ID, "default", "must rollback", "en", "standalone", "example.test", true); e == nil { + t.Fatal("host collision accepted") + } + current, e := s.GetCampusByUUIDContext(ctx, campus.UUID) + if e != nil || current.Title != "キャンパス 🏫" || current.FQDN != "pages.example.test" { + t.Fatal("failed update persisted", current, e) + } + if e := update(ctx, campus.ID, "default", "disabled", "en", "standalone", "pages.example.test", false); e == nil { + t.Fatal("referenced Campus disabled") + } + if e := create(ctx, "managed", "Managed", "en", "managed", "managed.example.test", true); e == nil { + t.Fatal("managed creation bypassed enrollment") + } + keys := []string{"Key", "key", "key ", "日本語", "é", "e\u0301"} + for i, key := range keys { + for _, id := range []string{short.UUID, absolute.UUID} { + v := fmt.Sprintf("%s-%d-本文 🗒️\n? ' \"", id, i) + if e := write(ctx, id, key, "old"); e != nil { + t.Fatal(e) + } + if e := write(ctx, id, key, v); e != nil { + t.Fatal(e) + } + } + } + for i, key := range keys { + for _, id := range []string{short.UUID, absolute.UUID} { + want := fmt.Sprintf("%s-%d-本文 🗒️\n? ' \"", id, i) + if got, e := read(ctx, id, key); e != nil || got != want { + t.Fatal("config isolation/normalization", key, got, e) + } + } + } + if got, e := read(ctx, short.UUID, "missing"); e != nil || got != "" { + t.Fatal(got, e) + } + // Two distinct names claiming the same FQDN must not both commit. + start, results := make(chan struct{}), make(chan error, 2) + for i := 0; i < 2; i++ { + go func(i int) { + <-start + results <- create(ctx, fmt.Sprintf("race-%d", i), "Race", "en", "standalone", "race.example.test", true) + }(i) + } + close(start) + success := 0 + for i := 0; i < 2; i++ { + if <-results == nil { + success++ + } + } + if success != 1 { + t.Fatal("topology serialization", success) + } + cancelled, cancel := context.WithCancel(ctx) + cancel() + if e := create(cancelled, "cancelled", "Canceled", "en", "standalone", "cancelled.example.test", true); !errors.Is(e, context.Canceled) { + t.Fatal("create cancellation", e) + } + if e := update(cancelled, campus.ID, "default", "Canceled", "en", "standalone", "pages.example.test", true); !errors.Is(e, context.Canceled) { + t.Fatal("update cancellation", e) + } + if e := write(cancelled, short.UUID, "cancelled", "private"); !errors.Is(e, context.Canceled) { + t.Fatal("config cancellation", e) + } + if _, e := resolve(cancelled, "pages.example.test"); !errors.Is(e, context.Canceled) { + t.Fatal("read cancellation", e) + } + s.ReadOnly = true + if e := create(ctx, "readonly", "Readonly", "en", "standalone", "readonly.example.test", true); !errors.Is(e, ErrReadOnly) { + t.Fatal("readonly create", e) + } + if e := update(ctx, campus.ID, "default", "Readonly", "en", "standalone", "pages.example.test", true); !errors.Is(e, ErrReadOnly) { + t.Fatal("readonly update", e) + } + }) + } +} + +func TestMySQLNamespaceBoundaryAndRollback(t *testing.T) { + s := testNamespaceCoreStore(t, storeMySQL) + r := &MySQLNamespaceRepository{store: s} + ctx := context.Background() + domain, e := s.GetDefaultDomain() + if e != nil { + t.Fatal(e) + } + for _, bad := range []string{domain.UUID + " ", strings.ToUpper(domain.UUID), "invalid"} { + if e := r.SetConfig(ctx, bad, "key", "secret"); e == nil { + t.Fatal("noncanonical UUID", bad) + } + } + if e := r.SetConfig(ctx, uuid.NewString(), "key", "secret"); !errors.Is(e, sql.ErrNoRows) { + t.Fatal("orphan config", e) + } + if e := r.SetConfig(ctx, domain.UUID, machineLearningConfigKey, "{}"); e == nil { + t.Fatal("CAS bypass") + } + if e := r.SetConfig(ctx, domain.UUID, strings.Repeat("k", 256), "secret"); e == nil { + t.Fatal("oversize key") + } + campus, e := s.GetDefaultCampus() + if e != nil { + t.Fatal(e) + } + if e := r.UpdateCampus(ctx, campus.ID, "default", "Inherited", "en", " MANAGED ", "controller.example.test", true); e == nil { + t.Fatal("enrollment bypassed by update") + } + for _, unsupported := range []func() error{ + s.EnsureDomainsSchema, s.EnsureCampusesSchema, s.EnsureConfigTable, + func() error { return s.DeleteDomain(domain.ID) }, + func() error { return s.DeleteCampus(1) }, + } { + if e := unsupported(); !errors.Is(e, ErrBackendFeatureUnavailable) { + t.Fatal("unported operation not refused", e) + } + } + if e := s.CreateDomain(domain.CampusUUID, "no-auth-schema", "No auth schema", "no-auth", "local", "", "", true); e == nil { + t.Fatal("Domain created without auth dependencies") + } + if _, e := s.GetDomainByHost("no-auth.localhost"); !errors.Is(e, sql.ErrNoRows) { + t.Fatal("partial Domain remains", e) + } + if e := r.CreateCampus(ctx, "default", "private-title", "en", "standalone", "private-host.example.test", true); e == nil || strings.Contains(e.Error(), "private") || strings.Contains(e.Error(), "Duplicate") { + t.Fatal("unsafe error", e) + } + // Reserve the topology lock, mutate, then abort. Neither changes nor lock + // survive rollback. This verifies the lock is transactional, not session-only. + e = s.namespaceWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { + if _, e := tx.ExecContext(ctx, `UPDATE domains SET title='must rollback' WHERE uuid=?`, domain.UUID); e != nil { + return e + } + return ErrReadOnly + }) + if !errors.Is(e, ErrReadOnly) { + t.Fatal(e) + } + got, e := s.GetDomainByUUID(domain.UUID) + if e != nil || got.Title != domain.Title { + t.Fatal("rollback failed", got, e) + } + deadline, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + if e := r.CreateCampus(deadline, "after-rollback", "Works", "en", "standalone", "after.example.test", true); e != nil { + t.Fatal("retained lock", e) + } + s.ReadOnly = true + if e := r.SetConfig(ctx, domain.UUID, "readonly", "secret"); !errors.Is(e, ErrReadOnly) { + t.Fatal("readonly config", e) + } + s.ReadOnly = false + if _, e := s.DB.Exec(`ALTER TABLE campuses DROP INDEX name`); e != nil { + t.Fatal(e) + } + if _, e := r.InspectSchema(ctx); e == nil { + t.Fatal("missing unique index accepted") + } +} + +func TestMySQLNamespaceLockDeadline(t *testing.T) { + s := testNamespaceCoreStore(t, storeMySQL) + r := &MySQLNamespaceRepository{store: s} + ctx := context.Background() + tx, e := s.DB.BeginTx(ctx, nil) + if e != nil { + t.Fatal(e) + } + defer tx.Rollback() + if _, e := tx.ExecContext(ctx, `UPDATE namespace_write_lock SET id=id WHERE id=1`); e != nil { + t.Fatal(e) + } + deadline, cancel := context.WithTimeout(ctx, 80*time.Millisecond) + defer cancel() + if e := r.CreateCampus(deadline, "timeout", "Private", "en", "standalone", "timeout.example.test", true); !errors.Is(e, context.DeadlineExceeded) { + t.Fatal("lock ignored deadline", e) + } + if e := tx.Rollback(); e != nil { + t.Fatal(e) + } + deadline2, cancel2 := context.WithTimeout(ctx, 3*time.Second) + defer cancel2() + if e := r.CreateCampus(deadline2, "timeout", "Works", "en", "standalone", "timeout.example.test", true); e != nil { + t.Fatal("canceled transaction retained lock/data", e) + } +} + +func TestMySQLNamespaceSchemaResume(t *testing.T) { + s, _ := mlTestStore(t, storeMySQL) + ctx := context.Background() + r := &MySQLNamespaceRepository{store: s} + if e := r.PrepareSchema(ctx); e != nil { + t.Fatal(e) + } + if _, e := s.DB.Exec(`UPDATE schema_mysql_migrations SET state='running',next_operation=1 WHERE component='store-namespaces'`); e != nil { + t.Fatal(e) + } + if e := r.PrepareSchema(ctx); !errors.Is(e, db.ErrMySQLMigrationDirty) { + t.Fatal(e) + } + if e := r.ResumeSchema(ctx); e != nil { + t.Fatal(e) + } +} + +func TestMySQLConfigVersionOneUpgrade(t *testing.T) { + database := mysqlTestDatabase(t) + ctx := context.Background() + steps := mysqlMLMigrations() + if e := db.ApplyMySQLMigrations(ctx, database, "machine-learning", steps[:1]); e != nil { + t.Fatal(e) + } + domain := uuid.NewString() + if _, e := database.Exec("INSERT INTO config(domain_uuid,`key`,value,updated_at) VALUES(?,'Existing','本文 📝',123)", domain); e != nil { + t.Fatal(e) + } + var originalHash string + if e := database.QueryRow(`SELECT checksum FROM schema_mysql_migrations WHERE component='machine-learning' AND version=1`).Scan(&originalHash); e != nil { + t.Fatal(e) + } + r := NewMySQLNamespaceRepository(database) + status, e := r.InspectSchema(ctx) + if e != nil || status.Pending != 2 || status.Applied != 1 { + t.Fatal(status, e) + } + if e := r.PrepareSchema(ctx); e != nil { + t.Fatal(e) + } + var value, hash string + if e := database.QueryRow("SELECT value FROM config WHERE domain_uuid=? AND `key`='Existing'", domain).Scan(&value); e != nil || value != "本文 📝" { + t.Fatal("data lost", value, e) + } + if e := database.QueryRow(`SELECT checksum FROM schema_mysql_migrations WHERE component='machine-learning' AND version=1`).Scan(&hash); e != nil || hash != originalHash { + t.Fatal("v1 history changed", e) + } + // Simulate ALTER committed before its acknowledgement; the v2 resume + // checks the new collation and must not re-adopt or destroy config data. + if _, e := database.Exec(`UPDATE schema_mysql_migrations SET state='running',next_operation=0 WHERE component='machine-learning' AND version=2`); e != nil { + t.Fatal(e) + } + if e := r.ResumeSchema(ctx); e == nil { + t.Fatal("dirty prerequisite ignored") + } + status, e = r.InspectSchema(ctx) + if e != nil || !status.Dirty || status.DirtyComponent != "machine-learning" { + t.Fatal(status, e) + } + if e := NewMySQLMLRepository(database).ResumeSchema(ctx); e != nil { + t.Fatal(e) + } + if e := r.ResumeSchema(ctx); e != nil { + t.Fatal(e) + } + // Each pooled connection must refuse truncation, even if the server's + // global defaults are permissive. Hold both open to force two connections. + for i := 0; i < 2; i++ { + connection, e := database.Conn(ctx) + if e != nil { + t.Fatal(e) + } + defer connection.Close() + var mode string + if e := connection.QueryRowContext(ctx, `SELECT @@SESSION.sql_mode`).Scan(&mode); e != nil || !strings.Contains(mode, "STRICT_ALL_TABLES") { + t.Fatal("strict mode not set", e) + } + if _, e := connection.ExecContext(ctx, "INSERT INTO config(domain_uuid,`key`,value,updated_at) VALUES(?,?,?,0)", domain, strings.Repeat("k", 256), "must not truncate"); e == nil { + t.Fatal("silently truncated oversized key") + } + } +} diff --git a/internal/store/schema_modules.go b/internal/store/schema_modules.go index 61d3d11..c5be876 100644 --- a/internal/store/schema_modules.go +++ b/internal/store/schema_modules.go @@ -12,12 +12,13 @@ import ( // Once released, add a new version; never edit an applied definition. // Auth, City, tasks and calendars remain in their existing migration paths. var managedStoreSchemas = map[string][]db.SQLMigration{ - "feeds": feedMigrations, - "contacts": contactMigrations, - "task-productivity": taskProductivityMigrations, - "cli-auth": cliAuthMigrations, - "profile-contacts": profileContactMigrations, - "event-jobs": eventJobMigrations, + "machine-learning-budget": mlBudgetMigrations, + "feeds": feedMigrations, + "contacts": contactMigrations, + "task-productivity": taskProductivityMigrations, + "cli-auth": cliAuthMigrations, + "profile-contacts": profileContactMigrations, + "event-jobs": eventJobMigrations, "projection-metadata": {{Version: 1, Name: "adopt_projection_metadata", Statements: []string{ `CREATE TABLE IF NOT EXISTS projection_metadata ( document_hash TEXT NOT NULL,kind TEXT NOT NULL,version INTEGER NOT NULL, diff --git a/internal/store/sql_backend.go b/internal/store/sql_backend.go index ced4c42..0546375 100644 --- a/internal/store/sql_backend.go +++ b/internal/store/sql_backend.go @@ -18,6 +18,8 @@ type storeSQLBackend uint8 const ( storeSQLite storeSQLBackend = iota storePostgreSQL + // Restricted to ported component facades; never used for serving Pages. + storeMySQL ) var ErrPostgreSQLComponentNotReady = errors.New("PostgreSQL component dependencies are not ported") @@ -41,6 +43,26 @@ func (s *Store) sqlValues(n int) string { } return strings.Join(parts, ",") } +func (s *Store) sqlConfigKey() string { + if s.sqlBackend == storeMySQL { + return "`key`" + } + return "key" +} +func (s *Store) sqlGroupTable() string { + if s.sqlBackend == storeMySQL { + return "`groups`" + } + return "groups" +} + +// Owned identifiers only. This is a statement suffix, not SQL rewriting. +func (s *Store) sqlConflictDoNothing(table, primary, conflict string) string { + if s.sqlBackend == storeMySQL { + return " ON DUPLICATE KEY UPDATE `" + primary + "`=`" + table + "`.`" + primary + "`" + } + return " ON CONFLICT(" + conflict + ") DO NOTHING" +} func (s *Store) sqlHasDot(expression string) string { if s.sqlBackend == storePostgreSQL { return "strpos(" + expression + ", '.') > 0" @@ -48,6 +70,15 @@ func (s *Store) sqlHasDot(expression string) string { return "instr(" + expression + ", '.') > 0" } +// Only owned SQL expressions, never user input. MySQL's || is logical OR +// without a special sql_mode; do not change session modes to emulate SQLite. +func (s *Store) sqlConcat(expressions ...string) string { + if s.sqlBackend == storeMySQL { + return "CONCAT(" + strings.Join(expressions, ",") + ")" + } + return strings.Join(expressions, " || ") +} + // Owned expressions only. C/BINARY ordering makes '%' and '_' literal and // keeps segment ranges case-sensitive, independent of database locale. func (s *Store) pathScopeSQL(parent, child string) string { @@ -70,6 +101,9 @@ func (s *Store) sqlStringPosition(expression, literal string) string { } func (s *Store) sqlError(operation string, err error) error { + if s.sqlBackend == storeMySQL { + return mysqlStoreError(operation, err) + } if s.sqlBackend != storePostgreSQL || err == nil { return err } @@ -143,6 +177,10 @@ func (s *Store) administrativeWrite(ctx context.Context, sqliteReservation strin defer tx.Rollback() if s.sqlBackend == storePostgreSQL { _, err = tx.ExecContext(ctx, `SELECT pg_advisory_xact_lock(1885431653, 1853058931)`) + } else if s.sqlBackend == storeMySQL { + // A real row lock, held until commit/rollback. A WHERE 0 update does + // not reserve a writer on InnoDB. Insert also covers first-use races. + _, err = tx.ExecContext(ctx, `INSERT INTO namespace_write_lock(id) VALUES(1) ON DUPLICATE KEY UPDATE id=1`) } else { _, err = tx.ExecContext(ctx, sqliteReservation) }