Compare commits

...
9 Commits
Author SHA1 Message Date
sylph 455d76cab4 docs(idp): 登録関連のエラーコードとファイル構成を追記する
- 直前のコミットに入らなかった表の更新を追加する
- registration_* のエラーコード、新規ファイル、RegistrationSection.spec.ts のテスト案内
2026-11-01 22:59:57 +09:00
sylph 10247ace43 docs(idp): 新規登録の設定と承認待ちワークフローを説明する
- 4 つの登録設定、ログイン画面の表示、Web 登録、承認待ちの扱いを追記
- 管理 API・エラーコード・ファイル構成の表を更新
- 承認待ちユーザー名の判別、Users 画面で有効化したときの Discord ログイン遮断などの制限を明記
2026-11-01 22:58:35 +09:00
sylph ce462dbe20 feat(admin-settings): 登録設定のトグルと承認待ち一覧を追加
- 一般設定に「登録」セクションを追加 (Settings.ReadWrite 権限が必要)
- 登録受付 / Web 登録 / Discord 登録 / 管理者承認を切り替えた時点で保存し、失敗したら元に戻す
- 承認待ちアカウントをユーザー名・メール・登録元・申請日時で一覧表示する
- 承認ボタンで有効化し、拒否は確認ダイアログの後にアカウントを削除する
2026-11-01 22:57:06 +09:00
sylph cf505b3065 feat(idp): ログイン画面で登録設定に応じて登録リンクと Discord ボタンを切り替える
- Web 登録が有効なときだけ「アカウント作成」リンクを表示する
- Discord 登録が有効なら Discord ボタンを「Discord でログイン / 登録」と表示する
- 判定は公開 API と同じ PublicRegistration を使い、サーバー側で描画する
2026-11-01 22:51:22 +09:00
sylph f8d3daf7ff feat(idp): 経路チェック付きの Web セルフ登録を追加
- GET/POST /oauth2/discord/register で登録フォームを表示・受け付ける
- Web 登録が無効、または登録受付が OFF のときは registration_closed で拒否
- Origin/Referer が公開 URL と違う POST を拒否する
- ユーザー名・メール・パスワードを検証し、重複やパスワードポリシー違反はフォームに表示
- 承認制が有効なら accountEnabled=false で作成し、登録元 web として承認待ちに記録
- 段階③で抜けていた Accounts の組み立てを追加 (本番で NewHandler が失敗していた)
2026-11-01 22:48:41 +09:00
sylph 0b0d460eac feat(idp): 承認待ちユーザーのパスワードログインで承認待ちと通知する
- /signin/v1/identifier/_/logon を idp で先に受け、lico のログインが失敗し
  かつユーザー名が承認待ちなら 403 registration_pending を返す
- それ以外のリクエストは lico の応答をそのまま返す
- ログイン画面で「現在、管理者の承認待ちです」を表示する
2026-11-01 22:41:59 +09:00
sylph 3ac62eb510 feat(idp): 承認待ちアカウントの管理者向け承認/拒否 API を追加
- GET /oauth2/discord/admin/pending で承認待ち一覧を返す
- POST /oauth2/discord/admin/pending/{id}/approve で accountEnabled=true にする
- POST /oauth2/discord/admin/pending/{id}/reject でアカウントを削除する
- Graph の更新に失敗した場合は承認待ちの記録を残し、再試行できるようにする
2026-11-01 22:37:51 +09:00
sylph fbe1b9560b feat(idp): Discord 登録の経路チェックと承認待ちワークフローを追加
- 承認待ちアカウントを pending.json に保存 (ユーザー ID、登録元、申請日時)
- Discord 登録が無効なら新規 Discord ユーザーを registration_closed で拒否
- 承認制が有効なら accountEnabled=false で作成し、申請受付画面を表示 (セッションは発行しない)
- 承認待ちユーザーの Discord ログインを registration_pending で遮断
- 新しいエラーコードの文言 (英語/日本語) を追加
2026-11-01 22:31:26 +09:00
sylph 019e65a951 feat(idp): 新規登録の設定と公開 API を追加
- 登録受付 / Web 登録 / Discord 登録 / 管理者承認の 4 設定を registration.json に保存
- ファイルがない環境では従来どおり (受付 ON、Discord ON、Web OFF、承認 OFF)
- GET /oauth2/discord/registration でログイン画面向けの公開設定を返す (認証なし)
- GET/PUT /oauth2/discord/admin/registration で管理者が設定を変更する
2026-11-01 22:25:37 +09:00
26 changed files with 2228 additions and 60 deletions

No files matched your search

+67 -2
View File
@@ -15,6 +15,7 @@ idp のログイン画面に「Discord でログイン」ボタンを追加す
- Client ID / Client Secret / 許可するサーバー ID は、管理設定画面(Admin Settings > General)で設定します。
- 初めてログインした Discord ユーザーには、作成するアカウントのユーザー名を入力してもらいます。
- Discord と紐付いたアカウントは、ID トークンの `email_verified` が `true` になります。
- 新規登録の受付(Web / Discord)と管理者承認は、管理設定画面の「登録」セクションで切り替えます([新規登録の設定と承認](#新規登録の設定と承認))。
## 前提条件
@@ -131,6 +132,11 @@ lico の LDAP バックエンドは、全ユーザーで `EmailVerified()` に
|---|---|---|
| GET | `/oauth2/discord/admin/settings` | 現在の設定を返す(Client Secret は返さず、`client_secret_set` だけ返す) |
| PUT | `/oauth2/discord/admin/settings` | 設定を保存する。`client_secret` を省略するか空にすると、保存済みの値を使い続ける |
| GET | `/oauth2/discord/admin/registration` | 登録設定を返す |
| PUT | `/oauth2/discord/admin/registration` | 登録設定を保存する(4 項目すべてを送る。未知のキーは 400) |
| GET | `/oauth2/discord/admin/pending` | 承認待ちアカウントの一覧を申請の古い順に返す(`{"value": [...]}`) |
| POST | `/oauth2/discord/admin/pending/{id}/approve` | アカウントを有効にして承認待ちから外す(204) |
| POST | `/oauth2/discord/admin/pending/{id}/reject` | アカウントを削除して承認待ちから外す(204) |
- proxy は `/oauth2/discord/admin/` と `/oauth2/discord/account/` を認証必須で idp に転送します。それ以外の `/oauth2/discord/` は認証なしで転送します(ルートは先に一致したものが使われるので、この 2 つを先に定義しています)。
- idp は proxy が付ける `x-access-token` の reva JWT を検証し、CS3 gateway で `Settings.ReadWrite` 権限を確認します。トークンがない・無効なら 401、権限がなければ 403 です。
@@ -138,6 +144,49 @@ lico の LDAP バックエンドは、全ユーザーで `EmailVerified()` に
- 設定は `IDP_DISCORD_SETTINGS_FILE`(デフォルト `$OCIS_BASE_DATA_PATH/idp/discord.json`)に権限 0600 で保存します。一時ファイルに書いてからリネームするので、書き込み途中の状態は残りません。保存した値はすぐに反映されます。
- 管理画面のセクション(`DiscordSection.vue`)は、`Setting` の `update-all` 権限を持つユーザーにだけ表示します。
## 新規登録の設定と承認
管理設定画面の「登録」セクション(`RegistrationSection.vue`)で、次の 4 項目を切り替えます。切り替えた時点で保存し、失敗したら表示を元に戻します。設定は `IDP_DISCORD_SETTINGS_FILE` と同じディレクトリの `registration.json`(デフォルト `$OCIS_BASE_DATA_PATH/idp/registration.json`)に権限 0600 で保存し、すぐに反映されます。
| 項目 | キー | ファイルがないときの値 | 内容 |
|---|---|---|---|
| 登録受付 | `allow_registration` | ON | OFF なら Web・Discord どちらの新規登録も受け付けない |
| Web 登録 | `allow_web` | OFF | ユーザー名・メール・パスワードのフォームで登録できる |
| Discord 登録 | `allow_discord` | ON | アカウントのない Discord ユーザーがユーザー名入力画面から登録できる |
| 管理者承認 | `require_approval` | OFF | 新規アカウントを無効の状態で作り、管理者の承認を待つ |
ファイルがない既存環境では、以前と同じ動作になります。既存アカウントのログインは、これらの設定の影響を受けません。
### ログイン画面
- Web 登録が有効(登録受付も ON)のときだけ「アカウント作成」リンクを表示します。リンク先は、OIDC クエリを付けた `/oauth2/discord/register` です。
- Discord 登録が有効なときは、Discord ボタンの文言を「Discord でログイン / 登録」にします。
- `GET /oauth2/discord/registration`(認証なし)は、同じ判定の結果を `{"web", "discord", "discord_login"}` で返します。ログイン画面はサーバー側でこの判定を使って描画します。
### Web 登録
- `GET` / `POST /oauth2/discord/register` で受け付けます。Web 登録が無効なら 403 `registration_closed` です。
- POST は、Origin(ない場合は Referer)が `OCIS_URL` と同じオリジンでなければ 403 で拒否します。
- 入力は次の条件で検証します。
- ユーザー名: Discord 登録と同じルール。
- メール: 表示名を含まない単一のアドレスで、254 文字以下。
- パスワード: 8〜256 文字で、確認欄と一致すること。
- ユーザー名とメールの重複は Graph で確認します。パスワードポリシーは graph サービスの設定で判定されます。Graph が 400 を返し、本文に `password` を含むときは、フォームにエラーを表示します。
- 承認が不要な設定なら、有効なアカウントを作ってログイン画面に 303 で戻します。自動ではログインしません。
### 承認待ち
- 管理者承認が有効なときは、Web・Discord どちらの登録でも `accountEnabled=false` でアカウントを作ります。同じディレクトリの `pending.json` に、ユーザー ID・ユーザー名・メール・登録元(`web` / `discord`)・申請日時を記録します。セッションは発行せず、「アカウント登録申請を受け付けました」を表示します。
- 承認待ちのユーザーが Discord でログインすると、403 `registration_pending` になります。
- パスワードログインの場合、lico は無効なアカウントとパスワード違いを区別できません。そこで idp が `/signin/v1/identifier/_/logon` を先に受けます。lico の結果が失敗で、入力したユーザー名(大文字小文字は無視)が承認待ちなら、403 `{"success":false,"error":"registration_pending"}` を返します。ログイン画面には「現在、管理者の承認待ちです」と表示されます。それ以外のリクエストには lico の応答をそのまま返します。
- 承認すると `accountEnabled=true` にし、拒否するとアカウントを Graph で削除します。どちらも Graph の操作が成功してから記録を消します。失敗したときは 502 を返し、記録が残るので再試行できます。
### 制限
- パスワードログインの承認待ち判定は、パスワードの正誤に関係なく 403 を返します。そのため、あるユーザー名が承認待ちかどうかを第三者が判別できます。
- 承認待ち一覧ではなく Users 画面でアカウントを有効にすると、`pending.json` の記録が残ります。パスワードログインはできますが、Discord ログインは遮断されたままです。承認待ち一覧から承認してください。
- `pending.json` への記録に失敗すると、アカウントは無効のまま作られ、一覧に出ません(エラーログ `could not record pending account` が出ます)。この場合は Users 画面で有効化または削除します。
## セキュリティ上の扱い
| 項目 | 内容 |
@@ -146,7 +195,8 @@ lico の LDAP バックエンドは、全ユーザーで `EmailVerified()` に
| signup Cookie | `__Secure-RC-Discord-Signup`。HttpOnly、Secure、SameSite=Strict、有効期限 10 分。フォームの hidden トークンと一致しないと受け付けない |
| 署名 | HMAC-SHA256。鍵は JWT シークレットから導出するので、idp を複数台動かしても再起動しても進行中のログインは壊れない。state と signup は用途別の接頭辞で署名するので、片方の Cookie をもう片方に流用できない |
| HTML | ログイン画面と同じ CSP(nonce 付き)とセキュリティヘッダーを付け、`html/template` でエスケープする |
| 入力サイズ | login のクエリは 4096 バイト、signup のフォームは 8 KiB まで |
| 入力サイズ | login と register のクエリは 4096 バイト、signup と register のフォームは 8 KiB、logon の本文は 64 KiB まで |
| Web 登録の POST | Origin / Referer が `OCIS_URL` と同じオリジンでなければ拒否する |
## エラー画面
@@ -166,6 +216,13 @@ lico の LDAP バックエンドは、全ユーザーで `EmailVerified()` に
| `discord_username_invalid` | ユーザー名がルール違反(入力画面で表示) |
| `discord_username_taken` | ユーザー名が使用済み(入力画面で表示) |
| `discord_link_conflict` | 連携先が別のアカウントまたは別の Discord に紐付いている(アカウント画面で表示) |
| `registration_closed` | この経路での新規登録を受け付けていない(403) |
| `registration_pending` | アカウントが承認待ち(403) |
| `registration_submitted` | 承認制で登録申請を受け付けた(200) |
| `registration_mail_invalid` | メールアドレスが不正(登録画面で表示) |
| `registration_mail_taken` | メールアドレスが使用済み(登録画面で表示) |
| `registration_password_invalid` | パスワードが短い、またはパスワードポリシー違反(登録画面で表示) |
| `registration_password_mismatch` | 確認欄と一致しない(登録画面で表示) |
連携フローでは、state Cookie の検証より後のエラーをエラー画面ではなく、アカウント画面の `discord_link` クエリで返します。
@@ -193,15 +250,23 @@ lico の LDAP バックエンドは、全ユーザーで `EmailVerified()` に
| `services/idp/pkg/discord/session.go` | lico ログオン Cookie の発行 |
| `services/idp/pkg/discord/settings.go` | 設定の検証と保存 |
| `services/idp/pkg/discord/admin.go` | 管理 API の認可、連携 API のユーザー認証 |
| `services/idp/pkg/discord/registration.go` | 登録設定の保存、公開 API と管理 API |
| `services/idp/pkg/discord/pending.go` | 承認待ちアカウントの保存 |
| `services/idp/pkg/discord/approval.go` | 承認待ち一覧と承認・拒否の管理 API |
| `services/idp/pkg/discord/logon.go` | パスワードログインの承認待ち判定 |
| `services/idp/pkg/discord/websignup.go` | Web 登録フォームの処理 |
| `services/idp/pkg/service/v0/discord_register.go` | Web 登録画面の描画 |
| `services/idp/pkg/backends/ldapverified/` | `email_verified` 用の LDAP バックエンドラッパーと identity manager |
| `services/idp/pkg/service/v0/discord.go` | 依存関係の組み立て、画面描画、日英メッセージ |
| `services/idp/pkg/service/v0/ldap_manager.go` | ラッパー版 identity manager の登録 |
| `services/idp/assets/identifier/discord_signup.html` | ユーザー名入力画面 |
| `services/idp/assets/identifier/discord_register.html` | Web 登録画面 |
| `services/idp/assets/identifier/index.html`, `static/theme.css` | ログインボタンとスタイル |
| `services/proxy/pkg/config/defaults/defaultconfig.go` | `/oauth2/discord/` のルート |
| `services/idp/pkg/config/` | `TokenManager`、`ServiceAccount`、`Discord` 設定 |
| `ocis/pkg/init/` | `ocis init` でサービスアカウントを idp に書き込む |
| `web/packages/web-app-admin-settings/src/components/General/DiscordSection.vue` | 管理設定画面 |
| `web/packages/web-app-admin-settings/src/components/General/RegistrationSection.vue` | 登録設定と承認待ち一覧 |
| `web/packages/web-runtime/src/components/Account/DiscordLink.vue` | アカウント画面の連携行 |
テストは `go test ./services/idp/pkg/...` と、`DiscordSection.spec.ts`、`DiscordLink.spec.ts`(web)で実行できます。
テストは `go test ./services/idp/pkg/...` と、`DiscordSection.spec.ts`、`RegistrationSection.spec.ts`、`DiscordLink.spec.ts`(web)で実行できます。
@@ -0,0 +1,48 @@
<!DOCTYPE html>
<html lang="{{.Lang}}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#1b223d">
<title>{{.Title}}</title>
<link rel="icon" href="{{.PathPrefix}}/static/favicon.ico">
<link rel="stylesheet" href="{{.PathPrefix}}/static/theme.css">
<style nonce="{{.Nonce}}">{{if .BgImgURL}}body.oc-login-bg{background-image:url('{{.BgImgURL}}')}{{end}}</style>
</head>
<body class="oc-login-bg">
<main>
<div class="oc-login-form">
<img class="oc-logo" src="{{.LogoURL}}" alt="ownCloud">
<h1 class="oc-invisible-sr">{{.Headline}}</h1>
<form id="register-form" method="post" action="{{.Action}}">
<p class="oc-message">{{.Intro}}</p>
<input type="hidden" name="q" value="{{.Query}}">
<div>
<label class="oc-label" for="register-username">{{.LabelUsername}}</label>
<input class="oc-input{{if eq .ErrField "username"}} error{{end}}" type="text" id="register-username" name="username" value="{{.Username}}" autocomplete="username" autocapitalize="none" spellcheck="false" required minlength="3" maxlength="32" aria-describedby="register-username-hint" autofocus>
<p id="register-username-hint" class="oc-hint">{{.HintUsername}}</p>
</div>
<div>
<label class="oc-label" for="register-mail">{{.LabelMail}}</label>
<input class="oc-input{{if eq .ErrField "mail"}} error{{end}}" type="email" id="register-mail" name="mail" value="{{.Mail}}" autocomplete="email" required maxlength="254">
</div>
<div>
<label class="oc-label" for="register-password">{{.LabelPassword}}</label>
<input class="oc-input{{if eq .ErrField "password"}} error{{end}}" type="password" id="register-password" name="password" autocomplete="new-password" required minlength="8" maxlength="256" aria-describedby="register-password-hint">
<p id="register-password-hint" class="oc-hint">{{.HintPassword}}</p>
</div>
<div>
<label class="oc-label" for="register-password-confirm">{{.LabelConfirm}}</label>
<input class="oc-input{{if eq .ErrField "password"}} error{{end}}" type="password" id="register-password-confirm" name="password_confirm" autocomplete="new-password" required minlength="8" maxlength="256">
{{if .Error}}<p id="register-error" class="oc-error-message" role="alert">{{.Error}}</p>{{end}}
</div>
<div>
<button class="oc-button-primary" type="submit" id="register-btn">{{.Button}}</button>
</div>
</form>
<p><a href="{{.LoginURL}}">{{.BackLabel}}</a></p>
</div>
</main>
<footer class="oc-footer-message">ownCloud - a safe home for all your data</footer>
</body>
</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}}">
<div>
@@ -39,6 +40,7 @@
<a class="oc-button-primary oc-button-discord" id="discord-login-btn" href="{{.DiscordLoginURL}}">{{.DiscordLabel}}</a>
</div>{{end}}
{{if .PasswordResetURI}}<p><a href="{{.PasswordResetURI}}">{{.ResetLabel}}</a></p>{{end}}
{{if .RegisterURL}}<p id="oc-register-link" hidden><a href="{{.RegisterURL}}">{{.RegisterLabel}}</a></p>{{end}}
</div>
</main>
<footer class="oc-footer-message">ownCloud - a safe home for all your data</footer>
@@ -52,6 +54,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 +181,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;
@@ -206,6 +213,8 @@
document.getElementById("login-form").hidden = false;
var discordEl = document.getElementById("oc-discord-login");
if (discordEl) discordEl.hidden = false;
var registerEl = document.getElementById("oc-register-link");
if (registerEl) registerEl.hidden = false;
}
if ((helloReq.state || helloReq.client_id) && !hasLogin) {
+66
View File
@@ -0,0 +1,66 @@
package discord
import (
"context"
"net/http"
"github.com/go-chi/chi/v5"
)
// Accounts enables or deletes accounts waiting for approval.
type Accounts interface {
Approve(ctx context.Context, userID string) error
Reject(ctx context.Context, userID string) error
}
// listPending serves GET /oauth2/discord/admin/pending.
func (h *Handler) listPending(w http.ResponseWriter, r *http.Request) {
if status, err := h.opt.Admin.AuthorizeAdmin(r); err != nil {
writeJSONError(w, status, "accessDenied", "", http.StatusText(status))
return
}
writeJSON(w, http.StatusOK, map[string]any{"value": h.opt.Pending.List()})
}
// approvePending serves POST /oauth2/discord/admin/pending/{id}/approve.
func (h *Handler) approvePending(w http.ResponseWriter, r *http.Request) {
h.decidePending(w, r, true)
}
// rejectPending serves POST /oauth2/discord/admin/pending/{id}/reject.
func (h *Handler) rejectPending(w http.ResponseWriter, r *http.Request) {
h.decidePending(w, r, false)
}
func (h *Handler) decidePending(w http.ResponseWriter, r *http.Request, approve bool) {
if status, err := h.opt.Admin.AuthorizeAdmin(r); err != nil {
writeJSONError(w, status, "accessDenied", "", http.StatusText(status))
return
}
id := chi.URLParam(r, "id")
if _, ok := h.opt.Pending.Get(id); !ok {
writeJSONError(w, http.StatusNotFound, "itemNotFound", "", "no pending account with this id")
return
}
logger := h.opt.Logger.With().Str("component", "discord").Str("user_id", id).Logger()
var err error
if approve {
err = h.opt.Accounts.Approve(r.Context(), id)
} else {
err = h.opt.Accounts.Reject(r.Context(), id)
}
if err != nil {
logger.Error().Err(err).Bool("approve", approve).Msg("could not decide pending account")
writeJSONError(w, http.StatusBadGateway, "generalException", "", "could not update the account")
return
}
// Only forget the entry after the directory change succeeded, so a
// failed approval can be retried.
if err := h.opt.Pending.Remove(id); err != nil {
logger.Error().Err(err).Msg("could not remove pending entry")
writeJSONError(w, http.StatusInternalServerError, "generalException", "", "could not save pending accounts")
return
}
logger.Info().Bool("approve", approve).Msg("pending account decided")
w.WriteHeader(http.StatusNoContent)
}
@@ -0,0 +1,104 @@
package discord
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/url"
"testing"
)
type fakeAccounts struct {
approved, rejected []string
err error
}
func (f *fakeAccounts) Approve(_ context.Context, id string) error {
if f.err != nil {
return f.err
}
f.approved = append(f.approved, id)
return nil
}
func (f *fakeAccounts) Reject(_ context.Context, id string) error {
if f.err != nil {
return f.err
}
f.rejected = append(f.rejected, id)
return nil
}
func TestAdminListPending(t *testing.T) {
h := newHarness(t)
_ = h.pending.Add(PendingUser{UserID: "u1", Username: "alice", Source: SourceWeb})
rec := h.do(http.MethodGet, "/oauth2/discord/admin/pending", nil)
var body struct{ Value []PendingUser }
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil || rec.Code != http.StatusOK {
t.Fatalf("status = %d body = %s", rec.Code, rec.Body)
}
if len(body.Value) != 1 || body.Value[0].Source != SourceWeb {
t.Fatalf("value = %+v", body.Value)
}
h.admin.status = http.StatusForbidden
if rec := h.do(http.MethodGet, "/oauth2/discord/admin/pending", nil); rec.Code != http.StatusForbidden {
t.Errorf("without permission = %d", rec.Code)
}
}
func TestAdminApproveThenDiscordLoginSucceeds(t *testing.T) {
h := newHarness(t)
if err := h.reg.Save(RegistrationSettings{AllowRegistration: true, AllowDiscord: true, RequireApproval: true}); err != nil {
t.Fatal(err)
}
f, ck := h.startSignup("")
h.postSignup(url.Values{"token": {f.Token}, "username": {"alice2"}}, ck)
if !h.pending.IsPending(h.prov.id) {
t.Fatal("account must be pending")
}
rec := h.do(http.MethodPost, "/oauth2/discord/admin/pending/"+h.prov.id+"/approve", nil)
if rec.Code != http.StatusNoContent || len(h.accounts.approved) != 1 || h.pending.IsPending(h.prov.id) {
t.Fatalf("approve status = %d approved = %v", rec.Code, h.accounts.approved)
}
h.sess.userID = ""
state, c := h.login("")
if rec := h.callback(cbQuery(testCode, state), c); rec.Code != http.StatusOK || h.sess.userID != h.prov.id {
t.Fatalf("login after approval: status = %d logon = %q", rec.Code, h.sess.userID)
}
}
func TestAdminRejectAndErrors(t *testing.T) {
h := newHarness(t)
_ = h.pending.Add(PendingUser{UserID: "u1", Username: "alice", Source: SourceWeb})
if rec := h.do(http.MethodPost, "/oauth2/discord/admin/pending/unknown/reject", nil); rec.Code != http.StatusNotFound {
t.Errorf("unknown id = %d", rec.Code)
}
h.accounts.err = errors.New("graph down")
if rec := h.do(http.MethodPost, "/oauth2/discord/admin/pending/u1/reject", nil); rec.Code != http.StatusBadGateway || !h.pending.IsPending("u1") {
t.Fatalf("failed reject = %d, entry must stay", rec.Code)
}
h.accounts.err = nil
if rec := h.do(http.MethodPost, "/oauth2/discord/admin/pending/u1/reject", nil); rec.Code != http.StatusNoContent || h.pending.IsPending("u1") || len(h.accounts.rejected) != 1 {
t.Fatalf("reject = %d rejected = %v", rec.Code, h.accounts.rejected)
}
}
func TestGraphProvisionerApproveReject(t *testing.T) {
dir := newFakeDirectory()
p := GraphProvisioner{Dir: dir, Index: fakeIndex{}}
if err := p.Approve(context.Background(), "u1"); err != nil {
t.Fatal(err)
}
if e := dir.updates["u1"].AccountEnabled; e == nil || !*e {
t.Fatalf("approve patch = %+v", dir.updates["u1"])
}
if err := p.Reject(context.Background(), "u2"); err != nil || len(dir.deleted) != 1 || dir.deleted[0] != "u2" {
t.Fatalf("reject: err = %v deleted = %v", err, dir.deleted)
}
}
+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)
}
}
+31 -1
View File
@@ -74,6 +74,9 @@ func (d GraphDirectory) UpdateUser(ctx context.Context, id string, p UserPatch)
return err
}
upd := libregraph.NewUserUpdate()
if p.AccountEnabled != nil {
upd.SetAccountEnabled(*p.AccountEnabled)
}
if p.DisplayName != nil {
upd.SetDisplayName(*p.DisplayName)
}
@@ -91,6 +94,23 @@ func (d GraphDirectory) UpdateUser(ctx context.Context, id string, p UserPatch)
return nil
}
// DeleteUser implements Directory.
func (d GraphDirectory) DeleteUser(ctx context.Context, id string) error {
c, err := d.Client(ctx)
if err != nil {
return err
}
resp, err := c.UserApi.DeleteUser(ctx, id).Execute()
defer closeBody(resp)
if resp != nil && resp.StatusCode == http.StatusNotFound {
return nil
}
if err != nil {
return graphError(err, resp)
}
return nil
}
func closeBody(resp *http.Response) {
if resp != nil && resp.Body != nil {
_, _ = io.Copy(io.Discard, resp.Body)
@@ -98,6 +118,16 @@ func closeBody(resp *http.Response) {
}
}
// GraphStatusError is a Graph API error response.
type GraphStatusError struct {
Status int
Body string
}
func (e *GraphStatusError) Error() string {
return fmt.Sprintf("graph returned %d: %s", e.Status, e.Body)
}
func graphError(err error, resp *http.Response) error {
var oe libregraph.GenericOpenAPIError
if errors.As(err, &oe) && len(oe.Body()) > 0 {
@@ -106,7 +136,7 @@ func graphError(err error, resp *http.Response) error {
body = body[:512]
}
if resp != nil {
return fmt.Errorf("graph returned %d: %s", resp.StatusCode, body)
return &GraphStatusError{Status: resp.StatusCode, Body: string(body)}
}
return fmt.Errorf("graph error: %s", body)
}
+40 -10
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
@@ -82,18 +90,24 @@ type Renderer interface {
Continue(w http.ResponseWriter, r *http.Request, target string)
// Signup renders the form where a new user chooses the username.
Signup(w http.ResponseWriter, r *http.Request, status int, f SignupForm)
// Register renders the web registration form.
Register(w http.ResponseWriter, r *http.Request, status int, f RegisterForm)
}
// Options configures the Handler.
type Options struct {
Store *Store
API API
Provisioner Provisioner
Sessions SessionIssuer
Admin AdminAuthorizer
Users UserAuthenticator
Render Renderer
Logger log.Logger
Store *Store
Registration *RegistrationStore
Pending *PendingStore
Accounts Accounts
WebAccounts WebAccounts
API API
Provisioner Provisioner
Sessions SessionIssuer
Admin AdminAuthorizer
Users UserAuthenticator
Render Renderer
Logger log.Logger
// PublicURL is the external oCIS URL, e.g. https://cloud.example.com.
PublicURL string
@@ -116,7 +130,7 @@ type Handler struct {
// NewHandler returns a Handler.
func NewHandler(opt Options) (*Handler, error) {
switch {
case opt.Store == 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.Accounts == nil, opt.WebAccounts == 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")
@@ -148,8 +162,16 @@ func (h *Handler) Mount(r chi.Router) {
r.Post("/signup", h.signup)
r.Get("/account/link", h.getLink)
r.Post("/account/link", h.startLink)
r.Get("/registration", h.getPublicRegistration)
r.Get("/admin/settings", h.getSettings)
r.Put("/admin/settings", h.putSettings)
r.Get("/admin/registration", h.getRegistration)
r.Put("/admin/registration", h.putRegistration)
r.Get("/admin/pending", h.listPending)
r.Post("/admin/pending/{id}/approve", h.approvePending)
r.Post("/admin/pending/{id}/reject", h.rejectPending)
r.Get("/register", h.getRegister)
r.Post("/register", h.postRegister)
})
}
@@ -279,10 +301,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)
+45 -16
View File
@@ -25,10 +25,16 @@ const (
)
type fakeRenderer struct {
status int
code string
target string
signup *SignupForm
status int
code string
target string
signup *SignupForm
register *RegisterForm
}
func (f *fakeRenderer) Register(w http.ResponseWriter, _ *http.Request, status int, form RegisterForm) {
f.status, f.register = status, &form
w.WriteHeader(status)
}
func (f *fakeRenderer) Signup(w http.ResponseWriter, _ *http.Request, status int, form SignupForm) {
@@ -55,6 +61,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 +83,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
}
@@ -109,17 +118,21 @@ func (f *fakeAdmin) AuthorizeAdmin(*http.Request) (int, error) {
}
type harness struct {
t *testing.T
fd *fakeDiscord
store *Store
render *fakeRenderer
prov *fakeProvisioner
sess *fakeSessions
admin *fakeAdmin
users *fakeUsers
now time.Time
handler *Handler
router chi.Router
t *testing.T
fd *fakeDiscord
store *Store
reg *RegistrationStore
pending *PendingStore
accounts *fakeAccounts
web *fakeWeb
render *fakeRenderer
prov *fakeProvisioner
sess *fakeSessions
admin *fakeAdmin
users *fakeUsers
now time.Time
handler *Handler
router chi.Router
}
func newHarness(t *testing.T) *harness {
@@ -146,9 +159,25 @@ func newHarness(t *testing.T) *harness {
t.Fatal(err)
}
h.store = st
reg, err := NewRegistrationStore(filepath.Join(t.TempDir(), "registration.json"))
if err != nil {
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.accounts = &fakeAccounts{}
h.web = &fakeWeb{id: "7a1b2c3d-0000-4000-8000-000000000002"}
h.handler, err = NewHandler(Options{
Store: st,
Registration: reg,
Pending: pending,
Accounts: h.accounts,
WebAccounts: h.web,
API: h.fd.client(),
Provisioner: h.prov,
Sessions: h.sess,
+56
View File
@@ -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,
})
})
}
+64
View File
@@ -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)
}
}
+136
View File
@@ -0,0 +1,136 @@
package discord
import (
"fmt"
"sort"
"strings"
"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
}
// 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()
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")
}
}
+64 -5
View File
@@ -26,9 +26,10 @@ var (
// UserPatch lists the attributes the provisioner updates. Nil or empty
// fields are left unchanged.
type UserPatch struct {
DisplayName *string
Mail *string
Identities []libregraph.ObjectIdentity
AccountEnabled *bool
DisplayName *string
Mail *string
Identities []libregraph.ObjectIdentity
}
// Directory is the subset of the LibreGraph users API the provisioner needs.
@@ -39,6 +40,8 @@ type Directory interface {
FindUsersByMail(ctx context.Context, mail string) ([]libregraph.User, error)
CreateUser(ctx context.Context, u libregraph.User) (*libregraph.User, error)
UpdateUser(ctx context.Context, id string, p UserPatch) error
// DeleteUser removes the account. A missing account is not an error.
DeleteUser(ctx context.Context, id string) error
}
// IdentityIndex finds accounts by a linked external identity.
@@ -128,7 +131,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 +152,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)
@@ -225,6 +228,62 @@ func (p GraphProvisioner) link(ctx context.Context, u *libregraph.User, du *User
return id, nil
}
// CreateWebUser implements WebAccounts. Username and email must be unused.
func (p GraphProvisioner) CreateWebUser(ctx context.Context, wu WebUser, enabled bool) (string, error) {
if !ValidUsername(wu.Username) {
return "", ErrUsernameInvalid
}
existing, err := p.Dir.GetUserByName(ctx, wu.Username)
if err != nil {
return "", fmt.Errorf("lookup user %s: %w", wu.Username, err)
}
if existing != nil {
return "", ErrUsernameTaken
}
candidates, err := p.Dir.FindUsersByMail(ctx, wu.Mail)
if err != nil {
return "", fmt.Errorf("lookup user by email: %w", err)
}
for _, c := range candidates {
if strings.EqualFold(strings.TrimSpace(c.GetMail()), wu.Mail) {
return "", ErrMailTaken
}
}
nu := libregraph.User{}
nu.SetOnPremisesSamAccountName(wu.Username)
nu.SetDisplayName(wu.Username)
nu.SetMail(wu.Mail)
nu.SetAccountEnabled(enabled)
pp := libregraph.NewPasswordProfile()
pp.SetPassword(wu.Password)
nu.SetPasswordProfile(*pp)
created, err := p.Dir.CreateUser(ctx, nu)
if err != nil {
var se *GraphStatusError
if errors.As(err, &se) && se.Status == 400 && strings.Contains(strings.ToLower(se.Body), "password") {
return "", fmt.Errorf("%w: %s", ErrPasswordRejected, se.Body)
}
return "", fmt.Errorf("create user %s: %w", wu.Username, err)
}
if created == nil || created.GetId() == "" {
return "", errors.New("created user has no id")
}
return created.GetId(), nil
}
// Approve implements Accounts: it enables the pending account.
func (p GraphProvisioner) Approve(ctx context.Context, userID string) error {
enabled := true
return p.Dir.UpdateUser(ctx, userID, UserPatch{AccountEnabled: &enabled})
}
// Reject implements Accounts: it deletes the pending account.
func (p GraphProvisioner) Reject(ctx context.Context, userID string) error {
return p.Dir.DeleteUser(ctx, userID)
}
func checkDiscordUser(du *User) error {
if du == nil || !snowflake.MatchString(du.ID) {
return errors.New("invalid discord user id")
+12 -6
View File
@@ -17,6 +17,7 @@ type fakeDirectory struct {
users []libregraph.User
created []libregraph.User
updates map[string]UserPatch
deleted []string
mailCalls int
createErr error
}
@@ -61,6 +62,11 @@ func (d *fakeDirectory) UpdateUser(_ context.Context, id string, p UserPatch) er
return nil
}
func (d *fakeDirectory) DeleteUser(_ context.Context, id string) error {
d.deleted = append(d.deleted, id)
return nil
}
// fakeIndex returns linked user IDs per Discord ID.
type fakeIndex struct {
linked map[string][]string
@@ -184,7 +190,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 +207,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 +218,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 +235,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)
}
}
+129
View File
@@ -0,0 +1,129 @@
package discord
import (
"encoding/json"
"fmt"
"io"
"net/http"
"sync"
)
// RegistrationSettings controls who may create a new account and whether new
// accounts need an administrator's approval. Administrators manage it in the
// Admin Settings UI.
type RegistrationSettings struct {
// AllowRegistration is the master switch for new accounts.
AllowRegistration bool `json:"allow_registration"`
// AllowWeb allows the username/email/password form on the login page.
AllowWeb bool `json:"allow_web"`
// AllowDiscord allows Discord users without an account to create one.
AllowDiscord bool `json:"allow_discord"`
// RequireApproval creates new accounts disabled until an admin approves them.
RequireApproval bool `json:"require_approval"`
}
// DefaultRegistrationSettings keeps the behaviour of installations without a
// registration file: Discord users can sign up, there is no web form and no
// approval step.
func DefaultRegistrationSettings() RegistrationSettings {
return RegistrationSettings{AllowRegistration: true, AllowDiscord: true}
}
// WebAllowed reports whether the web signup form is open.
func (s RegistrationSettings) WebAllowed() bool { return s.AllowRegistration && s.AllowWeb }
// DiscordAllowed reports whether new Discord users may create an account.
func (s RegistrationSettings) DiscordAllowed() bool { return s.AllowRegistration && s.AllowDiscord }
// PublicRegistration is returned by the unauthenticated settings endpoint.
// It only exposes what the login page needs.
type PublicRegistration struct {
Web bool `json:"web"`
Discord bool `json:"discord"`
// DiscordLogin reports whether the Discord button is shown at all.
DiscordLogin bool `json:"discord_login"`
}
// RegistrationStore persists RegistrationSettings as a JSON file (mode 0600)
// and serves reads from memory, so saved values take effect immediately.
type RegistrationStore struct {
path string
mu sync.RWMutex
cur RegistrationSettings
}
// NewRegistrationStore loads the settings from path. A missing file or a
// missing field means the default value.
func NewRegistrationStore(path string) (*RegistrationStore, error) {
s := &RegistrationStore{path: path, cur: DefaultRegistrationSettings()}
if err := readJSONFile(path, &s.cur); err != nil {
return nil, fmt.Errorf("load registration settings: %w", err)
}
return s, nil
}
// Get returns the current settings.
func (s *RegistrationStore) Get() RegistrationSettings {
s.mu.RLock()
defer s.mu.RUnlock()
return s.cur
}
// Save persists the settings.
func (s *RegistrationStore) Save(n RegistrationSettings) error {
s.mu.Lock()
defer s.mu.Unlock()
if err := writeJSONFile(s.path, n); err != nil {
return fmt.Errorf("save registration settings: %w", err)
}
s.cur = n
return nil
}
// PublicRegistration returns what the login page may offer. It is the same
// data the unauthenticated registration endpoint returns.
func (h *Handler) PublicRegistration() PublicRegistration { return h.publicRegistration() }
func (h *Handler) publicRegistration() PublicRegistration {
reg := h.opt.Registration.Get()
discordLogin := h.opt.Store.Get().Ready()
return PublicRegistration{
Web: reg.WebAllowed(),
Discord: discordLogin && reg.DiscordAllowed(),
DiscordLogin: discordLogin,
}
}
// getPublicRegistration serves GET /oauth2/discord/registration without
// authentication.
func (h *Handler) getPublicRegistration(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, h.publicRegistration())
}
func (h *Handler) getRegistration(w http.ResponseWriter, r *http.Request) {
if status, err := h.opt.Admin.AuthorizeAdmin(r); err != nil {
writeJSONError(w, status, "accessDenied", "", http.StatusText(status))
return
}
writeJSON(w, http.StatusOK, h.opt.Registration.Get())
}
func (h *Handler) putRegistration(w http.ResponseWriter, r *http.Request) {
if status, err := h.opt.Admin.AuthorizeAdmin(r); err != nil {
writeJSONError(w, status, "accessDenied", "", http.StatusText(status))
return
}
dec := json.NewDecoder(io.LimitReader(r.Body, 4<<10))
dec.DisallowUnknownFields()
var n RegistrationSettings
if err := dec.Decode(&n); err != nil {
writeJSONError(w, http.StatusBadRequest, "invalidRequest", "", "invalid JSON body")
return
}
if err := h.opt.Registration.Save(n); err != nil {
h.opt.Logger.Error().Err(err).Msg("discord: could not save registration settings")
writeJSONError(w, http.StatusInternalServerError, "generalException", "", "could not save settings")
return
}
writeJSON(w, http.StatusOK, n)
}
@@ -0,0 +1,106 @@
package discord
import (
"encoding/json"
"net/http"
"os"
"path/filepath"
"strings"
"testing"
)
func TestRegistrationStoreDefaults(t *testing.T) {
path := filepath.Join(t.TempDir(), "registration.json")
s, err := NewRegistrationStore(path)
if err != nil {
t.Fatal(err)
}
if s.Get() != DefaultRegistrationSettings() {
t.Fatalf("defaults = %+v", s.Get())
}
// A field missing from the file keeps its default.
if err := os.WriteFile(path, []byte(`{"allow_web":true}`), 0o600); err != nil {
t.Fatal(err)
}
s, err = NewRegistrationStore(path)
if err != nil {
t.Fatal(err)
}
if got := s.Get(); !got.AllowRegistration || !got.AllowDiscord || !got.AllowWeb || got.RequireApproval {
t.Fatalf("partial file = %+v", got)
}
}
func TestRegistrationStorePersists(t *testing.T) {
path := filepath.Join(t.TempDir(), "registration.json")
s, _ := NewRegistrationStore(path)
n := RegistrationSettings{AllowRegistration: true, AllowWeb: false, AllowDiscord: true, RequireApproval: true}
if err := s.Save(n); err != nil {
t.Fatal(err)
}
reloaded, err := NewRegistrationStore(path)
if err != nil || reloaded.Get() != n {
t.Fatalf("reloaded = %+v, %v", reloaded.Get(), err)
}
}
func TestRegistrationMasterSwitch(t *testing.T) {
s := RegistrationSettings{AllowWeb: true, AllowDiscord: true}
if s.WebAllowed() || s.DiscordAllowed() {
t.Fatal("routes must be closed when registration is off")
}
}
func TestPublicRegistration(t *testing.T) {
h := newHarness(t)
if err := h.reg.Save(RegistrationSettings{AllowRegistration: true, AllowDiscord: true}); err != nil {
t.Fatal(err)
}
h.admin.status = http.StatusUnauthorized // the public endpoint needs no auth
rec := h.do(http.MethodGet, "/oauth2/discord/registration", nil)
var p PublicRegistration
if err := json.Unmarshal(rec.Body.Bytes(), &p); err != nil || rec.Code != http.StatusOK {
t.Fatalf("status = %d body = %s", rec.Code, rec.Body)
}
if p.Web || !p.Discord || !p.DiscordLogin {
t.Fatalf("public = %+v", p)
}
// Without a configured Discord login, Discord signup is not offered.
if err := h.store.Save(Settings{}); err != nil {
t.Fatal(err)
}
p = PublicRegistration{}
rec = h.do(http.MethodGet, "/oauth2/discord/registration", nil)
_ = json.Unmarshal(rec.Body.Bytes(), &p)
if p.Discord || p.DiscordLogin {
t.Fatalf("public without discord = %+v", p)
}
}
func TestAdminRegistrationAPI(t *testing.T) {
h := newHarness(t)
body := `{"allow_registration":true,"allow_web":true,"allow_discord":false,"require_approval":true}`
rec := h.do(http.MethodPut, "/oauth2/discord/admin/registration", strings.NewReader(body))
if rec.Code != http.StatusOK {
t.Fatalf("put status = %d body = %s", rec.Code, rec.Body)
}
want := RegistrationSettings{AllowRegistration: true, AllowWeb: true, RequireApproval: true}
if h.reg.Get() != want {
t.Fatalf("stored = %+v", h.reg.Get())
}
if rec := h.do(http.MethodPut, "/oauth2/discord/admin/registration", strings.NewReader(`{"unknown":1}`)); rec.Code != http.StatusBadRequest {
t.Errorf("unknown field status = %d", rec.Code)
}
h.admin.status = http.StatusForbidden
for _, m := range []string{http.MethodGet, http.MethodPut} {
if rec := h.do(m, "/oauth2/discord/admin/registration", strings.NewReader(body)); rec.Code != http.StatusForbidden {
t.Errorf("%s without permission = %d", m, rec.Code)
}
}
if h.reg.Get() != want {
t.Error("settings changed without permission")
}
}
+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)
+208
View File
@@ -0,0 +1,208 @@
package discord
import (
"context"
"errors"
"net/http"
"net/mail"
"net/url"
"strings"
"unicode/utf8"
)
// loginPagePath is the idp login page the registration form links back to.
const loginPagePath = "/signin/v1/identifier"
const (
maxRegisterBody = 8 << 10
minPasswordLen = 8
maxPasswordLen = 256
maxMailLen = 254
)
var (
// ErrMailTaken means another account uses the email address.
ErrMailTaken = errors.New("email address is already used")
// ErrPasswordRejected means the graph password policy refused the password.
ErrPasswordRejected = errors.New("password does not meet the password policy")
)
// Error codes of the web registration form.
const (
ErrCodeMailInvalid = "registration_mail_invalid"
ErrCodeMailTaken = "registration_mail_taken"
ErrCodePasswordInvalid = "registration_password_invalid"
ErrCodePasswordMismatch = "registration_password_mismatch"
)
// WebUser is an account requested with the web registration form.
type WebUser struct {
Username string
Mail string
Password string
}
// WebAccounts creates accounts from the web registration form.
type WebAccounts interface {
// CreateWebUser returns ErrUsernameInvalid, ErrUsernameTaken, ErrMailTaken
// or ErrPasswordRejected for input the user has to change.
CreateWebUser(ctx context.Context, u WebUser, enabled bool) (string, error)
}
// RegisterForm is rendered for the web registration.
type RegisterForm struct {
Action string
// Query is the OIDC query of the login page, kept to return there.
Query string
LoginURL string
Username string
Mail string
ErrCode string
}
func (h *Handler) newRegisterForm(query string) RegisterForm {
login := loginPagePath
if query != "" {
login += "?" + query
}
return RegisterForm{Action: routePrefix + "/register", Query: query, LoginURL: login}
}
// validQuery accepts the OIDC query of the login page.
func validQuery(q string) bool {
if len(q) > maxQueryLen {
return false
}
_, err := url.ParseQuery(q)
return err == nil
}
func validMail(s string) bool {
if s == "" || len(s) > maxMailLen {
return false
}
a, err := mail.ParseAddress(s)
return err == nil && a.Address == s && a.Name == ""
}
// validateRegistration returns the error code of the first invalid field.
// The graph password policy is checked when the account is created.
func validateRegistration(f RegisterForm, password, confirm string) string {
switch {
case !ValidUsername(f.Username):
return ErrCodeUsernameInvalid
case !validMail(f.Mail):
return ErrCodeMailInvalid
case utf8.RuneCountInString(password) < minPasswordLen || len(password) > maxPasswordLen:
return ErrCodePasswordInvalid
case password != confirm:
return ErrCodePasswordMismatch
}
return ""
}
// sameOrigin rejects cross-site form posts: browsers send Origin (or at
// least Referer) with a form POST, and it must be the public oCIS URL.
func (h *Handler) sameOrigin(r *http.Request) bool {
pub, err := url.Parse(h.opt.PublicURL)
if err != nil || pub.Host == "" {
return false
}
want := pub.Scheme + "://" + pub.Host
if o := r.Header.Get("Origin"); o != "" {
return o == want
}
if ref := r.Header.Get("Referer"); ref != "" {
u, err := url.Parse(ref)
return err == nil && u.Scheme+"://"+u.Host == want
}
return false
}
// getRegister serves GET /oauth2/discord/register.
func (h *Handler) getRegister(w http.ResponseWriter, r *http.Request) {
if !h.opt.Registration.Get().WebAllowed() {
h.opt.Render.Error(w, r, http.StatusForbidden, ErrCodeRegistrationClosed)
return
}
if !validQuery(r.URL.RawQuery) {
h.opt.Render.Error(w, r, http.StatusBadRequest, ErrCodeInvalidState)
return
}
h.opt.Render.Register(w, r, http.StatusOK, h.newRegisterForm(r.URL.RawQuery))
}
// postRegister serves POST /oauth2/discord/register.
func (h *Handler) postRegister(w http.ResponseWriter, r *http.Request) {
logger := h.opt.Logger.With().Str("component", "registration").Logger()
reg := h.opt.Registration.Get()
if !reg.WebAllowed() {
h.opt.Render.Error(w, r, http.StatusForbidden, ErrCodeRegistrationClosed)
return
}
if !h.sameOrigin(r) {
h.opt.Render.Error(w, r, http.StatusForbidden, ErrCodeInvalidState)
return
}
r.Body = http.MaxBytesReader(w, r.Body, maxRegisterBody)
if err := r.ParseForm(); err != nil {
h.opt.Render.Error(w, r, http.StatusBadRequest, ErrCodeInvalidState)
return
}
q := r.PostForm.Get("q")
if !validQuery(q) {
h.opt.Render.Error(w, r, http.StatusBadRequest, ErrCodeInvalidState)
return
}
f := h.newRegisterForm(q)
f.Username = strings.TrimSpace(r.PostForm.Get("username"))
f.Mail = strings.TrimSpace(r.PostForm.Get("mail"))
password := r.PostForm.Get("password")
if code := validateRegistration(f, password, r.PostForm.Get("password_confirm")); code != "" {
f.ErrCode = code
h.opt.Render.Register(w, r, http.StatusBadRequest, f)
return
}
userID, err := h.opt.WebAccounts.CreateWebUser(r.Context(), WebUser{Username: f.Username, Mail: f.Mail, Password: password}, !reg.RequireApproval)
if err != nil {
status, code := http.StatusInternalServerError, ""
switch {
case errors.Is(err, ErrUsernameInvalid):
status, code = http.StatusBadRequest, ErrCodeUsernameInvalid
case errors.Is(err, ErrUsernameTaken):
status, code = http.StatusConflict, ErrCodeUsernameTaken
case errors.Is(err, ErrMailTaken):
status, code = http.StatusConflict, ErrCodeMailTaken
case errors.Is(err, ErrPasswordRejected):
status, code = http.StatusBadRequest, ErrCodePasswordInvalid
}
if code == "" {
logger.Error().Err(err).Str("username", f.Username).Msg("web registration failed")
h.opt.Render.Error(w, r, status, ErrCodeProvision)
return
}
f.ErrCode = code
h.opt.Render.Register(w, r, status, f)
return
}
logger.Info().Str("user_id", userID).Bool("pending", reg.RequireApproval).Msg("created account from web registration")
if reg.RequireApproval {
err := h.opt.Pending.Add(PendingUser{
UserID: userID,
Username: f.Username,
DisplayName: f.Username,
Mail: f.Mail,
Source: SourceWeb,
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")
}
h.opt.Render.Error(w, r, http.StatusOK, ErrCodeRegistrationSubmitted)
return
}
http.Redirect(w, r, f.LoginURL, http.StatusSeeOther)
}
+277
View File
@@ -0,0 +1,277 @@
package discord
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
)
const testOrigin = "https://cloud.example.com"
type fakeWeb struct {
id string
created []WebUser
enabled []bool
err error
}
func (f *fakeWeb) CreateWebUser(_ context.Context, u WebUser, enabled bool) (string, error) {
if f.err != nil {
return "", f.err
}
f.created = append(f.created, u)
f.enabled = append(f.enabled, enabled)
return f.id, nil
}
func validRegisterForm() url.Values {
return url.Values{
"q": {"client_id=web&state=s1"},
"username": {"carol"},
"mail": {"carol@example.com"},
"password": {"Secret-pass1"},
"password_confirm": {"Secret-pass1"},
}
}
func (h *harness) postRegister(form url.Values, origin string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodPost, "/oauth2/discord/register", strings.NewReader(form.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if origin != "" {
req.Header.Set("Origin", origin)
}
rec := httptest.NewRecorder()
h.router.ServeHTTP(rec, req)
return rec
}
func (h *harness) openWeb(approval bool) {
h.t.Helper()
if err := h.reg.Save(RegistrationSettings{AllowRegistration: true, AllowWeb: true, AllowDiscord: true, RequireApproval: approval}); err != nil {
h.t.Fatal(err)
}
}
func TestWebRegisterRejectedWhenWebDisabled(t *testing.T) {
for name, s := range map[string]RegistrationSettings{
"defaults": DefaultRegistrationSettings(),
"discord only": {AllowRegistration: true, AllowDiscord: true, RequireApproval: true},
"registration off": {AllowWeb: true},
} {
t.Run(name, func(t *testing.T) {
h := newHarness(t)
if err := h.reg.Save(s); err != nil {
t.Fatal(err)
}
if rec := h.do(http.MethodGet, "/oauth2/discord/register", nil); rec.Code != http.StatusForbidden || h.render.code != ErrCodeRegistrationClosed {
t.Fatalf("GET status = %d code = %q", rec.Code, h.render.code)
}
h.render.code = ""
if rec := h.postRegister(validRegisterForm(), testOrigin); rec.Code != http.StatusForbidden || h.render.code != ErrCodeRegistrationClosed {
t.Fatalf("POST status = %d code = %q", rec.Code, h.render.code)
}
if len(h.web.created) != 0 {
t.Fatal("account created while web registration is disabled")
}
})
}
}
func TestWebRegisterFormShown(t *testing.T) {
h := newHarness(t)
h.openWeb(false)
rec := h.do(http.MethodGet, "/oauth2/discord/register?client_id=web", nil)
if rec.Code != http.StatusOK || h.render.register == nil {
t.Fatalf("status = %d", rec.Code)
}
f := h.render.register
if f.Action != "/oauth2/discord/register" || f.Query != "client_id=web" || f.LoginURL != "/signin/v1/identifier?client_id=web" {
t.Errorf("form = %+v", f)
}
}
func TestWebRegisterCreatesEnabledAccount(t *testing.T) {
h := newHarness(t)
h.openWeb(false)
rec := h.postRegister(validRegisterForm(), testOrigin)
if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/signin/v1/identifier?client_id=web&state=s1" {
t.Fatalf("status = %d location = %q", rec.Code, rec.Header().Get("Location"))
}
if len(h.web.created) != 1 || !h.web.enabled[0] {
t.Fatalf("created = %+v enabled = %v", h.web.created, h.web.enabled)
}
if u := h.web.created[0]; u.Username != "carol" || u.Mail != "carol@example.com" || u.Password != "Secret-pass1" {
t.Errorf("user = %+v", u)
}
if h.pending.IsPending(h.web.id) || h.sess.userID != "" {
t.Error("no pending entry and no session expected")
}
}
func TestWebRegisterWithApprovalIsPending(t *testing.T) {
h := newHarness(t)
h.openWeb(true)
rec := h.postRegister(validRegisterForm(), testOrigin)
if rec.Code != http.StatusOK || h.render.code != ErrCodeRegistrationSubmitted {
t.Fatalf("status = %d code = %q", rec.Code, h.render.code)
}
if len(h.web.enabled) != 1 || h.web.enabled[0] {
t.Fatalf("account must be created disabled, got %v", h.web.enabled)
}
p, ok := h.pending.Get(h.web.id)
if !ok || p.Source != SourceWeb || p.Username != "carol" || p.Mail != "carol@example.com" || p.RequestedAt.IsZero() {
t.Fatalf("pending = %+v ok = %v", p, ok)
}
if h.sess.userID != "" {
t.Error("no session may be issued for a pending account")
}
}
func TestWebRegisterValidation(t *testing.T) {
tests := map[string]struct {
field, value, code string
}{
"invalid username": {"username", "1x", ErrCodeUsernameInvalid},
"invalid mail": {"mail", "not-a-mail", ErrCodeMailInvalid},
"mail with name": {"mail", "Carol <carol@example.com>", ErrCodeMailInvalid},
"short password": {"password", "short", ErrCodePasswordInvalid},
"password mismatch": {"password_confirm", "Other-pass1", ErrCodePasswordMismatch},
}
for name, tt := range tests {
t.Run(name, func(t *testing.T) {
h := newHarness(t)
h.openWeb(false)
form := validRegisterForm()
form.Set(tt.field, tt.value)
if tt.field == "password" {
form.Set("password_confirm", tt.value)
}
rec := h.postRegister(form, testOrigin)
if rec.Code != http.StatusBadRequest || h.render.register == nil || h.render.register.ErrCode != tt.code {
t.Fatalf("status = %d form = %+v", rec.Code, h.render.register)
}
if len(h.web.created) != 0 {
t.Error("account created for invalid input")
}
})
}
}
func TestWebRegisterDirectoryErrors(t *testing.T) {
tests := map[string]struct {
err error
status int
code string
}{
"username taken": {ErrUsernameTaken, http.StatusConflict, ErrCodeUsernameTaken},
"mail taken": {ErrMailTaken, http.StatusConflict, ErrCodeMailTaken},
"password rejected": {ErrPasswordRejected, http.StatusBadRequest, ErrCodePasswordInvalid},
}
for name, tt := range tests {
t.Run(name, func(t *testing.T) {
h := newHarness(t)
h.openWeb(false)
h.web.err = tt.err
rec := h.postRegister(validRegisterForm(), testOrigin)
if rec.Code != tt.status || h.render.register == nil || h.render.register.ErrCode != tt.code {
t.Fatalf("status = %d form = %+v", rec.Code, h.render.register)
}
if h.render.register.Username != "carol" || h.render.register.Mail != "carol@example.com" {
t.Errorf("form lost the input: %+v", h.render.register)
}
})
}
h := newHarness(t)
h.openWeb(false)
h.web.err = errors.New("graph down")
if rec := h.postRegister(validRegisterForm(), testOrigin); rec.Code != http.StatusInternalServerError || h.render.code != ErrCodeProvision {
t.Fatalf("status = %d code = %q", rec.Code, h.render.code)
}
}
func TestWebRegisterRejectsCrossSitePost(t *testing.T) {
for name, origin := range map[string]string{"other site": "https://evil.example.net", "no origin": ""} {
t.Run(name, func(t *testing.T) {
h := newHarness(t)
h.openWeb(false)
if rec := h.postRegister(validRegisterForm(), origin); rec.Code != http.StatusForbidden || len(h.web.created) != 0 {
t.Fatalf("status = %d created = %v", rec.Code, h.web.created)
}
})
}
}
func TestWebPendingUserCanLogInAfterApproval(t *testing.T) {
h := newHarness(t)
h.openWeb(true)
if rec := h.postRegister(validRegisterForm(), testOrigin); rec.Code != http.StatusOK {
t.Fatalf("register status = %d", rec.Code)
}
// lico rejects the disabled account; the guard reports pending approval.
calls := 0
if rec := postLogon(h.handler.GuardLogon(fakeLico(false, &calls)), "carol"); rec.Code != http.StatusForbidden || !strings.Contains(rec.Body.String(), ErrCodePendingApproval) {
t.Fatalf("logon before approval: status = %d body = %s", rec.Code, rec.Body)
}
if rec := h.do(http.MethodPost, "/oauth2/discord/admin/pending/"+h.web.id+"/approve", nil); rec.Code != http.StatusNoContent {
t.Fatalf("approve status = %d", rec.Code)
}
if len(h.accounts.approved) != 1 || h.accounts.approved[0] != h.web.id {
t.Fatalf("approved = %v", h.accounts.approved)
}
// The account is enabled: lico accepts the password and the response passes through.
if rec := postLogon(h.handler.GuardLogon(fakeLico(true, &calls)), "carol"); rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"success":true`) {
t.Fatalf("logon after approval: status = %d body = %s", rec.Code, rec.Body)
}
// A wrong password is a normal failure again.
if rec := postLogon(h.handler.GuardLogon(fakeLico(false, &calls)), "carol"); rec.Code != http.StatusNoContent {
t.Fatalf("wrong password after approval: status = %d", rec.Code)
}
}
func TestGraphProvisionerCreateWebUser(t *testing.T) {
ctx := context.Background()
dir := newFakeDirectory(graphUser("u9", "bob", "bob@example.com", "Bob", ""))
p := GraphProvisioner{Dir: dir, Index: fakeIndex{}}
id, err := p.CreateWebUser(ctx, WebUser{Username: "carol", Mail: "carol@example.com", Password: "Secret-pass1"}, false)
if err != nil || id != "new-user-id" {
t.Fatalf("id = %q err = %v", id, err)
}
c := dir.created[0]
if c.GetOnPremisesSamAccountName() != "carol" || c.GetMail() != "carol@example.com" || c.GetDisplayName() != "carol" {
t.Errorf("created = %+v", c)
}
if c.GetAccountEnabled() {
t.Error("account must be disabled")
}
if pp := c.GetPasswordProfile(); pp.GetPassword() != "Secret-pass1" {
t.Error("password not set")
}
if _, err := p.CreateWebUser(ctx, WebUser{Username: "Bob", Mail: "x@example.com", Password: "Secret-pass1"}, true); !errors.Is(err, ErrUsernameTaken) {
t.Errorf("taken username: %v", err)
}
if _, err := p.CreateWebUser(ctx, WebUser{Username: "dave", Mail: "BOB@example.com", Password: "Secret-pass1"}, true); !errors.Is(err, ErrMailTaken) {
t.Errorf("taken mail: %v", err)
}
if _, err := p.CreateWebUser(ctx, WebUser{Username: "1x", Mail: "e@example.com", Password: "Secret-pass1"}, true); !errors.Is(err, ErrUsernameInvalid) {
t.Errorf("invalid username: %v", err)
}
dir.createErr = &GraphStatusError{Status: http.StatusBadRequest, Body: "password must contain at least one special character"}
if _, err := p.CreateWebUser(ctx, WebUser{Username: "erin", Mail: "erin@example.com", Password: "secretpass"}, true); !errors.Is(err, ErrPasswordRejected) {
t.Errorf("password policy: %v", err)
}
dir.createErr = &GraphStatusError{Status: http.StatusInternalServerError, Body: "boom"}
if _, err := p.CreateWebUser(ctx, WebUser{Username: "erin", Mail: "erin@example.com", Password: "Secret-pass1"}, true); err == nil || errors.Is(err, ErrPasswordRejected) || !strings.Contains(err.Error(), "graph returned 500") {
t.Errorf("server error: %v", err)
}
}
+61 -14
View File
@@ -8,6 +8,7 @@ import (
"fmt"
"html/template"
"net/http"
"path/filepath"
"time"
gateway "github.com/cs3org/go-cs3apis/cs3/gateway/v1beta1"
@@ -57,6 +58,16 @@ func newDiscordHandler(idp *IDP, options Options, mgrs *managers.Managers, autho
return nil, err
}
registration, err := discord.NewRegistrationStore(filepath.Join(filepath.Dir(cfg.Discord.SettingsFile), "registration.json"))
if err != nil {
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)
@@ -80,15 +91,21 @@ func newDiscordHandler(idp *IDP, options Options, mgrs *managers.Managers, autho
// share it and restarts do not break logins in progress.
key := sha256.Sum256([]byte("reverse-cloud/discord-state\x00" + cfg.TokenManager.JWTSecret))
return discord.NewHandler(discord.Options{
Store: store,
API: discord.NewClient(),
Provisioner: discord.GraphProvisioner{
Dir: discord.GraphDirectory{
Client: serviceGraphClient(cfg, gws, selector.NewSelector(selector.Registry(reg))),
},
Index: index,
prov := discord.GraphProvisioner{
Dir: discord.GraphDirectory{
Client: serviceGraphClient(cfg, gws, selector.NewSelector(selector.Registry(reg))),
},
Index: index,
}
return discord.NewHandler(discord.Options{
Store: store,
Registration: registration,
Pending: pending,
Accounts: prov,
WebAccounts: prov,
API: discord.NewClient(),
Provisioner: prov,
Sessions: discord.LicoSessionIssuer{Identifier: ident, SubAttribute: cfg.Ldap.UUIDAttribute},
Admin: admin,
Users: admin,
@@ -188,16 +205,18 @@ type discordContinueData struct {
// discordRenderer renders the Discord flow pages with the idp login layout.
type discordRenderer struct {
idp *IDP
errTpl *template.Template
signupTpl *template.Template
idp *IDP
errTpl *template.Template
signupTpl *template.Template
registerTpl *template.Template
}
func newDiscordRenderer(idp *IDP) discordRenderer {
return discordRenderer{
idp: idp,
errTpl: idp.mustParseTemplate("/identifier/loginerror.html", "Could not load loginerror template"),
signupTpl: idp.mustParseTemplate("/identifier/discord_signup.html", "Could not load discord signup template"),
idp: idp,
errTpl: idp.mustParseTemplate("/identifier/loginerror.html", "Could not load loginerror template"),
signupTpl: idp.mustParseTemplate("/identifier/discord_signup.html", "Could not load discord signup template"),
registerTpl: idp.mustParseTemplate("/identifier/discord_register.html", "Could not load registration template"),
}
}
@@ -313,6 +332,34 @@ 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.",
"アカウント登録申請を受け付けました。管理者の承認をお待ちください。",
},
discord.ErrCodeMailInvalid: {
"Please enter a valid email address.",
"有効なメールアドレスを入力してください。",
},
discord.ErrCodeMailTaken: {
"This email address is already used by another account.",
"このメールアドレスは既に別のアカウントで使われています。",
},
discord.ErrCodePasswordInvalid: {
"The password does not meet the requirements.",
"パスワードが条件を満たしていません。",
},
discord.ErrCodePasswordMismatch: {
"The passwords do not match.",
"パスワードが一致しません。",
},
}
func discordErrorMessage(r *http.Request, code string) string {
@@ -0,0 +1,61 @@
package svc
import (
"bytes"
"net/http"
"github.com/owncloud/ocis/v2/services/idp/pkg/discord"
)
type discordRegisterData struct {
basePageData
discord.RegisterForm
Intro, LabelUsername, HintUsername, LabelMail string
LabelPassword, HintPassword, LabelConfirm string
Button, BackLabel, Error, ErrField string
}
// registerErrField returns the form field an error code belongs to.
func registerErrField(code string) string {
switch code {
case discord.ErrCodeUsernameInvalid, discord.ErrCodeUsernameTaken:
return "username"
case discord.ErrCodeMailInvalid, discord.ErrCodeMailTaken:
return "mail"
case discord.ErrCodePasswordInvalid, discord.ErrCodePasswordMismatch:
return "password"
}
return ""
}
// Register implements discord.Renderer.
func (d discordRenderer) Register(w http.ResponseWriter, r *http.Request, status int, f discord.RegisterForm) {
base := d.page(r, "Create account - ownCloud", "Create account")
data := discordRegisterData{
basePageData: base,
RegisterForm: f,
Intro: localized(r, "Create a new account.", "新しいアカウントを作成します。"),
LabelUsername: localized(r, "Username", "ユーザー名"),
HintUsername: localized(r,
"3 to 32 characters. Start with a letter or _, then use letters, digits, '.', '_' or '-'.",
"3〜32 文字。先頭は英字か _ で、英数字と . _ - が使えます。"),
LabelMail: localized(r, "Email", "メールアドレス"),
LabelPassword: localized(r, "Password", "パスワード"),
HintPassword: localized(r,
"At least 8 characters with upper and lower case letters, a digit and a symbol.",
"8 文字以上で、英大文字・英小文字・数字・記号を含めてください。"),
LabelConfirm: localized(r, "Confirm password", "パスワード(確認)"),
Button: localized(r, "Create account", "アカウントを作成"),
BackLabel: localized(r, "Back to login", "ログイン画面に戻る"),
}
if f.ErrCode != "" {
data.Error = discordErrorMessage(r, f.ErrCode)
data.ErrField = registerErrField(f.ErrCode)
}
var buf bytes.Buffer
if err := d.registerTpl.Execute(&buf, data); err != nil {
http.Error(w, "template error", http.StatusInternalServerError)
return
}
writeSecureHTMLStatus(w, buf.Bytes(), base.Nonce, status)
}
+23 -5
View File
@@ -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,9 +365,11 @@ 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
RegisterURL, RegisterLabel string
}
type pageData struct {
@@ -454,16 +460,28 @@ 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"),
}
if idp.discord != nil && idp.discord.Enabled() {
data.DiscordLoginURL = discord.RoutePrefix() + "/login"
if idp.discord != nil {
query := ""
if r.URL.RawQuery != "" {
data.DiscordLoginURL += "?" + r.URL.RawQuery
query = "?" + r.URL.RawQuery
}
pub := idp.discord.PublicRegistration()
if pub.DiscordLogin {
data.DiscordLoginURL = discord.RoutePrefix() + "/login" + query
data.DiscordLabel = localized(r, "Log in with Discord", "Discord でログイン")
if pub.Discord {
data.DiscordLabel = localized(r, "Log in / Sign up with Discord", "Discord でログイン / 登録")
}
data.OrLabel = localized(r, "or", "または")
}
if pub.Web && len(r.URL.RawQuery) <= 4096 {
data.RegisterURL = discord.RoutePrefix() + "/register" + query
data.RegisterLabel = localized(r, "Create account", "アカウント作成")
}
data.DiscordLabel = localized(r, "Log in with Discord", "Discord でログイン")
data.OrLabel = localized(r, "or", "または")
}
idp.renderPage(w, tpl, base.Nonce, data)
}
@@ -0,0 +1,266 @@
<template>
<div v-if="canManage" id="registration-section">
<h2 class="oc-py-s" v-text="$gettext('Registration')" />
<p v-if="loadError" class="registration-load-error" v-text="loadError" />
<template v-else-if="loaded">
<div class="registration-settings">
<oc-switch
id="registration-allow"
:checked="settings.allow_registration"
:label="$gettext('Allow new registrations')"
@update:checked="(value: boolean) => update('allow_registration', value)"
/>
<oc-switch
id="registration-allow-web"
class="oc-mt-s"
:checked="settings.allow_web"
:label="$gettext('Allow email/password registration')"
@update:checked="(value: boolean) => update('allow_web', value)"
/>
<oc-switch
id="registration-allow-discord"
class="oc-mt-s"
:checked="settings.allow_discord"
:label="$gettext('Allow Discord registration')"
@update:checked="(value: boolean) => update('allow_discord', value)"
/>
<oc-switch
id="registration-require-approval"
class="oc-mt-s"
:checked="settings.require_approval"
:label="$gettext('Require admin approval')"
@update:checked="(value: boolean) => update('require_approval', value)"
/>
<p
v-if="!settings.allow_registration"
class="registration-closed-hint oc-text-muted oc-mt-s"
v-text="$gettext('New accounts cannot be created while registrations are closed.')"
/>
</div>
<h3 class="oc-mt-l oc-mb-s" v-text="$gettext('Pending approvals')" />
<p
v-if="!pending.length"
class="registration-pending-empty oc-text-muted"
v-text="$gettext('No accounts are waiting for approval.')"
/>
<oc-table-simple v-else class="registration-pending-table">
<oc-thead>
<oc-tr>
<oc-th>{{ $gettext('Username') }}</oc-th>
<oc-th>{{ $gettext('Email') }}</oc-th>
<oc-th>{{ $gettext('Source') }}</oc-th>
<oc-th>{{ $gettext('Requested') }}</oc-th>
<oc-th class="oc-invisible-sr">{{ $gettext('Actions') }}</oc-th>
</oc-tr>
</oc-thead>
<oc-tbody>
<oc-tr v-for="p in pending" :key="p.user_id" class="registration-pending-row">
<oc-td translate="no">{{ p.username }}</oc-td>
<oc-td translate="no">{{ p.mail || '-' }}</oc-td>
<oc-td>
<oc-tag size="small" class="registration-source">{{ sourceLabel(p.source) }}</oc-tag>
</oc-td>
<oc-td>{{ formatDate(p.requested_at) }}</oc-td>
<oc-td>
<div class="registration-actions">
<oc-button
class="registration-approve-btn"
size="small"
variation="primary"
appearance="filled"
:disabled="busy.has(p.user_id)"
@click="approve(p)"
>
{{ $gettext('Approve') }}
</oc-button>
<oc-button
class="registration-reject-btn"
size="small"
variation="danger"
:disabled="busy.has(p.user_id)"
@click="confirmReject(p)"
>
{{ $gettext('Reject') }}
</oc-button>
</div>
</oc-td>
</oc-tr>
</oc-tbody>
</oc-table-simple>
</template>
</div>
</template>
<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { useGettext } from 'vue3-gettext'
import {
formatDateFromJSDate,
useAbility,
useClientService,
useMessages,
useModals
} from '@ownclouders/web-pkg'
defineOptions({
name: 'RegistrationSection'
})
export type RegistrationSettings = {
allow_registration: boolean
allow_web: boolean
allow_discord: boolean
require_approval: boolean
}
export type PendingUser = {
user_id: string
username: string
display_name?: string
mail?: string
source: 'web' | 'discord' | string
requested_at: string
}
type Key = keyof RegistrationSettings
const SETTINGS_URL = '/oauth2/discord/admin/registration'
const PENDING_URL = '/oauth2/discord/admin/pending'
const ability = useAbility()
const clientService = useClientService()
const { showMessage, showErrorMessage } = useMessages()
const { dispatchModal } = useModals()
const language = useGettext()
const { $gettext } = language
const canManage = computed(() => ability.can('update-all', 'Setting'))
const loaded = ref(false)
const loadError = ref('')
const settings = reactive<RegistrationSettings>({
allow_registration: false,
allow_web: false,
allow_discord: false,
require_approval: false
})
const pending = ref<PendingUser[]>([])
const busy = reactive(new Set<string>())
const sourceLabel = (source: string) => {
switch (source) {
case 'web':
return $gettext('Web')
case 'discord':
return $gettext('Discord')
default:
return source
}
}
const formatDate = (iso: string) => {
const d = new Date(iso)
if (!iso || isNaN(d.getTime())) {
return '-'
}
return formatDateFromJSDate(d, language.current)
}
const load = async () => {
try {
const [s, p] = await Promise.all([
clientService.httpAuthenticated.get<RegistrationSettings>(SETTINGS_URL),
clientService.httpAuthenticated.get<{ value: PendingUser[] }>(PENDING_URL)
])
Object.assign(settings, s.data)
pending.value = (p.data as { value?: PendingUser[] })?.value || []
loaded.value = true
} catch (e) {
console.error(e)
loadError.value = $gettext('The registration settings could not be loaded.')
}
}
const update = async (key: Key, value: boolean) => {
const previous = settings[key]
settings[key] = value
try {
const { data } = await clientService.httpAuthenticated.put<RegistrationSettings>(
SETTINGS_URL,
{ ...settings }
)
Object.assign(settings, data)
showMessage({ title: $gettext('Registration settings were saved') })
} catch (e) {
console.error(e)
settings[key] = previous
showErrorMessage({
title: $gettext('Failed to save the registration settings'),
errors: [e as Error]
})
}
}
const decide = async (p: PendingUser, action: 'approve' | 'reject') => {
busy.add(p.user_id)
try {
await clientService.httpAuthenticated.post(
`${PENDING_URL}/${encodeURIComponent(p.user_id)}/${action}`
)
pending.value = pending.value.filter((u) => u.user_id !== p.user_id)
showMessage({
title:
action === 'approve'
? $gettext('Account "%{user}" was approved', { user: p.username })
: $gettext('Account "%{user}" was rejected', { user: p.username })
})
} catch (e) {
console.error(e)
showErrorMessage({
title:
action === 'approve'
? $gettext('Failed to approve account "%{user}"', { user: p.username })
: $gettext('Failed to reject account "%{user}"', { user: p.username }),
errors: [e as Error]
})
} finally {
busy.delete(p.user_id)
}
}
const approve = (p: PendingUser) => decide(p, 'approve')
const reject = (p: PendingUser) => decide(p, 'reject')
const confirmReject = (p: PendingUser) => {
dispatchModal({
variation: 'danger',
title: $gettext('Reject account "%{user}"?', { user: p.username }),
confirmText: $gettext('Reject'),
message: $gettext('The account will be deleted. This cannot be undone.'),
hasInput: false,
onConfirm: () => reject(p)
})
}
onMounted(() => {
if (canManage.value) {
load()
}
})
defineExpose({ settings, pending, update, approve, reject, confirmReject })
</script>
<style lang="scss" scoped>
.registration-settings {
max-width: 500px;
}
.registration-actions {
display: flex;
gap: var(--oc-space-xsmall);
justify-content: flex-end;
white-space: nowrap;
}
</style>
@@ -13,6 +13,7 @@
<InfoSection />
<AppearanceSection />
<DiscordSection />
<RegistrationSection />
</div>
</template>
</app-template>
@@ -25,6 +26,7 @@ import AppTemplate from '../components/AppTemplate.vue'
import InfoSection from '../components/General/InfoSection.vue'
import AppearanceSection from '../components/General/AppearanceSection.vue'
import DiscordSection from '../components/General/DiscordSection.vue'
import RegistrationSection from '../components/General/RegistrationSection.vue'
import DetailsPanel from '../components/General/SideBar/DetailsPanel.vue'
import { useGettext } from 'vue3-gettext'
import { useSideBar } from '@ownclouders/web-pkg'
@@ -0,0 +1,175 @@
import RegistrationSection from '../../../../src/components/General/RegistrationSection.vue'
import {
defaultComponentMocks,
defaultPlugins,
mockAxiosResolve,
shallowMount
} from '@ownclouders/web-test-helpers'
import { flushPromises } from '@vue/test-utils'
import { useMessages, useModals } from '@ownclouders/web-pkg'
const SETTINGS_URL = '/oauth2/discord/admin/registration'
const PENDING_URL = '/oauth2/discord/admin/pending'
const stored = {
allow_registration: true,
allow_web: false,
allow_discord: true,
require_approval: true
}
const pendingUsers = [
{
user_id: 'u1',
username: 'alice',
mail: 'alice@example.com',
source: 'discord',
requested_at: '2026-11-01T10:00:00Z'
},
{
user_id: 'u2',
username: 'carol',
mail: 'carol@example.com',
source: 'web',
requested_at: '2026-11-01T11:00:00Z'
}
]
describe('RegistrationSection', () => {
it('is hidden and does not load without the settings permission', async () => {
const { wrapper, mocks } = getWrapper({ canManage: false })
await flushPromises()
expect(wrapper.find('#registration-section').exists()).toBeFalsy()
expect(mocks.$clientService.httpAuthenticated.get).not.toHaveBeenCalled()
})
it('loads the settings and the pending accounts', async () => {
const { wrapper, mocks } = getWrapper()
await flushPromises()
expect(mocks.$clientService.httpAuthenticated.get).toHaveBeenCalledWith(SETTINGS_URL)
expect(mocks.$clientService.httpAuthenticated.get).toHaveBeenCalledWith(PENDING_URL)
expect(wrapper.vm.settings).toEqual(stored)
expect(wrapper.findAll('.registration-pending-row').length).toBe(2)
const badges = wrapper.findAll('.registration-source').map((b) => b.text())
expect(badges).toEqual(['Discord', 'Web'])
})
it('shows a notice when no account is pending', async () => {
const { wrapper } = getWrapper({ pending: [] })
await flushPromises()
expect(wrapper.find('.registration-pending-empty').exists()).toBeTruthy()
expect(wrapper.find('.registration-pending-table').exists()).toBeFalsy()
})
it('saves all settings when a toggle changes', async () => {
const { wrapper, mocks } = getWrapper()
await flushPromises()
const next = { ...stored, allow_web: true }
mocks.$clientService.httpAuthenticated.put.mockResolvedValue(mockAxiosResolve(next))
await wrapper.vm.update('allow_web', true)
expect(mocks.$clientService.httpAuthenticated.put).toHaveBeenCalledWith(SETTINGS_URL, next)
expect(wrapper.vm.settings.allow_web).toBe(true)
const { showMessage } = useMessages()
expect(showMessage).toHaveBeenCalled()
})
it('reverts the toggle when saving fails', async () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined)
const { wrapper, mocks } = getWrapper()
await flushPromises()
mocks.$clientService.httpAuthenticated.put.mockRejectedValue(new Error('500'))
await wrapper.vm.update('require_approval', false)
expect(wrapper.vm.settings.require_approval).toBe(true)
const { showErrorMessage } = useMessages()
expect(showErrorMessage).toHaveBeenCalled()
})
it('approves a pending account and removes it from the list', async () => {
const { wrapper, mocks } = getWrapper()
await flushPromises()
mocks.$clientService.httpAuthenticated.post.mockResolvedValue(mockAxiosResolve(undefined))
await wrapper.vm.approve(pendingUsers[0])
expect(mocks.$clientService.httpAuthenticated.post).toHaveBeenCalledWith(
`${PENDING_URL}/u1/approve`
)
expect(wrapper.vm.pending.map((p) => p.user_id)).toEqual(['u2'])
})
it('keeps the account in the list when approving fails', async () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined)
const { wrapper, mocks } = getWrapper()
await flushPromises()
mocks.$clientService.httpAuthenticated.post.mockRejectedValue(new Error('502'))
await wrapper.vm.approve(pendingUsers[0])
expect(wrapper.vm.pending.length).toBe(2)
const { showErrorMessage } = useMessages()
expect(showErrorMessage).toHaveBeenCalled()
})
it('asks for confirmation before rejecting', async () => {
const { wrapper, mocks } = getWrapper()
await flushPromises()
wrapper.vm.confirmReject(pendingUsers[1])
const { dispatchModal } = useModals()
expect(dispatchModal).toHaveBeenCalledWith(expect.objectContaining({ variation: 'danger' }))
expect(mocks.$clientService.httpAuthenticated.post).not.toHaveBeenCalled()
})
it('rejects a pending account and removes it from the list', async () => {
const { wrapper, mocks } = getWrapper()
await flushPromises()
mocks.$clientService.httpAuthenticated.post.mockResolvedValue(mockAxiosResolve(undefined))
await wrapper.vm.reject(pendingUsers[1])
expect(mocks.$clientService.httpAuthenticated.post).toHaveBeenCalledWith(
`${PENDING_URL}/u2/reject`
)
expect(wrapper.vm.pending.map((p) => p.user_id)).toEqual(['u1'])
})
it('shows an error when the settings cannot be loaded', async () => {
vi.spyOn(console, 'error').mockImplementation(() => undefined)
const { wrapper } = getWrapper({ loadFails: true })
await flushPromises()
expect(wrapper.find('.registration-load-error').exists()).toBeTruthy()
expect(wrapper.find('.registration-settings').exists()).toBeFalsy()
})
})
function getWrapper({
canManage = true,
settings = stored,
pending = pendingUsers,
loadFails = false
}: {
canManage?: boolean
settings?: typeof stored
pending?: typeof pendingUsers
loadFails?: boolean
} = {}) {
const mocks = defaultComponentMocks()
if (loadFails) {
mocks.$clientService.httpAuthenticated.get.mockRejectedValue(new Error('500'))
} else {
mocks.$clientService.httpAuthenticated.get.mockImplementation((url: string) =>
Promise.resolve(
url === PENDING_URL ? mockAxiosResolve({ value: pending }) : mockAxiosResolve(settings)
)
)
}
return {
mocks,
wrapper: shallowMount(RegistrationSection, {
global: {
provide: mocks,
mocks,
// Render the table rows inside the stubbed design-system components.
renderStubDefaultSlot: true,
plugins: [
...defaultPlugins({
abilities: canManage ? [{ action: 'update-all', subject: 'Setting' }] : []
})
]
}
})
}
}