Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions cmd/server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down
52 changes: 50 additions & 2 deletions internal/apiclient/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -1022,6 +1030,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{}
Expand Down
38 changes: 26 additions & 12 deletions internal/auth/credentials.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
}

Expand All @@ -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,
Expand Down
42 changes: 41 additions & 1 deletion internal/auth/credentials_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down Expand Up @@ -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)
}
}
26 changes: 20 additions & 6 deletions internal/auth/permissions.go
Original file line number Diff line number Diff line change
Expand Up @@ -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:<id>" or "oauth:<grant id>"
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,
Expand All @@ -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 {
Expand Down
8 changes: 8 additions & 0 deletions internal/handlers/admin_routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
8 changes: 8 additions & 0 deletions internal/handlers/admin_routes_guard_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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(`\{[^}]+\}`)
Expand Down Expand Up @@ -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",
Expand Down
Loading