加固客户端凭据签发与撤销的本人密码验证
This commit is contained in:
1 parent
5bb1da01a4
commit
ad1f095837
6 files changed
+286
-68
No files matched your search
@@ -16,7 +16,6 @@ import (
|
||||
"git.pcux.cn/xuans/Smail/dto/response"
|
||||
"git.pcux.cn/xuans/Smail/models"
|
||||
"git.pcux.cn/xuans/Smail/services/access"
|
||||
"git.pcux.cn/xuans/Smail/services/auth"
|
||||
"git.pcux.cn/xuans/Smail/services/credentials"
|
||||
"git.pcux.cn/xuans/Smail/services/externalemail"
|
||||
"git.pcux.cn/xuans/Smail/services/recovery"
|
||||
@@ -422,9 +421,11 @@ func RevokeRecoveryCodes(ctx *context.Context, w http.ResponseWriter, req *http.
|
||||
type protocolCredentialRequest struct {
|
||||
Protocol string `json:"protocol"`
|
||||
Enabled *bool `json:"enabled,omitempty"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
func requireProtocolCredentialContext(ctx *context.Context, w http.ResponseWriter) (*credentials.Service, bool) {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
if ctx == nil || ctx.UserID <= 0 {
|
||||
writeSecurityError(w, response.NeedLogin, "请先登录")
|
||||
return nil, false
|
||||
@@ -463,6 +464,9 @@ func SetProtocolCredentialEnabled(ctx *context.Context, w http.ResponseWriter, r
|
||||
writeSecurityError(w, response.ParamsError, "协议设置请求无效")
|
||||
return
|
||||
}
|
||||
if !requireProtocolCredentialPassword(ctx, w, req, input.Password) {
|
||||
return
|
||||
}
|
||||
if err := service.SetProtocolEnabled(ctx.UserID, input.Protocol, *input.Enabled); err != nil {
|
||||
writeSecurityError(w, response.ParamsError, "协议设置失败")
|
||||
return
|
||||
@@ -481,6 +485,9 @@ func GenerateProtocolCredential(ctx *context.Context, w http.ResponseWriter, req
|
||||
writeSecurityError(w, response.ParamsError, "协议请求无效")
|
||||
return
|
||||
}
|
||||
if !requireProtocolCredentialPassword(ctx, w, req, input.Password) {
|
||||
return
|
||||
}
|
||||
code, err := service.GenerateProtocolCode(ctx.UserID, input.Protocol)
|
||||
if err != nil {
|
||||
if writePasswordBusy(w, err) {
|
||||
@@ -504,6 +511,9 @@ func RevokeProtocolCredential(ctx *context.Context, w http.ResponseWriter, req *
|
||||
writeSecurityError(w, response.ParamsError, "协议请求无效")
|
||||
return
|
||||
}
|
||||
if !requireProtocolCredentialPassword(ctx, w, req, input.Password) {
|
||||
return
|
||||
}
|
||||
if err := service.RevokeProtocolCode(ctx.UserID, input.Protocol); err != nil {
|
||||
writeSecurityError(w, response.ParamsError, "撤销授权码失败")
|
||||
return
|
||||
@@ -525,11 +535,7 @@ func RevealProtocolCredentials(ctx *context.Context, w http.ResponseWriter, req
|
||||
writeSecurityError(w, response.ParamsError, "请输入当前账号密码进行安全验证")
|
||||
return
|
||||
}
|
||||
if _, err := auth.AuthenticateUserByID(ctx.UserID, input.Password); err != nil {
|
||||
if writePasswordBusy(w, err) {
|
||||
return
|
||||
}
|
||||
writeSecurityError(w, response.ParamsError, "密码验证失败")
|
||||
if !requireProtocolCredentialPassword(ctx, w, req, input.Password) {
|
||||
return
|
||||
}
|
||||
codes, err := service.RevealProtocolCodes(ctx.UserID)
|
||||
|
||||
@@ -2,6 +2,7 @@ package controllers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
@@ -32,6 +33,11 @@ func TestSecurityHandlersRejectUnauthenticatedRequests(t *testing.T) {
|
||||
{name: "generate protocol credential", hand: GenerateProtocolCredential, body: `{"protocol":"smtp"}`},
|
||||
{name: "revoke protocol credential", hand: RevokeProtocolCredential, body: `{"protocol":"smtp"}`},
|
||||
{name: "reveal protocol credentials", hand: RevealProtocolCredentials, body: `{"password":"FixtureP12"}`},
|
||||
{name: "list client credentials", hand: ListClientCredentials},
|
||||
{name: "create client credential", hand: CreateClientCredential, body: `{"client_name":"设备","password":"FixtureP12"}`},
|
||||
{name: "regenerate client credential", hand: RegenerateClientCredential, body: `{"client_id":1,"password":"FixtureP12"}`},
|
||||
{name: "revoke client credential", hand: RevokeClientCredential, body: `{"client_id":1,"password":"FixtureP12"}`},
|
||||
{name: "reveal client credentials", hand: RevealClientCredentials, body: `{"password":"FixtureP12"}`},
|
||||
{name: "request verification", hand: RequestVerification, body: `{"purpose":"login","account":"smail","email":"user@example.com"}`},
|
||||
{name: "verify verification", hand: VerifyVerification, body: `{"id":"challenge","account":"smail","email":"user@example.com","code":"12345678","purpose":"login"}`},
|
||||
{name: "list external emails", hand: ListExternalEmails},
|
||||
@@ -157,7 +163,7 @@ func TestProtocolCredentialHandlersManageCurrentUserCredential(t *testing.T) {
|
||||
setRequest := httptest.NewRequest(
|
||||
http.MethodPut,
|
||||
"/api/security/credentials/protocols/enabled",
|
||||
strings.NewReader(`{"protocol":"SMTP","enabled":true}`),
|
||||
strings.NewReader(`{"protocol":"SMTP","enabled":true,"password":"FixtureP12"}`),
|
||||
)
|
||||
SetProtocolCredentialEnabled(ctx, setRecorder, setRequest)
|
||||
var setResult response.Response
|
||||
@@ -172,7 +178,7 @@ func TestProtocolCredentialHandlersManageCurrentUserCredential(t *testing.T) {
|
||||
generateRequest := httptest.NewRequest(
|
||||
http.MethodPost,
|
||||
"/api/security/credentials/protocols/generate",
|
||||
strings.NewReader(`{"protocol":"smtp"}`),
|
||||
strings.NewReader(`{"protocol":"smtp","password":"FixtureP12"}`),
|
||||
)
|
||||
GenerateProtocolCredential(ctx, generateRecorder, generateRequest)
|
||||
var generateResult response.Response
|
||||
@@ -251,7 +257,7 @@ func TestProtocolCredentialHandlersManageCurrentUserCredential(t *testing.T) {
|
||||
revokeRequest := httptest.NewRequest(
|
||||
http.MethodPost,
|
||||
"/api/security/credentials/protocols/revoke",
|
||||
strings.NewReader(`{"protocol":"smtp"}`),
|
||||
strings.NewReader(`{"protocol":"smtp","password":"FixtureP12"}`),
|
||||
)
|
||||
RevokeProtocolCredential(ctx, revokeRecorder, revokeRequest)
|
||||
var revokeResult response.Response
|
||||
@@ -273,3 +279,117 @@ func TestProtocolCredentialHandlersManageCurrentUserCredential(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientCredentialEntryPointsRequireOwnPassword(t *testing.T) {
|
||||
_, _, engine, user, other := newPublicSecurityFixture(t)
|
||||
service, err := credentials.NewService(engine)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service.SetVaultRoot(t.TempDir())
|
||||
previousDB, previousRuntime := db.Instance, securityRuntime
|
||||
previousUserLimiter, previousIPLimiter := reauthUserAttempts, reauthIPAttempts
|
||||
db.Instance, securityRuntime.credentials = engine, service
|
||||
t.Cleanup(func() {
|
||||
db.Instance, securityRuntime = previousDB, previousRuntime
|
||||
reauthUserAttempts, reauthIPAttempts = previousUserLimiter, previousIPLimiter
|
||||
})
|
||||
_, client, err := service.CreateClientCredential(user.ID, "原设备")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := service.SetProtocolEnabled(user.ID, "smtp", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := service.GenerateProtocolCode(user.ID, "smtp"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
status := func() string {
|
||||
t.Helper()
|
||||
clients, err := service.ListClientCredentials(user.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
protocols, err := service.ListProtocolCredentials(user.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, err := json.Marshal([]any{clients, protocols})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return string(data)
|
||||
}
|
||||
before := status()
|
||||
entries := []struct {
|
||||
name string
|
||||
hand func(*appcontext.Context, http.ResponseWriter, *http.Request)
|
||||
body string
|
||||
}{
|
||||
{"create", CreateClientCredential, `{"client_name":"新设备"`},
|
||||
{"regenerate", RegenerateClientCredential, fmt.Sprintf(`{"client_id":%d`, client.ID)},
|
||||
{"revoke", RevokeClientCredential, fmt.Sprintf(`{"client_id":%d`, client.ID)},
|
||||
{"reveal", RevealClientCredentials, `{"unused":true`},
|
||||
{"enable protocol", SetProtocolCredentialEnabled, `{"protocol":"imap","enabled":true`},
|
||||
{"disable protocol", SetProtocolCredentialEnabled, `{"protocol":"smtp","enabled":false`},
|
||||
{"generate protocol", GenerateProtocolCredential, `{"protocol":"smtp"`},
|
||||
{"revoke protocol", RevokeProtocolCredential, `{"protocol":"smtp"`},
|
||||
{"reveal protocol", RevealProtocolCredentials, `{"unused":true`},
|
||||
}
|
||||
for _, role := range []access.Role{access.RoleUser, access.RoleAdmin, access.RoleSuperAdmin} {
|
||||
for _, entry := range entries {
|
||||
t.Run(string(role)+"/"+entry.name, func(t *testing.T) {
|
||||
reauthUserAttempts, reauthIPAttempts = newLoginLimiter(10), newLoginLimiter(50)
|
||||
ctx := &appcontext.Context{UserID: user.ID, Role: role, RecentAuth: true}
|
||||
for _, suffix := range []string{`}`, `,"password":"incorrect"}`, `,"password":" FixtureP12 "}`} {
|
||||
recorder := httptest.NewRecorder()
|
||||
entry.hand(ctx, recorder, httptest.NewRequest(http.MethodPost, "/api/security", strings.NewReader(entry.body+suffix)))
|
||||
var result response.Response
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &result); err != nil || result.ErrorNo == 0 {
|
||||
t.Fatal("missing or incorrect password must not allow credential operations")
|
||||
}
|
||||
if recorder.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatal("credential responses must not be cached")
|
||||
}
|
||||
if status() != before {
|
||||
t.Fatal("rejected operation changed credential state")
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
// 本人验证通过也不能重置或撤销其他账号的客户端。
|
||||
reauthUserAttempts, reauthIPAttempts = newLoginLimiter(10), newLoginLimiter(50)
|
||||
for _, hand := range []func(*appcontext.Context, http.ResponseWriter, *http.Request){RegenerateClientCredential, RevokeClientCredential} {
|
||||
recorder := httptest.NewRecorder()
|
||||
body := fmt.Sprintf(`{"client_id":%d,"password":"FixtureP12"}`, client.ID)
|
||||
hand(&appcontext.Context{UserID: other.ID, Role: access.RoleSuperAdmin}, recorder, httptest.NewRequest(http.MethodPost, "/api/security", strings.NewReader(body)))
|
||||
var result response.Response
|
||||
if err := json.Unmarshal(recorder.Body.Bytes(), &result); err != nil || result.ErrorNo == 0 || status() != before {
|
||||
t.Fatal("credential operations must remain scoped to the current account")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientCredentialPasswordFailuresShareRateLimit(t *testing.T) {
|
||||
_, _, engine, user, _ := newPublicSecurityFixture(t)
|
||||
service, err := credentials.NewService(engine)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
previousDB, previousRuntime := db.Instance, securityRuntime
|
||||
previousUserLimiter, previousIPLimiter := reauthUserAttempts, reauthIPAttempts
|
||||
db.Instance, securityRuntime.credentials = engine, service
|
||||
reauthUserAttempts, reauthIPAttempts = newLoginLimiter(1), newLoginLimiter(10)
|
||||
t.Cleanup(func() {
|
||||
db.Instance, securityRuntime = previousDB, previousRuntime
|
||||
reauthUserAttempts, reauthIPAttempts = previousUserLimiter, previousIPLimiter
|
||||
})
|
||||
ctx := &appcontext.Context{UserID: user.ID, RecentAuth: true}
|
||||
CreateClientCredential(ctx, httptest.NewRecorder(), httptest.NewRequest(http.MethodPost, "/api/security", strings.NewReader(`{"client_name":"设备","password":"incorrect"}`)))
|
||||
recorder := httptest.NewRecorder()
|
||||
RevealProtocolCredentials(ctx, recorder, httptest.NewRequest(http.MethodPost, "/api/security", strings.NewReader(`{"password":"FixtureP12"}`)))
|
||||
if recorder.Code != http.StatusTooManyRequests {
|
||||
t.Fatal("switching from client to legacy protocol entry must not bypass password failure limits")
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package controllers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"git.pcux.cn/xuans/Smail/dto/response"
|
||||
@@ -9,6 +10,32 @@ import (
|
||||
"git.pcux.cn/xuans/Smail/utils/context"
|
||||
)
|
||||
|
||||
// requireProtocolCredentialPassword 对新旧客户端入口统一执行本人验证,不复用登录时的验证状态。
|
||||
func requireProtocolCredentialPassword(ctx *context.Context, w http.ResponseWriter, req *http.Request, plain string) bool {
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
if plain == "" {
|
||||
writeSecurityError(w, response.ParamsError, "请输入当前账号密码进行安全验证")
|
||||
return false
|
||||
}
|
||||
userKey := reauthUserAttempts.accountKey(strconv.Itoa(ctx.UserID))
|
||||
ipKey := reauthIPAttempts.ipKey(req)
|
||||
if reauthUserAttempts.blocked(userKey) || reauthIPAttempts.blocked(ipKey) {
|
||||
writeReauthError(w, http.StatusTooManyRequests, "REAUTH_RATE_LIMITED", "尝试次数过多,请稍后再试")
|
||||
return false
|
||||
}
|
||||
if _, err := auth.AuthenticateUserByID(ctx.UserID, plain); err != nil {
|
||||
if writePasswordBusy(w, err) {
|
||||
return false
|
||||
}
|
||||
reauthUserAttempts.recordFailure(userKey)
|
||||
reauthIPAttempts.recordFailure(ipKey)
|
||||
writeSecurityError(w, response.ParamsError, "密码验证失败")
|
||||
return false
|
||||
}
|
||||
reauthUserAttempts.clear(userKey)
|
||||
return true
|
||||
}
|
||||
|
||||
// ListClientCredentials 返回当前用户的客户端授权码列表
|
||||
func ListClientCredentials(ctx *context.Context, w http.ResponseWriter, req *http.Request) {
|
||||
service, ok := requireProtocolCredentialContext(ctx, w)
|
||||
@@ -31,11 +58,15 @@ func CreateClientCredential(ctx *context.Context, w http.ResponseWriter, req *ht
|
||||
}
|
||||
var input struct {
|
||||
ClientName string `json:"client_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := decodeJSONRequest(w, req, &input); err != nil || strings.TrimSpace(input.ClientName) == "" {
|
||||
writeSecurityError(w, response.ParamsError, "请输入客户端名称")
|
||||
return
|
||||
}
|
||||
if !requireProtocolCredentialPassword(ctx, w, req, input.Password) {
|
||||
return
|
||||
}
|
||||
code, item, err := service.CreateClientCredential(ctx.UserID, input.ClientName)
|
||||
if err != nil {
|
||||
if writePasswordBusy(w, err) {
|
||||
@@ -54,12 +85,16 @@ func RegenerateClientCredential(ctx *context.Context, w http.ResponseWriter, req
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
ClientID int `json:"client_id"`
|
||||
ClientID int `json:"client_id"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := decodeJSONRequest(w, req, &input); err != nil || input.ClientID <= 0 {
|
||||
writeSecurityError(w, response.ParamsError, "客户端标识无效")
|
||||
return
|
||||
}
|
||||
if !requireProtocolCredentialPassword(ctx, w, req, input.Password) {
|
||||
return
|
||||
}
|
||||
code, err := service.RegenerateClientCredential(ctx.UserID, input.ClientID)
|
||||
if err != nil {
|
||||
if writePasswordBusy(w, err) {
|
||||
@@ -78,12 +113,16 @@ func RevokeClientCredential(ctx *context.Context, w http.ResponseWriter, req *ht
|
||||
return
|
||||
}
|
||||
var input struct {
|
||||
ClientID int `json:"client_id"`
|
||||
ClientID int `json:"client_id"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := decodeJSONRequest(w, req, &input); err != nil || input.ClientID <= 0 {
|
||||
writeSecurityError(w, response.ParamsError, "客户端标识无效")
|
||||
return
|
||||
}
|
||||
if !requireProtocolCredentialPassword(ctx, w, req, input.Password) {
|
||||
return
|
||||
}
|
||||
if err := service.RevokeClientCredential(ctx.UserID, input.ClientID); err != nil {
|
||||
writeSecurityError(w, response.ParamsError, err.Error())
|
||||
return
|
||||
@@ -104,11 +143,7 @@ func RevealClientCredentials(ctx *context.Context, w http.ResponseWriter, req *h
|
||||
writeSecurityError(w, response.ParamsError, "请输入当前账号密码进行安全验证")
|
||||
return
|
||||
}
|
||||
if _, err := auth.AuthenticateUserByID(ctx.UserID, input.Password); err != nil {
|
||||
if writePasswordBusy(w, err) {
|
||||
return
|
||||
}
|
||||
writeSecurityError(w, response.ParamsError, "密码验证失败")
|
||||
if !requireProtocolCredentialPassword(ctx, w, req, input.Password) {
|
||||
return
|
||||
}
|
||||
codes, err := service.RevealClientCredentials(ctx.UserID)
|
||||
|
||||
Reference in new issue
Block a user