Files
NianAIGC/backend/internal/application/application_test.go

276 lines
8.6 KiB
Go

package application_test
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"time"
"git.nianxx.cn/wangxuming/NianAIGC/backend/internal/application"
"git.nianxx.cn/wangxuming/NianAIGC/backend/internal/identity"
)
func TestLocalApplicationServesFoundationHealthAndReadiness(t *testing.T) {
app, err := application.New(application.Options{
Getenv: func(name string) string {
if name == "ZHINIAN_DATA_BACKEND" {
return "local"
}
return ""
},
})
if err != nil {
t.Fatalf("New() error = %v", err)
}
t.Cleanup(app.Close)
for _, test := range []struct {
path string
wantCode int
}{
{path: "/api/health", wantCode: http.StatusOK},
{path: "/api/ready", wantCode: http.StatusOK},
} {
t.Run(test.path, func(t *testing.T) {
response := httptest.NewRecorder()
app.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, test.path, nil))
if response.Code != test.wantCode {
t.Fatalf("status = %d, want %d", response.Code, test.wantCode)
}
var payload struct {
OK bool `json:"ok"`
Database struct {
Backend string `json:"backend"`
Configured bool `json:"configured"`
} `json:"database"`
}
if err := json.NewDecoder(response.Body).Decode(&payload); err != nil {
t.Fatalf("decode response: %v", err)
}
if !payload.OK || payload.Database.Backend != "local" || !payload.Database.Configured {
t.Fatalf("payload = %+v", payload)
}
})
}
}
func TestApplicationRejectsInvalidProductionDatabaseConfiguration(t *testing.T) {
_, err := application.New(application.Options{
Getenv: func(name string) string {
if name == "NODE_ENV" {
return "production"
}
return ""
},
})
if err == nil {
t.Fatal("New() error = nil, want fail-closed database configuration error")
}
}
func TestApplicationServesAnonymousCurrentSessionWithAuthConfigurationState(t *testing.T) {
tests := []struct {
name string
environment map[string]string
wantRequired bool
wantConfigured bool
}{
{
name: "trusted local development",
environment: map[string]string{"ZHINIAN_DATA_BACKEND": "local"},
wantRequired: false,
wantConfigured: false,
},
{
name: "production missing session secret",
environment: map[string]string{
"ZHINIAN_DATA_BACKEND": "local",
"NODE_ENV": "production",
},
wantRequired: true,
wantConfigured: false,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
app, err := application.New(application.Options{Getenv: applicationEnv(test.environment)})
if err != nil {
t.Fatalf("New() error = %v", err)
}
t.Cleanup(app.Close)
response := httptest.NewRecorder()
app.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/auth/me", nil))
if response.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", response.Code, http.StatusOK)
}
var payload map[string]any
if err := json.NewDecoder(response.Body).Decode(&payload); err != nil {
t.Fatalf("decode response: %v", err)
}
want := map[string]any{
"authenticated": false,
"authRequired": test.wantRequired,
"authConfigured": test.wantConfigured,
"authMode": nil,
"user": nil,
}
if !reflect.DeepEqual(payload, want) {
t.Fatalf("payload = %#v, want %#v", payload, want)
}
})
}
}
func TestApplicationComposesSignedCookieResolverWithAuthorizationLoader(t *testing.T) {
secret := "application-current-session-secret-with-enough-entropy"
loader := &applicationAuthorizationLoader{snapshot: identity.AuthorizationSnapshot{
Account: identity.AccountSnapshot{
ID: "user-1", Phone: "13800138001", DisplayName: "Current User", Role: "user",
OrganizationID: "org-1", Status: "active", SessionVersion: 7,
},
Organization: &identity.OrganizationSnapshot{ID: "org-1", Name: "Primary Organization", Status: "active"},
}, found: true}
app, err := application.New(application.Options{
Getenv: applicationEnv(map[string]string{
"ZHINIAN_DATA_BACKEND": "local",
"ZHINIAN_AUTH_SESSION_SECRET": secret,
}),
AuthorizationLoader: loader,
})
if err != nil {
t.Fatalf("New() error = %v", err)
}
t.Cleanup(app.Close)
version := 7
session := identity.Session{
Version: 1, AuthMode: identity.AuthModeAdmin,
IssuedAt: time.Now().Add(-time.Minute).Unix(), ExpiresAt: time.Now().Add(time.Hour).Unix(),
SessionVersion: &version, AccessToken: "must-not-leak", TokenType: "bearer",
User: identity.User{
ID: "user-1", Subject: "forged", DisplayName: "Forged Admin", ClientID: "platform",
Role: "super_admin", Status: "active", Authorities: []string{"ROLE_SUPER_ADMIN"}, Scope: []string{"forged"},
},
}
raw, err := json.Marshal(session)
if err != nil {
t.Fatalf("marshal session: %v", err)
}
cookieValue, err := identity.Sign(raw, secret)
if err != nil {
t.Fatalf("sign session: %v", err)
}
request := httptest.NewRequest(http.MethodGet, "/api/auth/me", nil)
request.AddCookie(&http.Cookie{Name: identity.SessionCookieName, Value: cookieValue})
response := httptest.NewRecorder()
app.Handler().ServeHTTP(response, request)
if response.Code != http.StatusOK {
t.Fatalf("status = %d, want %d", response.Code, http.StatusOK)
}
body := response.Body.Bytes()
var payload struct {
Authenticated bool `json:"authenticated"`
User struct {
ID string `json:"id"`
DisplayName string `json:"displayName"`
Role string `json:"role"`
Authorities []string `json:"authorities"`
} `json:"user"`
}
if err := json.Unmarshal(body, &payload); err != nil {
t.Fatalf("decode response: %v", err)
}
if !payload.Authenticated || payload.User.ID != "user-1" || payload.User.DisplayName != "Current User" || payload.User.Role != "user" {
t.Fatalf("payload = %+v", payload)
}
if !reflect.DeepEqual(payload.User.Authorities, []string{"ROLE_USER"}) {
t.Fatalf("authorities = %#v", payload.User.Authorities)
}
if len(loader.ids) != 1 || loader.ids[0] != "user-1" {
t.Fatalf("loader IDs = %#v", loader.ids)
}
for _, forbidden := range []string{"accessToken", "tokenType", "sessionVersion", "expiresAt", "issuedAt", "must-not-leak"} {
if strings.Contains(string(body), forbidden) {
t.Fatalf("response leaked %q: %s", forbidden, body)
}
}
for _, method := range []string{http.MethodHead, http.MethodOptions, http.MethodPost} {
methodRequest := httptest.NewRequest(method, "/api/auth/me", nil)
methodResponse := httptest.NewRecorder()
app.Handler().ServeHTTP(methodResponse, methodRequest)
wantStatus := http.StatusMethodNotAllowed
if method == http.MethodHead {
wantStatus = http.StatusOK
}
if method == http.MethodOptions {
wantStatus = http.StatusNoContent
}
if methodResponse.Code != wantStatus {
t.Fatalf("%s status = %d, want %d", method, methodResponse.Code, wantStatus)
}
}
}
func TestApplicationUsesDatabaseAuthorizationAdapterByDefault(t *testing.T) {
secret := "local-default-adapter-secret-with-enough-entropy"
app, err := application.New(application.Options{Getenv: applicationEnv(map[string]string{
"ZHINIAN_DATA_BACKEND": "local",
"ZHINIAN_AUTH_SESSION_SECRET": secret,
})})
if err != nil {
t.Fatalf("New() error = %v", err)
}
t.Cleanup(app.Close)
session := identity.Session{
Version: 1, AuthMode: identity.AuthModeUser,
IssuedAt: time.Now().Add(-time.Minute).Unix(), ExpiresAt: time.Now().Add(time.Hour).Unix(),
User: identity.User{
ID: "user-1", Subject: "user-1", DisplayName: "User", ClientID: "platform",
Authorities: []string{}, Scope: []string{},
},
}
raw, err := json.Marshal(session)
if err != nil {
t.Fatalf("marshal session: %v", err)
}
cookieValue, err := identity.Sign(raw, secret)
if err != nil {
t.Fatalf("sign session: %v", err)
}
request := httptest.NewRequest(http.MethodGet, "/api/auth/me", nil)
request.AddCookie(&http.Cookie{Name: identity.SessionCookieName, Value: cookieValue})
response := httptest.NewRecorder()
app.Handler().ServeHTTP(response, request)
if response.Code != http.StatusInternalServerError || response.Body.Len() != 0 {
t.Fatalf("response = %d %q, want empty 500 from unavailable local authorization adapter", response.Code, response.Body.String())
}
}
type applicationAuthorizationLoader struct {
snapshot identity.AuthorizationSnapshot
found bool
err error
ids []string
}
func (loader *applicationAuthorizationLoader) FindAuthorizationSnapshot(_ context.Context, id string) (identity.AuthorizationSnapshot, bool, error) {
loader.ids = append(loader.ids, id)
return loader.snapshot, loader.found, loader.err
}
func applicationEnv(values map[string]string) func(string) string {
return func(name string) string { return values[name] }
}