232 lines
8.9 KiB
Go
232 lines
8.9 KiB
Go
package v1
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"log/slog"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/ogen-go/ogen/ogenerrors"
|
|
|
|
"lincodex/backend/internal/adapter/primary/http/api"
|
|
httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware"
|
|
"lincodex/backend/internal/adapter/primary/http/problem"
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/usecase/identity"
|
|
)
|
|
|
|
type sessionAuthenticatorStub struct {
|
|
result identity.AuthenticatedSession
|
|
err error
|
|
calls int
|
|
}
|
|
|
|
func (authenticator *sessionAuthenticatorStub) Authenticate(_ context.Context, _ string) (identity.AuthenticatedSession, error) {
|
|
authenticator.calls++
|
|
return authenticator.result, authenticator.err
|
|
}
|
|
|
|
func TestSessionSecurityAddsVerifiedPrincipalForEveryProtectedOperationClass(t *testing.T) {
|
|
token, err := domain.NewSecretToken()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
userID := uuid.New()
|
|
verifiedAt := time.Now()
|
|
authenticator := &sessionAuthenticatorStub{result: identity.AuthenticatedSession{
|
|
User: domain.User{ID: userID, EmailVerifiedAt: &verifiedAt},
|
|
SessionID: uuid.New(),
|
|
CSRFToken: "bound-csrf-token",
|
|
}}
|
|
security := NewSessionSecurity(authenticator, "https://app.example.com")
|
|
|
|
for _, operation := range []api.OperationName{
|
|
api.GetCurrentAccountOperation,
|
|
api.GetCurrentSessionOperation,
|
|
api.GetMyProfileOperation,
|
|
api.CreateOrganizationOperation,
|
|
api.LogoutOperation,
|
|
} {
|
|
ctx := sessionRequestContext(t, token.Reveal(), "https://app.example.com")
|
|
authenticated, err := security.HandleSessionCookie(ctx, operation, api.SessionCookie{APIKey: token.Reveal()})
|
|
if err != nil {
|
|
t.Fatalf("HandleSessionCookie(%s) error = %v", operation, err)
|
|
}
|
|
principal, ok := PrincipalFromContext(authenticated)
|
|
if !ok || principal.UserID != userID || !principal.EmailVerified {
|
|
t.Fatalf("PrincipalFromContext(%s) = %+v, %v", operation, principal, ok)
|
|
}
|
|
}
|
|
if authenticator.calls != 5 {
|
|
t.Fatalf("authentication calls = %d, want one for each protected operation class", authenticator.calls)
|
|
}
|
|
}
|
|
|
|
func TestSessionCsrfRequiresExactOriginForAnyContractOperation(t *testing.T) {
|
|
token, err := domain.NewSecretToken()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
verifiedAt := time.Now()
|
|
authenticator := &sessionAuthenticatorStub{result: identity.AuthenticatedSession{
|
|
User: domain.User{ID: uuid.New(), EmailVerifiedAt: &verifiedAt},
|
|
SessionID: uuid.New(),
|
|
CSRFToken: "csrf-for-this-session",
|
|
}}
|
|
security := NewSessionSecurity(authenticator, "https://app.example.com")
|
|
|
|
for _, test := range []struct {
|
|
name string
|
|
origin string
|
|
csrf string
|
|
wantErr error
|
|
}{
|
|
{name: "valid pair", origin: "https://app.example.com", csrf: "csrf-for-this-session"},
|
|
{name: "wrong token", origin: "https://app.example.com", csrf: "csrf-from-another-session", wantErr: errCsrfCheckFailed},
|
|
{name: "wrong origin", origin: "https://attacker.example", csrf: "csrf-for-this-session", wantErr: errCsrfCheckFailed},
|
|
{name: "missing origin", csrf: "csrf-for-this-session", wantErr: errCsrfCheckFailed},
|
|
} {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
ctx := sessionRequestContext(t, token.Reveal(), test.origin)
|
|
ctx, err := security.HandleSessionCookie(ctx, api.CreateOrganizationOperation, api.SessionCookie{APIKey: token.Reveal()})
|
|
if err != nil {
|
|
t.Fatalf("HandleSessionCookie() error = %v", err)
|
|
}
|
|
_, err = security.HandleSessionCsrf(ctx, api.CreateOrganizationOperation, api.SessionCsrf{APIKey: test.csrf})
|
|
if !errors.Is(err, test.wantErr) {
|
|
t.Fatalf("HandleSessionCsrf() error = %v, want %v", err, test.wantErr)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestSessionSecurityRejectsInvalidAuthenticatedSession(t *testing.T) {
|
|
token, err := domain.NewSecretToken()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
verifiedAt := time.Now()
|
|
valid := identity.AuthenticatedSession{
|
|
User: domain.User{ID: uuid.New(), EmailVerifiedAt: &verifiedAt},
|
|
SessionID: uuid.New(),
|
|
CSRFToken: "csrf-for-this-session",
|
|
}
|
|
for _, test := range []struct {
|
|
name string
|
|
result identity.AuthenticatedSession
|
|
}{
|
|
{name: "unverified account", result: identity.AuthenticatedSession{User: domain.User{ID: valid.User.ID}, SessionID: valid.SessionID, CSRFToken: valid.CSRFToken}},
|
|
{name: "missing user ID", result: identity.AuthenticatedSession{User: domain.User{EmailVerifiedAt: &verifiedAt}, SessionID: valid.SessionID, CSRFToken: valid.CSRFToken}},
|
|
{name: "missing session ID", result: identity.AuthenticatedSession{User: valid.User, CSRFToken: valid.CSRFToken}},
|
|
{name: "missing CSRF token", result: identity.AuthenticatedSession{User: valid.User, SessionID: valid.SessionID}},
|
|
} {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
authenticator := &sessionAuthenticatorStub{result: test.result}
|
|
security := NewSessionSecurity(authenticator, "https://app.example.com")
|
|
ctx := sessionRequestContext(t, token.Reveal(), "https://app.example.com")
|
|
authenticated, err := security.HandleSessionCookie(ctx, api.GetMyProfileOperation, api.SessionCookie{APIKey: token.Reveal()})
|
|
if !errors.Is(err, ogenerrors.ErrSkipServerSecurity) {
|
|
t.Fatalf("HandleSessionCookie() error = %v, want skipped authentication", err)
|
|
}
|
|
if _, ok := PrincipalFromContext(authenticated); ok {
|
|
t.Fatal("invalid authenticated session installed a principal")
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestSecurityErrorsMapToUnauthenticatedOrCSRFProblem(t *testing.T) {
|
|
logger := slog.New(slog.NewTextHandler(&strings.Builder{}, nil))
|
|
handler := NewHandler(nil, problem.NewResponder(logger))
|
|
tests := []struct {
|
|
name string
|
|
ctx context.Context
|
|
err error
|
|
want api.ProblemCode
|
|
wantStatus int
|
|
}{
|
|
{name: "missing cookie", ctx: context.Background(), err: &ogenerrors.SecurityError{Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied}, want: api.ProblemCodeUnauthenticated, wantStatus: http.StatusUnauthorized},
|
|
{name: "missing csrf with principal", ctx: principalTestContext(), err: &ogenerrors.SecurityError{Err: ogenerrors.ErrSecurityRequirementIsNotSatisfied}, want: api.ProblemCodeCsrfCheckFailed, wantStatus: http.StatusForbidden},
|
|
{name: "bad csrf", err: &ogenerrors.SecurityError{Security: "SessionCsrf", Err: errCsrfCheckFailed}, want: api.ProblemCodeCsrfCheckFailed, wantStatus: http.StatusForbidden},
|
|
}
|
|
for _, test := range tests {
|
|
t.Run(test.name, func(t *testing.T) {
|
|
ctx := test.ctx
|
|
if ctx == nil {
|
|
ctx = context.Background()
|
|
}
|
|
response := handler.NewError(ctx, test.err)
|
|
if response.StatusCode != test.wantStatus || response.Response.Code != test.want {
|
|
t.Fatalf("NewError() = %d %s, want %d %s", response.StatusCode, response.Response.Code, test.wantStatus, test.want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestSessionCookiesUseRequiredAttributesAndClearStaleValues(t *testing.T) {
|
|
token, err := domain.NewSecretToken()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
start := time.Date(2026, time.January, 2, 3, 4, 5, 0, time.UTC)
|
|
session, err := domain.NewSession(domain.NewSessionInput{
|
|
UserID: uuid.New(), TokenHash: token.Hash(), StartedAt: start, AbsoluteLifetime: 168 * time.Hour,
|
|
})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
response := &http.Response{Header: http.Header{"Set-Cookie": {sessionCookie(token, session)}}}
|
|
cookies := response.Cookies()
|
|
if len(cookies) != 1 {
|
|
t.Fatalf("login cookie count = %d", len(cookies))
|
|
}
|
|
cookie := cookies[0]
|
|
if cookie.Name != httpmiddleware.SessionCookieName || cookie.Value != token.Reveal() || cookie.Path != "/" ||
|
|
cookie.Domain != "" || !cookie.Secure || !cookie.HttpOnly || cookie.SameSite != http.SameSiteStrictMode ||
|
|
cookie.MaxAge != int((168*time.Hour).Seconds()) || !cookie.Expires.Equal(session.ExpiresAt) {
|
|
t.Fatalf("login cookie attributes = %+v", cookie)
|
|
}
|
|
|
|
clearResponse := &http.Response{Header: http.Header{"Set-Cookie": {ExpiredSessionCookie()}}}
|
|
cleared := clearResponse.Cookies()
|
|
if len(cleared) != 1 || cleared[0].Name != httpmiddleware.SessionCookieName || cleared[0].Value != "" ||
|
|
cleared[0].Path != "/" || cleared[0].MaxAge >= 0 || !cleared[0].Secure || !cleared[0].HttpOnly ||
|
|
cleared[0].SameSite != http.SameSiteStrictMode {
|
|
t.Fatalf("logout clearing cookie = %+v", cleared)
|
|
}
|
|
}
|
|
|
|
func sessionRequestContext(t *testing.T, rawToken, origin string) context.Context {
|
|
t.Helper()
|
|
request := httptest.NewRequest(http.MethodGet, "/api/v1/identity/me", nil)
|
|
if origin != "" {
|
|
request.Header.Set("Origin", origin)
|
|
}
|
|
if rawToken != "" {
|
|
request.AddCookie(&http.Cookie{Name: httpmiddleware.SessionCookieName, Value: rawToken})
|
|
}
|
|
capture := &sessionContextCapture{}
|
|
httpmiddleware.SessionRequestMetadata()(capture).ServeHTTP(httptest.NewRecorder(), request)
|
|
if capture.ctx == nil {
|
|
t.Fatal("session request middleware did not pass a context")
|
|
}
|
|
return capture.ctx
|
|
}
|
|
|
|
type sessionContextCapture struct {
|
|
ctx context.Context
|
|
}
|
|
|
|
func (capture *sessionContextCapture) ServeHTTP(_ http.ResponseWriter, request *http.Request) {
|
|
capture.ctx = request.Context()
|
|
}
|
|
|
|
func principalTestContext() context.Context {
|
|
return context.WithValue(context.Background(), principalContextKey{}, Principal{UserID: uuid.New(), EmailVerified: true})
|
|
}
|