Skip to content

armgit / posta

Public Imported from GitHub
0

Self-hosted email delivery platform that enables applications to send emails via HTTP APIs while handling SMTP delivery, templates, storage, security, and analytics. Fully self-hostable alternative to services like SendGrid or Mailgun.

feat(workspaces): remove the personal workspace type

Jonas Kanindac815561b6cbc
diff --git a/cmd/posta/doctor.go b/cmd/posta/doctor.go
new file mode 100644
index 0000000..ac6eee4
--- /dev/null
+++ b/cmd/posta/doctor.go
@@ -0,0 +1,138 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package main
+
+import (
+ "fmt"
+ "os"
+ "strings"
+
+ "github.com/goposta/posta/internal/config"
+ "github.com/goposta/posta/internal/models"
+ workspacesvc "github.com/goposta/posta/internal/services/workspace"
+ "gorm.io/gorm"
+)
+
+// scopedTables are the tables whose rows must all carry a workspace_id before
+// the workspace lock in repositories.ApplyScope can be enabled. A row left with
+// a NULL workspace_id becomes permanently unreachable, so this is checked rather
+// than assumed.
+var scopedTables = []string{
+ "api_keys", "templates", "style_sheets", "languages", "domains",
+ "smtp_servers", "webhooks", "contacts", "subscribers", "subscriber_lists",
+ "unsubscribe_lists", "suppressions", "bounces", "emails", "inbound_emails",
+ "campaigns",
+}
+
+type check struct {
+ name string
+ detail string
+ count int64
+ fatal bool
+ fix string
+}
+
+func runDoctorWorkspaces() error {
+ cfg := config.New()
+ cfg.InitStorage()
+ db := cfg.Database.DB
+
+ checks := []check{}
+
+ checks = append(checks, unscopedRowChecks(db)...)
+
+ var noWorkspace int64
+ db.Model(&models.User{}).
+ Where("active = ? AND NOT EXISTS (SELECT 1 FROM workspace_members m WHERE m.user_id = users.id)", true).
+ Count(&noWorkspace)
+ checks = append(checks, check{
+ name: "users without a workspace",
+ detail: "these users land on an empty dashboard until one is provisioned",
+ count: noWorkspace,
+ fatal: false,
+ fix: "they are provisioned on next sign-in; POST /api/v1/admin/users/{id}/migrate forces it",
+ })
+
+ if hasColumn(db, "users", "migration_error") {
+ var failed int64
+ db.Model(&models.User{}).Where("migration_error <> ''").Count(&failed)
+ checks = append(checks, check{
+ name: "users with a recorded provisioning error",
+ detail: "the earlier workspace backfill did not finish for these users",
+ count: failed,
+ fatal: true,
+ fix: "resolve the recorded error, then re-run provisioning before upgrading",
+ })
+ }
+
+ var systems int64
+ db.Model(&models.Workspace{}).Where("system = ?", true).Count(&systems)
+
+ fmt.Println("Posta workspace check")
+ fmt.Println(strings.Repeat("-", 60))
+
+ blocked := false
+ for _, c := range checks {
+ status := "ok"
+ if c.count > 0 {
+ if c.fatal {
+ status = "BLOCKING"
+ blocked = true
+ } else {
+ status = "warn"
+ }
+ }
+ fmt.Printf("%-10s %-45s %d\n", status, c.name, c.count)
+ if c.count > 0 {
+ fmt.Printf(" %s\n fix: %s\n", c.detail, c.fix)
+ }
+ }
+
+ switch systems {
+ case 0:
+ fmt.Printf("%-10s %-45s %d\n", "warn", "system workspace", systems)
+ fmt.Println(" not created yet; the server creates it on next boot")
+ case 1:
+ fmt.Printf("%-10s %-45s %d\n", "ok", "system workspace", systems)
+ default:
+ fmt.Printf("%-10s %-45s %d\n", "BLOCKING", "system workspace", systems)
+ fmt.Println(" more than one exists; keep the oldest and clear the flag on the rest")
+ blocked = true
+ }
+
+ fmt.Println(strings.Repeat("-", 60))
+ if blocked {
+ fmt.Println("NOT SAFE TO UPGRADE — resolve the blocking rows above first.")
+ fmt.Printf("Reserved system slug: %q\n", workspacesvc.SystemSlug)
+ os.Exit(1)
+ }
+ fmt.Println("Safe to upgrade.")
+ return nil
+}
+
+func unscopedRowChecks(db *gorm.DB) []check {
+ out := make([]check, 0, len(scopedTables))
+ for _, table := range scopedTables {
+ if !hasColumn(db, table, "workspace_id") {
+ continue
+ }
+ var count int64
+ db.Table(table).Where("workspace_id IS NULL").Count(&count)
+ out = append(out, check{
+ name: table + " rows with no workspace",
+ detail: "these rows become unreachable once scoping is enforced",
+ count: count,
+ fatal: true,
+ fix: "run the earlier workspace backfill to completion before upgrading",
+ })
+ }
+ return out
+}
+
+func hasColumn(db *gorm.DB, table, column string) bool {
+ var count int64
+ db.Raw(`SELECT count(*) FROM information_schema.columns WHERE table_name = ? AND column_name = ?`,
+ table, column).Scan(&count)
+ return count > 0
+}
diff --git a/cmd/posta/main.go b/cmd/posta/main.go
index 301732b..4ff15b4 100644
--- a/cmd/posta/main.go
+++ b/cmd/posta/main.go
@@ -26,6 +26,10 @@ func main() {
}
return nil
})
+ cli.Command("doctor", "Check that this install is ready to upgrade", func(cmd *okapicli.Command) error {
+ return runDoctorWorkspaces()
+ })
+
cli.DefaultCommand("server")
if err := cli.Execute(); err != nil {
diff --git a/cmd/posta/server.go b/cmd/posta/server.go
index cb88fa3..e010aad 100644
--- a/cmd/posta/server.go
+++ b/cmd/posta/server.go
@@ -30,7 +30,8 @@ import (
"github.com/goposta/posta/internal/services/updatecheck"
"github.com/goposta/posta/internal/services/webhook"
"github.com/goposta/posta/internal/services/workermon"
- "github.com/goposta/posta/internal/services/workspacemigrate"
+ workspacesvc "github.com/goposta/posta/internal/services/workspace"
+ "github.com/goposta/posta/internal/services/workspaceprovision"
"github.com/goposta/posta/internal/storage"
"github.com/goposta/posta/internal/storage/blob"
"github.com/goposta/posta/internal/storage/migration"
@@ -90,6 +91,15 @@ func runServer(cli *okapicli.CLI) {
seedDefaults(res.db, cfg)
+ // The system workspace needs an administrator to own it, so it is
+ // ensured after seeding rather than in the migration step, which may
+ // run before any admin exists.
+ if _, err := workspacesvc.EnsureSystem(res.db); err != nil {
+ logger.Error("failed to ensure the system workspace", "error", err)
+ } else if err := workspacesvc.SyncMembers(res.db); err != nil {
+ logger.Error("failed to sync system workspace members", "error", err)
+ }
+
// Initialize blob storage (S3 or filesystem) for attachments
if cfg.BlobProvider != "" {
bs, err := blob.New(blob.Config{
@@ -214,9 +224,9 @@ func seedDefaults(db *gorm.DB, cfg *config.Config) {
repositories.NewTemplateLocalizationRepository(db),
repositories.NewLanguageRepository(db),
)
- migrator := workspacemigrate.New(cfg.PlanEnforcement)
+ migrator := workspaceprovision.New(cfg.PlanEnforcement)
migrator.SetSeeder(s)
- if _, err := migrator.MigrateUser(db, admin.ID); err != nil {
+ if _, err := migrator.EnsureWorkspace(db, admin.ID); err != nil {
logger.Error("failed to provision admin personal workspace", "error", err)
}
}
diff --git a/docs/docs/admin/user-management.md b/docs/docs/admin/user-management.md
index e1d10cb..86f7cdb 100644
--- a/docs/docs/admin/user-management.md
+++ b/docs/docs/admin/user-management.md
@@ -28,7 +28,7 @@ POST /api/v1/admin/users
| `user` | Standard user — can send emails, manage own resources |
| `admin` | Administrator — full platform access |
-Returns `409 Conflict` if the email already exists. A personal workspace is automatically provisioned for the new user.
+Returns `409 Conflict` if the email already exists. A workspace is automatically provisioned for the new user, named after them and owned by them like any other.
## List Users
diff --git a/docs/docs/workspaces/overview.md b/docs/docs/workspaces/overview.md
index 01538e7..bfcdab3 100644
--- a/docs/docs/workspaces/overview.md
+++ b/docs/docs/workspaces/overview.md
@@ -6,13 +6,15 @@ description: Multi-tenant workspaces, roles, and the workspace context header
# Workspaces
-Workspaces provide multi-tenant isolation within Posta. They work like GitHub Organizations — every user has a **personal space** by default and can optionally create **workspaces** to share resources with team members.
+Workspaces provide multi-tenant isolation within Posta. Every resource — templates, SMTP servers, domains, contacts, API keys — belongs to exactly one workspace, and a workspace is shared with as many or as few people as you invite.
## Concepts
### Personal space
-Every user has a personal space where their resources (templates, SMTP servers, domains, contacts, API keys, etc.) live by default. No workspace is required — the platform works for a single user out of the box. The personal space is itself a workspace flagged `is_personal: true`; it is owned by the user and cannot be deleted.
+A workspace is provisioned for you when you sign up, named after you and owned by you. It is an ordinary workspace in every respect: rename it, invite people to it, or delete it once you have another. There is no separate "personal" workspace type.
+
+One workspace is special. The **system workspace** is created on first boot, owned by the first administrator, and holds platform-managed resources. It is flagged `system: true`, admits only platform administrators, and cannot be renamed or deleted.
### Workspaces
@@ -69,7 +71,7 @@ The header value is the numeric workspace ID. If you are not a member of that wo
The correct header is `X-Posta-Workspace-Id`. Earlier drafts referred to `X-Workspace-ID` — that name is wrong and is not recognized by the API.
:::
-To operate against your personal space, pass its workspace ID in the header (you can find it in the `GET /api/v1/workspaces` list, where `is_personal` is `true`).
+Omit the header and the request operates on your **default workspace** — the one you last set with `PUT /api/v1/users/me/default-workspace`, or the oldest one you belong to. The role you hold in that workspace applies, so a viewer stays a viewer on a header-less request.
### Workspace-scoped API keys
@@ -150,7 +152,7 @@ Response (`201`):
"description": "",
"owner_id": 42,
"role": "owner",
- "is_personal": false,
+ "system": false,
"created_at": "2026-05-31T10:00:00Z"
}
}
@@ -164,7 +166,7 @@ Creating a workspace is subject to your plan's workspace quota; exceeding it ret
GET /api/v1/workspaces
```
-Returns every workspace the current user is a member of, including the personal space. Each entry carries the caller's `role` in that workspace and the `is_personal` flag.
+Returns every workspace the current user is a member of. Each entry carries the caller's `role` in that workspace and a `system` flag, which is true only for the built-in platform workspace.
## Get, update, and delete the current workspace
@@ -184,7 +186,12 @@ DELETE /api/v1/workspaces/current
}
```
-`DELETE` removes the workspace and returns `204`. The personal workspace cannot be deleted (`400`).
+`DELETE` removes the workspace and returns `204`.
+
+Two workspaces refuse deletion:
+
+- The **system workspace** returns `409`. It is the built-in platform workspace, created on first boot, owned by the first administrator, and holds platform-managed resources. It cannot be renamed either, and only platform administrators are members.
+- Your **last remaining workspace** returns `400`. Everything in Posta belongs to a workspace, so deleting the only one you belong to would leave you with nowhere to work. Create another first.
```bash
curl -X PUT http://localhost:9000/api/v1/workspaces/current \
diff --git a/internal/config/config.go b/internal/config/config.go
index 87f43e4..51af3e6 100644
--- a/internal/config/config.go
+++ b/internal/config/config.go
@@ -6,6 +6,7 @@ package config
import (
"crypto/tls"
"fmt"
+ "os"
"strings"
errorhandlers "github.com/goposta/posta/internal/error_handlers"
@@ -51,8 +52,7 @@ type Config struct {
// admins; it never upgrades anything and sends nothing about this install.
UpdateCheck bool
- PlanEnforcement bool
- WorkspaceOnlyMode bool
+ PlanEnforcement bool
// WebDir overrides where the dashboard is served from. The UI is normally
// embedded in the binary (internal/web); setting POSTA_WEB_DIR serves it from
@@ -259,13 +259,12 @@ func New() *Config {
AllowDowngrade: goutils.EnvBool("POSTA_ALLOW_DOWNGRADE", false),
securitySchemes: okapi.SecuritySchemes{},
- MetricsEnabled: goutils.EnvBool("POSTA_METRICS_ENABLED", false),
- UpdateCheck: goutils.EnvBool("POSTA_UPDATE_CHECK", true),
- PlanEnforcement: goutils.EnvBool("POSTA_PLAN_ENFORCEMENT", false),
- WorkspaceOnlyMode: goutils.EnvBool("POSTA_WORKSPACE_ONLY_MODE", false),
- WebDir: goutils.Env("POSTA_WEB_DIR", ""),
- AppWebURL: goutils.Env("POSTA_WEB_URL", ""),
- ApiBaseURL: goutils.Env("POSTA_API_URL", ""),
+ MetricsEnabled: goutils.EnvBool("POSTA_METRICS_ENABLED", false),
+ UpdateCheck: goutils.EnvBool("POSTA_UPDATE_CHECK", true),
+ PlanEnforcement: goutils.EnvBool("POSTA_PLAN_ENFORCEMENT", false),
+ WebDir: goutils.Env("POSTA_WEB_DIR", ""),
+ AppWebURL: goutils.Env("POSTA_WEB_URL", ""),
+ ApiBaseURL: goutils.Env("POSTA_API_URL", ""),
CORSOrigins: goutils.Env("POSTA_CORS_ORIGINS", "*"),
@@ -337,7 +336,23 @@ func New() *Config {
SMTPRelayRateWindow: goutils.EnvInt("POSTA_SMTP_RELAY_RATE_WINDOW", 60),
}
}
+
+// removedEnvVars are settings that no longer do anything. Setting one is not an
+// error, but it is worth telling the operator so they can clean up.
+var removedEnvVars = map[string]string{
+ "POSTA_WORKSPACE_ONLY_MODE": "every resource is workspace-scoped unconditionally; the flag no longer does anything",
+}
+
+func warnRemovedEnvVars() {
+ for name, why := range removedEnvVars {
+ if _, ok := os.LookupEnv(name); ok {
+ logger.Warn("ignoring removed setting", "variable", name, "reason", why)
+ }
+ }
+}
+
func (c *Config) validate() error {
+ warnRemovedEnvVars()
if c.MessagesEnabled && c.MessagesInboundDomain != "" && !c.InboundEnabled {
return fmt.Errorf("POSTA_MESSAGES_INBOUND_DOMAIN requires POSTA_INBOUND_ENABLED=true")
}
diff --git a/internal/handlers/admin_handler.go b/internal/handlers/admin_handler.go
index 6998ea3..88bc470 100644
--- a/internal/handlers/admin_handler.go
+++ b/internal/handlers/admin_handler.go
@@ -18,7 +18,7 @@ import (
"github.com/goposta/posta/internal/services/session"
"github.com/goposta/posta/internal/services/settings"
"github.com/goposta/posta/internal/services/workermon"
- "github.com/goposta/posta/internal/services/workspacemigrate"
+ "github.com/goposta/posta/internal/services/workspaceprovision"
"github.com/goposta/posta/internal/storage/repositories"
"github.com/hibiken/asynq"
"github.com/jkaninda/logger"
@@ -41,7 +41,7 @@ type AdminHandler struct {
redis *redis.Client
bus *eventbus.EventBus
seeder *seeder.Seeder
- migrator *workspacemigrate.Service
+ migrator *workspaceprovision.Service
embeddedWorker bool
emailSettings *settings.Provider
sessionRepo *repositories.SessionRepository
@@ -50,7 +50,7 @@ type AdminHandler struct {
// SetMigrator wires the personal-workspace migrator used to provision (and seed)
// a personal workspace for admin-created users. See §4.
-func (h *AdminHandler) SetMigrator(m *workspacemigrate.Service) {
+func (h *AdminHandler) SetMigrator(m *workspaceprovision.Service) {
h.migrator = m
}
@@ -108,9 +108,9 @@ type PlatformMetrics struct {
TwoFactorAdoptionRate float64 `json:"two_factor_adoption_rate"`
TwoFactorUsers int64 `json:"two_factor_users"`
- // Workspace-only migration progress
- UsersUnmigrated int64 `json:"users_unmigrated"`
- UsersMigrationFailed int64 `json:"users_migration_failed"`
+ // Users belonging to no workspace at all. Non-zero means provisioning failed
+ // for somebody and they will land on the dashboard's empty state.
+ UsersWithoutWorkspace int64 `json:"users_without_workspace"`
}
// processStartTime records when the process started, for uptime reporting.
@@ -191,7 +191,7 @@ func (h *AdminHandler) CreateUser(c *okapi.Context, req *AdminCreateUserRequest)
// Provision the new user's personal workspace and seed its default content.
if h.migrator != nil {
go func(id uint) {
- if _, err := h.migrator.MigrateUser(h.db, id); err != nil {
+ if _, err := h.migrator.EnsureWorkspace(h.db, id); err != nil {
logger.Error("failed to provision personal workspace", "user_id", id, "err", err)
}
}(user.ID)
@@ -423,8 +423,9 @@ func (h *AdminHandler) Metrics(c *okapi.Context) error {
}
// Workspace-only migration progress.
- h.db.Model(&models.User{}).Where("personal_workspace_id IS NULL").Count(&m.UsersUnmigrated)
- h.db.Model(&models.User{}).Where("migration_error IS NOT NULL AND migration_error <> ''").Count(&m.UsersMigrationFailed)
+ h.db.Model(&models.User{}).
+ Where("active = ? AND NOT EXISTS (SELECT 1 FROM workspace_members m WHERE m.user_id = users.id)", true).
+ Count(&m.UsersWithoutWorkspace)
h.cache.Set(ctx, cacheKey, m, cache.AdminMetricsTTL)
diff --git a/internal/handlers/oauth_handler.go b/internal/handlers/oauth_handler.go
index 202cda0..cc1881b 100644
--- a/internal/handlers/oauth_handler.go
+++ b/internal/handlers/oauth_handler.go
@@ -18,7 +18,7 @@ import (
"github.com/goposta/posta/internal/services/eventbus"
"github.com/goposta/posta/internal/services/seeder"
sessionpkg "github.com/goposta/posta/internal/services/session"
- "github.com/goposta/posta/internal/services/workspacemigrate"
+ "github.com/goposta/posta/internal/services/workspaceprovision"
"github.com/goposta/posta/internal/storage/repositories"
"github.com/jkaninda/logger"
"github.com/jkaninda/okapi"
@@ -39,12 +39,12 @@ type OAuthHandler struct {
callbackBase string // e.g. "http://localhost:9000"
appWebURL string // e.g. "http://localhost:9000"
db *gorm.DB
- migrator *workspacemigrate.Service
+ migrator *workspaceprovision.Service
}
// SetMigrator wires the personal-workspace migrator used to provision (and seed)
// a personal workspace after OAuth user upsert. See §4.
-func (h *OAuthHandler) SetMigrator(db *gorm.DB, m *workspacemigrate.Service) {
+func (h *OAuthHandler) SetMigrator(db *gorm.DB, m *workspaceprovision.Service) {
h.db = db
h.migrator = m
}
@@ -248,7 +248,7 @@ func (h *OAuthHandler) Callback(c *okapi.Context) error {
// Provision the personal workspace (and seed defaults for new users) before
// issuing the JWT. Idempotent: a no-op for already-migrated returning users.
if h.migrator != nil && h.db != nil {
- if _, err := h.migrator.MigrateUser(h.db, user.ID); err != nil {
+ if _, err := h.migrator.EnsureWorkspace(h.db, user.ID); err != nil {
logger.Error("failed to provision personal workspace", "user_id", user.ID, "err", err)
}
}
diff --git a/internal/handlers/user_handler.go b/internal/handlers/user_handler.go
index 5c6489d..f2baa5e 100644
--- a/internal/handlers/user_handler.go
+++ b/internal/handlers/user_handler.go
@@ -22,7 +22,7 @@ import (
"github.com/goposta/posta/internal/services/session"
"github.com/goposta/posta/internal/services/settings"
"github.com/goposta/posta/internal/services/twofactor"
- "github.com/goposta/posta/internal/services/workspacemigrate"
+ "github.com/goposta/posta/internal/services/workspaceprovision"
"github.com/goposta/posta/internal/storage/repositories"
"github.com/jkaninda/logger"
"github.com/jkaninda/okapi"
@@ -41,7 +41,7 @@ type UserHandler struct {
emailVerifier *emailverify.Service
passwordReset *passwordreset.Service
db *gorm.DB
- migrator *workspacemigrate.Service
+ migrator *workspaceprovision.Service
}
func NewUserHandler(repo *repositories.UserRepository, jwtSecret string, seeder *seeder.Seeder, bus *eventbus.EventBus) *UserHandler {
@@ -53,7 +53,7 @@ func NewUserHandler(repo *repositories.UserRepository, jwtSecret string, seeder
}
}
-func (h *UserHandler) SetMigrator(db *gorm.DB, m *workspacemigrate.Service) {
+func (h *UserHandler) SetMigrator(db *gorm.DB, m *workspaceprovision.Service) {
h.db = db
h.migrator = m
}
@@ -62,7 +62,7 @@ func (h *UserHandler) ensurePersonalWorkspace(userID uint) {
if h.migrator == nil || h.db == nil {
return
}
- if _, err := h.migrator.MigrateUser(h.db, userID); err != nil {
+ if _, err := h.migrator.EnsureWorkspace(h.db, userID); err != nil {
logger.Error("failed to provision personal workspace", "user_id", userID, "err", err)
}
}
@@ -127,7 +127,11 @@ type UserProfile struct {
ScheduledDeletionAt *time.Time `json:"scheduled_deletion_at"`
EmailVerifiedAt *time.Time `json:"email_verified_at"`
EmailVerificationRequired bool `json:"email_verification_required"`
- CreatedAt time.Time `json:"created_at"`
+ DefaultWorkspaceID *uint `json:"default_workspace_id"`
+ // Deprecated: renamed to default_workspace_id. Mirrors it for one minor
+ // release so an older dashboard build keeps working.
+ PersonalWorkspaceID *uint `json:"personal_workspace_id"`
+ CreatedAt time.Time `json:"created_at"`
}
type Enable2FAResponse struct {
@@ -543,6 +547,8 @@ func (h *UserHandler) buildProfile(user *models.User) UserProfile {
ScheduledDeletionAt: user.ScheduledDeletionAt,
EmailVerifiedAt: user.EmailVerifiedAt,
EmailVerificationRequired: required,
+ DefaultWorkspaceID: user.DefaultWorkspaceID,
+ PersonalWorkspaceID: user.DefaultWorkspaceID,
CreatedAt: user.CreatedAt,
}
}
@@ -788,3 +794,29 @@ func (h *UserHandler) CancelAccountDeletion(c *okapi.Context) error {
return ok(c, map[string]any{"message": "Account deletion cancelled"})
}
+
+type SetDefaultWorkspaceRequest struct {
+ Body struct {
+ WorkspaceID uint `json:"workspace_id" required:"true"`
+ } `json:"body"`
+}
+
+// SetDefaultWorkspace records which workspace a request that names none lands
+// in. The caller must be a member, and the system workspace is not a valid
+// choice: landing there by default would hide the user's real work.
+func (h *UserHandler) SetDefaultWorkspace(c *okapi.Context, req *SetDefaultWorkspaceRequest) error {
+ userID := uint(c.GetInt("user_id"))
+
+ ws, _, err := h.repo.WorkspaceForMember(userID, req.Body.WorkspaceID)
+ if err != nil {
+ return c.AbortNotFound("workspace not found, or you are not a member of it")
+ }
+ if ws.System {
+ return c.AbortBadRequest("the system workspace cannot be your default")
+ }
+
+ if err := h.repo.SetDefaultWorkspace(userID, &ws.ID); err != nil {
+ return c.AbortInternalServerError("failed to update the default workspace")
+ }
+ return ok(c, dto.MessageData{Message: "Default workspace updated"})
+}
diff --git a/internal/handlers/workspace_handler.go b/internal/handlers/workspace_handler.go
index 4255031..8e25ae5 100644
--- a/internal/handlers/workspace_handler.go
+++ b/internal/handlers/workspace_handler.go
@@ -14,6 +14,7 @@ import (
"github.com/goposta/posta/internal/models"
"github.com/goposta/posta/internal/services/audit"
"github.com/goposta/posta/internal/services/notification"
+ "github.com/goposta/posta/internal/services/workspace"
"github.com/goposta/posta/internal/storage/repositories"
"github.com/jkaninda/okapi"
"gorm.io/gorm"
@@ -91,14 +92,17 @@ type DeclineInvitationRequest struct {
}
type WorkspaceResponse struct {
- ID uint `json:"id"`
- Name string `json:"name"`
- Slug string `json:"slug"`
- Description string `json:"description"`
- OwnerID uint `json:"owner_id"`
- Role string `json:"role"`
- IsPersonal bool `json:"is_personal"`
- CreatedAt time.Time `json:"created_at"`
+ ID uint `json:"id"`
+ Name string `json:"name"`
+ Slug string `json:"slug"`
+ Description string `json:"description"`
+ OwnerID uint `json:"owner_id"`
+ Role string `json:"role"`
+ System bool `json:"system"`
+ // Deprecated: the personal workspace type was removed; always false. Kept for
+ // one minor release so an older dashboard build keeps parsing the response.
+ IsPersonal bool `json:"is_personal"`
+ CreatedAt time.Time `json:"created_at"`
}
type WorkspaceMemberResponse struct {
@@ -139,6 +143,9 @@ func (h *WorkspaceHandler) Create(c *okapi.Context, req *CreateWorkspaceRequest)
if !isValidSlug(slug) {
return c.AbortBadRequest("slug must contain only lowercase letters, numbers, and hyphens")
}
+ if workspace.IsReservedSlug(slug) {
+ return c.AbortConflict("that slug is reserved by the platform")
+ }
// Check slug uniqueness
if _, err := h.workspaceRepo.FindBySlug(slug); err == nil {
@@ -181,7 +188,7 @@ func (h *WorkspaceHandler) Create(c *okapi.Context, req *CreateWorkspaceRequest)
Description: ws.Description,
OwnerID: ws.OwnerID,
Role: string(models.WorkspaceRoleOwner),
- IsPersonal: ws.IsPersonal,
+ System: ws.System,
CreatedAt: ws.CreatedAt,
})
}
@@ -208,7 +215,7 @@ func (h *WorkspaceHandler) List(c *okapi.Context) error {
Description: ws.Description,
OwnerID: ws.OwnerID,
Role: role,
- IsPersonal: ws.IsPersonal,
+ System: ws.System,
CreatedAt: ws.CreatedAt,
})
}
@@ -233,7 +240,7 @@ func (h *WorkspaceHandler) Get(c *okapi.Context) error {
Description: ws.Description,
OwnerID: ws.OwnerID,
Role: role,
- IsPersonal: ws.IsPersonal,
+ System: ws.System,
CreatedAt: ws.CreatedAt,
})
}
@@ -246,6 +253,9 @@ func (h *WorkspaceHandler) Update(c *okapi.Context, req *UpdateWorkspaceRequest)
return c.AbortNotFound("workspace not found")
}
+ if ws.System && req.Body.Name != "" && strings.TrimSpace(req.Body.Name) != ws.Name {
+ return c.AbortConflict("the system workspace cannot be renamed")
+ }
if req.Body.Name != "" {
ws.Name = strings.TrimSpace(req.Body.Name)
}
@@ -272,7 +282,7 @@ func (h *WorkspaceHandler) Update(c *okapi.Context, req *UpdateWorkspaceRequest)
Description: ws.Description,
OwnerID: ws.OwnerID,
Role: role,
- IsPersonal: ws.IsPersonal,
+ System: ws.System,
CreatedAt: ws.CreatedAt,
})
}
@@ -284,8 +294,12 @@ func (h *WorkspaceHandler) Delete(c *okapi.Context) error {
if err != nil {
return c.AbortNotFound("workspace not found")
}
- if ws.IsPersonal {
- return c.AbortBadRequest("personal workspace cannot be deleted")
+ if ws.System {
+ return c.AbortConflict("the system workspace cannot be deleted")
+ }
+ userID := uint(c.GetInt("user_id"))
+ if h.workspaceRepo.CountNonSystemMemberships(userID) <= 1 {
+ return c.AbortBadRequest("this is your only workspace; create another before deleting this one")
}
if err := h.workspaceRepo.Delete(uint(wsID)); err != nil {
diff --git a/internal/middlewares/default_workspace_test.go b/internal/middlewares/default_workspace_test.go
new file mode 100644
index 0000000..5bb81e1
--- /dev/null
+++ b/internal/middlewares/default_workspace_test.go
@@ -0,0 +1,112 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package middlewares
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/goposta/posta/internal/models"
+ "github.com/jkaninda/okapi"
+)
+
+type stubResolver struct {
+ ws *models.Workspace
+ role models.WorkspaceRole
+ err error
+ called int
+}
+
+func (s *stubResolver) DefaultWorkspace(uint) (*models.Workspace, models.WorkspaceRole, error) {
+ s.called++
+ return s.ws, s.role, s.err
+}
+
+func runFallback(t *testing.T, resolver DefaultWorkspaceResolver) (int, string, int) {
+ t.Helper()
+ app := okapi.New()
+
+ var gotWorkspace int
+ var gotRole string
+ app.Get("/t", func(c *okapi.Context) error {
+ gotWorkspace = c.GetInt(CtxWorkspaceID)
+ gotRole = c.GetString(CtxWorkspaceRole)
+ return c.JSON(http.StatusOK, okapi.M{"ok": true})
+ }).Use(stashJWT(42), OptionalWorkspaceMiddleware(nil, resolver))
+
+ rec := httptest.NewRecorder()
+ app.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/t", nil))
+ return gotWorkspace, gotRole, rec.Code
+}
+
+// The default workspace used to be the caller's personal one, which they always
+// owned, so the fallback hard-coded owner. It can now be any workspace they
+// belong to — including one where they are a viewer — and carrying owner through
+// would grant write access on every header-less request.
+func TestDefaultWorkspaceFallbackUsesMembershipRole(t *testing.T) {
+ for _, role := range []models.WorkspaceRole{
+ models.WorkspaceRoleViewer,
+ models.WorkspaceRoleEditor,
+ models.WorkspaceRoleAdmin,
+ models.WorkspaceRoleOwner,
+ } {
+ t.Run(string(role), func(t *testing.T) {
+ resolver := &stubResolver{ws: &models.Workspace{ID: 9}, role: role}
+ ws, got, code := runFallback(t, resolver)
+
+ if code != http.StatusOK {
+ t.Fatalf("status = %d, want 200", code)
+ }
+ if ws != 9 {
+ t.Fatalf("workspace = %d, want 9", ws)
+ }
+ if got != string(role) {
+ t.Fatalf("role = %q, want %q", got, role)
+ }
+ })
+ }
+}
+
+func TestDefaultWorkspaceFallbackViewerCannotEdit(t *testing.T) {
+ resolver := &stubResolver{ws: &models.Workspace{ID: 9}, role: models.WorkspaceRoleViewer}
+ _, role, _ := runFallback(t, resolver)
+
+ if models.WorkspaceRole(role).CanEdit() {
+ t.Fatal("a viewer resolved through the header-less fallback must not be able to edit")
+ }
+}
+
+func TestDefaultWorkspaceFallbackWithNoMembership(t *testing.T) {
+ resolver := &stubResolver{}
+ ws, role, code := runFallback(t, resolver)
+
+ if code != http.StatusOK {
+ t.Fatalf("status = %d, want 200: a user with no workspace gets the empty state, not an error", code)
+ }
+ if ws != 0 || role != "" {
+ t.Fatalf("workspace = %d role = %q, want unset", ws, role)
+ }
+}
+
+func TestDefaultWorkspaceFallbackSkippedForBoundAPIKey(t *testing.T) {
+ resolver := &stubResolver{ws: &models.Workspace{ID: 9}, role: models.WorkspaceRoleOwner}
+
+ app := okapi.New()
+ var gotWorkspace int
+ app.Get("/t", func(c *okapi.Context) error {
+ gotWorkspace = c.GetInt(CtxWorkspaceID)
+ return c.JSON(http.StatusOK, okapi.M{"ok": true})
+ }).Use(stashAPIKey(1, 7, models.ScopeAll), OptionalWorkspaceMiddleware(nil, resolver))
+
+ rec := httptest.NewRecorder()
+ app.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/t", nil))
+
+ if resolver.called != 0 {
+ t.Fatal("a workspace-bound API key is its own workspace; the fallback must not run")
+ }
+ if gotWorkspace != 7 {
+ t.Fatalf("workspace = %d, want the key's binding (7)", gotWorkspace)
+ }
+}
diff --git a/internal/middlewares/workspace.go b/internal/middlewares/workspace.go
index 3a1b955..19c3a5b 100644
--- a/internal/middlewares/workspace.go
+++ b/internal/middlewares/workspace.go
@@ -26,12 +26,20 @@ const WorkspaceHeader = "X-Posta-Workspace-Id"
// - An account-wide API key, and any JWT session, must prove membership of the
// workspace they name, and inherit that membership's role.
// - When nobody names a workspace and `required` is false, we fall back to the
-// user's personal workspace.
+// user's default workspace, with the role from that membership.
//
// Membership answers "which workspace?", never "how much of it?". An API key's
// scopes answer the latter, and are enforced here for every workspace-scoped
// route — see requireWorkspaceScope.
-func resolveWorkspace(c *okapi.Context, workspaceRepo *repositories.WorkspaceRepository, userRepo *repositories.UserRepository, raw string, required bool) error {
+// DefaultWorkspaceResolver answers where a request that names no workspace
+// lands, and with what role. Narrow on purpose: the role it returns is the only
+// thing standing between a viewer and write access on a header-less request, so
+// it is worth being able to substitute in a test.
+type DefaultWorkspaceResolver interface {
+ DefaultWorkspace(userID uint) (*models.Workspace, models.WorkspaceRole, error)
+}
+
+func resolveWorkspace(c *okapi.Context, workspaceRepo *repositories.WorkspaceRepository, userRepo DefaultWorkspaceResolver, raw string, required bool) error {
userID := c.GetInt(CtxUserID)
if userID == 0 {
return c.AbortUnauthorized("authentication required")
@@ -76,12 +84,17 @@ func resolveWorkspace(c *okapi.Context, workspaceRepo *repositories.WorkspaceRep
return c.AbortBadRequest(WorkspaceHeader + " header is required")
}
- // Nobody named a workspace: fall back to the caller's personal one. An
- // unmigrated user has none — that is the legacy personal mode, not an error.
+ // Nobody named a workspace: fall back to the caller's default one.
+ //
+ // The role comes from the membership row, never a constant. The default
+ // workspace used to be the caller's personal one, which they always owned, so
+ // hard-coding owner was safe. It is now any workspace they belong to —
+ // possibly as a viewer — and assuming owner here would grant write access on
+ // every header-less request.
if userRepo != nil {
- if personalID, err := userRepo.PersonalWorkspaceID(uint(userID)); err == nil && personalID != nil {
- c.Set(CtxWorkspaceID, int(*personalID))
- c.Set(CtxWorkspaceRole, string(models.WorkspaceRoleOwner))
+ if ws, role, err := userRepo.DefaultWorkspace(uint(userID)); err == nil && ws != nil {
+ c.Set(CtxWorkspaceID, int(ws.ID))
+ c.Set(CtxWorkspaceRole, string(role))
}
}
return c.Next()
@@ -89,7 +102,7 @@ func resolveWorkspace(c *okapi.Context, workspaceRepo *repositories.WorkspaceRep
// RequireWorkspaceMiddleware demands an explicit workspace, except for a
// workspace-bound API key, whose binding names it.
-func RequireWorkspaceMiddleware(workspaceRepo *repositories.WorkspaceRepository, userRepo *repositories.UserRepository) okapi.Middleware {
+func RequireWorkspaceMiddleware(workspaceRepo *repositories.WorkspaceRepository, userRepo DefaultWorkspaceResolver) okapi.Middleware {
return func(c *okapi.Context) error {
return resolveWorkspace(c, workspaceRepo, userRepo, c.Header(WorkspaceHeader), true)
}
@@ -97,7 +110,7 @@ func RequireWorkspaceMiddleware(workspaceRepo *repositories.WorkspaceRepository,
// OptionalWorkspaceMiddleware resolves the workspace when named, and otherwise
// falls back to the caller's personal workspace.
-func OptionalWorkspaceMiddleware(workspaceRepo *repositories.WorkspaceRepository, userRepo *repositories.UserRepository) okapi.Middleware {
+func OptionalWorkspaceMiddleware(workspaceRepo *repositories.WorkspaceRepository, userRepo DefaultWorkspaceResolver) okapi.Middleware {
return func(c *okapi.Context) error {
return resolveWorkspace(c, workspaceRepo, userRepo, c.Header(WorkspaceHeader), false)
}
@@ -105,7 +118,7 @@ func OptionalWorkspaceMiddleware(workspaceRepo *repositories.WorkspaceRepository
// WorkspaceFromQueryOrHeader is OptionalWorkspaceMiddleware for browser-direct
// requests, which can pass the workspace only as a query parameter.
-func WorkspaceFromQueryOrHeader(workspaceRepo *repositories.WorkspaceRepository, userRepo *repositories.UserRepository) okapi.Middleware {
+func WorkspaceFromQueryOrHeader(workspaceRepo *repositories.WorkspaceRepository, userRepo DefaultWorkspaceResolver) okapi.Middleware {
return func(c *okapi.Context) error {
raw := c.Header(WorkspaceHeader)
if raw == "" {
diff --git a/internal/models/user.go b/internal/models/user.go
index dfcf5c8..a0eede3 100644
--- a/internal/models/user.go
+++ b/internal/models/user.go
@@ -30,9 +30,11 @@ type User struct {
CreatedAt time.Time `json:"created_at"`
LastLoginAt *time.Time `json:"last_login_at"`
- PersonalWorkspaceID *uint `json:"personal_workspace_id" gorm:"index"`
- MigratedAt *time.Time `json:"migrated_at"`
- MigrationError string `json:"migration_error,omitempty" gorm:"type:text"`
+ // DefaultWorkspaceID is where a request that names no workspace lands. It is
+ // user-settable and repaired when it points at a workspace the user has left.
+ DefaultWorkspaceID *uint `json:"default_workspace_id" gorm:"index"`
+ MigratedAt *time.Time `json:"-"`
+ MigrationError string `json:"-" gorm:"type:text"`
Plan Plan `json:"-" gorm:"foreignKey:PlanID"`
}
diff --git a/internal/models/workspace.go b/internal/models/workspace.go
index 2006e1e..8f90996 100644
--- a/internal/models/workspace.go
+++ b/internal/models/workspace.go
@@ -23,16 +23,19 @@ const (
)
type Workspace struct {
- ID uint `json:"id" gorm:"primaryKey"`
- Name string `json:"name" gorm:"not null"`
- Slug string `json:"slug" gorm:"uniqueIndex;not null"`
- Description string `json:"description"`
- OwnerID uint `json:"owner_id" gorm:"index;not null"`
- PlanID *uint `json:"plan_id" gorm:"index"`
- DefaultLanguage string `json:"default_language" gorm:"size:10;default:'en'"`
- IsPersonal bool `json:"is_personal" gorm:"not null;default:false"`
- CreatedAt time.Time `json:"created_at"`
- UpdatedAt time.Time `json:"updated_at"`
+ ID uint `json:"id" gorm:"primaryKey"`
+ Name string `json:"name" gorm:"not null"`
+ Slug string `json:"slug" gorm:"uniqueIndex;not null"`
+ Description string `json:"description"`
+ OwnerID uint `json:"owner_id" gorm:"index;not null"`
+ PlanID *uint `json:"plan_id" gorm:"index"`
+ DefaultLanguage string `json:"default_language" gorm:"size:10;default:'en'"`
+ // System marks the single built-in platform workspace. It owns
+ // platform-managed resources, is created on first boot, cannot be renamed or
+ // deleted, and admits only platform admins.
+ System bool `json:"system" gorm:"not null;default:false"`
+ CreatedAt time.Time `json:"created_at"`
+ UpdatedAt time.Time `json:"updated_at"`
Owner User `json:"-" gorm:"foreignKey:OwnerID"`
Plan Plan `json:"-" gorm:"foreignKey:PlanID"`
@@ -65,6 +68,9 @@ type WorkspaceInvitation struct {
Inviter User `json:"-" gorm:"foreignKey:InvitedBy"`
}
+// IsSystem reports whether this is the built-in platform workspace.
+func (w *Workspace) IsSystem() bool { return w.System }
+
// CanManageMembers returns true if the role can invite/remove members.
func (r WorkspaceRole) CanManageMembers() bool {
return r == WorkspaceRoleOwner || r == WorkspaceRoleAdmin
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
index d81e9bc..a8088ef 100644
--- a/internal/routes/routes.go
+++ b/internal/routes/routes.go
@@ -34,7 +34,7 @@ import (
"github.com/goposta/posta/internal/services/verifier"
"github.com/goposta/posta/internal/services/webhook"
"github.com/goposta/posta/internal/services/workermon"
- "github.com/goposta/posta/internal/services/workspacemigrate"
+ "github.com/goposta/posta/internal/services/workspaceprovision"
"github.com/goposta/posta/internal/storage/blob"
"github.com/goposta/posta/internal/storage/repositories"
"github.com/goposta/posta/internal/web"
@@ -122,8 +122,6 @@ type routerHandlers struct {
func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *config.Config, producer *worker.Producer, cronManager *cronpkg.Manager, blobStore blob.Store, ctx context.Context, notifier ...*notification.Service) *email.Service {
- repositories.SetWorkspaceOnlyMode(cfg.WorkspaceOnlyMode)
-
// Repositories
userRepo := repositories.NewUserRepository(db)
apiKeyRepo := repositories.NewAPIKeyRepository(db)
@@ -203,7 +201,7 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
// Handlers
userSeeder := seeder.New(templateRepo, stylesheetRepo, versionRepo, localizationRepo, languageRepo)
- migrator := workspacemigrate.New(cfg.PlanEnforcement)
+ migrator := workspaceprovision.New(cfg.PlanEnforcement)
migrator.SetSeeder(userSeeder)
userHandler := handlers.NewUserHandler(userRepo, cfg.JWTSecret, userSeeder, bus)
userHandler.SetSettings(settingsProvider)
diff --git a/internal/routes/user_routes.go b/internal/routes/user_routes.go
index aa240c3..d424d37 100644
--- a/internal/routes/user_routes.go
+++ b/internal/routes/user_routes.go
@@ -157,6 +157,20 @@ func (r *Router) userRoutes() []okapi.RouteDefinition {
Description: "Revoke the current session's JWT token",
Response: &dto.Response[any]{},
},
+ {
+ Method: http.MethodPut,
+ Path: "/default-workspace",
+ Handler: okapi.H(r.h.user.SetDefaultWorkspace),
+ Group: userGroup,
+ Summary: "Set the default workspace",
+ Description: "Chooses which workspace a request that sends no X-Posta-Workspace-Id header operates on. The caller must be a member.",
+ Request: &handlers.SetDefaultWorkspaceRequest{},
+ Response: &dto.Response[dto.MessageData]{},
+ Options: []okapi.RouteOption{
+ okapi.DocErrorResponse(400, &dto.ErrorResponseBody{}),
+ okapi.DocErrorResponse(404, &dto.ErrorResponseBody{}),
+ },
+ },
{
Method: http.MethodGet,
Path: "/audit-log",
diff --git a/internal/services/plan/service.go b/internal/services/plan/service.go
index 9a8ac98..b81b824 100644
--- a/internal/services/plan/service.go
+++ b/internal/services/plan/service.go
@@ -169,8 +169,12 @@ func (s *Service) CheckWorkspaceQuota(db *gorm.DB, userID uint) error {
return nil // unlimited
}
+ // The system workspace is platform infrastructure, not tenant capacity, so it
+ // never counts against the admin who happens to own it.
var count int64
- if err := db.Model(&models.Workspace{}).Where("owner_id = ?", userID).Count(&count).Error; err != nil {
+ if err := db.Model(&models.Workspace{}).
+ Where("owner_id = ? AND system = ?", userID, false).
+ Count(&count).Error; err != nil {
return fmt.Errorf("failed to count workspaces: %w", err)
}
diff --git a/internal/services/seeder/seeder.go b/internal/services/seeder/seeder.go
index 45b714f..299c02c 100644
--- a/internal/services/seeder/seeder.go
+++ b/internal/services/seeder/seeder.go
@@ -115,7 +115,11 @@ func (s *Seeder) SeedWorkspaceDefaults(workspaceID, userID uint, userName string
if userName == "" {
userName = "Jonas"
}
- templates, total, err := s.templateRepo.FindByUserID(userID, 1, 0)
+ // Scoped to the workspace being seeded, not to the user. A user's second
+ // workspace needs its own defaults, and a re-run against an already-seeded
+ // workspace must not duplicate them.
+ scope := repositories.ResourceScope{UserID: userID, WorkspaceID: &workspaceID}
+ templates, total, err := s.templateRepo.FindByScope(scope, "", 1, 0)
if err != nil || total > 0 || len(templates) > 0 {
return
}
diff --git a/internal/services/workspace/system.go b/internal/services/workspace/system.go
new file mode 100644
index 0000000..5c4e398
--- /dev/null
+++ b/internal/services/workspace/system.go
@@ -0,0 +1,138 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package workspace
+
+import (
+ "errors"
+ "fmt"
+
+ "github.com/goposta/posta/internal/models"
+ "github.com/jkaninda/logger"
+ "gorm.io/gorm"
+)
+
+const (
+ SystemSlug = "system"
+ SystemName = "Posta System"
+ SystemDescription = "Built-in workspace for platform-managed resources. Managed by platform administrators."
+)
+
+var ErrNoAdmin = errors.New("no active platform administrator to own the system workspace")
+
+// FindSystem returns the built-in platform workspace.
+func FindSystem(db *gorm.DB) (*models.Workspace, error) {
+ var ws models.Workspace
+ if err := db.Where("system = ?", true).First(&ws).Error; err != nil {
+ return nil, err
+ }
+ return &ws, nil
+}
+
+// EnsureSystem creates the built-in platform workspace when it does not exist,
+// owned by the lowest-id active administrator. Idempotent.
+func EnsureSystem(db *gorm.DB) (*models.Workspace, error) {
+ if ws, err := FindSystem(db); err == nil {
+ return ws, nil
+ } else if !errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, err
+ }
+
+ var owner models.User
+ if err := db.Where("role = ? AND active = ?", models.UserRoleAdmin, true).
+ Order("id ASC").First(&owner).Error; err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, ErrNoAdmin
+ }
+ return nil, fmt.Errorf("resolve system workspace owner: %w", err)
+ }
+
+ slug, err := availableSlug(db, SystemSlug)
+ if err != nil {
+ return nil, err
+ }
+
+ ws := &models.Workspace{
+ Name: SystemName,
+ Slug: slug,
+ Description: SystemDescription,
+ OwnerID: owner.ID,
+ System: true,
+ }
+
+ err = db.Transaction(func(tx *gorm.DB) error {
+ if err := tx.Create(ws).Error; err != nil {
+ return fmt.Errorf("create system workspace: %w", err)
+ }
+ member := &models.WorkspaceMember{
+ WorkspaceID: ws.ID,
+ UserID: owner.ID,
+ Role: models.WorkspaceRoleOwner,
+ }
+ if err := tx.Create(member).Error; err != nil {
+ return fmt.Errorf("create system workspace owner: %w", err)
+ }
+ return nil
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ logger.Info("platform system workspace ready", "workspace_id", ws.ID, "slug", ws.Slug, "owner_id", owner.ID)
+ return ws, nil
+}
+
+// SyncMembers makes the system workspace's membership match the set of active
+// platform administrators: every admin is a member, and nobody else is.
+func SyncMembers(db *gorm.DB) error {
+ ws, err := FindSystem(db)
+ if err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil
+ }
+ return err
+ }
+
+ var adminIDs []uint
+ if err := db.Model(&models.User{}).
+ Where("role = ? AND active = ?", models.UserRoleAdmin, true).
+ Pluck("id", &adminIDs).Error; err != nil {
+ return fmt.Errorf("list admins: %w", err)
+ }
+ if len(adminIDs) == 0 {
+ return nil
+ }
+
+ for _, id := range adminIDs {
+ role := models.WorkspaceRoleAdmin
+ if id == ws.OwnerID {
+ role = models.WorkspaceRoleOwner
+ }
+ member := models.WorkspaceMember{WorkspaceID: ws.ID, UserID: id, Role: role}
+ if err := db.Where("workspace_id = ? AND user_id = ?", ws.ID, id).
+ FirstOrCreate(&member).Error; err != nil {
+ return fmt.Errorf("add admin %d to system workspace: %w", id, err)
+ }
+ }
+
+ return db.Where("workspace_id = ? AND user_id NOT IN ?", ws.ID, adminIDs).
+ Delete(&models.WorkspaceMember{}).Error
+}
+
+// IsReservedSlug reports whether slug is claimable only by the system workspace.
+func IsReservedSlug(slug string) bool { return slug == SystemSlug }
+
+func availableSlug(db *gorm.DB, base string) (string, error) {
+ slug := base
+ for i := 2; i < 100; i++ {
+ var count int64
+ if err := db.Model(&models.Workspace{}).Where("slug = ?", slug).Count(&count).Error; err != nil {
+ return "", err
+ }
+ if count == 0 {
+ return slug, nil
+ }
+ slug = fmt.Sprintf("%s-%d", base, i)
+ }
+ return "", fmt.Errorf("could not find an available slug for %q", base)
+}
diff --git a/internal/services/workspace/system_test.go b/internal/services/workspace/system_test.go
new file mode 100644
index 0000000..248fd35
--- /dev/null
+++ b/internal/services/workspace/system_test.go
@@ -0,0 +1,17 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package workspace
+
+import "testing"
+
+func TestIsReservedSlug(t *testing.T) {
+ if !IsReservedSlug(SystemSlug) {
+ t.Fatalf("IsReservedSlug(%q) = false, want true", SystemSlug)
+ }
+ for _, slug := range []string{"acme", "system-2", "systems", "", "System"} {
+ if IsReservedSlug(slug) {
+ t.Fatalf("IsReservedSlug(%q) = true, want false", slug)
+ }
+ }
+}
diff --git a/internal/services/workspacemigrate/migrate.go b/internal/services/workspaceprovision/provision.go
similarity index 64%
rename from internal/services/workspacemigrate/migrate.go
rename to internal/services/workspaceprovision/provision.go
index b35e80c..46f1649 100644
--- a/internal/services/workspacemigrate/migrate.go
+++ b/internal/services/workspaceprovision/provision.go
@@ -1,7 +1,7 @@
// SPDX-FileCopyrightText: 2026 Jonas Kaninda
// SPDX-License-Identifier: AGPL-3.0-or-later
-package workspacemigrate
+package workspaceprovision
import (
"errors"
@@ -37,14 +37,15 @@ type Seeder interface {
SeedWorkspaceDefaults(workspaceID, userID uint, userName string)
}
-// Service performs personal-workspace migrations.
+// Service provisions a user's first workspace, and backfills workspaces for
+// users that predate workspace scoping.
type Service struct {
planEnforcement bool
seeder Seeder
}
-// New constructs a migration service.
+// New constructs a provisioning service.
func New(planEnforcement bool) *Service {
return &Service{planEnforcement: planEnforcement}
}
@@ -53,23 +54,25 @@ func (s *Service) SetSeeder(seeder Seeder) {
s.seeder = seeder
}
-func (s *Service) MigrateUser(db *gorm.DB, userID uint) (uint, error) {
+// EnsureWorkspace gives userID a workspace if they have none, and returns the
+// id of the workspace they should land in. Idempotent.
+func (s *Service) EnsureWorkspace(db *gorm.DB, userID uint) (uint, error) {
var existing models.User
- if err := db.Select("personal_workspace_id", "name").First(&existing, userID).Error; err == nil &&
- existing.PersonalWorkspaceID != nil {
- return *existing.PersonalWorkspaceID, nil
+ if err := db.Select("default_workspace_id", "name").First(&existing, userID).Error; err == nil &&
+ existing.DefaultWorkspaceID != nil {
+ return *existing.DefaultWorkspaceID, nil
}
var wsID uint
err := db.Transaction(func(tx *gorm.DB) error {
- id, e := s.migrate(tx, userID)
+ id, e := s.provision(tx, userID)
wsID = id
return e
})
if err != nil {
var u models.User
- if e := db.First(&u, userID).Error; e == nil && u.PersonalWorkspaceID != nil {
- return *u.PersonalWorkspaceID, nil
+ if e := db.First(&u, userID).Error; e == nil && u.DefaultWorkspaceID != nil {
+ return *u.DefaultWorkspaceID, nil
}
return 0, err
}
@@ -81,25 +84,28 @@ func (s *Service) MigrateUser(db *gorm.DB, userID uint) (uint, error) {
return wsID, nil
}
-func (s *Service) MigrateAllUnmigrated(tx *gorm.DB) error {
+// BackfillMissingWorkspaces gives every workspace-less user a workspace and
+// moves their legacy unscoped rows into it. Retained for installs upgrading from
+// before workspace scoping; a no-op once every user has one.
+func (s *Service) BackfillMissingWorkspaces(tx *gorm.DB) error {
var ids []uint
if err := tx.Model(&models.User{}).
- Where("personal_workspace_id IS NULL").
+ Where("default_workspace_id IS NULL").
Order("id").
Pluck("id", &ids).Error; err != nil {
return fmt.Errorf("list unmigrated users: %w", err)
}
- logger.Info("workspace migration: backfilling personal workspaces", "users", len(ids))
+ logger.Info("workspace backfill: provisioning workspaces", "users", len(ids))
migrated := 0
for _, id := range ids {
err := tx.Transaction(func(utx *gorm.DB) error {
- _, e := s.migrate(utx, id)
+ _, e := s.provision(utx, id)
return e
})
if err != nil {
- logger.Error("workspace migration failed for user", "user_id", id, "error", err)
+ logger.Error("workspace provisioning failed for user", "user_id", id, "error", err)
if uerr := tx.Model(&models.User{}).Where("id = ?", id).
Update("migration_error", err.Error()).Error; uerr != nil {
return fmt.Errorf("record migration error for user %d: %w", id, uerr)
@@ -109,19 +115,19 @@ func (s *Service) MigrateAllUnmigrated(tx *gorm.DB) error {
migrated++
}
- logger.Info("workspace migration: backfill complete", "migrated", migrated, "failed", len(ids)-migrated)
+ logger.Info("workspace backfill complete", "migrated", migrated, "failed", len(ids)-migrated)
return nil
}
-func (s *Service) migrate(tx *gorm.DB, userID uint) (uint, error) {
+func (s *Service) provision(tx *gorm.DB, userID uint) (uint, error) {
var user models.User
if err := tx.First(&user, userID).Error; err != nil {
return 0, fmt.Errorf("load user: %w", err)
}
- // Already migrated — no-op.
- if user.PersonalWorkspaceID != nil {
- return *user.PersonalWorkspaceID, nil
+ // Already has one — no-op.
+ if user.DefaultWorkspaceID != nil {
+ return *user.DefaultWorkspaceID, nil
}
// Resolve the plan (NULL in OSS / non-enforcing mode).
@@ -130,20 +136,14 @@ func (s *Service) migrate(tx *gorm.DB, userID uint) (uint, error) {
return 0, err
}
- // Create the personal workspace.
- name := strings.TrimSpace(user.Name)
- if name == "" {
- name = "Personal"
- }
ws := &models.Workspace{
- Name: name,
- Slug: personalSlug(user.ID),
- OwnerID: user.ID,
- IsPersonal: true,
- PlanID: planID,
+ Name: workspaceName(user.Name),
+ Slug: workspaceSlug(user.ID),
+ OwnerID: user.ID,
+ PlanID: planID,
}
if err := tx.Create(ws).Error; err != nil {
- return 0, fmt.Errorf("create personal workspace: %w", err)
+ return 0, fmt.Errorf("create workspace: %w", err)
}
// Owner member row
@@ -168,13 +168,12 @@ func (s *Service) migrate(tx *gorm.DB, userID uint) (uint, error) {
}
}
- // Mark the user migrated and clear any prior error.
if err := tx.Model(&models.User{}).Where("id = ?", user.ID).Updates(map[string]interface{}{
- "personal_workspace_id": ws.ID,
- "migrated_at": time.Now().UTC(),
- "migration_error": "",
+ "default_workspace_id": ws.ID,
+ "migrated_at": time.Now().UTC(),
+ "migration_error": "",
}).Error; err != nil {
- return 0, fmt.Errorf("mark user migrated: %w", err)
+ return 0, fmt.Errorf("record default workspace: %w", err)
}
return ws.ID, nil
@@ -224,7 +223,20 @@ func (s *Service) copySettings(tx *gorm.DB, userID, workspaceID uint, requireVer
return nil
}
-// personalSlug derives a stable, unique slug for a user's personal workspace.
-func personalSlug(userID uint) string {
- return fmt.Sprintf("personal-%d", userID)
+// workspaceName labels a user's first workspace after them, so a switcher with
+// several entries reads as names rather than as "Workspace 1, Workspace 2".
+func workspaceName(userName string) string {
+ first := strings.TrimSpace(userName)
+ if idx := strings.IndexAny(first, " \t"); idx > 0 {
+ first = first[:idx]
+ }
+ if first == "" {
+ return "My workspace"
+ }
+ return first + "'s workspace"
+}
+
+// workspaceSlug derives a stable, unique slug for a user's first workspace.
+func workspaceSlug(userID uint) string {
+ return fmt.Sprintf("workspace-%d", userID)
}
diff --git a/internal/services/workspacemigrate/migrate_test.go b/internal/services/workspaceprovision/provision_test.go
similarity index 59%
rename from internal/services/workspacemigrate/migrate_test.go
rename to internal/services/workspaceprovision/provision_test.go
index 00305b5..67c988d 100644
--- a/internal/services/workspacemigrate/migrate_test.go
+++ b/internal/services/workspaceprovision/provision_test.go
@@ -1,7 +1,7 @@
// SPDX-FileCopyrightText: 2026 Jonas Kaninda
// SPDX-License-Identifier: AGPL-3.0-or-later
-package workspacemigrate
+package workspaceprovision
import (
"fmt"
@@ -10,12 +10,27 @@ import (
"github.com/goposta/posta/internal/models"
)
-func TestPersonalSlugIsStableAndUnique(t *testing.T) {
- if got := personalSlug(42); got != "personal-42" {
- t.Fatalf("personalSlug(42) = %q, want %q", got, "personal-42")
+func TestWorkspaceSlugIsStableAndUnique(t *testing.T) {
+ if got := workspaceSlug(42); got != "workspace-42" {
+ t.Fatalf("workspaceSlug(42) = %q, want %q", got, "workspace-42")
}
- if personalSlug(1) == personalSlug(2) {
- t.Fatal("personalSlug must differ per user")
+ if workspaceSlug(1) == workspaceSlug(2) {
+ t.Fatal("workspaceSlug must differ per user")
+ }
+}
+
+func TestWorkspaceName(t *testing.T) {
+ cases := map[string]string{
+ "Jonas Kaninda": "Jonas's workspace",
+ "Ada": "Ada's workspace",
+ " Grace ": "Grace's workspace",
+ "": "My workspace",
+ " ": "My workspace",
+ }
+ for in, want := range cases {
+ if got := workspaceName(in); got != want {
+ t.Fatalf("workspaceName(%q) = %q, want %q", in, got, want)
+ }
}
}
diff --git a/internal/storage/migration/constraints.go b/internal/storage/migration/constraints.go
index 2d60301..5e6cdeb 100644
--- a/internal/storage/migration/constraints.go
+++ b/internal/storage/migration/constraints.go
@@ -65,7 +65,7 @@ func runConstraints(db *gorm.DB) {
END $$`)
db.Exec(`DO $$ BEGIN
- CREATE UNIQUE INDEX IF NOT EXISTS one_personal_per_user ON workspaces (owner_id) WHERE is_personal;
+ CREATE UNIQUE INDEX IF NOT EXISTS one_system_workspace ON workspaces ((true)) WHERE system;
EXCEPTION WHEN others THEN NULL;
END $$`)
diff --git a/internal/storage/migration/upgrade/step.go b/internal/storage/migration/upgrade/step.go
index b70f0e7..beb915f 100644
--- a/internal/storage/migration/upgrade/step.go
+++ b/internal/storage/migration/upgrade/step.go
@@ -29,6 +29,18 @@ var registry = []Step{
ID: "2026-06-11-api-key-scopes",
Apply: applyAPIKeyScopes,
},
+ {
+ ID: "2026-08-28-system-workspace",
+ Apply: applySystemWorkspace,
+ },
+ {
+ ID: "2026-08-28-personal-to-normal",
+ Apply: applyPersonalToNormal,
+ },
+ {
+ ID: "2026-08-28-default-workspace",
+ Apply: applyDefaultWorkspace,
+ },
}
func Registry() []Step {
diff --git a/internal/storage/migration/upgrade/step_test.go b/internal/storage/migration/upgrade/step_test.go
new file mode 100644
index 0000000..2d75798
--- /dev/null
+++ b/internal/storage/migration/upgrade/step_test.go
@@ -0,0 +1,66 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package upgrade
+
+import "testing"
+
+func TestRegistryIDsAreUniqueAndOrdered(t *testing.T) {
+ steps := Registry()
+ seen := make(map[string]bool, len(steps))
+ prev := ""
+
+ for i, s := range steps {
+ if s.ID == "" {
+ t.Fatalf("step %d has an empty id", i)
+ }
+ if s.Apply == nil {
+ t.Fatalf("step %q has no Apply func", s.ID)
+ }
+ if seen[s.ID] {
+ t.Fatalf("step %q is registered twice; applied steps are keyed by id", s.ID)
+ }
+ seen[s.ID] = true
+
+ // Only the date prefix must not go backwards. Steps sharing a date run in
+ // dependency order, which is rarely alphabetical: 2026-08-28-system-workspace
+ // has to precede the steps that read workspaces.system.
+ date := s.ID
+ if len(date) > 10 {
+ date = date[:10]
+ }
+ if prev != "" && date < prev {
+ t.Fatalf("step %q is dated before %q; the registry is append-only", s.ID, prev)
+ }
+ prev = date
+ }
+}
+
+func TestRegistryIsACopy(t *testing.T) {
+ a := Registry()
+ if len(a) == 0 {
+ t.Fatal("registry is empty")
+ }
+ a[0].ID = "mutated"
+
+ if Registry()[0].ID == "mutated" {
+ t.Fatal("Registry must hand out a copy; a caller mutated the in-tree registry")
+ }
+}
+
+func TestWorkspaceTypeStepsAreRegistered(t *testing.T) {
+ want := []string{
+ "2026-08-28-system-workspace",
+ "2026-08-28-personal-to-normal",
+ "2026-08-28-default-workspace",
+ }
+ got := make(map[string]bool)
+ for _, s := range Registry() {
+ got[s.ID] = true
+ }
+ for _, id := range want {
+ if !got[id] {
+ t.Fatalf("upgrade step %q is not registered", id)
+ }
+ }
+}
diff --git a/internal/storage/migration/upgrade/steps_2026_05_31_personal_workspaces.go b/internal/storage/migration/upgrade/steps_2026_05_31_personal_workspaces.go
index 7c916d5..8f10b80 100644
--- a/internal/storage/migration/upgrade/steps_2026_05_31_personal_workspaces.go
+++ b/internal/storage/migration/upgrade/steps_2026_05_31_personal_workspaces.go
@@ -4,13 +4,13 @@
package upgrade
import (
- "github.com/goposta/posta/internal/services/workspacemigrate"
+ "github.com/goposta/posta/internal/services/workspaceprovision"
"gorm.io/gorm"
)
// applyPersonalWorkspaces is the Apply func for the one-shot personal-workspace
// backfill.
func applyPersonalWorkspaces(tx *gorm.DB) error {
- svc := workspacemigrate.New(runOptions.PlanEnforcement)
- return svc.MigrateAllUnmigrated(tx)
+ svc := workspaceprovision.New(runOptions.PlanEnforcement)
+ return svc.BackfillMissingWorkspaces(tx)
}
diff --git a/internal/storage/migration/upgrade/steps_2026_08_28_workspace_types.go b/internal/storage/migration/upgrade/steps_2026_08_28_workspace_types.go
new file mode 100644
index 0000000..735b5fd
--- /dev/null
+++ b/internal/storage/migration/upgrade/steps_2026_08_28_workspace_types.go
@@ -0,0 +1,101 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package upgrade
+
+import (
+ "errors"
+ "fmt"
+
+ "github.com/goposta/posta/internal/services/workspace"
+ "github.com/jkaninda/logger"
+ "gorm.io/gorm"
+)
+
+// applySystemWorkspace creates the built-in platform workspace. A install with
+// no administrator yet (fresh database, admin seeded later) is not an error:
+// the server calls EnsureSystem again once seeding completes.
+func applySystemWorkspace(tx *gorm.DB) error {
+ if err := tx.Exec(`ALTER TABLE workspaces ADD COLUMN IF NOT EXISTS system boolean NOT NULL DEFAULT false`).Error; err != nil {
+ return fmt.Errorf("add workspaces.system: %w", err)
+ }
+ if err := tx.Exec(`CREATE UNIQUE INDEX IF NOT EXISTS one_system_workspace ON workspaces ((true)) WHERE system`).Error; err != nil {
+ return fmt.Errorf("create one_system_workspace: %w", err)
+ }
+
+ if _, err := workspace.EnsureSystem(tx); err != nil {
+ if errors.Is(err, workspace.ErrNoAdmin) {
+ logger.Info("system workspace deferred: no administrator yet")
+ return nil
+ }
+ return err
+ }
+ return nil
+}
+
+// applyPersonalToNormal turns every personal workspace into an ordinary one.
+// Nothing moves: ids, slugs, members, plans, and resources are untouched.
+func applyPersonalToNormal(tx *gorm.DB) error {
+ if !hasColumn(tx, "workspaces", "is_personal") {
+ return nil
+ }
+ res := tx.Exec(`UPDATE workspaces SET is_personal = false WHERE is_personal = true`)
+ if res.Error != nil {
+ return fmt.Errorf("flatten personal workspaces: %w", res.Error)
+ }
+ if res.RowsAffected > 0 {
+ logger.Info("workspace types: personal workspaces converted to normal", "count", res.RowsAffected)
+ }
+ return tx.Exec(`DROP INDEX IF EXISTS one_personal_per_user`).Error
+}
+
+// applyDefaultWorkspace renames personal_workspace_id to default_workspace_id so
+// every user keeps landing exactly where they landed before, then repairs any
+// value that points at a workspace the user is not a member of.
+func applyDefaultWorkspace(tx *gorm.DB) error {
+ switch {
+ case hasColumn(tx, "users", "default_workspace_id"):
+ // Already renamed, or created fresh by AutoMigrate.
+ if hasColumn(tx, "users", "personal_workspace_id") {
+ if err := tx.Exec(`
+ UPDATE users SET default_workspace_id = personal_workspace_id
+ WHERE default_workspace_id IS NULL AND personal_workspace_id IS NOT NULL`).Error; err != nil {
+ return fmt.Errorf("copy personal_workspace_id: %w", err)
+ }
+ }
+ case hasColumn(tx, "users", "personal_workspace_id"):
+ if err := tx.Exec(`ALTER TABLE users RENAME COLUMN personal_workspace_id TO default_workspace_id`).Error; err != nil {
+ return fmt.Errorf("rename personal_workspace_id: %w", err)
+ }
+ default:
+ return nil
+ }
+
+ res := tx.Exec(`
+ UPDATE users u SET default_workspace_id = (
+ SELECT m.workspace_id FROM workspace_members m
+ JOIN workspaces w ON w.id = m.workspace_id AND w.system = false
+ WHERE m.user_id = u.id
+ ORDER BY m.created_at ASC, m.workspace_id ASC
+ LIMIT 1
+ )
+ WHERE u.default_workspace_id IS NOT NULL
+ AND NOT EXISTS (
+ SELECT 1 FROM workspace_members m
+ WHERE m.user_id = u.id AND m.workspace_id = u.default_workspace_id
+ )`)
+ if res.Error != nil {
+ return fmt.Errorf("repair dangling default workspaces: %w", res.Error)
+ }
+ if res.RowsAffected > 0 {
+ logger.Info("workspace types: dangling default workspaces repaired", "count", res.RowsAffected)
+ }
+ return nil
+}
+
+func hasColumn(tx *gorm.DB, table, column string) bool {
+ var count int64
+ tx.Raw(`SELECT count(*) FROM information_schema.columns WHERE table_name = ? AND column_name = ?`,
+ table, column).Scan(&count)
+ return count > 0
+}
diff --git a/internal/storage/repositories/scope.go b/internal/storage/repositories/scope.go
index 8f031c0..42aacd0 100644
--- a/internal/storage/repositories/scope.go
+++ b/internal/storage/repositories/scope.go
@@ -13,36 +13,27 @@ type ResourceScope struct {
WorkspaceID *uint
}
-var workspaceOnlyMode bool
-
-// SetWorkspaceOnlyMode enables or disables the R6 personal-mode lock.
-func SetWorkspaceOnlyMode(enabled bool) { workspaceOnlyMode = enabled }
-
+// ApplyScope narrows a query to the caller's workspace. Every resource is
+// workspace-scoped; a scope without one matches nothing rather than falling back
+// to the pre-workspace "user_id AND workspace_id IS NULL" rows, which no longer
+// exist. UserID remains on the scope for attribution, and never selects rows.
func ApplyScope(db *gorm.DB, scope ResourceScope) *gorm.DB {
- if scope.WorkspaceID != nil {
- return db.Where("workspace_id = ?", *scope.WorkspaceID)
- }
- if workspaceOnlyMode {
- logger.Warn("ApplyScope: personal-mode scope rejected (workspace-only mode)", "user_id", scope.UserID)
+ if scope.WorkspaceID == nil {
+ logger.Warn("ApplyScope: request has no workspace; matching nothing", "user_id", scope.UserID)
return db.Where("1 = 0")
}
- return db.Where("user_id = ? AND workspace_id IS NULL", scope.UserID)
+ return db.Where("workspace_id = ?", *scope.WorkspaceID)
}
// OwnsResource checks whether the given resource belongs to the current scope.
-func OwnsResource(scope ResourceScope, resourceUserID uint, resourceWorkspaceID *uint) bool {
- if scope.WorkspaceID != nil {
- return resourceWorkspaceID != nil && *resourceWorkspaceID == *scope.WorkspaceID
- }
- return resourceUserID == scope.UserID && resourceWorkspaceID == nil
+func OwnsResource(scope ResourceScope, _ uint, resourceWorkspaceID *uint) bool {
+ return OwnsWorkspaceResource(scope, resourceWorkspaceID)
}
+// ApplyWorkspaceScope is an alias for ApplyScope, kept for one release so the
+// call sites added while the two behaved differently keep compiling.
func ApplyWorkspaceScope(db *gorm.DB, scope ResourceScope) *gorm.DB {
- if scope.WorkspaceID == nil {
- logger.Warn("ApplyWorkspaceScope: workspace-only resource requested without a workspace", "user_id", scope.UserID)
- return db.Where("1 = 0")
- }
- return db.Where("workspace_id = ?", *scope.WorkspaceID)
+ return ApplyScope(db, scope)
}
func OwnsWorkspaceResource(scope ResourceScope, resourceWorkspaceID *uint) bool {
diff --git a/internal/storage/repositories/scope_lock_test.go b/internal/storage/repositories/scope_lock_test.go
new file mode 100644
index 0000000..c0ee480
--- /dev/null
+++ b/internal/storage/repositories/scope_lock_test.go
@@ -0,0 +1,24 @@
+// SPDX-FileCopyrightText: 2026 Jonas Kaninda
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package repositories
+
+import "testing"
+
+func TestOwnsResourceIgnoresLegacyUserOwnership(t *testing.T) {
+ ws := uint(7)
+ other := uint(8)
+
+ if !OwnsResource(ResourceScope{UserID: 1, WorkspaceID: &ws}, 999, &ws) {
+ t.Fatal("a resource in the caller's workspace must be owned regardless of its user_id")
+ }
+ if OwnsResource(ResourceScope{UserID: 1, WorkspaceID: &ws}, 1, &other) {
+ t.Fatal("a resource in another workspace must never be owned, even when user_id matches")
+ }
+ if OwnsResource(ResourceScope{UserID: 1, WorkspaceID: &ws}, 1, nil) {
+ t.Fatal("an unscoped resource must not be owned once scoping is enforced")
+ }
+ if OwnsResource(ResourceScope{UserID: 1}, 1, nil) {
+ t.Fatal("a scope with no workspace must own nothing")
+ }
+}
diff --git a/internal/storage/repositories/user_repo.go b/internal/storage/repositories/user_repo.go
index b108fce..8d9b7b0 100644
--- a/internal/storage/repositories/user_repo.go
+++ b/internal/storage/repositories/user_repo.go
@@ -4,9 +4,11 @@
package repositories
import (
+ "errors"
"time"
"github.com/goposta/posta/internal/models"
+ "github.com/jkaninda/logger"
"gorm.io/gorm"
)
@@ -38,15 +40,84 @@ func (r *UserRepository) FindByID(id uint) (*models.User, error) {
return &user, nil
}
-func (r *UserRepository) PersonalWorkspaceID(userID uint) (*uint, error) {
+// DefaultWorkspace resolves where a request that names no workspace should land.
+// It verifies membership, so a stale default (the user left, or the workspace was
+// deleted) falls back to the oldest remaining membership and is repaired in place.
+// Returns (nil, "", nil) when the user belongs to no workspace at all.
+func (r *UserRepository) DefaultWorkspace(userID uint) (*models.Workspace, models.WorkspaceRole, error) {
var user models.User
- if err := r.db.Model(&models.User{}).
- Select("personal_workspace_id").
- Where("id = ?", userID).
- First(&user).Error; err != nil {
- return nil, err
+ if err := r.db.Select("id", "default_workspace_id").First(&user, userID).Error; err != nil {
+ return nil, "", err
+ }
+
+ if user.DefaultWorkspaceID != nil {
+ ws, role, err := r.WorkspaceForMember(userID, *user.DefaultWorkspaceID)
+ if err == nil {
+ return ws, role, nil
+ }
+ if !errors.Is(err, gorm.ErrRecordNotFound) {
+ return nil, "", err
+ }
+ }
+
+ ws, role, err := r.oldestMembership(userID)
+ if err != nil {
+ if errors.Is(err, gorm.ErrRecordNotFound) {
+ if user.DefaultWorkspaceID != nil {
+ _ = r.SetDefaultWorkspace(userID, nil)
+ }
+ return nil, "", nil
+ }
+ return nil, "", err
+ }
+
+ if err := r.SetDefaultWorkspace(userID, &ws.ID); err != nil {
+ logger.Warn("failed to repair default workspace", "user_id", userID, "error", err)
+ }
+ return ws, role, nil
+}
+
+// SetDefaultWorkspace records where header-less requests land. Nil clears it.
+func (r *UserRepository) SetDefaultWorkspace(userID uint, workspaceID *uint) error {
+ return r.db.Model(&models.User{}).Where("id = ?", userID).
+ Update("default_workspace_id", workspaceID).Error
+}
+
+// WorkspaceForMember returns the workspace and the caller's role in it, or
+// gorm.ErrRecordNotFound when they are not a member.
+func (r *UserRepository) WorkspaceForMember(userID, workspaceID uint) (*models.Workspace, models.WorkspaceRole, error) {
+ var row struct {
+ models.Workspace
+ Role models.WorkspaceRole
+ }
+ err := r.db.Model(&models.Workspace{}).
+ Select("workspaces.*, workspace_members.role AS role").
+ Joins("JOIN workspace_members ON workspace_members.workspace_id = workspaces.id").
+ Where("workspaces.id = ? AND workspace_members.user_id = ?", workspaceID, userID).
+ First(&row).Error
+ if err != nil {
+ return nil, "", err
+ }
+ ws := row.Workspace
+ return &ws, row.Role, nil
+}
+
+func (r *UserRepository) oldestMembership(userID uint) (*models.Workspace, models.WorkspaceRole, error) {
+ var row struct {
+ models.Workspace
+ Role models.WorkspaceRole
+ }
+ err := r.db.Model(&models.Workspace{}).
+ Select("workspaces.*, workspace_members.role AS role").
+ Joins("JOIN workspace_members ON workspace_members.workspace_id = workspaces.id").
+ Where("workspace_members.user_id = ? AND workspaces.system = ?", userID, false).
+ Order("workspace_members.created_at ASC, workspaces.id ASC").
+ First(&row).Error
+ if err != nil {
+ return nil, "", err
}
- return user.PersonalWorkspaceID, nil
+ ws := row.Workspace
+ return &ws, row.Role, nil
}
func (r *UserRepository) FindAll(search string, limit, offset int) ([]models.User, int64, error) {
diff --git a/internal/storage/repositories/workspace_repo.go b/internal/storage/repositories/workspace_repo.go
index 9c9e7dd..fab8b7c 100644
--- a/internal/storage/repositories/workspace_repo.go
+++ b/internal/storage/repositories/workspace_repo.go
@@ -65,19 +65,51 @@ func (r *WorkspaceRepository) FindAll() ([]models.Workspace, error) {
return workspaces, nil
}
-// FindByUserID returns all workspaces the user is a member of.
+// FindByUserID returns all workspaces the user is a member of. The system
+// workspace sorts last so it never displaces a real one at the top of a list.
func (r *WorkspaceRepository) FindByUserID(userID uint) ([]models.Workspace, error) {
var workspaces []models.Workspace
if err := r.db.
Joins("JOIN workspace_members ON workspace_members.workspace_id = workspaces.id").
Where("workspace_members.user_id = ?", userID).
- Order("workspaces.created_at DESC").
+ Order("workspaces.system ASC, workspaces.created_at DESC").
Find(&workspaces).Error; err != nil {
return nil, err
}
return workspaces, nil
}
+// FindSystem returns the built-in platform workspace.
+func (r *WorkspaceRepository) FindSystem() (*models.Workspace, error) {
+ var ws models.Workspace
+ if err := r.db.Where("system = ?", true).First(&ws).Error; err != nil {
+ return nil, err
+ }
+ return &ws, nil
+}
+
+// SlugExists reports whether slug is taken by a workspace other than excludeID.
+func (r *WorkspaceRepository) SlugExists(slug string, excludeID uint) bool {
+ var count int64
+ q := r.db.Model(&models.Workspace{}).Where("slug = ?", slug)
+ if excludeID > 0 {
+ q = q.Where("id <> ?", excludeID)
+ }
+ q.Count(&count)
+ return count > 0
+}
+
+// CountNonSystemMemberships returns how many ordinary workspaces the user
+// belongs to. Used to refuse deleting somebody's last workspace.
+func (r *WorkspaceRepository) CountNonSystemMemberships(userID uint) int64 {
+ var count int64
+ r.db.Model(&models.WorkspaceMember{}).
+ Joins("JOIN workspaces ON workspaces.id = workspace_members.workspace_id").
+ Where("workspace_members.user_id = ? AND workspaces.system = ?", userID, false).
+ Count(&count)
+ return count
+}
+
// AddMember adds a user as a member of a workspace.
func (r *WorkspaceRepository) AddMember(member *models.WorkspaceMember) error {
return r.db.Create(member).Error
diff --git a/web/src/api/types.ts b/web/src/api/types.ts
index 2cd20cd..a822651 100644
--- a/web/src/api/types.ts
+++ b/web/src/api/types.ts
@@ -543,8 +543,7 @@ export interface AdminMetrics {
failed_logins_last_24h: number
two_factor_adoption_rate: number
two_factor_users: number
- users_unmigrated: number
- users_migration_failed: number
+ users_without_workspace: number
}
export interface WorkerStatus {
@@ -878,7 +877,7 @@ export interface Workspace {
description: string
owner_id: number
role: WorkspaceRole
- is_personal: boolean
+ system: boolean
created_at: string
}
diff --git a/web/src/layouts/DashboardLayout.vue b/web/src/layouts/DashboardLayout.vue
index abfb9c0..1f118ea 100644
--- a/web/src/layouts/DashboardLayout.vue
+++ b/web/src/layouts/DashboardLayout.vue
@@ -21,17 +21,6 @@ const userMenuOpen = ref(false)
const wsSwitcherOpen = ref(false)
const themeModes = ['light', 'dark', 'system'] as const
-// One-time banner introducing the personal workspace after the workspace-only
-// migration cutover. Dismissal is remembered in localStorage.
-const PERSONAL_BANNER_KEY = 'posta_personal_ws_banner_dismissed'
-const personalBannerDismissed = ref(localStorage.getItem(PERSONAL_BANNER_KEY) === 'true')
-const showPersonalBanner = computed(
- () => wsStore.currentWorkspaceIsPersonal && !personalBannerDismissed.value
-)
-function dismissPersonalBanner() {
- personalBannerDismissed.value = true
- localStorage.setItem(PERSONAL_BANNER_KEY, 'true')
-}
function goWorkspaceSettings() {
const id = wsStore.currentWorkspace?.id
@@ -109,8 +98,8 @@ interface NavItem {
requiresWorkspace?: boolean
/** Only show when the user is an owner or admin of the current workspace. */
requiresWorkspaceAdmin?: boolean
- /** Hidden when the active workspace is the user's personal one (no team). */
- hideInPersonal?: boolean
+ /** Hidden while the active workspace is the platform's system workspace. */
+ hideInSystem?: boolean
/** Only show when the backend exposes the OpenAPI docs. */
requiresOpenapiDocs?: boolean
/** Deep-link into a WorkspaceSettings tab of the current workspace. */
@@ -222,7 +211,7 @@ const navSections: NavSection[] = [
defaultOpen: true,
items: [
{ name: 'All Workspaces', path: '/workspaces', icon: 'layers' },
- { name: 'Members', path: '', icon: 'users', workspaceSubpath: 'members', hideInPersonal: true },
+ { name: 'Members', path: '', icon: 'users', workspaceSubpath: 'members' },
{ name: 'Audit Log', path: '/audit-log', icon: 'history' },
{ name: 'Settings', path: '', icon: 'settings', workspaceTab: 'settings', requiresWorkspaceAdmin: true },
],
@@ -279,7 +268,7 @@ function sectionItems(section: NavSection): NavItem[] {
return section.items.filter((item) => {
if (item.requiresWorkspace && !wsStore.isWorkspaceContext) return false
if (item.requiresWorkspaceAdmin && !wsStore.isWorkspaceAdmin) return false
- if (item.hideInPersonal && wsStore.currentWorkspaceIsPersonal) return false
+ if (item.hideInSystem && wsStore.currentWorkspaceIsSystem) return false
if (item.requiresOpenapiDocs && !appInfo.value?.openapi_docs) return false
return true
})
@@ -419,7 +408,7 @@ function getIcon(name: string): string {
:class="{ active: wsStore.currentWorkspaceId === ws.id }" @click="switchContext(ws.id)">
<div class="ws-avatar-sm">{{ ws.name.charAt(0).toUpperCase() }}</div>
<span>{{ ws.name }}</span>
- <span class="ws-role-badge">{{ ws.is_personal ? 'personal' : ws.role }}</span>
+ <span class="ws-role-badge" :class="{ 'ws-role-badge--system': ws.system }">{{ ws.system ? 'system' : ws.role }}</span>
</div>
<div class="ws-switcher-divider"></div>
<div class="ws-switcher-action" @click="createWorkspace">
@@ -595,25 +584,6 @@ function getIcon(name: string): string {
aria-label="Dismiss until the next release" @click="dismissUpdate">×</button>
</div>
</div>
- <div v-if="showPersonalBanner" class="app-banner app-banner--info personal-ws-banner">
- <svg class="app-banner-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
- stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
- <circle cx="12" cy="12" r="10" />
- <line x1="12" y1="16" x2="12" y2="12" />
- <line x1="12" y1="8" x2="12.01" y2="8" />
- </svg>
- <div class="app-banner-content">
- <p class="app-banner-title">Your personal workspace is ready</p>
- <p class="app-banner-text">
- Your data now lives in <strong>{{ wsStore.currentWorkspace?.name }}</strong>.
- Invite collaborators or rename it in workspace settings.
- </p>
- </div>
- <div class="app-banner-actions">
- <button class="app-banner-btn" @click="goWorkspaceSettings">Workspace settings</button>
- <button class="app-banner-dismiss" @click="dismissPersonalBanner" aria-label="Dismiss banner">×</button>
- </div>
- </div>
<router-view />
</main>
<footer class="main-footer">
@@ -678,7 +648,7 @@ function getIcon(name: string): string {
<span class="ws-avatar">{{ ws.name?.charAt(0)?.toUpperCase() }}</span>
<div style="display: flex; flex-direction: column;">
<span>{{ ws.name }}</span>
- <small style="font-size: 0.75rem; opacity: 0.7;">{{ ws.is_personal ? 'personal' : ws.role }}</small>
+ <small style="font-size: 0.75rem; opacity: 0.7;">{{ ws.system ? 'system' : ws.role }}</small>
</div>
</div>
@@ -1355,10 +1325,9 @@ function getIcon(name: string): string {
padding: 28px;
}
-/* ─── Personal workspace intro banner ─── */
-/* Visuals come from the shared .app-banner system; only spacing is local. */
-.personal-ws-banner {
- margin-bottom: 20px;
+.ws-role-badge--system {
+ background: var(--warning-50);
+ color: var(--warning-600);
}
/* ─── Footer ─── */
diff --git a/web/src/stores/workspace.ts b/web/src/stores/workspace.ts
index 29b4477..b49d20d 100644
--- a/web/src/stores/workspace.ts
+++ b/web/src/stores/workspace.ts
@@ -20,22 +20,24 @@ export const useWorkspaceStore = defineStore('workspace', () => {
)
const currentRole = computed(() => currentWorkspace.value?.role ?? null)
- const isPersonal = computed(() => currentWorkspaceId.value === null)
const isWorkspaceContext = computed(() => currentWorkspaceId.value !== null)
const isWorkspaceAdmin = computed(() => currentRole.value === 'owner' || currentRole.value === 'admin')
+ // No workspace means no permissions. The pre-workspace era granted edit rights
+ // to a context with no workspace; every resource is scoped now, so a caller
+ // without one can read and write nothing.
const canEdit = computed(() => {
- if (!currentWorkspaceId.value) return true // personal mode
const role = currentRole.value
return role === 'owner' || role === 'admin' || role === 'editor'
})
- // The user's auto-provisioned personal workspace (workspace-only migration).
- const personalWorkspace = computed(() => workspaces.value.find((w) => w.is_personal) ?? null)
- // True when the active workspace is the user's personal one — used to hide
- // team-only affordances (Members, Plan & Billing).
- const currentWorkspaceIsPersonal = computed(() => currentWorkspace.value?.is_personal ?? false)
+ // Ordinary workspaces, i.e. everything the user actually works in. The system
+ // workspace is platform infrastructure and only platform admins can see it.
+ const ownWorkspaces = computed(() => workspaces.value.filter((w) => !w.system))
+ const systemWorkspace = computed(() => workspaces.value.find((w) => w.system) ?? null)
+ const currentWorkspaceIsSystem = computed(() => currentWorkspace.value?.system ?? false)
+ const hasWorkspace = computed(() => ownWorkspaces.value.length > 0)
- const contextLabel = computed(() => currentWorkspace.value?.name ?? 'Personal')
+ const contextLabel = computed(() => currentWorkspace.value?.name ?? 'No workspace')
function setWorkspace(wsId: number | null) {
currentWorkspaceId.value = wsId
@@ -51,11 +53,10 @@ export const useWorkspaceStore = defineStore('workspace', () => {
const res = await workspaceApi.list()
workspaces.value = res.data.data ?? []
const valid = currentWorkspaceId.value && workspaces.value.find((w) => w.id === currentWorkspaceId.value)
- // After the workspace-only migration every user owns a personal workspace.
- // Land there by default (instead of legacy header-less "personal mode") so
- // the active context always maps to a real workspace.
+ // Land in an ordinary workspace, never the system one: a platform admin
+ // opening the dashboard wants their own work, not platform infrastructure.
if (!valid) {
- setWorkspace(personalWorkspace.value?.id ?? null)
+ setWorkspace(ownWorkspaces.value[0]?.id ?? null)
}
} catch {
workspaces.value = []
@@ -72,12 +73,13 @@ export const useWorkspaceStore = defineStore('workspace', () => {
currentWorkspaceId,
currentWorkspace,
currentRole,
- isPersonal,
isWorkspaceContext,
isWorkspaceAdmin,
canEdit,
- personalWorkspace,
- currentWorkspaceIsPersonal,
+ ownWorkspaces,
+ systemWorkspace,
+ currentWorkspaceIsSystem,
+ hasWorkspace,
contextLabel,
setWorkspace,
fetchWorkspaces,
diff --git a/web/src/views/admin/AdminHealth.vue b/web/src/views/admin/AdminHealth.vue
index 6ed854e..11e4868 100644
--- a/web/src/views/admin/AdminHealth.vue
+++ b/web/src/views/admin/AdminHealth.vue
@@ -99,14 +99,11 @@ const health = computed(() => {
);
}
- if (m.users_migration_failed > 0) {
- raise("crit");
- reasons.push(`Workspace migration failed for ${m.users_migration_failed} user(s)`);
- }
-
- if (m.users_unmigrated > 0) {
+ if (m.users_without_workspace > 0) {
raise("warn");
- reasons.push(`${m.users_unmigrated} user(s) have not been migrated to a workspace`);
+ reasons.push(
+ `${m.users_without_workspace} user(s) belong to no workspace and land on an empty dashboard`
+ );
}
for (const meter of meters.value) {
diff --git a/web/src/views/dashboard/Dashboard.vue b/web/src/views/dashboard/Dashboard.vue
index 3417928..bc25d66 100644
--- a/web/src/views/dashboard/Dashboard.vue
+++ b/web/src/views/dashboard/Dashboard.vue
@@ -163,6 +163,14 @@ watch(currentWorkspaceId, () => load(true));
</div>
</template>
+ <div v-else-if="!ws.hasWorkspace" class="card">
+ <div class="empty-state">
+ <h3>No workspace yet</h3>
+ <p>Everything in Posta belongs to a workspace. Create one to start sending.</p>
+ <button class="btn btn-primary" @click="router.push('/workspaces')">Create workspace</button>
+ </div>
+ </div>
+
<div v-else class="card">
<div class="empty-state">
<h3>Dashboard unavailable</h3>
diff --git a/web/src/views/workspaces/WorkspaceSettings.vue b/web/src/views/workspaces/WorkspaceSettings.vue
index ed84dd0..960cbd4 100644
--- a/web/src/views/workspaces/WorkspaceSettings.vue
+++ b/web/src/views/workspaces/WorkspaceSettings.vue
@@ -94,8 +94,11 @@ const myRole = computed(() => {
})
const isAdminOrOwner = computed(() => myRole.value === 'owner' || myRole.value === 'admin')
const isOwner = computed(() => myRole.value === 'owner')
-// Personal workspaces are auto-provisioned and cannot be deleted (enforced server-side).
-const isPersonal = computed(() => ws.value?.is_personal ?? false)
+// The system workspace is platform infrastructure and cannot be deleted or
+// renamed (enforced server-side). A user's last workspace cannot be deleted
+// either, since it would leave them with nowhere to work.
+const isSystem = computed(() => ws.value?.system ?? false)
+const isLastWorkspace = computed(() => wsStore.ownWorkspaces.length <= 1)
async function withWorkspace<T>(fn: () => Promise<T>): Promise<T> {
const prevWs = wsStore.currentWorkspaceId
@@ -617,18 +620,23 @@ watch(activeTab, (value) => {
</div>
</div>
- <div v-if="isOwner && !isPersonal" class="card-body" style="border-top: 1px solid var(--border-primary);">
+ <div v-if="isOwner && isSystem" class="card-body" style="border-top: 1px solid var(--border-primary);">
+ <p style="font-size: 13px; color: var(--text-muted);">
+ This is the platform system workspace. It owns platform-managed resources and cannot be renamed or deleted.
+ </p>
+ </div>
+ <div v-else-if="isOwner && isLastWorkspace" class="card-body" style="border-top: 1px solid var(--border-primary);">
+ <p style="font-size: 13px; color: var(--text-muted);">
+ This is your only workspace. Create another before deleting this one.
+ </p>
+ </div>
+ <div v-else-if="isOwner" class="card-body" style="border-top: 1px solid var(--border-primary);">
<h4 style="color: var(--danger-600); margin-bottom: 8px;">Danger Zone</h4>
<p style="font-size: 13px; color: var(--text-muted); margin-bottom: 12px;">
Deleting this workspace will permanently remove all its resources. This cannot be undone.
</p>
<button class="btn btn-danger" @click="deleteWorkspace">Delete Workspace</button>
</div>
- <div v-else-if="isOwner && isPersonal" class="card-body" style="border-top: 1px solid var(--border-primary);">
- <p style="font-size: 13px; color: var(--text-muted);">
- This is your personal workspace and cannot be deleted. It is removed only if you delete your account.
- </p>
- </div>
</div>
<!-- Data Management (GDPR) Tab — admin/owner only -->