fix: access-revoked event on ban and password changes, banned users lose their link, token-specific MCP revoke
- AccessRevokedEvent and FireAccessRevoked: fired in the write's transaction
by the ban action (newly banned users only), the password reset, an
administrator setting a password and the self-service password change;
a revoked subject event per user after commit
- LinkedBackendUser answers no administrator for a banned user
- FireSubjectEvent / FireSubjectEventAfterCommit carry TokenID or ClientID;
DELETE /tokens/{id} ends only that token's MCP sessions
- the MCP personal-token path stamps last_used_ip from towel.ClientIP
- BackendLinksFor replaces the duplicate lookups; requestUsable uses
IsUsableAt
This commit is contained in:
57
classes/access_revoked.go
Normal file
57
classes/access_revoked.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// Reasons FireAccessRevoked is called with by this plugin.
|
||||
const (
|
||||
AccessRevokedBan = "ban"
|
||||
AccessRevokedPasswordReset = "password_reset"
|
||||
AccessRevokedPasswordSetByAdmin = "password_set_by_admin"
|
||||
AccessRevokedPasswordChanged = "password_changed"
|
||||
)
|
||||
|
||||
// FireAccessRevoked tells the application that userIDs lost every
|
||||
// credential issued before before (reason names why: a ban, a password reset
|
||||
// or change). It fires *AccessRevokedEvent in tx at once, so a listener
|
||||
// error is returned and the caller's transaction rolls back, and then one
|
||||
// "revoked" *pact.MCPSubjectChanged per user once tx commits, so MCP
|
||||
// sessions of those users end on every instance. A nil app or bus, or an
|
||||
// empty id list, does nothing. A nil tx fires the subject events at once.
|
||||
//
|
||||
// The plugin calls it from the ban action, the password reset, an
|
||||
// administrator setting a password and the self-service password change.
|
||||
// RevokeUserAccess, BanUsers and DeactivateUsers do not fire it: an
|
||||
// application that calls RevokeUserAccess or BanUsers directly calls
|
||||
// FireAccessRevoked too, in the same transaction.
|
||||
func FireAccessRevoked(ctx context.Context, app *backpack.App, tx *gorm.DB, userIDs []uint, before time.Time, reason string) error {
|
||||
if app == nil || app.Events == nil || len(userIDs) == 0 {
|
||||
return nil
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
ids := make([]uint, 0, len(userIDs))
|
||||
for _, id := range userIDs {
|
||||
if id != 0 {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil
|
||||
}
|
||||
if err := app.Events.Fire(ctx, &AccessRevokedEvent{UserIDs: ids, Before: before, Reason: reason, Tx: tx}); err != nil {
|
||||
return fmt.Errorf("%s: %w", AccessRevokedEventName, err)
|
||||
}
|
||||
for _, id := range ids {
|
||||
FireSubjectChangedAfterCommit(ctx, app, tx, SubjectGuardUser, id, pact.MCPSubjectRevoked)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -52,6 +52,17 @@ type BackendLinks struct {
|
||||
App *backpack.App
|
||||
}
|
||||
|
||||
// BackendLinksFor returns the link service Boot published on app, or one
|
||||
// over app when none is published.
|
||||
func BackendLinksFor(app *backpack.App) *BackendLinks {
|
||||
if app != nil {
|
||||
if links, ok := app.Lookup[*BackendLinks](); ok && links != nil {
|
||||
return links
|
||||
}
|
||||
}
|
||||
return &BackendLinks{App: app}
|
||||
}
|
||||
|
||||
// BackendLinkRequestTTL reads golem15.user.backend_links.request_ttl, a Go
|
||||
// duration (10m by default). A value that does not parse or is not positive
|
||||
// is an error, so a typo fails the boot instead of silently changing the
|
||||
@@ -211,14 +222,16 @@ func (s *BackendLinks) LinkRequestByCode(ctx context.Context, plain string) (*mo
|
||||
return req, admin, nil
|
||||
}
|
||||
|
||||
// requestUsable answers why a request cannot be used (used or expired), or
|
||||
// nil when req.IsUsableAt(now).
|
||||
func requestUsable(req *models.BackendLinkRequest, now time.Time) error {
|
||||
if req.IsUsableAt(now) {
|
||||
return nil
|
||||
}
|
||||
if req.UsedAt != nil {
|
||||
return ErrLinkRequestUsed
|
||||
}
|
||||
if !req.ExpiresAt.After(now) {
|
||||
return ErrLinkRequestExpired
|
||||
}
|
||||
return nil
|
||||
return ErrLinkRequestExpired
|
||||
}
|
||||
|
||||
// ConfirmLinkRequest stores the link between the signed-in frontend user and
|
||||
@@ -313,7 +326,9 @@ func (s *BackendLinks) SetLink(ctx context.Context, tx *gorm.DB, frontendUserID,
|
||||
|
||||
// insertLink writes one link in tx after checking both sides are free; a
|
||||
// concurrent writer that wins the unique index also ends in
|
||||
// ErrAlreadyLinked.
|
||||
// ErrAlreadyLinked. It is the one write path of a link (ConfirmLinkRequest
|
||||
// and SetLink), so BackendLinkedEvent, with Link.UserID set, fires on every
|
||||
// link; RemoveLink is the one removal path and fires BackendUnlinkedEvent.
|
||||
func (s *BackendLinks) insertLink(ctx context.Context, tx *gorm.DB, frontendUserID, backendUserID uint, linkedBy *uint) (*models.BackendLink, error) {
|
||||
var taken int64
|
||||
if err := fresh(ctx, tx).Model(&models.BackendLink{}).
|
||||
@@ -343,7 +358,8 @@ func (s *BackendLinks) insertLink(ctx context.Context, tx *gorm.DB, frontendUser
|
||||
return link, nil
|
||||
}
|
||||
|
||||
// RemoveLink deletes link in tx, fires BackendUnlinkedEvent there and the
|
||||
// RemoveLink deletes link in tx, fires BackendUnlinkedEvent (Link.UserID
|
||||
// set) there and the
|
||||
// two pact.MCPSubjectChanged link events after tx commits. A link that is
|
||||
// already gone is not an error and fires nothing.
|
||||
func (s *BackendLinks) RemoveLink(ctx context.Context, tx *gorm.DB, link *models.BackendLink) error {
|
||||
@@ -402,7 +418,8 @@ func (s *BackendLinks) linkWhere(ctx context.Context, where string, id uint) (*m
|
||||
// LinkedBackendUser implements pact.MCPLinkedBackendResolver with one
|
||||
// indexed query per call (no cache): the administrator linked to the
|
||||
// frontend user, false when there is no link, when the frontend user is
|
||||
// deactivated, or when the administrator is deactivated or deleted.
|
||||
// deactivated or banned (user_throttle.is_banned on any of their rows), or
|
||||
// when the administrator is deactivated or deleted.
|
||||
func (s *BackendLinks) LinkedBackendUser(ctx context.Context, frontendUserID uint) (pact.LinkedBackendUser, bool, error) {
|
||||
if frontendUserID == 0 {
|
||||
return pact.LinkedBackendUser{}, false, nil
|
||||
@@ -422,6 +439,7 @@ FROM golem15_user_backend_links l
|
||||
JOIN backend_users b ON b.id = l.backend_user_id
|
||||
JOIN users u ON u.id = l.user_id
|
||||
WHERE l.user_id = ? AND b.deleted_at IS NULL AND b.is_activated = TRUE AND u.deleted_at IS NULL
|
||||
AND NOT EXISTS (SELECT 1 FROM user_throttle t WHERE t.user_id = l.user_id AND t.is_banned)
|
||||
LIMIT 1`, frontendUserID).Scan(&rows).Error
|
||||
if err != nil {
|
||||
return pact.LinkedBackendUser{}, false, err
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
package classes
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"git.golem15.com/golem15/sm-user-plugin/models"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -20,6 +22,9 @@ const BackendLinkedEventName = "user.BackendLinked"
|
||||
// BackendUnlinkedEventName is the festival name of BackendUnlinkedEvent.
|
||||
const BackendUnlinkedEventName = "user.BackendUnlinked"
|
||||
|
||||
// AccessRevokedEventName is the festival name of AccessRevokedEvent.
|
||||
const AccessRevokedEventName = "user.AccessRevoked"
|
||||
|
||||
// GetApiArrayEvent is the fire-and-collect payload other plugins extend.
|
||||
type GetApiArrayEvent struct {
|
||||
User *models.User
|
||||
@@ -90,3 +95,19 @@ type BackendUnlinkedEvent struct {
|
||||
Link *models.BackendLink
|
||||
Tx *gorm.DB
|
||||
}
|
||||
|
||||
// AccessRevokedEvent fires inside the write transaction when users lose
|
||||
// every credential issued before Before: a ban, a password reset, a password
|
||||
// an administrator set, or the user's own password change (FireAccessRevoked;
|
||||
// Reason names which). Listeners revoke what such a credential still holds
|
||||
// elsewhere, for example OAuth access and refresh tokens created before
|
||||
// Before. Before is the untruncated instant of the revocation, while the
|
||||
// users' tokens_valid_after keeps its whole-second value. A listener error
|
||||
// rolls the write back. Deactivation and deletion keep their own events
|
||||
// (DeactivatingEvent, DeletingEvent).
|
||||
type AccessRevokedEvent struct {
|
||||
UserIDs []uint
|
||||
Before time.Time
|
||||
Reason string
|
||||
Tx *gorm.DB
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"git.golem15.com/golem15/summercms/modules/cabana"
|
||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||
"git.golem15.com/golem15/summercms/modules/pact"
|
||||
"git.golem15.com/golem15/summercms/modules/towel"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -139,7 +140,9 @@ func (g *MCPUserGuard) MCPDispatch(ctx context.Context, subject pact.MCPSubject,
|
||||
// an MCP subject with the token's own scopes. A token without the configured
|
||||
// prefix answers false; one with it that is unknown, revoked, expired or
|
||||
// whose user is gone answers pact.ErrMCPTokenInvalid. A usable token gets
|
||||
// its last_used_at stamped, as the api_token guard does.
|
||||
// its last_used_at stamped, and its last_used_ip when the context carries
|
||||
// the client address (towel.ClientIP, which the MCP endpoint sets), as the
|
||||
// api_token guard does.
|
||||
func (g *MCPUserGuard) MCPResolvePersonalToken(ctx context.Context, raw string) (pact.MCPSubject, bool, error) {
|
||||
prefix, err := APITokenPrefix(g.app())
|
||||
if err != nil || !strings.HasPrefix(raw, prefix) {
|
||||
@@ -166,7 +169,11 @@ func (g *MCPUserGuard) MCPResolvePersonalToken(ctx context.Context, raw string)
|
||||
if principal == nil {
|
||||
return pact.MCPSubject{}, true, pact.ErrMCPTokenInvalid
|
||||
}
|
||||
if err := db.Model(&models.APIToken{}).Where("id = ?", token.ID).UpdateColumn("last_used_at", now).Error; err != nil {
|
||||
used := map[string]any{"last_used_at": now}
|
||||
if ip, ok := towel.ClientIP(ctx); ok && strings.TrimSpace(ip) != "" {
|
||||
used["last_used_ip"] = strings.TrimSpace(ip)
|
||||
}
|
||||
if err := db.Model(&models.APIToken{}).Where("id = ?", token.ID).UpdateColumns(used).Error; err != nil {
|
||||
return pact.MCPSubject{}, true, err
|
||||
}
|
||||
return pact.MCPSubject{Guard: SubjectGuardUser, UserID: token.UserID, Scopes: slices.Clone(token.Scopes.Get()), TokenID: token.ID}, true, nil
|
||||
|
||||
@@ -17,39 +17,53 @@ const (
|
||||
SubjectGuardBackend = "backend"
|
||||
)
|
||||
|
||||
// FireSubjectChanged fires one *pact.MCPSubjectChanged (guard, user id,
|
||||
// kind) through the application's event bus at once, so the MCP endpoint
|
||||
// re-lists the subject's tools or ends its sessions. A missing application
|
||||
// or bus, or a zero id, is a no-op; a listener's error is logged and never
|
||||
// returned, so the write that caused the event never fails because of it
|
||||
// (every MCP request re-checks anyway).
|
||||
func FireSubjectChanged(ctx context.Context, app *backpack.App, guard string, userID uint, kind string) {
|
||||
if app == nil || app.Events == nil || userID == 0 || kind == "" {
|
||||
// FireSubjectEvent fires ev through the application's event bus at once, so
|
||||
// the MCP endpoint re-lists the subject's tools or ends its sessions. A
|
||||
// revoked event may carry TokenID (only the sessions one personal token
|
||||
// opened end) or ClientID with UserID (only that OAuth client's sessions
|
||||
// end). A missing application or bus, a zero UserID or an empty Kind is a
|
||||
// no-op; a listener's error is logged and never returned, so the write that
|
||||
// caused the event never fails because of it (every MCP request re-checks
|
||||
// anyway).
|
||||
func FireSubjectEvent(ctx context.Context, app *backpack.App, ev pact.MCPSubjectChanged) {
|
||||
if app == nil || app.Events == nil || ev.UserID == 0 || ev.Kind == "" {
|
||||
return
|
||||
}
|
||||
if ctx == nil {
|
||||
ctx = context.Background()
|
||||
}
|
||||
event := &pact.MCPSubjectChanged{Guard: guard, UserID: userID, Kind: kind}
|
||||
if err := app.Events.Fire(ctx, event); err != nil {
|
||||
pluginLog.WarnContext(ctx, "golem15.user: subject changed listener failed", "guard", guard, "user_id", userID, "kind", kind, "err", err)
|
||||
event := ev
|
||||
if err := app.Events.Fire(ctx, &event); err != nil {
|
||||
pluginLog.WarnContext(ctx, "golem15.user: subject changed listener failed", "guard", ev.Guard, "user_id", ev.UserID, "kind", ev.Kind, "token_id", ev.TokenID, "client_id", ev.ClientID, "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
// FireSubjectChangedAfterCommit is FireSubjectChanged once the write
|
||||
// FireSubjectEventAfterCommit is FireSubjectEvent once the write
|
||||
// transaction tx commits (lagoon.AfterCommit), so a listener that reads the
|
||||
// database sees the change; nothing is fired when the transaction rolls
|
||||
// back. A nil tx fires at once. ctx must be the context the transaction
|
||||
// runs under (the one cabana hands a hook or an action).
|
||||
func FireSubjectChangedAfterCommit(ctx context.Context, app *backpack.App, tx *gorm.DB, guard string, userID uint, kind string) {
|
||||
if app == nil || app.Events == nil || userID == 0 || kind == "" {
|
||||
func FireSubjectEventAfterCommit(ctx context.Context, app *backpack.App, tx *gorm.DB, ev pact.MCPSubjectChanged) {
|
||||
if app == nil || app.Events == nil || ev.UserID == 0 || ev.Kind == "" {
|
||||
return
|
||||
}
|
||||
if tx == nil {
|
||||
FireSubjectChanged(ctx, app, guard, userID, kind)
|
||||
FireSubjectEvent(ctx, app, ev)
|
||||
return
|
||||
}
|
||||
lagoon.AfterCommit(ctx, tx, func(ctx context.Context, _ *gorm.DB) {
|
||||
FireSubjectChanged(ctx, app, guard, userID, kind)
|
||||
FireSubjectEvent(ctx, app, ev)
|
||||
})
|
||||
}
|
||||
|
||||
// FireSubjectChanged fires one *pact.MCPSubjectChanged (guard, user id,
|
||||
// kind) at once: FireSubjectEvent for the whole subject.
|
||||
func FireSubjectChanged(ctx context.Context, app *backpack.App, guard string, userID uint, kind string) {
|
||||
FireSubjectEvent(ctx, app, pact.MCPSubjectChanged{Guard: guard, UserID: userID, Kind: kind})
|
||||
}
|
||||
|
||||
// FireSubjectChangedAfterCommit is FireSubjectChanged once the write
|
||||
// transaction tx commits: FireSubjectEventAfterCommit for the whole subject.
|
||||
func FireSubjectChangedAfterCommit(ctx context.Context, app *backpack.App, tx *gorm.DB, guard string, userID uint, kind string) {
|
||||
FireSubjectEventAfterCommit(ctx, app, tx, pact.MCPSubjectChanged{Guard: guard, UserID: userID, Kind: kind})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user