Перенесите реализацию ЛР 4 на стенд ЛР 5
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/httpx"
|
||||
"messenger/internal/user"
|
||||
)
|
||||
|
||||
// Challenges sent with every 401: Basic on the login endpoint, Bearer on
|
||||
// every protected one.
|
||||
const (
|
||||
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
bearerChallenge = `Bearer realm="messenger"`
|
||||
)
|
||||
|
||||
var errCredentialsRequired = apperr.Unauthorized("basic credentials are required")
|
||||
|
||||
type Handler struct {
|
||||
sessions *Service
|
||||
}
|
||||
|
||||
func NewHandler(sessions *Service) *Handler {
|
||||
return &Handler{sessions: sessions}
|
||||
}
|
||||
|
||||
// Register mounts login on the public router and logout on the router
|
||||
// guarded by RequireSession.
|
||||
func (h *Handler) Register(public, protected gin.IRouter) {
|
||||
public.POST("/auth/sessions", h.login)
|
||||
protected.DELETE("/auth/sessions/current", h.logout)
|
||||
}
|
||||
|
||||
type sessionResponse struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
User user.Response `json:"user"`
|
||||
}
|
||||
|
||||
// login accepts only the Authorization header; the body is not read.
|
||||
// BasicAuth splits at the first colon, so a password may contain colons.
|
||||
func (h *Handler) login(c *gin.Context) {
|
||||
username, password, ok := c.Request.BasicAuth()
|
||||
if !ok {
|
||||
unauthorized(c, basicChallenge, errCredentialsRequired)
|
||||
return
|
||||
}
|
||||
issued, err := h.sessions.Login(c.Request.Context(), username, password)
|
||||
if err != nil {
|
||||
unauthorized(c, basicChallenge, err)
|
||||
return
|
||||
}
|
||||
httpx.JSON(c, http.StatusCreated, sessionResponse{
|
||||
Token: issued.Token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: httpx.Timestamp(issued.ExpiresAt),
|
||||
User: user.ToResponse(issued.User),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handler) logout(c *gin.Context) {
|
||||
token, ok := c.Get(keyToken)
|
||||
if !ok {
|
||||
httpx.Error(c, errors.New("logout route is missing the RequireSession middleware"))
|
||||
return
|
||||
}
|
||||
if err := h.sessions.Logout(c.Request.Context(), token.(string)); err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
// Status alone is buffered by gin; writing the header now sends the 204
|
||||
// with an empty body.
|
||||
c.Status(http.StatusNoContent)
|
||||
c.Writer.WriteHeaderNow()
|
||||
}
|
||||
|
||||
// unauthorized adds the challenge only to a 401: an unavailable store is a
|
||||
// 503 and must not invite the client to retry its credentials.
|
||||
func unauthorized(c *gin.Context, challenge string, err error) {
|
||||
if apperr.KindOf(err) == apperr.KindUnauthorized {
|
||||
c.Header("WWW-Authenticate", challenge)
|
||||
}
|
||||
httpx.Error(c, err)
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package auth_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"messenger/internal/testenv"
|
||||
)
|
||||
|
||||
var (
|
||||
db *testenv.DB
|
||||
kv *testenv.KV
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
ctx := context.Background()
|
||||
var err error
|
||||
if db, err = testenv.StartPostgres(ctx); err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if kv, err = testenv.StartValkey(ctx); err != nil {
|
||||
db.Close()
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
code := m.Run()
|
||||
kv.Close()
|
||||
db.Close()
|
||||
os.Exit(code)
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"messenger/internal/platform/httpx"
|
||||
)
|
||||
|
||||
const keyToken = "messenger.session_token"
|
||||
|
||||
// RequireSession admits a request only with Authorization: Bearer <token> of
|
||||
// a live session and records its owner for the handlers behind it. Any other
|
||||
// identification, including Basic credentials and X-User-Id, is ignored, so
|
||||
// it can neither grant access nor change the caller.
|
||||
func RequireSession(sessions *Service) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
token, ok := bearerToken(c.GetHeader("Authorization"))
|
||||
if !ok {
|
||||
unauthorized(c, bearerChallenge, ErrUnauthenticated)
|
||||
return
|
||||
}
|
||||
userID, err := sessions.Authenticate(c.Request.Context(), token)
|
||||
if err != nil {
|
||||
unauthorized(c, bearerChallenge, err)
|
||||
return
|
||||
}
|
||||
httpx.SetUserID(c, userID)
|
||||
c.Set(keyToken, token)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// bearerToken parses "Bearer <token>": the scheme is case-insensitive and
|
||||
// may be followed by several spaces (RFC 7235); the token itself never
|
||||
// contains whitespace.
|
||||
func bearerToken(header string) (string, bool) {
|
||||
scheme, rest, found := strings.Cut(header, " ")
|
||||
if !found || !strings.EqualFold(scheme, "Bearer") {
|
||||
return "", false
|
||||
}
|
||||
token := strings.TrimLeft(rest, " ")
|
||||
if token == "" || strings.ContainsAny(token, " \t") {
|
||||
return "", false
|
||||
}
|
||||
return token, true
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
// Create stores the session until its absolute ExpiresAt.
|
||||
Create(ctx context.Context, s Session) error
|
||||
// UserID returns the owner of a live session, or ErrUnauthenticated when
|
||||
// the token is unknown, expired or revoked: the store cannot tell these
|
||||
// apart, and the client must not either.
|
||||
UserID(ctx context.Context, tokenHash string) (uuid.UUID, error)
|
||||
// Delete revokes the session; deleting a missing one is not an error.
|
||||
Delete(ctx context.Context, tokenHash string) error
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/user"
|
||||
)
|
||||
|
||||
var ErrUnauthenticated = apperr.Unauthorized("a valid bearer token is required")
|
||||
|
||||
// Credentials is what this module needs from the users module: the user
|
||||
// whose password matches, or user.ErrInvalidCredentials.
|
||||
type Credentials interface {
|
||||
Authenticate(ctx context.Context, username, password string) (user.User, error)
|
||||
}
|
||||
|
||||
// Issued is a new session as the client sees it; Token is shown only here.
|
||||
type Issued struct {
|
||||
Token string
|
||||
ExpiresAt time.Time
|
||||
User user.User
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
users Credentials
|
||||
sessions Repository
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
func NewService(users Credentials, sessions Repository, ttl time.Duration) *Service {
|
||||
return &Service{users: users, sessions: sessions, ttl: ttl}
|
||||
}
|
||||
|
||||
// Login checks the credentials first, so a store outage never hands out a
|
||||
// token without a stored session. The expiry is fixed here and never
|
||||
// extended; it is truncated to milliseconds, the precision of both the API
|
||||
// timestamps and the store.
|
||||
func (s *Service) Login(ctx context.Context, username, password string) (Issued, error) {
|
||||
u, err := s.users.Authenticate(ctx, username, password)
|
||||
if err != nil {
|
||||
return Issued{}, err
|
||||
}
|
||||
token := newToken()
|
||||
expiresAt := time.Now().Add(s.ttl).Truncate(time.Millisecond).UTC()
|
||||
if err := s.sessions.Create(ctx, Session{TokenHash: HashToken(token), UserID: u.ID, ExpiresAt: expiresAt}); err != nil {
|
||||
return Issued{}, err
|
||||
}
|
||||
return Issued{Token: token, ExpiresAt: expiresAt, User: u}, nil
|
||||
}
|
||||
|
||||
// Authenticate returns the owner of the token's live session or
|
||||
// ErrUnauthenticated. A store failure stays an unavailability, never
|
||||
// ErrUnauthenticated: an outage must not look like a bad token to the client.
|
||||
func (s *Service) Authenticate(ctx context.Context, token string) (uuid.UUID, error) {
|
||||
return s.sessions.UserID(ctx, HashToken(token))
|
||||
}
|
||||
|
||||
func (s *Service) Logout(ctx context.Context, token string) error {
|
||||
return s.sessions.Delete(ctx, HashToken(token))
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package auth_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"messenger/internal/auth"
|
||||
authstore "messenger/internal/auth/store"
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/user"
|
||||
userstore "messenger/internal/user/store"
|
||||
)
|
||||
|
||||
const pw = "correct-horse-battery"
|
||||
|
||||
type fixture struct {
|
||||
ctx context.Context
|
||||
svc *auth.Service
|
||||
alice user.User
|
||||
}
|
||||
|
||||
// newFixture wires the real users service and session store over empty
|
||||
// databases and registers alice.
|
||||
func newFixture(t *testing.T, ttl time.Duration) fixture {
|
||||
t.Helper()
|
||||
db.Reset(t)
|
||||
kv.Reset(t)
|
||||
ctx := context.Background()
|
||||
users := user.NewService(userstore.NewUsers(db.Pool))
|
||||
alice, err := users.Register(ctx, "alice", "Алиса", pw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return fixture{ctx: ctx, svc: auth.NewService(users, authstore.NewSessions(kv.Client), ttl), alice: alice}
|
||||
}
|
||||
|
||||
func TestLoginIssuesOpaqueTokenBackedByStoredSession(t *testing.T) {
|
||||
f := newFixture(t, time.Hour)
|
||||
before := time.Now()
|
||||
issued, err := f.svc.Login(f.ctx, "alice", pw)
|
||||
after := time.Now()
|
||||
if err != nil {
|
||||
t.Fatalf("Login: %v", err)
|
||||
}
|
||||
raw, err := base64.RawURLEncoding.DecodeString(issued.Token)
|
||||
if err != nil || len(raw) != 32 {
|
||||
t.Fatalf("token %q must be 32 random bytes in base64url, got %d bytes, %v", issued.Token, len(raw), err)
|
||||
}
|
||||
if strings.Contains(issued.Token, f.alice.ID.String()) || strings.Contains(issued.Token, "alice") {
|
||||
t.Fatal("token must not carry the identity")
|
||||
}
|
||||
if issued.User != f.alice {
|
||||
t.Fatalf("User = %+v, want alice", issued.User)
|
||||
}
|
||||
if issued.ExpiresAt.Before(before.Add(time.Hour).Add(-time.Millisecond)) || issued.ExpiresAt.After(after.Add(time.Hour)) {
|
||||
t.Fatalf("ExpiresAt = %v, want login time + 1h", issued.ExpiresAt)
|
||||
}
|
||||
|
||||
key := "session:" + auth.HashToken(issued.Token)
|
||||
owner, err := kv.Client.Get(f.ctx, key).Result()
|
||||
if err != nil || owner != f.alice.ID.String() {
|
||||
t.Fatalf("stored owner = %q, %v; want alice", owner, err)
|
||||
}
|
||||
expireAt, err := kv.Client.PExpireTime(f.ctx, key).Result()
|
||||
if err != nil || expireAt != time.Duration(issued.ExpiresAt.UnixMilli())*time.Millisecond {
|
||||
t.Fatalf("store expiry = %v, %v; want the absolute ExpiresAt %d ms", expireAt, err, issued.ExpiresAt.UnixMilli())
|
||||
}
|
||||
keys, err := kv.Client.Keys(f.ctx, "*").Result()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, k := range keys {
|
||||
if strings.Contains(k, issued.Token) {
|
||||
t.Fatal("the raw token must never be stored")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginWithBadCredentialsCreatesNoSession(t *testing.T) {
|
||||
f := newFixture(t, time.Hour)
|
||||
for name, in := range map[string][2]string{
|
||||
"wrong password": {"alice", pw + "!"},
|
||||
"unknown user": {"mallory", pw},
|
||||
} {
|
||||
if _, err := f.svc.Login(f.ctx, in[0], in[1]); !errors.Is(err, user.ErrInvalidCredentials) {
|
||||
t.Errorf("%s: err = %v, want ErrInvalidCredentials", name, err)
|
||||
}
|
||||
}
|
||||
if n, err := kv.Client.DBSize(f.ctx).Result(); err != nil || n != 0 {
|
||||
t.Fatalf("sessions = %d, %v; want none", n, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthenticateResolvesTheOwner(t *testing.T) {
|
||||
f := newFixture(t, time.Hour)
|
||||
first, _ := f.svc.Login(f.ctx, "alice", pw)
|
||||
second, _ := f.svc.Login(f.ctx, "alice", pw)
|
||||
if first.Token == second.Token {
|
||||
t.Fatal("every login must get its own token")
|
||||
}
|
||||
for _, token := range []string{first.Token, second.Token} {
|
||||
id, err := f.svc.Authenticate(f.ctx, token)
|
||||
if err != nil || id != f.alice.ID {
|
||||
t.Fatalf("Authenticate = %v, %v; want alice", id, err)
|
||||
}
|
||||
}
|
||||
_, err := f.svc.Authenticate(f.ctx, "unknown-token")
|
||||
if !errors.Is(err, auth.ErrUnauthenticated) || apperr.KindOf(err) != apperr.KindUnauthorized {
|
||||
t.Fatalf("unknown token: err = %v, want ErrUnauthenticated", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogoutRevokesOnlyThatSession(t *testing.T) {
|
||||
f := newFixture(t, time.Hour)
|
||||
first, _ := f.svc.Login(f.ctx, "alice", pw)
|
||||
second, _ := f.svc.Login(f.ctx, "alice", pw)
|
||||
if err := f.svc.Logout(f.ctx, first.Token); err != nil {
|
||||
t.Fatalf("Logout: %v", err)
|
||||
}
|
||||
if _, err := f.svc.Authenticate(f.ctx, first.Token); !errors.Is(err, auth.ErrUnauthenticated) {
|
||||
t.Fatalf("revoked token: err = %v, want ErrUnauthenticated", err)
|
||||
}
|
||||
if id, err := f.svc.Authenticate(f.ctx, second.Token); err != nil || id != f.alice.ID {
|
||||
t.Fatalf("other session: %v, %v; want still valid", id, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Valkey enforces the expiry by the Docker VM clock, which may lag this host
|
||||
// by a fraction of a second, so the expiry is awaited with a tolerance.
|
||||
func TestSessionExpiresAfterTTL(t *testing.T) {
|
||||
const clockTolerance = 3 * time.Second
|
||||
f := newFixture(t, time.Second)
|
||||
issued, err := f.svc.Login(f.ctx, "alice", pw)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := f.svc.Authenticate(f.ctx, issued.Token); err != nil {
|
||||
t.Fatalf("fresh session: %v", err)
|
||||
}
|
||||
time.Sleep(time.Until(issued.ExpiresAt))
|
||||
deadline := time.Now().Add(clockTolerance)
|
||||
for {
|
||||
_, err := f.svc.Authenticate(f.ctx, issued.Token)
|
||||
if errors.Is(err, auth.ErrUnauthenticated) {
|
||||
return
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("expired session: err = %v %v after ExpiresAt, want ErrUnauthenticated", err, clockTolerance)
|
||||
}
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// Package auth authenticates callers.
|
||||
//
|
||||
// A login with Basic credentials creates a server-side session and returns an
|
||||
// opaque bearer token; every protected request presents the token, and logout
|
||||
// deletes the session, which revokes the token at once. The store keeps only
|
||||
// the SHA-256 of a token: a token is a random 256-bit value, so a fast digest
|
||||
// cannot be reversed by guessing, and a leaked store yields no usable tokens.
|
||||
// Passwords need the opposite treatment (a slow KDF), see platform/password.
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Session struct {
|
||||
TokenHash string
|
||||
UserID uuid.UUID
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
// newToken returns 32 random bytes in base64url: 43 characters, 256 bits.
|
||||
func newToken() string {
|
||||
raw := make([]byte, 32)
|
||||
// Since Go 1.24 crypto/rand.Read never returns an error.
|
||||
_, _ = rand.Read(raw)
|
||||
return base64.RawURLEncoding.EncodeToString(raw)
|
||||
}
|
||||
|
||||
// HashToken is the key under which a token's session is stored.
|
||||
func HashToken(token string) string {
|
||||
sum := sha256.Sum256([]byte(token))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// Package store holds the session store implementations.
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"messenger/internal/auth"
|
||||
"messenger/internal/platform/apperr"
|
||||
)
|
||||
|
||||
const keyPrefix = "session:"
|
||||
|
||||
// Sessions keeps one key per session, session:<sha256 of token>, holding the
|
||||
// owner's id. Valkey expires the key itself, so no cleanup job is needed.
|
||||
type Sessions struct {
|
||||
client *redis.Client
|
||||
}
|
||||
|
||||
var _ auth.Repository = (*Sessions)(nil)
|
||||
|
||||
func NewSessions(client *redis.Client) *Sessions {
|
||||
return &Sessions{client: client}
|
||||
}
|
||||
|
||||
// Create sets an absolute expiry (EXAT/PXAT): a restart of the store replays
|
||||
// it from the append-only file and does not extend the session.
|
||||
func (r *Sessions) Create(ctx context.Context, s auth.Session) error {
|
||||
err := r.client.SetArgs(ctx, keyPrefix+s.TokenHash, s.UserID.String(), redis.SetArgs{ExpireAt: s.ExpiresAt}).Err()
|
||||
if err != nil {
|
||||
return unavailable(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Sessions) UserID(ctx context.Context, tokenHash string) (uuid.UUID, error) {
|
||||
raw, err := r.client.Get(ctx, keyPrefix+tokenHash).Result()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return uuid.Nil, auth.ErrUnauthenticated
|
||||
}
|
||||
if err != nil {
|
||||
return uuid.Nil, unavailable(err)
|
||||
}
|
||||
id, err := uuid.Parse(raw)
|
||||
if err != nil {
|
||||
return uuid.Nil, fmt.Errorf("session holds a malformed user id: %w", err)
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (r *Sessions) Delete(ctx context.Context, tokenHash string) error {
|
||||
if err := r.client.Del(ctx, keyPrefix+tokenHash).Err(); err != nil {
|
||||
return unavailable(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func unavailable(err error) error {
|
||||
return apperr.Wrap(apperr.KindUnavailable, "session store unavailable", err)
|
||||
}
|
||||
Reference in New Issue
Block a user