Files
Docwell/Server/internal/httpapi/security.go
T
tajniak81andClaude Opus 5.5 0ebf064173
CI / go (Server) (push) Failing after 25m5s
CI / go (Web-App) (push) Canceled after 0s
CI / frontend (push) Failing after 8m38s
CI / desktop (ubuntu-latest) (push) Successful in 1h41m20s
CI / mobile (push) Failing after 4m19s
CI / docker (push) Failing after 44m8s
Docs / build (push) Successful in 17m11s
Docs / deploy (push) Skipped
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
Add audio transcripts, monthly AI limits, PDF sources and AI chat on phones
Follow-ups to Phase E (ADR-15):

- Transcription (E2): OpenAI-compatible profiles can name a speech-to-text
  model; POST /files/{id}/transcribe turns an audio or video attachment
  (up to 25 MB) into text and a summary with key points and action items.
  The editor gets a Transcribe button on media files that inserts the
  summary and the transcript in a toggle.
- Monthly token limits: ai_usage counts requests and tokens per workspace
  and month. Workspace admins can cap their workspace; superadmins can cap
  what each workspace uses through the server's providers, after which
  the workspace's own providers keep working. The admin panel lists usage.
- PDF text for extra retrieval files (ledongthuc/pdf, pure Go).
- Phone app: an AI chat screen for the workspace or a page, with streamed
  answers and sources that open the cited block.
- OpenAPI, generated clients, migration, translations and docs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 22:26:27 +01:00

235 lines
8.5 KiB
Go

// SPDX-License-Identifier: AGPL-3.0-or-later
package httpapi
import (
"context"
"errors"
"io"
"net/http"
"strconv"
"strings"
"time"
"docwell/server/internal/access"
"docwell/server/internal/audit"
"docwell/server/internal/auth"
)
// AuditService records and reads the audit log.
type AuditService interface {
Record(e audit.Entry)
List(ctx context.Context, c access.Caller, q audit.Query) (audit.Page, error)
ExportCSV(ctx context.Context, c access.Caller, q audit.Query, w io.Writer) error
}
// UserManager is the part of directory.Service that checks a manager's
// rights over another user.
type UserManager interface {
CanManageUser(ctx context.Context, c access.Caller, id string) error
// AccountByEmail finds an account's id and organization (empty when
// there is none), to file sign-in attempts under the right organization.
AccountByEmail(ctx context.Context, email string) (id, org string)
}
// unaudited are changes too frequent or too slight for the audit log.
var unaudited = map[string]bool{
"POST /api/v1/pages/{id}/visit": true,
"POST /api/v1/notifications/read": true,
"POST /api/v1/files/token": true,
"PUT /api/v1/pages/{id}/favorite": true,
"POST /api/v1/comments/{id}/reactions": true,
// Questions and writing help change no page; their sessions are private.
"POST /api/v1/ai/sessions/{id}/messages": true,
"POST /api/v1/workspaces/{id}/ai/write": true,
"POST /api/v1/workspaces/{id}/ai/sessions": true,
"POST /api/v1/ai/sessions/{id}/fork": true,
"POST /api/v1/files/{id}/transcribe": true,
"PATCH /api/v1/ai/sessions/{id}": true,
"DELETE /api/v1/ai/sessions/{id}": true,
}
// routeEntry describes a successful change request: the route (without the
// /api/v1 prefix), the ids in its path and who made it. Never the body.
func routeEntry(r *http.Request, u auth.User, status int) audit.Entry {
route := strings.Replace(r.Pattern, " /api/v1/", " /", 1)
e := audit.Entry{
Action: route, ActorID: u.ID, ActorEmail: u.Email, Org: u.Organization, Status: status,
IP: audit.ClientIP(r), UserAgent: r.UserAgent(),
}
if _, path, ok := strings.Cut(route, " /"); ok {
e.TargetType, _, _ = strings.Cut(path, "/")
}
e.TargetID = r.PathValue("id")
meta := map[string]any{}
for _, k := range []string{"userId", "groupId", "pageId", "fileId", "name", "key"} {
if v := r.PathValue(k); v != "" {
meta[k] = v
}
}
if via, _ := r.Context().Value(viaTokenKey{}).(bool); via {
meta["apiToken"] = true
}
if len(meta) > 0 {
e.Meta = meta
}
return e
}
// auditAuth records a sign-in step: success (with the user), a failure, or
// a second step being asked for.
func (a *api) auditAuth(r *http.Request, action, email string, sess auth.Session, err error) {
if a.audit == nil {
return
}
e := audit.Entry{Action: action, ActorEmail: email, IP: audit.ClientIP(r), UserAgent: r.UserAgent(), Status: http.StatusOK}
var totp *auth.TOTPRequiredError
switch {
case err == nil:
e.ActorID, e.ActorEmail, e.Org = sess.User.ID, sess.User.Email, sess.User.Organization
case errors.As(err, &totp):
e.Action += ".second_step"
e.Status = http.StatusUnauthorized
default:
e.Action += ".failed"
e.Status = http.StatusUnauthorized
e.Meta = map[string]any{"reason": err.Error()}
}
if e.ActorID == "" && email != "" && a.dir != nil {
e.ActorID, e.Org = a.dir.AccountByEmail(r.Context(), email)
}
a.audit.Record(e)
}
func (a *api) securityRoutes(mux *routeMux, users UserManager) {
// Second step of sign-in, and sign-in with a provider.
mux.HandleFunc("POST /api/v1/auth/totp/verify", func(w http.ResponseWriter, r *http.Request) {
var in struct{ Challenge, Code string }
if !a.decode(w, r, &in) {
return
}
sess, err := a.auth.VerifyTOTP(r.Context(), in.Challenge, in.Code)
a.auditAuth(r, "auth.totp", sess.User.Email, sess, err)
a.respond(w, sess, err)
})
mux.HandleFunc("POST /api/v1/auth/oauth2/start", func(w http.ResponseWriter, r *http.Request) {
var in struct{ Provider, Redirect string }
if !a.decode(w, r, &in) {
return
}
start, err := a.auth.StartOAuth(r.Context(), in.Provider, in.Redirect)
a.respond(w, start, err)
})
mux.HandleFunc("POST /api/v1/auth/oauth2/finish", func(w http.ResponseWriter, r *http.Request) {
var in struct{ State, Code string }
if !a.decode(w, r, &in) {
return
}
sess, err := a.auth.FinishOAuth(r.Context(), in.State, in.Code)
a.auditAuth(r, "auth.oauth2", sess.User.Email, sess, err)
a.respond(w, sess, err)
})
// The caller's own two-step sign-in and API tokens: sessions only.
mux.HandleFunc("GET /api/v1/me/totp", a.requireSession(func(w http.ResponseWriter, r *http.Request) {
u, _ := CurrentUser(r.Context())
st, err := a.auth.TOTPStatus(r.Context(), u.ID)
a.respond(w, st, err)
}))
mux.HandleFunc("POST /api/v1/me/totp/setup", a.requireSession(func(w http.ResponseWriter, r *http.Request) {
u, _ := CurrentUser(r.Context())
issuer := "Docwell"
if a.settings != nil {
if p, err := a.settings.Public(r.Context()); err == nil && p.AppName != "" {
issuer = p.AppName
}
}
setup, err := a.auth.StartTOTP(r.Context(), u, issuer)
a.respond(w, setup, err)
}))
mux.HandleFunc("POST /api/v1/me/totp/enable", a.requireSession(func(w http.ResponseWriter, r *http.Request) {
var in struct{ Code string }
if !a.decode(w, r, &in) {
return
}
u, _ := CurrentUser(r.Context())
codes, err := a.auth.EnableTOTP(r.Context(), u, in.Code)
a.respond(w, map[string][]string{"recoveryCodes": codes}, err)
}))
mux.HandleFunc("POST /api/v1/me/totp/disable", a.requireSession(func(w http.ResponseWriter, r *http.Request) {
var in struct{ Code string }
if !a.decode(w, r, &in) {
return
}
u, _ := CurrentUser(r.Context())
a.respondNoContent(w, a.auth.DisableTOTP(r.Context(), u, in.Code))
}))
mux.HandleFunc("GET /api/v1/me/tokens", a.requireSession(func(w http.ResponseWriter, r *http.Request) {
u, _ := CurrentUser(r.Context())
list, err := a.auth.ListAPITokens(r.Context(), u.ID)
a.respond(w, list, err)
}))
mux.HandleFunc("POST /api/v1/me/tokens", a.requireSession(func(w http.ResponseWriter, r *http.Request) {
var in struct {
Name string
Scope string
ExpiresDays int
}
if !a.decode(w, r, &in) {
return
}
u, _ := CurrentUser(r.Context())
t, err := a.auth.CreateAPIToken(r.Context(), u, in.Name, in.Scope, in.ExpiresDays)
a.respondStatus(w, http.StatusCreated, t, err)
}))
mux.HandleFunc("DELETE /api/v1/me/tokens/{id}", a.requireSession(func(w http.ResponseWriter, r *http.Request) {
u, _ := CurrentUser(r.Context())
a.respondNoContent(w, a.auth.RevokeAPIToken(r.Context(), u.Caller(), r.PathValue("id"), nil))
}))
// Admins: the audit log, everyone's tokens, and resetting two-step sign-in.
query := func(r *http.Request) audit.Query {
q := r.URL.Query()
page, _ := strconv.Atoi(q.Get("page"))
perPage, _ := strconv.Atoi(q.Get("perPage"))
return audit.Query{Search: q.Get("q"), Since: q.Get("since"), Until: q.Get("until"), Page: page, PerPage: perPage}
}
mux.HandleFunc("GET /api/v1/admin/audit", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
if a.audit == nil {
writeJSON(w, http.StatusOK, audit.Page{Items: []audit.View{}})
return
}
page, err := a.audit.List(r.Context(), caller(r), query(r))
a.respond(w, page, err)
}))
mux.HandleFunc("GET /api/v1/admin/audit/export", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
if a.audit == nil {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "text/csv; charset=utf-8")
w.Header().Set("Content-Disposition", `attachment; filename="docwell-audit-`+time.Now().UTC().Format("2006-01-02")+`.csv"`)
if err := a.audit.ExportCSV(r.Context(), caller(r), query(r), w); err != nil {
a.log.Error("audit export", "err", err)
}
}))
mux.HandleFunc("GET /api/v1/admin/tokens", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
list, err := a.auth.AdminListAPITokens(r.Context(), caller(r))
a.respond(w, list, err)
}))
mux.HandleFunc("DELETE /api/v1/admin/tokens/{id}", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
c := caller(r)
a.respondNoContent(w, a.auth.RevokeAPIToken(r.Context(), c, r.PathValue("id"), func(owner string) error {
return users.CanManageUser(r.Context(), c, owner)
}))
}))
mux.HandleFunc("DELETE /api/v1/users/{id}/totp", a.requireManager(func(w http.ResponseWriter, r *http.Request) {
id := r.PathValue("id")
if err := users.CanManageUser(r.Context(), caller(r), id); err != nil {
a.writeError(w, err)
return
}
a.respondNoContent(w, a.auth.ResetTOTP(r.Context(), id))
}))
}