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
9 changes: 2 additions & 7 deletions cmd/mcp/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,10 @@ package main

import (
"context"
"crypto/rand"
"encoding/hex"
"fmt"
"log"
"os"
"strings"
"time"

"github.com/metavert-io/lightcms/v7/internal/apiclient"
"github.com/metavert-io/lightcms/v7/internal/mcp"
Expand Down Expand Up @@ -37,14 +34,12 @@ func main() {
// Every MCP session gets a unique agent-session ID. The server groups
// this session's changes in the audit log so humans can review or roll
// them back as a unit.
sessionBytes := make([]byte, 8)
if _, err := rand.Read(sessionBytes); err == nil {
client.SetAgentSession("agent-" + time.Now().UTC().Format("20060102-150405") + "-" + hex.EncodeToString(sessionBytes))
}
client.SetAgentSession(apiclient.NewAgentSessionID())

// Create and run MCP server
ctx := context.Background()
server := mcp.NewServer(client)
server.AllowLocalFiles()
if err := server.Run(ctx); err != nil {
log.Printf("MCP server error: %v", err)
os.Exit(1)
Expand Down
305 changes: 19 additions & 286 deletions cmd/server/main.go

Large diffs are not rendered by default.

26 changes: 25 additions & 1 deletion internal/apiclient/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package apiclient
import (
"bytes"
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"io"
Expand All @@ -28,6 +30,14 @@ func (c *Client) SetAgentSession(id string) { c.agentSession = id }
// AgentSession returns the session ID configured via SetAgentSession.
func (c *Client) AgentSession() string { return c.agentSession }

// NewAgentSessionID returns a new ID for an agent session. The server groups a
// session's changes under it so they can be reviewed or rolled back as a unit.
func NewAgentSessionID() string {
b := make([]byte, 8)
_, _ = rand.Read(b) // never fails: crypto/rand aborts the process instead
return "agent-" + time.Now().UTC().Format("20060102-150405") + "-" + hex.EncodeToString(b)
}

// New creates a new API client
func New(baseURL, apiKey string) *Client {
return &Client{
Expand All @@ -39,6 +49,18 @@ func New(baseURL, apiKey string) *Client {
}
}

// NewWithTransport creates a client that carries no key and sends its requests
// through transport, which is responsible for saying who the caller is.
func NewWithTransport(baseURL string, transport http.RoundTripper) *Client {
return &Client{
baseURL: baseURL,
httpClient: &http.Client{
Timeout: 60 * time.Second,
Transport: transport,
},
}
}

// do executes an HTTP request with auth and JSON handling
func (c *Client) do(ctx context.Context, method, path string, body interface{}, result interface{}) error {
var bodyReader io.Reader
Expand All @@ -55,7 +77,9 @@ func (c *Client) do(ctx context.Context, method, path string, body interface{},
return fmt.Errorf("failed to create request: %w", err)
}

req.Header.Set("Authorization", "Bearer "+c.apiKey)
if c.apiKey != "" {
req.Header.Set("Authorization", "Bearer "+c.apiKey)
}
if c.agentSession != "" {
req.Header.Set("X-Agent-Session", c.agentSession)
}
Expand Down
1 change: 0 additions & 1 deletion internal/apiclient/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,6 @@ type UploadAssetRequest struct {
Filename string `json:"filename"`
ServePath string `json:"serve_path"`
DataBase64 string `json:"data_base64,omitempty"`
FilePath string `json:"file_path,omitempty"`
Description string `json:"description,omitempty"`
}

Expand Down
5 changes: 5 additions & 0 deletions internal/auth/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,11 @@ func (m *Manager) ValidateCredentials(ctx context.Context, email, password strin
return m.userService.ValidateCredentials(ctx, email, password)
}

// GetUserByID returns a user account, or nil if there is none.
func (m *Manager) GetUserByID(ctx context.Context, id primitive.ObjectID) (*models.User, error) {
return m.userService.GetByID(ctx, id)
}

// ChangePassword updates a user's password via the user service
func (m *Manager) ChangePassword(ctx context.Context, userID primitive.ObjectID, currentPassword, newPassword string) error {
if err := ValidatePasswordStrength(newPassword); err != nil {
Expand Down
117 changes: 117 additions & 0 deletions internal/auth/credentials.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
package auth

import (
"context"
"fmt"
"log"

"github.com/metavert-io/lightcms/v7/internal/models"
"github.com/metavert-io/lightcms/v7/internal/services"
)

// CredentialResolver turns an API key or OAuth access token into the person it
// acts for. It runs on every request, so a change of role, a disabled account
// or a revoked connection takes effect at once, and any doubt about who is
// behind a credential refuses the request.
type CredentialResolver struct {
users *services.UserService
apiKeys *services.APIKeyService
oauth *services.OAuthService
resource string
onActivity func(userID string)
}

// NewCredentialResolver creates a resolver. resource is the identifier OAuth
// tokens must have been issued for. onActivity, if set, is called with each
// authenticated user's ID.
func NewCredentialResolver(users *services.UserService, apiKeys *services.APIKeyService, oauth *services.OAuthService, resource string, onActivity func(userID string)) *CredentialResolver {
return &CredentialResolver{users: users, apiKeys: apiKeys, oauth: oauth, resource: resource, onActivity: onActivity}
}

// ResolveAPIKey implements middleware.APIKeyValidateFunc.
func (c *CredentialResolver) ResolveAPIKey(ctx context.Context, rawKey string) (interface{}, error) {
key, err := c.apiKeys.ValidateAPIKey(ctx, rawKey)
if err != nil {
return nil, err
}
owner, err := c.keyOwner(ctx, key)
if err != nil {
return nil, err
}
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,
}, nil
}

// ResolveOAuthToken implements middleware.OAuthValidateFunc.
func (c *CredentialResolver) ResolveOAuthToken(ctx context.Context, rawToken string) (interface{}, error) {
grant, err := c.oauth.ValidateAccessToken(ctx, rawToken, c.resource)
if err != nil {
return nil, err
}
user, err := c.users.GetByID(ctx, grant.UserID)
if err != nil {
return nil, fmt.Errorf("loading connection owner: %w", err)
}
if user == nil || user.Disabled {
return nil, fmt.Errorf("connection owner is missing or disabled")
}
c.recordActivity(user)
return &SessionUser{
ID: user.ID.Hex(),
Email: user.Email,
Role: user.Role,
ViaOAuth: true,
Credential: "oauth:" + grant.ID.Hex(),
}, nil
}

// 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,
// whatever the reason: a passing database error must not change who it acts as.
func (c *CredentialResolver) keyOwner(ctx context.Context, key *models.APIKey) (*models.User, error) {
if key.UserID == nil {
return c.adoptOwnerlessKey(ctx, key)
}
owner, err := c.users.GetByID(ctx, *key.UserID)
if err != nil {
return nil, fmt.Errorf("loading API key owner: %w", err)
}
if owner == nil || owner.Disabled {
return nil, fmt.Errorf("API key owner is missing or disabled")
}
return owner, nil
}

func (c *CredentialResolver) adoptOwnerlessKey(ctx context.Context, key *models.APIKey) (*models.User, error) {
users, err := c.users.ListUsers(ctx)
if err != nil {
return nil, fmt.Errorf("listing users for an unowned API key: %w", err)
}
for i := range users {
admin := &users[i]
if admin.Role != models.RoleAdmin || admin.Disabled {
continue
}
if err := c.apiKeys.AssignOwner(ctx, key.ID, admin.ID); err != nil {
return nil, err
}
log.Printf("[security] API key %q had no owner; assigned to admin %s", key.Name, admin.Email)
return admin, nil
}
return nil, fmt.Errorf("API key has no owner and no admin is available to take it")
}

func (c *CredentialResolver) recordActivity(user *models.User) {
if c.onActivity != nil {
c.onActivity(user.ID.Hex())
}
}
Loading
Loading