Compare commits
11
Commits
8b132a520e
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
456dc232cb | ||
|
|
b690f4eb8f | ||
|
|
455d76cab4 | ||
|
|
10247ace43 | ||
|
|
ce462dbe20 | ||
|
|
cf505b3065 | ||
|
|
f8d3daf7ff | ||
|
|
0b0d460eac | ||
|
|
3ac62eb510 | ||
|
|
fbe1b9560b | ||
|
|
019e65a951 |
No files matched your search
@@ -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,86 @@
|
||||
// Package eventdedup drops redelivered copies of events.
|
||||
//
|
||||
// JetStream redelivers a message when its ack does not arrive within AckWait.
|
||||
// With reva's event consumers the ack is sent only after a worker takes the
|
||||
// event off the channel, so messages that wait behind a long running task can
|
||||
// be redelivered and processed twice. Every published event carries a unique
|
||||
// event ID (see reva events.Publish), so a redelivered copy has the same ID as
|
||||
// the original and can be recognised.
|
||||
//
|
||||
// The key is the event ID, not the upload ID: a single upload legitimately
|
||||
// produces several distinct events (BytesReceived, StepFinished, ...).
|
||||
package eventdedup
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/owncloud/reva/v2/pkg/events"
|
||||
)
|
||||
|
||||
// Seen remembers event IDs for a limited time.
|
||||
type Seen struct {
|
||||
mu sync.Mutex
|
||||
ttl time.Duration
|
||||
now func() time.Time
|
||||
ids map[string]time.Time
|
||||
lastGC time.Time
|
||||
}
|
||||
|
||||
// NewSeen returns a Seen that forgets IDs after ttl.
|
||||
func NewSeen(ttl time.Duration) *Seen {
|
||||
return &Seen{ttl: ttl, now: time.Now, ids: map[string]time.Time{}}
|
||||
}
|
||||
|
||||
// FirstTime records id and reports whether it was not seen within the ttl.
|
||||
// Empty IDs are always reported as first time, since they cannot be matched.
|
||||
func (s *Seen) FirstTime(id string) bool {
|
||||
if id == "" {
|
||||
return true
|
||||
}
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
now := s.now()
|
||||
if now.Sub(s.lastGC) > s.ttl {
|
||||
for k, t := range s.ids {
|
||||
if now.Sub(t) > s.ttl {
|
||||
delete(s.ids, k)
|
||||
}
|
||||
}
|
||||
s.lastGC = now
|
||||
}
|
||||
|
||||
if t, ok := s.ids[id]; ok && now.Sub(t) <= s.ttl {
|
||||
return false
|
||||
}
|
||||
s.ids[id] = now
|
||||
return true
|
||||
}
|
||||
|
||||
// Len returns the number of remembered IDs.
|
||||
func (s *Seen) Len() int {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return len(s.ids)
|
||||
}
|
||||
|
||||
// Filter forwards events from in whose ID was not seen before. onDrop, if not
|
||||
// nil, is called for every dropped duplicate. The returned channel is closed
|
||||
// when in is closed.
|
||||
func Filter(in <-chan events.Event, seen *Seen, onDrop func(events.Event)) <-chan events.Event {
|
||||
out := make(chan events.Event)
|
||||
go func() {
|
||||
defer close(out)
|
||||
for e := range in {
|
||||
if !seen.FirstTime(e.ID) {
|
||||
if onDrop != nil {
|
||||
onDrop(e)
|
||||
}
|
||||
continue
|
||||
}
|
||||
out <- e
|
||||
}
|
||||
}()
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
package eventdedup_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-micro/plugins/v4/events/natsjs"
|
||||
"github.com/nats-io/nats-server/v2/server"
|
||||
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/eventdedup"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/natsconsumer"
|
||||
"github.com/owncloud/reva/v2/pkg/events"
|
||||
"github.com/owncloud/reva/v2/pkg/events/stream"
|
||||
)
|
||||
|
||||
func TestSeen(t *testing.T) {
|
||||
s := eventdedup.NewSeen(time.Hour)
|
||||
if !s.FirstTime("a") || s.FirstTime("a") || !s.FirstTime("b") {
|
||||
t.Fatal("unexpected dedup result")
|
||||
}
|
||||
if !s.FirstTime("") || !s.FirstTime("") {
|
||||
t.Fatal("empty IDs must never be dropped")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeenExpires(t *testing.T) {
|
||||
s := eventdedup.NewSeen(50 * time.Millisecond)
|
||||
s.FirstTime("a")
|
||||
time.Sleep(120 * time.Millisecond)
|
||||
if !s.FirstTime("a") {
|
||||
t.Fatal("id should be forgotten after ttl")
|
||||
}
|
||||
if s.Len() != 1 {
|
||||
t.Fatalf("expired ids must be removed, len=%d", s.Len())
|
||||
}
|
||||
}
|
||||
|
||||
// runLongTaskScenario reproduces the production problem against a real
|
||||
// JetStream server. AckWait is short compared to the processing time of one
|
||||
// upload ("big"), and there is a single worker. While "big" is processed, the
|
||||
// reva forwarding goroutine is blocked handing off the first follower, so the
|
||||
// remaining followers stay unacked in the natsjs callback and JetStream
|
||||
// redelivers them. Those redelivered copies carry the same event ID as the
|
||||
// originals. The function returns how often each upload was processed.
|
||||
func runLongTaskScenario(t *testing.T, dedup bool) map[string]int {
|
||||
t.Helper()
|
||||
srv, err := server.NewServer(&server.Options{Host: "127.0.0.1", Port: -1, JetStream: true, StoreDir: t.TempDir(), NoSigs: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
go srv.Start()
|
||||
if !srv.ReadyForConnections(10 * time.Second) {
|
||||
t.Fatal("nats server not ready")
|
||||
}
|
||||
defer srv.Shutdown()
|
||||
|
||||
bus, err := stream.Nats(natsjs.Address(srv.ClientURL()), natsjs.ClusterID("test"), natsjs.SynchronousPublish(true))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ch, err := events.Consume(bus, "postprocessing", events.BytesReceived{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// shorten AckWait on the server so the test finishes in seconds
|
||||
nc, js, err := natsconsumer.Connect(natsconsumer.Connection{Endpoint: srv.ClientURL(), Name: "test"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer nc.Close()
|
||||
if _, err := natsconsumer.Apply(js, events.MainQueueName, "postprocessing", natsconsumer.Settings{AckWait: time.Second}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if dedup {
|
||||
ch = eventdedup.Filter(ch, eventdedup.NewSeen(time.Hour), nil)
|
||||
}
|
||||
|
||||
var mu sync.Mutex
|
||||
counts := map[string]int{}
|
||||
go func() { // a single worker, like a fully occupied worker pool
|
||||
for e := range ch {
|
||||
id := e.Event.(events.BytesReceived).UploadID
|
||||
mu.Lock()
|
||||
counts[id]++
|
||||
mu.Unlock()
|
||||
if id == "big" {
|
||||
time.Sleep(5 * time.Second) // much longer than AckWait
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// "big" occupies the worker; the followers queue up behind it. The first
|
||||
// follower is acked at hand-off, the later ones stay unacked and are
|
||||
// redelivered while the worker is busy.
|
||||
ids := []string{"big", "f0", "f1", "f2", "f3"}
|
||||
for _, id := range ids {
|
||||
if err := events.Publish(context.Background(), bus, events.BytesReceived{UploadID: id}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
time.Sleep(10 * time.Second)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
res := map[string]int{}
|
||||
for k, v := range counts {
|
||||
res[k] = v
|
||||
}
|
||||
return res
|
||||
}
|
||||
|
||||
func total(counts map[string]int) int {
|
||||
n := 0
|
||||
for _, v := range counts {
|
||||
n += v
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func TestRedeliveredEventsProcessedTwiceWithoutDedup(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("integration test")
|
||||
}
|
||||
counts := runLongTaskScenario(t, false)
|
||||
// 5 distinct uploads; any duplicate from redelivery pushes the total above 5.
|
||||
if total(counts) <= len(counts) {
|
||||
t.Fatalf("expected redelivered events to be processed more than once, counts=%v", counts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedeliveredEventsProcessedOnceWithDedup(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("integration test")
|
||||
}
|
||||
counts := runLongTaskScenario(t, true)
|
||||
var dupes []string
|
||||
for id, c := range counts {
|
||||
if c != 1 {
|
||||
dupes = append(dupes, fmt.Sprintf("%s=%d", id, c))
|
||||
}
|
||||
}
|
||||
if len(dupes) > 0 {
|
||||
t.Fatalf("each upload must be processed exactly once, duplicates: %v (counts=%v)", dupes, counts)
|
||||
}
|
||||
if len(counts) != 5 {
|
||||
t.Fatalf("all 5 uploads should be processed once, counts=%v", counts)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
// Package natsconsumer adjusts the settings of durable JetStream consumers that
|
||||
// were created by other components (for example reva's event consumers).
|
||||
//
|
||||
// The go-micro natsjs plugin used by reva creates its consumers with the server
|
||||
// defaults (AckWait 30s, unlimited MaxDeliver) and does not expose these options.
|
||||
// Passing them as subscribe options would break restarts, because nats.go rejects
|
||||
// a subscription whose options differ from the existing durable consumer.
|
||||
// Updating the consumer on the server avoids that: the client never sends
|
||||
// AckWait or MaxDeliver, so the server-side values survive restarts.
|
||||
package natsconsumer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/log"
|
||||
)
|
||||
|
||||
// Settings are the consumer settings to enforce. Zero values leave the current
|
||||
// server value untouched.
|
||||
type Settings struct {
|
||||
// AckWait is how long the server waits for an ack before redelivering.
|
||||
AckWait time.Duration
|
||||
// MaxDeliver is the maximum number of delivery attempts. -1 means unlimited.
|
||||
MaxDeliver int
|
||||
}
|
||||
|
||||
// IsZero reports whether no setting is requested.
|
||||
func (s Settings) IsZero() bool {
|
||||
return s.AckWait == 0 && s.MaxDeliver == 0
|
||||
}
|
||||
|
||||
// Validate checks the settings for values the server would reject.
|
||||
func (s Settings) Validate() error {
|
||||
if s.AckWait < 0 {
|
||||
return fmt.Errorf("ack wait must not be negative, got %s", s.AckWait)
|
||||
}
|
||||
if s.MaxDeliver < -1 {
|
||||
return fmt.Errorf("max deliver must be -1 (unlimited), 0 (unchanged) or positive, got %d", s.MaxDeliver)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Connection holds what is needed to reach the NATS server.
|
||||
type Connection struct {
|
||||
Endpoint string
|
||||
Name string
|
||||
EnableTLS bool
|
||||
TLSInsecure bool
|
||||
TLSRootCACertificate string
|
||||
AuthUsername string
|
||||
AuthPassword string
|
||||
}
|
||||
|
||||
// Connect opens a NATS connection and a JetStream context.
|
||||
func Connect(c Connection) (*nats.Conn, nats.JetStreamContext, error) {
|
||||
opts := []nats.Option{nats.Name(c.Name)}
|
||||
if c.AuthUsername != "" || c.AuthPassword != "" {
|
||||
opts = append(opts, nats.UserInfo(c.AuthUsername, c.AuthPassword))
|
||||
}
|
||||
if c.EnableTLS {
|
||||
tlsConf := &tls.Config{
|
||||
MinVersion: tls.VersionTLS12,
|
||||
InsecureSkipVerify: c.TLSInsecure, //nolint:gosec
|
||||
}
|
||||
if c.TLSRootCACertificate != "" {
|
||||
pem, err := os.ReadFile(c.TLSRootCACertificate)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
pool := x509.NewCertPool()
|
||||
if !pool.AppendCertsFromPEM(pem) {
|
||||
return nil, nil, errors.New("failed to append cert from PEM")
|
||||
}
|
||||
tlsConf.RootCAs = pool
|
||||
tlsConf.InsecureSkipVerify = false
|
||||
}
|
||||
opts = append(opts, nats.Secure(tlsConf))
|
||||
}
|
||||
|
||||
nc, err := nats.Connect(c.Endpoint, opts...)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
js, err := nc.JetStream()
|
||||
if err != nil {
|
||||
nc.Close()
|
||||
return nil, nil, err
|
||||
}
|
||||
return nc, js, nil
|
||||
}
|
||||
|
||||
// Apply updates the consumer when its settings differ from s. It reports
|
||||
// whether an update was sent.
|
||||
func Apply(js nats.JetStreamManager, stream, consumer string, s Settings) (bool, error) {
|
||||
if err := s.Validate(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
info, err := js.ConsumerInfo(stream, consumer)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
cfg := info.Config
|
||||
changed := false
|
||||
if s.AckWait > 0 && cfg.AckWait != s.AckWait {
|
||||
if len(cfg.BackOff) > 0 {
|
||||
return false, fmt.Errorf("consumer %s/%s uses a backoff list, which overrides ack wait", stream, consumer)
|
||||
}
|
||||
cfg.AckWait = s.AckWait
|
||||
changed = true
|
||||
}
|
||||
if s.MaxDeliver != 0 && cfg.MaxDeliver != s.MaxDeliver {
|
||||
cfg.MaxDeliver = s.MaxDeliver
|
||||
changed = true
|
||||
}
|
||||
if !changed {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
if _, err := js.UpdateConsumer(stream, &cfg); err != nil {
|
||||
return false, fmt.Errorf("updating consumer %s/%s: %w", stream, consumer, err)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// Ensure connects to NATS and applies s to the consumer. It retries every
|
||||
// retryInterval while the stream or consumer does not exist yet, until ctx is done.
|
||||
func Ensure(ctx context.Context, logger log.Logger, conn Connection, stream, consumer string, s Settings, retryInterval time.Duration) error {
|
||||
if s.IsZero() {
|
||||
return nil
|
||||
}
|
||||
if err := s.Validate(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
nc, js, err := Connect(conn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer nc.Close()
|
||||
|
||||
for {
|
||||
updated, err := Apply(js, stream, consumer, s)
|
||||
switch {
|
||||
case err == nil:
|
||||
ev := logger.Debug()
|
||||
msg := "NATS consumer settings already up to date"
|
||||
if updated {
|
||||
ev = logger.Info()
|
||||
msg = "updated NATS consumer settings"
|
||||
}
|
||||
ev.Str("stream", stream).Str("consumer", consumer).
|
||||
Str("ackWait", s.AckWait.String()).Int("maxDeliver", s.MaxDeliver).Msg(msg)
|
||||
return nil
|
||||
case errors.Is(err, nats.ErrConsumerNotFound), errors.Is(err, nats.ErrStreamNotFound):
|
||||
// the owning component has not subscribed yet
|
||||
default:
|
||||
return err
|
||||
}
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return fmt.Errorf("consumer %s/%s not found: %w", stream, consumer, ctx.Err())
|
||||
case <-time.After(retryInterval):
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package natsconsumer_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/nats-io/nats-server/v2/server"
|
||||
"github.com/nats-io/nats.go"
|
||||
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/log"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/natsconsumer"
|
||||
)
|
||||
|
||||
func runServer(t *testing.T) string {
|
||||
t.Helper()
|
||||
s, err := server.NewServer(&server.Options{Host: "127.0.0.1", Port: -1, JetStream: true, StoreDir: t.TempDir(), NoSigs: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
go s.Start()
|
||||
if !s.ReadyForConnections(10 * time.Second) {
|
||||
t.Fatal("nats server not ready")
|
||||
}
|
||||
t.Cleanup(s.Shutdown)
|
||||
return s.ClientURL()
|
||||
}
|
||||
|
||||
// subscribeLikeNatsjs subscribes with exactly the options the go-micro natsjs
|
||||
// plugin uses (no AckWait, no MaxDeliver).
|
||||
func subscribeLikeNatsjs(t *testing.T, url string) *nats.Conn {
|
||||
t.Helper()
|
||||
nc, err := nats.Connect(url)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
js, err := nc.JetStream()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := js.StreamInfo("main-queue"); err != nil {
|
||||
if _, err := js.AddStream(&nats.StreamConfig{Name: "main-queue"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
_, err = js.QueueSubscribe("main-queue", "dcfs", func(*nats.Msg) {},
|
||||
nats.AckExplicit(), nats.DeliverNew(), nats.Durable("dcfs"))
|
||||
if err != nil {
|
||||
t.Fatalf("subscribe: %v", err)
|
||||
}
|
||||
return nc
|
||||
}
|
||||
|
||||
func TestApplyUpdatesConsumerAndSurvivesRestart(t *testing.T) {
|
||||
url := runServer(t)
|
||||
nc := subscribeLikeNatsjs(t, url)
|
||||
|
||||
cnc, js, err := natsconsumer.Connect(natsconsumer.Connection{Endpoint: url, Name: "test"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer cnc.Close()
|
||||
|
||||
want := natsconsumer.Settings{AckWait: 30 * time.Minute, MaxDeliver: 3}
|
||||
updated, err := natsconsumer.Apply(js, "main-queue", "dcfs", want)
|
||||
if err != nil || !updated {
|
||||
t.Fatalf("Apply: updated=%v err=%v", updated, err)
|
||||
}
|
||||
if updated, err := natsconsumer.Apply(js, "main-queue", "dcfs", want); err != nil || updated {
|
||||
t.Fatalf("second Apply should be a no-op: updated=%v err=%v", updated, err)
|
||||
}
|
||||
|
||||
// Simulate a service restart: the durable stays, the client resubscribes
|
||||
// with the natsjs options. This must not fail with a config mismatch.
|
||||
nc.Close()
|
||||
nc2 := subscribeLikeNatsjs(t, url)
|
||||
defer nc2.Close()
|
||||
|
||||
info, err := js.ConsumerInfo("main-queue", "dcfs")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Config.AckWait != want.AckWait || info.Config.MaxDeliver != want.MaxDeliver {
|
||||
t.Fatalf("got AckWait=%s MaxDeliver=%d", info.Config.AckWait, info.Config.MaxDeliver)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnsureWaitsForConsumer(t *testing.T) {
|
||||
url := runServer(t)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- natsconsumer.Ensure(ctx, log.NopLogger(), natsconsumer.Connection{Endpoint: url, Name: "test"},
|
||||
"main-queue", "dcfs", natsconsumer.Settings{AckWait: 10 * time.Minute, MaxDeliver: 2}, 100*time.Millisecond)
|
||||
}()
|
||||
|
||||
time.Sleep(500 * time.Millisecond) // the consumer appears after Ensure starts
|
||||
nc := subscribeLikeNatsjs(t, url)
|
||||
defer nc.Close()
|
||||
|
||||
if err := <-done; err != nil {
|
||||
t.Fatalf("Ensure: %v", err)
|
||||
}
|
||||
js, _ := nc.JetStream()
|
||||
info, err := js.ConsumerInfo("main-queue", "dcfs")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Config.AckWait != 10*time.Minute || info.Config.MaxDeliver != 2 {
|
||||
t.Fatalf("got AckWait=%s MaxDeliver=%d", info.Config.AckWait, info.Config.MaxDeliver)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidate(t *testing.T) {
|
||||
if err := (natsconsumer.Settings{MaxDeliver: -2}).Validate(); err == nil {
|
||||
t.Fatal("expected error for MaxDeliver -2")
|
||||
}
|
||||
if err := (natsconsumer.Settings{AckWait: -time.Second}).Validate(); err == nil {
|
||||
t.Fatal("expected error for negative AckWait")
|
||||
}
|
||||
}
|
||||
@@ -566,7 +566,7 @@ func (g Graph) updateDrive(w http.ResponseWriter, r *http.Request, apiVersion AP
|
||||
}
|
||||
|
||||
if _, ok := drive.GetNameOk(); ok {
|
||||
spacename := strings.TrimSpace(drive.GetName())
|
||||
spacename := sanitizeSpaceName(drive.GetName())
|
||||
if err := validateSpaceName(spacename); err != nil {
|
||||
logger.Info().Err(err).Msg("could not update drive: spacename invalid")
|
||||
errorcode.GeneralException.Render(w, r, http.StatusBadRequest, err.Error())
|
||||
|
||||
@@ -123,6 +123,27 @@ func TestSort(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSanitizeSpaceName(t *testing.T) {
|
||||
testCases := []struct {
|
||||
Alias string
|
||||
Input string
|
||||
Expected string
|
||||
}{
|
||||
{"slash and spaces", "User / Name", "User _ Name"},
|
||||
{"all forbidden", `/ \ . : ? * " > < |`, "_ _ _ _ _ _ _ _ _ _"},
|
||||
{"trim", " Alice ", "Alice"},
|
||||
{"safe name", "Alice", "Alice"},
|
||||
{"empty", " ", ""},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
require.Equal(t, tc.Expected, sanitizeSpaceName(tc.Input), tc.Alias)
|
||||
if tc.Expected != "" {
|
||||
require.NoError(t, validateSpaceName(sanitizeSpaceName(tc.Input)), tc.Alias)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSpaceNameValidation(t *testing.T) {
|
||||
// set max length
|
||||
_maxSpaceNameLength = 10
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package svc
|
||||
|
||||
import "strings"
|
||||
|
||||
const spaceNameReplacement = "_"
|
||||
|
||||
func sanitizeSpaceName(name string) string {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
return ""
|
||||
}
|
||||
for _, c := range _invalidSpaceNameCharacters {
|
||||
name = strings.ReplaceAll(name, c, spaceNameReplacement)
|
||||
}
|
||||
name = strings.Join(strings.Fields(name), " ")
|
||||
return strings.TrimSpace(name)
|
||||
}
|
||||
@@ -30,6 +30,7 @@ import (
|
||||
ocissettingssvc "github.com/owncloud/ocis/v2/services/settings/pkg/service/v0"
|
||||
"github.com/owncloud/ocis/v2/services/settings/pkg/store/defaults"
|
||||
revactx "github.com/owncloud/reva/v2/pkg/ctx"
|
||||
userv1beta1 "github.com/cs3org/go-cs3apis/cs3/identity/user/v1beta1"
|
||||
"github.com/owncloud/reva/v2/pkg/events"
|
||||
"github.com/owncloud/reva/v2/pkg/rgrpc/status"
|
||||
"github.com/owncloud/reva/v2/pkg/utils"
|
||||
@@ -513,6 +514,10 @@ func (g Graph) PostUser(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
if err := g.ensurePersonalSpace(r.Context(), u); err != nil {
|
||||
logger.Error().Err(err).Str("id", u.GetId()).Msg("could not provision personal space")
|
||||
}
|
||||
|
||||
// assign roles if possible
|
||||
if g.roleService != nil && g.config.API.AssignDefaultUserRole {
|
||||
// All users get the user role by default currently.
|
||||
@@ -1058,9 +1063,134 @@ func (g Graph) patchUser(w http.ResponseWriter, r *http.Request, nameOrID string
|
||||
}
|
||||
|
||||
u.PreferredLanguage = preferredLanguage
|
||||
|
||||
if _, ok := changes.GetDisplayNameOk(); ok {
|
||||
if err := g.syncPersonalSpaceName(r.Context(), u); err != nil {
|
||||
logger.Error().Err(err).Str("id", u.GetId()).Msg("could not sync personal space name")
|
||||
errorcode.GeneralException.Render(w, r, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
g.patchUserResponse(w, r, u, features)
|
||||
}
|
||||
|
||||
func (g Graph) syncPersonalSpaceName(ctx context.Context, user *libregraph.User) error {
|
||||
if user == nil || user.GetId() == "" {
|
||||
return nil
|
||||
}
|
||||
spaceName := sanitizeSpaceName(user.GetDisplayName())
|
||||
if err := validateSpaceName(spaceName); err != nil {
|
||||
return fmt.Errorf("invalid spacename: %s", err.Error())
|
||||
}
|
||||
|
||||
client, err := g.gatewaySelector.Next()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
spaces, err := client.ListStorageSpaces(ctx, &storageprovider.ListStorageSpacesRequest{
|
||||
Opaque: utils.AppendPlainToOpaque(nil, "unrestricted", "T"),
|
||||
Filters: []*storageprovider.ListStorageSpacesRequest_Filter{
|
||||
listStorageSpacesUserFilter(user.GetId()),
|
||||
listStorageSpacesTypeFilter(_spaceTypePersonal),
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch spaces.GetStatus().GetCode() {
|
||||
case cs3rpc.Code_CODE_OK:
|
||||
case cs3rpc.Code_CODE_NOT_FOUND:
|
||||
return g.ensurePersonalSpace(ctx, user)
|
||||
default:
|
||||
return fmt.Errorf("%s", spaces.GetStatus().GetMessage())
|
||||
}
|
||||
if len(spaces.GetStorageSpaces()) == 0 {
|
||||
return g.ensurePersonalSpace(ctx, user)
|
||||
}
|
||||
|
||||
sp := spaces.GetStorageSpaces()[0]
|
||||
if sp.GetName() == spaceName {
|
||||
return nil
|
||||
}
|
||||
resp, err := client.UpdateStorageSpace(ctx, &storageprovider.UpdateStorageSpaceRequest{
|
||||
StorageSpace: &storageprovider.StorageSpace{
|
||||
Id: &storageprovider.StorageSpaceId{OpaqueId: sp.GetId().GetOpaqueId()},
|
||||
Root: sp.GetRoot(),
|
||||
Name: spaceName,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.GetStatus().GetCode() != cs3rpc.Code_CODE_OK {
|
||||
return fmt.Errorf("%s", resp.GetStatus().GetMessage())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g Graph) ensurePersonalSpace(ctx context.Context, user *libregraph.User) error {
|
||||
if user == nil || user.GetId() == "" {
|
||||
return nil
|
||||
}
|
||||
spaceName := sanitizeSpaceName(user.GetDisplayName())
|
||||
if spaceName == "" {
|
||||
spaceName = sanitizeSpaceName(user.GetOnPremisesSamAccountName())
|
||||
}
|
||||
if err := validateSpaceName(spaceName); err != nil {
|
||||
return fmt.Errorf("invalid spacename: %s", err.Error())
|
||||
}
|
||||
|
||||
client, err := g.gatewaySelector.Next()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
existing, err := client.ListStorageSpaces(ctx, &storageprovider.ListStorageSpacesRequest{
|
||||
Opaque: utils.AppendPlainToOpaque(nil, "unrestricted", "T"),
|
||||
Filters: []*storageprovider.ListStorageSpacesRequest_Filter{
|
||||
listStorageSpacesUserFilter(user.GetId()),
|
||||
listStorageSpacesTypeFilter(_spaceTypePersonal),
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if existing.GetStatus().GetCode() == cs3rpc.Code_CODE_OK && len(existing.GetStorageSpaces()) > 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
owner := &userv1beta1.User{
|
||||
Id: &userv1beta1.UserId{
|
||||
OpaqueId: user.GetId(),
|
||||
},
|
||||
Username: user.GetOnPremisesSamAccountName(),
|
||||
DisplayName: spaceName,
|
||||
}
|
||||
if current, ok := revactx.ContextGetUser(ctx); ok && current.GetId().GetOpaqueId() == user.GetId() {
|
||||
owner = current
|
||||
owner.DisplayName = spaceName
|
||||
}
|
||||
|
||||
spaceCtx := revactx.ContextSetUser(ctx, owner)
|
||||
resp, err := client.CreateStorageSpace(spaceCtx, &storageprovider.CreateStorageSpaceRequest{
|
||||
Type: _spaceTypePersonal,
|
||||
Name: spaceName,
|
||||
Owner: owner,
|
||||
Opaque: utils.AppendPlainToOpaque(nil, "space_id", user.GetId()),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch resp.GetStatus().GetCode() {
|
||||
case cs3rpc.Code_CODE_OK, cs3rpc.Code_CODE_ALREADY_EXISTS:
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("%s", resp.GetStatus().GetMessage())
|
||||
}
|
||||
}
|
||||
|
||||
func (g *Graph) patchUserResponse(w http.ResponseWriter, r *http.Request, user *libregraph.User, features []events.UserFeature) {
|
||||
e := events.UserFeatureChanged{
|
||||
UserID: *user.Id,
|
||||
|
||||
@@ -1328,6 +1328,93 @@ var _ = Describe("Users", func() {
|
||||
Expect(rr.Code).To(Equal(http.StatusBadRequest))
|
||||
})
|
||||
|
||||
It("syncs a personal space name that contains forbidden characters", func() {
|
||||
user.SetDisplayName("User / Name")
|
||||
user.SetId("user-id")
|
||||
user.SetOnPremisesSamAccountName("missan")
|
||||
|
||||
userUpdate.SetDisplayName("User / Name")
|
||||
expectedUser.SetDisplayName("User / Name")
|
||||
expectedUser.SetId(user.GetId())
|
||||
expectedUser.SetOnPremisesSamAccountName("missan")
|
||||
|
||||
permissionService.On("GetPermissionByID", mock.Anything, mock.Anything).Return(&settings.GetPermissionByIDResponse{
|
||||
Permission: &settingsmsg.Permission{
|
||||
Constraint: settingsmsg.Permission_CONSTRAINT_ALL,
|
||||
},
|
||||
}, nil)
|
||||
identityBackend.On("UpdateUser", mock.Anything, user.GetId(), mock.Anything).Return(expectedUser, nil)
|
||||
gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(&provider.ListStorageSpacesResponse{
|
||||
Status: status.NewOK(ctx),
|
||||
StorageSpaces: []*provider.StorageSpace{{
|
||||
Id: &provider.StorageSpaceId{OpaqueId: "space-id"},
|
||||
Name: "User / Name",
|
||||
Root: &provider.ResourceId{StorageId: "pro-1", SpaceId: "space-id", OpaqueId: "space-id"},
|
||||
}},
|
||||
}, nil)
|
||||
gatewayClient.On("UpdateStorageSpace", mock.Anything, mock.Anything).Return(&provider.UpdateStorageSpaceResponse{
|
||||
Status: status.NewOK(ctx),
|
||||
StorageSpace: &provider.StorageSpace{
|
||||
Id: &provider.StorageSpaceId{OpaqueId: "space-id"},
|
||||
Name: "User _ Name",
|
||||
Root: &provider.ResourceId{StorageId: "pro-1", SpaceId: "space-id", OpaqueId: "space-id"},
|
||||
},
|
||||
}, nil)
|
||||
|
||||
data, err := json.Marshal(userUpdate)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
r := httptest.NewRequest(http.MethodPost, "/graph/v1.0/users", bytes.NewBuffer(data))
|
||||
rctx := chi.NewRouteContext()
|
||||
rctx.URLParams.Add("userID", user.GetId())
|
||||
r = r.WithContext(context.WithValue(revactx.ContextSetUser(ctx, currentUser), chi.RouteCtxKey, rctx))
|
||||
svc.PatchUser(rr, r)
|
||||
|
||||
Expect(rr.Code).To(Equal(http.StatusOK))
|
||||
gatewayClient.AssertCalled(GinkgoT(), "UpdateStorageSpace", mock.Anything, mock.MatchedBy(func(req *provider.UpdateStorageSpaceRequest) bool {
|
||||
return req.GetStorageSpace().GetName() == "User _ Name"
|
||||
}))
|
||||
})
|
||||
|
||||
It("creates a missing personal space with a sanitized name", func() {
|
||||
user.SetDisplayName("User / Name")
|
||||
user.SetId("user-id")
|
||||
user.SetOnPremisesSamAccountName("missan")
|
||||
|
||||
userUpdate.SetDisplayName("User / Name")
|
||||
expectedUser.SetDisplayName("User / Name")
|
||||
expectedUser.SetId(user.GetId())
|
||||
expectedUser.SetOnPremisesSamAccountName("missan")
|
||||
|
||||
permissionService.On("GetPermissionByID", mock.Anything, mock.Anything).Return(&settings.GetPermissionByIDResponse{
|
||||
Permission: &settingsmsg.Permission{
|
||||
Constraint: settingsmsg.Permission_CONSTRAINT_ALL,
|
||||
},
|
||||
}, nil)
|
||||
identityBackend.On("UpdateUser", mock.Anything, user.GetId(), mock.Anything).Return(expectedUser, nil)
|
||||
gatewayClient.On("ListStorageSpaces", mock.Anything, mock.Anything).Return(&provider.ListStorageSpacesResponse{
|
||||
Status: status.NewOK(ctx),
|
||||
StorageSpaces: []*provider.StorageSpace{},
|
||||
}, nil)
|
||||
gatewayClient.On("CreateStorageSpace", mock.Anything, mock.Anything).Return(&provider.CreateStorageSpaceResponse{
|
||||
Status: status.NewOK(ctx),
|
||||
}, nil)
|
||||
|
||||
data, err := json.Marshal(userUpdate)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
|
||||
r := httptest.NewRequest(http.MethodPost, "/graph/v1.0/users", bytes.NewBuffer(data))
|
||||
rctx := chi.NewRouteContext()
|
||||
rctx.URLParams.Add("userID", user.GetId())
|
||||
r = r.WithContext(context.WithValue(revactx.ContextSetUser(ctx, currentUser), chi.RouteCtxKey, rctx))
|
||||
svc.PatchUser(rr, r)
|
||||
|
||||
Expect(rr.Code).To(Equal(http.StatusOK))
|
||||
gatewayClient.AssertCalled(GinkgoT(), "CreateStorageSpace", mock.Anything, mock.MatchedBy(func(req *provider.CreateStorageSpaceRequest) bool {
|
||||
return req.GetType() == "personal" && req.GetName() == "User _ Name"
|
||||
}))
|
||||
})
|
||||
|
||||
It("updates attributes", func() {
|
||||
userUpdate.SetMail("mail@mail.test")
|
||||
userUpdate.SetDisplayName("New Display Name")
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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")
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -5,13 +5,16 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"time"
|
||||
|
||||
"github.com/owncloud/reva/v2/pkg/events"
|
||||
"github.com/owncloud/reva/v2/pkg/events/stream"
|
||||
"github.com/owncloud/reva/v2/pkg/store"
|
||||
"github.com/urfave/cli/v2"
|
||||
microstore "go-micro.dev/v4/store"
|
||||
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/generators"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/natsconsumer"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/runner"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/tracing"
|
||||
"github.com/owncloud/ocis/v2/services/postprocessing/pkg/config"
|
||||
@@ -73,6 +76,27 @@ func Server(cfg *config.Config) *cli.Command {
|
||||
return err
|
||||
}
|
||||
|
||||
// The consumer exists now (NewPostprocessingService subscribed), so its
|
||||
// server-side settings can be adjusted without breaking later restarts.
|
||||
go func() {
|
||||
ev := cfg.Postprocessing.Events
|
||||
err := natsconsumer.Ensure(ctx, logger, natsconsumer.Connection{
|
||||
Endpoint: ev.Endpoint,
|
||||
Name: cfg.Service.Name + "-consumer-config",
|
||||
EnableTLS: ev.EnableTLS,
|
||||
TLSInsecure: ev.TLSInsecure,
|
||||
TLSRootCACertificate: ev.TLSRootCACertificate,
|
||||
AuthUsername: ev.AuthUsername,
|
||||
AuthPassword: ev.AuthPassword,
|
||||
}, events.MainQueueName, "postprocessing", natsconsumer.Settings{
|
||||
AckWait: cfg.Postprocessing.AckWait,
|
||||
MaxDeliver: cfg.Postprocessing.MaxDelivery,
|
||||
}, 5*time.Second)
|
||||
if err != nil {
|
||||
logger.Error().Err(err).Msg("could not apply NATS consumer settings")
|
||||
}
|
||||
}()
|
||||
|
||||
gr.Add(runner.New(cfg.Service.Name+".svc", func() error {
|
||||
return svc.Run()
|
||||
}, func() {
|
||||
|
||||
@@ -26,7 +26,11 @@ type Config struct {
|
||||
// Postprocessing defines the config options for the postprocessing service.
|
||||
type Postprocessing struct {
|
||||
Events Events `yaml:"events"`
|
||||
Workers int `yaml:"workers" env:"POSTPROCESSING_WORKERS" desc:"The number of concurrent go routines that fetch events from the event queue." introductionVersion:"6.7"`
|
||||
Workers int `yaml:"workers" env:"POSTPROCESSING_WORKERS;POSTPROCESSING_CONCURRENCY" desc:"The number of concurrent go routines that fetch events from the event queue. POSTPROCESSING_CONCURRENCY is an alias and takes precedence when both are set." introductionVersion:"6.7"`
|
||||
|
||||
AckWait time.Duration `yaml:"ack_wait" env:"POSTPROCESSING_ACK_WAIT" desc:"How long the NATS JetStream server waits for an acknowledgement before it redelivers an event to the postprocessing consumer. The value is written to the durable consumer on the server at startup. Set to 0 to keep the current server value. See the Environment Variable Types description for more details." introductionVersion:"8.3.0"`
|
||||
MaxDelivery int `yaml:"max_delivery" env:"POSTPROCESSING_MAX_DELIVERY" desc:"Maximum number of delivery attempts of an event to the postprocessing consumer. Events exceeding it are no longer redelivered. -1 means unlimited, 0 keeps the current server value." introductionVersion:"8.3.0"`
|
||||
DedupWindow time.Duration `yaml:"dedup_window" env:"POSTPROCESSING_DEDUP_WINDOW" desc:"How long event IDs are remembered to drop redelivered duplicates. Should be at least ack_wait multiplied by max_delivery. Set to 0 to disable deduplication. See the Environment Variable Types description for more details." introductionVersion:"8.3.0"`
|
||||
|
||||
Steps []string `yaml:"steps" env:"POSTPROCESSING_STEPS" desc:"A list of postprocessing steps processed in order of their appearance. Currently supported values by the system are: 'virusscan', 'policies' and 'delay'. Custom steps are allowed. See the documentation for instructions. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
Delayprocessing time.Duration `yaml:"delayprocessing" env:"POSTPROCESSING_DELAY" desc:"After uploading a file but before making it available for download, a delay step can be added. Intended for developing purposes only. If a duration is set but the keyword 'delay' is not explicitely added to 'POSTPROCESSING_STEPS', the delay step will be processed as last step. In such a case, a log entry will be written on service startup to remind the admin about that situation. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
@@ -57,11 +61,11 @@ type Debug struct {
|
||||
|
||||
// Store configures the store to use
|
||||
type Store struct {
|
||||
Store string `yaml:"store" env:"OCIS_PERSISTENT_STORE;POSTPROCESSING_STORE" desc:"The type of the store. Supported values are: 'memory', 'redis-sentinel', 'nats-js-kv', 'noop'. See the text description for details." introductionVersion:"pre5.0"`
|
||||
Nodes []string `yaml:"nodes" env:"OCIS_PERSISTENT_STORE_NODES;POSTPROCESSING_STORE_NODES" desc:"A list of nodes to access the configured store. This has no effect when 'memory' store is configured. Note that the behaviour how nodes are used is dependent on the library of the configured store. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
Database string `yaml:"database" env:"POSTPROCESSING_STORE_DATABASE" desc:"The database name the configured store should use." introductionVersion:"pre5.0"`
|
||||
Table string `yaml:"table" env:"POSTPROCESSING_STORE_TABLE" desc:"The database table the store should use." introductionVersion:"pre5.0"`
|
||||
TTL time.Duration `yaml:"ttl" env:"OCIS_PERSISTENT_STORE_TTL;POSTPROCESSING_STORE_TTL" desc:"Time to live for events in the store. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
Store string `yaml:"store" env:"OCIS_PERSISTENT_STORE;POSTPROCESSING_STORE" desc:"The type of the store. Supported values are: 'memory', 'redis-sentinel', 'nats-js-kv', 'noop'. See the text description for details." introductionVersion:"pre5.0"`
|
||||
Nodes []string `yaml:"nodes" env:"OCIS_PERSISTENT_STORE_NODES;POSTPROCESSING_STORE_NODES" desc:"A list of nodes to access the configured store. This has no effect when 'memory' store is configured. Note that the behaviour how nodes are used is dependent on the library of the configured store. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
Database string `yaml:"database" env:"POSTPROCESSING_STORE_DATABASE" desc:"The database name the configured store should use." introductionVersion:"pre5.0"`
|
||||
Table string `yaml:"table" env:"POSTPROCESSING_STORE_TABLE" desc:"The database table the store should use." introductionVersion:"pre5.0"`
|
||||
TTL time.Duration `yaml:"ttl" env:"OCIS_PERSISTENT_STORE_TTL;POSTPROCESSING_STORE_TTL" desc:"Time to live for events in the store. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
AuthUsername string `yaml:"username" env:"OCIS_PERSISTENT_STORE_AUTH_USERNAME;POSTPROCESSING_STORE_AUTH_USERNAME" desc:"The username to authenticate with the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
AuthPassword string `yaml:"password" env:"OCIS_PERSISTENT_STORE_AUTH_PASSWORD;POSTPROCESSING_STORE_AUTH_PASSWORD" desc:"The password to authenticate with the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
EnableTLS bool `yaml:"enable_tls" env:"OCIS_PERSISTENT_STORE_ENABLE_TLS;POSTPROCESSING_STORE_ENABLE_TLS" desc:"Activate TLS for the connection to the store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
|
||||
|
||||
@@ -32,6 +32,9 @@ func DefaultConfig() *config.Config {
|
||||
Cluster: "ocis-cluster",
|
||||
},
|
||||
Workers: 3,
|
||||
AckWait: 30 * time.Minute,
|
||||
MaxDelivery: 3,
|
||||
DedupWindow: 2 * time.Hour,
|
||||
RetryBackoffDuration: 5 * time.Second,
|
||||
MaxRetries: 14,
|
||||
},
|
||||
@@ -71,6 +74,9 @@ func EnsureDefaults(cfg *config.Config) {
|
||||
}
|
||||
}
|
||||
|
||||
// Sanitize does nothing atm
|
||||
// Sanitize sanitizes the config
|
||||
func Sanitize(cfg *config.Config) {
|
||||
if cfg.Postprocessing.Workers < 1 {
|
||||
cfg.Postprocessing.Workers = 1
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/eventdedup"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/log"
|
||||
"github.com/owncloud/ocis/v2/services/postprocessing/pkg/config"
|
||||
"github.com/owncloud/ocis/v2/services/postprocessing/pkg/postprocessing"
|
||||
@@ -56,6 +57,12 @@ func NewPostprocessingService(ctx context.Context, stream events.Stream, logger
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if c.DedupWindow > 0 {
|
||||
evs = eventdedup.Filter(evs, eventdedup.NewSeen(c.DedupWindow), func(e events.Event) {
|
||||
logger.Info().Str("eventID", e.ID).Str("type", e.Type).Msg("dropping redelivered duplicate event")
|
||||
})
|
||||
}
|
||||
|
||||
return &PostprocessingService{
|
||||
ctx: ctx,
|
||||
log: logger,
|
||||
|
||||
@@ -4,8 +4,10 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os/signal"
|
||||
"time"
|
||||
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/config/configlog"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/natsconsumer"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/registry"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/runner"
|
||||
"github.com/owncloud/ocis/v2/ocis-pkg/tracing"
|
||||
@@ -17,6 +19,7 @@ import (
|
||||
"github.com/owncloud/ocis/v2/services/storage-users/pkg/revaconfig"
|
||||
"github.com/owncloud/ocis/v2/services/storage-users/pkg/server/debug"
|
||||
"github.com/owncloud/reva/v2/cmd/revad/runtime"
|
||||
revaevents "github.com/owncloud/reva/v2/pkg/events"
|
||||
"github.com/owncloud/reva/v2/pkg/rgrpc/todo/pool"
|
||||
"github.com/urfave/cli/v2"
|
||||
)
|
||||
@@ -95,6 +98,30 @@ func Server(cfg *config.Config) *cli.Command {
|
||||
return err
|
||||
}
|
||||
|
||||
// The decomposedfs consumer is created by reva once the storage
|
||||
// provider starts; Ensure retries until it exists.
|
||||
go func() {
|
||||
group := cfg.Events.ConsumerGroup
|
||||
if group == "" {
|
||||
group = "dcfs"
|
||||
}
|
||||
err := natsconsumer.Ensure(ctx, logger, natsconsumer.Connection{
|
||||
Endpoint: cfg.Events.Addr,
|
||||
Name: cfg.Service.Name + "-consumer-config",
|
||||
EnableTLS: cfg.Events.EnableTLS,
|
||||
TLSInsecure: cfg.Events.TLSInsecure,
|
||||
TLSRootCACertificate: cfg.Events.TLSRootCaCertPath,
|
||||
AuthUsername: cfg.Events.AuthUsername,
|
||||
AuthPassword: cfg.Events.AuthPassword,
|
||||
}, revaevents.MainQueueName, group, natsconsumer.Settings{
|
||||
AckWait: cfg.Events.AckWait,
|
||||
MaxDeliver: cfg.Events.MaxDelivery,
|
||||
}, 5*time.Second)
|
||||
if err != nil {
|
||||
logger.Error().Err(err).Str("consumer", group).Msg("could not apply NATS consumer settings")
|
||||
}
|
||||
}()
|
||||
|
||||
eventSVC, err := event.NewService(ctx, selector, stream, traceProvider, logger, *cfg)
|
||||
if err != nil {
|
||||
logger.Fatal().Err(err).Msg("can't create event handler")
|
||||
|
||||
@@ -211,43 +211,45 @@ type PosixDriver struct {
|
||||
|
||||
// Events combines the configuration options for the event bus.
|
||||
type Events struct {
|
||||
Addr string `yaml:"endpoint" env:"OCIS_EVENTS_ENDPOINT;STORAGE_USERS_EVENTS_ENDPOINT" desc:"The address of the event system. The event system is the message queuing service. It is used as message broker for the microservice architecture." introductionVersion:"pre5.0"`
|
||||
ClusterID string `yaml:"cluster" env:"OCIS_EVENTS_CLUSTER;STORAGE_USERS_EVENTS_CLUSTER" desc:"The clusterID of the event system. The event system is the message queuing service. It is used as message broker for the microservice architecture. Mandatory when using NATS as event system." introductionVersion:"pre5.0"`
|
||||
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_INSECURE;STORAGE_USERS_EVENTS_TLS_INSECURE" desc:"Whether to verify the server TLS certificates." introductionVersion:"pre5.0"`
|
||||
TLSRootCaCertPath string `yaml:"tls_root_ca_cert_path" env:"OCIS_EVENTS_TLS_ROOT_CA_CERTIFICATE;STORAGE_USERS_EVENTS_TLS_ROOT_CA_CERTIFICATE" desc:"The root CA certificate used to validate the server's TLS certificate. If provided STORAGE_USERS_EVENTS_TLS_INSECURE will be seen as false." introductionVersion:"pre5.0"`
|
||||
EnableTLS bool `yaml:"enable_tls" env:"OCIS_EVENTS_ENABLE_TLS;STORAGE_USERS_EVENTS_ENABLE_TLS" desc:"Enable TLS for the connection to the events broker. The events broker is the ocis service which receives and delivers events between the services." introductionVersion:"pre5.0"`
|
||||
NumConsumers int `yaml:"num_consumers" env:"STORAGE_USERS_EVENTS_NUM_CONSUMERS" desc:"The amount of concurrent event consumers to start. Event consumers are used for post-processing files. Multiple consumers increase parallelisation, but will also increase CPU and memory demands. The setting has no effect when the OCIS_ASYNC_UPLOADS is set to false. The default and minimum value is 1." introductionVersion:"pre5.0"`
|
||||
ConsumerGroup string `yaml:"consumer_group" env:"STORAGE_USERS_EVENTS_CONSUMER_GROUP" desc:"The name of the consumer group to be used at the event to help consumers identify the unique group." introductionVersion:"8.1.0"`
|
||||
AuthUsername string `yaml:"username" env:"OCIS_EVENTS_AUTH_USERNAME;STORAGE_USERS_EVENTS_AUTH_USERNAME" desc:"The username to authenticate with the events broker. The events broker is the ocis service which receives and delivers events between the services." introductionVersion:"5.0"`
|
||||
AuthPassword string `yaml:"password" env:"OCIS_EVENTS_AUTH_PASSWORD;STORAGE_USERS_EVENTS_AUTH_PASSWORD" desc:"The password to authenticate with the events broker. The events broker is the ocis service which receives and delivers events between the services." introductionVersion:"5.0"`
|
||||
Addr string `yaml:"endpoint" env:"OCIS_EVENTS_ENDPOINT;STORAGE_USERS_EVENTS_ENDPOINT" desc:"The address of the event system. The event system is the message queuing service. It is used as message broker for the microservice architecture." introductionVersion:"pre5.0"`
|
||||
ClusterID string `yaml:"cluster" env:"OCIS_EVENTS_CLUSTER;STORAGE_USERS_EVENTS_CLUSTER" desc:"The clusterID of the event system. The event system is the message queuing service. It is used as message broker for the microservice architecture. Mandatory when using NATS as event system." introductionVersion:"pre5.0"`
|
||||
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_INSECURE;STORAGE_USERS_EVENTS_TLS_INSECURE" desc:"Whether to verify the server TLS certificates." introductionVersion:"pre5.0"`
|
||||
TLSRootCaCertPath string `yaml:"tls_root_ca_cert_path" env:"OCIS_EVENTS_TLS_ROOT_CA_CERTIFICATE;STORAGE_USERS_EVENTS_TLS_ROOT_CA_CERTIFICATE" desc:"The root CA certificate used to validate the server's TLS certificate. If provided STORAGE_USERS_EVENTS_TLS_INSECURE will be seen as false." introductionVersion:"pre5.0"`
|
||||
EnableTLS bool `yaml:"enable_tls" env:"OCIS_EVENTS_ENABLE_TLS;STORAGE_USERS_EVENTS_ENABLE_TLS" desc:"Enable TLS for the connection to the events broker. The events broker is the ocis service which receives and delivers events between the services." introductionVersion:"pre5.0"`
|
||||
NumConsumers int `yaml:"num_consumers" env:"STORAGE_USERS_EVENTS_NUM_CONSUMERS" desc:"The amount of concurrent event consumers to start. Event consumers are used for post-processing files. Multiple consumers increase parallelisation, but will also increase CPU and memory demands. The setting has no effect when the OCIS_ASYNC_UPLOADS is set to false. The default and minimum value is 1." introductionVersion:"pre5.0"`
|
||||
ConsumerGroup string `yaml:"consumer_group" env:"STORAGE_USERS_EVENTS_CONSUMER_GROUP" desc:"The name of the consumer group to be used at the event to help consumers identify the unique group." introductionVersion:"8.1.0"`
|
||||
AckWait time.Duration `yaml:"ack_wait" env:"STORAGE_USERS_EVENTS_ACK_WAIT" desc:"How long the NATS JetStream server waits for an acknowledgement before it redelivers an event to the storage postprocessing consumer (the one finalizing uploads into the blobstore). Written to the durable consumer on the server at startup. Set to 0 to keep the current server value. See the Environment Variable Types description for more details." introductionVersion:"8.3.0"`
|
||||
MaxDelivery int `yaml:"max_delivery" env:"STORAGE_USERS_EVENTS_MAX_DELIVERY" desc:"Maximum number of delivery attempts of an event to the storage postprocessing consumer. -1 means unlimited, 0 keeps the current server value." introductionVersion:"8.3.0"`
|
||||
AuthUsername string `yaml:"username" env:"OCIS_EVENTS_AUTH_USERNAME;STORAGE_USERS_EVENTS_AUTH_USERNAME" desc:"The username to authenticate with the events broker. The events broker is the ocis service which receives and delivers events between the services." introductionVersion:"5.0"`
|
||||
AuthPassword string `yaml:"password" env:"OCIS_EVENTS_AUTH_PASSWORD;STORAGE_USERS_EVENTS_AUTH_PASSWORD" desc:"The password to authenticate with the events broker. The events broker is the ocis service which receives and delivers events between the services." introductionVersion:"5.0"`
|
||||
}
|
||||
|
||||
// FilemetadataCache holds cache config
|
||||
type FilemetadataCache struct {
|
||||
Store string `yaml:"store" env:"OCIS_CACHE_STORE;STORAGE_USERS_FILEMETADATA_CACHE_STORE" desc:"The type of the cache store. Supported values are: 'memory', 'redis-sentinel', 'nats-js-kv', 'noop'. See the text description for details." introductionVersion:"pre5.0"`
|
||||
Nodes []string `yaml:"nodes" env:"OCIS_CACHE_STORE_NODES;STORAGE_USERS_FILEMETADATA_CACHE_STORE_NODES" desc:"A list of nodes to access the configured store. This has no effect when 'memory' store is configured. Note that the behaviour how nodes are used is dependent on the library of the configured store. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
Database string `yaml:"database" env:"OCIS_CACHE_DATABASE" desc:"The database name the configured store should use." introductionVersion:"pre5.0"`
|
||||
TTL time.Duration `yaml:"ttl" env:"OCIS_CACHE_TTL;STORAGE_USERS_FILEMETADATA_CACHE_TTL" desc:"Default time to live for user info in the user info cache. Only applied when access tokens has no expiration. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
DisablePersistence bool `yaml:"disable_persistence" env:"OCIS_CACHE_DISABLE_PERSISTENCE;STORAGE_USERS_FILEMETADATA_CACHE_DISABLE_PERSISTENCE" desc:"Disables persistence of the cache. Only applies when store type 'nats-js-kv' is configured. Defaults to false." introductionVersion:"5.0"`
|
||||
AuthUsername string `yaml:"username" env:"OCIS_CACHE_AUTH_USERNAME;STORAGE_USERS_FILEMETADATA_CACHE_AUTH_USERNAME" desc:"The username to authenticate with the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
AuthPassword string `yaml:"password" env:"OCIS_CACHE_AUTH_PASSWORD;STORAGE_USERS_FILEMETADATA_CACHE_AUTH_PASSWORD" desc:"The password to authenticate with the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;STORAGE_USERS_FILEMETADATA_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
|
||||
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;STORAGE_USERS_FILEMETADATA_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
|
||||
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;STORAGE_USERS_FILEMETADATA_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
|
||||
Store string `yaml:"store" env:"OCIS_CACHE_STORE;STORAGE_USERS_FILEMETADATA_CACHE_STORE" desc:"The type of the cache store. Supported values are: 'memory', 'redis-sentinel', 'nats-js-kv', 'noop'. See the text description for details." introductionVersion:"pre5.0"`
|
||||
Nodes []string `yaml:"nodes" env:"OCIS_CACHE_STORE_NODES;STORAGE_USERS_FILEMETADATA_CACHE_STORE_NODES" desc:"A list of nodes to access the configured store. This has no effect when 'memory' store is configured. Note that the behaviour how nodes are used is dependent on the library of the configured store. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
Database string `yaml:"database" env:"OCIS_CACHE_DATABASE" desc:"The database name the configured store should use." introductionVersion:"pre5.0"`
|
||||
TTL time.Duration `yaml:"ttl" env:"OCIS_CACHE_TTL;STORAGE_USERS_FILEMETADATA_CACHE_TTL" desc:"Default time to live for user info in the user info cache. Only applied when access tokens has no expiration. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
DisablePersistence bool `yaml:"disable_persistence" env:"OCIS_CACHE_DISABLE_PERSISTENCE;STORAGE_USERS_FILEMETADATA_CACHE_DISABLE_PERSISTENCE" desc:"Disables persistence of the cache. Only applies when store type 'nats-js-kv' is configured. Defaults to false." introductionVersion:"5.0"`
|
||||
AuthUsername string `yaml:"username" env:"OCIS_CACHE_AUTH_USERNAME;STORAGE_USERS_FILEMETADATA_CACHE_AUTH_USERNAME" desc:"The username to authenticate with the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
AuthPassword string `yaml:"password" env:"OCIS_CACHE_AUTH_PASSWORD;STORAGE_USERS_FILEMETADATA_CACHE_AUTH_PASSWORD" desc:"The password to authenticate with the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;STORAGE_USERS_FILEMETADATA_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
|
||||
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;STORAGE_USERS_FILEMETADATA_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
|
||||
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;STORAGE_USERS_FILEMETADATA_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
|
||||
}
|
||||
|
||||
// IDCache holds cache config
|
||||
type IDCache struct {
|
||||
Store string `yaml:"store" env:"OCIS_CACHE_STORE;STORAGE_USERS_ID_CACHE_STORE" desc:"The type of the cache store. Supported values are: 'memory', 'redis-sentinel', 'nats-js-kv', 'noop'. See the text description for details." introductionVersion:"pre5.0"`
|
||||
Nodes []string `yaml:"nodes" env:"OCIS_CACHE_STORE_NODES;STORAGE_USERS_ID_CACHE_STORE_NODES" desc:"A list of nodes to access the configured store. This has no effect when 'memory' store is configured. Note that the behaviour how nodes are used is dependent on the library of the configured store. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
Database string `yaml:"database" env:"OCIS_CACHE_DATABASE" desc:"The database name the configured store should use." introductionVersion:"pre5.0"`
|
||||
TTL time.Duration `yaml:"ttl" env:"OCIS_CACHE_TTL;STORAGE_USERS_ID_CACHE_TTL" desc:"Default time to live for user info in the user info cache. Only applied when access tokens have no expiration. Defaults to 300s which is derived from the underlaying package though not explicitly set as default. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
DisablePersistence bool `yaml:"disable_persistence" env:"OCIS_CACHE_DISABLE_PERSISTENCE;STORAGE_USERS_ID_CACHE_DISABLE_PERSISTENCE" desc:"Disables persistence of the cache. Only applies when store type 'nats-js-kv' is configured. Defaults to false." introductionVersion:"5.0"`
|
||||
AuthUsername string `yaml:"username" env:"OCIS_CACHE_AUTH_USERNAME;STORAGE_USERS_ID_CACHE_AUTH_USERNAME" desc:"The username to authenticate with the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
AuthPassword string `yaml:"password" env:"OCIS_CACHE_AUTH_PASSWORD;STORAGE_USERS_ID_CACHE_AUTH_PASSWORD" desc:"The password to authenticate with the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;STORAGE_USERS_ID_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
|
||||
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;STORAGE_USERS_ID_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
|
||||
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;STORAGE_USERS_ID_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
|
||||
Store string `yaml:"store" env:"OCIS_CACHE_STORE;STORAGE_USERS_ID_CACHE_STORE" desc:"The type of the cache store. Supported values are: 'memory', 'redis-sentinel', 'nats-js-kv', 'noop'. See the text description for details." introductionVersion:"pre5.0"`
|
||||
Nodes []string `yaml:"nodes" env:"OCIS_CACHE_STORE_NODES;STORAGE_USERS_ID_CACHE_STORE_NODES" desc:"A list of nodes to access the configured store. This has no effect when 'memory' store is configured. Note that the behaviour how nodes are used is dependent on the library of the configured store. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
Database string `yaml:"database" env:"OCIS_CACHE_DATABASE" desc:"The database name the configured store should use." introductionVersion:"pre5.0"`
|
||||
TTL time.Duration `yaml:"ttl" env:"OCIS_CACHE_TTL;STORAGE_USERS_ID_CACHE_TTL" desc:"Default time to live for user info in the user info cache. Only applied when access tokens have no expiration. Defaults to 300s which is derived from the underlaying package though not explicitly set as default. See the Environment Variable Types description for more details." introductionVersion:"pre5.0"`
|
||||
DisablePersistence bool `yaml:"disable_persistence" env:"OCIS_CACHE_DISABLE_PERSISTENCE;STORAGE_USERS_ID_CACHE_DISABLE_PERSISTENCE" desc:"Disables persistence of the cache. Only applies when store type 'nats-js-kv' is configured. Defaults to false." introductionVersion:"5.0"`
|
||||
AuthUsername string `yaml:"username" env:"OCIS_CACHE_AUTH_USERNAME;STORAGE_USERS_ID_CACHE_AUTH_USERNAME" desc:"The username to authenticate with the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
AuthPassword string `yaml:"password" env:"OCIS_CACHE_AUTH_PASSWORD;STORAGE_USERS_ID_CACHE_AUTH_PASSWORD" desc:"The password to authenticate with the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"5.0"`
|
||||
EnableTLS bool `yaml:"enable_tls" env:"OCIS_CACHE_ENABLE_TLS;STORAGE_USERS_ID_CACHE_ENABLE_TLS" desc:"Activate TLS for the connection to the cache store. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
|
||||
TLSInsecure bool `yaml:"tls_insecure" env:"OCIS_CACHE_TLS_INSECURE;STORAGE_USERS_ID_CACHE_TLS_INSECURE" desc:"Disable TLS certificate verification for the cache store connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
|
||||
TLSRootCACertificate string `yaml:"tls_root_ca_certificate" env:"OCIS_CACHE_TLS_ROOT_CA_CERTIFICATE;STORAGE_USERS_ID_CACHE_TLS_ROOT_CA_CERTIFICATE" desc:"Path to the PEM-encoded root CA certificate for the cache store TLS connection. Only applies when store type 'nats-js-kv' is configured." introductionVersion:"8.3.0"`
|
||||
}
|
||||
|
||||
// S3Driver is the storage driver configuration when using 's3' storage driver
|
||||
|
||||
@@ -151,9 +151,12 @@ func DefaultConfig() *config.Config {
|
||||
},
|
||||
},
|
||||
Events: config.Events{
|
||||
Addr: "127.0.0.1:9233",
|
||||
ClusterID: "ocis-cluster",
|
||||
EnableTLS: false,
|
||||
Addr: "127.0.0.1:9233",
|
||||
ClusterID: "ocis-cluster",
|
||||
EnableTLS: false,
|
||||
NumConsumers: 4,
|
||||
AckWait: 30 * time.Minute,
|
||||
MaxDelivery: 3,
|
||||
},
|
||||
FilemetadataCache: config.FilemetadataCache{
|
||||
Store: "memory",
|
||||
|
||||
@@ -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'
|
||||
|
||||
+175
@@ -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' }] : []
|
||||
})
|
||||
]
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user