feat(idp): 経路チェック付きの Web セルフ登録を追加
- GET/POST /oauth2/discord/register で登録フォームを表示・受け付ける - Web 登録が無効、または登録受付が OFF のときは registration_closed で拒否 - Origin/Referer が公開 URL と違う POST を拒否する - ユーザー名・メール・パスワードを検証し、重複やパスワードポリシー違反はフォームに表示 - 承認制が有効なら accountEnabled=false で作成し、登録元 web として承認待ちに記録 - 段階③で抜けていた Accounts の組み立てを追加 (本番で NewHandler が失敗していた)
This commit is contained in:
1 parent
0b0d460eac
commit
f8d3daf7ff
9 files changed
+695
-12
No files matched your search
@@ -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>
|
||||
@@ -118,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 {
|
||||
@@ -126,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)
|
||||
}
|
||||
|
||||
@@ -90,6 +90,8 @@ 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.
|
||||
@@ -98,6 +100,7 @@ type Options struct {
|
||||
Registration *RegistrationStore
|
||||
Pending *PendingStore
|
||||
Accounts Accounts
|
||||
WebAccounts WebAccounts
|
||||
API API
|
||||
Provisioner Provisioner
|
||||
Sessions SessionIssuer
|
||||
@@ -127,7 +130,7 @@ type Handler struct {
|
||||
// NewHandler returns a Handler.
|
||||
func NewHandler(opt Options) (*Handler, error) {
|
||||
switch {
|
||||
case opt.Store == nil, opt.Registration == nil, opt.Pending == nil, opt.Accounts == 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")
|
||||
@@ -167,6 +170,8 @@ func (h *Handler) Mount(r chi.Router) {
|
||||
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)
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -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) {
|
||||
@@ -118,6 +124,7 @@ type harness struct {
|
||||
reg *RegistrationStore
|
||||
pending *PendingStore
|
||||
accounts *fakeAccounts
|
||||
web *fakeWeb
|
||||
render *fakeRenderer
|
||||
prov *fakeProvisioner
|
||||
sess *fakeSessions
|
||||
@@ -163,12 +170,14 @@ func newHarness(t *testing.T) *harness {
|
||||
}
|
||||
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,
|
||||
|
||||
@@ -228,6 +228,51 @@ 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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -102,6 +102,8 @@ func newDiscordHandler(idp *IDP, options Options, mgrs *managers.Managers, autho
|
||||
Store: store,
|
||||
Registration: registration,
|
||||
Pending: pending,
|
||||
Accounts: prov,
|
||||
WebAccounts: prov,
|
||||
API: discord.NewClient(),
|
||||
Provisioner: prov,
|
||||
Sessions: discord.LicoSessionIssuer{Identifier: ident, SubAttribute: cfg.Ldap.UUIDAttribute},
|
||||
@@ -203,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"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -340,6 +344,22 @@ var discordMessages = map[string][2]string{ // {en, ja}
|
||||
"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)
|
||||
}
|
||||
Reference in new issue
Block a user