2026-10-04 12:24:13 +02:00
|
|
|
package store_test
|
|
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"context"
|
|
|
|
|
"database/sql"
|
|
|
|
|
"errors"
|
feat: account menu, database roles, and single logout
Bundles the console work from the current branch: the header account
control, database-backed roles and permissions, and signing out across
the applications that share this sign-in.
The account control replaces a separate identity chip and a separate
sign-out button, which meant the header carried two controls describing
one fact. web/account.js is mounted into every page by a placeholder and
owns the keyboard handling, the outside-click behaviour and the sign-out
form once. It also fills the trigger's name, which the previous markup
left empty.
Signing out revokes the hosted-login bearer sessions this installation
issued, then redirects to the provider's end_session_endpoint when the
discovery document advertises one. Applications that authenticate
against this installation therefore lose their session too; one pointed
straight at an identity provider is out of its reach and is unchanged.
Roles and permissions become rows rather than a closed enum, so a tenant
can extend the catalog without a migration, and a role can no longer be
granted a capability that is not in it. requireSameOrigin now compares
against the origin the request arrived on instead of the configured base
URL, which defaulted to http://localhost:8080 and so rejected every
write in a deployment that never set it.
Two bugs found while verifying in a browser:
- A profile picture never rendered. avatarURL built an absolute URL
from the configured base URL, and the page's own img-src 'self'
blocked it. The console's own pages now take a root-relative path;
only /connect/userinfo, read from another origin, needs an absolute
one, and it follows the request.
- absoluteURL preferred the configuration over the request while its
comment claimed the opposite, which also misdirected the logout
redirect.
Card layout: the footer was one two-column row shared between a label
and a forty-character identifier, so the identifier took the width and
crushed its label into three stacked words. Each pair is a line now, the
value truncates with the full text in the title, and cards align their
footers across a row.
2026-10-05 19:18:07 +02:00
|
|
|
"net/url"
|
2026-10-04 12:24:13 +02:00
|
|
|
"os"
|
|
|
|
|
"strings"
|
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
|
|
"github.com/danyel/go-loose/internal/contract"
|
|
|
|
|
"github.com/danyel/go-loose/internal/database"
|
|
|
|
|
"github.com/danyel/go-loose/internal/role"
|
|
|
|
|
"github.com/danyel/go-loose/internal/store"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// integrationStore opens the disposable PostgreSQL database named by
|
|
|
|
|
// GO_LOOSE_TEST_DATABASE_URL, drops every table, and applies all migrations. The
|
|
|
|
|
// test is skipped when the variable is absent so unit runs never touch a
|
|
|
|
|
// developer's data.
|
|
|
|
|
func integrationStore(t *testing.T) (*store.Store, *sql.DB, context.Context) {
|
|
|
|
|
t.Helper()
|
|
|
|
|
url := os.Getenv("GO_LOOSE_TEST_DATABASE_URL")
|
|
|
|
|
if url == "" {
|
|
|
|
|
t.Skip("set GO_LOOSE_TEST_DATABASE_URL to run PostgreSQL integration tests")
|
|
|
|
|
}
|
feat: account menu, database roles, and single logout
Bundles the console work from the current branch: the header account
control, database-backed roles and permissions, and signing out across
the applications that share this sign-in.
The account control replaces a separate identity chip and a separate
sign-out button, which meant the header carried two controls describing
one fact. web/account.js is mounted into every page by a placeholder and
owns the keyboard handling, the outside-click behaviour and the sign-out
form once. It also fills the trigger's name, which the previous markup
left empty.
Signing out revokes the hosted-login bearer sessions this installation
issued, then redirects to the provider's end_session_endpoint when the
discovery document advertises one. Applications that authenticate
against this installation therefore lose their session too; one pointed
straight at an identity provider is out of its reach and is unchanged.
Roles and permissions become rows rather than a closed enum, so a tenant
can extend the catalog without a migration, and a role can no longer be
granted a capability that is not in it. requireSameOrigin now compares
against the origin the request arrived on instead of the configured base
URL, which defaulted to http://localhost:8080 and so rejected every
write in a deployment that never set it.
Two bugs found while verifying in a browser:
- A profile picture never rendered. avatarURL built an absolute URL
from the configured base URL, and the page's own img-src 'self'
blocked it. The console's own pages now take a root-relative path;
only /connect/userinfo, read from another origin, needs an absolute
one, and it follows the request.
- absoluteURL preferred the configuration over the request while its
comment claimed the opposite, which also misdirected the logout
redirect.
Card layout: the footer was one two-column row shared between a label
and a forty-character identifier, so the identifier took the width and
crushed its label into three stacked words. Each pair is a line now, the
value truncates with the full text in the title, and cards align their
footers across a row.
2026-10-05 19:18:07 +02:00
|
|
|
requireScratchDatabase(t, url)
|
2026-10-04 12:24:13 +02:00
|
|
|
ctx := context.Background()
|
|
|
|
|
db, err := database.Open(ctx, url)
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("open database: %v", err)
|
|
|
|
|
}
|
|
|
|
|
t.Cleanup(func() { db.Close() })
|
|
|
|
|
if err := resetSchema(ctx, db); err != nil {
|
|
|
|
|
t.Fatalf("reset schema: %v", err)
|
|
|
|
|
}
|
|
|
|
|
if err := database.Migrate(ctx, db); err != nil {
|
|
|
|
|
t.Fatalf("migrate: %v", err)
|
|
|
|
|
}
|
|
|
|
|
return store.New(db), db, ctx
|
|
|
|
|
}
|
|
|
|
|
|
feat: account menu, database roles, and single logout
Bundles the console work from the current branch: the header account
control, database-backed roles and permissions, and signing out across
the applications that share this sign-in.
The account control replaces a separate identity chip and a separate
sign-out button, which meant the header carried two controls describing
one fact. web/account.js is mounted into every page by a placeholder and
owns the keyboard handling, the outside-click behaviour and the sign-out
form once. It also fills the trigger's name, which the previous markup
left empty.
Signing out revokes the hosted-login bearer sessions this installation
issued, then redirects to the provider's end_session_endpoint when the
discovery document advertises one. Applications that authenticate
against this installation therefore lose their session too; one pointed
straight at an identity provider is out of its reach and is unchanged.
Roles and permissions become rows rather than a closed enum, so a tenant
can extend the catalog without a migration, and a role can no longer be
granted a capability that is not in it. requireSameOrigin now compares
against the origin the request arrived on instead of the configured base
URL, which defaulted to http://localhost:8080 and so rejected every
write in a deployment that never set it.
Two bugs found while verifying in a browser:
- A profile picture never rendered. avatarURL built an absolute URL
from the configured base URL, and the page's own img-src 'self'
blocked it. The console's own pages now take a root-relative path;
only /connect/userinfo, read from another origin, needs an absolute
one, and it follows the request.
- absoluteURL preferred the configuration over the request while its
comment claimed the opposite, which also misdirected the logout
redirect.
Card layout: the footer was one two-column row shared between a label
and a forty-character identifier, so the identifier took the width and
crushed its label into three stacked words. Each pair is a line now, the
value truncates with the full text in the title, and cards align their
footers across a row.
2026-10-05 19:18:07 +02:00
|
|
|
// requireScratchDatabase refuses to run against anything that looks like a real
|
|
|
|
|
// database. resetSchema drops every table in the public schema, so pointing
|
|
|
|
|
// these tests at a development database destroys it. The database name must
|
|
|
|
|
// contain "test" unless the operator opts out explicitly.
|
|
|
|
|
func requireScratchDatabase(t *testing.T, rawURL string) {
|
|
|
|
|
t.Helper()
|
|
|
|
|
if os.Getenv("GO_LOOSE_TEST_DATABASE_DESTRUCTIVE") == "1" {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
parsed, err := url.Parse(rawURL)
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("parse GO_LOOSE_TEST_DATABASE_URL: %v", err)
|
|
|
|
|
}
|
|
|
|
|
name := strings.TrimPrefix(parsed.Path, "/")
|
|
|
|
|
if !strings.Contains(strings.ToLower(name), "test") {
|
|
|
|
|
t.Fatalf("refusing to run integration tests against database %q: resetSchema drops every table. "+
|
|
|
|
|
"Point GO_LOOSE_TEST_DATABASE_URL at a scratch database whose name contains \"test\" "+
|
|
|
|
|
"(run `make integration-db` to create one), or set GO_LOOSE_TEST_DATABASE_DESTRUCTIVE=1 to override.", name)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-04 12:24:13 +02:00
|
|
|
// grantApplicationAccess inserts an application grant directly so that tests can
|
|
|
|
|
// build states the management API intentionally refuses to create, such as a
|
|
|
|
|
// grant for a user with no membership.
|
|
|
|
|
func grantApplicationAccess(t *testing.T, db *sql.DB, ctx context.Context, applicationID, userID string) {
|
|
|
|
|
t.Helper()
|
|
|
|
|
if _, err := db.ExecContext(ctx, `
|
|
|
|
|
INSERT INTO user_application_access(application_id, user_id, granted_by)
|
|
|
|
|
VALUES ($1, $2, $2)`, applicationID, userID); err != nil {
|
|
|
|
|
t.Fatalf("grant application access: %v", err)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func contractDocument() contract.Document {
|
|
|
|
|
return contract.Document{
|
|
|
|
|
Version: "3.1.0",
|
|
|
|
|
JSON: []byte(`{"openapi":"3.1.0","paths":{"/health":{"get":{"operationId":"health"}}}}`),
|
|
|
|
|
Endpoints: []contract.Endpoint{{Method: "GET", Path: "/health", OperationID: "health"}},
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// resetSchema drops every table in the public schema, including
|
|
|
|
|
// schema_migrations, so that Migrate replays the full history from scratch.
|
|
|
|
|
func resetSchema(ctx context.Context, db *sql.DB) error {
|
|
|
|
|
rows, err := db.QueryContext(ctx, `
|
|
|
|
|
SELECT tablename FROM pg_tables WHERE schemaname = 'public'`)
|
|
|
|
|
if err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
defer rows.Close()
|
|
|
|
|
tables := make([]string, 0)
|
|
|
|
|
for rows.Next() {
|
|
|
|
|
var name string
|
|
|
|
|
if err := rows.Scan(&name); err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
tables = append(tables, `"`+name+`"`)
|
|
|
|
|
}
|
|
|
|
|
if err := rows.Err(); err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
for _, name := range tables {
|
|
|
|
|
if _, err := db.ExecContext(ctx, "DROP TABLE IF EXISTS "+name+" CASCADE"); err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// newUser creates or reuses an account and returns its id.
|
|
|
|
|
func newUser(t *testing.T, s *store.Store, ctx context.Context, email string) string {
|
|
|
|
|
t.Helper()
|
|
|
|
|
user, err := s.UpsertUser(ctx, "test:"+email, email, strings.ToUpper(email[:1])+email[1:])
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("upsert %s: %v", email, err)
|
|
|
|
|
}
|
|
|
|
|
return user.ID
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// newTenant creates a tenant owned by owner and registers one application.
|
|
|
|
|
func newTenant(t *testing.T, s *store.Store, ctx context.Context, owner, slug string) store.Tenant {
|
|
|
|
|
t.Helper()
|
|
|
|
|
tenant, err := s.CreateTenant(ctx, owner, slug, strings.ToUpper(slug))
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("create tenant %s: %v", slug, err)
|
|
|
|
|
}
|
|
|
|
|
return tenant
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-04 16:57:30 +02:00
|
|
|
// addMember invites a member into the tenant with the given built-in role.
|
2026-10-04 12:24:13 +02:00
|
|
|
func addMember(t *testing.T, s *store.Store, ctx context.Context, owner string, tenantID, email, membershipRole string) string {
|
|
|
|
|
t.Helper()
|
2026-10-04 16:57:30 +02:00
|
|
|
roleID, err := s.SystemRoleID(ctx, membershipRole)
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("look up role %q: %v", membershipRole, err)
|
|
|
|
|
}
|
|
|
|
|
member, err := s.InviteUser(ctx, owner, tenantID, email, email, roleID, "not-a-real-hash")
|
2026-10-04 12:24:13 +02:00
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("invite %s as %s: %v", email, membershipRole, err)
|
|
|
|
|
}
|
|
|
|
|
if member.Role != membershipRole {
|
|
|
|
|
t.Fatalf("invited role = %q, want %q", member.Role, membershipRole)
|
|
|
|
|
}
|
|
|
|
|
return member.ID
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestMigrationsApplyAndRolesAreAccepted(t *testing.T) {
|
|
|
|
|
s, _, ctx := integrationStore(t)
|
|
|
|
|
owner := newUser(t, s, ctx, "owner@example.test")
|
|
|
|
|
tenant := newTenant(t, s, ctx, owner, "nmbs")
|
2026-10-04 16:57:30 +02:00
|
|
|
for _, item := range []string{"developer", "operator", "user"} {
|
|
|
|
|
addMember(t, s, ctx, owner, tenant.ID, item+"@example.test", item)
|
2026-10-04 12:24:13 +02:00
|
|
|
}
|
|
|
|
|
if _, err := s.ListTenants(ctx, owner); err != nil {
|
|
|
|
|
t.Fatalf("list tenants: %v", err)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-04 16:57:30 +02:00
|
|
|
func TestUnknownRoleIDIsRefused(t *testing.T) {
|
2026-10-04 12:24:13 +02:00
|
|
|
s, _, ctx := integrationStore(t)
|
|
|
|
|
owner := newUser(t, s, ctx, "owner@example.test")
|
|
|
|
|
tenant := newTenant(t, s, ctx, owner, "nmbs")
|
2026-10-04 16:57:30 +02:00
|
|
|
member := addMember(t, s, ctx, owner, tenant.ID, "member@example.test", "viewer")
|
|
|
|
|
if err := s.SetUserAccess(ctx, owner, tenant.ID, member, "00000000-0000-0000-0000-000000000000", nil); err == nil {
|
|
|
|
|
t.Fatal("assigning a role that does not exist must be refused")
|
2026-10-04 12:24:13 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestPermissionMatrixIsEnforcedInQueries(t *testing.T) {
|
|
|
|
|
s, _, ctx := integrationStore(t)
|
|
|
|
|
owner := newUser(t, s, ctx, "owner@example.test")
|
|
|
|
|
tenant := newTenant(t, s, ctx, owner, "nmbs")
|
|
|
|
|
application, err := s.CreateApplication(ctx, owner, store.Application{
|
|
|
|
|
TenantID: tenant.ID, Slug: "guess", Name: "Guess", AllowedHosts: []string{},
|
|
|
|
|
})
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("owner cannot create an application: %v", err)
|
|
|
|
|
}
|
|
|
|
|
tests := []struct {
|
2026-10-04 16:57:30 +02:00
|
|
|
role string
|
2026-10-04 12:24:13 +02:00
|
|
|
canCreateApp bool
|
|
|
|
|
canIssueKey bool
|
|
|
|
|
canSaveContract bool
|
|
|
|
|
canListManaged bool
|
|
|
|
|
canConfigureClien bool
|
|
|
|
|
}{
|
2026-10-04 16:57:30 +02:00
|
|
|
// owner and admin administer members; developer and operator may also
|
|
|
|
|
// maintain their own tenant's members, which is why they can list them.
|
|
|
|
|
{role: "owner", canCreateApp: true, canIssueKey: true, canSaveContract: true, canListManaged: true, canConfigureClien: true},
|
|
|
|
|
{role: "admin", canCreateApp: true, canIssueKey: true, canSaveContract: true, canListManaged: true, canConfigureClien: true},
|
|
|
|
|
{role: "developer", canCreateApp: true, canIssueKey: true, canSaveContract: true, canListManaged: true, canConfigureClien: true},
|
|
|
|
|
{role: "operator", canCreateApp: false, canIssueKey: true, canSaveContract: true, canListManaged: true, canConfigureClien: false},
|
|
|
|
|
{role: "viewer", canCreateApp: false, canIssueKey: false, canSaveContract: false, canListManaged: false, canConfigureClien: false},
|
|
|
|
|
{role: "user", canCreateApp: false, canIssueKey: false, canSaveContract: false, canListManaged: false, canConfigureClien: false},
|
2026-10-04 12:24:13 +02:00
|
|
|
}
|
|
|
|
|
for _, test := range tests {
|
2026-10-04 16:57:30 +02:00
|
|
|
t.Run(test.role, func(t *testing.T) {
|
|
|
|
|
member := addMember(t, s, ctx, owner, tenant.ID, test.role+"@example.test", test.role)
|
|
|
|
|
slug := strings.ReplaceAll(test.role, "owner", "own")
|
2026-10-04 12:24:13 +02:00
|
|
|
|
|
|
|
|
_, err := s.CreateApplication(ctx, member, store.Application{
|
|
|
|
|
TenantID: tenant.ID, Slug: slug, Name: slug, AllowedHosts: []string{},
|
|
|
|
|
})
|
|
|
|
|
assertPermission(t, "create application", err, test.canCreateApp)
|
|
|
|
|
|
|
|
|
|
_, err = s.CreateAPIKey(ctx, member, application.ID, slug+"-key", "gl_prefix", secretHash(slug), nil)
|
|
|
|
|
assertPermission(t, "issue key", err, test.canIssueKey)
|
|
|
|
|
|
|
|
|
|
_, err = s.SaveContract(ctx, member, application.ID, contractDocument(), nil)
|
|
|
|
|
assertPermission(t, "import contract", err, test.canSaveContract)
|
|
|
|
|
|
|
|
|
|
managed, err := s.ListManagedUsers(ctx, member)
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("list managed users: %v", err)
|
|
|
|
|
}
|
|
|
|
|
if test.canListManaged != (len(managed) > 0) {
|
|
|
|
|
t.Fatalf("users.read for %s: got %d members, want non-empty=%v", test.role, len(managed), test.canListManaged)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
_, err = s.ConfigureClient(ctx, member, application.ID, []string{"https://app.example.test/callback"}, secretHash(slug))
|
|
|
|
|
assertPermission(t, "configure client login", err, test.canConfigureClien)
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestConsoleAccessExcludesSelfServiceMembers(t *testing.T) {
|
|
|
|
|
s, _, ctx := integrationStore(t)
|
|
|
|
|
owner := newUser(t, s, ctx, "owner@example.test")
|
|
|
|
|
tenant := newTenant(t, s, ctx, owner, "nmbs")
|
2026-10-04 16:57:30 +02:00
|
|
|
selfService := addMember(t, s, ctx, owner, tenant.ID, "enduser@example.test", "user")
|
|
|
|
|
operator := addMember(t, s, ctx, owner, tenant.ID, "operator@example.test", "operator")
|
2026-10-04 12:24:13 +02:00
|
|
|
waiting := newUser(t, s, ctx, "waiting@example.test")
|
|
|
|
|
|
|
|
|
|
for _, test := range []struct {
|
|
|
|
|
name string
|
|
|
|
|
userID string
|
|
|
|
|
console bool
|
|
|
|
|
member bool
|
|
|
|
|
}{
|
|
|
|
|
{name: "owner", userID: owner, console: true, member: true},
|
|
|
|
|
{name: "operator", userID: operator, console: true, member: true},
|
|
|
|
|
{name: "self-service user", userID: selfService, console: false, member: true},
|
|
|
|
|
{name: "waiting room", userID: waiting, console: false, member: false},
|
|
|
|
|
} {
|
|
|
|
|
t.Run(test.name, func(t *testing.T) {
|
|
|
|
|
console, err := s.HasConsoleAccess(ctx, test.userID)
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("HasConsoleAccess: %v", err)
|
|
|
|
|
}
|
|
|
|
|
if console != test.console {
|
|
|
|
|
t.Fatalf("HasConsoleAccess = %v, want %v", console, test.console)
|
|
|
|
|
}
|
|
|
|
|
member, err := s.HasMembership(ctx, test.userID)
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("HasMembership: %v", err)
|
|
|
|
|
}
|
|
|
|
|
if member != test.member {
|
|
|
|
|
t.Fatalf("HasMembership = %v, want %v", member, test.member)
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestTenantPermissionsComeFromTheRoleMatrix(t *testing.T) {
|
|
|
|
|
s, _, ctx := integrationStore(t)
|
|
|
|
|
owner := newUser(t, s, ctx, "owner@example.test")
|
|
|
|
|
tenant := newTenant(t, s, ctx, owner, "nmbs")
|
2026-10-04 16:57:30 +02:00
|
|
|
developer := addMember(t, s, ctx, owner, tenant.ID, "dev@example.test", "developer")
|
2026-10-04 12:24:13 +02:00
|
|
|
|
|
|
|
|
tenants, err := s.ListTenants(ctx, developer)
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("list tenants: %v", err)
|
|
|
|
|
}
|
2026-10-04 16:57:30 +02:00
|
|
|
if len(tenants) != 1 || tenants[0].Role != "developer" {
|
2026-10-04 12:24:13 +02:00
|
|
|
t.Fatalf("tenants = %+v", tenants)
|
|
|
|
|
}
|
|
|
|
|
if !contains(tenants[0].Permissions, string(role.ManageApplications)) {
|
|
|
|
|
t.Fatalf("developer permissions = %v", tenants[0].Permissions)
|
|
|
|
|
}
|
2026-10-04 16:57:30 +02:00
|
|
|
// developer administers members but must not mint roles, which is what
|
|
|
|
|
// defines privilege in the first place.
|
|
|
|
|
if !contains(tenants[0].Permissions, string(role.ManageUsers)) {
|
|
|
|
|
t.Fatalf("developer permissions = %v, want users.manage", tenants[0].Permissions)
|
|
|
|
|
}
|
|
|
|
|
if contains(tenants[0].Permissions, string(role.ManageRoles)) {
|
|
|
|
|
t.Fatalf("developer permissions = %v, must not manage roles", tenants[0].Permissions)
|
2026-10-04 12:24:13 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestProfileRoundTrip(t *testing.T) {
|
|
|
|
|
s, _, ctx := integrationStore(t)
|
|
|
|
|
owner := newUser(t, s, ctx, "owner@example.test")
|
|
|
|
|
tenant := newTenant(t, s, ctx, owner, "nmbs")
|
2026-10-04 16:57:30 +02:00
|
|
|
member := addMember(t, s, ctx, owner, tenant.ID, "member@example.test", "operator")
|
2026-10-04 12:24:13 +02:00
|
|
|
|
|
|
|
|
before, err := s.Profile(ctx, member)
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("profile: %v", err)
|
|
|
|
|
}
|
|
|
|
|
if before.AvatarKey != nil || before.NameCustomized {
|
|
|
|
|
t.Fatalf("fresh profile = %+v", before)
|
|
|
|
|
}
|
2026-10-04 16:57:30 +02:00
|
|
|
if len(before.Memberships) != 1 || before.Memberships[0].Role != "operator" {
|
2026-10-04 12:24:13 +02:00
|
|
|
t.Fatalf("memberships = %+v", before.Memberships)
|
|
|
|
|
}
|
|
|
|
|
if !contains(before.Memberships[0].Permissions, string(role.ManageKeys)) {
|
|
|
|
|
t.Fatalf("membership permissions = %v", before.Memberships[0].Permissions)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
name := "Renamed By User"
|
|
|
|
|
if err := s.UpdateProfile(ctx, member, store.ProfileUpdate{DisplayName: &name}); err != nil {
|
|
|
|
|
t.Fatalf("rename: %v", err)
|
|
|
|
|
}
|
|
|
|
|
after, err := s.Profile(ctx, member)
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("profile after rename: %v", err)
|
|
|
|
|
}
|
|
|
|
|
if after.DisplayName != name || !after.NameCustomized || after.ProfileUpdatedAt == nil {
|
|
|
|
|
t.Fatalf("profile = %+v", after)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestLoginDoesNotOverwriteACustomizedDisplayName(t *testing.T) {
|
|
|
|
|
s, _, ctx := integrationStore(t)
|
|
|
|
|
user := newUser(t, s, ctx, "person@example.test")
|
|
|
|
|
name := "My Chosen Name"
|
|
|
|
|
if err := s.UpdateProfile(ctx, user, store.ProfileUpdate{DisplayName: &name}); err != nil {
|
|
|
|
|
t.Fatalf("rename: %v", err)
|
|
|
|
|
}
|
|
|
|
|
for range 2 {
|
|
|
|
|
if _, err := s.UpsertUser(ctx, "google:1234", "person@example.test", "Identity Provider Name"); err != nil {
|
|
|
|
|
t.Fatalf("upsert: %v", err)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
profile, err := s.Profile(ctx, user)
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("profile: %v", err)
|
|
|
|
|
}
|
|
|
|
|
if profile.DisplayName != name {
|
|
|
|
|
t.Fatalf("display name = %q, want %q", profile.DisplayName, name)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestUncustomizedDisplayNameStillFollowsTheIdentityProvider(t *testing.T) {
|
|
|
|
|
s, _, ctx := integrationStore(t)
|
|
|
|
|
user := newUser(t, s, ctx, "person@example.test")
|
|
|
|
|
if _, err := s.UpsertUser(ctx, "google:1234", "person@example.test", "Identity Provider Name"); err != nil {
|
|
|
|
|
t.Fatalf("upsert: %v", err)
|
|
|
|
|
}
|
|
|
|
|
profile, err := s.Profile(ctx, user)
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("profile: %v", err)
|
|
|
|
|
}
|
|
|
|
|
if profile.DisplayName != "Identity Provider Name" {
|
|
|
|
|
t.Fatalf("display name = %q", profile.DisplayName)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestPictureIsStoredAndReadableByKey(t *testing.T) {
|
|
|
|
|
s, _, ctx := integrationStore(t)
|
|
|
|
|
owner := newUser(t, s, ctx, "owner@example.test")
|
|
|
|
|
tenant := newTenant(t, s, ctx, owner, "nmbs")
|
2026-10-04 16:57:30 +02:00
|
|
|
member := addMember(t, s, ctx, owner, tenant.ID, "member@example.test", "viewer")
|
2026-10-04 12:24:13 +02:00
|
|
|
key := "Zq1Yb3l0Rk9pT2h3ZjQ4eXh3YjFkNGQ3OTFhMmNkYThl"
|
|
|
|
|
payload := []byte{0x89, 'P', 'N', 'G', 1, 2, 3, 4}
|
|
|
|
|
|
|
|
|
|
if err := s.UpdateProfile(ctx, member, store.ProfileUpdate{
|
|
|
|
|
AvatarKey: key, AvatarData: payload, ContentType: "image/png",
|
|
|
|
|
}); err != nil {
|
|
|
|
|
t.Fatalf("store picture: %v", err)
|
|
|
|
|
}
|
|
|
|
|
picture, err := s.Picture(ctx, key)
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("load picture: %v", err)
|
|
|
|
|
}
|
|
|
|
|
if picture.ContentType != "image/png" || string(picture.Data) != string(payload) {
|
|
|
|
|
t.Fatalf("picture = %+v", picture)
|
|
|
|
|
}
|
|
|
|
|
if picture.UpdatedAt.IsZero() {
|
|
|
|
|
t.Fatal("picture must record when it was stored")
|
|
|
|
|
}
|
|
|
|
|
profile, err := s.Profile(ctx, member)
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("profile: %v", err)
|
|
|
|
|
}
|
|
|
|
|
if profile.AvatarKey == nil || *profile.AvatarKey != key || profile.AvatarUpdatedAt == nil {
|
|
|
|
|
t.Fatalf("profile avatar = %+v", profile)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if err := s.UpdateProfile(ctx, member, store.ProfileUpdate{RemoveAvatar: true}); err != nil {
|
|
|
|
|
t.Fatalf("remove picture: %v", err)
|
|
|
|
|
}
|
|
|
|
|
if _, err := s.Picture(ctx, key); !errors.Is(err, store.ErrNotFound) {
|
|
|
|
|
t.Fatalf("Picture() error = %v, want ErrNotFound", err)
|
|
|
|
|
}
|
|
|
|
|
cleared, err := s.Profile(ctx, member)
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("profile: %v", err)
|
|
|
|
|
}
|
|
|
|
|
if cleared.AvatarKey != nil || cleared.AvatarUpdatedAt != nil {
|
|
|
|
|
t.Fatalf("profile still advertises a picture: %+v", cleared)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestReplacingAPictureRetiresTheOldKey(t *testing.T) {
|
|
|
|
|
s, _, ctx := integrationStore(t)
|
|
|
|
|
user := newUser(t, s, ctx, "person@example.test")
|
|
|
|
|
first := "Zq1Yb3l0Rk9pT2h3ZjQ4eXh3YjFkNGQ3OTFhMmNkYThl"
|
|
|
|
|
second := "b3JkZXJ5a2V5Zm9ydGhlU2Vjb25kVXBvZGF0ZVRlc3QxMjM0NQ"
|
|
|
|
|
if err := s.UpdateProfile(ctx, user, store.ProfileUpdate{AvatarKey: first, AvatarData: []byte("a"), ContentType: "image/png"}); err != nil {
|
|
|
|
|
t.Fatalf("store first picture: %v", err)
|
|
|
|
|
}
|
|
|
|
|
if err := s.UpdateProfile(ctx, user, store.ProfileUpdate{AvatarKey: second, AvatarData: []byte("b"), ContentType: "image/png"}); err != nil {
|
|
|
|
|
t.Fatalf("store second picture: %v", err)
|
|
|
|
|
}
|
|
|
|
|
if _, err := s.Picture(ctx, first); !errors.Is(err, store.ErrNotFound) {
|
|
|
|
|
t.Fatalf("the replaced key must stop resolving, got %v", err)
|
|
|
|
|
}
|
|
|
|
|
picture, err := s.Picture(ctx, second)
|
|
|
|
|
if err != nil || string(picture.Data) != "b" {
|
|
|
|
|
t.Fatalf("picture = %+v, err = %v", picture, err)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestPictureKeysAreUnique(t *testing.T) {
|
|
|
|
|
s, _, ctx := integrationStore(t)
|
|
|
|
|
first, second := newUser(t, s, ctx, "one@example.test"), newUser(t, s, ctx, "two@example.test")
|
|
|
|
|
key := "Zq1Yb3l0Rk9pT2h3ZjQ4eXh3YjFkNGQ3OTFhMmNkYThl"
|
|
|
|
|
if err := s.UpdateProfile(ctx, first, store.ProfileUpdate{AvatarKey: key, AvatarData: []byte("a"), ContentType: "image/png"}); err != nil {
|
|
|
|
|
t.Fatalf("store first picture: %v", err)
|
|
|
|
|
}
|
|
|
|
|
if err := s.UpdateProfile(ctx, second, store.ProfileUpdate{AvatarKey: key, AvatarData: []byte("b"), ContentType: "image/png"}); err == nil {
|
|
|
|
|
t.Fatal("two users must not be able to claim the same picture key")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestIncompletePictureIsRejectedByTheDatabase(t *testing.T) {
|
|
|
|
|
s, _, ctx := integrationStore(t)
|
|
|
|
|
user := newUser(t, s, ctx, "person@example.test")
|
|
|
|
|
err := s.UpdateProfile(ctx, user, store.ProfileUpdate{AvatarKey: "Zq1Yb3l0Rk9pT2h3ZjQ4eXh3YjFkNGQ3OTFhMmNkYThl"})
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("an update without picture bytes is a no-op, got %v", err)
|
|
|
|
|
}
|
|
|
|
|
if _, err := s.Picture(ctx, "Zq1Yb3l0Rk9pT2h3ZjQ4eXh3YjFkNGQ3OTFhMmNkYThl"); !errors.Is(err, store.ErrNotFound) {
|
|
|
|
|
t.Fatalf("Picture() error = %v, want ErrNotFound", err)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestClientSessionReportsMembershipRoleAndPicture(t *testing.T) {
|
|
|
|
|
s, db, ctx := integrationStore(t)
|
|
|
|
|
owner := newUser(t, s, ctx, "owner@example.test")
|
|
|
|
|
tenant := newTenant(t, s, ctx, owner, "nmbs")
|
|
|
|
|
application, err := s.CreateApplication(ctx, owner, store.Application{
|
|
|
|
|
TenantID: tenant.ID, Slug: "guess", Name: "Guess", AllowedHosts: []string{},
|
|
|
|
|
})
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("create application: %v", err)
|
|
|
|
|
}
|
2026-10-04 16:57:30 +02:00
|
|
|
member := addMember(t, s, ctx, owner, tenant.ID, "member@example.test", "operator")
|
2026-10-04 12:24:13 +02:00
|
|
|
if _, err := s.ConfigureClient(ctx, owner, application.ID, []string{"https://app.example.test/callback"}, []byte("hash")); err != nil {
|
|
|
|
|
t.Fatalf("configure client: %v", err)
|
|
|
|
|
}
|
|
|
|
|
if err := s.UpdateProfile(ctx, member, store.ProfileUpdate{
|
|
|
|
|
AvatarKey: "Zq1Yb3l0Rk9pT2h3ZjQ4eXh3YjFkNGQ3OTFhMmNkYThl",
|
|
|
|
|
AvatarData: []byte("a"), ContentType: "image/png",
|
|
|
|
|
}); err != nil {
|
|
|
|
|
t.Fatalf("store picture: %v", err)
|
|
|
|
|
}
|
|
|
|
|
grantApplicationAccess(t, db, ctx, application.ID, member)
|
|
|
|
|
if err := s.CreateAuthorizationCode(ctx, application.ID, member, "https://app.example.test/callback", []byte("code-hash")); err != nil {
|
|
|
|
|
t.Fatalf("create authorization code: %v", err)
|
|
|
|
|
}
|
|
|
|
|
user, _, err := s.ExchangeAuthorizationCode(ctx, application.ClientID, "https://app.example.test/callback", []byte("hash"), []byte("code-hash"), []byte("token-hash"))
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("exchange authorization code: %v", err)
|
|
|
|
|
}
|
2026-10-04 16:57:30 +02:00
|
|
|
if user.Role != "operator" {
|
2026-10-04 12:24:13 +02:00
|
|
|
t.Fatalf("role = %q, want operator", user.Role)
|
|
|
|
|
}
|
|
|
|
|
if user.AvatarKey == nil {
|
|
|
|
|
t.Fatal("the client payload must expose the picture locator")
|
|
|
|
|
}
|
|
|
|
|
byToken, err := s.ClientUserByToken(ctx, []byte("token-hash"))
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("client user by token: %v", err)
|
|
|
|
|
}
|
2026-10-04 16:57:30 +02:00
|
|
|
if byToken.Role != "operator" || byToken.AvatarKey == nil {
|
2026-10-04 12:24:13 +02:00
|
|
|
t.Fatalf("client user = %+v", byToken)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func TestClientSessionWithoutMembershipFallsBackToUserRole(t *testing.T) {
|
|
|
|
|
s, db, ctx := integrationStore(t)
|
|
|
|
|
owner := newUser(t, s, ctx, "owner@example.test")
|
|
|
|
|
tenant := newTenant(t, s, ctx, owner, "nmbs")
|
|
|
|
|
application, err := s.CreateApplication(ctx, owner, store.Application{
|
|
|
|
|
TenantID: tenant.ID, Slug: "guess", Name: "Guess", AllowedHosts: []string{},
|
|
|
|
|
})
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("create application: %v", err)
|
|
|
|
|
}
|
|
|
|
|
orphan := newUser(t, s, ctx, "orphan@example.test")
|
|
|
|
|
if _, err := s.ConfigureClient(ctx, owner, application.ID, []string{"https://app.example.test/cb"}, []byte("hash")); err != nil {
|
|
|
|
|
t.Fatalf("configure client: %v", err)
|
|
|
|
|
}
|
|
|
|
|
grantApplicationAccess(t, db, ctx, application.ID, orphan)
|
|
|
|
|
if err := s.CreateAuthorizationCode(ctx, application.ID, orphan, "https://app.example.test/cb", []byte("code")); err != nil {
|
|
|
|
|
t.Fatalf("create authorization code: %v", err)
|
|
|
|
|
}
|
|
|
|
|
user, _, err := s.ExchangeAuthorizationCode(ctx, application.ClientID, "https://app.example.test/cb", []byte("hash"), []byte("code"), []byte("token"))
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("exchange authorization code: %v", err)
|
|
|
|
|
}
|
2026-10-04 16:57:30 +02:00
|
|
|
if user.Role != "user" {
|
|
|
|
|
t.Fatalf("role = %q, want the least privileged fallback %q", user.Role, "user")
|
2026-10-04 12:24:13 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func assertPermission(t *testing.T, operation string, err error, allowed bool) {
|
|
|
|
|
t.Helper()
|
|
|
|
|
switch {
|
|
|
|
|
case allowed && err != nil:
|
|
|
|
|
t.Fatalf("%s must be allowed, got %v", operation, err)
|
|
|
|
|
case !allowed && !errors.Is(err, store.ErrNotFound):
|
|
|
|
|
t.Fatalf("%s must be denied with ErrNotFound, got %v", operation, err)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// secretHash builds a distinct digest per key name because secret_hash is unique.
|
|
|
|
|
func secretHash(name string) []byte {
|
|
|
|
|
return []byte("sha256-of-" + name)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func contains(values []string, want string) bool {
|
|
|
|
|
for _, item := range values {
|
|
|
|
|
if item == want {
|
|
|
|
|
return true
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return false
|
|
|
|
|
}
|
test: drive the whole application over HTTP, and serialise migrations
The behaviour suite in internal/behaviour installs the application into an
empty database through the web installer, signs in, walks every flow, and then
replaces the process to confirm the state was persisted rather than held in
memory. It found four defects, each fixed here or in the preceding commit:
- Migrate was not safe to run from two instances at once. CREATE TABLE IF NOT
EXISTS is not race free in PostgreSQL and collided on the pg_type unique
index, and two replicas could apply the same file. The run now holds a
session-level advisory lock, so a rolling deployment waits instead of failing.
- Bootstrap refused ownership whenever a tenant held any member, so installing
with the demonstration seed and then setting a local administrator password
produced an account that could never reach the console. It now grants
ownership only while the tenant has no owner, which still never takes a tenant
over from one that does.
Three of the fixes are covered by store-level regression tests in the same
commit: the ownership rule, the duplicate tenant slug conflict, and concurrent
migration runs.
The suite is skipped by go test ./... because it needs a scratch database and
the Google credentials for the installer. Run it with make behaviour-test, which
also resets the database afterwards. make test no longer inherits the database
variables, so unit runs need nothing.
Completes the earlier correction to the docs: the role matrix lives in the
database rather than in internal/role, and a local administrator claims the
system administrator role when no Google account has.
2026-10-05 19:37:09 +02:00
|
|
|
|
|
|
|
|
// TestBootstrapGrantsOwnershipOnlyWhileTheTenantHasNone pins the rule that a
|
|
|
|
|
// bootstrapped account becomes a tenant's owner only when nobody owns it yet. The
|
|
|
|
|
// installer's demonstration seed creates tenants that already hold members, and
|
|
|
|
|
// refusing ownership there used to leave a local administrator with an account
|
|
|
|
|
// that could never reach the console.
|
|
|
|
|
func TestBootstrapGrantsOwnershipOnlyWhileTheTenantHasNone(t *testing.T) {
|
|
|
|
|
s, db, ctx := integrationStore(t)
|
|
|
|
|
owner := newUser(t, s, ctx, "owner@example.test")
|
|
|
|
|
tenant := newTenant(t, s, ctx, owner, "bootstrap")
|
|
|
|
|
// Leave the tenant holding administrators but no owner, which is the state the
|
|
|
|
|
// installer's demonstration seed produces.
|
|
|
|
|
adminRole, err := s.SystemRoleID(ctx, "admin")
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("look up the admin role: %v", err)
|
|
|
|
|
}
|
|
|
|
|
if _, err := db.ExecContext(ctx,
|
|
|
|
|
`UPDATE memberships SET role_id = $1 WHERE tenant_id = $2`, adminRole, tenant.ID); err != nil {
|
|
|
|
|
t.Fatalf("demote the owner: %v", err)
|
|
|
|
|
}
|
|
|
|
|
addMember(t, s, ctx, owner, tenant.ID, "member@example.test", "admin")
|
|
|
|
|
late := newUser(t, s, ctx, "late@example.test")
|
|
|
|
|
|
|
|
|
|
if err := s.Bootstrap(ctx, late, tenant.Slug, "guess"); err != nil {
|
|
|
|
|
t.Fatalf("bootstrap into a tenant with no owner: %v", err)
|
|
|
|
|
}
|
|
|
|
|
assertRole(t, db, ctx, late, tenant.ID, "owner")
|
|
|
|
|
|
|
|
|
|
// A further account must not displace the owner that now exists.
|
|
|
|
|
third := newUser(t, s, ctx, "third@example.test")
|
|
|
|
|
if err := s.Bootstrap(ctx, third, tenant.Slug, "guess"); err != nil {
|
|
|
|
|
t.Fatalf("bootstrap again: %v", err)
|
|
|
|
|
}
|
|
|
|
|
var memberships int
|
|
|
|
|
if err := db.QueryRowContext(ctx, `
|
|
|
|
|
SELECT count(*) FROM memberships m
|
|
|
|
|
JOIN roles r ON r.id = m.role_id
|
|
|
|
|
WHERE m.tenant_id = $1 AND r.slug = 'owner'`, tenant.ID).Scan(&memberships); err != nil {
|
|
|
|
|
t.Fatalf("count owners: %v", err)
|
|
|
|
|
}
|
|
|
|
|
if memberships != 1 {
|
|
|
|
|
t.Errorf("owners = %d, want exactly one", memberships)
|
|
|
|
|
}
|
|
|
|
|
var thirdMemberships int
|
|
|
|
|
if err := db.QueryRowContext(ctx,
|
|
|
|
|
`SELECT count(*) FROM memberships WHERE user_id = $1`, third).Scan(&thirdMemberships); err != nil {
|
|
|
|
|
t.Fatalf("count memberships: %v", err)
|
|
|
|
|
}
|
|
|
|
|
if thirdMemberships != 0 {
|
|
|
|
|
t.Errorf("a later bootstrap joined a tenant that already had an owner")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func assertRole(t *testing.T, db *sql.DB, ctx context.Context, userID, tenantID, want string) {
|
|
|
|
|
t.Helper()
|
|
|
|
|
var got string
|
|
|
|
|
err := db.QueryRowContext(ctx, `
|
|
|
|
|
SELECT r.slug FROM memberships m JOIN roles r ON r.id = m.role_id
|
|
|
|
|
WHERE m.user_id = $1 AND m.tenant_id = $2`, userID, tenantID).Scan(&got)
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("read membership: %v", err)
|
|
|
|
|
}
|
|
|
|
|
if got != want {
|
|
|
|
|
t.Errorf("role = %q, want %q", got, want)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// TestCreateTenantReportsADuplicateSlug pins that a slug already in use is a
|
|
|
|
|
// conflict the caller can act on rather than an opaque server error.
|
|
|
|
|
func TestCreateTenantReportsADuplicateSlug(t *testing.T) {
|
|
|
|
|
s, _, ctx := integrationStore(t)
|
|
|
|
|
owner := newUser(t, s, ctx, "owner@example.test")
|
|
|
|
|
newTenant(t, s, ctx, owner, "nmbs")
|
|
|
|
|
if _, err := s.CreateTenant(ctx, owner, "nmbs", "Duplicate"); !errors.Is(err, store.ErrTenantSlugTaken) {
|
|
|
|
|
t.Fatalf("CreateTenant with a used slug = %v, want ErrTenantSlugTaken", err)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// TestConcurrentMigrationRunsDoNotCollide pins that instances starting together
|
|
|
|
|
// against an empty database all succeed. CREATE TABLE IF NOT EXISTS is not race
|
|
|
|
|
// free in PostgreSQL, so the run is serialised with an advisory lock.
|
|
|
|
|
func TestConcurrentMigrationRunsDoNotCollide(t *testing.T) {
|
|
|
|
|
databaseURL := os.Getenv("GO_LOOSE_TEST_DATABASE_URL")
|
|
|
|
|
if databaseURL == "" {
|
|
|
|
|
t.Skip("set GO_LOOSE_TEST_DATABASE_URL to run PostgreSQL integration tests")
|
|
|
|
|
}
|
|
|
|
|
requireScratchDatabase(t, databaseURL)
|
|
|
|
|
resetSchema(context.Background(), mustOpen(t, databaseURL))
|
|
|
|
|
|
|
|
|
|
const instances = 4
|
|
|
|
|
connections := make([]*sql.DB, instances)
|
|
|
|
|
for index := range connections {
|
|
|
|
|
connections[index] = mustOpen(t, databaseURL)
|
|
|
|
|
}
|
|
|
|
|
errs := make(chan error, instances)
|
|
|
|
|
for _, connection := range connections {
|
|
|
|
|
go func(conn *sql.DB) { errs <- database.Migrate(context.Background(), conn) }(connection)
|
|
|
|
|
}
|
|
|
|
|
for range connections {
|
|
|
|
|
if err := <-errs; err != nil {
|
|
|
|
|
t.Errorf("concurrent Migrate: %v", err)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
for _, connection := range connections {
|
|
|
|
|
var applied int
|
|
|
|
|
if err := connection.QueryRowContext(context.Background(),
|
|
|
|
|
`SELECT count(*) FROM schema_migrations`).Scan(&applied); err != nil {
|
|
|
|
|
t.Errorf("count migrations: %v", err)
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
if applied == 0 {
|
|
|
|
|
t.Error("no migration was recorded")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func mustOpen(t *testing.T, databaseURL string) *sql.DB {
|
|
|
|
|
t.Helper()
|
|
|
|
|
db, err := database.Open(context.Background(), databaseURL)
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("open database: %v", err)
|
|
|
|
|
}
|
|
|
|
|
t.Cleanup(func() { db.Close() })
|
|
|
|
|
return db
|
|
|
|
|
}
|