Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ Notable changes to Refract. The format follows [Keep a Changelog](https://keepac

### Added

- Administrators can create, rename, unlock and delete accounts, reset passwords, and end sessions from **Account administration**. The page also shows each account's model usage and project disk space. Run `refract users admin <email>` to grant the role or `refract users report <email> [since]` for the same report as JSON.
- Refract can read its encryption key, OpenID Connect client secret, SMTP URL and OpenAlex API key from files using the corresponding `REFRACT_*_FILE` variables. `refract users` and `refract local` also accept the encryption key from a file, and the systemd unit starts Refract directly with a systemd credential.
- `REFRACT_OUTBOUND` (`any` by default, or `public`) chooses whether AI provider base URLs and git remotes may reach loopback and private networks. `public` does what `REFRACT_MODE=saas` did for outbound requests, and checks at startup that git is 2.37 or later. With `public`, provider requests and redirects must be https, and link-local git remotes are refused in every mode. `REFRACT_MODE=saas` no longer changes it.
- Refract finds `tectonic`, `synctex`, `rg` and `git` in a bundled `libexec/refract` folder next to the executable (the executable's own folder on Windows) before the `PATH`, and runs them by absolute path; a bundled Git uses only its own helpers and templates. `REFRACT_TECTONIC_BIN`, `REFRACT_SYNCTEX_BIN`, `REFRACT_RG_BIN` and `REFRACT_GIT_BIN` override the lookup. The startup log shows where each was found, and the web app shows one notice when a tool is missing, saying what won't work, on whichever page opens first. On macOS and Linux a bundled tool in a folder that others can write, or that another user owns, is ignored. The same checks cover bundled Git's helpers and templates.
Expand Down
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,12 @@ docker exec refract refract users list

Accounts you add this way count as confirmed: you vouch for the address. People can see and end their own sessions in Settings → Account. To end all of someone's sessions for them (a lost laptop, say), run `refract users signout <email>`. After too many failed sign-ins an account waits 15 minutes; `refract users unlock <email>` lets it in at once. To delete an account with its projects (those in the trash too), chats and connections, run `refract users remove <email>`: it lists what would go, and deletes only when run again with `--yes`. With Cloudflare Access, also remove the person from your Access policy, or they get a new, empty account on their next visit.

Administrators can open **Account administration** from the account menu. They can create accounts, issue new passwords, change email addresses, end Refract sessions, clear lockouts and delete accounts. Changes are logged on the server. Changing an email address ends Refract sessions and invalidates existing account links. Passwords and Refract sessions apply to Refract's built-in sign-in. With Cloudflare Access, continue to manage access and sessions through Cloudflare. Without sign-in, account administration is available only when Refract itself listens on a loopback address.

On a new installation, the first account created by the CLI or a trusted sign-in becomes an administrator if the account list is empty. An open sign-up never grants the role. After upgrading an existing installation, grant the role to the confirmed account you trust with `refract users admin <email>` on the server.

Selecting an account shows its token usage this month and disk space per project, including Git history and projects in the trash. Generated build files are excluded from disk totals. For the same report as JSON, run `refract users report <email> [since]`. Pass a Unix timestamp in seconds to choose when to start counting tokens. The default counts all recorded usage.

### Sign in with OpenID Connect

With `REFRACT_AUTH=builtin`, an OpenID Connect provider (Google, Microsoft Entra, Keycloak, Authentik, Authelia…) can add a **Continue with …** button next to the password form.
Expand Down Expand Up @@ -614,6 +620,8 @@ refract users rename <a> <b> change an account's email, keeping its data
refract users signout <email> end all of an account's sessions
refract users unlock <email> clear an account's failed sign-ins and email limit (--all: every account and address)
refract users remove <email> delete an account and everything it owns, trash included (asks for --yes)
refract users admin <email> grant administrator access to a confirmed account
refract users report <email> [since] show model usage and project disk space as JSON
refract users list list accounts
refract version print the version
```
Expand Down
16 changes: 14 additions & 2 deletions cmd/refract/account_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ func (a *loginAPI) resetPassword(w http.ResponseWriter, r *http.Request) {
case err != nil:
httpError(w, err, http.StatusInternalServerError)
default:
a.signIn(w, r, u.ID)
a.signIn(w, r, u)
}
}

Expand Down Expand Up @@ -197,7 +197,7 @@ func (a *loginAPI) verifyEmail(w http.ResponseWriter, r *http.Request) {
case u.ID == signedInAs:
w.WriteHeader(http.StatusNoContent)
default:
a.signIn(w, r, u.ID)
a.signIn(w, r, u)
}
}

Expand Down Expand Up @@ -304,6 +304,9 @@ func (a *loginAPI) deleteAccount(w http.ResponseWriter, r *http.Request) {
// Once started, deleting runs to the end even if the client goes away.
n, err := a.users.Remove(context.WithoutCancel(r.Context()), u.ID, a.destroy)
switch {
case err != nil && n > 0:
partialAccountRemoval(w, int64(n), err)
return
case errors.Is(err, users.ErrOwnsProjects):
httpError(w, errors.New("a project was created meanwhile: try again"), http.StatusConflict)
return
Expand All @@ -321,6 +324,15 @@ func (a *loginAPI) deleteAccount(w http.ResponseWriter, r *http.Request) {
slog.Info("account deleted", "user", u.ID, "projects", n)
}

func partialAccountRemoval(w http.ResponseWriter, removed int64, err error) {
slog.Warn("account removal stopped after deleting projects", "removed_projects", removed, "err", err)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusConflict)
json.NewEncoder(w).Encode(map[string]any{"error": map[string]any{
"kind": "account_removal_partial", "message": "some projects were deleted before account removal stopped", "removed_projects": removed,
}})
}

// thenAccount is the only value oidcStart takes for ?then=.
func thenAccount(r *http.Request) bool { return r.URL.Query().Get("then") == "account" }

Expand Down
11 changes: 7 additions & 4 deletions cmd/refract/account_api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import (
"github.com/ponytojas/Refract/internal/mode"
"github.com/ponytojas/Refract/internal/projects"
"github.com/ponytojas/Refract/internal/store"
"github.com/ponytojas/Refract/internal/usage"
"github.com/ponytojas/Refract/internal/users"
)

Expand Down Expand Up @@ -63,15 +64,15 @@ func TestMain(m *testing.M) {
func newAccountEnv(t *testing.T, o envOpts) *accountEnv {
t.Helper()
dir := t.TempDir()
db, err := store.Open(filepath.Join(dir, "t.db"))
db, err := store.Open(filepath.Join(dir, "refract.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { db.Close() })
people := &users.Service{DB: db, Key: make([]byte, 32)}
ps := &projects.Service{DB: db, Dir: filepath.Join(dir, "projects"), Limits: projects.DefaultLimits}
e := &accountEnv{t: t, people: people, ps: ps, fake: &mail.Fake{}}
e.login = &loginAPI{users: people, mode: mode.SelfHost, signup: o.signup, destroy: destroyer(ps)}
e.login = &loginAPI{users: people, mode: mode.SelfHost, signup: o.signup, destroy: ps.DestroyOwnedProjects}
if !o.noMail {
e.login.public = "https://r.test"
e.outbox = mail.NewOutbox(e.fake)
Expand All @@ -80,6 +81,8 @@ func newAccountEnv(t *testing.T, o envOpts) *accountEnv {
}
app := http.NewServeMux()
rt := &router{mux: app, acc: &access.Checker{DB: db}}
rec := &usage.Recorder{DB: db}
(&api{usage: rec, admin: &adminAPI{users: people, projects: ps, usage: rec}}).routes(rt)
(&projectsAPI{svc: ps}).routes(rt)
e.login.accountRoutes(rt)
mux := http.NewServeMux()
Expand Down Expand Up @@ -410,9 +413,9 @@ func TestDeleteAccountSurvivesDisconnect(t *testing.T) {
reqCtx, cancel := context.WithCancel(as)
defer cancel()
inner := e.login.destroy
e.login.destroy = func(c context.Context, id string) error {
e.login.destroy = func(c context.Context, ids []string) (int, error) {
cancel() // the client hangs up as the first project goes
return inner(c, id)
return inner(c, ids)
}
body, _ := json.Marshal(map[string]string{"password": "correct horse"})
r := httptest.NewRequest("POST", "/api/account/delete", bytes.NewReader(body)).WithContext(reqCtx)
Expand Down
210 changes: 210 additions & 0 deletions cmd/refract/admin_api.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
package main

import (
"context"
"errors"
"log/slog"
"net/http"
"strconv"
"time"

"github.com/ponytojas/Refract/internal/projects"
"github.com/ponytojas/Refract/internal/usage"
"github.com/ponytojas/Refract/internal/users"
"github.com/ponytojas/Refract/web"
)

type adminAPI struct {
users *users.Service
projects *projects.Service
usage *usage.Recorder
}

func (a *adminAPI) routes(rt *router) {
rt.admin("GET /admin", web.Handler().ServeHTTP)
rt.admin("GET /api/admin/accounts", a.accounts)
rt.admin("GET /api/admin/accounts/report", a.report)
rt.admin("POST /api/admin/accounts", a.manage)
}

func (a *adminAPI) accounts(w http.ResponseWriter, r *http.Request) {
all, err := a.users.AdminAccounts(r.Context())
if err != nil {
accessError(w, err)
return
}
writeJSON(w, all)
}

type measuredProject struct {
ID string `json:"id"`
Name string `json:"name"`
Trashed bool `json:"trashed"`
Bytes int64 `json:"bytes"`
}

type accountReport struct {
Models []usage.ModelTotals `json:"models"`
Projects []measuredProject `json:"projects"`
}

func usageStart(raw string) (time.Time, error) {
since, err := strconv.ParseInt(raw, 10, 64)
if err != nil || since < 0 {
return time.Time{}, errors.New("since must be a Unix time in seconds")
}
return time.Unix(since, 0), nil
}

// accountUsageAndStorage is shared by the web reports and the operator CLI.
func (a *adminAPI) accountUsageAndStorage(ctx context.Context, id string, since time.Time) (accountReport, error) {
owned, err := a.users.OwnedProjects(ctx, id)
if err != nil {
return accountReport{}, err
}
models, err := a.usage.Report(ctx, id, since)
if err != nil {
return accountReport{}, err
}
out := accountReport{Models: models, Projects: make([]measuredProject, 0, len(owned))}
for _, p := range owned {
size, err := a.projects.StorageBytes(ctx, p.ID)
if err != nil {
return accountReport{}, err
}
out.Projects = append(out.Projects, measuredProject{ID: p.ID, Name: p.Name, Trashed: p.Trashed, Bytes: size})
}
return out, nil
}

func (a *adminAPI) report(w http.ResponseWriter, r *http.Request) {
since, err := usageStart(r.URL.Query().Get("since"))
if err != nil {
httpError(w, err, http.StatusBadRequest)
return
}
id := r.URL.Query().Get("id")
if _, err := a.users.AccountByID(r.Context(), id); err != nil {
adminError(w, err)
return
}
out, err := a.accountUsageAndStorage(r.Context(), id, since)
if err != nil {
accessError(w, err)
return
}
writeJSON(w, out)
}

type adminAction struct {
Action string `json:"action"`
ID string `json:"id"`
Email string `json:"email"`
Confirmed bool `json:"confirmed"`
}

type adminResult struct {
Password string `json:"password,omitempty"`
Count int64 `json:"count,omitempty"`
}

var (
errAdminAction = errors.New("unknown account action")
errAdminConfirmation = errors.New("confirm this action first")
errAdminAddress = errors.New("enter a valid email address")
)

func (a *adminAPI) manage(w http.ResponseWriter, r *http.Request) {
var in adminAction
if !decode(w, r, &in) {
return
}
switch in.Action {
case "add", "reset", "rename", "signout", "unlock", "unlock_all", "remove":
default:
adminError(w, errAdminAction)
return
}
out, target, err := a.apply(r.Context(), in)
partial := err != nil && in.Action == "remove" && out.Count > 0
result := "success"
if err != nil {
result = "failed"
}
if partial {
result = "partial"
}
slog.Info("account administration", "actor", requestUser(r.Context()), "target", target, "action", in.Action, "result", result, "affected", out.Count)
if partial {
partialAccountRemoval(w, out.Count, err)
return
}
if err != nil {
adminError(w, err)
return
}
writeJSON(w, out)
}

func (a *adminAPI) apply(ctx context.Context, in adminAction) (adminResult, string, error) {
var out adminResult
if in.Action == "add" || in.Action == "rename" {
if err := users.ValidateEmail(in.Email); err != nil {
return out, "", errAdminAddress
}
}
if in.Action == "add" {
u, password, err := a.users.ProvisionPassword(ctx, in.Email, true)
out.Password = password
return out, u.ID, err
}
if !in.Confirmed {
return out, "", errAdminConfirmation
}
if in.Action == "unlock_all" {
count, err := a.users.UnlockAll(ctx)
out.Count = count
return out, "", err
}

acct, err := a.users.AccountByID(ctx, in.ID)
if err != nil {
return out, "", err
}
switch in.Action {
case "reset":

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (optional): Nothing stops an administrator from removing the last administrator, themselves included. remove (and resetting or renaming one's own account) goes through with no check. After that, nobody can open Account administration until an operator runs refract users admin on the server. Fix: refuse remove when the target is the only remaining admin, or at least warn in the dialog.

out.Password, err = a.users.ResetAccountPassword(ctx, acct.ID)
case "rename":
err = a.users.RenameAccount(ctx, acct.ID, in.Email)
case "signout":
out.Count, err = a.users.SignOutAccount(ctx, acct.ID)
case "unlock":
var cleared bool
cleared, err = a.users.Unlock(ctx, acct.Email)
if cleared {
out.Count = 1
}
case "remove":

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important: An administrator can delete their own account (and every project in it) from the admin page with no password or recent sign-in. /api/account/delete requires both, through Login or recentSignIn, but manage → apply "remove" (and "reset") accepts any administrator session plus confirmed: true. Anyone holding a stolen or left-open admin session can wipe any account, their own included, with no reauthentication. Fix: require reauthentication (the current password, or recentSignIn) for destructive admin actions, or at least refuse remove on the actor's own ID and send them to the self-service flow.

var deleted int
deleted, err = a.users.Remove(context.WithoutCancel(ctx), acct.ID, a.projects.DestroyOwnedProjects)
out.Count = int64(deleted)
}
return out, acct.ID, err
}

func adminError(w http.ResponseWriter, err error) {
switch {
case errors.Is(err, users.ErrNoAccount):
httpError(w, err, http.StatusNotFound)
case errors.Is(err, errAdminConfirmation), errors.Is(err, errAdminAction):
httpError(w, err, http.StatusBadRequest)
case errors.Is(err, errAdminAddress):
kindError(w, http.StatusBadRequest, "admin_invalid_email", err)
case errors.Is(err, users.ErrAccountExists):
kindError(w, http.StatusConflict, "admin_account_exists", err)
case errors.Is(err, users.ErrOwnsProjects), errors.Is(err, projects.ErrTurnRunning):
kindError(w, http.StatusConflict, "admin_account_busy", errors.New("the account's projects are changing"))
default:
accessError(w, err)
}
}
Loading
Loading