This commit is contained in:
1 parent
de8c298bd5
commit
67931eab5d
38 files changed
+1128
-135
No files matched your search
@@ -108,6 +108,8 @@ func loginSecurityFields(user *models.User) map[string]any {
|
||||
"showSecuritySetupPrompt": user != nil,
|
||||
"externalEmailConfigured": false,
|
||||
"webAuthnEnabled": webAuthnRuntime() != nil,
|
||||
"totpConfigured": false,
|
||||
"securitySetupRequired": false,
|
||||
}
|
||||
if user == nil {
|
||||
return fields
|
||||
@@ -118,18 +120,29 @@ func loginSecurityFields(user *models.User) map[string]any {
|
||||
fields["externalEmailConfigured"] = emailConfigured
|
||||
}
|
||||
}
|
||||
configured := user.EffectiveRole() == access.RoleSuperAdmin
|
||||
if !configured {
|
||||
if service := credentialRuntime(); service != nil {
|
||||
configured, _ = service.HasValidRecoveryCode(user.ID)
|
||||
}
|
||||
fields["recoveryCodesConfigured"] = configured
|
||||
fields["showRecoverySetupPrompt"] = !configured
|
||||
configured := false
|
||||
if db.Instance != nil && user.ID > 0 {
|
||||
configured, _ = db.Instance.Where("user_id = ? AND used_at IS NULL", user.ID).Exist(&models.RecoveryCode{})
|
||||
enabled, _ := db.Instance.Where("user_id = ? AND enabled = ? AND revoked_at IS NULL", user.ID, true).Exist(&models.TOTPAuthenticator{})
|
||||
fields["totpConfigured"] = enabled
|
||||
}
|
||||
fields["recoveryCodesConfigured"] = configured
|
||||
fields["showRecoverySetupPrompt"] = !configured
|
||||
fields["showSecuritySetupPrompt"] = !configured || fields["externalEmailConfigured"] != true
|
||||
if user.EffectiveRole() == access.RoleSuperAdmin {
|
||||
required := !configured && fields["externalEmailConfigured"] != true && fields["totpConfigured"] != true
|
||||
fields["securitySetupRequired"] = required
|
||||
fields["showSecuritySetupPrompt"] = required
|
||||
fields["showRecoverySetupPrompt"] = false
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
// RequiresSecuritySetup 每次请求按当前凭据状态判断,撤销最后一种验证后立即恢复限制。
|
||||
func RequiresSecuritySetup(userID int, role access.Role) bool {
|
||||
return loginSecurityFields(&models.User{ID: userID, Role: string(role)})["securitySetupRequired"] == true
|
||||
}
|
||||
|
||||
func (limiter *loginLimiter) blocked(key string) bool {
|
||||
now := limiter.now()
|
||||
limiter.mu.Lock()
|
||||
|
||||
@@ -246,9 +246,9 @@ type recoveryCodeRequest struct {
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
func rejectSuperAdminRecoveryCodes(ctx *context.Context, w http.ResponseWriter) bool {
|
||||
if ctx != nil && ctx.EffectiveRole() == access.RoleSuperAdmin {
|
||||
writeSecurityError(w, response.NoAccessPrivileges, "超级管理员恢复码只能通过部署端专用通道管理")
|
||||
func requireSuperAdminRecoveryCodeAuth(ctx *context.Context, w http.ResponseWriter) bool {
|
||||
if ctx != nil && ctx.EffectiveRole() == access.RoleSuperAdmin && !ctx.RecentAuth {
|
||||
writeSecurityErrorWithCode(w, response.NoAccessPrivileges, "请先重新验证当前密码", string(access.CodeRecentAuthRequired))
|
||||
return true
|
||||
}
|
||||
return false
|
||||
@@ -306,7 +306,7 @@ func GenerateRecoveryCodes(ctx *context.Context, w http.ResponseWriter, req *htt
|
||||
writeSecurityError(w, response.NeedLogin, "请先登录")
|
||||
return
|
||||
}
|
||||
if rejectSuperAdminRecoveryCodes(ctx, w) {
|
||||
if requireSuperAdminRecoveryCodeAuth(ctx, w) {
|
||||
return
|
||||
}
|
||||
var input recoveryCodeRequest
|
||||
@@ -339,9 +339,6 @@ func GetRecoveryCodeStatus(ctx *context.Context, w http.ResponseWriter, req *htt
|
||||
writeSecurityError(w, response.NeedLogin, "请先登录")
|
||||
return
|
||||
}
|
||||
if rejectSuperAdminRecoveryCodes(ctx, w) {
|
||||
return
|
||||
}
|
||||
service := credentialRuntime()
|
||||
if service == nil {
|
||||
writeSecurityError(w, response.ServerError, "安全凭据服务不可用")
|
||||
@@ -361,7 +358,7 @@ func RevokeRecoveryCodes(ctx *context.Context, w http.ResponseWriter, req *http.
|
||||
writeSecurityError(w, response.NeedLogin, "请先登录")
|
||||
return
|
||||
}
|
||||
if rejectSuperAdminRecoveryCodes(ctx, w) {
|
||||
if requireSuperAdminRecoveryCodeAuth(ctx, w) {
|
||||
return
|
||||
}
|
||||
service := credentialRuntime()
|
||||
@@ -512,6 +509,10 @@ func RequestVerification(ctx *context.Context, w http.ResponseWriter, req *http.
|
||||
if input.Account == "" {
|
||||
input.Account = input.Identifier
|
||||
}
|
||||
if input.Purpose == verification.PurposeAdminLocalReset {
|
||||
writeSecurityError(w, response.NoAccessPrivileges, "请使用本机部署重置通道")
|
||||
return
|
||||
}
|
||||
if !strings.EqualFold(strings.TrimSpace(input.Account), strings.TrimSpace(ctx.UserAccount)) {
|
||||
writeSecurityError(w, response.ParamsError, "请求无效")
|
||||
return
|
||||
@@ -547,6 +548,10 @@ func VerifyVerification(ctx *context.Context, w http.ResponseWriter, req *http.R
|
||||
if input.Account == "" {
|
||||
input.Account = input.Identifier
|
||||
}
|
||||
if input.Purpose == verification.PurposeAdminLocalReset {
|
||||
writeSecurityError(w, response.NoAccessPrivileges, "请使用本机部署重置通道")
|
||||
return
|
||||
}
|
||||
if !strings.EqualFold(strings.TrimSpace(input.Account), strings.TrimSpace(ctx.UserAccount)) {
|
||||
writeSecurityError(w, response.ParamsError, "验证失败")
|
||||
return
|
||||
|
||||
@@ -56,7 +56,7 @@ func TestSecurityHandlersRejectUnauthenticatedRequests(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuperAdminCannotManageRecoveryCodesThroughWeb(t *testing.T) {
|
||||
func TestSuperAdminRecoveryCodesRequireRecentAuthentication(t *testing.T) {
|
||||
ctx := &appcontext.Context{UserID: 1, Role: access.RoleSuperAdmin}
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/security/credentials/recovery-codes", strings.NewReader(`{"count":5}`))
|
||||
recorder := httptest.NewRecorder()
|
||||
@@ -247,7 +247,6 @@ func TestProtocolCredentialHandlersManageCurrentUserCredential(t *testing.T) {
|
||||
t.Fatalf("expected revealed smtp code %v, got %v", generated["code"], revealedMap["smtp"])
|
||||
}
|
||||
|
||||
|
||||
revokeRecorder := httptest.NewRecorder()
|
||||
revokeRequest := httptest.NewRequest(
|
||||
http.MethodPost,
|
||||
|
||||
@@ -30,6 +30,10 @@ func AcknowledgeSecuritySetup(ctx *context.Context, w http.ResponseWriter, req *
|
||||
writeSecurityError(w, response.ServerError, "保存提醒状态失败,请重试")
|
||||
return
|
||||
}
|
||||
if RequiresSecuritySetup(user.ID, user.EffectiveRole()) {
|
||||
writeSecurityError(w, response.NoAccessPrivileges, "请先启用至少一种安全验证")
|
||||
return
|
||||
}
|
||||
session.Instance.Put(req.Context(), session.SecuritySetupDismissedKey, true)
|
||||
response.NewSuccessResponse(map[string]any{"showSecuritySetupPrompt": false}).FPrint(w)
|
||||
}
|
||||
@@ -62,7 +62,7 @@ func setupSecurityPromptTest(t *testing.T) *xorm.Engine {
|
||||
previous := db.Instance
|
||||
db.Instance = engine
|
||||
t.Cleanup(func() { db.Instance = previous; _ = engine.Close() })
|
||||
if err := engine.Sync2(&models.User{}, &models.ExternalEmail{}, &models.RecoveryCode{}); err != nil {
|
||||
if err := engine.Sync2(&models.User{}, &models.ExternalEmail{}, &models.RecoveryCode{}, &models.TOTPAuthenticator{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
previousRuntime := securityRuntime
|
||||
@@ -81,7 +81,7 @@ func TestSecuritySetupAcknowledgementIsSessionScoped(t *testing.T) {
|
||||
session.Instance, config.Instance = previousSession, previousConfig
|
||||
config.SetRuntimeManager(previousManager)
|
||||
})
|
||||
first := models.User{Account: "root", Name: "Root", Role: string(access.RoleSuperAdmin)}
|
||||
first := models.User{Account: "admin", Name: "Admin", Role: string(access.RoleAdmin)}
|
||||
second := models.User{Account: "alice", Name: "Alice", Role: string(access.RoleUser)}
|
||||
if _, err := engine.Insert(&first, &second); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -119,7 +119,7 @@ func TestSecuritySetupAcknowledgementIsSessionScoped(t *testing.T) {
|
||||
t.Fatal("dismissal must not persist on either account")
|
||||
}
|
||||
fields := loginSecurityFields(&loaded)
|
||||
if fields["showSecuritySetupPrompt"] != true || fields["showRecoverySetupPrompt"] != false {
|
||||
if fields["showSecuritySetupPrompt"] != true || fields["showRecoverySetupPrompt"] != true {
|
||||
t.Fatal("incomplete setup must be reported again on login")
|
||||
}
|
||||
if untouched.Password != second.Password || loaded.SecurityVersion != first.SecurityVersion {
|
||||
@@ -143,7 +143,7 @@ func TestSecuritySetupAcknowledgementIsSessionScoped(t *testing.T) {
|
||||
assertInfoPrompt := func(want bool) {
|
||||
t.Helper()
|
||||
recorder := httptest.NewRecorder()
|
||||
Info(&appcontext.Context{UserID: first.ID, Role: access.RoleSuperAdmin}, recorder, request.WithContext(refreshed))
|
||||
Info(&appcontext.Context{UserID: first.ID, Role: access.RoleAdmin}, recorder, request.WithContext(refreshed))
|
||||
var payload struct {
|
||||
ErrorNo int `json:"errorNo"`
|
||||
Data struct {
|
||||
@@ -188,8 +188,12 @@ func TestSecuritySetupRequiresUsableCredentials(t *testing.T) {
|
||||
}
|
||||
fields := loginSecurityFields(&user)
|
||||
emailReady := emailStatus == models.ExternalEmailStatusVerified
|
||||
codeReady := codeStatus == "valid" || role == access.RoleSuperAdmin
|
||||
if fields["externalEmailConfigured"] != emailReady || fields["showSecuritySetupPrompt"] != (!emailReady || !codeReady) {
|
||||
codeReady := codeStatus == "valid"
|
||||
wantPrompt := !emailReady || !codeReady
|
||||
if role == access.RoleSuperAdmin {
|
||||
wantPrompt = !emailReady && !codeReady
|
||||
}
|
||||
if fields["externalEmailConfigured"] != emailReady || fields["showSecuritySetupPrompt"] != wantPrompt {
|
||||
t.Fatalf("unexpected security state: %#v", fields)
|
||||
}
|
||||
})
|
||||
@@ -209,6 +213,46 @@ func TestSecuritySetupRejectsAnonymous(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuperAdminCannotDismissRequiredSetupAndTOTPQualifies(t *testing.T) {
|
||||
engine := setupSecurityPromptTest(t)
|
||||
previous := session.Instance
|
||||
session.Instance = scs.New()
|
||||
t.Cleanup(func() { session.Instance = previous })
|
||||
user := models.User{Account: "root", Role: string(access.RoleSuperAdmin)}
|
||||
if _, err := engine.Insert(&user); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
loaded, err := session.Instance.Load(context.Background(), "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/security/setup/acknowledge", nil).WithContext(loaded)
|
||||
recorder := httptest.NewRecorder()
|
||||
AcknowledgeSecuritySetup(&appcontext.Context{UserID: user.ID, Role: access.RoleSuperAdmin}, recorder, request)
|
||||
var payload struct {
|
||||
ErrorNo int `json:"errorNo"`
|
||||
}
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil || payload.ErrorNo == 0 {
|
||||
t.Fatal("required setup was dismissed")
|
||||
}
|
||||
if session.Instance.GetBool(loaded, session.SecuritySetupDismissedKey) {
|
||||
t.Fatal("dismissal persisted")
|
||||
}
|
||||
if _, err := engine.Insert(&models.TOTPAuthenticator{UserID: user.ID, Enabled: true}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if RequiresSecuritySetup(user.ID, user.EffectiveRole()) {
|
||||
t.Fatal("enabled TOTP did not qualify")
|
||||
}
|
||||
now := time.Now()
|
||||
if _, err := engine.Where("user_id = ?", user.ID).Cols("revoked_at").Update(&models.TOTPAuthenticator{RevokedAt: &now}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !RequiresSecuritySetup(user.ID, user.EffectiveRole()) {
|
||||
t.Fatal("revoked TOTP still qualifies")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLegacyConfigStatusReportsUnavailable(t *testing.T) {
|
||||
previous := config.CurrentManager()
|
||||
config.SetRuntimeManager(nil)
|
||||
|
||||
@@ -239,7 +239,7 @@ func Info(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
for key, value := range loginSecurityFields(&models.User{ID: ctx.UserID, Role: string(ctx.EffectiveRole())}) {
|
||||
result[key] = value
|
||||
}
|
||||
if session.Instance != nil && session.Instance.GetBool(req.Context(), session.SecuritySetupDismissedKey) {
|
||||
if result["securitySetupRequired"] != true && session.Instance != nil && session.Instance.GetBool(req.Context(), session.SecuritySetupDismissedKey) {
|
||||
result["showSecuritySetupPrompt"] = false
|
||||
result["showRecoverySetupPrompt"] = false
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user