forked from mtusi2026/mtusi2026lab7
lab7: безопасность, mTLS, OpenBao и PKI lifecycle
This commit is contained in:
@@ -2,6 +2,7 @@ package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
@@ -13,6 +14,7 @@ import (
|
||||
|
||||
type Repository interface {
|
||||
Credentials(ctx context.Context, username string) (domain.UserCredentials, error)
|
||||
UpdatePasswordHash(ctx context.Context, userID uuid.UUID, oldHash, newHash string) (bool, error)
|
||||
Create(ctx context.Context, session domain.NewSession) (domain.Session, error)
|
||||
Resolve(ctx context.Context, tokenHash []byte) (domain.Session, error)
|
||||
Revoke(ctx context.Context, userID uuid.UUID, tokenHash []byte) error
|
||||
@@ -36,12 +38,38 @@ func NewService(sessions Repository, tokens Tokens, ttl time.Duration) *Service
|
||||
func (s *Service) Authenticate(ctx context.Context, username, plain string) (domain.User, error) {
|
||||
credentials, err := s.sessions.Credentials(ctx, username)
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrUnauthenticated) {
|
||||
// Spend the same derivation budget as a real credential check so
|
||||
// an unknown username does not answer measurably faster.
|
||||
if dummyErr := password.DummyVerify(plain); dummyErr != nil {
|
||||
return domain.User{}, fmt.Errorf("verify password: %w", dummyErr)
|
||||
}
|
||||
}
|
||||
return domain.User{}, fmt.Errorf("authenticate: %w", err)
|
||||
}
|
||||
|
||||
if !password.Verify(plain, credentials.PasswordHash) {
|
||||
verified, err := password.Verify(plain, credentials.PasswordHash)
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("verify password: %w", err)
|
||||
}
|
||||
if !verified.Match {
|
||||
return domain.User{}, fmt.Errorf("authenticate: %w", domain.ErrUnauthenticated)
|
||||
}
|
||||
if verified.NeedsRehash {
|
||||
hash, err := password.Hash(plain)
|
||||
if errors.Is(err, password.ErrBusy) {
|
||||
// The credential is valid; a contended optional upgrade must not
|
||||
// turn a successful login into a failure.
|
||||
return credentials.User, nil
|
||||
}
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("rehash password: %w", err)
|
||||
}
|
||||
// A concurrent upgrade wins the CAS; it must not invalidate this login.
|
||||
if _, err := s.sessions.UpdatePasswordHash(ctx, credentials.User.ID, credentials.PasswordHash, hash); err != nil {
|
||||
return domain.User{}, fmt.Errorf("upgrade password: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return credentials.User, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user