forked from mtusi2026/mtusi2026lab6
162 lines
5.7 KiB
Go
162 lines
5.7 KiB
Go
package fiber
|
|
|
|
import (
|
|
"context"
|
|
"encoding/base64"
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
|
|
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
|
|
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/service"
|
|
)
|
|
|
|
type sessionFixture struct {
|
|
fixtureAuthentication
|
|
login func(string, string) (dto.SessionDTO, error)
|
|
logoutError error
|
|
}
|
|
|
|
// Login delegates the credentials decoded by the controller to the arranged scenario.
|
|
func (f sessionFixture) Login(_ context.Context, username, password string) (dto.SessionDTO, error) {
|
|
return f.login(username, password)
|
|
}
|
|
|
|
// Logout returns the prescribed revocation outcome.
|
|
func (f sessionFixture) Logout(context.Context, string) error {
|
|
return f.logoutError
|
|
}
|
|
|
|
// TestLoginHTTPChecksBasicEncoding verifies independent wire-level login scenarios.
|
|
func TestLoginHTTPChecksBasicEncoding(t *testing.T) {
|
|
cases := []struct {
|
|
name string
|
|
header string
|
|
body string
|
|
status int
|
|
}{
|
|
{"missing header", "", "", http.StatusUnauthorized},
|
|
{"wrong scheme", "Bearer abc", "", http.StatusUnauthorized},
|
|
{"bad base64", "Basic %%%", "", http.StatusUnauthorized},
|
|
{"no delimiter", "Basic " + base64.StdEncoding.EncodeToString([]byte("alice")), "", http.StatusUnauthorized},
|
|
{"unexpected body", "Basic " + base64.StdEncoding.EncodeToString([]byte("alice:long-password:ok")), "{}", http.StatusBadRequest},
|
|
{"valid colon in password", "Basic " + base64.StdEncoding.EncodeToString([]byte("alice:long-password:ok")), "", http.StatusCreated},
|
|
}
|
|
for _, tc := range cases {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
ctrl := testController(t, nil)
|
|
ctrl.auth = sessionFixture{login: func(username, password string) (dto.SessionDTO, error) {
|
|
if username != "alice" || password != "long-password:ok" {
|
|
t.Fatal("credentials altered")
|
|
}
|
|
return dto.SessionDTO{Token: "opaque", ExpiresAt: time.Now().UTC().Add(time.Hour), User: dto.UserDTO{ID: uuid.New(), Username: "alice"}}, nil
|
|
}}
|
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", strings.NewReader(tc.body))
|
|
req.Header.Set("Authorization", tc.header)
|
|
response, err := ctrl.server.Test(req)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer func() {
|
|
_ = response.Body.Close()
|
|
}()
|
|
if response.StatusCode != tc.status {
|
|
t.Fatalf("got %d want %d", response.StatusCode, tc.status)
|
|
}
|
|
if tc.status == http.StatusUnauthorized && response.Header.Get("WWW-Authenticate") != `Basic realm="messenger", charset="UTF-8"` {
|
|
t.Fatal("missing Basic challenge")
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestLoginInvalidCredentialsUsesBasicChallenge checks the service rejection mapping.
|
|
func TestLoginInvalidCredentialsUsesBasicChallenge(t *testing.T) {
|
|
ctrl := testController(t, nil)
|
|
ctrl.auth = sessionFixture{login: func(string, string) (dto.SessionDTO, error) {
|
|
return dto.SessionDTO{}, service.ErrUnauthorized
|
|
}}
|
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
|
|
req.SetBasicAuth("alice", "invalid-password")
|
|
response, err := ctrl.server.Test(req)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer func() {
|
|
_ = response.Body.Close()
|
|
}()
|
|
if response.StatusCode != http.StatusUnauthorized || response.Header.Get("WWW-Authenticate") != `Basic realm="messenger", charset="UTF-8"` {
|
|
t.Fatal("incorrect login rejection")
|
|
}
|
|
}
|
|
|
|
// TestLogoutHTTPReturnsNoContent checks the authenticated revocation response.
|
|
func TestLogoutHTTPReturnsNoContent(t *testing.T) {
|
|
ctrl := testController(t, nil)
|
|
actor := user(t, ctrl)
|
|
req := httptest.NewRequest(http.MethodDelete, "/api/v1/auth/sessions/current", nil)
|
|
req.Header.Set("Authorization", "Bearer "+actor)
|
|
response, err := ctrl.server.Test(req)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer func() {
|
|
_ = response.Body.Close()
|
|
}()
|
|
body, err := io.ReadAll(response.Body)
|
|
if err != nil || response.StatusCode != http.StatusNoContent || len(body) != 0 {
|
|
t.Fatalf("invalid logout response: %v", err)
|
|
}
|
|
}
|
|
|
|
// TestLogoutHTTPPreservesFailure ensures an unsuccessful revoke does not claim success.
|
|
func TestLogoutHTTPPreservesFailure(t *testing.T) {
|
|
ctrl := testController(t, nil)
|
|
actor := user(t, ctrl)
|
|
ctrl.auth = sessionFixture{fixtureAuthentication: fixtureAuthentication{ctrl.service}, logoutError: context.DeadlineExceeded}
|
|
status, _, err := request(ctrl, http.MethodDelete, "/api/v1/auth/sessions/current", actor, nil)
|
|
if err != nil || status != http.StatusInternalServerError {
|
|
t.Fatalf("revocation failure hidden: %d %v", status, err)
|
|
}
|
|
}
|
|
|
|
// TestLegacyIdentityDoesNotAuthenticate verifies the lab1 header cannot grant access.
|
|
func TestLegacyIdentityDoesNotAuthenticate(t *testing.T) {
|
|
ctrl := testController(t, nil)
|
|
actor := user(t, ctrl)
|
|
req := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
|
|
req.Header.Set("X-User-Id", actor)
|
|
response, err := ctrl.server.Test(req)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer func() {
|
|
_ = response.Body.Close()
|
|
}()
|
|
if response.StatusCode != http.StatusUnauthorized || response.Header.Get("WWW-Authenticate") != `Bearer realm="messenger"` {
|
|
t.Fatal("legacy identity granted access or missing challenge")
|
|
}
|
|
}
|
|
|
|
type unavailableReadiness struct{}
|
|
|
|
// Ping simulates an unavailable mandatory dependency for readiness mapping.
|
|
func (unavailableReadiness) Ping(context.Context) error {
|
|
return context.DeadlineExceeded
|
|
}
|
|
|
|
// TestReadinessRejectsDependencyFailure verifies readiness reflects mandatory infrastructure.
|
|
func TestReadinessRejectsDependencyFailure(t *testing.T) {
|
|
ctrl := testController(t, nil)
|
|
ctrl.readiness = unavailableReadiness{}
|
|
status, _, err := request(ctrl, http.MethodGet, "/health/ready", "", nil)
|
|
if err != nil || status != http.StatusServiceUnavailable {
|
|
t.Fatalf("incorrect readiness: %d %v", status, err)
|
|
}
|
|
}
|