Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
5.1 KB
Raw Blame
package handler

import (
	"context"
	"encoding/json"
	"errors"
	"net/http"
	"testing"

	"github.com/multica-ai/multica/server/internal/auth"
	"github.com/multica-ai/multica/server/internal/service"
	"github.com/multica-ai/multica/server/internal/testutil"
)

func TestLoginAccessAllowlist(t *testing.T) {
	t.Setenv("RESEND_API_KEY", "")
	t.Setenv("SMTP_HOST", "")
	a, err := auth.ParseAccessAllowlist("*@allowed.example,[email protected]", nil)
	if err != nil {
		t.Fatal(err)
	}
	auth.SetAccessAllowlist(a)
	t.Cleanup(func() { auth.SetAccessAllowlist(nil) })

	h := *testHandler
	// Signup itself is open: only the access allowlist decides.
	h.cfg = Config{AllowSignup: true}
	h.EmailService = service.NewEmailService()

	for email, want := range map[string]int{
		"[email protected]": http.StatusOK,
		"[email protected]":     http.StatusOK,
		"[email protected]":     http.StatusForbidden,
		// Existing accounts are gated too, not only new signups.
		handlerTestEmail: http.StatusForbidden,
	} {
		t.Run(email, func(t *testing.T) {
			dbfx.Cleanup(t, `DELETE FROM verification_code WHERE email = $1`, email)
			req := testutil.JSONRequest(http.MethodPost, "/auth/send-code", map[string]string{"email": email})
			testutil.Call(t, h.SendCode, req).Want(want)
			if want != http.StatusOK {
				if n := dbfx.Count(t, `SELECT count(*) FROM verification_code WHERE email = $1`, email); n != 0 {
					t.Fatal("a rejected email must not receive a code")
				}
			}
		})
	}

	const outsider = "[email protected]"
	dbfx.Cleanup(t, `DELETE FROM "user" WHERE email = $1`, outsider)
	if _, _, err := h.findOrCreateUser(context.Background(), outsider); !errors.Is(err, ErrEmailNotAllowed) {
		t.Fatalf("expected ErrEmailNotAllowed, got %v", err)
	}
	if n := dbfx.Count(t, `SELECT count(*) FROM "user" WHERE email = $1`, outsider); n != 0 {
		t.Fatal("a rejected email must not create an account")
	}
}

func TestClaimTask_AccessAllowlistFailsUnlistedOriginator(t *testing.T) {
	if testHandler == nil || testPool == nil {
		t.Skip("database not available")
	}
	t.Cleanup(func() { auth.SetAccessAllowlist(nil) })

	ctx := context.Background()
	rt := createClaimReclaimRuntime(t, ctx, "Allowlist claim rt")
	agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, rt, "Allowlist claim agent")
	agent2ID, issue2ID := createClaimReclaimAgentAndIssue(t, ctx, rt, "Allowlist claim agent 2")

	const (
		outsiderID = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"
		flakyID    = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"
	)

	unlistedTaskID := seedQueuedIssueTask(t, ctx, agentID, rt, issueID)
	dbfx.Exec(t, `UPDATE agent_task_queue SET originator_user_id = $1, accountable_user_id = $1 WHERE id = $2`, outsiderID, unlistedTaskID)

	allowedTaskID := seedQueuedIssueTask(t, ctx, agent2ID, rt, issue2ID)
	dbfx.Exec(t, `UPDATE agent_task_queue SET originator_user_id = $1, accountable_user_id = $1 WHERE id = $2`, testUserID, allowedTaskID)

	a, err := auth.ParseAccessAllowlist(handlerTestEmail, func(_ context.Context, userID string) (string, error) {
		switch userID {
		case testUserID:
			return handlerTestEmail, nil
		case outsiderID:
			return "[email protected]", nil
		case flakyID:
			return "", errors.New("database is down")
		}
		return "", nil
	})
	if err != nil {
		t.Fatal(err)
	}
	auth.SetAccessAllowlist(a)

	w := postBatchClaim(t, testWorkspaceID, []string{rt}, 5)
	if w.Code != http.StatusOK {
		t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())
	}
	var resp batchClaimReceiptResponse
	if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
		t.Fatalf("decode: %v", err)
	}
	if len(resp.Tasks) != 1 || resp.Tasks[0].ID != allowedTaskID {
		t.Fatalf("claimed = %+v, want only allowed task %s", resp.Tasks, allowedTaskID)
	}

	var unlistedStatus, unlistedErr string
	if err := testPool.QueryRow(ctx, `SELECT status, COALESCE(error, '') FROM agent_task_queue WHERE id = $1`, unlistedTaskID).Scan(&unlistedStatus, &unlistedErr); err != nil {
		t.Fatalf("read unlisted task: %v", err)
	}
	if unlistedStatus != "failed" || unlistedErr != auth.AccessNotAllowedError {
		t.Fatalf("unlisted task status=%q err=%q, want failed/%q", unlistedStatus, unlistedErr, auth.AccessNotAllowedError)
	}

	// Lookup errors must requeue the task rather than permanently failing it.
	flakyTaskID := seedQueuedIssueTask(t, ctx, agentID, rt, issueID)
	dbfx.Exec(t, `UPDATE agent_task_queue SET originator_user_id = $1, accountable_user_id = $1 WHERE id = $2`, flakyID, flakyTaskID)

	w = postBatchClaim(t, testWorkspaceID, []string{rt}, 5)
	if w.Code != http.StatusOK {
		t.Fatalf("expected 200 on lookup failure batch, got %d: %s", w.Code, w.Body.String())
	}
	resp = batchClaimReceiptResponse{}
	if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
		t.Fatalf("decode: %v", err)
	}
	if len(resp.Tasks) != 0 {
		t.Fatalf("flaky lookup must not dispatch task, got %+v", resp.Tasks)
	}
	var flakyStatus string
	if err := testPool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, flakyTaskID).Scan(&flakyStatus); err != nil {
		t.Fatalf("read flaky task: %v", err)
	}
	if flakyStatus != "queued" {
		t.Fatalf("flaky task status = %q, want queued (requeued)", flakyStatus)
	}
}