diff --git a/services/idp/assets/identifier/index.html b/services/idp/assets/identifier/index.html index 702088010b1..f1cbf7b3027 100644 --- a/services/idp/assets/identifier/index.html +++ b/services/idp/assets/identifier/index.html @@ -19,6 +19,7 @@ data-msg-invalid="{{.ErrInvalid}}" data-msg-failed="{{.ErrFailed}}" data-msg-default="{{.ErrDefault}}" + data-msg-pending="{{.ErrPending}}" data-msg-signing-in="{{.ButtonSigningIn}}" data-msg-sign-in="{{.ButtonSignIn}}">
@@ -52,6 +53,7 @@ var MSG_INVALID = form.dataset.msgInvalid; var MSG_FAILED = form.dataset.msgFailed; var MSG_DEFAULT = form.dataset.msgDefault; + var MSG_PENDING = form.dataset.msgPending; var MSG_SIGNING_IN = form.dataset.msgSigningIn; var MSG_SIGN_IN = form.dataset.msgSignIn; @@ -178,6 +180,10 @@ return; } } + if (result.status === 403 && result.data && result.data.error === "registration_pending") { + showError(MSG_PENDING); + return; + } if (result.status === 204 || result.status === 401 || (result.data && !result.data.success)) { showError(MSG_INVALID); return; diff --git a/services/idp/pkg/discord/logon.go b/services/idp/pkg/discord/logon.go new file mode 100644 index 00000000000..b834fdb143e --- /dev/null +++ b/services/idp/pkg/discord/logon.go @@ -0,0 +1,56 @@ +package discord + +import ( + "bytes" + "encoding/json" + "io" + "net/http" + "net/http/httptest" +) + +const maxLogonBody = 64 << 10 + +// GuardLogon wraps the lico logon endpoint. lico cannot tell a pending +// (disabled) account from a wrong password, so when the logon fails for a +// username that waits for approval, the response is replaced by +// {"success":false,"error":"registration_pending"} with status 403. +// All other requests pass through unchanged. +func (h *Handler) GuardLogon(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(io.LimitReader(r.Body, maxLogonBody)) + if err != nil { + http.Error(w, "bad request", http.StatusBadRequest) + return + } + r.Body = io.NopCloser(bytes.NewReader(body)) + + var req struct { + State string `json:"state"` + Params []string `json:"params"` + } + if json.Unmarshal(body, &req) != nil || len(req.Params) == 0 || !h.opt.Pending.IsPendingUsername(req.Params[0]) { + next.ServeHTTP(w, r) + return + } + + rec := httptest.NewRecorder() + next.ServeHTTP(rec, r) + var res struct { + Success bool `json:"success"` + } + if rec.Code == http.StatusOK && json.Unmarshal(rec.Body.Bytes(), &res) == nil && res.Success { + // The account was enabled meanwhile: keep the lico response. + for k, v := range rec.Header() { + w.Header()[k] = v + } + w.WriteHeader(rec.Code) + _, _ = w.Write(rec.Body.Bytes()) + return + } + writeJSON(w, http.StatusForbidden, map[string]any{ + "success": false, + "state": req.State, + "error": ErrCodePendingApproval, + }) + }) +} diff --git a/services/idp/pkg/discord/logon_test.go b/services/idp/pkg/discord/logon_test.go new file mode 100644 index 00000000000..fb8cd9c991e --- /dev/null +++ b/services/idp/pkg/discord/logon_test.go @@ -0,0 +1,64 @@ +package discord + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func fakeLico(success bool, calls *int) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + *calls++ + b, _ := io.ReadAll(r.Body) + if !strings.Contains(string(b), "params") { + w.WriteHeader(http.StatusBadRequest) + return + } + if success { + w.Header().Set("X-Lico", "1") + _, _ = w.Write([]byte(`{"success":true}`)) + return + } + w.WriteHeader(http.StatusNoContent) + }) +} + +func postLogon(h http.Handler, user string) *httptest.ResponseRecorder { + body := `{"state":"s1","params":["` + user + `","pw","1"]}` + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest(http.MethodPost, "/signin/v1/identifier/_/logon", strings.NewReader(body))) + return rec +} + +func TestGuardLogonPendingUser(t *testing.T) { + h := newHarness(t) + _ = h.pending.Add(PendingUser{UserID: "u1", Username: "alice", Source: SourceWeb}) + calls := 0 + rec := postLogon(h.handler.GuardLogon(fakeLico(false, &calls)), "Alice") + var res map[string]any + _ = json.Unmarshal(rec.Body.Bytes(), &res) + if rec.Code != http.StatusForbidden || res["error"] != ErrCodePendingApproval || res["success"] != false || calls != 1 { + t.Fatalf("status = %d body = %s calls = %d", rec.Code, rec.Body, calls) + } +} + +func TestGuardLogonPassesOtherUsers(t *testing.T) { + h := newHarness(t) + calls := 0 + if rec := postLogon(h.handler.GuardLogon(fakeLico(false, &calls)), "bob"); rec.Code != http.StatusNoContent || calls != 1 { + t.Fatalf("failed logon must stay a lico failure: %d", rec.Code) + } +} + +func TestGuardLogonApprovedMeanwhile(t *testing.T) { + h := newHarness(t) + _ = h.pending.Add(PendingUser{UserID: "u1", Username: "alice", Source: SourceWeb}) + calls := 0 + rec := postLogon(h.handler.GuardLogon(fakeLico(true, &calls)), "alice") + if rec.Code != http.StatusOK || rec.Header().Get("X-Lico") != "1" || !strings.Contains(rec.Body.String(), `"success":true`) { + t.Fatalf("status = %d body = %s", rec.Code, rec.Body) + } +} diff --git a/services/idp/pkg/discord/pending.go b/services/idp/pkg/discord/pending.go index 963161575f6..1b37346cab5 100644 --- a/services/idp/pkg/discord/pending.go +++ b/services/idp/pkg/discord/pending.go @@ -3,6 +3,7 @@ package discord import ( "fmt" "sort" + "strings" "sync" "time" ) @@ -52,6 +53,23 @@ func (s *PendingStore) IsPending(userID string) bool { return ok } +// IsPendingUsername reports whether an account with the username waits for +// approval. Usernames are compared case-insensitively like LDAP does. +func (s *PendingStore) IsPendingUsername(name string) bool { + name = strings.TrimSpace(name) + if name == "" { + return false + } + s.mu.RLock() + defer s.mu.RUnlock() + for _, p := range s.cur { + if strings.EqualFold(p.Username, name) { + return true + } + } + return false +} + // Get returns the pending account userID. func (s *PendingStore) Get(userID string) (PendingUser, bool) { s.mu.RLock() diff --git a/services/idp/pkg/service/v0/service.go b/services/idp/pkg/service/v0/service.go index 8a2dc051eb8..56680a0a37b 100644 --- a/services/idp/pkg/service/v0/service.go +++ b/services/idp/pkg/service/v0/service.go @@ -336,6 +336,10 @@ func (idp *IDP) initMux(ctx context.Context, r []server.WithRoutes, h http.Handl idp.mux.Group(func(r chi.Router) { // routes handled by lico r.Use(middleware.CheckRedirect(options.Config, options.Logger)) + if idp.discord != nil { + // Reports pending approval instead of a generic login failure. + r.Post("/signin/v1/identifier/_/logon", idp.discord.GuardLogon(gm).ServeHTTP) + } r.Mount("/", gm) }) @@ -361,6 +365,7 @@ type indexData struct { LabelUsername, LabelPassword string ButtonSignIn, ButtonSigningIn string ErrRequired, ErrInvalid, ErrFailed, ErrDefault string + ErrPending string PasswordResetURI template.URL ResetLabel string DiscordLoginURL, DiscordLabel, OrLabel string @@ -454,6 +459,7 @@ func (idp *IDP) Index() http.HandlerFunc { ErrInvalid: t.Get("Login failed. Invalid username or password."), ErrFailed: t.Get("Login failed. Invalid username or password."), ErrDefault: t.Get("Login failed. Invalid username or password."), + ErrPending: localized(r, "Your account is waiting for an administrator's approval.", "現在、管理者の承認待ちです。"), PasswordResetURI: idp.passwordResetURI, ResetLabel: t.Get("Reset password"), }