feat(idp): Discord 登録の経路チェックと承認待ちワークフローを追加

- 承認待ちアカウントを pending.json に保存 (ユーザー ID、登録元、申請日時)
- Discord 登録が無効なら新規 Discord ユーザーを registration_closed で拒否
- 承認制が有効なら accountEnabled=false で作成し、申請受付画面を表示 (セッションは発行しない)
- 承認待ちユーザーの Discord ログインを registration_pending で遮断
- 新しいエラーコードの文言 (英語/日本語) を追加
This commit is contained in:
sylph committed 2026-11-01 22:31:26 +09:00
1 parent 019e65a951
commit fbe1b9560b
9 files changed
+352 -12

No files matched your search

+103
View File
@@ -0,0 +1,103 @@
package discord
import (
"net/http"
"net/url"
"testing"
)
func TestDiscordOnlySignupWithApprovalCreatesPendingAccount(t *testing.T) {
h := newHarness(t)
if err := h.reg.Save(RegistrationSettings{AllowRegistration: true, AllowWeb: false, AllowDiscord: true, RequireApproval: true}); err != nil {
t.Fatal(err)
}
f, ck := h.startSignup("client_id=web")
rec := h.postSignup(url.Values{"token": {f.Token}, "username": {"alice2"}}, ck)
if rec.Code != http.StatusOK || h.render.code != ErrCodeRegistrationSubmitted {
t.Fatalf("status = %d code = %q", rec.Code, h.render.code)
}
if len(h.prov.createdEnabled) != 1 || h.prov.createdEnabled[0] {
t.Fatalf("account must be created disabled, got %v", h.prov.createdEnabled)
}
if h.sess.userID != "" {
t.Error("no logon may be issued for a pending account")
}
p, ok := h.pending.Get(h.prov.id)
if !ok || p.Source != SourceDiscord || p.Username != "alice2" || p.RequestedAt.IsZero() {
t.Fatalf("pending = %+v ok = %v", p, ok)
}
if c := findCookie(rec, signupCookieName); c == nil || c.MaxAge >= 0 {
t.Error("signup cookie was not cleared")
}
}
func TestSignupWithoutApprovalCreatesEnabledAccount(t *testing.T) {
h := newHarness(t)
f, ck := h.startSignup("")
h.postSignup(url.Values{"token": {f.Token}, "username": {"alice2"}}, ck)
if len(h.prov.createdEnabled) != 1 || !h.prov.createdEnabled[0] {
t.Fatalf("createdEnabled = %v", h.prov.createdEnabled)
}
if h.pending.IsPending(h.prov.id) || h.sess.userID != h.prov.id {
t.Error("account without approval must log on directly")
}
}
func TestDiscordRegistrationClosed(t *testing.T) {
for name, s := range map[string]RegistrationSettings{
"discord off": {AllowRegistration: true, AllowWeb: true},
"registration off": {AllowDiscord: true},
} {
t.Run(name, func(t *testing.T) {
h := newHarness(t)
if err := h.reg.Save(s); err != nil {
t.Fatal(err)
}
h.prov.missing = true
state, c := h.login("")
rec := h.callback(cbQuery(testCode, state), c)
if rec.Code != http.StatusForbidden || h.render.code != ErrCodeRegistrationClosed {
t.Fatalf("status = %d code = %q", rec.Code, h.render.code)
}
if h.render.signup != nil || len(h.prov.created) != 0 {
t.Error("signup form shown or account created while closed")
}
})
}
}
func TestSignupClosedAfterFormWasShown(t *testing.T) {
h := newHarness(t)
f, ck := h.startSignup("")
if err := h.reg.Save(RegistrationSettings{}); err != nil {
t.Fatal(err)
}
rec := h.postSignup(url.Values{"token": {f.Token}, "username": {"alice2"}}, ck)
if rec.Code != http.StatusForbidden || len(h.prov.created) != 0 {
t.Fatalf("status = %d created = %v", rec.Code, h.prov.created)
}
}
func TestPendingUserCannotLogInWithDiscord(t *testing.T) {
h := newHarness(t)
if err := h.pending.Add(PendingUser{UserID: h.prov.id, Username: "alice", Source: SourceDiscord}); err != nil {
t.Fatal(err)
}
state, c := h.login("")
rec := h.callback(cbQuery(testCode, state), c)
if rec.Code != http.StatusForbidden || h.render.code != ErrCodePendingApproval {
t.Fatalf("status = %d code = %q", rec.Code, h.render.code)
}
if h.sess.userID != "" {
t.Error("logon issued for a pending account")
}
// After approval the same login succeeds.
if err := h.pending.Remove(h.prov.id); err != nil {
t.Fatal(err)
}
state, c = h.login("")
if rec := h.callback(cbQuery(testCode, state), c); rec.Code != http.StatusOK || h.sess.userID != h.prov.id {
t.Fatalf("status = %d logon = %q", rec.Code, h.sess.userID)
}
}
+19 -2
View File
@@ -33,6 +33,13 @@ const (
// ErrCodeLinkConflict means the Discord user is linked to another
// account, or the account is linked to another Discord user.
ErrCodeLinkConflict = "discord_link_conflict"
// ErrCodeRegistrationClosed means new accounts cannot be created this way.
ErrCodeRegistrationClosed = "registration_closed"
// ErrCodePendingApproval means the account waits for an admin's approval.
ErrCodePendingApproval = "registration_pending"
// ErrCodeRegistrationSubmitted is shown right after a pending signup.
ErrCodeRegistrationSubmitted = "registration_submitted"
)
const maxQueryLen = 4096
@@ -53,7 +60,8 @@ type Provisioner interface {
// Create creates the account for u with the chosen username and returns
// its oCIS user ID. It returns ErrUsernameInvalid or ErrUsernameTaken
// when the username cannot be used.
Create(ctx context.Context, u *User, username string) (string, error)
// enabled=false creates the account disabled (pending approval).
Create(ctx context.Context, u *User, username string, enabled bool) (string, error)
// Link links u to the existing account userID. It returns
// ErrIdentityConflict when either side is linked to someone else.
Link(ctx context.Context, userID string, u *User) error
@@ -88,6 +96,7 @@ type Renderer interface {
type Options struct {
Store *Store
Registration *RegistrationStore
Pending *PendingStore
API API
Provisioner Provisioner
Sessions SessionIssuer
@@ -117,7 +126,7 @@ type Handler struct {
// NewHandler returns a Handler.
func NewHandler(opt Options) (*Handler, error) {
switch {
case opt.Store == nil, opt.Registration == nil, opt.API == nil, opt.Provisioner == nil, opt.Sessions == nil, opt.Admin == nil, opt.Users == nil, opt.Render == nil:
case opt.Store == nil, opt.Registration == nil, opt.Pending == nil, opt.API == nil, opt.Provisioner == nil, opt.Sessions == nil, opt.Admin == nil, opt.Users == nil, opt.Render == nil:
return nil, errors.New("discord handler: missing dependency")
case len(opt.StateKey) < 32:
return nil, errors.New("discord handler: state key must be at least 32 bytes")
@@ -283,10 +292,18 @@ func (h *Handler) callback(w http.ResponseWriter, r *http.Request) {
return
}
if userID == "" {
if !h.opt.Registration.Get().DiscordAllowed() {
h.opt.Render.Error(w, r, http.StatusForbidden, ErrCodeRegistrationClosed)
return
}
// No account yet: let the user choose the username first.
h.startSignup(w, r, user, sd.Query)
return
}
if h.opt.Pending.IsPending(userID) {
h.opt.Render.Error(w, r, http.StatusForbidden, ErrCodePendingApproval)
return
}
if err := h.opt.Sessions.IssueLogon(ctx, w, userID); err != nil {
logger.Error().Err(err).Str("user_id", userID).Msg("discord logon cookie failed")
h.opt.Render.Error(w, r, http.StatusInternalServerError, ErrCodeServer)
+11 -1
View File
@@ -55,6 +55,8 @@ type fakeProvisioner struct {
missing bool
created []string
createErr error
// createdEnabled records the enabled flag of each Create call.
createdEnabled []bool
// link flow
linkErr error
linkedID string
@@ -75,8 +77,9 @@ func (f *fakeProvisioner) Lookup(_ context.Context, u *User) (string, error) {
return f.id, nil
}
func (f *fakeProvisioner) Create(_ context.Context, u *User, username string) (string, error) {
func (f *fakeProvisioner) Create(_ context.Context, u *User, username string, enabled bool) (string, error) {
f.user = u
f.createdEnabled = append(f.createdEnabled, enabled)
if f.createErr != nil {
return "", f.createErr
}
@@ -113,6 +116,7 @@ type harness struct {
fd *fakeDiscord
store *Store
reg *RegistrationStore
pending *PendingStore
render *fakeRenderer
prov *fakeProvisioner
sess *fakeSessions
@@ -152,10 +156,16 @@ func newHarness(t *testing.T) *harness {
t.Fatal(err)
}
h.reg = reg
pending, err := NewPendingStore(filepath.Join(t.TempDir(), "pending.json"))
if err != nil {
t.Fatal(err)
}
h.pending = pending
h.handler, err = NewHandler(Options{
Store: st,
Registration: reg,
Pending: pending,
API: h.fd.client(),
Provisioner: h.prov,
Sessions: h.sess,
+118
View File
@@ -0,0 +1,118 @@
package discord
import (
"fmt"
"sort"
"sync"
"time"
)
// Registration sources stored with a pending account.
const (
SourceWeb = "web"
SourceDiscord = "discord"
)
// PendingUser is an account that was created disabled and waits for an
// administrator's approval.
type PendingUser struct {
UserID string `json:"user_id"`
Username string `json:"username"`
DisplayName string `json:"display_name,omitempty"`
Mail string `json:"mail,omitempty"`
Source string `json:"source"`
RequestedAt time.Time `json:"requested_at"`
}
// PendingStore persists the pending accounts as a JSON file (mode 0600).
type PendingStore struct {
path string
mu sync.RWMutex
cur map[string]PendingUser
}
// NewPendingStore loads the pending accounts from path. A missing file means
// no pending accounts.
func NewPendingStore(path string) (*PendingStore, error) {
s := &PendingStore{path: path, cur: map[string]PendingUser{}}
if err := readJSONFile(path, &s.cur); err != nil {
return nil, fmt.Errorf("load pending accounts: %w", err)
}
if s.cur == nil {
s.cur = map[string]PendingUser{}
}
return s, nil
}
// IsPending reports whether userID waits for approval.
func (s *PendingStore) IsPending(userID string) bool {
s.mu.RLock()
defer s.mu.RUnlock()
_, ok := s.cur[userID]
return ok
}
// Get returns the pending account userID.
func (s *PendingStore) Get(userID string) (PendingUser, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
p, ok := s.cur[userID]
return p, ok
}
// List returns the pending accounts, oldest request first.
func (s *PendingStore) List() []PendingUser {
s.mu.RLock()
defer s.mu.RUnlock()
out := make([]PendingUser, 0, len(s.cur))
for _, p := range s.cur {
out = append(out, p)
}
sort.Slice(out, func(i, j int) bool {
if out[i].RequestedAt.Equal(out[j].RequestedAt) {
return out[i].UserID < out[j].UserID
}
return out[i].RequestedAt.Before(out[j].RequestedAt)
})
return out
}
// Add records p as pending.
func (s *PendingStore) Add(p PendingUser) error {
if p.UserID == "" {
return fmt.Errorf("pending account without user id")
}
s.mu.Lock()
defer s.mu.Unlock()
next := s.copyLocked()
next[p.UserID] = p
return s.saveLocked(next)
}
// Remove forgets userID. Removing an unknown ID is not an error.
func (s *PendingStore) Remove(userID string) error {
s.mu.Lock()
defer s.mu.Unlock()
if _, ok := s.cur[userID]; !ok {
return nil
}
next := s.copyLocked()
delete(next, userID)
return s.saveLocked(next)
}
func (s *PendingStore) copyLocked() map[string]PendingUser {
next := make(map[string]PendingUser, len(s.cur)+1)
for k, v := range s.cur {
next[k] = v
}
return next
}
func (s *PendingStore) saveLocked(next map[string]PendingUser) error {
if err := writeJSONFile(s.path, next); err != nil {
return fmt.Errorf("save pending accounts: %w", err)
}
s.cur = next
return nil
}
+47
View File
@@ -0,0 +1,47 @@
package discord
import (
"path/filepath"
"testing"
"time"
)
func TestPendingStore(t *testing.T) {
path := filepath.Join(t.TempDir(), "pending.json")
s, err := NewPendingStore(path)
if err != nil {
t.Fatal(err)
}
if len(s.List()) != 0 || s.IsPending("a") {
t.Fatal("new store must be empty")
}
t0 := time.Unix(1700000000, 0).UTC()
if err := s.Add(PendingUser{UserID: "b", Username: "bob", Source: SourceWeb, RequestedAt: t0.Add(time.Minute)}); err != nil {
t.Fatal(err)
}
if err := s.Add(PendingUser{UserID: "a", Username: "alice", Source: SourceDiscord, RequestedAt: t0}); err != nil {
t.Fatal(err)
}
if err := s.Add(PendingUser{}); err == nil {
t.Error("an entry without user id must be refused")
}
reloaded, err := NewPendingStore(path)
if err != nil {
t.Fatal(err)
}
l := reloaded.List()
if len(l) != 2 || l[0].UserID != "a" || l[1].UserID != "b" || l[0].Source != SourceDiscord {
t.Fatalf("list = %+v", l)
}
if err := reloaded.Remove("a"); err != nil {
t.Fatal(err)
}
if err := reloaded.Remove("unknown"); err != nil {
t.Fatal(err)
}
if reloaded.IsPending("a") || !reloaded.IsPending("b") {
t.Fatal("remove did not work")
}
}
+2 -2
View File
@@ -128,7 +128,7 @@ func (p GraphProvisioner) Lookup(ctx context.Context, du *User) (string, error)
// Create implements Provisioner. It creates the account with the username
// the user chose and links the Discord identity.
func (p GraphProvisioner) Create(ctx context.Context, du *User, username string) (string, error) {
func (p GraphProvisioner) Create(ctx context.Context, du *User, username string, enabled bool) (string, error) {
if err := checkDiscordUser(du); err != nil {
return "", err
}
@@ -149,7 +149,7 @@ func (p GraphProvisioner) Create(ctx context.Context, du *User, username string)
if mail := du.VerifiedEmail(); mail != "" {
nu.SetMail(mail)
}
nu.SetAccountEnabled(true)
nu.SetAccountEnabled(enabled)
nu.SetIdentities([]libregraph.ObjectIdentity{newIdentity(du.ID)})
created, err := p.Dir.CreateUser(ctx, nu)
+6 -6
View File
@@ -184,7 +184,7 @@ func TestLookupIdentityConflictByEmail(t *testing.T) {
func TestCreateUsesChosenUsername(t *testing.T) {
dir := newFakeDirectory()
id, err := prov(dir).Create(context.Background(), discordUser(), "alice")
id, err := prov(dir).Create(context.Background(), discordUser(), "alice", true)
if err != nil || id != "new-user-id" || len(dir.created) != 1 {
t.Fatalf("id = %q created = %d err = %v", id, len(dir.created), err)
}
@@ -201,7 +201,7 @@ func TestCreateUnverifiedEmailIsNotStored(t *testing.T) {
dir := newFakeDirectory()
du := discordUser()
du.Verified = false
if _, err := prov(dir).Create(context.Background(), du, "alice"); err != nil {
if _, err := prov(dir).Create(context.Background(), du, "alice", true); err != nil {
t.Fatal(err)
}
if dir.created[0].HasMail() {
@@ -212,11 +212,11 @@ func TestCreateUnverifiedEmailIsNotStored(t *testing.T) {
func TestCreateRejectsUsername(t *testing.T) {
dir := newFakeDirectory(graphUser("x", "Bob", "", "Bob", ""))
for _, name := range []string{"", "ab", "1alice", "a b", "alice/x", "alice@example.com", strings.Repeat("a", 33)} {
if _, err := prov(dir).Create(context.Background(), discordUser(), name); !errors.Is(err, ErrUsernameInvalid) {
if _, err := prov(dir).Create(context.Background(), discordUser(), name, true); !errors.Is(err, ErrUsernameInvalid) {
t.Errorf("%q: err = %v, want ErrUsernameInvalid", name, err)
}
}
if _, err := prov(dir).Create(context.Background(), discordUser(), "bob"); !errors.Is(err, ErrUsernameTaken) {
if _, err := prov(dir).Create(context.Background(), discordUser(), "bob", true); !errors.Is(err, ErrUsernameTaken) {
t.Errorf("err = %v, want ErrUsernameTaken", err)
}
if len(dir.created) != 0 {
@@ -229,12 +229,12 @@ func TestProvisionErrors(t *testing.T) {
if _, err := p.Lookup(context.Background(), &User{ID: "not-a-snowflake"}); err == nil {
t.Error("expected an error for an invalid discord id")
}
if _, err := p.Create(context.Background(), nil, "alice"); err == nil {
if _, err := p.Create(context.Background(), nil, "alice", true); err == nil {
t.Error("expected an error for a nil user")
}
dir := newFakeDirectory()
dir.createErr = errors.New("graph returned 500")
if _, err := prov(dir).Create(context.Background(), discordUser(), "alice"); err == nil || !strings.Contains(err.Error(), "graph returned 500") {
if _, err := prov(dir).Create(context.Background(), discordUser(), "alice", true); err == nil || !strings.Contains(err.Error(), "graph returned 500") {
t.Errorf("err = %v", err)
}
}
+28 -1
View File
@@ -173,8 +173,14 @@ func (h *Handler) signup(w http.ResponseWriter, r *http.Request) {
return
}
if userID == "" {
reg := h.opt.Registration.Get()
if !reg.DiscordAllowed() {
http.SetCookie(w, h.signupCookie("", -1))
h.opt.Render.Error(w, r, http.StatusForbidden, ErrCodeRegistrationClosed)
return
}
username := strings.TrimSpace(r.PostForm.Get("username"))
userID, err = h.opt.Provisioner.Create(ctx, du, username)
userID, err = h.opt.Provisioner.Create(ctx, du, username, !reg.RequireApproval)
switch {
case errors.Is(err, ErrUsernameInvalid):
h.opt.Render.Signup(w, r, http.StatusBadRequest, h.signupForm(sd.Token, du, username, ErrCodeUsernameInvalid))
@@ -188,9 +194,30 @@ func (h *Handler) signup(w http.ResponseWriter, r *http.Request) {
return
}
logger.Info().Str("discord_id", du.ID).Str("user_id", userID).Msg("created account for discord user")
if reg.RequireApproval {
err := h.opt.Pending.Add(PendingUser{
UserID: userID,
Username: username,
DisplayName: du.DisplayName(),
Mail: du.VerifiedEmail(),
Source: SourceDiscord,
RequestedAt: h.opt.Now().UTC(),
})
if err != nil {
// The account is disabled, so it stays locked until an admin enables it.
logger.Error().Err(err).Str("user_id", userID).Msg("could not record pending account")
}
http.SetCookie(w, h.signupCookie("", -1))
h.opt.Render.Error(w, r, http.StatusOK, ErrCodeRegistrationSubmitted)
return
}
}
http.SetCookie(w, h.signupCookie("", -1))
if h.opt.Pending.IsPending(userID) {
h.opt.Render.Error(w, r, http.StatusForbidden, ErrCodePendingApproval)
return
}
if err := h.opt.Sessions.IssueLogon(ctx, w, userID); err != nil {
logger.Error().Err(err).Str("user_id", userID).Msg("discord logon cookie failed")
h.opt.Render.Error(w, r, http.StatusInternalServerError, ErrCodeServer)
+18
View File
@@ -63,6 +63,11 @@ func newDiscordHandler(idp *IDP, options Options, mgrs *managers.Managers, autho
return nil, err
}
pending, err := discord.NewPendingStore(filepath.Join(filepath.Dir(cfg.Discord.SettingsFile), "pending.json"))
if err != nil {
return nil, err
}
index, err := discord.NewLDAPIdentities(ldapIdentityConfig(cfg))
if err != nil {
return nil, fmt.Errorf("ldap identity lookup: %w", err)
@@ -89,6 +94,7 @@ func newDiscordHandler(idp *IDP, options Options, mgrs *managers.Managers, autho
return discord.NewHandler(discord.Options{
Store: store,
Registration: registration,
Pending: pending,
API: discord.NewClient(),
Provisioner: discord.GraphProvisioner{
Dir: discord.GraphDirectory{
@@ -320,6 +326,18 @@ var discordMessages = map[string][2]string{ // {en, ja}
"This username is already taken. Please choose another one.",
"このユーザー名は既に使われています。別のユーザー名を選んでください。",
},
discord.ErrCodeRegistrationClosed: {
"New registrations are currently not accepted.",
"現在、新規登録は受け付けていません。",
},
discord.ErrCodePendingApproval: {
"Your account is waiting for an administrator's approval.",
"現在、管理者の承認待ちです。",
},
discord.ErrCodeRegistrationSubmitted: {
"Your registration request has been received. Please wait for an administrator's approval.",
"アカウント登録申請を受け付けました。管理者の承認をお待ちください。",
},
}
func discordErrorMessage(r *http.Request, code string) string {