mirror of
https://github.com/J3vb/OwnCord.git
synced 2026-09-03 03:50:00 +03:00
fix: update tests and fix pending-join drain regression for CI
Update LiveKitSession tests to use _state discriminated union instead of old flat field names (room, currentChannelId, latestToken, etc.) removed in the state machine refactor. Also fix renderers.test.ts URL resolution by setting a server host in beforeEach so isSafeUrl can parse relative attachment URLs in jsdom. Stage all four Go test files so the CI Go job runs them. Additionally fix a regression in connectAndSetup's finally block: when a pendingJoin is queued during a stale-join abort, preserve the connecting state so handleVoiceToken's drain loop can pick it up rather than losing it by resetting to idle.
This commit is contained in:
@@ -74,6 +74,17 @@ func postJSONWithToken(t *testing.T, router http.Handler, path, token string, bo
|
||||
return rr
|
||||
}
|
||||
|
||||
func postJSONFromIP(t *testing.T, router http.Handler, path string, body any, ip string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
raw, _ := json.Marshal(body)
|
||||
req := httptest.NewRequest(http.MethodPost, path, bytes.NewReader(raw))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.RemoteAddr = ip + ":9999"
|
||||
rr := httptest.NewRecorder()
|
||||
router.ServeHTTP(rr, req)
|
||||
return rr
|
||||
}
|
||||
|
||||
// getWithToken performs a GET with an Authorization header.
|
||||
func getWithToken(t *testing.T, router http.Handler, path, token string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
@@ -344,6 +355,97 @@ func TestLogin_LockoutUsesTrustedForwardedIP(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogin_UsernameLockoutAcrossDifferentIPs(t *testing.T) {
|
||||
database := newAuthTestDB(t)
|
||||
limiter := auth.NewRateLimiter()
|
||||
router := buildAuthRouter(database, limiter)
|
||||
|
||||
hash, _ := auth.HashPassword("correctPass1")
|
||||
_, _ = database.CreateUser("lockoutuser", hash, 4)
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
rr := postJSONFromIP(t, router, "/api/v1/auth/login", map[string]string{
|
||||
"username": "lockoutuser",
|
||||
"password": "wrongpassword",
|
||||
}, fmt.Sprintf("198.51.100.%d", i+1))
|
||||
if rr.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("attempt %d status = %d, want 401; body = %s", i+1, rr.Code, rr.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
rr := postJSONFromIP(t, router, "/api/v1/auth/login", map[string]string{
|
||||
"username": "lockoutuser",
|
||||
"password": "wrongpassword",
|
||||
}, "198.51.100.250")
|
||||
if rr.Code != http.StatusTooManyRequests {
|
||||
t.Fatalf("username lockout status = %d, want 429; body = %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogin_UsernameLockoutBlocksCorrectPasswordFromFreshIP(t *testing.T) {
|
||||
database := newAuthTestDB(t)
|
||||
limiter := auth.NewRateLimiter()
|
||||
router := buildAuthRouter(database, limiter)
|
||||
|
||||
hash, _ := auth.HashPassword("correctPass1")
|
||||
_, _ = database.CreateUser("lockoutcorrect", hash, 4)
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
rr := postJSONFromIP(t, router, "/api/v1/auth/login", map[string]string{
|
||||
"username": "lockoutcorrect",
|
||||
"password": "wrongpassword",
|
||||
}, fmt.Sprintf("203.0.113.%d", i+1))
|
||||
if rr.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("setup attempt %d status = %d, want 401; body = %s", i+1, rr.Code, rr.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
rr := postJSONFromIP(t, router, "/api/v1/auth/login", map[string]string{
|
||||
"username": "lockoutcorrect",
|
||||
"password": "correctPass1",
|
||||
}, "203.0.113.250")
|
||||
if rr.Code != http.StatusTooManyRequests {
|
||||
t.Fatalf("locked correct-password status = %d, want 429; body = %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogin_SuccessResetsUsernameFailureCounter(t *testing.T) {
|
||||
database := newAuthTestDB(t)
|
||||
limiter := auth.NewRateLimiter()
|
||||
router := buildAuthRouter(database, limiter)
|
||||
|
||||
hash, _ := auth.HashPassword("correctPass1")
|
||||
_, _ = database.CreateUser("resetuser", hash, 4)
|
||||
|
||||
for i := 0; i < 8; i++ {
|
||||
rr := postJSONFromIP(t, router, "/api/v1/auth/login", map[string]string{
|
||||
"username": "resetuser",
|
||||
"password": "wrongpassword",
|
||||
}, fmt.Sprintf("192.0.2.%d", i+1))
|
||||
if rr.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("setup attempt %d status = %d, want 401; body = %s", i+1, rr.Code, rr.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
rr := postJSONFromIP(t, router, "/api/v1/auth/login", map[string]string{
|
||||
"username": "resetuser",
|
||||
"password": "correctPass1",
|
||||
}, "192.0.2.200")
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Fatalf("success status = %d, want 200; body = %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
|
||||
for i := 0; i < 3; i++ {
|
||||
rr = postJSONFromIP(t, router, "/api/v1/auth/login", map[string]string{
|
||||
"username": "resetuser",
|
||||
"password": "wrongpassword",
|
||||
}, fmt.Sprintf("192.0.2.%d", 201+i))
|
||||
if rr.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("post-reset attempt %d status = %d, want 401; body = %s", i+1, rr.Code, rr.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogin_GenericErrorOnBadCredentials(t *testing.T) {
|
||||
database := newAuthTestDB(t)
|
||||
limiter := auth.NewRateLimiter()
|
||||
@@ -396,6 +498,44 @@ func TestLogin_RequiresTOTPChallenge(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLogin_UsernameLockoutBlocksTOTPChallenge(t *testing.T) {
|
||||
database := newAuthTestDB(t)
|
||||
limiter := auth.NewRateLimiter()
|
||||
router := buildAuthRouter(database, limiter)
|
||||
|
||||
hash, _ := auth.HashPassword("correctPass1")
|
||||
userID, _ := database.CreateUser("totplocked", hash, 4)
|
||||
if _, err := database.Exec(`UPDATE users SET totp_secret = ? WHERE id = ?`, "JBSWY3DPEHPK3PXP", userID); err != nil {
|
||||
t.Fatalf("set totp secret: %v", err)
|
||||
}
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
rr := postJSONFromIP(t, router, "/api/v1/auth/login", map[string]string{
|
||||
"username": "totplocked",
|
||||
"password": "wrongpassword",
|
||||
}, fmt.Sprintf("198.18.0.%d", i+1))
|
||||
if rr.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("setup attempt %d status = %d, want 401; body = %s", i+1, rr.Code, rr.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
rr := postJSONFromIP(t, router, "/api/v1/auth/login", map[string]string{
|
||||
"username": "totplocked",
|
||||
"password": "correctPass1",
|
||||
}, "198.18.0.250")
|
||||
if rr.Code != http.StatusTooManyRequests {
|
||||
t.Fatalf("locked TOTP login status = %d, want 429; body = %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
|
||||
var resp map[string]any
|
||||
if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
if resp["partial_token"] != nil {
|
||||
t.Fatalf("partial_token = %v, want nil when username is locked out", resp["partial_token"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyTotp_Success(t *testing.T) {
|
||||
database := newAuthTestDB(t)
|
||||
limiter := auth.NewRateLimiter()
|
||||
|
||||
@@ -101,6 +101,95 @@ func TestCreateInvite_Unlimited(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateInvite_EmptyBody(t *testing.T) {
|
||||
database := newAuthTestDB(t)
|
||||
limiter := auth.NewRateLimiter()
|
||||
router := buildInviteRouter(database, limiter)
|
||||
token := loginAndGetToken(t, router, database, "emptyinvitebody", 2)
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/invites", http.NoBody)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
req.RemoteAddr = "127.0.0.1:9999"
|
||||
rr := httptest.NewRecorder()
|
||||
router.ServeHTTP(rr, req)
|
||||
|
||||
if rr.Code != http.StatusCreated {
|
||||
t.Fatalf("CreateInvite empty body status = %d, want 201; body = %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
|
||||
var resp map[string]any
|
||||
if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
if resp["max_uses"] != nil {
|
||||
t.Errorf("max_uses = %v, want nil", resp["max_uses"])
|
||||
}
|
||||
if resp["expires_at"] != nil {
|
||||
t.Errorf("expires_at = %v, want nil", resp["expires_at"])
|
||||
}
|
||||
if resp["code"] == nil || resp["code"] == "" {
|
||||
t.Fatal("expected invite code in response")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateInvite_CreateInviteFailure(t *testing.T) {
|
||||
database := newAuthTestDB(t)
|
||||
limiter := auth.NewRateLimiter()
|
||||
router := buildInviteRouter(database, limiter)
|
||||
token := loginAndGetToken(t, router, database, "invitecreatefail", 2)
|
||||
|
||||
if _, err := database.Exec(`DROP TABLE invites`); err != nil {
|
||||
t.Fatalf("drop invites table: %v", err)
|
||||
}
|
||||
|
||||
rr := postJSONWithToken(t, router, "/api/v1/invites", token, map[string]any{})
|
||||
if rr.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("CreateInvite create failure status = %d, want 500; body = %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
|
||||
var resp map[string]any
|
||||
if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
if resp["message"] != "failed to create invite" {
|
||||
t.Errorf("message = %v, want failed to create invite", resp["message"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateInvite_GetInviteFailure(t *testing.T) {
|
||||
database := newAuthTestDB(t)
|
||||
limiter := auth.NewRateLimiter()
|
||||
router := buildInviteRouter(database, limiter)
|
||||
token := loginAndGetToken(t, router, database, "invitegetfail", 2)
|
||||
|
||||
if _, err := database.Exec(`
|
||||
CREATE TRIGGER delete_invite_after_insert
|
||||
AFTER INSERT ON invites
|
||||
BEGIN
|
||||
DELETE FROM invites WHERE code = NEW.code;
|
||||
END;
|
||||
`); err != nil {
|
||||
t.Fatalf("create trigger: %v", err)
|
||||
}
|
||||
|
||||
rr := postJSONWithToken(t, router, "/api/v1/invites", token, map[string]any{})
|
||||
if rr.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("CreateInvite get failure status = %d, want 500; body = %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
|
||||
var resp map[string]any
|
||||
if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
if resp["message"] != "failed to retrieve invite" {
|
||||
t.Errorf("message = %v, want failed to retrieve invite", resp["message"])
|
||||
}
|
||||
if _, err := database.Exec(`DROP TRIGGER delete_invite_after_insert`); err != nil {
|
||||
t.Fatalf("drop trigger: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// ─── GET /api/v1/invites ──────────────────────────────────────────────────────
|
||||
|
||||
func TestListInvites_Success(t *testing.T) {
|
||||
@@ -146,6 +235,31 @@ func TestListInvites_Unauthorized(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestListInvites_EmptyArray(t *testing.T) {
|
||||
database := newAuthTestDB(t)
|
||||
limiter := auth.NewRateLimiter()
|
||||
router := buildInviteRouter(database, limiter)
|
||||
token := loginAndGetToken(t, router, database, "emptyinvitelist", 2)
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/invites", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
req.RemoteAddr = "127.0.0.1:9999"
|
||||
rr := httptest.NewRecorder()
|
||||
router.ServeHTTP(rr, req)
|
||||
|
||||
if rr.Code != http.StatusOK {
|
||||
t.Fatalf("ListInvites empty status = %d, want 200; body = %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
|
||||
var resp []any
|
||||
if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
if len(resp) != 0 {
|
||||
t.Fatalf("ListInvites empty returned %d items, want 0", len(resp))
|
||||
}
|
||||
}
|
||||
|
||||
// ─── DELETE /api/v1/invites/:code ─────────────────────────────────────────────
|
||||
|
||||
func TestRevokeInvite_Success(t *testing.T) {
|
||||
@@ -230,6 +344,51 @@ func TestRevokeInvite_MemberForbidden(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRevokeInvite_RevokeFailure(t *testing.T) {
|
||||
database := newAuthTestDB(t)
|
||||
limiter := auth.NewRateLimiter()
|
||||
router := buildInviteRouter(database, limiter)
|
||||
token := loginAndGetToken(t, router, database, "revokefailure", 2)
|
||||
|
||||
rr := postJSONWithToken(t, router, "/api/v1/invites", token, map[string]any{})
|
||||
if rr.Code != http.StatusCreated {
|
||||
t.Fatalf("setup create invite: status = %d, body = %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
var created map[string]any
|
||||
if err := json.NewDecoder(rr.Body).Decode(&created); err != nil {
|
||||
t.Fatalf("decode create response: %v", err)
|
||||
}
|
||||
code := created["code"].(string)
|
||||
|
||||
if _, err := database.Exec(`
|
||||
CREATE TRIGGER block_revoke_invite
|
||||
BEFORE UPDATE OF revoked ON invites
|
||||
BEGIN
|
||||
SELECT RAISE(FAIL, 'revoke blocked');
|
||||
END;
|
||||
`); err != nil {
|
||||
t.Fatalf("create trigger: %v", err)
|
||||
}
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/api/v1/invites/"+code, nil)
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
req.RemoteAddr = "127.0.0.1:9999"
|
||||
rr2 := httptest.NewRecorder()
|
||||
router.ServeHTTP(rr2, req)
|
||||
|
||||
if rr2.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("RevokeInvite failure status = %d, want 500; body = %s", rr2.Code, rr2.Body.String())
|
||||
}
|
||||
|
||||
var resp map[string]any
|
||||
if err := json.NewDecoder(rr2.Body).Decode(&resp); err != nil {
|
||||
t.Fatalf("decode revoke failure response: %v", err)
|
||||
}
|
||||
if resp["message"] != "failed to revoke invite" {
|
||||
t.Errorf("message = %v, want failed to revoke invite", resp["message"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestListInvites_IncludesRevokedAndActive checks the list endpoint returns
|
||||
// correct data for both revoked and active invites.
|
||||
func TestListInvites_IncludesRevokedAndActive(t *testing.T) {
|
||||
|
||||
@@ -11,6 +11,8 @@ import (
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"testing/fstest"
|
||||
|
||||
@@ -153,6 +155,15 @@ func buildUploadRouter(database *db.DB, store *storage.Storage, allowedOrigins [
|
||||
return r
|
||||
}
|
||||
|
||||
func buildUploadRouterWithLimiter(database *db.DB, store *storage.Storage, limiter *auth.RateLimiter, allowedOrigins []string) http.Handler {
|
||||
r := chi.NewRouter()
|
||||
if limiter == nil {
|
||||
limiter = auth.NewRateLimiter()
|
||||
}
|
||||
api.MountUploadRoutes(r, database, store, limiter, allowedOrigins)
|
||||
return r
|
||||
}
|
||||
|
||||
// uploadCreateToken creates a user+session and returns the plaintext token.
|
||||
func uploadCreateToken(t *testing.T, database *db.DB, username string, roleID int) string {
|
||||
t.Helper()
|
||||
@@ -462,6 +473,139 @@ func TestUpload_BlockedFileType_ELF(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpload_RateLimitedAfterBurst(t *testing.T) {
|
||||
database := newUploadTestDB(t)
|
||||
store := newUploadTestStorage(t)
|
||||
limiter := auth.NewRateLimiter()
|
||||
router := buildUploadRouterWithLimiter(database, store, limiter, nil)
|
||||
token := uploadCreateToken(t, database, "burstuser", 1)
|
||||
otherToken := uploadCreateToken(t, database, "otherburstuser", 1)
|
||||
content := []byte("upload payload with enough bytes for content type detection")
|
||||
|
||||
for range 10 {
|
||||
rr := doUpload(t, router, token, "file", "burst.txt", content)
|
||||
if rr.Code != http.StatusCreated {
|
||||
t.Fatalf("pre-limit upload status = %d, want 201; body: %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
rr := doUpload(t, router, token, "file", "burst.txt", content)
|
||||
if rr.Code != http.StatusTooManyRequests {
|
||||
t.Fatalf("rate-limited upload status = %d, want 429; body: %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
|
||||
var resp map[string]any
|
||||
if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {
|
||||
t.Fatalf("decode rate-limit response: %v", err)
|
||||
}
|
||||
if resp["error"] != "RATE_LIMITED" {
|
||||
t.Errorf("error = %v, want RATE_LIMITED", resp["error"])
|
||||
}
|
||||
|
||||
rr = doUpload(t, router, otherToken, "file", "burst.txt", content)
|
||||
if rr.Code != http.StatusCreated {
|
||||
t.Fatalf("other user upload status = %d, want 201; body: %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpload_OversizedFileRejected(t *testing.T) {
|
||||
database := newUploadTestDB(t)
|
||||
dir := t.TempDir()
|
||||
store, err := storage.New(dir, 1)
|
||||
if err != nil {
|
||||
t.Fatalf("storage.New: %v", err)
|
||||
}
|
||||
router := buildUploadRouter(database, store, nil)
|
||||
token := uploadCreateToken(t, database, "largeupload", 1)
|
||||
content := bytes.Repeat([]byte("a"), (1<<20)+1)
|
||||
|
||||
rr := doUpload(t, router, token, "file", "too-large.txt", content)
|
||||
if rr.Code != http.StatusBadRequest {
|
||||
t.Fatalf("oversized upload status = %d, want 400; body: %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
|
||||
var resp map[string]any
|
||||
if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {
|
||||
t.Fatalf("decode oversized response: %v", err)
|
||||
}
|
||||
message, _ := resp["message"].(string)
|
||||
if !strings.Contains(message, "file exceeds maximum size") {
|
||||
t.Fatalf("message = %q, want size rejection", message)
|
||||
}
|
||||
if resp["error"] != "BAD_REQUEST" {
|
||||
t.Errorf("error = %v, want BAD_REQUEST", resp["error"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpload_DBCreateAttachmentFailureDeletesStoredFile(t *testing.T) {
|
||||
database := newUploadTestDB(t)
|
||||
dir := t.TempDir()
|
||||
store, err := storage.New(dir, 10)
|
||||
if err != nil {
|
||||
t.Fatalf("storage.New: %v", err)
|
||||
}
|
||||
router := buildUploadRouter(database, store, nil)
|
||||
token := uploadCreateToken(t, database, "dbfailupload", 1)
|
||||
|
||||
if _, err := database.Exec(`DROP TABLE attachments`); err != nil {
|
||||
t.Fatalf("drop attachments table: %v", err)
|
||||
}
|
||||
|
||||
content := []byte("content that will save to disk before attachment insert fails")
|
||||
rr := doUpload(t, router, token, "file", "cleanup.txt", content)
|
||||
if rr.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("upload status = %d, want 500; body: %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
|
||||
var resp map[string]any
|
||||
if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {
|
||||
t.Fatalf("decode db failure response: %v", err)
|
||||
}
|
||||
if resp["error"] != "INTERNAL_ERROR" {
|
||||
t.Errorf("error = %v, want INTERNAL_ERROR", resp["error"])
|
||||
}
|
||||
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadDir: %v", err)
|
||||
}
|
||||
if len(entries) != 0 {
|
||||
t.Fatalf("expected stored file cleanup on DB failure, found %d entries", len(entries))
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpload_SanitizesReservedFilenameToUnnamed(t *testing.T) {
|
||||
database := newUploadTestDB(t)
|
||||
store := newUploadTestStorage(t)
|
||||
router := buildUploadRouter(database, store, nil)
|
||||
token := uploadCreateToken(t, database, "sanitizeupload", 1)
|
||||
content := []byte("content for reserved filename sanitization")
|
||||
|
||||
rr := doUpload(t, router, token, "file", ".", content)
|
||||
if rr.Code != http.StatusCreated {
|
||||
t.Fatalf("status = %d, want 201; body: %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
|
||||
var resp map[string]any
|
||||
if err := json.NewDecoder(rr.Body).Decode(&resp); err != nil {
|
||||
t.Fatalf("decode response: %v", err)
|
||||
}
|
||||
if resp["filename"] != "unnamed" {
|
||||
t.Fatalf("filename = %v, want unnamed", resp["filename"])
|
||||
}
|
||||
|
||||
att, err := database.GetAttachmentByID(resp["id"].(string))
|
||||
if err != nil {
|
||||
t.Fatalf("GetAttachmentByID: %v", err)
|
||||
}
|
||||
if att == nil {
|
||||
t.Fatal("expected attachment record in DB, got nil")
|
||||
}
|
||||
if att.Filename != "unnamed" {
|
||||
t.Fatalf("DB filename = %q, want unnamed", att.Filename)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpload_SuccessfulUploadCreatesDBRecord(t *testing.T) {
|
||||
database := newUploadTestDB(t)
|
||||
store := newUploadTestStorage(t)
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/corazawaf/coraza/v3/types"
|
||||
)
|
||||
|
||||
func TestHandleWAFInterruption_WritesJSONAndStatus(t *testing.T) {
|
||||
rr := httptest.NewRecorder()
|
||||
handleWAFInterruption(rr, &types.Interruption{
|
||||
Action: "deny",
|
||||
Status: http.StatusForbidden,
|
||||
RuleID: 942100,
|
||||
Data: "SQL Injection detected",
|
||||
})
|
||||
|
||||
if rr.Code != http.StatusForbidden {
|
||||
t.Fatalf("status = %d, want 403", rr.Code)
|
||||
}
|
||||
if rr.Header().Get("Content-Type") != "application/json" {
|
||||
t.Fatalf("Content-Type = %q, want application/json", rr.Header().Get("Content-Type"))
|
||||
}
|
||||
if strings.TrimSpace(rr.Body.String()) != `{"error":"request blocked by security rules"}` {
|
||||
t.Fatalf("body = %q, want blocked JSON", rr.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestWAFMiddleware_AllowsBenignRequest(t *testing.T) {
|
||||
called := false
|
||||
middleware := NewWAFMiddleware(2)
|
||||
handler := middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
called = true
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/channels?q=hello", nil)
|
||||
req.RemoteAddr = "127.0.0.1:9999"
|
||||
rr := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rr, req)
|
||||
|
||||
if !called {
|
||||
t.Fatal("expected downstream handler to be called")
|
||||
}
|
||||
if rr.Code != http.StatusNoContent {
|
||||
t.Fatalf("status = %d, want 204", rr.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWAFMiddleware_InvalidParanoiaLevelStillAllowsBenignRequest(t *testing.T) {
|
||||
called := false
|
||||
middleware := NewWAFMiddleware(99)
|
||||
handler := middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
called = true
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/channels?q=hello", nil)
|
||||
req.RemoteAddr = "127.0.0.1:9999"
|
||||
rr := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rr, req)
|
||||
|
||||
if !called {
|
||||
t.Fatal("expected downstream handler to be called")
|
||||
}
|
||||
if rr.Code != http.StatusNoContent {
|
||||
t.Fatalf("status = %d, want 204", rr.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWAFMiddleware_BlocksScannerUserAgent(t *testing.T) {
|
||||
middleware := NewWAFMiddleware(2)
|
||||
handler := middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Fatal("downstream handler should not be called for blocked scanner request")
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest(http.MethodGet, "/api/v1/channels", nil)
|
||||
req.Header.Set("User-Agent", "sqlmap/1.8")
|
||||
req.RemoteAddr = "127.0.0.1:9999"
|
||||
rr := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rr, req)
|
||||
|
||||
if rr.Code != http.StatusForbidden {
|
||||
t.Fatalf("status = %d, want 403; body = %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestWAFMiddleware_PreservesReadableBodyForDownstream(t *testing.T) {
|
||||
const requestBody = `{"message":"hello world"}`
|
||||
middleware := NewWAFMiddleware(2)
|
||||
handler := middleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadAll: %v", err)
|
||||
}
|
||||
if string(body) != requestBody {
|
||||
t.Fatalf("body = %q, want %q", string(body), requestBody)
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/messages", strings.NewReader(requestBody))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.RemoteAddr = "127.0.0.1:9999"
|
||||
rr := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rr, req)
|
||||
|
||||
if rr.Code != http.StatusNoContent {
|
||||
t.Fatalf("status = %d, want 204; body = %s", rr.Code, rr.Body.String())
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user