From 6c091395ac63229ba8ce074f76ac6a16b9a97b96 Mon Sep 17 00:00:00 2001 From: "Jon Radoff (Metavert)" Date: Mon, 9 Nov 2026 21:34:30 -0500 Subject: [PATCH 1/2] Enforce the agent sandbox on the server The sandbox was a variable in one MCP session: the REST API didn't know about it, ending it lifted every restriction, and webhooks, settings, imports and approvals ignored it. It is now a property of the API key or OAuth connection. - Access: each key and connection is Sandbox (only forks it created) or Full (its owner's role). New OAuth connections and new keys made in the admin UI start as Sandbox; existing keys keep Full. - A default-deny table lists the write routes a sandboxed caller may use. Everything else is refused in the REST layer, whichever tool or client sends it, and a test fails on any route not decided in it. - Writes must target a fork the same key or connection created. Uploads are limited to new images, PDFs, fonts and text; nothing executable, and nothing replaced. - start_agent_sandbox records the fork on the credential (REST: GET/POST /api/v1/sandbox, POST /api/v1/sandbox/end), so it applies to every session and survives a restart. Ending it on a Sandbox credential only hands the fork off. A sandboxed caller can discard its own forks. - Connected Apps (/cm/connected-apps) lists, changes and disconnects OAuth connections; API keys get the same Access setting. Letting a credential merge its own forks is stored here, settable only by a signed-in admin for an account that can merge, and enforced next. - MCP tools no longer block anything themselves; the server does. Co-Authored-By: Claude Opus 5.5 --- cmd/server/main.go | 2 + internal/apiclient/client.go | 40 ++ internal/auth/credentials.go | 38 +- internal/auth/credentials_test.go | 42 +- internal/auth/permissions.go | 26 +- internal/handlers/admin_routes.go | 8 + internal/handlers/admin_routes_guard_test.go | 8 + internal/handlers/admin_templates.go | 119 +++- internal/handlers/admin_ui_guard_743_test.go | 2 +- internal/handlers/api.go | 5 +- internal/handlers/api_assets.go | 44 +- internal/handlers/api_content.go | 19 +- internal/handlers/api_forks.go | 37 +- internal/handlers/api_identity_test.go | 64 +- internal/handlers/api_routes.go | 6 + internal/handlers/api_sandbox.go | 308 +++++++++ internal/handlers/api_sandbox_test.go | 664 +++++++++++++++++++ internal/handlers/fork_followups_test.go | 1 + internal/handlers/governance_api_test.go | 20 +- internal/handlers/handlers.go | 36 +- internal/handlers/handlers_connections.go | 223 +++++++ internal/handlers/testhelper_test.go | 2 + internal/mcp/content_tools.go | 36 +- internal/mcp/coverage_more_test.go | 12 - internal/mcp/draft_safety_test.go | 11 - internal/mcp/fork_tools.go | 14 - internal/mcp/sandbox_test.go | 158 +++-- internal/mcp/sandbox_tools.go | 162 ++--- internal/mcp/search_tools.go | 3 - internal/mcp/server.go | 1 - internal/mcp/settings_tools.go | 3 - internal/models/models.go | 39 +- internal/models/oauth.go | 16 +- internal/oauth/handler.go | 13 +- internal/oauth/handler_test.go | 2 +- internal/oauth/identity_test.go | 71 ++ internal/oauth/templates.go | 33 +- internal/services/apikey.go | 33 + internal/services/asset.go | 14 + internal/services/fork.go | 33 +- internal/services/oauth.go | 51 +- internal/services/oauth_grant_test.go | 12 +- internal/services/oauth_test.go | 2 +- 43 files changed, 2104 insertions(+), 329 deletions(-) create mode 100644 internal/handlers/api_sandbox.go create mode 100644 internal/handlers/api_sandbox_test.go create mode 100644 internal/handlers/handlers_connections.go diff --git a/cmd/server/main.go b/cmd/server/main.go index c773c13..2696ba3 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -297,6 +297,8 @@ func main() { log.Printf("Removed the legacy system API key") } + apiHandler.SetOAuthService(oauthService) + h.SetOAuthService(oauthService) oauthHandler := oauth.NewHandler(oauthService, authManager, cfg.BaseURL, cfg.SessionSecret) // Allow browser-based admin UI calls to /api/v1/ using session cookies (no Bearer token required). diff --git a/internal/apiclient/client.go b/internal/apiclient/client.go index 41fb48e..8607c0f 100644 --- a/internal/apiclient/client.go +++ b/internal/apiclient/client.go @@ -1022,6 +1022,46 @@ func (c *Client) GetForkDiff(ctx context.Context, forkID string) (*ForkDiff, err return &result, nil } +// SandboxState is the caller's agent sandbox, as the server keeps it on the +// API key or OAuth connection. +type SandboxState struct { + Active bool `json:"active"` + Restricted bool `json:"restricted"` // the key or connection is set to Sandbox access + CanMergeOwnForks bool `json:"can_merge_own_forks"` + ForkID string `json:"fork_id,omitempty"` + Name string `json:"name,omitempty"` + ReviewURL string `json:"review_url,omitempty"` +} + +// GetSandbox returns the caller's sandbox. +func (c *Client) GetSandbox(ctx context.Context) (*SandboxState, error) { + var result SandboxState + if err := c.do(ctx, "GET", "/sandbox", nil, &result); err != nil { + return nil, err + } + return &result, nil +} + +// StartSandbox opens a sandbox: a new fork that every later request from this +// key or connection is held to until the sandbox ends. +func (c *Client) StartSandbox(ctx context.Context, name, description string) (*SandboxState, error) { + var result SandboxState + if err := c.do(ctx, "POST", "/sandbox", map[string]string{"name": name, "description": description}, &result); err != nil { + return nil, err + } + return &result, nil +} + +// EndSandbox closes the caller's sandbox: "submit" leaves the fork for +// review, "discard" deletes it. +func (c *Client) EndSandbox(ctx context.Context, action string) (map[string]interface{}, error) { + var result map[string]interface{} + if err := c.do(ctx, "POST", "/sandbox/end", map[string]string{"action": action}, &result); err != nil { + return nil, err + } + return result, nil +} + // GetAgentSessionChanges returns the audit ledger for an agent session. func (c *Client) GetAgentSessionChanges(ctx context.Context, sessionID string) (map[string]interface{}, error) { var result map[string]interface{} diff --git a/internal/auth/credentials.go b/internal/auth/credentials.go index d06987c..8bb2533 100644 --- a/internal/auth/credentials.go +++ b/internal/auth/credentials.go @@ -7,6 +7,8 @@ import ( "github.com/metavert-io/lightcms/v7/internal/models" "github.com/metavert-io/lightcms/v7/internal/services" + + "go.mongodb.org/mongo-driver/bson/primitive" ) // CredentialResolver turns an API key or OAuth access token into the person it @@ -40,13 +42,15 @@ func (c *CredentialResolver) ResolveAPIKey(ctx context.Context, rawKey string) ( } c.recordActivity(owner) return &SessionUser{ - ID: owner.ID.Hex(), - Email: owner.Email, - Role: owner.Role, - ViaAPIKey: true, - Credential: "apikey:" + key.ID.Hex(), - Scopes: key.Scopes, - SandboxOnly: key.SandboxOnly, + ID: owner.ID.Hex(), + Email: owner.Email, + Role: owner.Role, + ViaAPIKey: true, + Credential: "apikey:" + key.ID.Hex(), + Scopes: key.Scopes, + SandboxOnly: key.SandboxOnly, + CanMergeOwnForks: key.CanMergeOwnForks, + ActiveSandboxFork: hexOrEmpty(key.ActiveSandboxFork), }, nil } @@ -65,14 +69,24 @@ func (c *CredentialResolver) ResolveOAuthToken(ctx context.Context, rawToken str } c.recordActivity(user) return &SessionUser{ - ID: user.ID.Hex(), - Email: user.Email, - Role: user.Role, - ViaOAuth: true, - Credential: "oauth:" + grant.ID.Hex(), + ID: user.ID.Hex(), + Email: user.Email, + Role: user.Role, + ViaOAuth: true, + Credential: "oauth:" + grant.ID.Hex(), + SandboxOnly: grant.SandboxOnly, + CanMergeOwnForks: grant.CanMergeOwnForks, + ActiveSandboxFork: hexOrEmpty(grant.ActiveSandboxFork), }, nil } +func hexOrEmpty(id *primitive.ObjectID) string { + if id == nil || id.IsZero() { + return "" + } + return id.Hex() +} + // keyOwner returns the active user an API key belongs to. A key with no owner // on record predates ownership and is given to the first active admin, once; // it keeps its restrictions. A key whose owner cannot be loaded is refused, diff --git a/internal/auth/credentials_test.go b/internal/auth/credentials_test.go index 8499cc7..771a543 100644 --- a/internal/auth/credentials_test.go +++ b/internal/auth/credentials_test.go @@ -54,7 +54,7 @@ func (f *credentialFixture) accessToken(t *testing.T, user *models.User) (string if err != nil { t.Fatalf("RegisterClient: %v", err) } - grant, err := f.oauth.SaveGrant(ctx, client, user.ID, credentialTestResource) + grant, err := f.oauth.SaveGrant(ctx, client, user.ID, credentialTestResource, services.AccessSettings{}) if err != nil { t.Fatalf("SaveGrant: %v", err) } @@ -280,3 +280,43 @@ func TestCredentialResolver_ReportsActivity(t *testing.T) { t.Errorf("activity recorded for %q", seen) } } + +func TestResolver_CarriesAccessSettingsAndOpenSandbox(t *testing.T) { + f := newCredentialFixture(t) + ctx := context.Background() + admin := f.user(t, "admin@example.com", models.RoleAdmin) + + raw, key, _ := f.keys.CreateScopedAPIKey(ctx, "Agent", "", &admin.ID, nil, true) + fork := primitive.NewObjectID() + if err := f.keys.UpdateAccess(ctx, key.ID, services.AccessSettings{SandboxOnly: true, CanMergeOwnForks: true}); err != nil { + t.Fatalf("UpdateAccess: %v", err) + } + if err := f.keys.SetActiveSandbox(ctx, key.ID, &fork); err != nil { + t.Fatalf("SetActiveSandbox: %v", err) + } + v, err := f.resolver.ResolveAPIKey(ctx, raw) + got := caller(t, v, err) + if !got.SandboxOnly || !got.CanMergeOwnForks || got.ActiveSandboxFork != fork.Hex() || !got.Sandboxed() { + t.Errorf("key caller: %+v", got) + } + + token, grant := f.accessToken(t, admin) + if err := f.oauth.SetActiveSandbox(ctx, grant.ID, &fork); err != nil { + t.Fatalf("SetActiveSandbox: %v", err) + } + v, err = f.resolver.ResolveOAuthToken(ctx, token) + got = caller(t, v, err) + if got.SandboxOnly || got.ActiveSandboxFork != fork.Hex() || !got.Sandboxed() { + t.Errorf("a Full connection with a sandbox open: %+v", got) + } + if UserHasPermission(got, PermContentPublish) { + t.Error("a caller with a sandbox open may not publish") + } + if err := f.oauth.SetActiveSandbox(ctx, grant.ID, nil); err != nil { + t.Fatalf("SetActiveSandbox(nil): %v", err) + } + v, err = f.resolver.ResolveOAuthToken(ctx, token) + if got = caller(t, v, err); got.Sandboxed() || !UserHasPermission(got, PermContentPublish) { + t.Errorf("after the sandbox ended: %+v", got) + } +} diff --git a/internal/auth/permissions.go b/internal/auth/permissions.go index 6d16a22..3858c50 100644 --- a/internal/auth/permissions.go +++ b/internal/auth/permissions.go @@ -135,16 +135,30 @@ type SessionUser struct { ViaOAuth bool `json:"via_oauth,omitempty"` // true when authenticated via an OAuth connection (not session) Credential string `json:"credential,omitempty"` // the API key or OAuth connection in use: "apikey:" or "oauth:" Scopes []string `json:"scopes,omitempty"` // API-key permission allowlist; empty = full role permissions - SandboxOnly bool `json:"sandbox_only,omitempty"` // API key restricted to fork-sandboxed content writes + SandboxOnly bool `json:"sandbox_only,omitempty"` // key or connection confined to forks it created + // CanMergeOwnForks: the key or connection may merge forks it created. + CanMergeOwnForks bool `json:"can_merge_own_forks,omitempty"` + // ActiveSandboxFork is the fork of the credential's current sandbox + // (hex ID), or "" when none is active. + ActiveSandboxFork string `json:"active_sandbox_fork,omitempty"` } // CredentialKey implements middleware.CredentialBound. func (u *SessionUser) CredentialKey() string { return u.Credential } -// sandboxAllowedPerms is the permission set available to sandbox-only API -// keys: reading, creating/editing content (fork-scoped, enforced by the -// content handlers), uploading assets, and working with forks. Everything -// that mutates the live site directly is excluded. +// Sandboxed reports whether the caller is confined to forks it created right +// now: a key or connection set to Sandbox always, and any other while it has a +// sandbox open. +func (u *SessionUser) Sandboxed() bool { + return u != nil && (u.SandboxOnly || u.ActiveSandboxFork != "") +} + +// sandboxAllowedPerms is the permission set available to a sandboxed caller: +// reading, creating/editing content (in its own forks, enforced by the +// content handlers), uploading new non-executable assets, and working with +// its own forks. Everything that mutates the live site directly is excluded. +// The REST layer also refuses every write route not listed in +// handlers.sandboxWriteRoutes. var sandboxAllowedPerms = map[string]bool{ PermContentView: true, PermContentCreate: true, @@ -166,7 +180,7 @@ func UserHasPermission(u *SessionUser, perm string) bool { if !HasPermission(u.Role, perm) { return false } - if u.SandboxOnly && !sandboxAllowedPerms[perm] { + if u.Sandboxed() && !sandboxAllowedPerms[perm] { return false } if len(u.Scopes) > 0 { diff --git a/internal/handlers/admin_routes.go b/internal/handlers/admin_routes.go index 20d28ca..d19c2d6 100644 --- a/internal/handlers/admin_routes.go +++ b/internal/handlers/admin_routes.go @@ -155,6 +155,14 @@ func (h *Handler) AdminRoutes() []AdminRoute { perm("GET", "/api-keys/new", h.NewAPIKeyPage, auth.PermAPIKeyManage), perm("POST", "/api-keys/new", h.CreateAPIKey, auth.PermAPIKeyManage).audited("apikey.create"), perm("POST", "/api-keys/{id}/delete", h.DeleteAPIKey, auth.PermAPIKeyManage).audited("apikey.delete"), + perm("POST", "/api-keys/{id}/access", h.UpdateAPIKeyAccess, auth.PermAPIKeyManage).audited("apikey.update"), + + // Connected apps (OAuth connections): everyone manages their own; the + // handlers refuse anyone else's below apikey.manage_all, and only a + // role that can merge may let an app merge its own forks. + session("GET", "/connected-apps", h.ConnectedAppsPage, "lists the signed-in user's own app connections"), + session("POST", "/connected-apps/{id}/access", h.UpdateConnectedApp, "changes the signed-in user's own app connection").audited("oauth.update"), + session("POST", "/connected-apps/{id}/revoke", h.RevokeConnectedApp, "disconnects the signed-in user's own app").audited("oauth.revoke"), // Approvals dashboard perm("GET", "/approvals", h.ApprovalsPage, auth.PermApprovalView), diff --git a/internal/handlers/admin_routes_guard_test.go b/internal/handlers/admin_routes_guard_test.go index c9b2a25..b88cbf2 100644 --- a/internal/handlers/admin_routes_guard_test.go +++ b/internal/handlers/admin_routes_guard_test.go @@ -36,6 +36,9 @@ var writeRoutesWithoutPermission = map[string]string{ "POST /cm/logout": "public: only clears the caller's own session cookie", "POST /cm/change-password": "session: the forced change of the signed-in user's own password", "POST /cm/security": "session: changes the signed-in user's own password and requires the current one", + + "POST /cm/connected-apps/{id}/access": "session: a viewer can connect an app too; the handler refuses another person's connection below apikey.manage_all, and merging needs fork.merge", + "POST /cm/connected-apps/{id}/revoke": "session: anyone may disconnect their own app; the handler refuses another person's below apikey.manage_all", } var routeVarRe = regexp.MustCompile(`\{[^}]+\}`) @@ -163,6 +166,11 @@ var adminRoleMatrix = map[string]string{ "POST /cm/security": "*", "GET /cm/forks/exit-preview": "*", + "GET /cm/connected-apps": "*", + "POST /cm/connected-apps/{id}/access": "*", + "POST /cm/connected-apps/{id}/revoke": "*", + "POST /cm/api-keys/{id}/access": "-cea", + // Templates and snippets: everyone reads, only admin writes "GET /cm/templates": "vcea", "GET /cm/templates/new": "---a", diff --git a/internal/handlers/admin_templates.go b/internal/handlers/admin_templates.go index ff51397..eef30eb 100644 --- a/internal/handlers/admin_templates.go +++ b/internal/handlers/admin_templates.go @@ -5445,7 +5445,7 @@ var adminTemplates = map[string]string{ {{if .Error}}
{{.Error}}
{{end}} {{if .Success}}
{{.Success}}
{{end}} -

API keys provide programmatic access to the LightCMS REST API. Use them with the CLI tool, MCP server, or custom integrations.

+

API keys provide programmatic access to the LightCMS REST API. Use them with the CLI tool, MCP server, or custom integrations. A key acts as its owner, limited by its access: Sandbox keys change things only in forks they created, which a person then reviews and merges; Full keys can do anything their owner's role can. Only an admin can let a key merge its own forks.

{{if .APIKeys}}
@@ -5453,8 +5453,9 @@ var adminTemplates = map[string]string{ Name - Description + {{if .SeeAll}}Owner{{end}} Key Prefix + Access Created Last Used @@ -5463,13 +5464,29 @@ var adminTemplates = map[string]string{ {{range .APIKeys}} - {{.Name}} - {{if .Description}}{{.Description}}{{else}}—{{end}} - {{.Prefix}}... - {{.CreatedAt.Format "Jan 2, 2006"}} - {{if .LastUsedAt}}{{.LastUsedAt.Format "Jan 2, 2006 3:04 PM"}}{{else}}Never{{end}} + {{.Key.Name}}{{if .Key.Description}}
{{.Key.Description}}
{{end}} + {{if $.SeeAll}}{{.OwnerEmail}}{{end}} + {{.Key.Prefix}}... + +
+ {{$.CSRFField}} + + {{if .MergeEditable}} + + + {{else if .Key.CanMergeOwnForks}} + Can merge its own forks + {{end}} + +
+ + {{.Key.CreatedAt.Format "Jan 2, 2006"}} + {{if .Key.LastUsedAt}}{{.Key.LastUsedAt.Format "Jan 2, 2006 3:04 PM"}}{{else}}Never{{end}} -
+ {{$.CSRFField}}
@@ -5479,6 +5496,11 @@ var adminTemplates = map[string]string{
+ {{else}}

No API keys yet. Create one to enable programmatic access.

@@ -5486,6 +5508,74 @@ var adminTemplates = map[string]string{ {{end}} ` + adminLayoutEnd, + "connected_apps": adminLayoutStart + ` + + {{if .Error}}
{{.Error}}
{{end}} + {{if .Success}}
{{.Success}}
{{end}} + +

Apps you connected by signing in (for example an AI assistant using this site's MCP server). Each one acts as the person who connected it, limited by its access: Sandbox apps change things only in forks they created, which a person then reviews and merges; Full apps can do anything that person's role can. Only an admin can let an app merge its own forks. Disconnecting stops an app at once.

+ + {{if .Connections}} +
+ + + + + {{if .SeeAll}}{{end}} + + + + + + + + {{range .Connections}} + + + {{if $.SeeAll}}{{end}} + + + + + + {{end}} + +
AppConnected byAccessConnectedLast Used
{{.Grant.ClientName}}{{.OwnerEmail}} +
+ {{$.CSRFField}} + + {{if .MergeEditable}} + + + {{else if .Grant.CanMergeOwnForks}} + Can merge its own forks + {{end}} + +
+
{{.Grant.CreatedAt.Format "Jan 2, 2006"}}{{if .Grant.LastUsedAt}}{{.Grant.LastUsedAt.Format "Jan 2, 2006 3:04 PM"}}{{else}}Never{{end}} +
+ {{$.CSRFField}} + +
+
+
+ + {{else}} +
+

No apps are connected.

+
+ {{end}} + ` + adminLayoutEnd, + "api_key_new": adminLayoutStart + ` +
+ + + + {{if index $.Can "fork.merge"}} + + {{end}} +
Cancel
+ ` + adminLayoutEnd, "api_key_created": adminLayoutStart + ` @@ -9581,6 +9683,7 @@ const adminLayoutStart = ` ↪️ Redirects ⚙️ Configuration 🔑 API Keys + 🔌 Connected Apps 🔒 Security 🔔 Webhooks {{if and .CurrentUser (eq .CurrentUser.Role "admin")}} diff --git a/internal/handlers/admin_ui_guard_743_test.go b/internal/handlers/admin_ui_guard_743_test.go index 1b2ffdc..4e04ce8 100644 --- a/internal/handlers/admin_ui_guard_743_test.go +++ b/internal/handlers/admin_ui_guard_743_test.go @@ -60,7 +60,7 @@ func TestAdminTemplates_DeleteFormsAskFirst(t *testing.T) { t.Fatalf("only %d delete forms found; the scan is not seeing the templates", checked) } for _, want := range []string{ - `action="/cm/api-keys/{{.ID.Hex}}/delete" style="display:inline;" data-confirm="`, + `action="/cm/api-keys/{{.Key.ID.Hex}}/delete" style="display:inline;" data-confirm="`, `action="/cm/snippets/{{.ID.Hex}}/delete" style="display:inline;" data-confirm="`, } { found := false diff --git a/internal/handlers/api.go b/internal/handlers/api.go index 472d0a7..b6c2d49 100644 --- a/internal/handlers/api.go +++ b/internal/handlers/api.go @@ -36,6 +36,7 @@ type APIHandler struct { indexNowService *services.IndexNowService seoService *services.SEOService analyticsService *services.AnalyticsService + oauthService *services.OAuthService baseURL string } @@ -92,8 +93,8 @@ func (a *APIHandler) requirePermission(w http.ResponseWriter, r *http.Request, p } if !auth.UserHasPermission(user, perm) { msg := "insufficient permissions" - if user.SandboxOnly && auth.HasPermission(user.Role, perm) { - msg = "this API key is sandbox-only: live mutations are not permitted — work inside a fork and submit it for human review" + if user.Sandboxed() && auth.HasPermission(user.Role, perm) { + msg = sandboxRefusal } a.jsonError(w, http.StatusForbidden, msg) return false diff --git a/internal/handlers/api_assets.go b/internal/handlers/api_assets.go index cb1a605..4f8031d 100644 --- a/internal/handlers/api_assets.go +++ b/internal/handlers/api_assets.go @@ -174,6 +174,9 @@ func (a *APIHandler) APIUploadAsset(w http.ResponseWriter, r *http.Request) { a.jsonError(w, http.StatusBadRequest, "serve_path must begin with /assets/, /images/, /docs/, /media/, or /files/") return } + if !a.callerMayUpload(w, r, req.Filename, req.ServePath) { + return + } data, err := base64.StdEncoding.DecodeString(req.DataBase64) if err != nil { @@ -257,6 +260,28 @@ func (a *APIHandler) APIUploadAssetFromURL(w http.ResponseWriter, r *http.Reques return } + // Derive filename from URL path if serve_path not provided + servePath := req.ServePath + if servePath == "" { + urlPath := req.URL + if idx := strings.Index(urlPath, "?"); idx != -1 { + urlPath = urlPath[:idx] + } + filename := filepath.Base(urlPath) + if filename == "" || filename == "." || filename == "/" { + filename = "asset" + } + servePath = "/assets/" + filename + } + if !isValidAssetServePath(servePath) { + a.jsonError(w, http.StatusBadRequest, "serve_path must begin with /assets/, /images/, /docs/, /media/, or /files/") + return + } + filename := filepath.Base(servePath) + if !a.callerMayUpload(w, r, filename, servePath) { + return + } + // ssrfSafeClient resolves the host and blocks private/reserved IPs before connecting resp, err := ssrfSafeClient.Get(req.URL) if err != nil { @@ -277,25 +302,6 @@ func (a *APIHandler) APIUploadAssetFromURL(w http.ResponseWriter, r *http.Reques return } - // Derive filename from URL path if serve_path not provided - servePath := req.ServePath - if servePath == "" { - urlPath := req.URL - if idx := strings.Index(urlPath, "?"); idx != -1 { - urlPath = urlPath[:idx] - } - filename := filepath.Base(urlPath) - if filename == "" || filename == "." || filename == "/" { - filename = "asset" - } - servePath = "/assets/" + filename - } - if !isValidAssetServePath(servePath) { - a.jsonError(w, http.StatusBadRequest, "serve_path must begin with /assets/, /images/, /docs/, /media/, or /files/") - return - } - filename := filepath.Base(servePath) - asset, err := a.assetService.UploadAsset(r.Context(), data, filename, servePath, req.Description) if err != nil { a.jsonError(w, http.StatusBadRequest, err.Error()) diff --git a/internal/handlers/api_content.go b/internal/handlers/api_content.go index a20ed6b..a5eefd5 100644 --- a/internal/handlers/api_content.go +++ b/internal/handlers/api_content.go @@ -386,9 +386,9 @@ func (a *APIHandler) APICreateContent(w http.ResponseWriter, r *http.Request) { } } - // Sandbox-only keys must create inside a fork. - if u := a.getAPIUser(r); u != nil && u.SandboxOnly && req.ForkID == "" { - a.jsonError(w, http.StatusForbidden, "this API key is sandbox-only: new content must be created inside a fork (set fork_id)") + // A sandboxed caller creates pages only inside its own forks. + if a.getAPIUser(r).Sandboxed() && req.ForkID == "" { + a.jsonError(w, http.StatusForbidden, sandboxRefusal) return } @@ -414,6 +414,9 @@ func (a *APIHandler) APICreateContent(w http.ResponseWriter, r *http.Request) { a.jsonError(w, http.StatusBadRequest, "fork is not active (status: "+fork.Status+")") return } + if !a.callerMayWriteFork(w, r, fork) { + return + } forkID = &fid } @@ -498,9 +501,8 @@ func (a *APIHandler) APIUpdateContent(w http.ResponseWriter, r *http.Request) { return } - // Sandbox-only keys may write to fork copies only, never live pages. - if u := a.getAPIUser(r); u != nil && u.SandboxOnly && content.ForkID == nil { - a.jsonError(w, http.StatusForbidden, "this API key is sandbox-only: it can edit fork copies but not live content — fork the page first") + // A sandboxed caller edits copies in its own forks, never live pages. + if !a.callerMayWriteContent(w, r, content) { return } @@ -1492,9 +1494,8 @@ func (a *APIHandler) APIUpdateContentByPath(w http.ResponseWriter, r *http.Reque return } - // Sandbox-only keys may write to fork copies only, never live pages. - if u := a.getAPIUser(r); u != nil && u.SandboxOnly && content.ForkID == nil { - a.jsonError(w, http.StatusForbidden, "this API key is sandbox-only: it can edit fork copies but not live content — fork the page first") + // A sandboxed caller edits copies in its own forks, never live pages. + if !a.callerMayWriteContent(w, r, content) { return } diff --git a/internal/handlers/api_forks.go b/internal/handlers/api_forks.go index c634f7d..22b31c8 100644 --- a/internal/handlers/api_forks.go +++ b/internal/handlers/api_forks.go @@ -92,12 +92,13 @@ func (a *APIHandler) APICreateFork(w http.ResponseWriter, r *http.Request) { } user := a.getAPIUser(r) var userID primitive.ObjectID - var userEmail string + var userEmail, credential string if user != nil { userID, _ = primitive.ObjectIDFromHex(user.ID) userEmail = user.Email + credential = user.Credential } - fork, err := a.forkService.Create(r.Context(), body.Name, body.Description, userID, userEmail) + fork, err := a.forkService.CreateWithCredential(r.Context(), body.Name, body.Description, userID, userEmail, credential) if err != nil { a.jsonError(w, http.StatusInternalServerError, err.Error()) return @@ -194,6 +195,9 @@ func (a *APIHandler) APIForkPage(w http.ResponseWriter, r *http.Request) { return } ctx := r.Context() + if !a.mayWriteForkByID(w, r, forkID) { + return + } var contentID primitive.ObjectID if body.ContentID != "" { @@ -240,6 +244,19 @@ func (a *APIHandler) APIForkPage(w http.ResponseWriter, r *http.Request) { }) } +// mayWriteForkByID loads a fork and applies callerMayWriteFork. +func (a *APIHandler) mayWriteForkByID(w http.ResponseWriter, r *http.Request, forkID primitive.ObjectID) bool { + if !a.getAPIUser(r).Sandboxed() { + return true + } + fork, err := a.forkService.GetByID(r.Context(), forkID) + if err != nil { + a.jsonError(w, http.StatusNotFound, "fork not found") + return false + } + return a.callerMayWriteFork(w, r, fork) +} + // APIListForkPages lists all pages in a fork. func (a *APIHandler) APIListForkPages(w http.ResponseWriter, r *http.Request) { if !a.requirePermission(w, r, auth.PermForkCreate) { @@ -290,6 +307,9 @@ func (a *APIHandler) APIRemoveForkPage(w http.ResponseWriter, r *http.Request) { a.jsonError(w, http.StatusBadRequest, "invalid page ID") return } + if !a.mayWriteForkByID(w, r, forkID) { + return + } if err := a.forkService.RemovePage(r.Context(), forkID, pageID); err != nil { a.jsonError(w, http.StatusInternalServerError, err.Error()) return @@ -445,16 +465,23 @@ func (a *APIHandler) APIPurgeForkCopies(w http.ResponseWriter, r *http.Request) } // APIDeleteFork permanently deletes a fork and all its pages (admin only). +// +// A sandboxed caller may discard a fork it created, and no other; anyone else +// needs fork.merge. func (a *APIHandler) APIDeleteFork(w http.ResponseWriter, r *http.Request) { - if !a.requirePermission(w, r, auth.PermForkMerge) { - return - } vars := mux.Vars(r) forkID, err := primitive.ObjectIDFromHex(vars["id"]) if err != nil { a.jsonError(w, http.StatusBadRequest, "invalid fork ID") return } + if a.getAPIUser(r).Sandboxed() { + if !a.requirePermission(w, r, auth.PermForkCreate) || !a.mayWriteForkByID(w, r, forkID) { + return + } + } else if !a.requirePermission(w, r, auth.PermForkMerge) { + return + } if err := a.forkService.Delete(r.Context(), forkID); err != nil { a.jsonError(w, http.StatusInternalServerError, err.Error()) return diff --git a/internal/handlers/api_identity_test.go b/internal/handlers/api_identity_test.go index 3ba5470..50678c5 100644 --- a/internal/handlers/api_identity_test.go +++ b/internal/handlers/api_identity_test.go @@ -356,16 +356,22 @@ func newMCPEnvironment(t *testing.T) *mcpEnvironment { return &mcpEnvironment{url: srv.URL, db: db, users: users, oauth: oauth} } -// connect signs person in through the OAuth service and returns the access -// token and grant. +// connect signs person in through the OAuth service with Full access and +// returns the access token and grant. func (e *mcpEnvironment) connect(t *testing.T, person *models.User) (string, *models.OAuthGrant) { + t.Helper() + return e.connectWith(t, person, services.AccessSettings{}) +} + +// connectWith is connect with the given access settings. +func (e *mcpEnvironment) connectWith(t *testing.T, person *models.User, access services.AccessSettings) (string, *models.OAuthGrant) { t.Helper() ctx := context.Background() client, _, err := e.oauth.RegisterClient(ctx, "Test App", []string{"http://localhost/cb"}) if err != nil { t.Fatalf("RegisterClient: %v", err) } - grant, err := e.oauth.SaveGrant(ctx, client, person.ID, services.MCPResourceURL(mcpTestBaseURL)) + grant, err := e.oauth.SaveGrant(ctx, client, person.ID, services.MCPResourceURL(mcpTestBaseURL), access) if err != nil { t.Fatalf("SaveGrant: %v", err) } @@ -377,11 +383,11 @@ func (e *mcpEnvironment) connect(t *testing.T, person *models.User) (string, *mo if err != nil { t.Fatalf("CreateAuthCode: %v", err) } - access, _, _, err := e.oauth.ExchangeAuthCode(ctx, code, client.ClientID, "http://localhost/cb", verifier) + token, _, _, err := e.oauth.ExchangeAuthCode(ctx, code, client.ClientID, "http://localhost/cb", verifier) if err != nil { t.Fatalf("ExchangeAuthCode: %v", err) } - return access, grant + return token, grant } func (e *mcpEnvironment) person(t *testing.T, email, role string) *models.User { @@ -551,3 +557,51 @@ func TestEndToEnd_OAuthTokenRefusedAtTheRESTAPI(t *testing.T) { t.Errorf("got %d, want 401", resp.StatusCode) } } + +func TestEndToEnd_SandboxConnectionWorksOnlyInItsOwnFork(t *testing.T) { + env := newMCPEnvironment(t) + tmpl := seedTemplate(t, env.db, "Page", "page") + live := seedContent(t, env.db, tmpl, "Live", "live", "/live") + token, _ := env.connectWith(t, env.person(t, "editor@example.com", models.RoleEditor), services.AccessSettings{SandboxOnly: true}) + session := env.session(t, token) + + // Without a sandbox, a Sandbox connection can't touch the live page. + result := callTool(t, session, "update_content", map[string]interface{}{"id": live.Hex(), "title": "Changed live"}) + if !result.IsError || !strings.Contains(toolText(result), "limited to its own forks") { + t.Fatalf("live edit: %s", toolText(result)) + } + if result := callTool(t, session, "get_agent_sandbox", map[string]interface{}{}); !strings.Contains(toolText(result), "set to Sandbox access") { + t.Errorf("status: %s", toolText(result)) + } + + if result := callTool(t, session, "start_agent_sandbox", map[string]interface{}{"name": "edits"}); result.IsError { + t.Fatalf("start_agent_sandbox: %s", toolText(result)) + } + // A second session on the same connection is in the same sandbox. + second := env.session(t, token) + if result := callTool(t, second, "update_content", map[string]interface{}{"id": live.Hex(), "title": "Changed in the fork"}); result.IsError { + t.Fatalf("update in the sandbox: %s", toolText(result)) + } + if result := callTool(t, second, "publish_content", map[string]interface{}{"id": live.Hex()}); !result.IsError { + t.Errorf("publishing from a sandbox: %s", toolText(result)) + } + + var page models.Content + env.db.FindOne(context.Background(), "content", bson.M{"_id": live}, &page) + if page.Title != "Live" { + t.Errorf("the live page changed to %q", page.Title) + } + var copies int64 + copies, _ = env.db.Count(context.Background(), "content", bson.M{"full_path": "/live", "fork_id": bson.M{"$ne": nil}, "title": "Changed in the fork"}) + if copies != 1 { + t.Errorf("%d fork copies carry the change, want 1", copies) + } + + if result := callTool(t, session, "end_agent_sandbox", map[string]interface{}{"action": "submit"}); result.IsError { + t.Fatalf("submit: %s", toolText(result)) + } + result = callTool(t, session, "update_content", map[string]interface{}{"id": live.Hex(), "title": "After submit"}) + if !result.IsError { + t.Error("ending the sandbox lifted a Sandbox connection's restriction") + } +} diff --git a/internal/handlers/api_routes.go b/internal/handlers/api_routes.go index 7c61876..0cf9eeb 100644 --- a/internal/handlers/api_routes.go +++ b/internal/handlers/api_routes.go @@ -44,6 +44,7 @@ func (a *APIHandler) MountAPI(r *mux.Router, apiAuth *middleware.APIAuth) *mux.R apiv1.Use(middleware.APIRateLimit) // per-credential sliding-window rate limit (300 req/min) apiv1.Use(middleware.APIBodySizeLimit) // cap request body at 10 MiB to prevent memory exhaustion apiv1.Use(StampProvenance) + apiv1.Use(SandboxGate) // a sandboxed caller can change only its own forks // Content apiv1.HandleFunc("/content", a.APIListContent).Methods("GET") @@ -150,6 +151,11 @@ func (a *APIHandler) MountAPI(r *mux.Router, apiAuth *middleware.APIAuth) *mux.R apiv1.HandleFunc("/forks/{id}/pages/{pageID}", a.APIRemoveForkPage).Methods("DELETE") apiv1.HandleFunc("/forks/{id}/diff", a.APIForkDiff).Methods("GET") + // Agent sandbox: a fork the caller's key or connection works in + apiv1.HandleFunc("/sandbox", a.APIGetSandbox).Methods("GET") + apiv1.HandleFunc("/sandbox", a.APIStartSandbox).Methods("POST") + apiv1.HandleFunc("/sandbox/end", a.APIEndSandbox).Methods("POST") + // Agent session ledger & rollback apiv1.HandleFunc("/agent-sessions/{id}/changes", a.APIAgentSessionChanges).Methods("GET") apiv1.HandleFunc("/agent-sessions/{id}/rollback", a.APIAgentSessionRollback).Methods("POST") diff --git a/internal/handlers/api_sandbox.go b/internal/handlers/api_sandbox.go new file mode 100644 index 0000000..af0f64b --- /dev/null +++ b/internal/handlers/api_sandbox.go @@ -0,0 +1,308 @@ +package handlers + +import ( + "context" + "fmt" + "net/http" + "path/filepath" + "strings" + + "github.com/metavert-io/lightcms/v7/internal/auth" + "github.com/metavert-io/lightcms/v7/internal/models" + "github.com/metavert-io/lightcms/v7/internal/services" + + "github.com/gorilla/mux" + "go.mongodb.org/mongo-driver/bson/primitive" +) + +// sandboxWriteRoutes are the only /api/v1 routes that change state which a +// sandboxed caller (auth.SessionUser.Sandboxed) may call; SandboxGate refuses +// every other non-read request from one. Each entry says why it cannot reach +// the live site. A new route is refused until it is added here, and +// TestSandboxRoutes_EveryWriteRouteIsDecided fails until it is listed here or +// in that test's list of refusals. +var sandboxWriteRoutes = map[string]string{ + "POST /api/v1/content": "creates a page inside a fork the caller created (fork_id is required)", + "PUT /api/v1/content/{id}": "edits a page copy in a fork the caller created", + "PUT /api/v1/content/by-path": "edits a page copy in a fork the caller created", + "POST /api/v1/content/{id}/preview": "renders a page without saving anything", + "POST /api/v1/content/export": "reads content without changing it", + "POST /api/v1/content/{id}/comments": "adds a comment for reviewers; comments are not shown on the site", + "POST /api/v1/assets": "uploads a new image, PDF, font or text file; never replaces one, never HTML, JS, CSS or SVG", + "POST /api/v1/assets/from-url": "the same, fetched from a URL", + "POST /api/v1/forks": "creates a fork owned by the caller", + "DELETE /api/v1/forks/{id}": "discards a fork the caller created", + "POST /api/v1/forks/{id}/fork-page": "copies a live page into a fork the caller created", + "DELETE /api/v1/forks/{id}/pages/{pageID}": "removes a page copy from a fork the caller created", + "POST /api/v1/sandbox": "starts a sandbox: a new fork owned by the caller", + "POST /api/v1/sandbox/end": "hands off or discards the caller's own sandbox fork", +} + +// sandboxRefusal is the error a sandboxed caller gets for anything outside its forks. +const sandboxRefusal = "this connection is limited to its own forks. Start a sandbox (start_agent_sandbox, or POST /api/v1/sandbox) and make the change there for a person to review and merge" + +// SandboxGate refuses every state-changing request from a sandboxed caller +// except the routes in sandboxWriteRoutes, whichever tool or client sent it. +// The handlers behind those routes then hold the caller to its own forks. +// Reads pass, governed by the caller's permissions. +func SandboxGate(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + user, _ := auth.UserFromAPIContext(r.Context()) + if !user.Sandboxed() || r.Method == http.MethodGet || r.Method == http.MethodHead || r.Method == http.MethodOptions { + next.ServeHTTP(w, r) + return + } + template := "" + if route := mux.CurrentRoute(r); route != nil { + template, _ = route.GetPathTemplate() + } + if _, ok := sandboxWriteRoutes[r.Method+" "+template]; !ok { + writeJSONError(w, http.StatusForbidden, sandboxRefusal) + return + } + next.ServeHTTP(w, r) + }) +} + +func writeJSONError(w http.ResponseWriter, status int, message string) { + (&APIHandler{}).jsonError(w, status, message) +} + +// callerMayWriteFork reports whether the caller may change pages in fork, +// writing the refusal when not. A sandboxed caller may write only to an +// active fork that it created. +func (a *APIHandler) callerMayWriteFork(w http.ResponseWriter, r *http.Request, fork *models.ContentFork) bool { + user := a.getAPIUser(r) + if !user.Sandboxed() { + return true + } + if fork.CreatedByCredential == "" || fork.CreatedByCredential != user.Credential { + a.jsonError(w, http.StatusForbidden, "this connection can change only forks it created") + return false + } + if fork.Status != "active" { + a.jsonError(w, http.StatusConflict, "fork is "+fork.Status+"; it can't be changed") + return false + } + return true +} + +// callerMayWriteContent applies callerMayWriteFork to the fork a page belongs +// to; a sandboxed caller may not change a live page at all. +func (a *APIHandler) callerMayWriteContent(w http.ResponseWriter, r *http.Request, content *models.Content) bool { + user := a.getAPIUser(r) + if !user.Sandboxed() { + return true + } + if content.ForkID == nil { + a.jsonError(w, http.StatusForbidden, sandboxRefusal) + return false + } + fork, err := a.forkService.GetByID(r.Context(), *content.ForkID) + if err != nil { + a.jsonError(w, http.StatusNotFound, "fork not found") + return false + } + return a.callerMayWriteFork(w, r, fork) +} + +// sandboxUploadTypes are the file types a sandboxed caller may upload: ones a +// browser does not run. HTML, JavaScript, CSS, SVG, XML and JSON are left out. +var sandboxUploadTypes = map[string]bool{ + ".jpg": true, ".jpeg": true, ".png": true, ".gif": true, ".webp": true, + ".avif": true, ".bmp": true, ".ico": true, ".pdf": true, + ".woff": true, ".woff2": true, ".ttf": true, ".otf": true, ".eot": true, + ".txt": true, ".csv": true, +} + +// callerMayUpload holds a sandboxed caller to new files of a safe type: an +// upload goes live at its URL at once, and one at an existing path replaces +// the file the site is already serving. +func (a *APIHandler) callerMayUpload(w http.ResponseWriter, r *http.Request, filename, servePath string) bool { + if !a.getAPIUser(r).Sandboxed() { + return true + } + for _, name := range []string{filename, servePath} { + if !sandboxUploadTypes[strings.ToLower(filepath.Ext(name))] { + a.jsonError(w, http.StatusForbidden, "this connection can upload images, PDFs, fonts and text files only (not "+filepath.Ext(name)+")") + return false + } + } + exists, err := a.assetService.AssetExistsAt(r.Context(), servePath) + if err != nil { + a.jsonError(w, http.StatusInternalServerError, "could not check the asset path") + return false + } + if exists { + a.jsonError(w, http.StatusConflict, "an asset already exists at "+servePath+"; this connection can add new files but not replace them") + return false + } + return true +} + +// SetOAuthService wires in the OAuth service (sandbox state of connections). +func (a *APIHandler) SetOAuthService(s *services.OAuthService) { a.oauthService = s } + +// setActiveSandbox records fork (nil: none) as the caller's sandbox, on the +// API key or OAuth connection it signed in with. +func (a *APIHandler) setActiveSandbox(ctx context.Context, user *auth.SessionUser, fork *primitive.ObjectID) error { + kind, hexID, _ := strings.Cut(user.Credential, ":") + id, err := primitive.ObjectIDFromHex(hexID) + if err != nil { + return fmt.Errorf("unrecognised credential %q", user.Credential) + } + switch kind { + case "apikey": + return a.apiKeyService.SetActiveSandbox(ctx, id, fork) + case "oauth": + if a.oauthService == nil { + return fmt.Errorf("OAuth service unavailable") + } + return a.oauthService.SetActiveSandbox(ctx, id, fork) + } + return fmt.Errorf("unrecognised credential %q", user.Credential) +} + +// activeSandbox returns the caller's open sandbox fork, or nil. A sandbox +// whose fork has since been merged, archived or deleted is closed here. +func (a *APIHandler) activeSandbox(ctx context.Context, user *auth.SessionUser) *models.ContentFork { + if user.ActiveSandboxFork == "" { + return nil + } + id, err := primitive.ObjectIDFromHex(user.ActiveSandboxFork) + if err == nil { + if fork, err := a.forkService.GetByID(ctx, id); err == nil && fork.Status == "active" { + return fork + } + } + if err := a.setActiveSandbox(ctx, user, nil); err != nil { + fmt.Printf("Warning: failed to close a stale sandbox for %s: %v\n", user.Credential, err) + } + user.ActiveSandboxFork = "" + return nil +} + +func sandboxResponse(user *auth.SessionUser, fork *models.ContentFork) map[string]interface{} { + resp := map[string]interface{}{ + "active": fork != nil, + // restricted: the credential is set to Sandbox and stays confined + // to its forks whether or not a sandbox is open. + "restricted": user.SandboxOnly, + "can_merge_own_forks": user.CanMergeOwnForks, + } + if fork != nil { + resp["fork_id"] = fork.ID.Hex() + resp["name"] = fork.Name + resp["review_url"] = "/cm/forks/" + fork.ID.Hex() + } + return resp +} + +// APIGetSandbox reports the caller's sandbox. +// GET /api/v1/sandbox +func (a *APIHandler) APIGetSandbox(w http.ResponseWriter, r *http.Request) { + if !a.requirePermission(w, r, auth.PermContentView) { + return + } + user := a.getAPIUser(r) + a.jsonResponse(w, http.StatusOK, sandboxResponse(user, a.activeSandbox(r.Context(), user))) +} + +// APIStartSandbox opens a sandbox: a new fork owned by the caller's key or +// connection, recorded on it so every later request is held to the fork. +// POST /api/v1/sandbox {"name": "...", "description": "..."} +func (a *APIHandler) APIStartSandbox(w http.ResponseWriter, r *http.Request) { + if !a.requirePermission(w, r, auth.PermForkCreate) { + return + } + user := a.getAPIUser(r) + if user.Credential == "" { + a.jsonError(w, http.StatusBadRequest, "a sandbox belongs to an API key or OAuth connection; a browser session has none") + return + } + var body struct { + Name string `json:"name"` + Description string `json:"description"` + } + if r.ContentLength != 0 { + if err := a.decodeJSON(r, &body); err != nil { + a.jsonError(w, http.StatusBadRequest, "invalid request body") + return + } + } + if open := a.activeSandbox(r.Context(), user); open != nil { + a.jsonResponse(w, http.StatusConflict, map[string]interface{}{ + "error": fmt.Sprintf("a sandbox (%q) is already open; end it first", open.Name), + "fork_id": open.ID.Hex(), + }) + return + } + if body.Name == "" { + body.Name = "agent-session" + } + if body.Description == "" { + body.Description = "Agent sandbox session" + } + + userID, _ := primitive.ObjectIDFromHex(user.ID) + fork, err := a.forkService.CreateWithCredential(r.Context(), body.Name, body.Description, userID, user.Email, user.Credential) + if err != nil { + a.jsonError(w, http.StatusInternalServerError, err.Error()) + return + } + if err := a.setActiveSandbox(r.Context(), user, &fork.ID); err != nil { + _ = a.forkService.Delete(r.Context(), fork.ID) + a.jsonError(w, http.StatusInternalServerError, "could not open the sandbox: "+err.Error()) + return + } + user.ActiveSandboxFork = fork.ID.Hex() + a.auditLog(r, "sandbox.start", "fork", fork.ID.Hex(), map[string]interface{}{"name": fork.Name}) + a.jsonResponse(w, http.StatusCreated, sandboxResponse(user, fork)) +} + +// APIEndSandbox closes the caller's sandbox. "submit" leaves the fork for a +// person to review; "discard" deletes it. A key or connection set to Sandbox +// stays confined to its forks afterwards. +// POST /api/v1/sandbox/end {"action": "submit"|"discard"} +func (a *APIHandler) APIEndSandbox(w http.ResponseWriter, r *http.Request) { + if !a.requirePermission(w, r, auth.PermForkCreate) { + return + } + user := a.getAPIUser(r) + var body struct { + Action string `json:"action"` + } + if err := a.decodeJSON(r, &body); err != nil || (body.Action != "submit" && body.Action != "discard") { + a.jsonError(w, http.StatusBadRequest, `action must be "submit" or "discard"`) + return + } + fork := a.activeSandbox(r.Context(), user) + if fork == nil { + a.jsonError(w, http.StatusConflict, "no sandbox is open") + return + } + + if body.Action == "discard" { + if err := a.forkService.Delete(r.Context(), fork.ID); err != nil { + a.jsonError(w, http.StatusInternalServerError, err.Error()) + return + } + } + if err := a.setActiveSandbox(r.Context(), user, nil); err != nil { + a.jsonError(w, http.StatusInternalServerError, "could not close the sandbox: "+err.Error()) + return + } + user.ActiveSandboxFork = "" + a.auditLog(r, "sandbox."+body.Action, "fork", fork.ID.Hex(), map[string]interface{}{"name": fork.Name}) + + resp := map[string]interface{}{ + "action": body.Action, + "fork_id": fork.ID.Hex(), + "name": fork.Name, + "restricted": user.SandboxOnly, + } + if body.Action == "submit" { + resp["review_url"] = "/cm/forks/" + fork.ID.Hex() + } + a.jsonResponse(w, http.StatusOK, resp) +} diff --git a/internal/handlers/api_sandbox_test.go b/internal/handlers/api_sandbox_test.go new file mode 100644 index 0000000..238b6d9 --- /dev/null +++ b/internal/handlers/api_sandbox_test.go @@ -0,0 +1,664 @@ +package handlers + +import ( + "context" + "encoding/base64" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "sort" + "strings" + "testing" + + "github.com/metavert-io/lightcms/v7/internal/auth" + "github.com/metavert-io/lightcms/v7/internal/database" + "github.com/metavert-io/lightcms/v7/internal/middleware" + "github.com/metavert-io/lightcms/v7/internal/models" + "github.com/metavert-io/lightcms/v7/internal/services" + + "github.com/gorilla/mux" + "github.com/gorilla/sessions" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" +) + +// sandboxRefusedRoutes lists every state-changing /api/v1 route a sandboxed +// caller may not use, with the reason. Together with sandboxWriteRoutes it +// must cover every write route the router has, so a new route needs a +// decision before this test passes. +var sandboxRefusedRoutes = map[string]string{ + "DELETE /api/v1/api-keys/{id}": "manages credentials", + "POST /api/v1/api-keys": "manages credentials", + "DELETE /api/v1/approval-workflows/{id}": "changes the approval process", + "POST /api/v1/approval-workflows": "changes the approval process", + "PUT /api/v1/approval-workflows/{id}": "changes the approval process", + "POST /api/v1/approval-requests/{id}/approve": "approving publishes live content", + "POST /api/v1/approval-requests/{id}/reject": "decides on someone else's change", + "POST /api/v1/approval-requests/{id}/cancel": "decides on someone else's change", + "POST /api/v1/content/{id}/submit-approval": "starts an approval of a live page", + "DELETE /api/v1/assets/{id}": "removes a file the site serves", + "DELETE /api/v1/collections/{id}": "site structure", + "POST /api/v1/collections": "site structure", + "PUT /api/v1/collections/{id}": "site structure", + "DELETE /api/v1/folders/{id}": "site structure", + "POST /api/v1/folders": "site structure", + "DELETE /api/v1/redirects/{id}": "changes live URLs", + "POST /api/v1/redirects": "changes live URLs", + "PUT /api/v1/redirects/{id}": "changes live URLs", + "DELETE /api/v1/snippets/{id}": "snippets render on live pages", + "POST /api/v1/snippets": "snippets render on live pages", + "PUT /api/v1/snippets/{id}": "snippets render on live pages", + "DELETE /api/v1/templates/{id}": "templates render live pages", + "POST /api/v1/templates": "templates render live pages", + "PUT /api/v1/templates/{id}": "templates render live pages", + "PUT /api/v1/theme": "the theme renders every live page", + "POST /api/v1/theme/versions/{version}/revert": "the theme renders every live page", + "POST /api/v1/theme/versions/{version}/pin": "theme history", + "POST /api/v1/theme/versions/{version}/unpin": "theme history", + "PUT /api/v1/config": "site configuration", + "PUT /api/v1/seo": "site configuration (robots.txt, feeds)", + "PUT /api/v1/indexnow": "site configuration", + "POST /api/v1/indexnow/submit": "contacts search engines", + "DELETE /api/v1/webhooks/{id}": "sends data off the site", + "POST /api/v1/webhooks": "sends data off the site", + "PUT /api/v1/webhooks/{id}": "sends data off the site", + "POST /api/v1/webhooks/{id}/regenerate-secret": "webhook credentials", + "DELETE /api/v1/content/{id}": "deletes a live page (a fork copy is removed through its fork)", + "POST /api/v1/content/{id}/restore": "brings back a live page", + "POST /api/v1/content/{id}/publish": "publishes", + "POST /api/v1/content/{id}/unpublish": "takes a live page down", + "POST /api/v1/content/{id}/schedule": "publishes later", + "POST /api/v1/content/{id}/versions/{version}/revert": "rewrites a page's history", + "POST /api/v1/content/batch-publish": "publishes", + "POST /api/v1/content/bulk-create": "writes live pages in bulk", + "POST /api/v1/content/bulk-update": "writes live pages in bulk", + "POST /api/v1/content/bulk-field-op": "writes live pages in bulk", + "POST /api/v1/content/{id}/lock": "locks a live page against its editors", + "DELETE /api/v1/content/{id}/lock": "locks a live page against its editors", + "POST /api/v1/content/{id}/lock/force": "breaks someone else's lock", + "DELETE /api/v1/content/{id}/comments/{cid}": "removes someone else's comment", + "POST /api/v1/search-replace/execute": "writes live pages in bulk", + "POST /api/v1/search-replace/scoped/execute": "writes live pages in bulk", + "POST /api/v1/search-replace/preview": "needs search_replace.execute, which a sandbox never has", + "POST /api/v1/search-replace/scoped/preview": "needs search_replace.execute, which a sandbox never has", + "POST /api/v1/regenerate": "rewrites every live page", + "POST /api/v1/reindex-embeddings": "rebuilds the search index", + "POST /api/v1/link-check": "fetches every outbound link", + "POST /api/v1/maintenance/scan": "site maintenance", + "POST /api/v1/maintenance/backfill-published-dates": "changes live pages' dates", + "POST /api/v1/maintenance/repair-fork-damage": "rewrites live pages", + "POST /api/v1/agent-sessions/{id}/rollback": "rewrites live pages", + "POST /api/v1/imports/csv": "creates pages outside any fork", + "POST /api/v1/imports/markdown": "creates pages outside any fork", + "POST /api/v1/imports/sources": "creates pages outside any fork, on a schedule", + "PUT /api/v1/imports/sources/{id}": "creates pages outside any fork, on a schedule", + "DELETE /api/v1/imports/sources/{id}": "import configuration", + "POST /api/v1/imports/sources/{id}/trigger": "creates pages outside any fork", + "POST /api/v1/imports/jobs/{id}/cancel": "stops someone else's import", + "POST /api/v1/forks/{id}/merge": "merging writes the live site", + "POST /api/v1/forks/{id}/archive": "ends a fork without review", + "POST /api/v1/forks/{id}/purge-copies": "fork housekeeping", +} + +// apiWriteRoutes walks the real /api/v1 router and returns every route that +// is not a read, as "METHOD /api/v1/template". +func apiWriteRoutes(t *testing.T) []string { + t.Helper() + r := mux.NewRouter() + (&APIHandler{}).MountAPI(r, middleware.NewAPIAuth(nil)) + var routes []string + err := r.Walk(func(route *mux.Route, _ *mux.Router, _ []*mux.Route) error { + tpl, err := route.GetPathTemplate() + if err != nil { + return nil + } + methods, err := route.GetMethods() + if err != nil { + if tpl != "/api/v1" { + t.Errorf("route %s is registered for every method", tpl) + } + return nil + } + for _, m := range methods { + if m != http.MethodGet { + routes = append(routes, m+" "+tpl) + } + } + return nil + }) + if err != nil { + t.Fatalf("walk: %v", err) + } + sort.Strings(routes) + return routes +} + +func TestSandboxRoutes_EveryWriteRouteIsDecided(t *testing.T) { + routes := apiWriteRoutes(t) + if len(routes) < 80 { + t.Fatalf("only %d write routes found; the walk looks wrong", len(routes)) + } + seen := map[string]bool{} + for _, key := range routes { + seen[key] = true + _, allowed := sandboxWriteRoutes[key] + _, refused := sandboxRefusedRoutes[key] + switch { + case allowed && refused: + t.Errorf("%s is both allowed and refused for a sandbox", key) + case !allowed && !refused: + t.Errorf("%s: decide whether a sandboxed connection may call it (sandboxWriteRoutes, with why it can't reach the live site) or not (sandboxRefusedRoutes)", key) + } + } + for key := range sandboxWriteRoutes { + if !seen[key] { + t.Errorf("sandboxWriteRoutes lists %s, which is not a route", key) + } + } + for key := range sandboxRefusedRoutes { + if !seen[key] { + t.Errorf("sandboxRefusedRoutes lists %s, which is not a route", key) + } + } +} + +// Every write route outside the table is refused to a sandboxed caller +// before its handler runs: nothing reaches the database. +func TestSandboxGate_RefusesEveryRouteOutsideTheTable(t *testing.T) { + a, db, cleanup := newTestAPIHandler(t) + defer cleanup() + tmpl := seedTemplate(t, db, "Page", "page") + live := seedContent(t, db, tmpl, "Live", "live", "/live") + + // Each route gets its own pair of keys, so the per-key rate limits + // don't get in the way of sending every route at once. + routes := apiWriteRoutes(t) + callers := map[string]*auth.SessionUser{} + for i := range routes { + sandboxed := keyCaller(fmt.Sprintf("agent-%d", i), models.RoleAdmin) + sandboxed.SandboxOnly = true + inSandbox := keyCaller(fmt.Sprintf("helper-%d", i), models.RoleAdmin) // Full access, with a sandbox open + inSandbox.ActiveSandboxFork = primitive.NewObjectID().Hex() + callers[fmt.Sprintf("lc_sandboxed_%d", i)] = sandboxed + callers[fmt.Sprintf("lc_insandbox_%d", i)] = inSandbox + } + router := apiRouterWithKeys(a, callers) + + for i, key := range routes { + if _, allowed := sandboxWriteRoutes[key]; allowed { + continue + } + method, tpl, _ := strings.Cut(key, " ") + target := strings.NewReplacer("{id}", live.Hex(), "{version}", "1", "{pageID}", live.Hex(), "{cid}", live.Hex()).Replace(tpl) + for _, credential := range []string{fmt.Sprintf("lc_sandboxed_%d", i), fmt.Sprintf("lc_insandbox_%d", i)} { + rr := sendJSON(router, credential, method, target, `{}`) + if rr.Code != http.StatusForbidden || !strings.Contains(rr.Body.String(), "limited to its own forks") { + t.Errorf("%s as %s: %d %s", key, credential, rr.Code, rr.Body.String()) + } + } + } + + var page models.Content + if err := db.FindOne(context.Background(), "content", bson.M{"_id": live}, &page); err != nil || page.Deleted || page.Title != "Live" { + t.Errorf("the live page changed: %+v, %v", page, err) + } +} + +// --- sandbox state and fork ownership, with real keys ----------------------- + +type sandboxEnv struct { + a *APIHandler + db *database.DB + router http.Handler + keys *services.APIKeyService + tmpl string + live primitive.ObjectID + owner *models.User +} + +func newSandboxEnv(t *testing.T) *sandboxEnv { + t.Helper() + a, db, cleanup := newTestAPIHandler(t) + t.Cleanup(cleanup) + users := services.NewUserService(db) + owner, err := users.CreateUserWithHash(context.Background(), "editor@example.com", "Editor", models.RoleEditor, "unused", false) + if err != nil { + t.Fatalf("CreateUserWithHash: %v", err) + } + keys := services.NewAPIKeyService(db) + resolver := auth.NewCredentialResolver(users, keys, services.NewOAuthService(db), "https://example.com/mcp", nil) + r := mux.NewRouter() + a.MountAPI(r, middleware.NewAPIAuth(resolver.ResolveAPIKey)) + tmpl := seedTemplate(t, db, "Page", "page") + return &sandboxEnv{ + a: a, db: db, router: r, keys: keys, owner: owner, + tmpl: tmpl.Hex(), + live: seedContent(t, db, tmpl, "Live", "live", "/live"), + } +} + +// key creates an API key for the editor with the given access. +func (e *sandboxEnv) key(t *testing.T, name string, sandboxOnly bool) string { + t.Helper() + raw, _, err := e.keys.CreateScopedAPIKey(context.Background(), name, "", &e.owner.ID, nil, sandboxOnly) + if err != nil { + t.Fatalf("CreateScopedAPIKey: %v", err) + } + return raw +} + +func (e *sandboxEnv) send(key, method, target, body string) *httptest.ResponseRecorder { + return sendJSON(e.router, key, method, target, body) +} + +func decode(t *testing.T, rr *httptest.ResponseRecorder) map[string]interface{} { + t.Helper() + var out map[string]interface{} + if err := json.Unmarshal(rr.Body.Bytes(), &out); err != nil { + t.Fatalf("decoding %q: %v", rr.Body.String(), err) + } + return out +} + +func (e *sandboxEnv) startSandbox(t *testing.T, key string) string { + t.Helper() + rr := e.send(key, "POST", "/api/v1/sandbox", `{"name":"work"}`) + if rr.Code != http.StatusCreated { + t.Fatalf("start sandbox: %d %s", rr.Code, rr.Body.String()) + } + return decode(t, rr)["fork_id"].(string) +} + +func TestSandbox_ConnectionsWriteOnlyToTheirOwnForks(t *testing.T) { + e := newSandboxEnv(t) + mine := e.key(t, "Mine", true) + other := e.key(t, "Other agent", true) + full := e.key(t, "Full", false) + + fork := e.startSandbox(t, mine) + create := func(key, forkID, slug string) *httptest.ResponseRecorder { + body := fmt.Sprintf(`{"template_id":%q,"title":"T","slug":%q,"data":{}`, e.tmpl, slug) + if forkID != "" { + body += fmt.Sprintf(`,"fork_id":%q`, forkID) + } + return e.send(key, "POST", "/api/v1/content", body+"}") + } + + if rr := create(mine, "", "outside"); rr.Code != http.StatusForbidden { + t.Errorf("sandboxed create outside a fork: %d %s", rr.Code, rr.Body.String()) + } + rr := create(mine, fork, "inside") + if rr.Code != http.StatusCreated { + t.Fatalf("create in own fork: %d %s", rr.Code, rr.Body.String()) + } + copyID := decode(t, rr)["id"].(string) + + if rr := create(other, fork, "intruder"); rr.Code != http.StatusForbidden { + t.Errorf("another sandboxed key creating in the fork: %d %s", rr.Code, rr.Body.String()) + } + if rr := e.send(other, "PUT", "/api/v1/content/"+copyID, `{"title":"Hijacked"}`); rr.Code != http.StatusForbidden { + t.Errorf("another sandboxed key editing the copy: %d %s", rr.Code, rr.Body.String()) + } + if rr := e.send(other, "POST", "/api/v1/forks/"+fork+"/fork-page", `{"path":"/live"}`); rr.Code != http.StatusForbidden { + t.Errorf("another sandboxed key adding a page: %d %s", rr.Code, rr.Body.String()) + } + if rr := e.send(other, "DELETE", "/api/v1/forks/"+fork, ``); rr.Code != http.StatusForbidden { + t.Errorf("another sandboxed key discarding the fork: %d %s", rr.Code, rr.Body.String()) + } + + if rr := e.send(mine, "PUT", "/api/v1/content/"+e.live.Hex(), `{"title":"Live change"}`); rr.Code != http.StatusForbidden { + t.Errorf("sandboxed edit of a live page: %d %s", rr.Code, rr.Body.String()) + } + if rr := e.send(mine, "PUT", "/api/v1/content/by-path?path=/live", `{"title":"Live change"}`); rr.Code != http.StatusForbidden { + t.Errorf("sandboxed edit of a live page by path: %d %s", rr.Code, rr.Body.String()) + } + if rr := e.send(mine, "PUT", "/api/v1/content/"+copyID, `{"title":"Edited in sandbox"}`); rr.Code != http.StatusOK { + t.Errorf("own copy: %d %s", rr.Code, rr.Body.String()) + } + if rr := e.send(mine, "POST", "/api/v1/forks/"+fork+"/fork-page", `{"path":"/live"}`); rr.Code != http.StatusOK { + t.Errorf("adding a live page to own fork: %d %s", rr.Code, rr.Body.String()) + } + + // A Full key is not held to forks. + if rr := e.send(full, "PUT", "/api/v1/content/"+copyID, `{"title":"Edited by a person's tool"}`); rr.Code != http.StatusOK { + t.Errorf("full key on the copy: %d %s", rr.Code, rr.Body.String()) + } + + var live models.Content + e.db.FindOne(context.Background(), "content", bson.M{"_id": e.live}, &live) + if live.Title != "Live" { + t.Errorf("live page title is %q", live.Title) + } + + // Ending the sandbox doesn't lift a Sandbox key's restriction. + if rr := e.send(mine, "POST", "/api/v1/sandbox/end", `{"action":"submit"}`); rr.Code != http.StatusOK { + t.Fatalf("submit: %d %s", rr.Code, rr.Body.String()) + } + state := decode(t, e.send(mine, "GET", "/api/v1/sandbox", ``)) + if state["active"] != false || state["restricted"] != true { + t.Errorf("after submit: %+v", state) + } + if rr := create(mine, "", "after-submit"); rr.Code != http.StatusForbidden { + t.Errorf("sandbox key after submit: %d %s", rr.Code, rr.Body.String()) + } + if rr := e.send(mine, "PUT", "/api/v1/content/"+e.live.Hex(), `{"title":"Live change"}`); rr.Code != http.StatusForbidden { + t.Errorf("sandbox key editing live after submit: %d %s", rr.Code, rr.Body.String()) + } + + // It can still discard the fork it made; nobody else's. + if rr := e.send(mine, "DELETE", "/api/v1/forks/"+fork, ``); rr.Code != http.StatusOK { + t.Errorf("discarding own fork: %d %s", rr.Code, rr.Body.String()) + } +} + +func TestSandbox_FullKeyIsHeldToItsSandboxUntilItEnds(t *testing.T) { + e := newSandboxEnv(t) + full := e.key(t, "Full", false) + + fork := e.startSandbox(t, full) + if rr := e.send(full, "POST", "/api/v1/sandbox", `{}`); rr.Code != http.StatusConflict { + t.Errorf("second sandbox: %d %s", rr.Code, rr.Body.String()) + } + if rr := e.send(full, "PUT", "/api/v1/content/"+e.live.Hex(), `{"title":"Live change"}`); rr.Code != http.StatusForbidden { + t.Errorf("live edit with a sandbox open: %d %s", rr.Code, rr.Body.String()) + } + if rr := e.send(full, "POST", "/api/v1/content/"+e.live.Hex()+"/publish", ``); rr.Code != http.StatusForbidden { + t.Errorf("publish with a sandbox open: %d %s", rr.Code, rr.Body.String()) + } + + rr := e.send(full, "POST", "/api/v1/sandbox/end", `{"action":"discard"}`) + if rr.Code != http.StatusOK { + t.Fatalf("discard: %d %s", rr.Code, rr.Body.String()) + } + if _, err := e.a.forkService.GetByID(context.Background(), mustOID(t, fork)); err == nil { + t.Error("the discarded fork still exists") + } + if rr := e.send(full, "PUT", "/api/v1/content/"+e.live.Hex(), `{"title":"Live change"}`); rr.Code != http.StatusOK { + t.Errorf("live edit after the sandbox ended: %d %s", rr.Code, rr.Body.String()) + } +} + +func TestSandbox_EndsWhenItsForkIsMergedArchivedOrDeleted(t *testing.T) { + e := newSandboxEnv(t) + ctx := context.Background() + full := e.key(t, "Full", false) + + fork := e.startSandbox(t, full) + if err := e.a.forkService.Delete(ctx, mustOID(t, fork)); err != nil { + t.Fatalf("Delete: %v", err) + } + if rr := e.send(full, "PUT", "/api/v1/content/"+e.live.Hex(), `{"title":"After delete"}`); rr.Code != http.StatusOK { + t.Errorf("a person deleted the fork, but the key is still confined: %d %s", rr.Code, rr.Body.String()) + } + + fork = e.startSandbox(t, full) + if err := e.a.forkService.Archive(ctx, mustOID(t, fork)); err != nil { + t.Fatalf("Archive: %v", err) + } + if state := decode(t, e.send(full, "GET", "/api/v1/sandbox", ``)); state["active"] != false { + t.Errorf("after archive: %+v", state) + } + + // A sandbox left pointing at a fork that is no longer active is closed + // the next time it is looked at. + fork = e.startSandbox(t, full) + if err := e.db.UpdateOne(ctx, "content_forks", bson.M{"_id": mustOID(t, fork)}, bson.M{"$set": bson.M{"status": "merged"}}); err != nil { + t.Fatalf("marking merged: %v", err) + } + if state := decode(t, e.send(full, "GET", "/api/v1/sandbox", ``)); state["active"] != false { + t.Errorf("stale sandbox: %+v", state) + } + if rr := e.send(full, "PUT", "/api/v1/content/"+e.live.Hex(), `{"title":"After stale"}`); rr.Code != http.StatusOK { + t.Errorf("live edit after a stale sandbox was closed: %d %s", rr.Code, rr.Body.String()) + } +} + +func TestSandbox_BrowserSessionsHaveNoSandbox(t *testing.T) { + a, _, cleanup := newTestAPIHandler(t) + defer cleanup() + req := httptest.NewRequest("POST", "/api/v1/sandbox", strings.NewReader(`{}`)) + req = req.WithContext(middleware.InjectAPIUser(req.Context(), &auth.SessionUser{ID: primitive.NewObjectID().Hex(), Email: "a@example.com", Role: models.RoleAdmin})) + rr := httptest.NewRecorder() + a.APIStartSandbox(rr, req) + if rr.Code != http.StatusBadRequest { + t.Errorf("got %d %s", rr.Code, rr.Body.String()) + } +} + +func mustOID(t *testing.T, hex string) primitive.ObjectID { + t.Helper() + id, err := primitive.ObjectIDFromHex(hex) + if err != nil { + t.Fatalf("bad id %q", hex) + } + return id +} + +func TestSandbox_UploadsAreNewAndInert(t *testing.T) { + e := newSandboxEnv(t) + t.Chdir(t.TempDir()) // uploads are written under content/generated + sandboxed := e.key(t, "Agent", true) + full := e.key(t, "Full", false) + + png := base64.StdEncoding.EncodeToString([]byte("\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x08\x06\x00\x00\x00\x1f\x15\xc4\x89")) + svg := base64.StdEncoding.EncodeToString([]byte(``)) + html := base64.StdEncoding.EncodeToString([]byte(``)) + upload := func(key, filename, servePath, data string) int { + return e.send(key, "POST", "/api/v1/assets", fmt.Sprintf(`{"filename":%q,"serve_path":%q,"data_base64":%q}`, filename, servePath, data)).Code + } + + if code := upload(sandboxed, "a.png", "/assets/a.png", png); code != http.StatusCreated { + t.Errorf("new png: %d", code) + } + if code := upload(sandboxed, "a.png", "/assets/a.png", png); code != http.StatusConflict { + t.Errorf("replacing a file: %d", code) + } + if code := upload(sandboxed, "x.svg", "/assets/x.svg", svg); code != http.StatusForbidden { + t.Errorf("svg: %d", code) + } + if code := upload(sandboxed, "x.html", "/assets/x.html", html); code != http.StatusForbidden { + t.Errorf("html: %d", code) + } + if code := upload(sandboxed, "x.png", "/assets/x.html", png); code != http.StatusForbidden { + t.Errorf("png named into an html path: %d", code) + } + if rr := e.send(sandboxed, "POST", "/api/v1/assets/from-url", `{"url":"https://example.invalid/x.js"}`); rr.Code != http.StatusForbidden { + t.Errorf("script by URL: %d %s", rr.Code, rr.Body.String()) + } + + if code := upload(full, "x.svg", "/assets/x.svg", svg); code != http.StatusCreated { + t.Errorf("full key svg: %d", code) + } +} + +// --- admin pages --------------------------------------------------------- + +// userReq is a signed-in admin-page request as the given account. +func userReq(user *models.User, method, target string, form url.Values) *http.Request { + store := sessions.NewCookieStore([]byte(testSessionSecret)) + req := httptest.NewRequest(method, target, strings.NewReader(form.Encode())) + if method != http.MethodGet { + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + } + rec := httptest.NewRecorder() + sess, _ := store.New(req, "lightcms-session") + sess.Values["authenticated"] = true + sess.Values["user_id"] = user.ID.Hex() + sess.Values["user_email"] = user.Email + sess.Values["user_role"] = user.Role + _ = sess.Save(req, rec) + for _, c := range rec.Result().Cookies() { + req.AddCookie(c) + } + return req +} + +func serveAs(r http.Handler, user *models.User, method, target string, form url.Values) *httptest.ResponseRecorder { + rr := httptest.NewRecorder() + r.ServeHTTP(rr, userReq(user, method, target, form)) + return rr +} + +type adminEnv struct { + h *Handler + router http.Handler + db *database.DB + users *services.UserService + oauth *services.OAuthService + keys *services.APIKeyService +} + +func newAdminEnv(t *testing.T) *adminEnv { + t.Helper() + h, cleanup := newTestHandler(t) + t.Cleanup(cleanup) + return &adminEnv{h: h, router: adminRouter(h), db: h.db, users: services.NewUserService(h.db), oauth: services.NewOAuthService(h.db), keys: services.NewAPIKeyService(h.db)} +} + +func (e *adminEnv) user(t *testing.T, email, role string) *models.User { + t.Helper() + u, err := e.users.CreateUserWithHash(context.Background(), email, email, role, "unused", false) + if err != nil { + t.Fatalf("CreateUserWithHash: %v", err) + } + return u +} + +func (e *adminEnv) connection(t *testing.T, owner *models.User, name string) *models.OAuthGrant { + t.Helper() + ctx := context.Background() + client, _, err := e.oauth.RegisterClient(ctx, name, []string{"https://app.example/cb"}) + if err != nil { + t.Fatalf("RegisterClient: %v", err) + } + grant, err := e.oauth.SaveGrant(ctx, client, owner.ID, "https://example.com/mcp", services.AccessSettings{SandboxOnly: true}) + if err != nil { + t.Fatalf("SaveGrant: %v", err) + } + return grant +} + +func TestConnectedApps_PeopleSeeAndChangeOnlyTheirOwn(t *testing.T) { + e := newAdminEnv(t) + ctx := context.Background() + admin := e.user(t, "admin@example.com", models.RoleAdmin) + editor := e.user(t, "editor@example.com", models.RoleEditor) + viewer := e.user(t, "viewer@example.com", models.RoleViewer) + editorsApp := e.connection(t, editor, "Editor's Assistant") + viewersApp := e.connection(t, viewer, "Viewer's Reader") + + page := serveAs(e.router, viewer, "GET", "/cm/connected-apps", nil).Body.String() + if !strings.Contains(page, "Viewer's Reader") || strings.Contains(page, "Editor's Assistant") { + t.Errorf("a viewer should see only their own connection:\n%s", page) + } + if page := serveAs(e.router, admin, "GET", "/cm/connected-apps", nil).Body.String(); !strings.Contains(page, "Editor's Assistant") || !strings.Contains(page, "viewer@example.com") { + t.Error("an admin should see every connection and who made it") + } + + // Someone else's connection is refused. + rr := serveAs(e.router, viewer, "POST", "/cm/connected-apps/"+editorsApp.ID.Hex()+"/access", url.Values{"access": {"full"}}) + if rr.Code != http.StatusForbidden { + t.Errorf("changing another person's connection: %d", rr.Code) + } + rr = serveAs(e.router, viewer, "POST", "/cm/connected-apps/"+editorsApp.ID.Hex()+"/revoke", nil) + if rr.Code != http.StatusForbidden { + t.Errorf("revoking another person's connection: %d", rr.Code) + } + + // Their own works. + if rr := serveAs(e.router, viewer, "POST", "/cm/connected-apps/"+viewersApp.ID.Hex()+"/access", url.Values{"access": {"full"}}); rr.Code != http.StatusSeeOther { + t.Errorf("changing own connection: %d", rr.Code) + } + if grant, _ := e.oauth.GetGrant(ctx, viewersApp.ID); grant.SandboxOnly { + t.Error("access was not changed") + } + if rr := serveAs(e.router, viewer, "POST", "/cm/connected-apps/"+viewersApp.ID.Hex()+"/revoke", nil); rr.Code != http.StatusSeeOther { + t.Errorf("revoking own connection: %d", rr.Code) + } + if grant, _ := e.oauth.GetGrant(ctx, viewersApp.ID); grant.RevokedAt == nil { + t.Error("the connection was not revoked") + } +} + +func TestConnectedApps_OnlyAnAdminCanAllowSelfMerge(t *testing.T) { + e := newAdminEnv(t) + ctx := context.Background() + admin := e.user(t, "admin@example.com", models.RoleAdmin) + editor := e.user(t, "editor@example.com", models.RoleEditor) + adminsApp := e.connection(t, admin, "Admin's Assistant") + editorsApp := e.connection(t, editor, "Editor's Assistant") + merge := url.Values{"access": {"sandbox"}, "merge_shown": {"1"}, "can_merge_own_forks": {"1"}} + + // An editor can't merge, so can't allow an app of theirs to. + serveAs(e.router, editor, "POST", "/cm/connected-apps/"+editorsApp.ID.Hex()+"/access", merge) + if grant, _ := e.oauth.GetGrant(ctx, editorsApp.ID); grant.CanMergeOwnForks { + t.Error("an editor let their app merge") + } + // Nor can an admin, for an account that can't merge. + serveAs(e.router, admin, "POST", "/cm/connected-apps/"+editorsApp.ID.Hex()+"/access", merge) + if grant, _ := e.oauth.GetGrant(ctx, editorsApp.ID); grant.CanMergeOwnForks { + t.Error("an admin let an editor's app merge") + } + + if rr := serveAs(e.router, admin, "POST", "/cm/connected-apps/"+adminsApp.ID.Hex()+"/access", merge); rr.Code != http.StatusSeeOther { + t.Fatalf("admin allowing merge: %d", rr.Code) + } + grant, _ := e.oauth.GetGrant(ctx, adminsApp.ID) + if !grant.CanMergeOwnForks || !grant.SandboxOnly { + t.Errorf("after allowing merge: %+v", grant) + } + + // A form without the checkbox leaves the setting alone. + serveAs(e.router, admin, "POST", "/cm/connected-apps/"+adminsApp.ID.Hex()+"/access", url.Values{"access": {"full"}}) + if grant, _ := e.oauth.GetGrant(ctx, adminsApp.ID); !grant.CanMergeOwnForks || grant.SandboxOnly { + t.Errorf("after an access-only change: %+v", grant) + } + // Unticking it turns merging off. + serveAs(e.router, admin, "POST", "/cm/connected-apps/"+adminsApp.ID.Hex()+"/access", url.Values{"access": {"full"}, "merge_shown": {"1"}}) + if grant, _ := e.oauth.GetGrant(ctx, adminsApp.ID); grant.CanMergeOwnForks { + t.Error("merging is still allowed") + } +} + +func TestAPIKeys_NewKeysAreSandboxAndAccessCanBeChanged(t *testing.T) { + e := newAdminEnv(t) + ctx := context.Background() + admin := e.user(t, "admin@example.com", models.RoleAdmin) + editor := e.user(t, "editor@example.com", models.RoleEditor) + + if rr := serveAs(e.router, editor, "POST", "/cm/api-keys/new", url.Values{"name": {"Agent"}, "can_merge_own_forks": {"1"}}); rr.Code != http.StatusOK { + t.Fatalf("create: %d", rr.Code) + } + keys, _ := e.keys.ListAPIKeysForUser(ctx, editor.ID) + if len(keys) != 1 || !keys[0].SandboxOnly || keys[0].CanMergeOwnForks { + t.Fatalf("new key: %+v", keys) + } + + // The owner can switch it to Full; another non-admin can't touch it. + other := e.user(t, "other@example.com", models.RoleEditor) + if rr := serveAs(e.router, other, "POST", "/cm/api-keys/"+keys[0].ID.Hex()+"/access", url.Values{"access": {"full"}}); rr.Code != http.StatusForbidden { + t.Errorf("another editor: %d", rr.Code) + } + serveAs(e.router, editor, "POST", "/cm/api-keys/"+keys[0].ID.Hex()+"/access", url.Values{"access": {"full"}}) + if key, _ := e.keys.GetAPIKey(ctx, keys[0].ID); key.SandboxOnly { + t.Error("the owner could not switch the key to Full") + } + + // An admin's own key can be allowed to merge. + if rr := serveAs(e.router, admin, "POST", "/cm/api-keys/new", url.Values{"name": {"Publisher"}, "access": {"full"}, "can_merge_own_forks": {"1"}}); rr.Code != http.StatusOK { + t.Fatalf("admin create: %d", rr.Code) + } + adminKeys, _ := e.keys.ListAPIKeysForUser(ctx, admin.ID) + if len(adminKeys) != 1 || adminKeys[0].SandboxOnly || !adminKeys[0].CanMergeOwnForks { + t.Errorf("admin key: %+v", adminKeys) + } + + page := serveAs(e.router, admin, "GET", "/cm/api-keys", nil).Body.String() + for _, want := range []string{"editor@example.com", "Can merge its own forks", `value="sandbox"`} { + if !strings.Contains(page, want) { + t.Errorf("API keys page lacks %q", want) + } + } +} diff --git a/internal/handlers/fork_followups_test.go b/internal/handlers/fork_followups_test.go index bf98774..a79510d 100644 --- a/internal/handlers/fork_followups_test.go +++ b/internal/handlers/fork_followups_test.go @@ -100,6 +100,7 @@ func TestAPIContentByPath_ResolvesLivePagesOnly(t *testing.T) { tmplID := seedTemplate(t, db, "Page", "page") forkID := createTestFork(t, db, "bp") + ownedBySandboxKey(t, db, forkID) otherFork := createTestFork(t, db, "bp-other") // Copies are seeded first so an unfiltered lookup could return them. forkCopy := seedPage(t, db, models.Content{TemplateID: tmplID, Title: "Copy", FullPath: "/bp-page", ForkID: &forkID}) diff --git a/internal/handlers/governance_api_test.go b/internal/handlers/governance_api_test.go index 7bc0846..0811b1b 100644 --- a/internal/handlers/governance_api_test.go +++ b/internal/handlers/governance_api_test.go @@ -11,13 +11,27 @@ import ( "time" "github.com/metavert-io/lightcms/v7/internal/auth" + "github.com/metavert-io/lightcms/v7/internal/database" "github.com/metavert-io/lightcms/v7/internal/middleware" "github.com/metavert-io/lightcms/v7/internal/models" "github.com/gorilla/mux" + "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" ) +// sandboxTestCredential is the key sandboxOnlyReq signs in with. +const sandboxTestCredential = "apikey:sandbox-test" + +// ownedBySandboxKey records that the sandboxOnlyReq key created the fork, so +// it may write to it. +func ownedBySandboxKey(t *testing.T, db *database.DB, forkID primitive.ObjectID) { + t.Helper() + if err := db.UpdateOne(context.Background(), "content_forks", bson.M{"_id": forkID}, bson.M{"$set": bson.M{"created_by_credential": sandboxTestCredential}}); err != nil { + t.Fatalf("ownedBySandboxKey: %v", err) + } +} + // sandboxOnlyReq builds a request authenticated as an admin whose API key is // sandbox-only. func sandboxOnlyReq(method, target string, body io.Reader) *http.Request { @@ -25,6 +39,7 @@ func sandboxOnlyReq(method, target string, body io.Reader) *http.Request { u := &auth.SessionUser{ ID: "000000000000000000000001", Email: "agent@localhost", Role: "admin", ViaAPIKey: true, SandboxOnly: true, + Credential: sandboxTestCredential, } return req.WithContext(middleware.InjectAPIUser(req.Context(), u)) } @@ -35,6 +50,7 @@ func TestSandboxOnlyKey_Enforcement(t *testing.T) { tmplID := seedTemplate(t, db, "Page", "page") forkID := createTestFork(t, db, "gov") + ownedBySandboxKey(t, db, forkID) // Live create without fork_id → 403. req := sandboxOnlyReq("POST", "/api/v1/content", strings.NewReader( @@ -95,8 +111,8 @@ func TestSandboxOnlyKey_Enforcement(t *testing.T) { if rr.Code != 403 { t.Errorf("publish: status = %d, want 403", rr.Code) } - if !strings.Contains(rr.Body.String(), "sandbox-only") { - t.Errorf("publish denial should explain sandbox-only, got: %s", rr.Body.String()) + if !strings.Contains(rr.Body.String(), "limited to its own forks") { + t.Errorf("publish denial should explain the sandbox, got: %s", rr.Body.String()) } // Delete → 403. diff --git a/internal/handlers/handlers.go b/internal/handlers/handlers.go index d061e5f..3f5a14a 100644 --- a/internal/handlers/handlers.go +++ b/internal/handlers/handlers.go @@ -97,6 +97,7 @@ type Handler struct { agentService *services.AgentService indexNowService *services.IndexNowService seoService *services.SEOService + oauthService *services.OAuthService } // SetMaintenanceService wires the maintenance scan service (used by the copilot). @@ -3290,7 +3291,8 @@ func (h *Handler) APIKeysPage(w http.ResponseWriter, r *http.Request) { var keys []models.APIKey var err error - if auth.HasPermission(user.Role, auth.PermAPIKeyManageAll) { + seeAll := auth.HasPermission(user.Role, auth.PermAPIKeyManageAll) + if seeAll { keys, err = h.apiKeyService.ListAPIKeys(r.Context()) } else { userID, _ := primitive.ObjectIDFromHex(user.ID) @@ -3300,8 +3302,23 @@ func (h *Handler) APIKeysPage(w http.ResponseWriter, r *http.Request) { log.Printf("Failed to list API keys: %v", err) } + cache := map[primitive.ObjectID]*models.User{} + rows := make([]credentialRow, 0, len(keys)) + for i := range keys { + row := credentialRow{Key: &keys[i], OwnerEmail: "(no owner)"} + if keys[i].UserID != nil { + email, ownerCanMerge := h.ownerInfo(r, cache, *keys[i].UserID) + row.OwnerEmail = email + row.MergeEditable = ownerCanMerge && auth.HasPermission(user.Role, auth.PermForkMerge) + } + rows = append(rows, row) + } + h.renderAdmin(w, r, "api_keys", map[string]interface{}{ - "APIKeys": keys, + "APIKeys": rows, + "SeeAll": seeAll, + "Success": r.URL.Query().Get("success"), + "Error": r.URL.Query().Get("error"), }) } @@ -3333,14 +3350,27 @@ func (h *Handler) CreateAPIKey(w http.ResponseWriter, r *http.Request) { return } + // New keys are Sandbox unless Full is chosen. Merging its own forks + // needs a role that can merge. + access := services.AccessSettings{ + SandboxOnly: r.FormValue("access") != "full", + CanMergeOwnForks: r.FormValue("can_merge_own_forks") == "1" && auth.HasPermission(user.Role, auth.PermForkMerge), + } userID, _ := primitive.ObjectIDFromHex(user.ID) - rawKey, apiKey, err := h.apiKeyService.CreateAPIKeyForUser(r.Context(), name, description, &userID) + rawKey, apiKey, err := h.apiKeyService.CreateScopedAPIKey(r.Context(), name, description, &userID, nil, access.SandboxOnly) + if err == nil && access.CanMergeOwnForks { + if err = h.apiKeyService.UpdateAccess(r.Context(), apiKey.ID, access); err == nil { + apiKey.CanMergeOwnForks = true + } + } if err != nil { h.renderAdmin(w, r, "api_key_new", map[string]interface{}{ "Error": "Failed to create API key: " + err.Error(), }) return } + auditDetail(r, "sandbox_only", access.SandboxOnly) + auditDetail(r, "can_merge_own_forks", access.CanMergeOwnForks) auditResource(r, apiKey.ID.Hex()) h.renderAdmin(w, r, "api_key_created", map[string]interface{}{ diff --git a/internal/handlers/handlers_connections.go b/internal/handlers/handlers_connections.go new file mode 100644 index 0000000..eb60a4c --- /dev/null +++ b/internal/handlers/handlers_connections.go @@ -0,0 +1,223 @@ +package handlers + +import ( + "log" + "net/http" + "net/url" + "strings" + + "github.com/metavert-io/lightcms/v7/internal/auth" + "github.com/metavert-io/lightcms/v7/internal/models" + "github.com/metavert-io/lightcms/v7/internal/services" + + "github.com/gorilla/mux" + "go.mongodb.org/mongo-driver/bson/primitive" +) + +// SetOAuthService wires in the OAuth service (the Connected Apps page). +func (h *Handler) SetOAuthService(s *services.OAuthService) { h.oauthService = s } + +// credentialRow is one API key or connection on an admin page. +type credentialRow struct { + Key *models.APIKey // set for an API key + Grant *models.OAuthGrant // set for a connection + OwnerEmail string + // MergeEditable: the person viewing may change the merge setting (their + // role can merge, and so can the owner's). + MergeEditable bool +} + +// ownerInfo returns an account's email and whether its role can merge forks. +func (h *Handler) ownerInfo(r *http.Request, cache map[primitive.ObjectID]*models.User, id primitive.ObjectID) (string, bool) { + user, ok := cache[id] + if !ok { + user, _ = h.userService.GetByID(r.Context(), id) + cache[id] = user + } + if user == nil { + return "(deleted account)", false + } + return user.Email, auth.HasPermission(user.Role, auth.PermForkMerge) +} + +// accessFromForm reads the Access and merge settings posted from an admin +// page. Only someone whose role can merge may turn merging on, and only for +// an owner whose role can merge too; mergeShown is false when the page did +// not offer the checkbox, which then leaves the setting as it was. +func accessFromForm(r *http.Request, editor *auth.SessionUser, ownerCanMerge, currentMerge bool) (services.AccessSettings, string) { + access := services.AccessSettings{ + SandboxOnly: r.FormValue("access") != "full", + CanMergeOwnForks: currentMerge, + } + if r.FormValue("merge_shown") != "1" { + return access, "" + } + wantMerge := r.FormValue("can_merge_own_forks") == "1" + if wantMerge && !currentMerge && (!auth.HasPermission(editor.Role, auth.PermForkMerge) || !ownerCanMerge) { + return access, "Only an admin can let an agent merge its own forks, and only for an account that can merge." + } + access.CanMergeOwnForks = wantMerge + return access, "" +} + +func redirectWithMessage(w http.ResponseWriter, r *http.Request, path, kind, msg string) { + http.Redirect(w, r, path+"?"+kind+"="+url.QueryEscape(msg), http.StatusSeeOther) +} + +// ConnectedAppsPage lists OAuth connections: the user's own, or everyone's +// for someone who manages all API keys. +func (h *Handler) ConnectedAppsPage(w http.ResponseWriter, r *http.Request) { + user, ok := h.auth.GetCurrentUser(r) + if !ok { + http.Redirect(w, r, "/cm/login", http.StatusSeeOther) + return + } + data := map[string]interface{}{ + "Success": r.URL.Query().Get("success"), + "Error": r.URL.Query().Get("error"), + } + if h.oauthService == nil { + data["Error"] = "Connections are not available on this server." + h.renderAdmin(w, r, "connected_apps", data) + return + } + + seeAll := auth.HasPermission(user.Role, auth.PermAPIKeyManageAll) + var owner *primitive.ObjectID + if !seeAll { + id, err := primitive.ObjectIDFromHex(user.ID) + if err != nil { + http.Redirect(w, r, "/cm/login", http.StatusSeeOther) + return + } + owner = &id + } + grants, err := h.oauthService.ListGrants(r.Context(), owner) + if err != nil { + log.Printf("Failed to list connections: %v", err) + data["Error"] = "Could not load connections." + } + + cache := map[primitive.ObjectID]*models.User{} + rows := make([]credentialRow, 0, len(grants)) + for i := range grants { + email, ownerCanMerge := h.ownerInfo(r, cache, grants[i].UserID) + rows = append(rows, credentialRow{ + Grant: &grants[i], + OwnerEmail: email, + MergeEditable: ownerCanMerge && auth.HasPermission(user.Role, auth.PermForkMerge), + }) + } + data["Connections"] = rows + data["SeeAll"] = seeAll + h.renderAdmin(w, r, "connected_apps", data) +} + +// connectionForEditor loads a connection the signed-in user may change: their +// own, or anyone's with apikey.manage_all. It writes the response when not. +func (h *Handler) connectionForEditor(w http.ResponseWriter, r *http.Request, user *auth.SessionUser) *models.OAuthGrant { + id, err := primitive.ObjectIDFromHex(mux.Vars(r)["id"]) + if err != nil || h.oauthService == nil { + auditSkip(r) + http.NotFound(w, r) + return nil + } + grant, err := h.oauthService.GetGrant(r.Context(), id) + if err != nil || grant.RevokedAt != nil { + auditSkip(r) + http.NotFound(w, r) + return nil + } + if grant.UserID.Hex() != user.ID && !auth.HasPermission(user.Role, auth.PermAPIKeyManageAll) { + h.refuseAdminMessage(w, r, false, "That connection is not yours. Nothing was changed.") + return nil + } + return grant +} + +// UpdateConnectedApp changes a connection's access. +func (h *Handler) UpdateConnectedApp(w http.ResponseWriter, r *http.Request) { + user, ok := h.auth.GetCurrentUser(r) + if !ok { + http.Redirect(w, r, "/cm/login", http.StatusSeeOther) + return + } + grant := h.connectionForEditor(w, r, user) + if grant == nil { + return + } + _, ownerCanMerge := h.ownerInfo(r, map[primitive.ObjectID]*models.User{}, grant.UserID) + access, refusal := accessFromForm(r, user, ownerCanMerge, grant.CanMergeOwnForks) + if refusal != "" { + redirectWithMessage(w, r, "/cm/connected-apps", "error", refusal) + return + } + if err := h.oauthService.UpdateGrantAccess(r.Context(), grant.ID, access); err != nil { + redirectWithMessage(w, r, "/cm/connected-apps", "error", "Could not save the change.") + return + } + auditDetail(r, "sandbox_only", access.SandboxOnly) + auditDetail(r, "can_merge_own_forks", access.CanMergeOwnForks) + redirectWithMessage(w, r, "/cm/connected-apps", "success", "Saved access for "+grant.ClientName+".") +} + +// RevokeConnectedApp disconnects an app: its tokens stop working at once. +func (h *Handler) RevokeConnectedApp(w http.ResponseWriter, r *http.Request) { + user, ok := h.auth.GetCurrentUser(r) + if !ok { + http.Redirect(w, r, "/cm/login", http.StatusSeeOther) + return + } + grant := h.connectionForEditor(w, r, user) + if grant == nil { + return + } + if err := h.oauthService.RevokeGrant(r.Context(), grant.ID); err != nil { + redirectWithMessage(w, r, "/cm/connected-apps", "error", "Could not disconnect the app.") + return + } + redirectWithMessage(w, r, "/cm/connected-apps", "success", "Disconnected "+grant.ClientName+".") +} + +// UpdateAPIKeyAccess changes an API key's access: the caller's own key, or +// any key with apikey.manage_all. +func (h *Handler) UpdateAPIKeyAccess(w http.ResponseWriter, r *http.Request) { + user, ok := h.auth.GetCurrentUser(r) + if !ok { + http.Redirect(w, r, "/cm/login", http.StatusSeeOther) + return + } + id, err := primitive.ObjectIDFromHex(mux.Vars(r)["id"]) + if err != nil { + auditSkip(r) + http.NotFound(w, r) + return + } + key, err := h.apiKeyService.GetAPIKey(r.Context(), id) + if err != nil { + auditSkip(r) + http.NotFound(w, r) + return + } + mine := key.UserID != nil && key.UserID.Hex() == user.ID + if !mine && !auth.HasPermission(user.Role, auth.PermAPIKeyManageAll) { + h.refuseAdminMessage(w, r, false, "That API key was not found or is not yours. Nothing was changed.") + return + } + ownerCanMerge := false + if key.UserID != nil { + _, ownerCanMerge = h.ownerInfo(r, map[primitive.ObjectID]*models.User{}, *key.UserID) + } + access, refusal := accessFromForm(r, user, ownerCanMerge, key.CanMergeOwnForks) + if refusal != "" { + redirectWithMessage(w, r, "/cm/api-keys", "error", refusal) + return + } + if err := h.apiKeyService.UpdateAccess(r.Context(), key.ID, access); err != nil { + redirectWithMessage(w, r, "/cm/api-keys", "error", "Could not save the change.") + return + } + auditDetail(r, "sandbox_only", access.SandboxOnly) + auditDetail(r, "can_merge_own_forks", access.CanMergeOwnForks) + redirectWithMessage(w, r, "/cm/api-keys", "success", "Saved access for "+strings.TrimSpace(key.Name)+".") +} diff --git a/internal/handlers/testhelper_test.go b/internal/handlers/testhelper_test.go index c897aef..8beeeda 100644 --- a/internal/handlers/testhelper_test.go +++ b/internal/handlers/testhelper_test.go @@ -216,6 +216,7 @@ func newTestHandler(t *testing.T) (*Handler, func()) { h.SetForkService(services.NewForkService(db, contentService)) h.SetApprovalService(services.NewApprovalService(db, contentService, commentService, webhookService)) h.SetAnalyticsService(services.NewAnalyticsService(context.Background(), db, "http://localhost:8082")) + h.SetOAuthService(services.NewOAuthService(db)) cleanup := func() { cleanupCollections(t, db) @@ -373,6 +374,7 @@ func newTestAPIHandler(t *testing.T) (*APIHandler, *database.DB, func()) { ah.SetImportService(services.NewImportService(db, contentService)) ah.SetUserService(services.NewUserService(db)) ah.SetApprovalService(services.NewApprovalService(db, contentService, commentService, webhookService)) + ah.SetOAuthService(services.NewOAuthService(db)) cleanup := func() { cleanupCollections(t, db) diff --git a/internal/mcp/content_tools.go b/internal/mcp/content_tools.go index 5f4a200..e6217b2 100644 --- a/internal/mcp/content_tools.go +++ b/internal/mcp/content_tools.go @@ -391,7 +391,7 @@ Templates can use {{.lc_toc}} in their HTML layout to inject an auto-generated t } // Sandbox: create the page inside the sandbox fork instead of live. - if forkID, _, active := s.sandboxFork(); active { + if forkID, _, active := s.sandboxFork(ctx); active { if args.Upsert { return textResult("upsert is not available while an agent sandbox is active — use update_content so the change stays in the sandbox fork"), nil, nil } @@ -502,7 +502,7 @@ Templates can use {{.lc_toc}} in their HTML layout to inject an auto-generated t // Sandbox: redirect the write to the fork copy (copy-on-write). targetID := args.ID - if _, _, active := s.sandboxFork(); active { + if _, _, active := s.sandboxFork(ctx); active { tid, err := s.sandboxTargetForContent(ctx, args.ID) if err != nil { return errorResult(err), nil, nil @@ -571,9 +571,6 @@ Templates can use {{.lc_toc}} in their HTML layout to inject an auto-generated t OpenWorldHint: boolPtr(false), }, }, func(ctx context.Context, req *mcp.CallToolRequest, args ContentIDInput) (*mcp.CallToolResult, any, error) { - if blocked := s.sandboxBlock("publish_content"); blocked != nil { - return blocked, nil, nil - } if err := s.client.PublishContent(ctx, args.ID); err != nil { return errorResult(err), nil, nil } @@ -593,9 +590,6 @@ Templates can use {{.lc_toc}} in their HTML layout to inject an auto-generated t OpenWorldHint: boolPtr(false), }, }, func(ctx context.Context, req *mcp.CallToolRequest, args ContentIDInput) (*mcp.CallToolResult, any, error) { - if blocked := s.sandboxBlock("unpublish_content"); blocked != nil { - return blocked, nil, nil - } if err := s.client.UnpublishContent(ctx, args.ID); err != nil { return errorResult(err), nil, nil } @@ -615,9 +609,6 @@ Templates can use {{.lc_toc}} in their HTML layout to inject an auto-generated t OpenWorldHint: boolPtr(false), }, }, func(ctx context.Context, req *mcp.CallToolRequest, args ContentIDInput) (*mcp.CallToolResult, any, error) { - if blocked := s.sandboxBlock("delete_content"); blocked != nil { - return blocked, nil, nil - } if err := s.client.DeleteContent(ctx, args.ID); err != nil { return errorResult(err), nil, nil } @@ -637,9 +628,6 @@ Templates can use {{.lc_toc}} in their HTML layout to inject an auto-generated t OpenWorldHint: boolPtr(false), }, }, func(ctx context.Context, req *mcp.CallToolRequest, args ContentIDInput) (*mcp.CallToolResult, any, error) { - if blocked := s.sandboxBlock("restore_content"); blocked != nil { - return blocked, nil, nil - } if err := s.client.RestoreContent(ctx, args.ID); err != nil { return errorResult(err), nil, nil } @@ -719,9 +707,6 @@ Templates can use {{.lc_toc}} in their HTML layout to inject an auto-generated t OpenWorldHint: boolPtr(false), }, }, func(ctx context.Context, req *mcp.CallToolRequest, args RevertToVersionInput) (*mcp.CallToolResult, any, error) { - if blocked := s.sandboxBlock("revert_to_version"); blocked != nil { - return blocked, nil, nil - } if err := s.client.RevertContentVersion(ctx, args.ContentID, args.Version, args.VersionComment); err != nil { return errorResult(err), nil, nil } @@ -749,9 +734,6 @@ Returns published IDs, skipped items, and any failures.`, OpenWorldHint: boolPtr(false), }, }, func(ctx context.Context, req *mcp.CallToolRequest, args BatchPublishInput) (*mcp.CallToolResult, any, error) { - if blocked := s.sandboxBlock("publish_multiple"); blocked != nil { - return blocked, nil, nil - } result, err := s.client.BatchPublishContent(ctx, args.IDs, args.PublishAllDrafts) if err != nil { return errorResult(err), nil, nil @@ -810,7 +792,7 @@ Only the fields you provide are changed. Always include a version_comment descri }, func(ctx context.Context, req *mcp.CallToolRequest, args UpdateContentByPathInput) (*mcp.CallToolResult, any, error) { // Sandbox: copy-on-write the page into the fork and update the copy. sandboxID := "" - if _, _, active := s.sandboxFork(); active { + if _, _, active := s.sandboxFork(ctx); active { tid, err := s.sandboxTargetForPath(ctx, args.Path) if err != nil { return errorResult(err), nil, nil @@ -992,9 +974,6 @@ Example: {"search": "old text", "replace": "new text", "folder_path": "/blog", " OpenWorldHint: boolPtr(false), }, }, func(ctx context.Context, req *mcp.CallToolRequest, args ScopedSearchReplaceInput) (*mcp.CallToolResult, any, error) { - if blocked := s.sandboxBlock("scoped_search_replace_execute"); blocked != nil { - return blocked, nil, nil - } scope := apiclient.ScopedSearchReplaceScope{ ContentIDs: args.ContentIDs, FolderPath: args.FolderPath, @@ -1028,9 +1007,6 @@ Returns: total attempted, succeeded, failed counts, and per-item {id, full_path, OpenWorldHint: boolPtr(false), }, }, func(ctx context.Context, req *mcp.CallToolRequest, args BulkCreateContentInput) (*mcp.CallToolResult, any, error) { - if blocked := s.sandboxBlock("bulk_create_content"); blocked != nil { - return blocked, nil, nil - } result, err := s.client.BulkCreateContent(ctx, args) if err != nil { return errorResult(err), nil, nil @@ -1060,9 +1036,6 @@ Recommended batch size: up to 50 per call for optimal performance.`, OpenWorldHint: boolPtr(false), }, }, func(ctx context.Context, req *mcp.CallToolRequest, args BulkUpdateContentInput) (*mcp.CallToolResult, any, error) { - if blocked := s.sandboxBlock("bulk_update_content"); blocked != nil { - return blocked, nil, nil - } result, err := s.client.BulkUpdateContent(ctx, args) if err != nil { return errorResult(err), nil, nil @@ -1096,9 +1069,6 @@ Example: {"operation": "prepend", "field": "disclaimer", "value": "

Note:

OpenWorldHint: boolPtr(false), }, }, func(ctx context.Context, req *mcp.CallToolRequest, args BulkFieldOperationInput) (*mcp.CallToolResult, any, error) { - if blocked := s.sandboxBlock("bulk_field_operation"); blocked != nil { - return blocked, nil, nil - } body := map[string]interface{}{ "operation": args.Operation, "field": args.Field, diff --git a/internal/mcp/coverage_more_test.go b/internal/mcp/coverage_more_test.go index d324c7f..920ce52 100644 --- a/internal/mcp/coverage_more_test.go +++ b/internal/mcp/coverage_more_test.go @@ -314,18 +314,6 @@ func TestSandbox_PassthroughAndFailureBranches(t *testing.T) { t.Errorf("expected copy-on-write failure by ID, got: %v %s", res.IsError, resultText(t, res)) } - // Destructive tools that consult sandboxBlock are refused while active. - res = callTool(t, s, "revert_to_version", map[string]interface{}{"content_id": "live1", "version": 1}) - if !strings.Contains(resultText(t, res), "BLOCKED") { - t.Errorf("revert_to_version should be blocked in sandbox: %s", resultText(t, res)) - } - res = callTool(t, s, "bulk_create_content", map[string]interface{}{ - "items": []map[string]interface{}{{"template_id": "t1", "title": "A", "slug": "a", "data": map[string]interface{}{}}}, - }) - if !strings.Contains(resultText(t, res), "BLOCKED") { - t.Errorf("bulk_create_content should be blocked in sandbox: %s", resultText(t, res)) - } - // Diff backend failure: status and submit both surface the error. state.mu.Lock() state.diffFails = true diff --git a/internal/mcp/draft_safety_test.go b/internal/mcp/draft_safety_test.go index 423f234..e11bba4 100644 --- a/internal/mcp/draft_safety_test.go +++ b/internal/mcp/draft_safety_test.go @@ -230,14 +230,3 @@ func TestDraftSafety_PurgeRefusedOnActiveFork(t *testing.T) { t.Errorf("expected refusal for an active fork, got: %v %s", res.IsError, resultText(t, res)) } } - -func TestDraftSafety_PurgeBlockedInSandbox(t *testing.T) { - s, _, cleanup := newSandboxServer(t) - defer cleanup() - - callTool(t, s, "start_agent_sandbox", map[string]interface{}{"name": "s"}) - res := callTool(t, s, "purge_fork_copies", map[string]interface{}{"fork_id": "other"}) - if !strings.Contains(resultText(t, res), "BLOCKED") { - t.Errorf("purge_fork_copies should be blocked while sandboxed, got: %s", resultText(t, res)) - } -} diff --git a/internal/mcp/fork_tools.go b/internal/mcp/fork_tools.go index 8873b0c..162e7f4 100644 --- a/internal/mcp/fork_tools.go +++ b/internal/mcp/fork_tools.go @@ -201,9 +201,6 @@ ALWAYS confirm with the user before merging, as this pushes changes to the live OpenWorldHint: boolPtr(false), }, }, func(ctx context.Context, req *mcp.CallToolRequest, args MergeForkInput) (*mcp.CallToolResult, any, error) { - if sbID, sbName, sbActive := s.sandboxFork(); sbActive && args.ForkID == sbID { - return textResult(fmt.Sprintf("BLOCKED: %s targets the active agent sandbox %q. Agents cannot merge their own sandbox — use end_agent_sandbox instead; merging is a human decision.", "merge_fork", sbName)), nil, nil - } result, err := s.client.MergeFork(ctx, args.ForkID, args.PublishNew) if err != nil { return errorResult(err), nil, nil @@ -224,9 +221,6 @@ ALWAYS confirm with the user before merging, as this pushes changes to the live OpenWorldHint: boolPtr(false), }, }, func(ctx context.Context, req *mcp.CallToolRequest, args ArchiveForkInput) (*mcp.CallToolResult, any, error) { - if sbID, sbName, sbActive := s.sandboxFork(); sbActive && args.ForkID == sbID { - return textResult(fmt.Sprintf("BLOCKED: %s targets the active agent sandbox %q. Agents cannot archive their own sandbox — use end_agent_sandbox instead; merging is a human decision.", "archive_fork", sbName)), nil, nil - } if err := s.client.ArchiveFork(ctx, args.ForkID); err != nil { return errorResult(err), nil, nil } @@ -246,9 +240,6 @@ ALWAYS confirm with the user before merging, as this pushes changes to the live OpenWorldHint: boolPtr(false), }, }, func(ctx context.Context, req *mcp.CallToolRequest, args DeleteForkInput) (*mcp.CallToolResult, any, error) { - if sbID, sbName, sbActive := s.sandboxFork(); sbActive && args.ForkID == sbID { - return textResult(fmt.Sprintf("BLOCKED: %s targets the active agent sandbox %q. Agents cannot delete their own sandbox — use end_agent_sandbox instead; merging is a human decision.", "delete_fork", sbName)), nil, nil - } if err := s.client.DeleteFork(ctx, args.ForkID); err != nil { return errorResult(err), nil, nil } @@ -275,11 +266,6 @@ Use dry_run: true first to see the count and the list of {id, full_path}. Return if args.ForkID == "" { return errorResult(fmt.Errorf("fork_id is required")), nil, nil } - if !args.DryRun { - if blocked := s.sandboxBlock("purge_fork_copies"); blocked != nil { - return blocked, nil, nil - } - } result, err := s.client.PurgeForkCopies(ctx, args.ForkID, args.DryRun) if err != nil { return errorResult(err), nil, nil diff --git a/internal/mcp/sandbox_test.go b/internal/mcp/sandbox_test.go index a438d94..f4e24a4 100644 --- a/internal/mcp/sandbox_test.go +++ b/internal/mcp/sandbox_test.go @@ -1,6 +1,7 @@ package mcp import ( + "context" "encoding/json" "net/http" "net/http/httptest" @@ -11,38 +12,79 @@ import ( "github.com/metavert-io/lightcms/v7/internal/apiclient" ) -// sandboxAPI is a minimal fake REST API tracking fork state, for exercising -// the agent-sandbox flow end to end at the MCP layer. +// sandboxAPI is a minimal fake REST API that keeps the sandbox the way the +// server does: on the credential, outside any MCP session. type sandboxAPI struct { mu sync.Mutex + active bool // a sandbox is open + restricted bool // the credential is set to Sandbox access forkCreated bool forkDeleted bool forkPages map[string]string // path -> fork page ID updates map[string]int // content ID -> update count diffFails bool // when true, the fork diff endpoint returns 500 - deleteFails bool // when true, deleting the fork returns 500 + deleteFails bool // when true, discarding the sandbox returns 500 +} + +func (state *sandboxAPI) sandboxJSON() map[string]interface{} { + resp := map[string]interface{}{"active": state.active, "restricted": state.restricted} + if state.active { + resp["fork_id"] = "fork1" + resp["name"] = "agent-session" + resp["review_url"] = "/cm/forks/fork1" + } + return resp } func newSandboxServer(t *testing.T) (*Server, *sandboxAPI, func()) { t.Helper() state := &sandboxAPI{forkPages: map[string]string{}, updates: map[string]int{}} + ts := httptest.NewServer(sandboxMux(state)) + return NewServer(apiclient.New(ts.URL, "test-key")), state, ts.Close +} +func sandboxMux(state *sandboxAPI) *http.ServeMux { mux := http.NewServeMux() - mux.HandleFunc("POST /api/v1/forks", func(w http.ResponseWriter, r *http.Request) { + mux.HandleFunc("GET /api/v1/sandbox", func(w http.ResponseWriter, r *http.Request) { state.mu.Lock() - state.forkCreated = true - state.mu.Unlock() - json.NewEncoder(w).Encode(map[string]interface{}{"id": "fork1", "name": "agent-session", "status": "active"}) + defer state.mu.Unlock() + json.NewEncoder(w).Encode(state.sandboxJSON()) }) - mux.HandleFunc("DELETE /api/v1/forks/fork1", func(w http.ResponseWriter, r *http.Request) { + mux.HandleFunc("POST /api/v1/sandbox", func(w http.ResponseWriter, r *http.Request) { + state.mu.Lock() + defer state.mu.Unlock() + if state.active { + w.WriteHeader(http.StatusConflict) + json.NewEncoder(w).Encode(map[string]string{"error": `a sandbox ("agent-session") is already open; end it first`}) + return + } + state.active, state.forkCreated = true, true + w.WriteHeader(http.StatusCreated) + json.NewEncoder(w).Encode(state.sandboxJSON()) + }) + mux.HandleFunc("POST /api/v1/sandbox/end", func(w http.ResponseWriter, r *http.Request) { + var body map[string]string + json.NewDecoder(r.Body).Decode(&body) state.mu.Lock() - fails := state.deleteFails - if !fails { + defer state.mu.Unlock() + if body["action"] == "discard" { + if state.deleteFails { + http.Error(w, `{"error":"cannot delete"}`, http.StatusInternalServerError) + return + } state.forkDeleted = true } + state.active = false + json.NewEncoder(w).Encode(map[string]interface{}{"action": body["action"], "fork_id": "fork1", "restricted": state.restricted}) + }) + // The server refuses live changes from a sandboxed caller. + mux.HandleFunc("POST /api/v1/content/live1/publish", func(w http.ResponseWriter, r *http.Request) { + state.mu.Lock() + active := state.active || state.restricted state.mu.Unlock() - if fails { - http.Error(w, `{"error":"cannot delete"}`, http.StatusInternalServerError) + if active { + w.WriteHeader(http.StatusForbidden) + json.NewEncoder(w).Encode(map[string]string{"error": "this connection is limited to its own forks"}) return } json.NewEncoder(w).Encode(map[string]interface{}{"success": true}) @@ -127,10 +169,7 @@ func newSandboxServer(t *testing.T) (*Server, *sandboxAPI, func()) { }) }) - ts := httptest.NewServer(mux) - client := apiclient.New(ts.URL, "test-key") - s := NewServer(client) - return s, state, ts.Close + return mux } func TestSandbox_Lifecycle(t *testing.T) { @@ -151,13 +190,13 @@ func TestSandbox_Lifecycle(t *testing.T) { if !state.forkCreated { t.Fatal("fork was not created") } - if _, _, active := s.sandboxFork(); !active { + if _, _, active := s.sandboxFork(context.Background()); !active { t.Fatal("sandbox not active after start") } // Double-start is refused. res = callTool(t, s, "start_agent_sandbox", map[string]string{}) - if !strings.Contains(resultText(t, res), "already active") { + if !strings.Contains(resultText(t, res), "already open") { t.Errorf("double start: %s", resultText(t, res)) } @@ -173,11 +212,51 @@ func TestSandbox_Lifecycle(t *testing.T) { if !strings.Contains(txt, "/cm/forks/fork1") { t.Errorf("submit should include review URL: %s", txt) } - if _, _, active := s.sandboxFork(); active { + if _, _, active := s.sandboxFork(context.Background()); active { t.Fatal("sandbox still active after submit") } } +// The sandbox lives on the server, so a new MCP session (or a restarted +// server) carries on in the same fork. +func TestSandbox_ContinuesInANewSession(t *testing.T) { + state := &sandboxAPI{forkPages: map[string]string{}, updates: map[string]int{}} + ts := httptest.NewServer(sandboxMux(state)) + defer ts.Close() + + first := NewServer(apiclient.New(ts.URL, "test-key")) + callTool(t, first, "start_agent_sandbox", map[string]string{}) + + second := NewServer(apiclient.New(ts.URL, "test-key")) + if _, _, active := second.sandboxFork(context.Background()); !active { + t.Fatal("a new session does not see the open sandbox") + } + callTool(t, second, "update_content", map[string]interface{}{"id": "live1", "title": "From the new session"}) + state.mu.Lock() + defer state.mu.Unlock() + if state.updates["live1"] != 0 || state.updates["fp-live-page"] != 1 { + t.Errorf("live=%d fork=%d, want 0/1", state.updates["live1"], state.updates["fp-live-page"]) + } +} + +func TestSandbox_StatusSaysWhenTheConnectionIsSandboxOnly(t *testing.T) { + s, state, cleanup := newSandboxServer(t) + defer cleanup() + state.restricted = true + + res := callTool(t, s, "get_agent_sandbox", struct{}{}) + if !strings.Contains(resultText(t, res), "set to Sandbox access") { + t.Errorf("status: %s", resultText(t, res)) + } + res = callTool(t, s, "start_agent_sandbox", map[string]string{}) + callTool(t, s, "end_agent_sandbox", map[string]string{"action": "discard"}) + res = callTool(t, s, "start_agent_sandbox", map[string]string{}) + res = callTool(t, s, "end_agent_sandbox", map[string]string{"action": "discard"}) + if !strings.Contains(resultText(t, res), "can still change only forks") { + t.Errorf("discard on a sandbox-only connection: %s", resultText(t, res)) + } +} + func TestSandbox_CopyOnWriteUpdate(t *testing.T) { s, state, cleanup := newSandboxServer(t) defer cleanup() @@ -236,40 +315,19 @@ func TestSandbox_CreateGoesIntoFork(t *testing.T) { } } -func TestSandbox_BlocksDestructiveTools(t *testing.T) { +// Tools no longer refuse anything themselves: the server does, for every +// client, and its reason reaches the agent. +func TestSandbox_LiveChangesAreRefusedByTheServer(t *testing.T) { s, _, cleanup := newSandboxServer(t) defer cleanup() - callTool(t, s, "start_agent_sandbox", map[string]string{}) - - blocked := []struct { - tool string - args interface{} - }{ - {"publish_content", map[string]string{"id": "live1"}}, - {"unpublish_content", map[string]string{"id": "live1"}}, - {"delete_content", map[string]string{"id": "live1"}}, - {"restore_content", map[string]string{"id": "live1"}}, - {"publish_multiple", map[string]interface{}{"ids": []string{"live1"}}}, - {"bulk_update_content", map[string]interface{}{"updates": []map[string]interface{}{}}}, - {"bulk_field_operation", map[string]interface{}{"operation": "set", "field": "x"}}, - {"search_replace_execute", map[string]interface{}{"search": "a", "replace": "b"}}, - {"scoped_search_replace_execute", map[string]interface{}{"search": "a", "replace": "b"}}, - {"regenerate_all_content", struct{}{}}, + if res := callTool(t, s, "publish_content", map[string]string{"id": "live1"}); res.IsError { + t.Fatalf("without a sandbox: %s", resultText(t, res)) } - for _, b := range blocked { - res := callTool(t, s, b.tool, b.args) - if !strings.Contains(resultText(t, res), "BLOCKED") { - t.Errorf("%s should be blocked in sandbox, got: %s", b.tool, resultText(t, res)) - } - } - - // Fork tools targeting the sandbox's own fork are blocked too. - for _, tool := range []string{"merge_fork", "archive_fork", "delete_fork"} { - res := callTool(t, s, tool, map[string]string{"fork_id": "fork1"}) - if !strings.Contains(resultText(t, res), "BLOCKED") { - t.Errorf("%s on own sandbox should be blocked, got: %s", tool, resultText(t, res)) - } + callTool(t, s, "start_agent_sandbox", map[string]string{}) + res := callTool(t, s, "publish_content", map[string]string{"id": "live1"}) + if !res.IsError || !strings.Contains(resultText(t, res), "limited to its own forks") { + t.Errorf("publish in a sandbox: %v %s", res.IsError, resultText(t, res)) } } @@ -285,7 +343,7 @@ func TestSandbox_DiscardDeletesFork(t *testing.T) { if !state.forkDeleted { t.Error("fork was not deleted on discard") } - if _, _, active := s.sandboxFork(); active { + if _, _, active := s.sandboxFork(context.Background()); active { t.Error("sandbox still active after discard") } } diff --git a/internal/mcp/sandbox_tools.go b/internal/mcp/sandbox_tools.go index 7858596..c868083 100644 --- a/internal/mcp/sandbox_tools.go +++ b/internal/mcp/sandbox_tools.go @@ -4,48 +4,27 @@ import ( "context" "encoding/json" "fmt" - "sync" "github.com/modelcontextprotocol/go-sdk/mcp" ) -// sandboxState tracks the agent sandbox for this MCP session. While a -// sandbox is active, all content writes are redirected into its fork — -// live content is untouched until a human reviews and merges the fork. -type sandboxState struct { - mu sync.Mutex - forkID string - forkName string -} - -// sandboxFork returns the active sandbox fork, if any. -func (s *Server) sandboxFork() (id, name string, active bool) { - s.sandbox.mu.Lock() - defer s.sandbox.mu.Unlock() - return s.sandbox.forkID, s.sandbox.forkName, s.sandbox.forkID != "" -} - -// sandboxBlock returns a non-nil error result when a sandbox is active, -// explaining why the tool is unavailable. Tools that publish, delete, or -// bulk-modify live content call this first. -func (s *Server) sandboxBlock(tool string) *mcp.CallToolResult { - forkID, forkName, active := s.sandboxFork() - if !active { - return nil +// sandboxFork returns the caller's open sandbox, which the server keeps on the +// API key or OAuth connection: the same in every MCP session, and kept across +// restarts. When it cannot be read, writes are not redirected; the server +// still refuses anything a sandboxed caller may not do. +func (s *Server) sandboxFork(ctx context.Context) (id, name string, active bool) { + state, err := s.client.GetSandbox(ctx) + if err != nil || state == nil || !state.Active { + return "", "", false } - return textResult(fmt.Sprintf( - "BLOCKED: %s is not available while agent sandbox %q (fork %s) is active. "+ - "All changes must stay in the sandbox fork until a human reviews and merges it. "+ - "Use update_content / create_content (they write into the sandbox automatically), "+ - "then end_agent_sandbox to hand the fork off for review.", - tool, forkName, forkID)) + return state.ForkID, state.Name, true } // sandboxTargetForContent resolves which content ID an update should hit // while a sandbox is active: fork copies pass through, live pages get a // copy-on-write fork copy, and pages from other forks are rejected. func (s *Server) sandboxTargetForContent(ctx context.Context, contentID string) (string, error) { - forkID, _, active := s.sandboxFork() + forkID, _, active := s.sandboxFork(ctx) if !active { return contentID, nil } @@ -71,7 +50,7 @@ func (s *Server) sandboxTargetForContent(ctx context.Context, contentID string) // It returns the ID of the sandbox copy for the page at path ("" when no // sandbox is active, meaning: use the normal by-path flow). func (s *Server) sandboxTargetForPath(ctx context.Context, path string) (string, error) { - forkID, _, active := s.sandboxFork() + forkID, _, active := s.sandboxFork(ctx) if !active { return "", nil } @@ -98,13 +77,13 @@ func (s *Server) registerSandboxTools() { Title: "Start Agent Sandbox", Description: `Start a sandboxed editing session backed by a content fork ("pull request for content"). -While the sandbox is active: -- update_content / update_content_by_path transparently copy pages into the fork and edit the copies (copy-on-write). Live content is never modified. +The server records the sandbox on this API key or connection. Until it ends, every request from this key or connection is limited to the fork, in any session, and across restarts: +- update_content / update_content_by_path copy pages into the fork and edit the copies (copy-on-write). Live content is not modified. - create_content creates new pages inside the fork. -- Publishing, deleting, bulk operations, and search/replace-execute are blocked. -- The site is unaffected until a human reviews the fork at /cm/forks and merges it. +- Anything else that would change the live site is refused by the server. +- The site is unaffected until the fork is merged at /cm/forks. -Recommended for any multi-page or risky editing task. End with end_agent_sandbox.`, +A key or connection set to Sandbox access is always limited to forks it created; it needs a sandbox (or create_fork) before it can change anything. On one with Full access the sandbox is an opt-in safety net. Recommended for any multi-page or risky editing task. End with end_agent_sandbox.`, Annotations: &mcp.ToolAnnotations{ Title: "Start Agent Sandbox", ReadOnlyHint: false, @@ -113,35 +92,19 @@ Recommended for any multi-page or risky editing task. End with end_agent_sandbox OpenWorldHint: boolPtr(false), }, }, func(ctx context.Context, req *mcp.CallToolRequest, args StartAgentSandboxInput) (*mcp.CallToolResult, any, error) { - if _, name, active := s.sandboxFork(); active { - return textResult(fmt.Sprintf("A sandbox (%q) is already active. End it with end_agent_sandbox before starting another.", name)), nil, nil - } - name := args.Name - if name == "" { - name = "agent-session" - } - desc := args.Description - if desc == "" { - desc = "Agent sandbox session" - } - fork, err := s.client.CreateFork(ctx, name, desc) + state, err := s.client.StartSandbox(ctx, args.Name, args.Description) if err != nil { return errorResult(err), nil, nil } - forkID, _ := fork["id"].(string) - if forkID == "" { - return textResult("fork created but no ID returned"), nil, nil + if state.ForkID == "" { + return textResult("sandbox started but no ID returned by the server"), nil, nil } - s.sandbox.mu.Lock() - s.sandbox.forkID = forkID - s.sandbox.forkName = name - s.sandbox.mu.Unlock() - return jsonResult(map[string]interface{}{ - "success": true, - "fork_id": forkID, - "name": name, - "message": "Sandbox active. All content writes now go into this fork; live content is protected. Call end_agent_sandbox when done.", + "success": true, + "fork_id": state.ForkID, + "name": state.Name, + "review_url": state.ReviewURL, + "message": "Sandbox active. All content writes now go into this fork; live content is protected. Call end_agent_sandbox when done.", }), nil, nil }) @@ -149,25 +112,32 @@ Recommended for any multi-page or risky editing task. End with end_agent_sandbox mcp.AddTool(s.mcpServer, &mcp.Tool{ Name: "get_agent_sandbox", Title: "Get Agent Sandbox Status", - Description: "Show whether an agent sandbox is active, and if so its fork ID, name, and the pages changed so far (with per-field diffs against live).", + Description: "Show whether an agent sandbox is open for this API key or connection, and if so its fork ID, name, and the pages changed so far (with per-field diffs against live). Also says whether this key or connection is set to Sandbox access.", Annotations: &mcp.ToolAnnotations{ Title: "Get Agent Sandbox Status", ReadOnlyHint: true, }, }, func(ctx context.Context, req *mcp.CallToolRequest, args struct{}) (*mcp.CallToolResult, any, error) { - forkID, name, active := s.sandboxFork() - if !active { + state, err := s.client.GetSandbox(ctx) + if err != nil { + return errorResult(err), nil, nil + } + if !state.Active { + if state.Restricted { + return textResult("No agent sandbox is open. This connection is set to Sandbox access: it can change only forks it created, so start a sandbox with start_agent_sandbox before changing content."), nil, nil + } return textResult("No agent sandbox is active. Content tools operate on live content."), nil, nil } - diff, err := s.client.GetForkDiff(ctx, forkID) + diff, err := s.client.GetForkDiff(ctx, state.ForkID) if err != nil { return errorResult(err), nil, nil } return jsonResult(map[string]interface{}{ - "active": true, - "fork_id": forkID, - "name": name, - "changes": diff.Pages, + "active": true, + "restricted": state.Restricted, + "fork_id": state.ForkID, + "name": state.Name, + "changes": diff.Pages, }), nil, nil }) @@ -175,7 +145,7 @@ Recommended for any multi-page or risky editing task. End with end_agent_sandbox mcp.AddTool(s.mcpServer, &mcp.Tool{ Name: "end_agent_sandbox", Title: "End Agent Sandbox", - Description: `End the sandbox session. action='submit' keeps the fork for human review and merge (at /cm/forks/{id}); action='discard' permanently deletes the fork and all its changes. Agents cannot merge their own sandbox — merging is a human decision.`, + Description: `End the sandbox. action='submit' leaves the fork for review and merge (at /cm/forks/{id}); action='discard' permanently deletes the fork and all its changes. A key or connection set to Sandbox access stays limited to forks it created afterwards. Merging is a separate step (merge_fork) that a sandboxed connection can't take.`, Annotations: &mcp.ToolAnnotations{ Title: "End Agent Sandbox", ReadOnlyHint: false, @@ -184,38 +154,42 @@ Recommended for any multi-page or risky editing task. End with end_agent_sandbox OpenWorldHint: boolPtr(false), }, }, func(ctx context.Context, req *mcp.CallToolRequest, args EndAgentSandboxInput) (*mcp.CallToolResult, any, error) { - forkID, name, active := s.sandboxFork() + if args.Action != "submit" && args.Action != "discard" { + return textResult("action must be 'submit' or 'discard'"), nil, nil + } + forkID, name, active := s.sandboxFork(ctx) if !active { return textResult("No agent sandbox is active."), nil, nil } - switch args.Action { - case "submit": - diff, err := s.client.GetForkDiff(ctx, forkID) + if args.Action == "discard" { + result, err := s.client.EndSandbox(ctx, "discard") if err != nil { return errorResult(err), nil, nil } - s.sandbox.mu.Lock() - s.sandbox.forkID, s.sandbox.forkName = "", "" - s.sandbox.mu.Unlock() - return jsonResult(map[string]interface{}{ - "success": true, - "fork_id": forkID, - "name": name, - "changes": diff.Pages, - "review_url": "/cm/forks/" + forkID, - "message": "Sandbox submitted. A human can review the changes and merge the fork from the admin UI.", - }), nil, nil - case "discard": - if err := s.client.DeleteFork(ctx, forkID); err != nil { - return errorResult(err), nil, nil + msg := fmt.Sprintf("Sandbox %q discarded — fork and all its changes deleted. Live content was never modified.", name) + if restricted, _ := result["restricted"].(bool); restricted { + msg += " This connection is set to Sandbox access and can still change only forks it creates." } - s.sandbox.mu.Lock() - s.sandbox.forkID, s.sandbox.forkName = "", "" - s.sandbox.mu.Unlock() - return textResult(fmt.Sprintf("Sandbox %q discarded — fork and all its changes deleted. Live content was never modified.", name)), nil, nil - default: - return textResult("action must be 'submit' or 'discard'"), nil, nil + return textResult(msg), nil, nil + } + + diff, err := s.client.GetForkDiff(ctx, forkID) + if err != nil { + return errorResult(err), nil, nil } + result, err := s.client.EndSandbox(ctx, "submit") + if err != nil { + return errorResult(err), nil, nil + } + return jsonResult(map[string]interface{}{ + "success": true, + "fork_id": forkID, + "name": name, + "changes": diff.Pages, + "review_url": "/cm/forks/" + forkID, + "restricted": result["restricted"], + "message": "Sandbox submitted. A person can review the changes and merge the fork from the admin UI.", + }), nil, nil }) // Fork diff (also useful outside sandbox sessions, e.g. for reviewers) diff --git a/internal/mcp/search_tools.go b/internal/mcp/search_tools.go index b9e397d..53f6988 100644 --- a/internal/mcp/search_tools.go +++ b/internal/mcp/search_tools.go @@ -124,9 +124,6 @@ For targeted replacements, use scoped_search_replace_execute instead.`, OpenWorldHint: boolPtr(false), }, }, func(ctx context.Context, req *mcp.CallToolRequest, args SearchReplaceExecuteInput) (*mcp.CallToolResult, any, error) { - if blocked := s.sandboxBlock("search_replace_execute"); blocked != nil { - return blocked, nil, nil - } if len(args.Pairs) > 0 { pairs := make([]map[string]interface{}, len(args.Pairs)) for i, p := range args.Pairs { diff --git a/internal/mcp/server.go b/internal/mcp/server.go index 6a16d0a..2992f9f 100644 --- a/internal/mcp/server.go +++ b/internal/mcp/server.go @@ -15,7 +15,6 @@ import ( type Server struct { mcpServer *mcp.Server client *apiclient.Client - sandbox sandboxState // localFiles lets upload_asset read file_path from this machine's disk. localFiles bool } diff --git a/internal/mcp/settings_tools.go b/internal/mcp/settings_tools.go index ddfc1a1..ef35f8f 100644 --- a/internal/mcp/settings_tools.go +++ b/internal/mcp/settings_tools.go @@ -737,9 +737,6 @@ Example: {"version": 5}`, OpenWorldHint: boolPtr(false), }, }, func(ctx context.Context, req *mcp.CallToolRequest, args struct{}) (*mcp.CallToolResult, any, error) { - if blocked := s.sandboxBlock("regenerate_all_content"); blocked != nil { - return blocked, nil, nil - } if err := s.client.RegenerateAllContent(ctx); err != nil { return errorResult(err), nil, nil } diff --git a/internal/models/models.go b/internal/models/models.go index 612c744..3bfd821 100644 --- a/internal/models/models.go +++ b/internal/models/models.go @@ -91,18 +91,22 @@ func (c *Content) ModifiedAt() time.Time { // ContentFork represents a named workspace for staging site changes before merging to live type ContentFork struct { - ID primitive.ObjectID `bson:"_id,omitempty" json:"id"` - Name string `bson:"name" json:"name"` - Description string `bson:"description" json:"description"` - Status string `bson:"status" json:"status"` // "active" | "merged" | "archived" - PreviewToken string `bson:"preview_token" json:"preview_token"` // random token for cookie-based preview - CreatedBy primitive.ObjectID `bson:"created_by" json:"created_by"` - CreatedByEmail string `bson:"created_by_email" json:"created_by_email"` - CreatedAt time.Time `bson:"created_at" json:"created_at"` - MergedAt *time.Time `bson:"merged_at,omitempty" json:"merged_at,omitempty"` - MergedBy *primitive.ObjectID `bson:"merged_by,omitempty" json:"merged_by,omitempty"` - MergedByEmail string `bson:"merged_by_email,omitempty" json:"merged_by_email,omitempty"` - ArchivedAt *time.Time `bson:"archived_at,omitempty" json:"archived_at,omitempty"` + ID primitive.ObjectID `bson:"_id,omitempty" json:"id"` + Name string `bson:"name" json:"name"` + Description string `bson:"description" json:"description"` + Status string `bson:"status" json:"status"` // "active" | "merged" | "archived" + PreviewToken string `bson:"preview_token" json:"preview_token"` // random token for cookie-based preview + CreatedBy primitive.ObjectID `bson:"created_by" json:"created_by"` + CreatedByEmail string `bson:"created_by_email" json:"created_by_email"` + // CreatedByCredential is the API key or OAuth connection that created the + // fork ("apikey:" / "oauth:"); empty for a person in the + // admin UI and for forks made before 7.5.0. + CreatedByCredential string `bson:"created_by_credential,omitempty" json:"created_by_credential,omitempty"` + CreatedAt time.Time `bson:"created_at" json:"created_at"` + MergedAt *time.Time `bson:"merged_at,omitempty" json:"merged_at,omitempty"` + MergedBy *primitive.ObjectID `bson:"merged_by,omitempty" json:"merged_by,omitempty"` + MergedByEmail string `bson:"merged_by_email,omitempty" json:"merged_by_email,omitempty"` + ArchivedAt *time.Time `bson:"archived_at,omitempty" json:"archived_at,omitempty"` // Page counts recorded at merge time (v7.4). The fork's page copies are // deleted after a successful merge, so these are the history of what it did. MergedCreated int `bson:"merged_created,omitempty" json:"merged_created,omitempty"` @@ -178,9 +182,14 @@ type APIKey struct { KeyHash string `bson:"key_hash" json:"-"` // SHA-256 hash of full key UserID *primitive.ObjectID `bson:"user_id,omitempty" json:"user_id,omitempty"` // Owning user Scopes []string `bson:"scopes,omitempty" json:"scopes,omitempty"` // Permission allowlist; empty = full owner permissions - SandboxOnly bool `bson:"sandbox_only,omitempty" json:"sandbox_only,omitempty"` // Content writes must target a fork; live mutations rejected - LastUsedAt *time.Time `bson:"last_used_at,omitempty" json:"last_used_at,omitempty"` - CreatedAt time.Time `bson:"created_at" json:"created_at"` + SandboxOnly bool `bson:"sandbox_only,omitempty" json:"sandbox_only,omitempty"` // Content writes must target a fork the key created; live mutations rejected + // CanMergeOwnForks lets the key merge forks it created into the live + // site. Only a signed-in admin can turn it on. + CanMergeOwnForks bool `bson:"can_merge_own_forks,omitempty" json:"can_merge_own_forks,omitempty"` + // ActiveSandboxFork is the fork the key's current sandbox writes to. + ActiveSandboxFork *primitive.ObjectID `bson:"active_sandbox_fork,omitempty" json:"active_sandbox_fork,omitempty"` + LastUsedAt *time.Time `bson:"last_used_at,omitempty" json:"last_used_at,omitempty"` + CreatedAt time.Time `bson:"created_at" json:"created_at"` } // Snippet is a named, reusable HTML fragment used as an item renderer in lc:query directives. diff --git a/internal/models/oauth.go b/internal/models/oauth.go index 90fd6f4..7d23f83 100644 --- a/internal/models/oauth.go +++ b/internal/models/oauth.go @@ -27,10 +27,18 @@ type OAuthGrant struct { ClientName string `bson:"client_name" json:"client_name"` // as registered, for display; chosen by the client UserID primitive.ObjectID `bson:"user_id" json:"user_id"` Resource string `bson:"resource" json:"resource"` - CreatedAt time.Time `bson:"created_at" json:"created_at"` - UpdatedAt time.Time `bson:"updated_at" json:"updated_at"` - LastUsedAt *time.Time `bson:"last_used_at,omitempty" json:"last_used_at,omitempty"` - RevokedAt *time.Time `bson:"revoked_at,omitempty" json:"revoked_at,omitempty"` + // SandboxOnly confines the connection to forks it created; nothing it + // does changes the live site unless CanMergeOwnForks lets it merge them. + SandboxOnly bool `bson:"sandbox_only" json:"sandbox_only"` + // CanMergeOwnForks lets the connection merge forks it created into the + // live site. Only a signed-in admin can turn it on. + CanMergeOwnForks bool `bson:"can_merge_own_forks" json:"can_merge_own_forks"` + // ActiveSandboxFork is the fork the connection's current sandbox writes to. + ActiveSandboxFork *primitive.ObjectID `bson:"active_sandbox_fork,omitempty" json:"active_sandbox_fork,omitempty"` + CreatedAt time.Time `bson:"created_at" json:"created_at"` + UpdatedAt time.Time `bson:"updated_at" json:"updated_at"` + LastUsedAt *time.Time `bson:"last_used_at,omitempty" json:"last_used_at,omitempty"` + RevokedAt *time.Time `bson:"revoked_at,omitempty" json:"revoked_at,omitempty"` } // OAuthAuthCode represents a pending authorization code diff --git a/internal/oauth/handler.go b/internal/oauth/handler.go index 8c9c9fb..84db819 100644 --- a/internal/oauth/handler.go +++ b/internal/oauth/handler.go @@ -251,6 +251,7 @@ func (h *Handler) AuthorizeSubmit(w http.ResponseWriter, r *http.Request) { templateData["UserEmail"] = user.Email templateData["UserRole"] = user.Role templateData["RoleSummary"] = roleSummary(user.Role) + templateData["CanGrantMerge"] = auth.HasPermission(user.Role, auth.PermForkMerge) templateData["LoginUser"] = userID templateData["LoginProof"] = h.computeLoginProof(userID, clientID, redirectURI, codeChallenge, resource, ts) templateData["LoginTS"] = ts @@ -277,7 +278,7 @@ func (h *Handler) AuthorizeSubmit(w http.ResponseWriter, r *http.Request) { return } - grant, err := h.oauthService.SaveGrant(r.Context(), client, user.ID, resource) + grant, err := h.oauthService.SaveGrant(r.Context(), client, user.ID, resource, consentAccess(r, user)) if err != nil { log.Printf("[OAuth] Failed to save grant: %v", err) redirectWithError(w, r, redirectURI, state, "server_error", "Failed to record the connection") @@ -439,6 +440,16 @@ func (h *Handler) approvingUser(r *http.Request, userID string) *models.User { return user } +// consentAccess reads the access chosen on the consent page. Anything but an +// explicit "full" is Sandbox. Merging its own forks is granted only by someone +// whose role can merge, which the person signing in here must be. +func consentAccess(r *http.Request, user *models.User) services.AccessSettings { + return services.AccessSettings{ + SandboxOnly: r.FormValue("access") != "full", + CanMergeOwnForks: r.FormValue("can_merge_own_forks") == "1" && auth.HasPermission(user.Role, auth.PermForkMerge), + } +} + // resolveResource returns the resource an authorization request is for. A // client that names none gets this server's MCP endpoint; naming anything else // is refused (RFC 8707). diff --git a/internal/oauth/handler_test.go b/internal/oauth/handler_test.go index 1c1e4d7..4e09648 100644 --- a/internal/oauth/handler_test.go +++ b/internal/oauth/handler_test.go @@ -64,7 +64,7 @@ const testResourceURL = "https://example.com/mcp" // testGrant records that a new person approved the client. func testGrant(t *testing.T, oauthSvc *services.OAuthService, client *models.OAuthClient) *models.OAuthGrant { t.Helper() - grant, err := oauthSvc.SaveGrant(context.Background(), client, primitive.NewObjectID(), testResourceURL) + grant, err := oauthSvc.SaveGrant(context.Background(), client, primitive.NewObjectID(), testResourceURL, services.AccessSettings{}) if err != nil { t.Fatalf("SaveGrant: %v", err) } diff --git a/internal/oauth/identity_test.go b/internal/oauth/identity_test.go index fb9f56b..02922a4 100644 --- a/internal/oauth/identity_test.go +++ b/internal/oauth/identity_test.go @@ -384,3 +384,74 @@ func TestConsent_ExpiredProofRefused(t *testing.T) { t.Fatal("approved with an expired proof") } } + +func approveWith(t *testing.T, handler *Handler, oauthSvc *services.OAuthService, users *services.UserService, role string, choices url.Values) *models.OAuthGrant { + t.Helper() + email := role + "-" + strconv.Itoa(int(time.Now().UnixNano()%1e9)) + "@example.com" + user := testAccount(t, users, email, role) + client, _, _ := oauthSvc.RegisterClient(context.Background(), "Some App", []string{"http://localhost/cb"}) + challenge := pkcePair("v") + page := signIn(t, handler, client, challenge, email) + + form := authorizeForm(client, challenge, "approve") + form.Set("resource", hiddenField(t, page, "resource")) + form.Set("login_user", hiddenField(t, page, "login_user")) + form.Set("login_proof", hiddenField(t, page, "login_proof")) + form.Set("login_ts", hiddenField(t, page, "login_ts")) + for k, v := range choices { + form[k] = v + } + if rr := postForm(handler.AuthorizeSubmit, "/oauth/authorize", form); rr.Code != http.StatusFound { + t.Fatalf("approve: %d %s", rr.Code, rr.Body.String()) + } + grants, err := oauthSvc.ListGrants(context.Background(), &user.ID) + if err != nil || len(grants) != 1 { + t.Fatalf("grants for %s: %v %v", email, grants, err) + } + return &grants[0] +} + +func TestConsent_AccessDefaultsToSandbox(t *testing.T) { + handler, oauthSvc, users, cleanup := newTestHandlerWithUsers(t) + defer cleanup() + + if grant := approveWith(t, handler, oauthSvc, users, models.RoleEditor, nil); !grant.SandboxOnly || grant.CanMergeOwnForks { + t.Errorf("no choice made: %+v", grant) + } + if grant := approveWith(t, handler, oauthSvc, users, models.RoleEditor, url.Values{"access": {"bogus"}}); !grant.SandboxOnly { + t.Errorf("unknown choice: %+v", grant) + } + if grant := approveWith(t, handler, oauthSvc, users, models.RoleEditor, url.Values{"access": {"full"}}); grant.SandboxOnly { + t.Errorf("Full chosen: %+v", grant) + } +} + +func TestConsent_OnlyARoleThatCanMergeCanGrantMerging(t *testing.T) { + handler, oauthSvc, users, cleanup := newTestHandlerWithUsers(t) + defer cleanup() + merge := url.Values{"can_merge_own_forks": {"1"}} + + if grant := approveWith(t, handler, oauthSvc, users, models.RoleEditor, merge); grant.CanMergeOwnForks { + t.Error("an editor granted merging") + } + if grant := approveWith(t, handler, oauthSvc, users, models.RoleAdmin, merge); !grant.CanMergeOwnForks || !grant.SandboxOnly { + t.Errorf("an admin granting merging on a sandbox connection: %+v", grant) + } +} + +func TestConsent_PageOffersMergeOnlyToAdmins(t *testing.T) { + handler, oauthSvc, users, cleanup := newTestHandlerWithUsers(t) + defer cleanup() + testAccount(t, users, "editor@example.com", models.RoleEditor) + testAccount(t, users, "admin@example.com", models.RoleAdmin) + client, _, _ := oauthSvc.RegisterClient(context.Background(), "Some App", []string{"http://localhost/cb"}) + + editorPage := signIn(t, handler, client, pkcePair("v"), "editor@example.com") + if !strings.Contains(editorPage, `value="sandbox" checked`) || strings.Contains(editorPage, "can_merge_own_forks") { + t.Error("the editor's consent page should default to Sandbox and offer no merge option") + } + adminPage := signIn(t, handler, client, pkcePair("v"), "admin@example.com") + if !strings.Contains(adminPage, "can_merge_own_forks") { + t.Error("an admin's consent page should offer the merge option") + } +} diff --git a/internal/oauth/templates.go b/internal/oauth/templates.go index b8fd0c3..fa87963 100644 --- a/internal/oauth/templates.go +++ b/internal/oauth/templates.go @@ -78,6 +78,29 @@ var oauthTemplates = map[string]string{ color: #94a3b8; font-size: 0.85rem; } + .access-choice { + border: 1px solid rgba(99, 102, 241, 0.2); + border-radius: 12px; + padding: 0.75rem 1rem; + margin-bottom: 0.5rem; + } + .access-choice legend { + color: #e2e8f0; + font-weight: 600; + padding: 0 0.25rem; + } + .access-choice .choice { + display: flex; + gap: 0.6rem; + align-items: flex-start; + color: #cbd5e1; + font-weight: 400; + font-size: 0.875rem; + line-height: 1.5; + margin: 0.5rem 0; + cursor: pointer; + } + .access-choice input { margin-top: 0.3rem; } label { display: block; color: #e2e8f0; @@ -179,7 +202,7 @@ var oauthTemplates = map[string]string{
@@ -194,6 +217,14 @@ var oauthTemplates = map[string]string{ +
+ Access + + + {{if .CanGrantMerge}} + + {{end}} +
diff --git a/internal/services/apikey.go b/internal/services/apikey.go index cb7b864..846b479 100644 --- a/internal/services/apikey.go +++ b/internal/services/apikey.go @@ -143,6 +143,39 @@ func (s *APIKeyService) deleteKey(ctx context.Context, filter bson.M) error { return nil } +// AccessSettings are what an API key or OAuth connection may do within its +// owner's role: confined to its own forks (SandboxOnly) or not, and whether +// it may merge the forks it created. +type AccessSettings struct { + SandboxOnly bool + CanMergeOwnForks bool +} + +// GetAPIKey returns a key by ID. +func (s *APIKeyService) GetAPIKey(ctx context.Context, id primitive.ObjectID) (*models.APIKey, error) { + var key models.APIKey + if err := s.db.FindOne(ctx, "api_keys", bson.M{"_id": id}, &key); err != nil { + return nil, ErrAPIKeyNotFound + } + return &key, nil +} + +// UpdateAccess changes a key's access settings. +func (s *APIKeyService) UpdateAccess(ctx context.Context, id primitive.ObjectID, settings AccessSettings) error { + return s.db.UpdateOne(ctx, "api_keys", bson.M{"_id": id}, bson.M{"$set": bson.M{ + "sandbox_only": settings.SandboxOnly, + "can_merge_own_forks": settings.CanMergeOwnForks, + }}) +} + +// SetActiveSandbox records the fork a key's sandbox writes to (nil: none). +func (s *APIKeyService) SetActiveSandbox(ctx context.Context, id primitive.ObjectID, fork *primitive.ObjectID) error { + if fork == nil { + return s.db.UpdateOne(ctx, "api_keys", bson.M{"_id": id}, bson.M{"$unset": bson.M{"active_sandbox_fork": ""}}) + } + return s.db.UpdateOne(ctx, "api_keys", bson.M{"_id": id}, bson.M{"$set": bson.M{"active_sandbox_fork": *fork}}) +} + // AssignOwner gives a key with no owner on record to a user. It never changes // the owner of a key that already has one. func (s *APIKeyService) AssignOwner(ctx context.Context, id, ownerID primitive.ObjectID) error { diff --git a/internal/services/asset.go b/internal/services/asset.go index 861f266..dc2dd3e 100644 --- a/internal/services/asset.go +++ b/internal/services/asset.go @@ -177,6 +177,20 @@ func (s *AssetService) GetAsset(ctx context.Context, id primitive.ObjectID) (*da return asset, nil } +// AssetExistsAt reports whether an asset is already stored at the serve path an +// upload names, after the same normalisation UploadAsset applies. +func (s *AssetService) AssetExistsAt(ctx context.Context, servePath string) (bool, error) { + p := filepath.Clean("/" + strings.TrimPrefix(servePath, "/")) + if strings.HasPrefix(p, "/assets/") { + p = strings.TrimPrefix(p, "/assets") + } + asset, err := s.db.GetAssetByPath(ctx, p) + if err != nil { + return false, err + } + return asset != nil, nil +} + // GetAssetByPath retrieves an asset by serve path func (s *AssetService) GetAssetByPath(ctx context.Context, path string) (*database.Asset, error) { return s.db.GetAssetByPath(ctx, path) diff --git a/internal/services/fork.go b/internal/services/fork.go index 180dc19..d359654 100644 --- a/internal/services/fork.go +++ b/internal/services/fork.go @@ -6,6 +6,7 @@ import ( "encoding/hex" "encoding/json" "fmt" + "log" "sort" "time" @@ -72,6 +73,12 @@ func generatePreviewToken() (string, error) { // Create creates a new fork workspace. func (s *ForkService) Create(ctx context.Context, name, description string, userID primitive.ObjectID, userEmail string) (*models.ContentFork, error) { + return s.CreateWithCredential(ctx, name, description, userID, userEmail, "") +} + +// CreateWithCredential creates a fork and records the API key or OAuth +// connection that made it, which a sandboxed caller needs to write to it. +func (s *ForkService) CreateWithCredential(ctx context.Context, name, description string, userID primitive.ObjectID, userEmail, credential string) (*models.ContentFork, error) { token, err := generatePreviewToken() if err != nil { return nil, fmt.Errorf("generate preview token: %w", err) @@ -86,6 +93,8 @@ func (s *ForkService) Create(ctx context.Context, name, description string, user CreatedBy: userID, CreatedByEmail: userEmail, CreatedAt: now, + + CreatedByCredential: credential, } if _, err := s.db.InsertOne(ctx, "content_forks", fork); err != nil { return nil, fmt.Errorf("insert fork: %w", err) @@ -340,6 +349,7 @@ func (s *ForkService) Merge(ctx context.Context, forkID primitive.ObjectID, merg }}); err != nil { return nil, fmt.Errorf("mark fork merged: %w", err) } + s.releaseSandboxes(ctx, forkID) // The copies have served their purpose: left behind they would only be // stale duplicates of live pages. A failure here does not undo the merge — @@ -371,10 +381,28 @@ func (s *ForkService) publishMerged(ctx context.Context, page *models.Content) s // Archive marks a fork as archived without merging. func (s *ForkService) Archive(ctx context.Context, forkID primitive.ObjectID) error { now := time.Now() - return s.db.UpdateOne(ctx, "content_forks", bson.M{"_id": forkID, "status": "active"}, bson.M{"$set": bson.M{ + if err := s.db.UpdateOne(ctx, "content_forks", bson.M{"_id": forkID, "status": "active"}, bson.M{"$set": bson.M{ "status": "archived", "archived_at": now, - }}) + }}); err != nil { + return err + } + s.releaseSandboxes(ctx, forkID) + return nil +} + +// releaseSandboxes ends any API key's or connection's sandbox that writes to +// a fork which is no longer open for work, so the credential is not left +// confined to it. Failures are logged: GET /api/v1/sandbox clears a stale +// sandbox too. +func (s *ForkService) releaseSandboxes(ctx context.Context, forkID primitive.ObjectID) { + for _, collection := range []string{"api_keys", "oauth_grants"} { + if _, err := s.db.Collection(collection).UpdateMany(ctx, + bson.M{"active_sandbox_fork": forkID}, + bson.M{"$unset": bson.M{"active_sandbox_fork": ""}}); err != nil { + log.Printf("Warning: failed to end sandboxes on fork %s in %s: %v", forkID.Hex(), collection, err) + } + } } // Delete permanently deletes a fork and all its pages. For a merged fork this @@ -392,6 +420,7 @@ func (s *ForkService) Delete(ctx context.Context, forkID primitive.ObjectID) err if _, err := s.db.Collection("content_forks").DeleteOne(ctx, bson.M{"_id": forkID}); err != nil { return fmt.Errorf("delete fork: %w", err) } + s.releaseSandboxes(ctx, forkID) return nil } diff --git a/internal/services/oauth.go b/internal/services/oauth.go index 3927e84..5df6da2 100644 --- a/internal/services/oauth.go +++ b/internal/services/oauth.go @@ -187,16 +187,23 @@ func (s *OAuthService) ValidateClientCredentials(ctx context.Context, clientID, return &client, nil } -// SaveGrant records that a person approved a client, and returns the grant. -// One person has one active grant per client: approving again reuses it. -func (s *OAuthService) SaveGrant(ctx context.Context, client *models.OAuthClient, userID primitive.ObjectID, resource string) (*models.OAuthGrant, error) { +// SaveGrant records that a person approved a client with the given access, +// and returns the grant. One person has one active grant per client: +// approving again reuses it with the access chosen this time. +func (s *OAuthService) SaveGrant(ctx context.Context, client *models.OAuthClient, userID primitive.ObjectID, resource string, access AccessSettings) (*models.OAuthGrant, error) { now := time.Now() var grant models.OAuthGrant save := func() error { return s.db.Collection("oauth_grants").FindOneAndUpdate(ctx, bson.M{"client_id": client.ClientID, "user_id": userID, "revoked_at": nil}, bson.M{ - "$set": bson.M{"client_name": client.ClientName, "resource": resource, "updated_at": now}, + "$set": bson.M{ + "client_name": client.ClientName, + "resource": resource, + "sandbox_only": access.SandboxOnly, + "can_merge_own_forks": access.CanMergeOwnForks, + "updated_at": now, + }, "$setOnInsert": bson.M{"created_at": now}, }, options.FindOneAndUpdate().SetUpsert(true).SetReturnDocument(options.After), @@ -222,6 +229,42 @@ func (s *OAuthService) GetGrant(ctx context.Context, id primitive.ObjectID) (*mo return &grant, nil } +// ListGrants returns the active connections, newest first: one person's when +// userID is set, everyone's otherwise. +func (s *OAuthService) ListGrants(ctx context.Context, userID *primitive.ObjectID) ([]models.OAuthGrant, error) { + filter := bson.M{"revoked_at": nil} + if userID != nil { + filter["user_id"] = *userID + } + cursor, err := s.db.FindMany(ctx, "oauth_grants", filter, options.Find().SetSort(bson.D{{Key: "created_at", Value: -1}})) + if err != nil { + return nil, fmt.Errorf("failed to list connections: %w", err) + } + defer cursor.Close(ctx) + grants := []models.OAuthGrant{} + if err := cursor.All(ctx, &grants); err != nil { + return nil, fmt.Errorf("failed to decode connections: %w", err) + } + return grants, nil +} + +// UpdateGrantAccess changes an active connection's access settings. +func (s *OAuthService) UpdateGrantAccess(ctx context.Context, id primitive.ObjectID, access AccessSettings) error { + return s.db.UpdateOne(ctx, "oauth_grants", bson.M{"_id": id, "revoked_at": nil}, bson.M{"$set": bson.M{ + "sandbox_only": access.SandboxOnly, + "can_merge_own_forks": access.CanMergeOwnForks, + "updated_at": time.Now(), + }}) +} + +// SetActiveSandbox records the fork a connection's sandbox writes to (nil: none). +func (s *OAuthService) SetActiveSandbox(ctx context.Context, id primitive.ObjectID, fork *primitive.ObjectID) error { + if fork == nil { + return s.db.UpdateOne(ctx, "oauth_grants", bson.M{"_id": id}, bson.M{"$unset": bson.M{"active_sandbox_fork": ""}}) + } + return s.db.UpdateOne(ctx, "oauth_grants", bson.M{"_id": id}, bson.M{"$set": bson.M{"active_sandbox_fork": *fork}}) +} + // activeGrant returns a grant that has not been revoked. func (s *OAuthService) activeGrant(ctx context.Context, id primitive.ObjectID) (*models.OAuthGrant, error) { if id.IsZero() { diff --git a/internal/services/oauth_grant_test.go b/internal/services/oauth_grant_test.go index be5060d..7116c8a 100644 --- a/internal/services/oauth_grant_test.go +++ b/internal/services/oauth_grant_test.go @@ -68,11 +68,11 @@ func TestSaveGrant_OneActiveGrantPerPersonAndClient(t *testing.T) { ctx := context.Background() user := primitive.NewObjectID() - first, err := f.svc.SaveGrant(ctx, f.client, user, testResource) + first, err := f.svc.SaveGrant(ctx, f.client, user, testResource, AccessSettings{}) if err != nil { t.Fatalf("SaveGrant: %v", err) } - again, err := f.svc.SaveGrant(ctx, f.client, user, testResource) + again, err := f.svc.SaveGrant(ctx, f.client, user, testResource, AccessSettings{}) if err != nil { t.Fatalf("SaveGrant again: %v", err) } @@ -80,7 +80,7 @@ func TestSaveGrant_OneActiveGrantPerPersonAndClient(t *testing.T) { t.Error("approving the same client again should reuse the grant") } - other, err := f.svc.SaveGrant(ctx, f.client, primitive.NewObjectID(), testResource) + other, err := f.svc.SaveGrant(ctx, f.client, primitive.NewObjectID(), testResource, AccessSettings{}) if err != nil { t.Fatalf("SaveGrant other: %v", err) } @@ -91,7 +91,7 @@ func TestSaveGrant_OneActiveGrantPerPersonAndClient(t *testing.T) { if err := f.svc.RevokeGrant(ctx, first.ID); err != nil { t.Fatalf("RevokeGrant: %v", err) } - after, err := f.svc.SaveGrant(ctx, f.client, user, testResource) + after, err := f.svc.SaveGrant(ctx, f.client, user, testResource, AccessSettings{}) if err != nil { t.Fatalf("SaveGrant after revoke: %v", err) } @@ -114,7 +114,7 @@ func TestSaveGrant_ConcurrentApprovalsMakeOneGrant(t *testing.T) { wg.Add(1) go func() { defer wg.Done() - grant, err := f.svc.SaveGrant(ctx, f.client, user, testResource) + grant, err := f.svc.SaveGrant(ctx, f.client, user, testResource, AccessSettings{}) if err != nil { t.Errorf("SaveGrant: %v", err) return @@ -141,7 +141,7 @@ func TestSaveGrant_ConcurrentApprovalsMakeOneGrant(t *testing.T) { t.Fatalf("RevokeGrant: %v", err) } } - if _, err := f.svc.SaveGrant(ctx, f.client, user, testResource); err != nil { + if _, err := f.svc.SaveGrant(ctx, f.client, user, testResource, AccessSettings{}); err != nil { t.Errorf("reconnecting after a revoke: %v", err) } } diff --git a/internal/services/oauth_test.go b/internal/services/oauth_test.go index c8e737a..4c93673 100644 --- a/internal/services/oauth_test.go +++ b/internal/services/oauth_test.go @@ -19,7 +19,7 @@ const testResource = "https://example.com/mcp" // testGrant records that a new person approved the client. func testGrant(t *testing.T, svc *OAuthService, client *models.OAuthClient) *models.OAuthGrant { t.Helper() - grant, err := svc.SaveGrant(context.Background(), client, primitive.NewObjectID(), testResource) + grant, err := svc.SaveGrant(context.Background(), client, primitive.NewObjectID(), testResource, AccessSettings{}) if err != nil { t.Fatalf("SaveGrant: %v", err) } From 19e84ac62130178f3c421323b4db3c2ada82b47d Mon Sep 17 00:00:00 2001 From: "Jon Radoff (Metavert)" Date: Mon, 9 Nov 2026 21:55:03 -0500 Subject: [PATCH 2/2] Close the review's findings on the server-side sandbox - A database error while reading a sandbox no longer closes it: only a fork that is gone, merged or archived does. Other errors answer 503. - Starting a sandbox is an atomic claim; of two racing starts one wins and the other's fork is removed. - The no-replace check for sandboxed uploads also finds assets recorded with the old /assets prefix and files that exist only on disk. - A sandboxed caller comments only on pages in its own forks: comments notify people and go out through webhooks. - A Full key or connection refused because it has a sandbox open is told so, and how to end it. - MCP writes stop when the sandbox can't be read instead of going to the live page; a server without sandboxes (before 7.5) still works. Co-Authored-By: Claude Opus 5.5 --- internal/apiclient/client.go | 12 +++- internal/handlers/api.go | 2 +- internal/handlers/api_comments.go | 13 ++++ internal/handlers/api_sandbox.go | 98 +++++++++++++++++++++----- internal/handlers/api_sandbox_test.go | 89 +++++++++++++++++++++++ internal/mcp/content_tools.go | 27 +++---- internal/mcp/sandbox_test.go | 38 ++++++++-- internal/mcp/sandbox_tools.go | 39 +++++++--- internal/services/apikey.go | 12 ++++ internal/services/asset.go | 24 +++++-- internal/services/asset_exists_test.go | 44 ++++++++++++ internal/services/oauth.go | 12 ++++ 12 files changed, 353 insertions(+), 57 deletions(-) create mode 100644 internal/services/asset_exists_test.go diff --git a/internal/apiclient/client.go b/internal/apiclient/client.go index 8607c0f..6d2816c 100644 --- a/internal/apiclient/client.go +++ b/internal/apiclient/client.go @@ -15,6 +15,14 @@ import ( "time" ) +// APIError is an error response from the REST API. +type APIError struct { + Status int + Message string +} + +func (e *APIError) Error() string { return e.Message } + // Client is an HTTP client for the LightCMS REST API type Client struct { baseURL string @@ -103,9 +111,9 @@ func (c *Client) do(ctx context.Context, method, path string, body interface{}, Error string `json:"error"` } if json.Unmarshal(respBody, &errResp) == nil && errResp.Error != "" { - return fmt.Errorf("%s", errResp.Error) + return &APIError{Status: resp.StatusCode, Message: errResp.Error} } - return fmt.Errorf("API error (status %d): %s", resp.StatusCode, string(respBody)) + return &APIError{Status: resp.StatusCode, Message: fmt.Sprintf("API error (status %d): %s", resp.StatusCode, string(respBody))} } if result != nil { diff --git a/internal/handlers/api.go b/internal/handlers/api.go index b6c2d49..59d29b2 100644 --- a/internal/handlers/api.go +++ b/internal/handlers/api.go @@ -94,7 +94,7 @@ func (a *APIHandler) requirePermission(w http.ResponseWriter, r *http.Request, p if !auth.UserHasPermission(user, perm) { msg := "insufficient permissions" if user.Sandboxed() && auth.HasPermission(user.Role, perm) { - msg = sandboxRefusal + msg = sandboxRefusalFor(user) } a.jsonError(w, http.StatusForbidden, msg) return false diff --git a/internal/handlers/api_comments.go b/internal/handlers/api_comments.go index e066402..ab7737f 100644 --- a/internal/handlers/api_comments.go +++ b/internal/handlers/api_comments.go @@ -54,6 +54,19 @@ func (a *APIHandler) APICreateComment(w http.ResponseWriter, r *http.Request) { return } + // A sandboxed caller comments only on pages in its own forks: comments + // notify people and go out through webhooks. + if a.getAPIUser(r).Sandboxed() { + content, err := a.contentService.GetContent(r.Context(), id) + if err != nil { + a.jsonError(w, http.StatusNotFound, "content not found") + return + } + if !a.callerMayWriteContent(w, r, content) { + return + } + } + user := a.getAPIUser(r) var ( userID primitive.ObjectID diff --git a/internal/handlers/api_sandbox.go b/internal/handlers/api_sandbox.go index af0f64b..c0e0404 100644 --- a/internal/handlers/api_sandbox.go +++ b/internal/handlers/api_sandbox.go @@ -2,6 +2,7 @@ package handlers import ( "context" + "errors" "fmt" "net/http" "path/filepath" @@ -13,6 +14,7 @@ import ( "github.com/gorilla/mux" "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo" ) // sandboxWriteRoutes are the only /api/v1 routes that change state which a @@ -27,7 +29,7 @@ var sandboxWriteRoutes = map[string]string{ "PUT /api/v1/content/by-path": "edits a page copy in a fork the caller created", "POST /api/v1/content/{id}/preview": "renders a page without saving anything", "POST /api/v1/content/export": "reads content without changing it", - "POST /api/v1/content/{id}/comments": "adds a comment for reviewers; comments are not shown on the site", + "POST /api/v1/content/{id}/comments": "comments on a page copy in a fork the caller created (APICreateComment)", "POST /api/v1/assets": "uploads a new image, PDF, font or text file; never replaces one, never HTML, JS, CSS or SVG", "POST /api/v1/assets/from-url": "the same, fetched from a URL", "POST /api/v1/forks": "creates a fork owned by the caller", @@ -41,6 +43,16 @@ var sandboxWriteRoutes = map[string]string{ // sandboxRefusal is the error a sandboxed caller gets for anything outside its forks. const sandboxRefusal = "this connection is limited to its own forks. Start a sandbox (start_agent_sandbox, or POST /api/v1/sandbox) and make the change there for a person to review and merge" +// sandboxRefusalFor explains a refusal to the caller: a Full key or connection +// is held to its forks only while it has a sandbox open, and is told how to +// end it. +func sandboxRefusalFor(user *auth.SessionUser) string { + if user != nil && !user.SandboxOnly && user.ActiveSandboxFork != "" { + return "this connection has a sandbox open (fork " + user.ActiveSandboxFork + "), so it is limited to its own forks until the sandbox ends. Finish the work there, or end it with end_agent_sandbox (POST /api/v1/sandbox/end) to change the live site" + } + return sandboxRefusal +} + // SandboxGate refuses every state-changing request from a sandboxed caller // except the routes in sandboxWriteRoutes, whichever tool or client sent it. // The handlers behind those routes then hold the caller to its own forks. @@ -57,7 +69,7 @@ func SandboxGate(next http.Handler) http.Handler { template, _ = route.GetPathTemplate() } if _, ok := sandboxWriteRoutes[r.Method+" "+template]; !ok { - writeJSONError(w, http.StatusForbidden, sandboxRefusal) + writeJSONError(w, http.StatusForbidden, sandboxRefusalFor(user)) return } next.ServeHTTP(w, r) @@ -95,7 +107,7 @@ func (a *APIHandler) callerMayWriteContent(w http.ResponseWriter, r *http.Reques return true } if content.ForkID == nil { - a.jsonError(w, http.StatusForbidden, sandboxRefusal) + a.jsonError(w, http.StatusForbidden, sandboxRefusalFor(user)) return false } fork, err := a.forkService.GetByID(r.Context(), *content.ForkID) @@ -163,23 +175,54 @@ func (a *APIHandler) setActiveSandbox(ctx context.Context, user *auth.SessionUse return fmt.Errorf("unrecognised credential %q", user.Credential) } -// activeSandbox returns the caller's open sandbox fork, or nil. A sandbox -// whose fork has since been merged, archived or deleted is closed here. -func (a *APIHandler) activeSandbox(ctx context.Context, user *auth.SessionUser) *models.ContentFork { +// claimSandbox records fork as the caller's sandbox only if none is open, and +// reports whether it did: of two requests racing to start a sandbox, one wins. +func (a *APIHandler) claimSandbox(ctx context.Context, user *auth.SessionUser, fork primitive.ObjectID) (bool, error) { + kind, hexID, _ := strings.Cut(user.Credential, ":") + id, err := primitive.ObjectIDFromHex(hexID) + if err != nil { + return false, fmt.Errorf("unrecognised credential %q", user.Credential) + } + switch kind { + case "apikey": + return a.apiKeyService.ClaimSandbox(ctx, id, fork) + case "oauth": + if a.oauthService == nil { + return false, fmt.Errorf("OAuth service unavailable") + } + return a.oauthService.ClaimSandbox(ctx, id, fork) + } + return false, fmt.Errorf("unrecognised credential %q", user.Credential) +} + +// activeSandbox returns the caller's open sandbox fork, or nil when none is +// open. A sandbox whose fork was deleted, or merged or archived, is closed +// here. Any other error is returned and the sandbox is left as it is: a +// passing database error must not lift it. +func (a *APIHandler) activeSandbox(ctx context.Context, user *auth.SessionUser) (*models.ContentFork, error) { if user.ActiveSandboxFork == "" { - return nil + return nil, nil } - id, err := primitive.ObjectIDFromHex(user.ActiveSandboxFork) - if err == nil { - if fork, err := a.forkService.GetByID(ctx, id); err == nil && fork.Status == "active" { - return fork + if id, err := primitive.ObjectIDFromHex(user.ActiveSandboxFork); err == nil { + fork, err := a.forkService.GetByID(ctx, id) + if err == nil && fork.Status == "active" { + return fork, nil + } + if err != nil && !errors.Is(err, mongo.ErrNoDocuments) { + return nil, fmt.Errorf("reading the sandbox fork: %w", err) } } if err := a.setActiveSandbox(ctx, user, nil); err != nil { - fmt.Printf("Warning: failed to close a stale sandbox for %s: %v\n", user.Credential, err) + return nil, fmt.Errorf("closing a finished sandbox: %w", err) } user.ActiveSandboxFork = "" - return nil + return nil, nil +} + +// sandboxUnavailable answers when the sandbox state can't be read. +func (a *APIHandler) sandboxUnavailable(w http.ResponseWriter, err error) { + fmt.Printf("Warning: sandbox state unavailable: %v\n", err) + a.jsonError(w, http.StatusServiceUnavailable, "the sandbox state could not be read; try again") } func sandboxResponse(user *auth.SessionUser, fork *models.ContentFork) map[string]interface{} { @@ -205,7 +248,12 @@ func (a *APIHandler) APIGetSandbox(w http.ResponseWriter, r *http.Request) { return } user := a.getAPIUser(r) - a.jsonResponse(w, http.StatusOK, sandboxResponse(user, a.activeSandbox(r.Context(), user))) + fork, err := a.activeSandbox(r.Context(), user) + if err != nil { + a.sandboxUnavailable(w, err) + return + } + a.jsonResponse(w, http.StatusOK, sandboxResponse(user, fork)) } // APIStartSandbox opens a sandbox: a new fork owned by the caller's key or @@ -230,7 +278,12 @@ func (a *APIHandler) APIStartSandbox(w http.ResponseWriter, r *http.Request) { return } } - if open := a.activeSandbox(r.Context(), user); open != nil { + open, err := a.activeSandbox(r.Context(), user) + if err != nil { + a.sandboxUnavailable(w, err) + return + } + if open != nil { a.jsonResponse(w, http.StatusConflict, map[string]interface{}{ "error": fmt.Sprintf("a sandbox (%q) is already open; end it first", open.Name), "fork_id": open.ID.Hex(), @@ -250,9 +303,14 @@ func (a *APIHandler) APIStartSandbox(w http.ResponseWriter, r *http.Request) { a.jsonError(w, http.StatusInternalServerError, err.Error()) return } - if err := a.setActiveSandbox(r.Context(), user, &fork.ID); err != nil { + claimed, err := a.claimSandbox(r.Context(), user, fork.ID) + if err != nil || !claimed { _ = a.forkService.Delete(r.Context(), fork.ID) - a.jsonError(w, http.StatusInternalServerError, "could not open the sandbox: "+err.Error()) + if err != nil { + a.jsonError(w, http.StatusInternalServerError, "could not open the sandbox: "+err.Error()) + } else { + a.jsonError(w, http.StatusConflict, "another sandbox was opened at the same time; end it first") + } return } user.ActiveSandboxFork = fork.ID.Hex() @@ -276,7 +334,11 @@ func (a *APIHandler) APIEndSandbox(w http.ResponseWriter, r *http.Request) { a.jsonError(w, http.StatusBadRequest, `action must be "submit" or "discard"`) return } - fork := a.activeSandbox(r.Context(), user) + fork, err := a.activeSandbox(r.Context(), user) + if err != nil { + a.sandboxUnavailable(w, err) + return + } if fork == nil { a.jsonError(w, http.StatusConflict, "no sandbox is open") return diff --git a/internal/handlers/api_sandbox_test.go b/internal/handlers/api_sandbox_test.go index 238b6d9..c417e1f 100644 --- a/internal/handlers/api_sandbox_test.go +++ b/internal/handlers/api_sandbox_test.go @@ -10,6 +10,7 @@ import ( "net/url" "sort" "strings" + "sync" "testing" "github.com/metavert-io/lightcms/v7/internal/auth" @@ -662,3 +663,91 @@ func TestAPIKeys_NewKeysAreSandboxAndAccessCanBeChanged(t *testing.T) { } } } + +func TestSandbox_ADatabaseErrorDoesNotEndTheSandbox(t *testing.T) { + a, db := newFaultAPIHandler(t) + ctx := context.Background() + users := services.NewUserService(db) + owner, err := users.CreateUserWithHash(ctx, "editor@example.com", "Editor", models.RoleEditor, "unused", false) + if err != nil { + t.Fatalf("CreateUserWithHash: %v", err) + } + keys := services.NewAPIKeyService(db) + raw, _, _ := keys.CreateScopedAPIKey(ctx, "Full", "", &owner.ID, nil, false) + resolver := auth.NewCredentialResolver(users, keys, services.NewOAuthService(db), "https://example.com/mcp", nil) + router := mux.NewRouter() + a.MountAPI(router, middleware.NewAPIAuth(resolver.ResolveAPIKey)) + tmpl := seedTemplate(t, db, "Page", "page") + live := seedContent(t, db, tmpl, "Live", "live", "/live") + + if rr := sendJSON(router, raw, "POST", "/api/v1/sandbox", `{}`); rr.Code != http.StatusCreated { + t.Fatalf("start: %d %s", rr.Code, rr.Body.String()) + } + db.SetFaultHook(func(op, collection string) error { + if collection == "content_forks" { + return fmt.Errorf("injected outage") + } + return nil + }) + if rr := sendJSON(router, raw, "GET", "/api/v1/sandbox", ``); rr.Code != http.StatusServiceUnavailable { + t.Errorf("reading the sandbox during an outage: %d %s", rr.Code, rr.Body.String()) + } + db.SetFaultHook(nil) + + if state := decode(t, sendJSON(router, raw, "GET", "/api/v1/sandbox", ``)); state["active"] != true { + t.Errorf("the outage ended the sandbox: %+v", state) + } + if rr := sendJSON(router, raw, "PUT", "/api/v1/content/"+live.Hex(), `{"title":"Live change"}`); rr.Code != http.StatusForbidden || !strings.Contains(rr.Body.String(), "has a sandbox open") { + t.Errorf("live edit with the sandbox still open: %d %s", rr.Code, rr.Body.String()) + } +} + +func TestSandbox_RacingStartsOpenOneSandbox(t *testing.T) { + e := newSandboxEnv(t) + key := e.key(t, "Agent", true) + + codes := make(chan int, 8) + var wg sync.WaitGroup + for i := 0; i < 8; i++ { + wg.Add(1) + go func() { + defer wg.Done() + codes <- e.send(key, "POST", "/api/v1/sandbox", `{}`).Code + }() + } + wg.Wait() + close(codes) + created := 0 + for code := range codes { + if code == http.StatusCreated { + created++ + } else if code != http.StatusConflict { + t.Errorf("unexpected status %d", code) + } + } + if created != 1 { + t.Errorf("%d sandboxes opened, want 1", created) + } + if n, _ := e.db.Count(context.Background(), "content_forks", bson.M{"status": "active"}); n != 1 { + t.Errorf("%d active forks left behind, want 1", n) + } +} + +func TestSandbox_CommentsOnlyOnPagesInItsOwnFork(t *testing.T) { + e := newSandboxEnv(t) + key := e.key(t, "Agent", true) + comment := `{"text":"Looks good"}` + + if rr := e.send(key, "POST", "/api/v1/content/"+e.live.Hex()+"/comments", comment); rr.Code != http.StatusForbidden { + t.Errorf("comment on a live page: %d %s", rr.Code, rr.Body.String()) + } + fork := e.startSandbox(t, key) + rr := e.send(key, "POST", "/api/v1/forks/"+fork+"/fork-page", `{"path":"/live"}`) + if rr.Code != http.StatusOK { + t.Fatalf("fork-page: %d %s", rr.Code, rr.Body.String()) + } + copyID := decode(t, rr)["id"].(string) + if rr := e.send(key, "POST", "/api/v1/content/"+copyID+"/comments", comment); rr.Code != http.StatusCreated { + t.Errorf("comment on its own copy: %d %s", rr.Code, rr.Body.String()) + } +} diff --git a/internal/mcp/content_tools.go b/internal/mcp/content_tools.go index e6217b2..1ab6c62 100644 --- a/internal/mcp/content_tools.go +++ b/internal/mcp/content_tools.go @@ -391,7 +391,11 @@ Templates can use {{.lc_toc}} in their HTML layout to inject an auto-generated t } // Sandbox: create the page inside the sandbox fork instead of live. - if forkID, _, active := s.sandboxFork(ctx); active { + forkID, _, active, err := s.sandboxFork(ctx) + if err != nil { + return errorResult(err), nil, nil + } + if active { if args.Upsert { return textResult("upsert is not available while an agent sandbox is active — use update_content so the change stays in the sandbox fork"), nil, nil } @@ -501,13 +505,9 @@ Templates can use {{.lc_toc}} in their HTML layout to inject an auto-generated t } // Sandbox: redirect the write to the fork copy (copy-on-write). - targetID := args.ID - if _, _, active := s.sandboxFork(ctx); active { - tid, err := s.sandboxTargetForContent(ctx, args.ID) - if err != nil { - return errorResult(err), nil, nil - } - targetID = tid + targetID, err := s.sandboxTargetForContent(ctx, args.ID) + if err != nil { + return errorResult(err), nil, nil } // For data fields, merge with existing content data @@ -791,13 +791,9 @@ Only the fields you provide are changed. Always include a version_comment descri }, }, func(ctx context.Context, req *mcp.CallToolRequest, args UpdateContentByPathInput) (*mcp.CallToolResult, any, error) { // Sandbox: copy-on-write the page into the fork and update the copy. - sandboxID := "" - if _, _, active := s.sandboxFork(ctx); active { - tid, err := s.sandboxTargetForPath(ctx, args.Path) - if err != nil { - return errorResult(err), nil, nil - } - sandboxID = tid + sandboxID, err := s.sandboxTargetForPath(ctx, args.Path) + if err != nil { + return errorResult(err), nil, nil } updates := map[string]interface{}{} @@ -856,7 +852,6 @@ Only the fields you provide are changed. Always include a version_comment descri updates["version_comment"] = args.VersionComment } var content *apiclient.Content - var err error if sandboxID != "" { content, err = s.client.UpdateContent(ctx, sandboxID, updates) } else { diff --git a/internal/mcp/sandbox_test.go b/internal/mcp/sandbox_test.go index f4e24a4..ab7192d 100644 --- a/internal/mcp/sandbox_test.go +++ b/internal/mcp/sandbox_test.go @@ -16,6 +16,7 @@ import ( // server does: on the credential, outside any MCP session. type sandboxAPI struct { mu sync.Mutex + stateStatus int // when set, GET /api/v1/sandbox answers with this status active bool // a sandbox is open restricted bool // the credential is set to Sandbox access forkCreated bool @@ -48,6 +49,11 @@ func sandboxMux(state *sandboxAPI) *http.ServeMux { mux.HandleFunc("GET /api/v1/sandbox", func(w http.ResponseWriter, r *http.Request) { state.mu.Lock() defer state.mu.Unlock() + if state.stateStatus != 0 { + w.WriteHeader(state.stateStatus) + json.NewEncoder(w).Encode(map[string]string{"error": "unavailable"}) + return + } json.NewEncoder(w).Encode(state.sandboxJSON()) }) mux.HandleFunc("POST /api/v1/sandbox", func(w http.ResponseWriter, r *http.Request) { @@ -190,7 +196,7 @@ func TestSandbox_Lifecycle(t *testing.T) { if !state.forkCreated { t.Fatal("fork was not created") } - if _, _, active := s.sandboxFork(context.Background()); !active { + if _, _, active, _ := s.sandboxFork(context.Background()); !active { t.Fatal("sandbox not active after start") } @@ -212,7 +218,7 @@ func TestSandbox_Lifecycle(t *testing.T) { if !strings.Contains(txt, "/cm/forks/fork1") { t.Errorf("submit should include review URL: %s", txt) } - if _, _, active := s.sandboxFork(context.Background()); active { + if _, _, active, _ := s.sandboxFork(context.Background()); active { t.Fatal("sandbox still active after submit") } } @@ -228,7 +234,7 @@ func TestSandbox_ContinuesInANewSession(t *testing.T) { callTool(t, first, "start_agent_sandbox", map[string]string{}) second := NewServer(apiclient.New(ts.URL, "test-key")) - if _, _, active := second.sandboxFork(context.Background()); !active { + if _, _, active, _ := second.sandboxFork(context.Background()); !active { t.Fatal("a new session does not see the open sandbox") } callTool(t, second, "update_content", map[string]interface{}{"id": "live1", "title": "From the new session"}) @@ -343,7 +349,7 @@ func TestSandbox_DiscardDeletesFork(t *testing.T) { if !state.forkDeleted { t.Error("fork was not deleted on discard") } - if _, _, active := s.sandboxFork(context.Background()); active { + if _, _, active, _ := s.sandboxFork(context.Background()); active { t.Error("sandbox still active after discard") } } @@ -411,3 +417,27 @@ func TestGovernanceAndMaintenanceTools(t *testing.T) { t.Errorf("rollback missing session message: %s", out) } } + +// If the sandbox can't be read, a write stops instead of going to the live +// page. A server with no sandbox endpoint (before 7.5) has no sandbox. +func TestSandbox_AFailedCheckStopsTheWrite(t *testing.T) { + s, state, cleanup := newSandboxServer(t) + defer cleanup() + + state.stateStatus = http.StatusServiceUnavailable + res := callTool(t, s, "update_content", map[string]interface{}{"id": "live1", "title": "X"}) + if !res.IsError || !strings.Contains(resultText(t, res), "could not check") { + t.Errorf("update with the sandbox unreadable: %s", resultText(t, res)) + } + state.mu.Lock() + writes := state.updates["live1"] + state.mu.Unlock() + if writes != 0 { + t.Error("the write went ahead") + } + + state.stateStatus = http.StatusNotFound + if res := callTool(t, s, "update_content", map[string]interface{}{"id": "live1", "title": "X"}); res.IsError { + t.Errorf("against a server without sandboxes: %s", resultText(t, res)) + } +} diff --git a/internal/mcp/sandbox_tools.go b/internal/mcp/sandbox_tools.go index c868083..b49cbec 100644 --- a/internal/mcp/sandbox_tools.go +++ b/internal/mcp/sandbox_tools.go @@ -3,28 +3,43 @@ package mcp import ( "context" "encoding/json" + "errors" "fmt" + "net/http" + + "github.com/metavert-io/lightcms/v7/internal/apiclient" "github.com/modelcontextprotocol/go-sdk/mcp" ) // sandboxFork returns the caller's open sandbox, which the server keeps on the // API key or OAuth connection: the same in every MCP session, and kept across -// restarts. When it cannot be read, writes are not redirected; the server -// still refuses anything a sandboxed caller may not do. -func (s *Server) sandboxFork(ctx context.Context) (id, name string, active bool) { +// restarts. When the server can't say, it returns an error and the write +// should stop: guessing "no sandbox" would send it to the live page. A server +// without the sandbox endpoint (before 7.5) has no server-side sandbox. +func (s *Server) sandboxFork(ctx context.Context) (id, name string, active bool, err error) { state, err := s.client.GetSandbox(ctx) - if err != nil || state == nil || !state.Active { - return "", "", false + if err != nil { + var apiErr *apiclient.APIError + if errors.As(err, &apiErr) && apiErr.Status == http.StatusNotFound { + return "", "", false, nil + } + return "", "", false, fmt.Errorf("could not check this connection's sandbox, so nothing was changed: %w", err) } - return state.ForkID, state.Name, true + if !state.Active { + return "", "", false, nil + } + return state.ForkID, state.Name, true, nil } // sandboxTargetForContent resolves which content ID an update should hit // while a sandbox is active: fork copies pass through, live pages get a // copy-on-write fork copy, and pages from other forks are rejected. func (s *Server) sandboxTargetForContent(ctx context.Context, contentID string) (string, error) { - forkID, _, active := s.sandboxFork(ctx) + forkID, _, active, err := s.sandboxFork(ctx) + if err != nil { + return "", err + } if !active { return contentID, nil } @@ -50,7 +65,10 @@ func (s *Server) sandboxTargetForContent(ctx context.Context, contentID string) // It returns the ID of the sandbox copy for the page at path ("" when no // sandbox is active, meaning: use the normal by-path flow). func (s *Server) sandboxTargetForPath(ctx context.Context, path string) (string, error) { - forkID, _, active := s.sandboxFork(ctx) + forkID, _, active, err := s.sandboxFork(ctx) + if err != nil { + return "", err + } if !active { return "", nil } @@ -157,7 +175,10 @@ A key or connection set to Sandbox access is always limited to forks it created; if args.Action != "submit" && args.Action != "discard" { return textResult("action must be 'submit' or 'discard'"), nil, nil } - forkID, name, active := s.sandboxFork(ctx) + forkID, name, active, err := s.sandboxFork(ctx) + if err != nil { + return errorResult(err), nil, nil + } if !active { return textResult("No agent sandbox is active."), nil, nil } diff --git a/internal/services/apikey.go b/internal/services/apikey.go index 846b479..ef5cecf 100644 --- a/internal/services/apikey.go +++ b/internal/services/apikey.go @@ -176,6 +176,18 @@ func (s *APIKeyService) SetActiveSandbox(ctx context.Context, id primitive.Objec return s.db.UpdateOne(ctx, "api_keys", bson.M{"_id": id}, bson.M{"$set": bson.M{"active_sandbox_fork": *fork}}) } +// ClaimSandbox records fork as the key's sandbox only if none is open, and +// reports whether it did. +func (s *APIKeyService) ClaimSandbox(ctx context.Context, id, fork primitive.ObjectID) (bool, error) { + result, err := s.db.Collection("api_keys").UpdateOne(ctx, + bson.M{"_id": id, "active_sandbox_fork": nil}, + bson.M{"$set": bson.M{"active_sandbox_fork": fork}}) + if err != nil { + return false, err + } + return result.ModifiedCount == 1, nil +} + // AssignOwner gives a key with no owner on record to a user. It never changes // the owner of a key that already has one. func (s *APIKeyService) AssignOwner(ctx context.Context, id, ownerID primitive.ObjectID) error { diff --git a/internal/services/asset.go b/internal/services/asset.go index dc2dd3e..4879000 100644 --- a/internal/services/asset.go +++ b/internal/services/asset.go @@ -177,18 +177,28 @@ func (s *AssetService) GetAsset(ctx context.Context, id primitive.ObjectID) (*da return asset, nil } -// AssetExistsAt reports whether an asset is already stored at the serve path an -// upload names, after the same normalisation UploadAsset applies. +// AssetExistsAt reports whether the site already serves something at the serve +// path an upload names, after the same normalisation UploadAsset applies: an +// asset recorded with or without the /assets prefix (older uploads kept it), +// or a file under content/generated at either location ServeAsset tries. func (s *AssetService) AssetExistsAt(ctx context.Context, servePath string) (bool, error) { p := filepath.Clean("/" + strings.TrimPrefix(servePath, "/")) if strings.HasPrefix(p, "/assets/") { p = strings.TrimPrefix(p, "/assets") } - asset, err := s.db.GetAssetByPath(ctx, p) - if err != nil { - return false, err - } - return asset != nil, nil + for _, candidate := range []string{p, "/assets" + p} { + asset, err := s.db.GetAssetByPath(ctx, candidate) + if err != nil { + return false, err + } + if asset != nil { + return true, nil + } + if info, err := os.Stat(filepath.Join("content/generated", candidate)); err == nil && !info.IsDir() { + return true, nil + } + } + return false, nil } // GetAssetByPath retrieves an asset by serve path diff --git a/internal/services/asset_exists_test.go b/internal/services/asset_exists_test.go new file mode 100644 index 0000000..39a5e14 --- /dev/null +++ b/internal/services/asset_exists_test.go @@ -0,0 +1,44 @@ +package services + +import ( + "context" + "os" + "path/filepath" + "testing" + "time" + + "github.com/metavert-io/lightcms/v7/internal/database" + "github.com/metavert-io/lightcms/v7/internal/testutil" +) + +func TestAssetExistsAt_SeesEveryWayTheSiteServesAFile(t *testing.T) { + db, cleanup := testutil.MustConnectTestDB(t) + defer cleanup() + t.Chdir(t.TempDir()) + ctx := context.Background() + assets := NewAssetService(db) + + // A file on disk with no record. + if err := os.MkdirAll(filepath.Join("content", "generated", "images"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join("content", "generated", "images", "logo.png"), []byte("x"), 0o644); err != nil { + t.Fatal(err) + } + // A record from before uploads dropped the /assets prefix. + if err := db.SaveAsset(ctx, &database.Asset{Filename: "old.png", FullPath: "/assets/old.png", ServePath: "/assets/old.png", CreatedAt: time.Now(), UpdatedAt: time.Now()}); err != nil { + t.Fatalf("SaveAsset: %v", err) + } + + for path, want := range map[string]bool{ + "/images/logo.png": true, + "/assets/images/logo.png": true, + "/assets/old.png": true, + "/assets/new.png": false, + } { + got, err := assets.AssetExistsAt(ctx, path) + if err != nil || got != want { + t.Errorf("AssetExistsAt(%q) = %v, %v; want %v", path, got, err, want) + } + } +} diff --git a/internal/services/oauth.go b/internal/services/oauth.go index 5df6da2..43185a2 100644 --- a/internal/services/oauth.go +++ b/internal/services/oauth.go @@ -265,6 +265,18 @@ func (s *OAuthService) SetActiveSandbox(ctx context.Context, id primitive.Object return s.db.UpdateOne(ctx, "oauth_grants", bson.M{"_id": id}, bson.M{"$set": bson.M{"active_sandbox_fork": *fork}}) } +// ClaimSandbox records fork as the connection's sandbox only if none is open, +// and reports whether it did. +func (s *OAuthService) ClaimSandbox(ctx context.Context, id, fork primitive.ObjectID) (bool, error) { + result, err := s.db.Collection("oauth_grants").UpdateOne(ctx, + bson.M{"_id": id, "revoked_at": nil, "active_sandbox_fork": nil}, + bson.M{"$set": bson.M{"active_sandbox_fork": fork}}) + if err != nil { + return false, err + } + return result.ModifiedCount == 1, nil +} + // activeGrant returns a grant that has not been revoked. func (s *OAuthService) activeGrant(ctx context.Context, id primitive.ObjectID) (*models.OAuthGrant, error) { if id.IsZero() {