保存显式授权范围与认证加固中间检查点

This commit is contained in:
xuans committed 2026-09-15 21:54:04 +08:00
1 parent 7f567ea23a
commit 49ede22861
28 files changed
+961 -148

No files matched your search

+22 -5
View File
@@ -33,6 +33,7 @@ type aliyunScopeResponse struct {
DiscoveredDomains []dnsprovider.AuthorizationDomain `json:"discovered_domains,omitempty"`
ManagedDomains []string `json:"managed_domains"`
CheckedAt string `json:"checked_at"`
UserScope *dnsprovider.AliyunScope `json:"user_scope,omitempty"`
}
func (s *Server) getAliyunDNSScope(c *gin.Context) {
@@ -63,6 +64,14 @@ func (s *Server) getAliyunDNSScope(c *gin.Context) {
CredentialRef: credentialRef,
CheckedAt: s.now().UTC().Format("2006-01-02T15:04:05Z"),
}
scope, scopeErr := dnsprovider.ParseAliyunScope(credentials)
if scopeErr != nil {
response.PolicyMode = "scope_required"
response.Message = scopeErr.Error()
c.JSON(http.StatusOK, response)
return
}
response.UserScope = &scope
// 读取当前系统内已经纳管的域名列表
if s.repository != nil {
@@ -136,6 +145,10 @@ func (s *Server) checkAliyunDNSDomain(c *gin.Context) {
return
}
if err := dnsprovider.ValidateAliyunDomainScope(provider, []string{targetDomain}, credentials); err != nil {
c.JSON(http.StatusOK, gin.H{"verified": false, "domain": targetDomain, "message": err.Error()})
return
}
report, verifyErr := s.aliyunChecker.Verify(c.Request.Context(), targetDomain, credentials)
report = sanitizeAliyunReport(report, targetDomain)
if verifyErr != nil {
@@ -162,7 +175,7 @@ func (s *Server) checkAliyunDNSDomain(c *gin.Context) {
})
}
func (s *Server) validateDomainAliyunAuthorization(ctx context.Context, domainName string) error {
func (s *Server) validateDomainAliyunAuthorization(ctx context.Context, domainNames ...string) error {
if s == nil {
return errors.New("域名授权检查服务未初始化")
}
@@ -189,10 +202,14 @@ func (s *Server) validateDomainAliyunAuthorization(ctx context.Context, domainNa
if _, err := dnsprovider.ValidateCredentials(dnsprovider.Aliyun, credentials); err != nil {
return fmt.Errorf("阿里云 DNS 凭据无效,不能确认域名授权:%w", err)
}
if err := s.aliyunChecker.VerifyDomain(ctx, dnsprovider.Aliyun, domainName, credentials); err != nil {
diagnosis := dnsprovider.DiagnoseAliyunError(err, domainName)
return fmt.Errorf("阿里云 RAM 账号无法操作域名 %s:%s", domainName, diagnosis)
if err := dnsprovider.ValidateAliyunDomainScope(provider, domainNames, credentials); err != nil {
return err
}
for _, domainName := range domainNames {
if err := s.aliyunChecker.VerifyDomain(ctx, dnsprovider.Aliyun, domainName, credentials); err != nil {
diagnosis := dnsprovider.DiagnoseAliyunError(err, domainName)
return fmt.Errorf("阿里云 RAM 账号无法操作域名 %s:%s", domainName, diagnosis)
}
}
return nil
}
@@ -81,6 +81,8 @@ func TestAliyunScopeAPIsAndDomainValidation(t *testing.T) {
"secret://dns/aliyun/ref1": {
"access_key_id": "LTAI_test",
"access_key_secret": "test_secret",
"managed_zones": "solit.cn,unauth.com,forbidden.cn",
"allowed_domains": "solit.cn,*.solit.cn,unauth.com,forbidden.cn",
},
},
}
@@ -208,7 +210,7 @@ func TestAliyunDomainAPIRejectsPartiallyUnauthorizedSAN(t *testing.T) {
server := New(Dependencies{
Config: cfg, Repository: &stubDomainRepository{},
Secrets: &fakeSecretReaderStore{data: map[string]map[string]string{
cfg.DNS.CredentialRef: {"access_key_id": "test-id", "access_key_secret": "test-secret"},
cfg.DNS.CredentialRef: {"access_key_id": "test-id", "access_key_secret": "test-secret", "managed_zones": "example.com", "allowed_domains": "example.com"},
}},
AliyunChecker: &fakeAliyunScopeChecker{allowedZones: []string{"example.com"}},
})
+21 -9
View File
@@ -69,6 +69,12 @@ func (s *Server) authLogin(c *gin.Context) {
s.writeError(c, http.StatusTooManyRequests, "登录失败次数过多,请稍后再试", nil)
return
}
if !s.reserveLogin(c.Request, key) {
c.Header("Retry-After", "60")
s.writeError(c, http.StatusTooManyRequests, "登录请求过于频繁或服务繁忙,请稍后再试", nil)
return
}
defer s.releaseLogin(c.Request, key)
account, userID, passwordHash, err := s.authenticateAccount(c.Request.Context(), request, cfg)
if err != nil {
@@ -92,9 +98,15 @@ func (s *Server) authLogin(c *gin.Context) {
expiresAt := minTime(now.Add(authSessionLifetime), absoluteExpiresAt)
s.authMu.Lock()
s.pruneAuthSessionsLocked(now)
if len(s.authSessions) >= authStateCapacity {
userSessions := 0
for _, session := range s.authSessions {
if session.UserID == userID {
userSessions++
}
}
if len(s.authSessions) >= authStateCapacity || userSessions >= authUserSessionCapacity {
s.authMu.Unlock()
s.writeError(c, http.StatusServiceUnavailable, "登录会话数量已达上限,请稍后重试", nil)
s.writeError(c, http.StatusServiceUnavailable, "登录会话数量已达上限,请退出其他设备或稍后重试", nil)
return
}
s.authSessions[token] = authSession{
@@ -180,7 +192,7 @@ func (s *Server) currentAuthSession(c *gin.Context) (authSession, bool) {
s.authMu.RLock()
session, ok := s.authSessions[token]
s.authMu.RUnlock()
if !ok || !session.ExpiresAt.After(now) || (!session.AbsoluteExpiresAt.IsZero() && !session.AbsoluteExpiresAt.After(now)) {
if !ok || !session.ExpiresAt.After(now) || session.AbsoluteExpiresAt.IsZero() || !session.AbsoluteExpiresAt.After(now) || session.ExpiresAt.After(session.AbsoluteExpiresAt) {
if ok {
s.authMu.Lock()
delete(s.authSessions, token)
@@ -198,7 +210,7 @@ func (s *Server) currentAuthSession(c *gin.Context) (authSession, bool) {
newExpiresAt := minTime(now.Add(authSessionLifetime), session.AbsoluteExpiresAt)
s.authMu.Lock()
current, exists := s.authSessions[token]
if !exists {
if !exists || current.UserID != session.UserID || current.PasswordHash != session.PasswordHash || current.Role != session.Role || current.Username != session.Username || current.Email != session.Email || !current.AbsoluteExpiresAt.Equal(session.AbsoluteExpiresAt) {
s.authMu.Unlock()
return authSession{}, false
}
@@ -216,11 +228,11 @@ func (s *Server) currentAuthSession(c *gin.Context) (authSession, bool) {
}
func (s *Server) authSessionAccountIsValid(ctx context.Context, session authSession) bool {
if session.UserID == "" {
return true
if strings.TrimSpace(session.UserID) == "" || strings.TrimSpace(session.PasswordHash) == "" || strings.TrimSpace(session.Username) == "" {
return false
}
if session.PasswordHash == "" {
return true
if session.Role != repository.UserRoleUser && session.Role != repository.UserRoleAdmin && session.Role != repository.UserRoleSuperAdmin {
return false
}
if session.UserID == "primary-super-admin" {
s.configMu.RLock()
@@ -290,7 +302,7 @@ func (s *Server) allowLogin(key string) bool {
if !attempt.BlockedTill.IsZero() && attempt.BlockedTill.After(now) {
return false
}
if attempt.WindowStart.IsZero() || now.Sub(attempt.WindowStart) >= loginWindow {
if attempt.WindowStart.IsZero() || now.Sub(attempt.WindowStart) >= loginWindow || (!attempt.BlockedTill.IsZero() && !attempt.BlockedTill.After(now)) {
delete(s.loginAttempts, key)
}
return true
@@ -0,0 +1,67 @@
package httpapi
import (
"net/http"
"strings"
"time"
)
const (
loginConcurrentLimit = 8
loginSourceConcurrentLimit = 2
loginSourceRequestLimit = 30
)
type loginSource struct {
WindowStart time.Time
Requests int
InFlight int
}
// 在密码计算和数据库查询之前预约容量,不建立无限等待队列。
// 来源只取真实 TCP 对端;不信任任意转发头。代理部署应另外配置边缘限流。
func (s *Server) reserveLogin(request *http.Request, key string) bool {
sourceKey := strings.SplitN(loginAttemptKey(request, ""), "|", 2)[0]
now := s.now()
s.loginMu.Lock()
defer s.loginMu.Unlock()
for name, source := range s.loginSources {
if source.InFlight == 0 && now.Sub(source.WindowStart) >= time.Minute {
delete(s.loginSources, name)
}
}
source, exists := s.loginSources[sourceKey]
attempt := s.loginAttempts[key]
if attempt.BlockedTill.After(now) || attempt.Failures+s.loginPending[key] >= loginFailureLimit ||
s.loginInFlight >= loginConcurrentLimit || source.InFlight >= loginSourceConcurrentLimit ||
(!exists && len(s.loginSources) >= authStateCapacity) {
return false
}
if source.WindowStart.IsZero() || now.Sub(source.WindowStart) >= time.Minute {
source.WindowStart = now
source.Requests = 0
}
if source.Requests >= loginSourceRequestLimit {
return false
}
source.Requests++
source.InFlight++
s.loginSources[sourceKey] = source
s.loginInFlight++
s.loginPending[key]++
return true
}
func (s *Server) releaseLogin(request *http.Request, key string) {
sourceKey := strings.SplitN(loginAttemptKey(request, ""), "|", 2)[0]
s.loginMu.Lock()
defer s.loginMu.Unlock()
source := s.loginSources[sourceKey]
source.InFlight--
s.loginSources[sourceKey] = source
s.loginInFlight--
s.loginPending[key]--
if s.loginPending[key] == 0 {
delete(s.loginPending, key)
}
}
+185
View File
@@ -0,0 +1,185 @@
package httpapi
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
func TestIncompleteSessionsFailClosed(t *testing.T) {
cfg := readyTestConfig(t.TempDir())
cfg.Admin.Username = "admin"
cfg.Admin.PasswordHash = httpUserPasswordHash(t, "AdminPass123")
for _, field := range []string{"user_id", "username", "hash", "role", "absolute", "inverted"} {
t.Run(field, func(t *testing.T) {
s := New(Dependencies{Config: cfg})
cookie := loginAuthTest(t, s, "admin", "AdminPass123", false).Result().Cookies()[0]
session := s.authSessions[cookie.Value]
switch field {
case "user_id":
session.UserID = ""
case "username":
session.Username = ""
case "hash":
session.PasswordHash = ""
case "role":
session.Role = "unknown"
case "absolute":
session.AbsoluteExpiresAt = time.Time{}
case "inverted":
session.AbsoluteExpiresAt = session.ExpiresAt.Add(-time.Second)
}
s.authSessions[cookie.Value] = session
if response := authSessionRequest(s, cookie); response.Code != http.StatusUnauthorized {
t.Fatal("不完整会话必须拒绝")
}
if _, ok := s.authSessions[cookie.Value]; ok {
t.Fatal("失效会话必须移除")
}
})
}
}
func TestLoginAdmissionConcurrentBurstAndRecovery(t *testing.T) {
s := New(Dependencies{Config: readyTestConfig(t.TempDir())})
const workers = 512
start, release := make(chan struct{}), make(chan struct{})
var attempted sync.WaitGroup
var done sync.WaitGroup
var accepted atomic.Int32
attempted.Add(workers)
done.Add(workers)
for i := 0; i < workers; i++ {
go func(i int) {
defer done.Done()
<-start
r := httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", nil)
r.RemoteAddr = fmt.Sprintf("192.0.2.%d:1234", i%250+1)
key := loginAttemptKey(r, fmt.Sprint(i))
ok := s.reserveLogin(r, key)
if ok {
accepted.Add(1)
}
attempted.Done()
if ok {
<-release
s.releaseLogin(r, key)
}
}(i)
}
close(start)
attempted.Wait()
if accepted.Load() != loginConcurrentLimit {
t.Errorf("并发容量错误:%d", accepted.Load())
}
close(release)
done.Wait()
if s.loginInFlight != 0 || len(s.loginPending) != 0 {
t.Fatal("并发预约没有完整释放")
}
r := httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", nil)
r.RemoteAddr = "198.51.100.1:1234"
key := loginAttemptKey(r, "normal")
if !s.reserveLogin(r, key) {
t.Fatal("突发结束后正常用户无法恢复")
}
s.releaseLogin(r, key)
}
func TestRandomIdentifiersCannotExhaustGlobalLoginState(t *testing.T) {
cfg := readyTestConfig(t.TempDir())
cfg.Admin.Username = "admin"
cfg.Admin.PasswordHash = httpUserPasswordHash(t, "AdminPass123")
s := New(Dependencies{Config: cfg})
now := time.Now()
s.now = func() time.Time { return now }
for i := 0; i < 5000; i++ {
r := httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", strings.NewReader(fmt.Sprintf(`{"identifier":"unknown-%d","password":"wrong"}`, i)))
r.RemoteAddr = "192.0.2.1:1234"
w := httptest.NewRecorder()
s.Handler().ServeHTTP(w, r)
if i >= loginSourceRequestLimit && w.Code != http.StatusTooManyRequests {
t.Fatalf("随机账号绕过来源限流:%d", w.Code)
}
}
if len(s.loginAttempts) > loginSourceRequestLimit {
t.Fatal("单一来源挤占了全局失败表")
}
normalRequest := httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", strings.NewReader(`{"identifier":"admin","password":"AdminPass123"}`))
normalRequest.RemoteAddr = "198.51.100.1:1234"
response := httptest.NewRecorder()
s.Handler().ServeHTTP(response, normalRequest)
if response.Code != http.StatusOK {
t.Fatal("独立来源正常用户不能登录")
}
now = now.Add(2 * time.Minute)
r := httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", strings.NewReader(`{"identifier":"admin","password":"AdminPass123"}`))
r.RemoteAddr = "192.0.2.1:1234"
w := httptest.NewRecorder()
s.Handler().ServeHTTP(w, r)
if w.Code != http.StatusOK {
t.Fatalf("来源窗口结束后无法恢复:%d", w.Code)
}
}
func TestLoginAttemptTableSaturationRecoversAfterWindow(t *testing.T) {
s := New(Dependencies{Config: readyTestConfig(t.TempDir())})
now := time.Now()
s.now = func() time.Time { return now }
for i := 0; i < authStateCapacity; i++ {
s.recordLoginFailure(fmt.Sprint(i))
}
if s.allowLogin("normal") {
t.Fatal("满容量不能无界增加新键")
}
now = now.Add(loginWindow + time.Second)
if !s.allowLogin("normal") || len(s.loginAttempts) != 0 {
t.Fatal("窗口到期后未恢复")
}
}
func TestLoginBlockExpiresAndUserSessionQuotaRecovers(t *testing.T) {
cfg := readyTestConfig(t.TempDir())
cfg.Admin.Username = "admin"
cfg.Admin.PasswordHash = httpUserPasswordHash(t, "AdminPass123")
s := New(Dependencies{Config: cfg})
now := time.Now()
s.now = func() time.Time { return now }
r := httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", nil)
key := loginAttemptKey(r, "admin")
for i := 0; i < loginFailureLimit; i++ {
s.recordLoginFailure(key)
}
if s.allowLogin(key) {
t.Fatal("封禁期间不能登录")
}
now = now.Add(loginBlockDuration + time.Second)
if !s.allowLogin(key) || !s.reserveLogin(r, key) {
t.Fatal("封禁到期后必须恢复预约")
}
s.releaseLogin(r, key)
var first *http.Cookie
for i := 0; i < authUserSessionCapacity; i++ {
cookie := loginAuthTest(t, s, "admin", "AdminPass123", false).Result().Cookies()[0]
if first == nil {
first = cookie
}
}
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", strings.NewReader(`{"identifier":"admin","password":"AdminPass123"}`))
w := httptest.NewRecorder()
s.Handler().ServeHTTP(w, request)
if w.Code != http.StatusServiceUnavailable {
t.Fatal("单账号不能占满全局会话容量")
}
logout := httptest.NewRequest(http.MethodPost, "/api/v1/auth/logout", nil)
logout.AddCookie(first)
s.Handler().ServeHTTP(httptest.NewRecorder(), logout)
if loginAuthTest(t, s, "admin", "AdminPass123", false).Code != http.StatusOK {
t.Fatal("主动退出后不能恢复登录")
}
}
@@ -3,6 +3,7 @@ package httpapi
import "time"
const authStateCapacity = 4096
const authUserSessionCapacity = 16
// 调用方持有认证锁;会话表有容量上限,不淘汰仍然有效的用户会话。
func (s *Server) pruneAuthSessionsLocked(now time.Time) {
@@ -41,6 +41,8 @@ func newRestoreAPITestServer(t *testing.T, restore func(context.Context, string,
audit := &restoreAuditRepository{}
cfg := config.Default(t.TempDir())
cfg.SetupReady = true
cfg.Admin.Username = "admin"
cfg.Admin.PasswordHash = httpUserPasswordHash(t, "RestoreTest123")
server := New(Dependencies{
Config: cfg,
Repository: &stubDomainRepository{},
@@ -49,9 +51,13 @@ func newRestoreAPITestServer(t *testing.T, restore func(context.Context, string,
Audit: audit,
})
server.authSessions["test-session"] = authSession{
Username: "admin",
Role: "super_admin",
ExpiresAt: time.Now().Add(time.Hour),
UserID: "primary-super-admin",
PasswordHash: cfg.Admin.PasswordHash,
Email: cfg.Admin.Email,
Username: "admin",
Role: "super_admin",
ExpiresAt: time.Now().Add(time.Hour),
AbsoluteExpiresAt: time.Now().Add(2 * time.Hour),
}
return server, audit
}
@@ -47,7 +47,7 @@ func TestAliyunReportHidesSDKErrorAndPreservesCleanupFailure(t *testing.T) {
cfg.DNS.CredentialRef = "secret://test/only"
server := New(Dependencies{
Config: cfg, AliyunChecker: &unsafeReportChecker{},
Secrets: &fakeSecretReaderStore{data: map[string]map[string]string{cfg.DNS.CredentialRef: {"access_key_id": "test-id", "access_key_secret": "test-secret"}}},
Secrets: &fakeSecretReaderStore{data: map[string]map[string]string{cfg.DNS.CredentialRef: {"access_key_id": "test-id", "access_key_secret": "test-secret", "managed_zones": "example.test", "allowed_domains": "example.test"}}},
})
response := httptest.NewRecorder()
serveAdminHTTP(server, response, httptest.NewRequest(http.MethodPost, "/api/v1/dns/aliyun/check", strings.NewReader(`{"domain":"example.test"}`)))
+15 -21
View File
@@ -106,6 +106,9 @@ type Server struct {
authMu sync.RWMutex
loginAttempts map[string]loginAttempt
loginMu sync.Mutex
loginSources map[string]loginSource
loginPending map[string]int
loginInFlight int
loginPrunedAt time.Time
now func() time.Time
httpServer *http.Server
@@ -144,6 +147,8 @@ func New(deps Dependencies) *Server {
resetLimiter: newResetRateLimiter(),
authSessions: make(map[string]authSession),
loginAttempts: make(map[string]loginAttempt),
loginSources: make(map[string]loginSource),
loginPending: make(map[string]int),
now: time.Now,
}
router.Use(server.requestMiddleware())
@@ -361,10 +366,17 @@ func (s *Server) ready(c *gin.Context) {
continue
}
checked[reference] = struct{}{}
if _, err := reader.Get(ctx, reference); err != nil {
credentials, err := reader.Get(ctx, reference)
if err != nil {
s.writeReadinessFailure(c, "credential_unavailable")
return
}
if reference == dnsReference && cfg.DNS.Provider == dnsprovider.Aliyun {
if _, err := dnsprovider.ParseAliyunScope(credentials); err != nil {
s.writeReadinessFailure(c, "dns_scope_required")
return
}
}
}
for _, path := range []string{cfg.Server.TLSCert, cfg.Server.TLSKey} {
@@ -460,19 +472,10 @@ func (s *Server) createDomain(c *gin.Context) {
s.writeError(c, http.StatusBadRequest, "域名配置无效", err)
return
}
if err := s.validateDomainAliyunAuthorization(c.Request.Context(), item.Name); err != nil {
if err := s.validateDomainAliyunAuthorization(c.Request.Context(), append([]string{item.Name}, item.SANs...)...); err != nil {
s.writeError(c, http.StatusBadRequest, err.Error(), err)
return
}
for _, san := range item.SANs {
if san == item.Name {
continue
}
if err := s.validateDomainAliyunAuthorization(c.Request.Context(), san); err != nil {
s.writeError(c, http.StatusBadRequest, err.Error(), err)
return
}
}
if err := s.repository.Create(c.Request.Context(), item); err != nil {
if repository.IsConflict(err) {
s.writeError(c, http.StatusConflict, "域名已经存在", err)
@@ -507,19 +510,10 @@ func (s *Server) updateDomain(c *gin.Context) {
s.writeError(c, http.StatusBadRequest, "域名配置无效", err)
return
}
if err := s.validateDomainAliyunAuthorization(c.Request.Context(), item.Name); err != nil {
if err := s.validateDomainAliyunAuthorization(c.Request.Context(), append([]string{item.Name}, item.SANs...)...); err != nil {
s.writeError(c, http.StatusBadRequest, err.Error(), err)
return
}
for _, san := range item.SANs {
if san == item.Name {
continue
}
if err := s.validateDomainAliyunAuthorization(c.Request.Context(), san); err != nil {
s.writeError(c, http.StatusBadRequest, err.Error(), err)
return
}
}
item.ID = existing.ID
item.CreatedAt = existing.CreatedAt
item.Status = "pending"
+24 -4
View File
@@ -12,6 +12,7 @@ import (
"git.pcux.cn/xuans/Scert/backend/internal/certificate"
"git.pcux.cn/xuans/Scert/backend/internal/config"
"git.pcux.cn/xuans/Scert/backend/internal/dnsprovider"
)
type settingsView struct {
@@ -54,9 +55,11 @@ type settingsACMEView struct {
}
type settingsDNSView struct {
Provider string `json:"provider"`
VerificationState string `json:"verification_state"`
CredentialConfigured bool `json:"credential_configured"`
Provider string `json:"provider"`
VerificationState string `json:"verification_state"`
CredentialConfigured bool `json:"credential_configured"`
UserScope *dnsprovider.AliyunScope `json:"user_scope,omitempty"`
ScopeMessage string `json:"scope_message,omitempty"`
}
type settingsNotificationView struct {
@@ -163,7 +166,24 @@ func (s *Server) getSettings(c *gin.Context) {
s.configMu.RLock()
cfg := s.config
s.configMu.RUnlock()
c.JSON(http.StatusOK, settingsViewFromConfig(cfg))
view := settingsViewFromConfig(cfg)
if cfg.DNS.Provider == dnsprovider.Aliyun {
credentials, err := s.readDNSCredentials(c.Request.Context(), cfg.DNS.CredentialRef)
if err == nil {
scope, scopeErr := dnsprovider.ParseAliyunScope(credentials)
if scopeErr == nil {
view.DNS.UserScope = &scope
} else {
view.DNS.ScopeMessage = scopeErr.Error()
}
} else {
view.DNS.ScopeMessage = "无法读取已保存授权范围,请检查凭据存储或重新验证"
}
if view.DNS.UserScope == nil {
view.DNS.VerificationState = "scope_required"
}
}
c.JSON(http.StatusOK, view)
}
func (s *Server) updateSettings(c *gin.Context) {
+46 -2
View File
@@ -3,6 +3,7 @@ package httpapi
import (
"bytes"
"context"
"database/sql"
"encoding/json"
"net/http"
"net/http/httptest"
@@ -134,16 +135,59 @@ func serveUserRequest(server *Server, cookie *http.Cookie, method, path, body st
func httpUserSessionCookie(server *Server, userID, role string) *http.Cookie {
token := userID + "-session"
now := time.Now()
now := server.now()
hash, err := bcrypt.GenerateFromPassword([]byte("FixturePass123"), bcrypt.MinCost)
if err != nil {
panic(err)
}
user := repository.User{ID: userID, Username: userID, Role: role, Status: repository.UserStatusActive, PasswordHash: string(hash)}
if userID == "primary-super-admin" {
user.Username = server.config.Admin.Username
user.Email = server.config.Admin.Email
user.PasswordHash = server.config.Admin.PasswordHash
} else {
if server.users == nil {
server.users = &sessionFixtureUsers{items: make(map[string]repository.User)}
}
if stored, err := server.users.GetUserByID(context.Background(), userID); err == nil {
user = stored
} else if err := server.users.CreateUser(context.Background(), user); err != nil {
panic(err)
}
}
server.authMu.Lock()
server.authSessions[token] = authSession{
UserID: userID, Username: userID, Role: role,
UserID: user.ID, Username: user.Username, Email: user.Email, Role: user.Role, PasswordHash: user.PasswordHash,
ExpiresAt: now.Add(time.Hour), AbsoluteExpiresAt: now.Add(2 * time.Hour),
}
server.authMu.Unlock()
return &http.Cookie{Name: authCookieName, Value: token, Path: "/"}
}
type sessionFixtureUsers struct {
repository.UserRepository
items map[string]repository.User
}
func (r *sessionFixtureUsers) GetUserByID(_ context.Context, id string) (repository.User, error) {
if user, ok := r.items[id]; ok {
return user, nil
}
return repository.User{}, sql.ErrNoRows
}
func (r *sessionFixtureUsers) CreateUser(_ context.Context, user repository.User) error {
r.items[user.ID] = user
return nil
}
func (r *sessionFixtureUsers) EnsureSuperAdmin(_ context.Context, user repository.User) error {
user.Role = repository.UserRoleSuperAdmin
user.Status = repository.UserStatusActive
r.items[user.ID] = user
return nil
}
func httpUserPasswordHash(t *testing.T, password string) string {
t.Helper()
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost)