Self-hosted workflows for coding-agent delivery. Orchestrate CodeBuddy, Codex and Claude Code with scripts and human approval gates. Includes Local workflows for coding assistants.
JavaScript agent-orchestrationagentic-workflowai-agentsai-codingclaude-codecode-reviewcodebuddycodexcoding-agentscursordeveloper-toolshuman-on-the-loopllmmcpmulti-agentsdlcself-hostedsopworkflow-automationworkflow-engine
fix(auth): define password-attempt limits per server and per request kind (#139)
Robert06223d35a52ccc14
diff --git a/internal/httpapi/auth_password.go b/internal/httpapi/auth_password.goindex 3dedf740..cd1adb15 100644--- a/internal/httpapi/auth_password.go+++ b/internal/httpapi/auth_password.go@@ -14,32 +14,70 @@ type loginAttempts struct {until time.Time}-var passwordAttempts = struct {- sync.Mutex+// Password attempts allowed per client IP per window, and the number of IPs+// tracked at once before new ones are refused.+const (+ passwordAttemptLimit = 10+ passwordAttemptWindow = time.Minute+ passwordAttemptSources = 4096+)++// passwordLimiter is the brute-force budget for one API server. Login and+// registration share it: both reveal whether credentials or account names+// exist. Each server owns its own limiter, so separately constructed servers+// (and tests) never share counters.+//+// Contract:+// - Every login request counts, malformed or not, before any lookup.+// - A registration request counts once it is well-formed and valid, i.e.+// when it reaches account creation (including "login taken", which+// discloses that an account exists). Malformed or invalid sign-up input+// is rejected for free: it reveals nothing and creates nothing.+type passwordLimiter struct {+ mu sync.Mutexentries map[string]loginAttempts-}{entries: map[string]loginAttempts{}}+ now func() time.Time+}++func newPasswordLimiter() *passwordLimiter {+ return &passwordLimiter{entries: map[string]loginAttempts{}, now: time.Now}+}-func allowPasswordAttempt(ip string) bool {- passwordAttempts.Lock()- defer passwordAttempts.Unlock()- now := time.Now()- for k, v := range passwordAttempts.entries {+func (l *passwordLimiter) allow(ip string) bool {+ l.mu.Lock()+ defer l.mu.Unlock()+ now := l.now()+ for k, v := range l.entries {if now.After(v.until) {- delete(passwordAttempts.entries, k)+ delete(l.entries, k)}}- v := passwordAttempts.entries[ip]- if v.count >= 10 || (v.count == 0 && len(passwordAttempts.entries) >= 4096) {+ v := l.entries[ip]+ if v.count >= passwordAttemptLimit || (v.count == 0 && len(l.entries) >= passwordAttemptSources) {return false}if v.count == 0 {- v.until = now.Add(time.Minute)+ v.until = now.Add(passwordAttemptWindow)}v.count++- passwordAttempts.entries[ip] = v+ l.entries[ip] = vreturn true}+// passwordLimiterInit guards lazy creation for handlers built without New.+var passwordLimiterInit sync.Mutex++// allowPasswordAttempt spends one attempt from this server's budget.+func (d *deps) allowPasswordAttempt(ip string) bool {+ passwordLimiterInit.Lock()+ if d.passwordAttempts == nil {+ d.passwordAttempts = newPasswordLimiter()+ }+ limiter := d.passwordAttempts+ passwordLimiterInit.Unlock()+ return limiter.allow(ip)+}+func (h *authHandlers) authPassword(c *gin.Context) {// Require a same-origin browser request; proxy headers cannot grant identity.origin, err := url.Parse(c.GetHeader("Origin"))@@ -47,7 +85,7 @@ func (h *authHandlers) authPassword(c *gin.Context) {c.JSON(http.StatusForbidden, gin.H{"error": "invalid request origin"})return}- if !allowPasswordAttempt(c.RemoteIP()) {+ if !h.allowPasswordAttempt(c.RemoteIP()) {c.JSON(http.StatusTooManyRequests, gin.H{"error": "Too many attempts. Try again in a minute."})return}diff --git a/internal/httpapi/auth_password_limiter_test.go b/internal/httpapi/auth_password_limiter_test.gonew file mode 100644index 00000000..f7e206aa--- /dev/null+++ b/internal/httpapi/auth_password_limiter_test.go@@ -0,0 +1,126 @@+package httpapi++import (+ "bytes"+ "net/http"+ "net/http/httptest"+ "strconv"+ "testing"+ "time"++ "agentflow/internal/engine"+ "agentflow/internal/repo"+ "agentflow/internal/runtime"+)++// limiterServer is a full API server with one existing local account.+func limiterServer(t *testing.T) func(path, body string) int {+ t.Helper()+ t.Setenv("AGENTFLOW_AUTH_REQUIRED", "true")+ t.Setenv("AGENTFLOW_SCHEDULER_ENABLED", "false")+ s, err := repo.OpenTest()+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(s.Close)+ if _, err := s.CreateLocalAccount("owner", "a-long-enough-password", true); err != nil {+ t.Fatal(err)+ }+ h := New(s, engine.New(s, runtime.NewManager(t.TempDir())), nil, "", "")+ return func(path, body string) int {+ r := httptest.NewRequest(http.MethodPost, "http://localhost"+path, bytes.NewBufferString(body))+ r.Header.Set("Content-Type", "application/json")+ r.Header.Set("Origin", "http://localhost")+ w := httptest.NewRecorder()+ h.ServeHTTP(w, r)+ return w.Code+ }+}++const wrongLogin = `{"login":"owner","password":"not-the-password"}`++func spendBudget(t *testing.T, call func(path, body string) int, path, body string, want int) {+ t.Helper()+ for i := 0; i < passwordAttemptLimit; i++ {+ if code := call(path, body); code != want {+ t.Fatalf("attempt %d on %s = %d, want %d", i+1, path, code, want)+ }+ }+}++func TestLoginCountsEveryAttempt(t *testing.T) {+ call := limiterServer(t)+ // Malformed login requests are credential probes too: they count.+ spendBudget(t, call, "/api/auth/password", `{"login":`, http.StatusBadRequest)+ if code := call("/api/auth/password", `{"login":"owner","password":"a-long-enough-password"}`); code != http.StatusTooManyRequests {+ t.Fatalf("login after %d malformed attempts = %d, want 429", passwordAttemptLimit, code)+ }+}++func TestRegistrationCountsOnlyValidRequests(t *testing.T) {+ t.Setenv("AGENTFLOW_ALLOW_SIGNUP", "true")+ call := limiterServer(t)+ // Malformed or invalid sign-ups reveal and create nothing: they are free.+ for i, body := range []string{`{`, `not json`, `{"login":"-bad","password":"a-long-enough-password"}`, `{"login":"ok-user","password":"short"}`} {+ for j := 0; j < passwordAttemptLimit; j++ {+ if code := call("/api/auth/register", body); code != http.StatusBadRequest {+ t.Fatalf("invalid sign-up %d/%d = %d, want 400", i, j, code)+ }+ }+ }+ // So the shared budget is intact for a real login.+ if code := call("/api/auth/password", `{"login":"owner","password":"a-long-enough-password"}`); code != http.StatusOK {+ t.Fatalf("login after free invalid sign-ups = %d", code)+ }+ // Valid sign-ups reach the accounts (and "taken" discloses one): they+ // count, and share the budget with login, which already spent one.+ for i := 1; i < passwordAttemptLimit; i++ {+ if code := call("/api/auth/register", `{"login":"owner","password":"a-long-enough-password"}`); code != http.StatusConflict {+ t.Fatalf("valid sign-up %d = %d, want 409", i+1, code)+ }+ }+ if code := call("/api/auth/register", `{"login":"fresh-user","password":"a-long-enough-password"}`); code != http.StatusTooManyRequests {+ t.Fatalf("sign-up after the budget = %d, want 429", code)+ }+ if code := call("/api/auth/password", wrongLogin); code != http.StatusTooManyRequests {+ t.Fatalf("login after sign-ups spent the budget = %d, want 429", code)+ }+}++func TestPasswordBudgetIsPerServer(t *testing.T) {+ first, second := limiterServer(t), limiterServer(t)+ spendBudget(t, first, "/api/auth/password", wrongLogin, http.StatusUnauthorized)+ if code := first("/api/auth/password", wrongLogin); code != http.StatusTooManyRequests {+ t.Fatalf("first server not limited: %d", code)+ }+ if code := second("/api/auth/password", wrongLogin); code != http.StatusUnauthorized {+ t.Fatalf("second server inherited the first server's attempts: %d", code)+ }+}++func TestPasswordLimiterWindowAndSourceCap(t *testing.T) {+ now := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)+ l := newPasswordLimiter()+ l.now = func() time.Time { return now }+ for i := 0; i < passwordAttemptLimit; i++ {+ if !l.allow("198.51.100.1") {+ t.Fatalf("attempt %d refused", i+1)+ }+ }+ if l.allow("198.51.100.1") {+ t.Fatal("attempt over the limit allowed")+ }+ now = now.Add(passwordAttemptWindow + time.Second)+ if !l.allow("198.51.100.1") {+ t.Fatal("budget did not reset after the window")+ }+ for i := 1; i < passwordAttemptSources; i++ {+ l.allow("10.0." + strconv.Itoa(i/256) + "." + strconv.Itoa(i%256))+ }+ if l.allow("203.0.113.9") {+ t.Fatal("a new source was admitted past the tracking cap")+ }+ if !l.allow("198.51.100.1") {+ t.Fatal("a tracked source lost its remaining budget at the cap")+ }+}diff --git a/internal/httpapi/auth_register.go b/internal/httpapi/auth_register.goindex 6f6edc64..d609c856 100644--- a/internal/httpapi/auth_register.go+++ b/internal/httpapi/auth_register.go@@ -64,10 +64,6 @@ func (h *authHandlers) authRegister(c *gin.Context) {c.JSON(http.StatusForbidden, gin.H{"error": "invalid request origin"})return}- if !allowPasswordAttempt(c.RemoteIP()) {- c.JSON(http.StatusTooManyRequests, gin.H{"error": "Too many attempts. Try again in a minute."})- return- }c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 4096)var input struct {Login string `json:"login"`@@ -86,6 +82,12 @@ func (h *authHandlers) authRegister(c *gin.Context) {c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Sprintf("密码需 %d–%d 个字符", repo.MinPasswordLength, repo.MaxPasswordLength)})return}+ // Only a valid request reaches the accounts, so only it spends the shared+ // password budget (see passwordLimiter).+ if !h.allowPasswordAttempt(c.RemoteIP()) {+ c.JSON(http.StatusTooManyRequests, gin.H{"error": "Too many attempts. Try again in a minute."})+ return+ }registerMu.Lock()first := h.repo.LocalAccountCount() == 0if !first && !signupEnabled() {diff --git a/internal/httpapi/server.go b/internal/httpapi/server.goindex bca13003..16a499b9 100644--- a/internal/httpapi/server.go+++ b/internal/httpapi/server.go@@ -43,6 +43,8 @@ type deps struct {schedule *schedule.ServiceauthClient *auth.Clientapi http.Handler+ // passwordAttempts is this server's brute-force budget (auth_password.go).+ passwordAttempts *passwordLimiter}// configureSync 是跨领域共享的依赖配置行为(mcp/issues/sync 都调用)。@@ -120,7 +122,7 @@ func NewWithNotificationsAndBackground(ctx context.Context, s *repo.Store, e *en}func newWithNotifications(s *repo.Store, e *engine.Engine, syncSvc *tracker.Service, basicUser, basicPass string, notifications *notification.Service, bg *Background, startBackground func(*assistantHandlers, *runsHandlers)) *gin.Engine {- d := &deps{repo: s, engine: e, sync: syncSvc, authClient: auth.NewClientFromEnv()}+ d := &deps{repo: s, engine: e, sync: syncSvc, authClient: auth.NewClientFromEnv(), passwordAttempts: newPasswordLimiter()}if err := ensureDefaultMCPsForAllProjects(s); err != nil {log.Printf("ensure default project MCPs: %v", err)} else {