Files
OpenFlare/backend/plugins/domain/user/plugin.go
T
Ryan 53ae3007d0 fix(cordis): fail-closed auth guards for user/message_gateway/admin (#1)
* autoresearch iter 23: fail-closed auth guarding for user/message_gateway

Both plugins resolve contracts.AuthService in Apply to build their route
middleware, but declared only DBService in Inject(). The kernel gates a
plugin's Apply solely on declared deps, and cmd/app.go registers user
before auth, so user mounted first, core.Inject failed, and loginMW
silently degraded to a pass-through closure — leaving /api/v1/user
change-password, profile and access-tokens unguarded. message_gateway
was saved only by its later list position.

Declare AuthService in Inject() for both, and pin the property with a
reconcile-level test that mirrors production registration order and
asserts the real auth middleware reaches the route table.

* autoresearch iter 24: make auth middleware fallbacks fail closed

user, message_gateway and admin each fell back to a c.Next() closure when
contracts.AuthService could not be resolved, so a route would be served as
if authenticated. For admin this is reachable at runtime: OnDispose calls
service.ResetServices(), which nils the global the per-request guard reads,
so requests still in flight during dispose bypass authorization entirely.

Add ginutil.AuthUnavailable() and bind every fallback to it, with a test
that drives each plugin's registered guard without an auth service present
and asserts the request is aborted rather than passed through.

* chore(autoresearch): log iter 23 (fail-open auth ordering, proven)

* autoresearch iter 24 follow-up: let staticcheck infer the auth guard type

* docs(autoresearch): log iters 24-25 and lessons 9-11 (declared-dep bug class, gate discipline)
2026-08-29 11:21:04 +08:00

172 lines
4.7 KiB
Go

// Copyright 2026 Arctel.net
// SPDX-License-Identifier: Apache-2.0
// Package user provides the user profile, credential management, role management, and access token domain plugin for Cordis.
package user
import (
"Wavelet/core"
"Wavelet/core/contracts"
"Wavelet/core/extpoints"
"Wavelet/pkg/ginutil"
"context"
"embed"
"reflect"
"github.com/gin-gonic/gin"
)
//go:embed migrations/*/*.sql
var userMigrations embed.FS
// Option configures the user plugin.
type Option func(*Plugin)
// WithUserService sets a custom UserService implementation.
func WithUserService(svc contracts.UserService) Option {
return func(p *Plugin) {
p.userSvc = svc
}
}
// Plugin implements core.Plugin to provide user account and credential domain services.
type Plugin struct {
userSvc contracts.UserService
}
// New creates a new user domain plugin.
func New(opts ...Option) *Plugin {
p := &Plugin{}
for _, opt := range opts {
if opt != nil {
opt(p)
}
}
return p
}
// PluginName 用户插件唯一名称标识
const PluginName = "user"
// Name returns the unique identifier for the user domain plugin.
func (p *Plugin) Name() string {
return PluginName
}
// Inject declares required dependencies for the user domain plugin.
func (p *Plugin) Inject() []reflect.Type {
return []reflect.Type{
reflect.TypeFor[contracts.DBService](),
// Apply resolves AuthService to build the route auth middleware. The
// kernel only gates Apply on declared deps, so leaving this out lets
// user mount before auth and fall back to a pass-through middleware.
reflect.TypeFor[contracts.AuthService](),
}
}
// Manifest returns the plugin metadata.
func (p *Plugin) Manifest() core.Manifest {
return core.Manifest{
Name: PluginName,
Version: "1.0.0",
Description: "User profiles, credentials, role management, and access token domain plugin",
Author: "Wavelet Team",
}
}
// Apply registers user migrations, services, routes, tasks, schedules, and settings into the Context.
func (p *Plugin) Apply(ctx *core.Context) error {
// 0. Bind DBService from Context
if db, err := core.Inject[contracts.DBService](ctx); err == nil && db != nil {
SetDBService(db)
} else {
core.When[contracts.DBService](ctx, func(db contracts.DBService) {
SetDBService(db)
})
}
ctx.OnDispose(func() error {
SetDBService(nil)
return nil
})
// 0.1 Resolve auth service for middleware (via IoC, not direct import)
denyAuth := ginutil.AuthUnavailable()
loginMW := denyAuth
noTokenMW := denyAuth
if authSvc, err := core.Inject[contracts.AuthService](ctx); err == nil && authSvc != nil {
if mw, ok := authSvc.RequireAuthMiddleware().(gin.HandlerFunc); ok {
loginMW = mw
}
if mw, ok := authSvc.DisallowTokenAuthMiddleware().(gin.HandlerFunc); ok {
noTokenMW = mw
}
}
// 1. Register migrations
ctx.Migrations().Register("user", userMigrations)
// 2. Initialize and provide UserService
if p.userSvc == nil {
p.userSvc = newUserService(ctx.Events())
}
core.Provide[contracts.UserService](ctx, p.userSvc)
// 3. Register HTTP Routes
userGroup := ctx.Router().Group("/api/v1/user")
{
userGroup.POST("/login", Login)
userGroup.POST("/register", Register)
userGroup.GET("/logout", Logout)
userGroup.POST("/send-email-code", SendEmailCode)
userGroup.POST("/change-password", loginMW, ChangePassword)
userGroup.PUT("/profile", loginMW, UpdateProfile)
// Access Tokens
tokensGroup := userGroup.Group("/access-tokens", loginMW, noTokenMW)
{
tokensGroup.GET("", ListAccessTokens)
tokensGroup.POST("", CreateAccessToken)
tokensGroup.DELETE("/:id", DeleteAccessToken)
tokensGroup.POST("/:id/rotate", RotateAccessToken)
}
}
const defaultUserTaskRetry = 3
// 4. Register background tasks
ctx.Task().Register("user:send_email_code", func(_ context.Context, _ []byte) error {
return nil
}, extpoints.WithTaskRetry(defaultUserTaskRetry))
ctx.Task().Register("user:cleanup_inactive", func(_ context.Context, _ []byte) error {
return nil
})
// 5. Register Settings Schemas
ctx.Settings().Register(extpoints.SettingSchema{
Key: "user.registration_enabled",
Default: true,
Description: "Whether new user registration is enabled",
Type: "boolean",
Category: "general",
Public: true,
})
ctx.Settings().Register(extpoints.SettingSchema{
Key: "user.password_login_enabled",
Default: true,
Description: "Whether password login is enabled",
Type: "boolean",
Category: "general",
Public: true,
})
ctx.Settings().Register(extpoints.SettingSchema{
Key: "user.min_password_length",
Default: 8,
Description: "Minimum password length required for user accounts",
Type: "integer",
Category: "security",
})
return nil
}