Files
Veyra/services/api/internal/transport/http/identity_test.go
T
Blizzard ba6dfffab7
Checks / verify (push) Canceled after 41s
init: initial commit
2026-10-06 11:24:02 +08:00

54 lines
2.1 KiB
Go

package http
import (
"context"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
identity "veyra/services/api/internal/identity/service"
operations "veyra/services/api/internal/operations/service"
)
func TestAuthenticationAndCSRFBoundaries(t *testing.T) {
auth, err := identity.NewAuthService(nil)
if err != nil {
t.Fatal(err)
}
probe := func(context.Context) error { return nil }
router := NewRouter(operations.NewHealthService(probe, probe), slog.New(slog.NewTextHandler(io.Discard, nil)), IdentityOptions{Auth: auth, DevelopmentLogin: true})
for _, tc := range []struct {
method, path, body, origin string
status int
}{
{http.MethodGet, "/api/admin/v1/users", "", "", 401},
{http.MethodGet, "/api/v1/accounts", "", "", 401},
{http.MethodPost, "/api/admin/v1/auth/login", `{"login_name":"admin","password":"test-password"}`, "http://evil.example", 403},
{http.MethodPost, "/api/admin/v1/auth/login", `{"login_name":"admin","password":"test-password"}`, "", 403},
{http.MethodPost, "/api/admin/v1/auth/login", `{"login_name":"admin","password":"test-password","role":"ADMIN"}`, "http://example.com", 422},
{http.MethodPost, "/api/v1/auth/login", `{} {}`, "", 422},
} {
req := httptest.NewRequest(tc.method, "http://example.com"+tc.path, strings.NewReader(tc.body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Origin", tc.origin)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != tc.status {
t.Fatalf("%s %s got %d want %d", tc.method, tc.path, rec.Code, tc.status)
}
}
}
func TestDevelopmentLoginDisabledByDefault(t *testing.T) {
probe := func(context.Context) error { return nil }
router := NewRouter(operations.NewHealthService(probe, probe), slog.New(slog.NewTextHandler(io.Discard, nil)), IdentityOptions{})
rec := httptest.NewRecorder()
router.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", strings.NewReader(`{}`)))
if rec.Code != http.StatusServiceUnavailable {
t.Fatal("development login open outside explicitly enabled environment")
}
}