Phase 1: accounts and sessions
CI / Test (ubuntu-latest) (push) Canceled after 0s
CI / Test (windows-latest) (push) Canceled after 0s
CI / Storage tests on PostgreSQL (push) Canceled after 0s
CI / Complement (federation off) (push) Canceled after 0s
CI / golangci-lint (push) Canceled after 0s
CI / Smoke test the binary (push) Canceled after 0s
CI / Test (ubuntu-latest) (push) Canceled after 0s
CI / Test (windows-latest) (push) Canceled after 0s
CI / Storage tests on PostgreSQL (push) Canceled after 0s
CI / Complement (federation off) (push) Canceled after 0s
CI / golangci-lint (push) Canceled after 0s
CI / Smoke test the binary (push) Canceled after 0s
Implements PLAN.md Phase 1. A client can now register, log in, manage its devices and set its profile; an operator can create accounts and flip the runtime switches. There are still no rooms and no real /sync. userapi: accounts, argon2id passwords in PHC format, devices, access and refresh tokens stored as SHA-256 hashes, account data and the admin flag. Its storage interface is storage.UserStore, implemented once in sqlstore with `?` placeholders; the postgres driver supplies a rebind function and unique-violation recognition rather than keeping a second copy of thirty statements. Timestamps in these tables are int64 milliseconds, the unit the Client-Server API uses on the wire. Client-Server API: register (user-interactive auth with m.login.dummy and optional registration tokens), register/available, token validity, login with m.login.password, logout, logout/all, refresh, account/whoami, capabilities, devices/* with password-gated deletion, profile/*, global and per-room account data. GET /sync is a deliberate placeholder: it answers a valid token with an empty but well-formed response and refuses a revoked one. Phase 1 has no rooms, so that is the whole truth, and it is what makes session revocation observable. Phase 4 replaces it with the syncapi. Auth middleware resolves a bearer token (header or the legacy query parameter) to a device and user, answering an expired token with the soft logout the spec asks for. Rate limiting is a token bucket per endpoint class keyed on the client address, returning M_LIMIT_EXCEEDED with retry_after_ms. adminapi v1 under /_warp/admin/v1: admin-only auth via a normal Matrix token, GET/PUT /federation and /registration driving internal/settings and reporting a config-pinned switch as a 409, GET/POST /users, GET /stats. warp create-account [--admin] creates the first account straight in the database, so a new install with registration off has a way in. Complement is wired up for the federation=off profile: an image meeting its contract, an entrypoint that configures Warp entirely from WARP_* variables, and a runner that builds, clones and executes the target set (TestRegistration, TestLogin, TestDeviceManagement). It has not been run yet -- there is no container runtime on the development machine -- so the three tests' assertions were read from the Complement sources and pinned as httptest tests instead, and CI gained a job that runs the real thing. Also fixes a .gitignore bug from Phase 0: the unanchored `warp` pattern, meant for the built binary, also matched the directory server/cmd/warp and silently excluded the entire command package from the repository. The binary patterns are now anchored to the repository root, and cmd/warp is committed for the first time. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b4fb60a8ab
commit
6004bb01de
68 files changed
+9729
-66
No files matched your search
@@ -0,0 +1,316 @@
|
||||
// Package adminapi serves /_warp/admin/v1: the API behind the admin panel.
|
||||
//
|
||||
// It is deliberately not part of the Matrix spec. Everything a client needs
|
||||
// goes through the Client-Server API; this is the operator's surface, and
|
||||
// the only thing in Warp that is ours rather than Matrix's.
|
||||
//
|
||||
// Authentication is a normal Matrix access token belonging to an account
|
||||
// with the admin flag, so the panel logs in the way any client does and
|
||||
// there is no second credential to manage.
|
||||
//
|
||||
// Phase 1 is the skeleton PLAN.md section 7 asks for: the two runtime
|
||||
// switches, user listing and creation, and the dashboard counters. Full user
|
||||
// management, registration tokens, the federation allow/deny list editor and
|
||||
// the audit log arrive in Phase 9.
|
||||
package adminapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/dariuszjaniak/warp/server/internal/buildinfo"
|
||||
"github.com/dariuszjaniak/warp/server/internal/federation"
|
||||
"github.com/dariuszjaniak/warp/server/internal/httputil"
|
||||
"github.com/dariuszjaniak/warp/server/internal/settings"
|
||||
"github.com/dariuszjaniak/warp/server/internal/storage"
|
||||
"github.com/dariuszjaniak/warp/server/internal/userapi"
|
||||
)
|
||||
|
||||
// Prefix is the path every admin endpoint lives under.
|
||||
const Prefix = "/_warp/admin/v1"
|
||||
|
||||
// AdminAPI serves the admin endpoints.
|
||||
type AdminAPI struct {
|
||||
serverName string
|
||||
users *userapi.API
|
||||
settings *settings.Service
|
||||
federation *federation.Gate
|
||||
database storage.Database
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
// Options configure the component.
|
||||
type Options struct {
|
||||
ServerName string
|
||||
Users *userapi.API
|
||||
Settings *settings.Service
|
||||
Federation *federation.Gate
|
||||
|
||||
// Database is used for the driver name the dashboard shows and for the
|
||||
// migration state; the admin API does not write to it directly.
|
||||
Database storage.Database
|
||||
|
||||
Logger *slog.Logger
|
||||
}
|
||||
|
||||
// New builds the component.
|
||||
func New(opts Options) (*AdminAPI, error) {
|
||||
switch {
|
||||
case opts.ServerName == "":
|
||||
return nil, errors.New("adminapi: ServerName must not be empty")
|
||||
case opts.Users == nil:
|
||||
return nil, errors.New("adminapi: Users must not be nil")
|
||||
case opts.Settings == nil:
|
||||
return nil, errors.New("adminapi: Settings must not be nil")
|
||||
}
|
||||
if opts.Federation == nil {
|
||||
opts.Federation = federation.NewGate(nil, nil)
|
||||
}
|
||||
if opts.Logger == nil {
|
||||
opts.Logger = slog.Default()
|
||||
}
|
||||
return &AdminAPI{
|
||||
serverName: opts.ServerName,
|
||||
users: opts.Users,
|
||||
settings: opts.Settings,
|
||||
federation: opts.Federation,
|
||||
database: opts.Database,
|
||||
log: opts.Logger,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// RegisterRoutes adds the admin endpoints to the router.
|
||||
func (a *AdminAPI) RegisterRoutes(r *httputil.Router) {
|
||||
a.handle(r, "GET "+Prefix+"/federation", a.handleGetFederation)
|
||||
a.handle(r, "PUT "+Prefix+"/federation", a.handlePutFederation)
|
||||
a.handle(r, "GET "+Prefix+"/registration", a.handleGetRegistration)
|
||||
a.handle(r, "PUT "+Prefix+"/registration", a.handlePutRegistration)
|
||||
a.handle(r, "GET "+Prefix+"/users", a.handleGetUsers)
|
||||
a.handle(r, "POST "+Prefix+"/users", a.handlePostUsers)
|
||||
a.handle(r, "GET "+Prefix+"/stats", a.handleGetStats)
|
||||
}
|
||||
|
||||
// adminHandler is a handler that has already been shown to be an admin.
|
||||
type adminHandler func(w http.ResponseWriter, r *http.Request, auth userapi.Authenticated) error
|
||||
|
||||
// handle registers an admin-only endpoint.
|
||||
//
|
||||
// Admin endpoints are not rate limited. They are reachable only with an
|
||||
// admin token, and an operator bulk-loading users through the panel is
|
||||
// exactly the traffic a limiter would get in the way of.
|
||||
func (a *AdminAPI) handle(r *httputil.Router, pattern string, h adminHandler) {
|
||||
r.HandleFunc(pattern, func(w http.ResponseWriter, req *http.Request) error {
|
||||
auth, err := a.requireAdmin(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return h(w, req, auth)
|
||||
})
|
||||
}
|
||||
|
||||
// requireAdmin resolves the access token and insists on the admin flag.
|
||||
//
|
||||
// A non-admin token gets M_FORBIDDEN rather than a 404: the caller is a
|
||||
// legitimate user of this server who is not allowed here, and pretending
|
||||
// the endpoint does not exist would only make the panel harder to debug.
|
||||
func (a *AdminAPI) requireAdmin(r *http.Request) (userapi.Authenticated, error) {
|
||||
token := accessTokenFrom(r)
|
||||
if token == "" {
|
||||
return userapi.Authenticated{}, httputil.MissingToken()
|
||||
}
|
||||
|
||||
auth, err := a.users.Authenticate(r.Context(), token)
|
||||
switch {
|
||||
case err == nil:
|
||||
case errors.Is(err, userapi.ErrNoSuchToken):
|
||||
return userapi.Authenticated{}, httputil.UnknownToken(false)
|
||||
case errors.Is(err, userapi.ErrTokenExpired):
|
||||
return userapi.Authenticated{}, httputil.UnknownToken(true)
|
||||
case errors.Is(err, userapi.ErrAccountDeactivated):
|
||||
return userapi.Authenticated{}, httputil.UserDeactivated()
|
||||
default:
|
||||
return userapi.Authenticated{}, err
|
||||
}
|
||||
|
||||
if !auth.Admin {
|
||||
return userapi.Authenticated{}, httputil.Forbidden("This endpoint requires a server administrator")
|
||||
}
|
||||
return auth, nil
|
||||
}
|
||||
|
||||
// accessTokenFrom reads the bearer token. The admin panel is a normal
|
||||
// Matrix client, so it sends the header form; the query parameter is not
|
||||
// accepted here, because an admin token in a URL ends up in access logs.
|
||||
func accessTokenFrom(r *http.Request) string {
|
||||
header := r.Header.Get("Authorization")
|
||||
const prefix = "Bearer "
|
||||
if len(header) <= len(prefix) || !equalFoldASCII(header[:len(prefix)], prefix) {
|
||||
return ""
|
||||
}
|
||||
return header[len(prefix):]
|
||||
}
|
||||
|
||||
// equalFoldASCII compares two ASCII strings case-insensitively. The scheme
|
||||
// of an Authorization header is case-insensitive per RFC 9110.
|
||||
func equalFoldASCII(a, b string) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for i := range len(a) {
|
||||
x, y := a[i], b[i]
|
||||
if 'A' <= x && x <= 'Z' {
|
||||
x += 'a' - 'A'
|
||||
}
|
||||
if 'A' <= y && y <= 'Z' {
|
||||
y += 'a' - 'A'
|
||||
}
|
||||
if x != y {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// switchResponse is the shape both runtime switches report.
|
||||
type switchResponse struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
|
||||
// Toggleable is false when the config file pinned the setting, in
|
||||
// which case the panel shows the switch greyed out rather than letting
|
||||
// an operator flip something that will bounce.
|
||||
Toggleable bool `json:"toggleable"`
|
||||
}
|
||||
|
||||
// switchRequest is the body of either PUT.
|
||||
type switchRequest struct {
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
|
||||
// federationResponse adds the allow and deny lists to the switch.
|
||||
type federationResponse struct {
|
||||
switchResponse
|
||||
Allowlist []string `json:"allowlist"`
|
||||
Denylist []string `json:"denylist"`
|
||||
}
|
||||
|
||||
// handleGetFederation implements GET /_warp/admin/v1/federation.
|
||||
func (a *AdminAPI) handleGetFederation(w http.ResponseWriter, _ *http.Request, _ userapi.Authenticated) error {
|
||||
allowlist, denylist := a.federation.Policy().Lists()
|
||||
httputil.WriteJSON(w, http.StatusOK, federationResponse{
|
||||
switchResponse: switchResponse{
|
||||
Enabled: a.settings.FederationEnabled(),
|
||||
Toggleable: a.settings.FederationToggleable(),
|
||||
},
|
||||
// Editing these is Phase 9; they are reported now because the
|
||||
// dashboard has to show which servers a running Warp will talk to.
|
||||
Allowlist: allowlist,
|
||||
Denylist: denylist,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// handlePutFederation implements PUT /_warp/admin/v1/federation, the switch
|
||||
// PLAN.md section 3 describes: no restart, the gate picks it up on the next
|
||||
// request.
|
||||
func (a *AdminAPI) handlePutFederation(w http.ResponseWriter, r *http.Request, auth userapi.Authenticated) error {
|
||||
enabled, err := decodeSwitch(w, r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := a.settings.SetFederationEnabled(r.Context(), enabled); err != nil {
|
||||
return toggleError(err, "federation")
|
||||
}
|
||||
a.log.Info("federation switch changed through the admin API",
|
||||
"enabled", enabled, "by", auth.UserID)
|
||||
return a.handleGetFederation(w, r, auth)
|
||||
}
|
||||
|
||||
// handleGetRegistration implements GET /_warp/admin/v1/registration.
|
||||
func (a *AdminAPI) handleGetRegistration(w http.ResponseWriter, _ *http.Request, _ userapi.Authenticated) error {
|
||||
httputil.WriteJSON(w, http.StatusOK, switchResponse{
|
||||
Enabled: a.settings.RegistrationEnabled(),
|
||||
Toggleable: a.settings.RegistrationToggleable(),
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// handlePutRegistration implements PUT /_warp/admin/v1/registration.
|
||||
func (a *AdminAPI) handlePutRegistration(w http.ResponseWriter, r *http.Request, auth userapi.Authenticated) error {
|
||||
enabled, err := decodeSwitch(w, r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := a.settings.SetRegistrationEnabled(r.Context(), enabled); err != nil {
|
||||
return toggleError(err, "registration")
|
||||
}
|
||||
a.log.Info("registration switch changed through the admin API",
|
||||
"enabled", enabled, "by", auth.UserID)
|
||||
return a.handleGetRegistration(w, r, auth)
|
||||
}
|
||||
|
||||
// decodeSwitch reads {"enabled": bool}. The field is a pointer so that a
|
||||
// body without it is a missing parameter rather than a silent "false".
|
||||
func decodeSwitch(w http.ResponseWriter, r *http.Request) (bool, error) {
|
||||
var req switchRequest
|
||||
if err := httputil.DecodeJSON(w, r, &req); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if req.Enabled == nil {
|
||||
return false, httputil.MissingParam("enabled is required")
|
||||
}
|
||||
return *req.Enabled, nil
|
||||
}
|
||||
|
||||
// toggleError turns a refused toggle into the right answer: a setting the
|
||||
// config file pinned is a 409, because the request was well formed and the
|
||||
// server's configuration is what stands in the way.
|
||||
func toggleError(err error, name string) error {
|
||||
if errors.Is(err, settings.ErrNotToggleable) {
|
||||
return httputil.NewError(http.StatusConflict, httputil.ErrCodeForbidden,
|
||||
"The %s switch is pinned by the configuration file (%s.allow_runtime_toggle is false)",
|
||||
name, name)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// statsResponse is the dashboard payload: PLAN.md section 8.1 lists users,
|
||||
// rooms, events, federation status, storage driver and version as the first
|
||||
// thing the panel shows. The room and event counters join it in Phase 3,
|
||||
// when there is something to count.
|
||||
type statsResponse struct {
|
||||
ServerName string `json:"server_name"`
|
||||
Version string `json:"version"`
|
||||
Database string `json:"database"`
|
||||
|
||||
Users int `json:"users"`
|
||||
Admins int `json:"admins"`
|
||||
Deactivated int `json:"deactivated"`
|
||||
Devices int `json:"devices"`
|
||||
|
||||
FederationEnabled bool `json:"federation_enabled"`
|
||||
RegistrationEnabled bool `json:"registration_enabled"`
|
||||
}
|
||||
|
||||
// handleGetStats implements GET /_warp/admin/v1/stats.
|
||||
func (a *AdminAPI) handleGetStats(w http.ResponseWriter, r *http.Request, _ userapi.Authenticated) error {
|
||||
stats, err := a.users.Stats(r.Context())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
resp := statsResponse{
|
||||
ServerName: a.serverName,
|
||||
Version: buildinfo.Version,
|
||||
Users: stats.Users,
|
||||
Admins: stats.Admins,
|
||||
Deactivated: stats.Deactivated,
|
||||
Devices: stats.Devices,
|
||||
FederationEnabled: a.settings.FederationEnabled(),
|
||||
RegistrationEnabled: a.settings.RegistrationEnabled(),
|
||||
}
|
||||
if a.database != nil {
|
||||
resp.Database = a.database.Driver()
|
||||
}
|
||||
httputil.WriteJSON(w, http.StatusOK, resp)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
package adminapi_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/dariuszjaniak/warp/server/internal/adminapi"
|
||||
"github.com/dariuszjaniak/warp/server/internal/federation"
|
||||
"github.com/dariuszjaniak/warp/server/internal/httputil"
|
||||
"github.com/dariuszjaniak/warp/server/internal/settings"
|
||||
"github.com/dariuszjaniak/warp/server/internal/storage"
|
||||
_ "github.com/dariuszjaniak/warp/server/internal/storage/drivers"
|
||||
"github.com/dariuszjaniak/warp/server/internal/userapi"
|
||||
)
|
||||
|
||||
const testServerName = "warp.example"
|
||||
|
||||
// testServer is an admin API on a throwaway SQLite database.
|
||||
type testServer struct {
|
||||
t *testing.T
|
||||
handler http.Handler
|
||||
users *userapi.API
|
||||
settings *settings.Service
|
||||
}
|
||||
|
||||
// newTestServer builds the component. defaults are the config-file values
|
||||
// the settings service starts from, which is how a test pins a switch.
|
||||
func newTestServer(t *testing.T, defaults settings.Defaults) *testServer {
|
||||
t.Helper()
|
||||
|
||||
path := filepath.ToSlash(filepath.Join(t.TempDir(), "warp.db"))
|
||||
db, err := storage.Open(t.Context(), storage.Config{
|
||||
Driver: storage.DriverSQLite,
|
||||
ConnectionString: "file:" + path,
|
||||
}, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatalf("open storage: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
if err := db.Migrate(t.Context()); err != nil {
|
||||
t.Fatalf("migrate: %v", err)
|
||||
}
|
||||
|
||||
users, err := userapi.New(userapi.Options{
|
||||
ServerName: testServerName,
|
||||
Store: db.Users(),
|
||||
Logger: slog.New(slog.DiscardHandler),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("userapi.New: %v", err)
|
||||
}
|
||||
|
||||
settingsService, err := settings.New(t.Context(), db.Settings(), defaults, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatalf("settings.New: %v", err)
|
||||
}
|
||||
|
||||
api, err := adminapi.New(adminapi.Options{
|
||||
ServerName: testServerName,
|
||||
Users: users,
|
||||
Settings: settingsService,
|
||||
Federation: federation.NewGate(settingsService.FederationEnabled,
|
||||
federation.NewPolicy([]string{"friend.example"}, []string{"spam.example"})),
|
||||
Database: db,
|
||||
Logger: slog.New(slog.DiscardHandler),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("adminapi.New: %v", err)
|
||||
}
|
||||
|
||||
router := httputil.NewRouter(nil)
|
||||
api.RegisterRoutes(router)
|
||||
return &testServer{t: t, handler: router, users: users, settings: settingsService}
|
||||
}
|
||||
|
||||
func (ts *testServer) do(method, path, token string, body any) *httptest.ResponseRecorder {
|
||||
ts.t.Helper()
|
||||
|
||||
var reader io.Reader
|
||||
if body != nil {
|
||||
raw, err := json.Marshal(body)
|
||||
if err != nil {
|
||||
ts.t.Fatal(err)
|
||||
}
|
||||
reader = bytes.NewReader(raw)
|
||||
}
|
||||
req := httptest.NewRequest(method, path, reader)
|
||||
if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
ts.handler.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
// admin creates an administrator and returns its access token.
|
||||
func (ts *testServer) admin(localpart string) string {
|
||||
ts.t.Helper()
|
||||
return ts.account(localpart, true)
|
||||
}
|
||||
|
||||
// user creates an ordinary account and returns its access token.
|
||||
func (ts *testServer) user(localpart string) string {
|
||||
ts.t.Helper()
|
||||
return ts.account(localpart, false)
|
||||
}
|
||||
|
||||
func (ts *testServer) account(localpart string, admin bool) string {
|
||||
ts.t.Helper()
|
||||
if _, err := ts.users.CreateAccount(ts.t.Context(), userapi.NewAccountRequest{
|
||||
Localpart: localpart,
|
||||
Password: "sUp3rs3kr1t",
|
||||
Admin: admin,
|
||||
}); err != nil {
|
||||
ts.t.Fatalf("CreateAccount: %v", err)
|
||||
}
|
||||
session, err := ts.users.CreateSession(ts.t.Context(), userapi.SessionRequest{Localpart: localpart})
|
||||
if err != nil {
|
||||
ts.t.Fatalf("CreateSession: %v", err)
|
||||
}
|
||||
return session.AccessToken
|
||||
}
|
||||
|
||||
func jsonBody(t *testing.T, rec *httptest.ResponseRecorder) map[string]any {
|
||||
t.Helper()
|
||||
var out map[string]any
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &out); err != nil {
|
||||
t.Fatalf("response is not JSON (%s): %v", rec.Body.String(), err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func expectStatus(t *testing.T, rec *httptest.ResponseRecorder, want int) {
|
||||
t.Helper()
|
||||
if rec.Code != want {
|
||||
t.Fatalf("status = %d, want %d (body: %s)", rec.Code, want, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func expectError(t *testing.T, rec *httptest.ResponseRecorder, status int, errcode string) {
|
||||
t.Helper()
|
||||
expectStatus(t, rec, status)
|
||||
if got := jsonBody(t, rec)["errcode"]; got != errcode {
|
||||
t.Errorf("errcode = %v, want %s (body: %s)", got, errcode, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
const (
|
||||
federationPath = adminapi.Prefix + "/federation"
|
||||
registrationPath = adminapi.Prefix + "/registration"
|
||||
usersPath = adminapi.Prefix + "/users"
|
||||
statsPath = adminapi.Prefix + "/stats"
|
||||
)
|
||||
|
||||
var toggleable = settings.Defaults{
|
||||
FederationAllowRuntimeToggle: true,
|
||||
RegistrationAllowRuntimeToggle: true,
|
||||
}
|
||||
|
||||
// TestAdminAuth is the gate everything else here depends on.
|
||||
func TestAdminAuth(t *testing.T) {
|
||||
ts := newTestServer(t, toggleable)
|
||||
admin := ts.admin("root")
|
||||
ordinary := ts.user("alice")
|
||||
|
||||
for name, tc := range map[string]struct {
|
||||
token string
|
||||
status int
|
||||
code string
|
||||
}{
|
||||
"no token": {"", http.StatusUnauthorized, "M_MISSING_TOKEN"},
|
||||
"unknown token": {"not-a-token", http.StatusUnauthorized, "M_UNKNOWN_TOKEN"},
|
||||
"ordinary user": {ordinary, http.StatusForbidden, "M_FORBIDDEN"},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
expectError(t, ts.do(http.MethodGet, statsPath, tc.token, nil), tc.status, tc.code)
|
||||
})
|
||||
}
|
||||
|
||||
expectStatus(t, ts.do(http.MethodGet, statsPath, admin, nil), http.StatusOK)
|
||||
}
|
||||
|
||||
// TestAdminTokenNotAcceptedInQueryString: an admin token in a URL ends up in
|
||||
// every access log between here and the browser.
|
||||
func TestAdminTokenNotAcceptedInQueryString(t *testing.T) {
|
||||
ts := newTestServer(t, toggleable)
|
||||
admin := ts.admin("root")
|
||||
|
||||
expectError(t, ts.do(http.MethodGet, statsPath+"?access_token="+admin, "", nil),
|
||||
http.StatusUnauthorized, "M_MISSING_TOKEN")
|
||||
}
|
||||
|
||||
// TestFederationSwitch is the admin half of PLAN.md section 3: the switch
|
||||
// flips at runtime and the gate follows.
|
||||
func TestFederationSwitch(t *testing.T) {
|
||||
ts := newTestServer(t, toggleable)
|
||||
admin := ts.admin("root")
|
||||
|
||||
rec := ts.do(http.MethodGet, federationPath, admin, nil)
|
||||
expectStatus(t, rec, http.StatusOK)
|
||||
body := jsonBody(t, rec)
|
||||
if body["enabled"] != false {
|
||||
t.Errorf("federation should start disabled, got %v", body["enabled"])
|
||||
}
|
||||
if body["toggleable"] != true {
|
||||
t.Errorf("toggleable = %v, want true", body["toggleable"])
|
||||
}
|
||||
// The dashboard needs to show which servers a running Warp will talk
|
||||
// to, even though editing the lists is Phase 9.
|
||||
if allowlist, _ := body["allowlist"].([]any); len(allowlist) != 1 || allowlist[0] != "friend.example" {
|
||||
t.Errorf("allowlist = %v", body["allowlist"])
|
||||
}
|
||||
if denylist, _ := body["denylist"].([]any); len(denylist) != 1 || denylist[0] != "spam.example" {
|
||||
t.Errorf("denylist = %v", body["denylist"])
|
||||
}
|
||||
|
||||
rec = ts.do(http.MethodPut, federationPath, admin, map[string]any{"enabled": true})
|
||||
expectStatus(t, rec, http.StatusOK)
|
||||
if jsonBody(t, rec)["enabled"] != true {
|
||||
t.Errorf("the PUT should report the new state, got %s", rec.Body.String())
|
||||
}
|
||||
if !ts.settings.FederationEnabled() {
|
||||
t.Error("the settings service did not pick the change up")
|
||||
}
|
||||
|
||||
rec = ts.do(http.MethodPut, federationPath, admin, map[string]any{"enabled": false})
|
||||
expectStatus(t, rec, http.StatusOK)
|
||||
if ts.settings.FederationEnabled() {
|
||||
t.Error("switching back off did not take effect")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegistrationSwitch(t *testing.T) {
|
||||
ts := newTestServer(t, toggleable)
|
||||
admin := ts.admin("root")
|
||||
|
||||
rec := ts.do(http.MethodPut, registrationPath, admin, map[string]any{"enabled": true})
|
||||
expectStatus(t, rec, http.StatusOK)
|
||||
if !ts.settings.RegistrationEnabled() {
|
||||
t.Error("registration was not enabled")
|
||||
}
|
||||
|
||||
rec = ts.do(http.MethodGet, registrationPath, admin, nil)
|
||||
expectStatus(t, rec, http.StatusOK)
|
||||
if jsonBody(t, rec)["enabled"] != true {
|
||||
t.Errorf("GET = %s", rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestSwitchPinnedByConfig covers settings.ErrNotToggleable: the request was
|
||||
// fine, the server's own configuration is what refuses it, so it is a
|
||||
// conflict rather than a bad request.
|
||||
func TestSwitchPinnedByConfig(t *testing.T) {
|
||||
ts := newTestServer(t, settings.Defaults{})
|
||||
admin := ts.admin("root")
|
||||
|
||||
for _, path := range []string{federationPath, registrationPath} {
|
||||
rec := ts.do(http.MethodPut, path, admin, map[string]any{"enabled": true})
|
||||
expectError(t, rec, http.StatusConflict, "M_FORBIDDEN")
|
||||
if msg, _ := jsonBody(t, rec)["error"].(string); msg == "" {
|
||||
t.Error("the refusal must say which setting is pinned")
|
||||
}
|
||||
|
||||
// And the GET says so in advance, so the panel can grey the
|
||||
// switch out instead of offering something that will bounce.
|
||||
rec = ts.do(http.MethodGet, path, admin, nil)
|
||||
expectStatus(t, rec, http.StatusOK)
|
||||
if jsonBody(t, rec)["toggleable"] != false {
|
||||
t.Errorf("GET %s reports toggleable, but it is pinned", path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSwitchRequiresTheEnabledField(t *testing.T) {
|
||||
ts := newTestServer(t, toggleable)
|
||||
admin := ts.admin("root")
|
||||
|
||||
expectError(t, ts.do(http.MethodPut, federationPath, admin, map[string]any{}),
|
||||
http.StatusBadRequest, "M_MISSING_PARAM")
|
||||
}
|
||||
|
||||
func TestListUsers(t *testing.T) {
|
||||
ts := newTestServer(t, toggleable)
|
||||
admin := ts.admin("root")
|
||||
ts.user("alice")
|
||||
ts.user("bob")
|
||||
|
||||
rec := ts.do(http.MethodGet, usersPath, admin, nil)
|
||||
expectStatus(t, rec, http.StatusOK)
|
||||
|
||||
body := jsonBody(t, rec)
|
||||
if total, _ := body["total"].(float64); total != 3 {
|
||||
t.Errorf("total = %v, want 3", body["total"])
|
||||
}
|
||||
users, _ := body["users"].([]any)
|
||||
if len(users) != 3 {
|
||||
t.Fatalf("got %d users, want 3", len(users))
|
||||
}
|
||||
first, _ := users[0].(map[string]any)
|
||||
if first["user_id"] != "@alice:warp.example" {
|
||||
t.Errorf("users are not ordered by localpart: %s", rec.Body.String())
|
||||
}
|
||||
if first["admin"] != false {
|
||||
t.Errorf("alice should not be an admin: %v", first)
|
||||
}
|
||||
|
||||
// Paging reports the full total so the panel can show how many pages
|
||||
// there are.
|
||||
rec = ts.do(http.MethodGet, usersPath+"?limit=1&offset=1", admin, nil)
|
||||
expectStatus(t, rec, http.StatusOK)
|
||||
body = jsonBody(t, rec)
|
||||
users, _ = body["users"].([]any)
|
||||
if len(users) != 1 || users[0].(map[string]any)["user_id"] != "@bob:warp.example" {
|
||||
t.Errorf("paged listing = %s", rec.Body.String())
|
||||
}
|
||||
if total, _ := body["total"].(float64); total != 3 {
|
||||
t.Errorf("paged total = %v, want 3", body["total"])
|
||||
}
|
||||
|
||||
rec = ts.do(http.MethodGet, usersPath+"?search=ali", admin, nil)
|
||||
expectStatus(t, rec, http.StatusOK)
|
||||
if total, _ := jsonBody(t, rec)["total"].(float64); total != 1 {
|
||||
t.Errorf("search found %v users, want 1", jsonBody(t, rec)["total"])
|
||||
}
|
||||
|
||||
expectError(t, ts.do(http.MethodGet, usersPath+"?limit=lots", admin, nil),
|
||||
http.StatusBadRequest, "M_INVALID_PARAM")
|
||||
expectError(t, ts.do(http.MethodGet, usersPath+"?offset=-1", admin, nil),
|
||||
http.StatusBadRequest, "M_INVALID_PARAM")
|
||||
}
|
||||
|
||||
// TestCreateUser covers the way an operator adds an account to a server with
|
||||
// registration switched off — which is the normal state of a private Warp.
|
||||
func TestCreateUser(t *testing.T) {
|
||||
ts := newTestServer(t, toggleable)
|
||||
admin := ts.admin("root")
|
||||
|
||||
if ts.settings.RegistrationEnabled() {
|
||||
t.Fatal("this test needs registration to be off")
|
||||
}
|
||||
|
||||
rec := ts.do(http.MethodPost, usersPath, admin, map[string]any{
|
||||
"username": "Alice",
|
||||
"password": "sUp3rs3kr1t",
|
||||
"display_name": "Alice",
|
||||
"admin": true,
|
||||
})
|
||||
expectStatus(t, rec, http.StatusCreated)
|
||||
|
||||
body := jsonBody(t, rec)
|
||||
if body["user_id"] != "@alice:warp.example" {
|
||||
t.Errorf("user_id = %v; the localpart should be normalised", body["user_id"])
|
||||
}
|
||||
if body["admin"] != true {
|
||||
t.Errorf("admin = %v, want true", body["admin"])
|
||||
}
|
||||
|
||||
// The new account can really log in, which is the only thing that
|
||||
// makes creating it useful.
|
||||
if err := ts.users.CheckPassword(t.Context(), "alice", "sUp3rs3kr1t"); err != nil {
|
||||
t.Errorf("the created account cannot log in: %v", err)
|
||||
}
|
||||
|
||||
expectError(t, ts.do(http.MethodPost, usersPath, admin, map[string]any{
|
||||
"username": "alice", "password": "sUp3rs3kr1t",
|
||||
}), http.StatusBadRequest, "M_USER_IN_USE")
|
||||
|
||||
expectError(t, ts.do(http.MethodPost, usersPath, admin, map[string]any{
|
||||
"username": "not valid", "password": "sUp3rs3kr1t",
|
||||
}), http.StatusBadRequest, "M_INVALID_USERNAME")
|
||||
|
||||
expectError(t, ts.do(http.MethodPost, usersPath, admin, map[string]any{"username": "bob"}),
|
||||
http.StatusBadRequest, "M_MISSING_PARAM")
|
||||
expectError(t, ts.do(http.MethodPost, usersPath, admin, map[string]any{"password": "x"}),
|
||||
http.StatusBadRequest, "M_MISSING_PARAM")
|
||||
}
|
||||
|
||||
func TestStats(t *testing.T) {
|
||||
ts := newTestServer(t, toggleable)
|
||||
admin := ts.admin("root")
|
||||
ts.user("alice")
|
||||
|
||||
rec := ts.do(http.MethodGet, statsPath, admin, nil)
|
||||
expectStatus(t, rec, http.StatusOK)
|
||||
|
||||
body := jsonBody(t, rec)
|
||||
if body["server_name"] != testServerName {
|
||||
t.Errorf("server_name = %v", body["server_name"])
|
||||
}
|
||||
if body["database"] != storage.DriverSQLite {
|
||||
t.Errorf("database = %v, want sqlite", body["database"])
|
||||
}
|
||||
if users, _ := body["users"].(float64); users != 2 {
|
||||
t.Errorf("users = %v, want 2", body["users"])
|
||||
}
|
||||
if admins, _ := body["admins"].(float64); admins != 1 {
|
||||
t.Errorf("admins = %v, want 1", body["admins"])
|
||||
}
|
||||
// Each account above got one session, so the device count follows.
|
||||
if devices, _ := body["devices"].(float64); devices != 2 {
|
||||
t.Errorf("devices = %v, want 2", body["devices"])
|
||||
}
|
||||
if body["federation_enabled"] != false || body["registration_enabled"] != false {
|
||||
t.Errorf("switch state = %s", rec.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package adminapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/dariuszjaniak/warp/server/internal/httputil"
|
||||
"github.com/dariuszjaniak/warp/server/internal/storage"
|
||||
"github.com/dariuszjaniak/warp/server/internal/userapi"
|
||||
)
|
||||
|
||||
// adminUser is one row of the user list. It is a flatter shape than the
|
||||
// Client-Server API's profile object because the panel shows it as a table.
|
||||
type adminUser struct {
|
||||
UserID string `json:"user_id"`
|
||||
DisplayName string `json:"display_name,omitempty"`
|
||||
AvatarURL string `json:"avatar_url,omitempty"`
|
||||
Admin bool `json:"admin"`
|
||||
Deactivated bool `json:"deactivated"`
|
||||
CreatedAtMS int64 `json:"created_at_ms"`
|
||||
}
|
||||
|
||||
type usersResponse struct {
|
||||
Users []adminUser `json:"users"`
|
||||
|
||||
// Total is the number of users matching the query, not the number
|
||||
// returned, so the panel can page.
|
||||
Total int `json:"total"`
|
||||
|
||||
Limit int `json:"limit"`
|
||||
Offset int `json:"offset"`
|
||||
}
|
||||
|
||||
// defaultUserPageLimit is what a request without ?limit= gets.
|
||||
const defaultUserPageLimit = 50
|
||||
|
||||
// handleGetUsers implements GET /_warp/admin/v1/users.
|
||||
func (a *AdminAPI) handleGetUsers(w http.ResponseWriter, r *http.Request, _ userapi.Authenticated) error {
|
||||
query := r.URL.Query()
|
||||
|
||||
limit, err := intParam(query.Get("limit"), defaultUserPageLimit)
|
||||
if err != nil {
|
||||
return httputil.InvalidParam("limit must be a number")
|
||||
}
|
||||
offset, err := intParam(query.Get("offset"), 0)
|
||||
if err != nil {
|
||||
return httputil.InvalidParam("offset must be a number")
|
||||
}
|
||||
if limit < 0 || offset < 0 {
|
||||
return httputil.InvalidParam("limit and offset must not be negative")
|
||||
}
|
||||
|
||||
accounts, total, err := a.users.ListAccounts(r.Context(), storage.AccountFilter{
|
||||
Search: query.Get("search"),
|
||||
Limit: limit,
|
||||
Offset: offset,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
users := make([]adminUser, 0, len(accounts))
|
||||
for _, acc := range accounts {
|
||||
users = append(users, adminUser{
|
||||
UserID: a.users.UserID(acc.Localpart),
|
||||
DisplayName: acc.DisplayName,
|
||||
AvatarURL: acc.AvatarURL,
|
||||
Admin: acc.Admin,
|
||||
Deactivated: acc.Deactivated,
|
||||
CreatedAtMS: acc.CreatedAtMS,
|
||||
})
|
||||
}
|
||||
httputil.WriteJSON(w, http.StatusOK, usersResponse{
|
||||
Users: users,
|
||||
Total: total,
|
||||
Limit: limit,
|
||||
Offset: offset,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// createUserRequest is the body of POST /_warp/admin/v1/users.
|
||||
type createUserRequest struct {
|
||||
// Username is the localpart; it is normalised like any other.
|
||||
Username string `json:"username"`
|
||||
|
||||
Password string `json:"password"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Admin bool `json:"admin"`
|
||||
}
|
||||
|
||||
// handlePostUsers implements POST /_warp/admin/v1/users.
|
||||
//
|
||||
// This is how an operator adds an account on a server with registration
|
||||
// turned off, so it deliberately ignores the registration switch: it is the
|
||||
// admin's own action, not a public sign-up. It does require a password —
|
||||
// unlike `warp create-account`, which may leave one unset — because an
|
||||
// account created from the panel is meant to be handed to somebody.
|
||||
func (a *AdminAPI) handlePostUsers(w http.ResponseWriter, r *http.Request, auth userapi.Authenticated) error {
|
||||
var req createUserRequest
|
||||
if err := httputil.DecodeJSON(w, r, &req); err != nil {
|
||||
return err
|
||||
}
|
||||
if req.Username == "" {
|
||||
return httputil.MissingParam("username is required")
|
||||
}
|
||||
if req.Password == "" {
|
||||
return httputil.MissingParam("password is required")
|
||||
}
|
||||
if len(req.Password) > userapi.MaxPasswordLength {
|
||||
return httputil.NewError(http.StatusBadRequest, httputil.ErrCodeWeakPassword,
|
||||
"Password must be at most %d bytes", userapi.MaxPasswordLength)
|
||||
}
|
||||
|
||||
account, err := a.users.CreateAccount(r.Context(), userapi.NewAccountRequest{
|
||||
Localpart: req.Username,
|
||||
Password: req.Password,
|
||||
DisplayName: req.DisplayName,
|
||||
Admin: req.Admin,
|
||||
})
|
||||
switch {
|
||||
case errors.Is(err, userapi.ErrUserExists):
|
||||
return httputil.UserInUse()
|
||||
case errors.Is(err, userapi.ErrInvalidLocalpart):
|
||||
return httputil.InvalidUsername("%s", err.Error())
|
||||
case err != nil:
|
||||
return err
|
||||
}
|
||||
|
||||
a.log.Info("account created through the admin API",
|
||||
"user_id", a.users.UserID(account.Localpart), "admin", account.Admin, "by", auth.UserID)
|
||||
|
||||
httputil.WriteJSON(w, http.StatusCreated, adminUser{
|
||||
UserID: a.users.UserID(account.Localpart),
|
||||
DisplayName: account.DisplayName,
|
||||
Admin: account.Admin,
|
||||
CreatedAtMS: account.CreatedAtMS,
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// intParam parses an optional integer query parameter.
|
||||
func intParam(raw string, fallback int) (int, error) {
|
||||
if raw == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
return strconv.Atoi(raw)
|
||||
}
|
||||
Reference in new issue
Block a user