package clientapi_test import ( "net/http" "strings" "testing" "github.com/dariuszjaniak/warp/server/internal/clientapi" "github.com/dariuszjaniak/warp/server/internal/config" ) const registerPath = "/_matrix/client/v3/register" // TestRegisterReturnsFlows covers the first half of the registration // handshake: an empty body gets the flows and a session, not a complaint // about the missing password. func TestRegisterReturnsFlows(t *testing.T) { ts := newTestServer(t, nil) rec := ts.do(request{method: http.MethodPost, path: registerPath, body: map[string]any{}}) expectStatus(t, rec, http.StatusUnauthorized) if ct := rec.Header().Get("Content-Type"); ct != "application/json" { t.Errorf("Content-Type = %q, want application/json", ct) } body := jsonBody(t, rec) if _, ok := body["session"].(string); !ok { t.Error("the challenge must carry a session") } if _, ok := body["params"].(map[string]any); !ok { t.Error("the challenge must carry a params object, even an empty one") } flows, ok := body["flows"].([]any) if !ok || len(flows) == 0 { t.Fatalf("flows = %v, want a non-empty array", body["flows"]) } for _, flow := range flows { stages, ok := flow.(map[string]any)["stages"].([]any) if !ok || len(stages) == 0 { t.Fatalf("every flow needs a non-empty stages array, got %v", flow) } if stages[0] != "m.login.dummy" { t.Errorf("first stage = %v, want m.login.dummy", stages[0]) } } } func TestRegisterCreatesAccount(t *testing.T) { ts := newTestServer(t, nil) acc := ts.register("alice", "sUp3rs3kr1t") if acc.UserID != "@alice:warp.example" { t.Errorf("user_id = %q, want @alice:warp.example", acc.UserID) } // The token works straight away: a registration that needs a separate // login is a registration that half worked. rec := ts.get("/_matrix/client/v3/account/whoami", acc.AccessToken) expectStatus(t, rec, http.StatusOK) if got := jsonBody(t, rec)["user_id"]; got != acc.UserID { t.Errorf("whoami = %v, want %s", got, acc.UserID) } } // TestRegisterDowncasesUsername pins the behaviour clients rely on: a // localpart is lowercase, so a capital in the request is normalised rather // than rejected. func TestRegisterDowncasesUsername(t *testing.T) { ts := newTestServer(t, nil) acc := ts.register("user-UPPER", "sUp3rs3kr1t") if acc.UserID != "@user-upper:warp.example" { t.Errorf("user_id = %q, want @user-upper:warp.example", acc.UserID) } } func TestRegisterHonoursRequestedDeviceID(t *testing.T) { ts := newTestServer(t, nil) rec := ts.do(request{method: http.MethodPost, path: registerPath, body: map[string]any{"username": "alice", "password": "sUp3rs3kr1t"}}) session := jsonBody(t, rec)["session"] rec = ts.do(request{method: http.MethodPost, path: registerPath, body: map[string]any{ "username": "alice", "password": "sUp3rs3kr1t", "device_id": "my_device_id", "initial_device_display_name": "a phone", "auth": map[string]any{"type": "m.login.dummy", "session": session}, }}) expectStatus(t, rec, http.StatusOK) if got := jsonBody(t, rec)["device_id"]; got != "my_device_id" { t.Errorf("device_id = %v, want my_device_id", got) } } // TestRegisterRejectsBadUsernamesBeforeUIA is the half of the ordering that // is easy to get wrong: a username that can never work is rejected with a // 400 straight away, rather than after the client has completed a flow. func TestRegisterRejectsBadUsernamesBeforeUIA(t *testing.T) { ts := newTestServer(t, nil) for _, ch := range []string{"!", `"`, ":", "?", `\`, "@", "[", "]", "{", "|", "}", "£", "é", "\n", "'", ","} { rec := ts.do(request{method: http.MethodPost, path: registerPath, body: map[string]any{"username": "user-" + ch + "-reject", "password": "sUp3rs3kr1t"}}) expectError(t, rec, http.StatusBadRequest, "M_INVALID_USERNAME") } // The characters the spec does allow must still get through. for _, ch := range []string{"q", "3", ".", "_", "=", "-", "/", "+"} { ts.register("chrtest"+ch, "sUp3rs3kr1t") } } func TestRegisterRejectsOverlongUsername(t *testing.T) { ts := newTestServer(t, nil) rec := ts.do(request{method: http.MethodPost, path: registerPath, body: map[string]any{ "username": strings.Repeat("a", 256), "password": "sUp3rs3kr1t", }}) expectError(t, rec, http.StatusBadRequest, "M_INVALID_USERNAME") } // TestRegisterRejectsTakenUsernameBeforeUIA is the other half: the name is // checked before the challenge, so a client is not asked to authenticate // only to be told the name was gone all along. func TestRegisterRejectsTakenUsernameBeforeUIA(t *testing.T) { ts := newTestServer(t, nil) ts.register("alice", "sUp3rs3kr1t") rec := ts.do(request{method: http.MethodPost, path: registerPath, body: map[string]any{"username": "alice", "password": "sUp3rs3kr1t"}}) expectError(t, rec, http.StatusBadRequest, "M_USER_IN_USE") // Capitalisation does not get around it, because the name is // normalised first. rec = ts.do(request{method: http.MethodPost, path: registerPath, body: map[string]any{"username": "ALICE", "password": "sUp3rs3kr1t"}}) expectError(t, rec, http.StatusBadRequest, "M_USER_IN_USE") } // TestRegisterRequiresTheSession covers the rule that makes the flow a flow: // an `auth` without the session the server handed out starts again rather // than completing. func TestRegisterRequiresTheSession(t *testing.T) { ts := newTestServer(t, nil) rec := ts.do(request{method: http.MethodPost, path: registerPath, body: map[string]any{ "username": "alice", "password": "sUp3rs3kr1t", "auth": map[string]any{"type": "m.login.dummy"}, }}) expectStatus(t, rec, http.StatusUnauthorized) // An unknown session is treated the same way, with a fresh one offered. rec = ts.do(request{method: http.MethodPost, path: registerPath, body: map[string]any{ "username": "alice", "password": "sUp3rs3kr1t", "auth": map[string]any{"type": "m.login.dummy", "session": "not-a-session"}, }}) expectStatus(t, rec, http.StatusUnauthorized) if _, ok := jsonBody(t, rec)["session"].(string); !ok { t.Error("a rejected session must come with a new one to try") } } func TestRegisterRejectsUnknownStage(t *testing.T) { ts := newTestServer(t, nil) rec := ts.do(request{method: http.MethodPost, path: registerPath, body: map[string]any{"username": "alice", "password": "sUp3rs3kr1t"}}) session := jsonBody(t, rec)["session"] rec = ts.do(request{method: http.MethodPost, path: registerPath, body: map[string]any{ "username": "alice", "password": "sUp3rs3kr1t", "auth": map[string]any{"type": "m.login.recaptcha", "session": session}, }}) expectError(t, rec, http.StatusBadRequest, "M_UNRECOGNIZED") } func TestRegisterRequiresPasswordAfterUIA(t *testing.T) { ts := newTestServer(t, nil) rec := ts.do(request{method: http.MethodPost, path: registerPath, body: map[string]any{"username": "alice"}}) expectStatus(t, rec, http.StatusUnauthorized) session := jsonBody(t, rec)["session"] rec = ts.do(request{method: http.MethodPost, path: registerPath, body: map[string]any{ "username": "alice", "auth": map[string]any{"type": "m.login.dummy", "session": session}, }}) expectError(t, rec, http.StatusBadRequest, "M_MISSING_PARAM") } func TestRegisterInhibitLogin(t *testing.T) { ts := newTestServer(t, nil) rec := ts.do(request{method: http.MethodPost, path: registerPath, body: map[string]any{"username": "alice", "password": "sUp3rs3kr1t"}}) session := jsonBody(t, rec)["session"] rec = ts.do(request{method: http.MethodPost, path: registerPath, body: map[string]any{ "username": "alice", "password": "sUp3rs3kr1t", "inhibit_login": true, "auth": map[string]any{"type": "m.login.dummy", "session": session}, }}) expectStatus(t, rec, http.StatusOK) body := jsonBody(t, rec) if body["user_id"] != "@alice:warp.example" { t.Errorf("user_id = %v", body["user_id"]) } for _, field := range []string{"access_token", "device_id"} { if _, present := body[field]; present { t.Errorf("inhibit_login must suppress %s", field) } } } // TestRegisterGeneratesUsername covers the case where the client leaves the // choice of name to the server. func TestRegisterGeneratesUsername(t *testing.T) { ts := newTestServer(t, nil) rec := ts.do(request{method: http.MethodPost, path: registerPath, body: map[string]any{"password": "sUp3rs3kr1t"}}) session := jsonBody(t, rec)["session"] rec = ts.do(request{method: http.MethodPost, path: registerPath, body: map[string]any{ "password": "sUp3rs3kr1t", "auth": map[string]any{"type": "m.login.dummy", "session": session}, }}) expectStatus(t, rec, http.StatusOK) userID, _ := jsonBody(t, rec)["user_id"].(string) if !strings.HasPrefix(userID, "@") || !strings.HasSuffix(userID, ":warp.example") { t.Errorf("generated user_id = %q, want @:warp.example", userID) } if len(userID) <= len("@:warp.example") { t.Errorf("generated user_id %q has an empty localpart", userID) } } func TestRegisterSessionIsSpentOnce(t *testing.T) { ts := newTestServer(t, nil) rec := ts.do(request{method: http.MethodPost, path: registerPath, body: map[string]any{"username": "alice", "password": "sUp3rs3kr1t"}}) session := jsonBody(t, rec)["session"] complete := map[string]any{ "username": "alice", "password": "sUp3rs3kr1t", "auth": map[string]any{"type": "m.login.dummy", "session": session}, } expectStatus(t, ts.do(request{method: http.MethodPost, path: registerPath, body: complete}), http.StatusOK) // Replaying the identical request must not create a second account; the // name is taken now, and the session is gone either way. rec = ts.do(request{method: http.MethodPost, path: registerPath, body: complete}) expectError(t, rec, http.StatusBadRequest, "M_USER_IN_USE") } func TestRegisterRespectsTheRegistrationSwitch(t *testing.T) { ts := newTestServer(t, nil) if err := ts.settings.SetRegistrationEnabled(t.Context(), false); err != nil { t.Fatalf("SetRegistrationEnabled: %v", err) } rec := ts.do(request{method: http.MethodPost, path: registerPath, body: map[string]any{"username": "alice", "password": "sUp3rs3kr1t"}}) expectError(t, rec, http.StatusForbidden, "M_FORBIDDEN") // And comes back without a restart, which is the point of the switch. if err := ts.settings.SetRegistrationEnabled(t.Context(), true); err != nil { t.Fatalf("SetRegistrationEnabled: %v", err) } ts.register("alice", "sUp3rs3kr1t") } func TestRegisterRejectsGuests(t *testing.T) { ts := newTestServer(t, nil) rec := ts.do(request{method: http.MethodPost, path: registerPath + "?kind=guest", body: map[string]any{}}) expectError(t, rec, http.StatusForbidden, "M_FORBIDDEN") } // TestRegisterWithRegistrationToken covers the second stage a server with // invite-only sign-up adds to the flow. func TestRegisterWithRegistrationToken(t *testing.T) { ts := newTestServer(t, func(o *clientapi.Options) { o.Registration = config.Registration{Enabled: true, Tokens: []string{"let-me-in"}} }) rec := ts.do(request{method: http.MethodPost, path: registerPath, body: map[string]any{"username": "alice", "password": "sUp3rs3kr1t"}}) expectStatus(t, rec, http.StatusUnauthorized) body := jsonBody(t, rec) flows, _ := body["flows"].([]any) stages, _ := flows[0].(map[string]any)["stages"].([]any) if len(stages) != 2 || stages[0] != "m.login.registration_token" { t.Fatalf("stages = %v, want the token stage first", stages) } session := body["session"] // A wrong token fails the stage: the client gets the error and the // flows together, so it can prompt again without starting over. rec = ts.do(request{method: http.MethodPost, path: registerPath, body: map[string]any{ "username": "alice", "password": "sUp3rs3kr1t", "auth": map[string]any{ "type": "m.login.registration_token", "session": session, "token": "nope", }, }}) expectStatus(t, rec, http.StatusUnauthorized) body = jsonBody(t, rec) if body["errcode"] != "M_FORBIDDEN" { t.Errorf("a failed stage must say why, got %s", rec.Body.String()) } if body["session"] != session { t.Error("a failed stage must keep the session alive") } // The right one advances the flow but does not finish it. rec = ts.do(request{method: http.MethodPost, path: registerPath, body: map[string]any{ "username": "alice", "password": "sUp3rs3kr1t", "auth": map[string]any{ "type": "m.login.registration_token", "session": session, "token": "let-me-in", }, }}) expectStatus(t, rec, http.StatusUnauthorized) completed, _ := jsonBody(t, rec)["completed"].([]any) if len(completed) != 1 || completed[0] != "m.login.registration_token" { t.Fatalf("completed = %v, want the token stage", completed) } // And the dummy stage completes it. rec = ts.do(request{method: http.MethodPost, path: registerPath, body: map[string]any{ "username": "alice", "password": "sUp3rs3kr1t", "auth": map[string]any{"type": "m.login.dummy", "session": session}, }}) expectStatus(t, rec, http.StatusOK) if jsonBody(t, rec)["user_id"] != "@alice:warp.example" { t.Errorf("user_id = %v", jsonBody(t, rec)["user_id"]) } } func TestRegisterAvailable(t *testing.T) { ts := newTestServer(t, nil) const path = "/_matrix/client/v3/register/available" rec := ts.get(path+"?username=free_name", "") expectStatus(t, rec, http.StatusOK) if jsonBody(t, rec)["available"] != true { t.Errorf("available = %v, want true", jsonBody(t, rec)["available"]) } ts.register("taken", "sUp3rs3kr1t") expectError(t, ts.get(path+"?username=taken", ""), http.StatusBadRequest, "M_USER_IN_USE") expectError(t, ts.get(path+"?username=not,valid", ""), http.StatusBadRequest, "M_INVALID_USERNAME") expectError(t, ts.get(path, ""), http.StatusBadRequest, "M_MISSING_PARAM") } func TestRegistrationTokenValidity(t *testing.T) { ts := newTestServer(t, func(o *clientapi.Options) { o.Registration = config.Registration{Enabled: true, Tokens: []string{"let-me-in"}} }) const path = "/_matrix/client/v1/register/m.login.registration_token/validity" rec := ts.get(path+"?token=let-me-in", "") expectStatus(t, rec, http.StatusOK) if jsonBody(t, rec)["valid"] != true { t.Errorf("valid = %v, want true", jsonBody(t, rec)["valid"]) } rec = ts.get(path+"?token=nope", "") expectStatus(t, rec, http.StatusOK) if jsonBody(t, rec)["valid"] != false { t.Errorf("valid = %v, want false", jsonBody(t, rec)["valid"]) } expectError(t, ts.get(path, ""), http.StatusBadRequest, "M_MISSING_PARAM") }