forked from mtusi2026/mtusi2026lab5
feat: process attachments through durable versioned jobs
This commit is contained in:
@@ -0,0 +1,123 @@
|
||||
// Package authentication validates credentials and owns the session lifecycle.
|
||||
package authentication
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/service"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/service/production"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
minimumPasswordRunes = 12
|
||||
maximumPasswordRunes = 128
|
||||
tokenBytes = 32
|
||||
)
|
||||
|
||||
// Service performs password and session operations through explicit boundaries.
|
||||
type Service struct {
|
||||
accounts service.Accounts
|
||||
passwords service.Passwords
|
||||
ttl time.Duration
|
||||
dummyHash string
|
||||
}
|
||||
|
||||
// New validates dependencies and prepares the unknown-account verification hash.
|
||||
func New(accounts service.Accounts, passwords service.Passwords, ttl time.Duration) (*Service, error) {
|
||||
if accounts == nil || passwords == nil || ttl <= 0 {
|
||||
return nil, fmt.Errorf("accounts, passwords and positive session TTL are required")
|
||||
}
|
||||
dummyHash, err := passwords.Hash("unknown-account-dummy-password")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &Service{accounts: accounts, passwords: passwords, ttl: ttl, dummyHash: dummyHash}, nil
|
||||
}
|
||||
|
||||
// Register checks profile and Unicode password bounds before hashing and persistence.
|
||||
func (s *Service) Register(ctx context.Context, request dto.UsersCreateRequestDTO, password string) (dto.UserDTO, error) {
|
||||
user, err := production.PrepareUser(request)
|
||||
if err != nil || !validPassword(password) {
|
||||
return dto.UserDTO{}, service.ErrInvalid
|
||||
}
|
||||
hash, err := s.passwords.Hash(password)
|
||||
if err != nil {
|
||||
return dto.UserDTO{}, err
|
||||
}
|
||||
user, err = s.accounts.Register(ctx, user, hash)
|
||||
if errors.Is(err, store.ErrConflict) {
|
||||
return dto.UserDTO{}, service.ErrConflict
|
||||
}
|
||||
return user, err
|
||||
}
|
||||
|
||||
// Login verifies credentials uniformly and persists a new session before returning its token.
|
||||
func (s *Service) Login(ctx context.Context, username, password string) (dto.SessionDTO, error) {
|
||||
if !validPassword(password) {
|
||||
return dto.SessionDTO{}, service.ErrUnauthorized
|
||||
}
|
||||
user, hash, err := s.accounts.Credentials(ctx, username)
|
||||
if err != nil && !errors.Is(err, store.ErrNotFound) {
|
||||
return dto.SessionDTO{}, err
|
||||
}
|
||||
missing := errors.Is(err, store.ErrNotFound)
|
||||
if missing {
|
||||
hash = s.dummyHash
|
||||
}
|
||||
if !s.passwords.Verify(hash, password) || missing {
|
||||
return dto.SessionDTO{}, service.ErrUnauthorized
|
||||
}
|
||||
random := make([]byte, tokenBytes)
|
||||
if _, err := rand.Read(random); err != nil {
|
||||
return dto.SessionDTO{}, err
|
||||
}
|
||||
token := base64.RawURLEncoding.EncodeToString(random)
|
||||
expiry := time.Now().UTC().Add(s.ttl)
|
||||
if err := s.accounts.SaveSession(ctx, digest(token), user.ID, expiry); err != nil {
|
||||
return dto.SessionDTO{}, err
|
||||
}
|
||||
return dto.SessionDTO{Token: token, ExpiresAt: expiry, User: user}, nil
|
||||
}
|
||||
|
||||
// Authenticate checks absolute expiry in the source of truth on every request.
|
||||
func (s *Service) Authenticate(ctx context.Context, token string) (string, error) {
|
||||
decoded, err := base64.RawURLEncoding.DecodeString(token)
|
||||
if err != nil || len(decoded) != tokenBytes {
|
||||
return "", service.ErrUnauthorized
|
||||
}
|
||||
id, err := s.accounts.SessionUser(ctx, digest(token))
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
return "", service.ErrUnauthorized
|
||||
}
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return id.String(), nil
|
||||
}
|
||||
|
||||
// Logout removes the current session from the authoritative store.
|
||||
func (s *Service) Logout(ctx context.Context, token string) error {
|
||||
return s.accounts.RevokeSession(ctx, digest(token))
|
||||
}
|
||||
|
||||
// digest produces the storage key without persisting the bearer secret.
|
||||
func digest(token string) string {
|
||||
hash := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(hash[:])
|
||||
}
|
||||
|
||||
// validPassword enforces the contract in Unicode code points without truncation.
|
||||
func validPassword(password string) bool {
|
||||
count := utf8.RuneCountInString(password)
|
||||
return utf8.ValidString(password) && count >= minimumPasswordRunes && count <= maximumPasswordRunes
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package authentication
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/model/dto"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/service"
|
||||
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab5/internal/store"
|
||||
)
|
||||
|
||||
type accountFixture struct {
|
||||
user dto.UserDTO
|
||||
hash string
|
||||
tokenHash string
|
||||
expiry time.Time
|
||||
failure error
|
||||
registerFailure error
|
||||
saveFailure error
|
||||
}
|
||||
|
||||
// Register captures one synthetic account or a prescribed persistence failure.
|
||||
func (f *accountFixture) Register(_ context.Context, user dto.UserDTO, hash string) (dto.UserDTO, error) {
|
||||
f.user = user
|
||||
f.hash = hash
|
||||
return user, f.registerFailure
|
||||
}
|
||||
|
||||
// Credentials returns the fixture account and its password encoding.
|
||||
func (f *accountFixture) Credentials(context.Context, string) (dto.UserDTO, string, error) {
|
||||
return f.user, f.hash, f.failure
|
||||
}
|
||||
|
||||
// SaveSession captures the digest and absolute expiry without storing the raw token.
|
||||
func (f *accountFixture) SaveSession(_ context.Context, hash string, _ uuid.UUID, expiry time.Time) error {
|
||||
f.tokenHash = hash
|
||||
f.expiry = expiry
|
||||
return f.saveFailure
|
||||
}
|
||||
|
||||
// SessionUser implements expiry and revocation for the service unit fixture.
|
||||
func (f *accountFixture) SessionUser(_ context.Context, hash string) (uuid.UUID, error) {
|
||||
if f.failure != nil {
|
||||
return uuid.Nil, f.failure
|
||||
}
|
||||
if hash != f.tokenHash || !f.expiry.After(time.Now()) {
|
||||
return uuid.Nil, store.ErrNotFound
|
||||
}
|
||||
return f.user.ID, nil
|
||||
}
|
||||
|
||||
// RevokeSession invalidates the fixture digest.
|
||||
func (f *accountFixture) RevokeSession(context.Context, string) error {
|
||||
f.tokenHash = ""
|
||||
return f.failure
|
||||
}
|
||||
|
||||
type passwordFixture struct {
|
||||
failure error
|
||||
}
|
||||
|
||||
// Hash creates an intentionally noncryptographic encoding for service-only unit tests.
|
||||
func (f passwordFixture) Hash(password string) (string, error) {
|
||||
return "fixture:" + password, f.failure
|
||||
}
|
||||
|
||||
// Verify compares only test fixture encodings; production uses Argon2id.
|
||||
func (passwordFixture) Verify(encoded, password string) bool {
|
||||
return encoded == "fixture:"+password
|
||||
}
|
||||
|
||||
// authFixture assembles deterministic service boundaries.
|
||||
func authFixture(t *testing.T) (*Service, *accountFixture) {
|
||||
t.Helper()
|
||||
accounts := &accountFixture{user: dto.UserDTO{ID: uuid.New(), Username: "alice"}, hash: "fixture:synthetic-password"}
|
||||
s, err := New(accounts, passwordFixture{}, time.Hour)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return s, accounts
|
||||
}
|
||||
|
||||
// TestRegisterValidatesPassword checks contract boundaries without truncation.
|
||||
func TestRegisterValidatesPassword(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
password string
|
||||
valid bool
|
||||
}{
|
||||
{"short", "short", false},
|
||||
{"minimum", strings.Repeat("a", 12), true},
|
||||
{"unicode maximum", strings.Repeat("🔐", 128), true},
|
||||
{"too long", strings.Repeat("a", 129), false},
|
||||
{"invalid UTF8", strings.Repeat("a", 12) + "\xff", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s, _ := authFixture(t)
|
||||
_, err := s.Register(t.Context(), dto.UsersCreateRequestDTO{Username: "alice", DisplayName: "Alice"}, tc.password)
|
||||
if (err == nil) != tc.valid {
|
||||
t.Fatalf("unexpected registration result: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestRegisterConflictMapsToApplicationError verifies uniqueness error translation.
|
||||
func TestRegisterConflictMapsToApplicationError(t *testing.T) {
|
||||
s, accounts := authFixture(t)
|
||||
accounts.registerFailure = store.ErrConflict
|
||||
_, err := s.Register(t.Context(), dto.UsersCreateRequestDTO{Username: "alice", DisplayName: "Alice"}, "synthetic-password")
|
||||
if !errors.Is(err, service.ErrConflict) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRegisterHashFailurePreservesCause checks KDF failures before persistence.
|
||||
func TestRegisterHashFailurePreservesCause(t *testing.T) {
|
||||
s, _ := authFixture(t)
|
||||
failure := errors.New("KDF unavailable")
|
||||
s.passwords = passwordFixture{failure: failure}
|
||||
_, err := s.Register(t.Context(), dto.UsersCreateRequestDTO{Username: "alice", DisplayName: "Alice"}, "synthetic-password")
|
||||
if !errors.Is(err, failure) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoginPersistsOnlyTokenDigest checks issued entropy, owner and deadline together.
|
||||
func TestLoginPersistsOnlyTokenDigest(t *testing.T) {
|
||||
s, accounts := authFixture(t)
|
||||
session, err := s.Login(t.Context(), "alice", "synthetic-password")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if session.Token == accounts.tokenHash || len(accounts.tokenHash) != 64 || session.User.ID != accounts.user.ID || !session.ExpiresAt.Equal(accounts.expiry) {
|
||||
t.Fatal("invalid issued session")
|
||||
}
|
||||
id, err := s.Authenticate(t.Context(), session.Token)
|
||||
if err != nil || id != accounts.user.ID.String() {
|
||||
t.Fatalf("session does not authenticate its owner: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoginRejectsCredentials checks independent authentication rejection scenarios.
|
||||
func TestLoginRejectsCredentials(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
password string
|
||||
failure error
|
||||
expected error
|
||||
}{
|
||||
{"short password", "short", nil, service.ErrUnauthorized},
|
||||
{"wrong password", "incorrect-password", nil, service.ErrUnauthorized},
|
||||
{"missing account", "synthetic-password", store.ErrNotFound, service.ErrUnauthorized},
|
||||
{"database unavailable", "synthetic-password", context.DeadlineExceeded, context.DeadlineExceeded},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
s, accounts := authFixture(t)
|
||||
accounts.failure = tc.failure
|
||||
_, err := s.Login(t.Context(), "alice", tc.password)
|
||||
if !errors.Is(err, tc.expected) {
|
||||
t.Fatalf("expected %v, got %v", tc.expected, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestLoginDoesNotReturnUnpersistedSession checks failure after successful password verification.
|
||||
func TestLoginDoesNotReturnUnpersistedSession(t *testing.T) {
|
||||
s, accounts := authFixture(t)
|
||||
accounts.saveFailure = context.DeadlineExceeded
|
||||
session, err := s.Login(t.Context(), "alice", "synthetic-password")
|
||||
if !errors.Is(err, context.DeadlineExceeded) || session.Token != "" {
|
||||
t.Fatal("unpersisted session escaped")
|
||||
}
|
||||
}
|
||||
|
||||
// TestAuthenticateRejectsUnknownToken checks malformed and correctly encoded unknown tokens.
|
||||
func TestAuthenticateRejectsUnknownToken(t *testing.T) {
|
||||
for _, token := range []string{"", "%%%", strings.Repeat("A", 43)} {
|
||||
t.Run(token, func(t *testing.T) {
|
||||
s, _ := authFixture(t)
|
||||
if _, err := s.Authenticate(t.Context(), token); !errors.Is(err, service.ErrUnauthorized) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAuthenticatePropagatesDatabaseFailure prevents trusting a token during an outage.
|
||||
func TestAuthenticatePropagatesDatabaseFailure(t *testing.T) {
|
||||
s, accounts := authFixture(t)
|
||||
accounts.failure = context.DeadlineExceeded
|
||||
if _, err := s.Authenticate(t.Context(), strings.Repeat("A", 43)); !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestLogoutRevokesIssuedToken checks that the same token cannot be reused.
|
||||
func TestLogoutRevokesIssuedToken(t *testing.T) {
|
||||
s, _ := authFixture(t)
|
||||
session, err := s.Login(t.Context(), "alice", "synthetic-password")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Logout(t.Context(), session.Token); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := s.Authenticate(t.Context(), session.Token); !errors.Is(err, service.ErrUnauthorized) {
|
||||
t.Fatal("revoked token authenticated")
|
||||
}
|
||||
}
|
||||
|
||||
// TestNewRejectsIncompleteDependencies checks constructor validation and KDF startup failure.
|
||||
func TestNewRejectsIncompleteDependencies(t *testing.T) {
|
||||
t.Run("missing accounts", func(t *testing.T) {
|
||||
if _, err := New(nil, passwordFixture{}, time.Hour); err == nil {
|
||||
t.Fatal("missing accounts accepted")
|
||||
}
|
||||
})
|
||||
t.Run("hash failure", func(t *testing.T) {
|
||||
if _, err := New(&accountFixture{}, passwordFixture{failure: context.Canceled}, time.Hour); !errors.Is(err, context.Canceled) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user