feat: terms of service and versioned consent; data rights for every account
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 9m21s
ci / test (pull_request) Successful in 13m53s
ci / build (pull_request) Successful in 11m22s
ci / image (pull_request) Successful in 4m36s

Terms of service join the legal notice and privacy policy, for the
platform only. Every account accepts the platform's privacy policy and
terms: on sign-up (also through an invitation) by ticking a box for the
versions shown, and after a sign-in through a provider right away. When
an admin saves a material change with "everyone has to accept again",
the document gets a new version and each account is asked at its next
request; corrections ask nobody. Acceptances are kept per version with
their time, as proof, and are part of the data export.

Until an account accepted, and while it is suspended, it can read the
documents, export its data, delete itself and sign out, nothing else:
pages lead to /consent or /account/suspended, other API calls answer 403
consent_required or account_suspended. Suspended accounts therefore sign
in again, by password or provider; their API tokens stay blocked.

Deleting an account deletes the organizations it owns, monitors and all,
also when they have other members (each organization has one owner); it
no longer refuses. The account settings name those organizations first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-11-23 22:26:20 +01:00
1 parent 61fdfa830a
commit 8d7c1f856c
38 files changed
+2033 -354

No files matched your search

+6 -3
View File
@@ -60,8 +60,11 @@ var endpoints = []endpoint{
{method: "GET", path: "/api/v1/me/export", tag: "Account", summary: "Export all personal data (GDPR Art. 15, 20)",
description: "`?format=pdf` returns a PDF instead of JSON.", resp: accountExport{}},
{method: "POST", path: "/api/v1/me/delete", tag: "Account", summary: "Delete the account (GDPR Art. 17)", sessionOnly: true,
description: "Refused with `owns_shared_orgs` while the user owns organizations with other members. Organizations only the user belongs to are deleted with the account.",
description: "Organizations the user owns are deleted with the account, with all their monitors, even when they have other members. Open to suspended accounts and to those that have not accepted the terms.",
req: deletionRequest{}, resp: obj{"status": ""}},
{method: "POST", path: "/api/v1/consent", tag: "Account", summary: "Accept the platform's privacy policy and terms", sessionOnly: true,
description: "`versions` are the versions shown, e.g. `privacy:12,terms:14`; `409 consent_outdated` when a document changed meanwhile. Until an account accepted the current versions, other requests of its sessions get `403 consent_required`.",
req: consentRequest{}, resp: obj{"redirect": ""}},
{method: "POST", path: "/api/v1/markdown/preview", tag: "Account", summary: "Render Markdown as pages will show it",
req: previewRequest{}, resp: obj{"html": ""}},
{method: "POST", path: "/api/v1/invitations/:token/accept", tag: "Account", summary: "Accept an invitation with the signed-in account", sessionOnly: true,
@@ -294,10 +297,10 @@ var endpoints = []endpoint{
perm: "platform admin", req: suspensionRequest{}, status: http.StatusNoContent},
{method: "DELETE", path: "/api/v1/admin/orgs/:id", tag: "Platform", summary: "Delete an organization with all its data", perm: "platform admin", status: http.StatusNoContent},
{method: "PUT", path: "/api/v1/admin/users/:id/suspension", tag: "Platform", summary: "Suspend or reinstate an account",
description: "A suspended account is signed out everywhere and can neither sign in nor use its API tokens. Platform admins cannot be suspended.",
description: "A suspended account is signed out everywhere and cannot use its API tokens; signing in again only lets it export or delete its data. Platform admins cannot be suspended.",
perm: "platform admin", req: suspensionRequest{}, status: http.StatusNoContent},
{method: "DELETE", path: "/api/v1/admin/users/:id", tag: "Platform", summary: "Delete an account",
description: "Organizations only the account belongs to are deleted with it; owning one shared with others gives 409 owns_shared_orgs. Platform admins cannot be deleted.",
description: "Organizations the account owns are deleted with it. Platform admins cannot be deleted.",
perm: "platform admin", status: http.StatusNoContent},
{method: "GET", path: "/api/v1/admin/regions", tag: "Platform", summary: "List platform regions", perm: "platform admin",
resp: obj{"regions": []regionView{}}},
+1
View File
@@ -37,6 +37,7 @@ var auditActions = map[string]string{
"POST /api/v1/auth/login": "auth.login",
"POST /api/v1/auth/login/totp": "auth.login",
"POST /api/v1/auth/logout": "auth.logout",
"POST /api/v1/consent": "account.consent",
"POST /api/v1/me/org": "",
"POST /api/v1/me/totp/setup": "",
"POST /api/v1/me/totp/enable": "account.totp_enable",
+16 -10
View File
@@ -35,6 +35,10 @@ type signupRequest struct {
// after confirming.
OrgName string `json:"org_name" binding:"max=200"`
OrgSlug string `json:"org_slug" binding:"max=63"`
// Consent accepts the platform's privacy policy and terms in the
// versions the form showed (ConsentVersions, "privacy:12,terms:14").
Consent bool `json:"consent"`
ConsentVersions string `json:"consent_versions" binding:"max=200"`
}
func (s *Server) signup(c *gin.Context) {
@@ -60,6 +64,10 @@ func (s *Server) signup(c *gin.Context) {
fail(c, http.StatusTooManyRequests, "signup_limit")
return
}
consent, ok := s.signupConsent(c, req.Consent, req.ConsentVersions)
if !ok {
return
}
verify := s.verificationRequired()
withOrg := !verify && strings.TrimSpace(req.OrgName) != "" && strings.TrimSpace(req.OrgSlug) != ""
hash, err := auth.HashPassword(req.Password)
@@ -103,6 +111,11 @@ func (s *Server) signup(c *gin.Context) {
}
return nil
})
if err == nil {
err = s.db.Tx(ctx, tenant.User(user.ID), func(q *store.Queries) error {
return recordConsent(ctx, q, user.ID, consent)
})
}
switch {
case isUniqueViolation(err, "users_email_key"), isUniqueViolation(err, "users_email_key_idx"):
fail(c, http.StatusConflict, "email_taken")
@@ -195,12 +208,9 @@ func (s *Server) login(c *gin.Context) {
invalidCredentials(c)
return
}
// Only someone who knows the password learns of the suspension or a
// missing confirmation.
if user.DisabledAt != nil {
fail(c, http.StatusForbidden, "account_suspended")
return
}
// Only someone who knows the password learns of a missing
// confirmation. Suspended accounts sign in, but only to export or
// delete their data.
if user.EmailVerifiedAt == nil {
fail(c, http.StatusForbidden, "email_unverified")
return
@@ -289,10 +299,6 @@ func (s *Server) finishLogin(c *gin.Context, userID uuid.UUID, method auth.Metho
internalError(c, err)
return
}
if user.DisabledAt != nil {
fail(c, http.StatusForbidden, "account_suspended")
return
}
var org uuid.UUID
if len(orgs) > 0 {
org = orgs[0].ID
+357
View File
@@ -0,0 +1,357 @@
package api
import (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"slices"
"strconv"
"strings"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
)
// Every account accepts the platform's privacy policy and terms in their
// current version: on sign-up, and otherwise right after signing in, again
// whenever a document asks for it. Until then, and while an account is
// suspended, it can only read the documents, export its data, delete
// itself and sign out.
// requiredConsent returns the current version of each document accounts
// accept; empty when the platform has none.
func (s *Server) requiredConsent(ctx context.Context) (map[string]int64, error) {
return s.consent.get(ctx, s.rdb, func(ctx context.Context) (map[string]int64, error) {
out := map[string]int64{}
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
rows, err := q.RequiredLegalVersions(ctx)
for _, r := range rows {
out[r.Kind] = r.Version
}
return err
})
return out, err
})
}
// consentVersions encodes versions for a form, e.g. "privacy:12,terms:14".
func consentVersions(v map[string]int64) string {
var parts []string
for _, kind := range web.ConsentKinds {
if n, ok := v[kind]; ok {
parts = append(parts, kind+":"+strconv.FormatInt(n, 10))
}
}
return strings.Join(parts, ",")
}
func parseConsentVersions(s string) map[string]int64 {
out := map[string]int64{}
for part := range strings.SplitSeq(s, ",") {
kind, n, ok := strings.Cut(strings.TrimSpace(part), ":")
if v, err := strconv.ParseInt(n, 10, 64); ok && err == nil {
out[kind] = v
}
}
return out
}
// errConsentOutdated reports an acceptance of versions that are no longer
// current: a document changed while the form was open.
var errConsentOutdated = errors.New("api: consent for outdated documents")
// checkConsent verifies that accepted covers exactly the documents
// required right now.
func checkConsent(required, accepted map[string]int64) error {
for kind, v := range required {
if accepted[kind] != v {
return errConsentOutdated
}
}
return nil
}
func recordConsent(ctx context.Context, q *store.Queries, user uuid.UUID, versions map[string]int64) error {
for kind, v := range versions {
if err := q.AcceptLegal(ctx, store.AcceptLegalParams{UserID: user, Kind: kind, Version: v}); err != nil {
return err
}
}
return nil
}
// access is what an account may do in the console.
type access struct {
suspended bool
reason string
// missing are the documents still to accept, with their versions.
missing map[string]int64
}
func (a access) restricted() bool { return a.suspended || len(a.missing) > 0 }
func (s *Server) accessOf(ctx context.Context, user uuid.UUID) (access, error) {
required, err := s.requiredConsent(ctx)
if err != nil {
return access{}, err
}
var a access
err = s.db.Tx(ctx, tenant.User(user), func(q *store.Queries) error {
u, err := q.GetUser(ctx, user)
if err != nil {
return err
}
if u.DisabledAt != nil {
a.suspended, a.reason = true, u.DisabledReason
}
if len(required) == 0 {
return nil
}
accepted, err := q.AcceptedLegalVersions(ctx, user)
if err != nil {
return err
}
for kind, v := range required {
if !slices.ContainsFunc(accepted, func(r store.AcceptedLegalVersionsRow) bool { return r.Kind == kind && r.Version == v }) {
if a.missing == nil {
a.missing = map[string]int64{}
}
a.missing[kind] = v
}
}
return nil
})
return a, err
}
// restrictedPaths stay open to accounts that are suspended or have yet to
// accept the documents. Admins keep editing the documents, which they may
// be publishing one after the other; the handlers still check they are.
var restrictedPaths = []string{
"/consent", "/account/suspended", "/legal/",
"/api/v1/auth/", "/api/v1/consent", "/api/v1/me/export", "/api/v1/me/delete", "/api/v1/locale",
"/admin/legal", "/api/v1/admin/legal/",
}
func allowedRestricted(path string) bool {
return slices.ContainsFunc(restrictedPaths, func(p string) bool {
return path == p || (strings.HasSuffix(p, "/") && strings.HasPrefix(path, p))
})
}
// accountGate keeps restricted accounts on the consent or suspension page.
func (s *Server) accountGate() gin.HandlerFunc {
return func(c *gin.Context) {
sess := auth.Current(c)
path := c.Request.URL.Path
if sess == nil || allowedRestricted(path) {
c.Next()
return
}
a, err := s.accessOf(c.Request.Context(), sess.UserID)
switch {
case err != nil:
internalError(c, err)
c.Abort()
return
case !a.restricted():
c.Next()
return
}
if strings.HasPrefix(path, "/api/") {
code := "consent_required"
if a.suspended {
code = "account_suspended"
}
fail(c, http.StatusForbidden, code)
c.Abort()
return
}
target := "/account/suspended"
if !a.suspended {
target = "/consent?next=" + url.QueryEscape(c.Request.URL.RequestURI())
}
c.Redirect(http.StatusSeeOther, target)
c.Abort()
}
}
// localNext keeps a redirect target on this site.
func localNext(next string) string {
if !strings.HasPrefix(next, "/") || strings.HasPrefix(next, "//") || strings.HasPrefix(next, "/\\") {
return "/"
}
return next
}
type consentRequest struct {
// Versions are the documents accepted, as shown: "privacy:12,terms:14".
Versions string `json:"versions" binding:"max=200"`
Next string `json:"next" binding:"max=2000"`
}
// acceptConsent records that the signed-in account accepts the current
// documents.
func (s *Server) acceptConsent(c *gin.Context) {
var req consentRequest
if !bind(c, &req) {
return
}
sess := auth.Current(c)
if sess == nil {
fail(c, http.StatusUnauthorized, "unauthenticated")
return
}
ctx := c.Request.Context()
required, err := s.requiredConsent(ctx)
if err != nil {
internalError(c, err)
return
}
accepted := parseConsentVersions(req.Versions)
if err := checkConsent(required, accepted); err != nil {
fail(c, http.StatusConflict, "consent_outdated")
return
}
auditDetail(c, "versions", consentVersions(required))
if err := s.db.Tx(ctx, tenant.User(sess.UserID), func(q *store.Queries) error {
return recordConsent(ctx, q, sess.UserID, required)
}); err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"redirect": localNext(req.Next)})
}
// consentDocs lists the documents of versions with their links.
func (s *Server) consentDocs(ctx context.Context, versions map[string]int64) []web.LegalLink {
var docs []web.LegalLink
for _, l := range web.LegalLinks(s.platformLegalDocs(ctx), "/legal/") {
if _, ok := versions[l.Kind]; ok {
docs = append(docs, l)
}
}
return docs
}
// restrictedMe is the account data the consent and suspension pages show,
// with the organizations its deletion would take along.
func (s *Server) restrictedMe(c *gin.Context, sess *auth.Session) (web.Me, error) {
m, err := s.loadMe(c.Request.Context(), sess)
if err != nil {
return web.Me{}, err
}
me := toWebMe(m)
me.DeletesOrgs, err = s.ownedOrgs(c.Request.Context(), sess.UserID)
return me, err
}
func (s *Server) consentPage(c *gin.Context) {
sess := auth.Current(c)
if sess == nil {
c.Redirect(http.StatusSeeOther, "/login")
return
}
next := localNext(c.Query("next"))
a, err := s.accessOf(c.Request.Context(), sess.UserID)
if err != nil {
internalError(c, err)
return
}
if a.suspended {
c.Redirect(http.StatusSeeOther, "/account/suspended")
return
}
if len(a.missing) == 0 {
c.Redirect(http.StatusSeeOther, next)
return
}
me, err := s.restrictedMe(c, sess)
if err != nil {
internalError(c, err)
return
}
required, err := s.requiredConsent(c.Request.Context())
if err != nil {
internalError(c, err)
return
}
web.Render(c, http.StatusOK, web.ConsentPage(s.pageFor(c, "consent.title"), me,
s.consentDocs(c.Request.Context(), a.missing), consentVersions(required), next))
}
func (s *Server) suspendedPage(c *gin.Context) {
sess := auth.Current(c)
if sess == nil {
c.Redirect(http.StatusSeeOther, "/login")
return
}
a, err := s.accessOf(c.Request.Context(), sess.UserID)
if err != nil {
internalError(c, err)
return
}
if !a.suspended {
c.Redirect(http.StatusSeeOther, "/")
return
}
me, err := s.restrictedMe(c, sess)
if err != nil {
internalError(c, err)
return
}
web.Render(c, http.StatusOK, web.SuspendedPage(s.pageFor(c, "suspended.title"), me, a.reason))
}
// signupConsent checks the consent given on a sign-up form and returns the
// versions to record.
func (s *Server) signupConsent(c *gin.Context, given bool, versions string) (map[string]int64, bool) {
required, err := s.requiredConsent(c.Request.Context())
if err != nil {
internalError(c, err)
return nil, false
}
if len(required) == 0 {
return nil, true
}
if !given {
fail(c, http.StatusUnprocessableEntity, "consent_required")
return nil, false
}
if err := checkConsent(required, parseConsentVersions(versions)); err != nil {
fail(c, http.StatusConflict, "consent_outdated")
return nil, false
}
return required, true
}
// signupConsentView is what sign-up forms show: the documents to accept
// and their versions.
func (s *Server) signupConsentView(ctx context.Context) (web.SignupConsent, error) {
required, err := s.requiredConsent(ctx)
if err != nil || len(required) == 0 {
return web.SignupConsent{}, err
}
return web.SignupConsent{Docs: s.consentDocs(ctx, required), Versions: consentVersions(required)}, nil
}
// ownedOrgs names the organizations user owns, which deleting the account
// deletes too.
func (s *Server) ownedOrgs(ctx context.Context, user uuid.UUID) ([]string, error) {
var out []string
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
owned, err := q.OwnedOrgs(ctx, user)
for _, o := range owned {
out = append(out, fmt.Sprintf("%s (%s)", o.Name, o.Slug))
}
return err
})
return out, err
}
+193
View File
@@ -0,0 +1,193 @@
package api_test
import (
"context"
"net/http"
"strings"
"testing"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/sso/ssotest"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
)
func TestConsent(t *testing.T) {
e := newEnv(t)
ctx := context.Background()
admin := e.browser(t)
admin.signup("a@"+uniq("cs")+".test", uniq("cs-"))
if err := tenant.New(e.dbPool).Tx(ctx, tenant.Global(), func(q *store.Queries) error {
return q.MakeAdmin(ctx, admin.userIDSelf())
}); err != nil {
t.Fatal(err)
}
earlier := e.browser(t)
earlier.signup("e@"+uniq("cs")+".test", uniq("cs-"))
t.Cleanup(func() { clearPlatformLegal(admin) })
for kind, text := range map[string]string{"privacy": "# Datenschutz", "terms": "# AGB"} {
if st, body := admin.do("PUT", "/api/v1/admin/legal/"+kind, map[string]any{"markdown": text}); st != http.StatusNoContent {
t.Fatalf("set %s = %d %v", kind, st, body)
}
}
admin.acceptConsent()
if _, _, html := e.browser(t).page("/login"); !strings.Contains(html, `href="/legal/terms"`) {
t.Error("the footer lacks the terms")
}
if st, body := admin.do("PUT", "/api/v1/org/legal/terms", map[string]any{"markdown": "x"}); st != http.StatusNotFound {
t.Errorf("organization sets terms = %d %v, want 404", st, body)
}
// Signing up needs the box ticked for the versions shown.
visitor := e.browser(t)
_, _, form := visitor.page("/signup")
versions := consentShown(form)
if !strings.Contains(versions, "privacy:") || !strings.Contains(versions, "terms:") || !strings.Contains(form, `name="consent" required`) {
t.Fatalf("sign-up form lacks the consent box: versions %q", versions)
}
signup := func(consent bool, versions string) (int, map[string]any) {
return e.browser(t).do("POST", "/api/v1/auth/signup", map[string]any{
"email": uniq("n") + "@example.test", "password": password, "consent": consent, "consent_versions": versions,
})
}
st, body := signup(false, versions)
expect(t, "sign up without consent", st, body, http.StatusUnprocessableEntity, "consent_required")
st, body = signup(true, "privacy:1,terms:1")
expect(t, "sign up with outdated versions", st, body, http.StatusConflict, "consent_outdated")
email := uniq("n") + "@example.test"
fresh := e.browser(t)
if st, body := fresh.do("POST", "/api/v1/auth/signup", map[string]any{
"email": email, "password": password, "consent": true, "consent_versions": versions,
}); st != http.StatusOK {
t.Fatalf("sign up with consent = %d %v", st, body)
}
freshID := fresh.userIDSelf()
if n := e.count(t, `SELECT count(*) FROM legal_acceptances WHERE user_id = $1`, freshID); n != 2 {
t.Errorf("recorded %d acceptances, want 2", n)
}
if got := fresh.visit("/"); got.Path == "/consent" {
t.Error("an account that accepted on sign-up is asked again")
}
// Accounts from before have to accept first; until then they can read
// the documents, take their data along and sign out.
if got := earlier.visit("/"); got.Path != "/consent" || got.Query().Get("next") != "/" {
t.Errorf("console before consent landed on %s", got)
}
st, body = earlier.do("GET", "/api/v1/org/monitors", nil)
expect(t, "API before consent", st, body, http.StatusForbidden, "consent_required")
for _, path := range []string{"/legal/terms", "/api/v1/me/export"} {
if st, _, _ := earlier.page(path); st != http.StatusOK {
t.Errorf("GET %s before consent = %d", path, st)
}
}
_, _, page := earlier.page("/consent")
if !strings.Contains(page, "Delete account") || !strings.Contains(page, `href="/legal/terms"`) {
t.Error("the consent page offers no way out or lacks the documents")
}
st, body = earlier.do("POST", "/api/v1/consent", map[string]any{"versions": "terms:1", "next": "/"})
expect(t, "accept outdated versions", st, body, http.StatusConflict, "consent_outdated")
if st, body := earlier.do("POST", "/api/v1/consent", map[string]any{"versions": consentShown(page), "next": "//evil.example"}); st != http.StatusOK || body["redirect"] != "/" {
t.Errorf("accept = %d %v, want a local redirect", st, body)
}
if st, _ := earlier.do("GET", "/api/v1/org/monitors", nil); st != http.StatusOK {
t.Errorf("API after consent = %d", st)
}
// A correction asks nobody again; a new version asks everyone.
admin.do("PUT", "/api/v1/admin/legal/terms", map[string]any{"markdown": "# AGB\n\nTippfehler behoben"})
if got := earlier.visit("/"); got.Path == "/consent" {
t.Error("a correction asked for consent again")
}
admin.do("PUT", "/api/v1/admin/legal/terms", map[string]any{"markdown": "# AGB v2", "new_version": true})
if got := earlier.visit("/"); got.Path != "/consent" {
t.Errorf("a new version of the terms was not put before the account: %s", got)
}
if _, _, page := earlier.page("/consent"); !strings.Contains(page, `href="/legal/terms"`) || strings.Contains(page, `<li><a href="/legal/privacy"`) {
t.Error("the consent page should list only the changed terms")
}
earlier.acceptConsent()
admin.acceptConsent()
// An account created through a sign-in provider is asked right after
// its first sign-in.
idp := ssotest.New(t)
st, provider := admin.do("POST", "/api/v1/admin/identity-providers", map[string]any{
"kind": "oidc", "name": "IdP", "issuer": idp.Issuer(), "client_id": idp.ClientID, "client_secret": idp.Secret,
"allow_signup": true, "enabled": true,
})
if st != http.StatusCreated {
t.Fatalf("create provider = %d %v", st, provider)
}
t.Cleanup(func() {
_ = e.asSystem(t, func(tx pgx.Tx) error {
_, err := tx.Exec(ctx, `DELETE FROM platform_identity_providers WHERE id = $1`, provider["id"])
return err
})
})
idp.SetUser(ssotest.User{Subject: uniq("sub"), Email: uniq("sso") + "@example.test", EmailVerified: true})
viaSSO := e.browser(t)
if got := viaSSO.visit("/login/sso/" + provider["id"].(string)); got.Path != "/consent" {
t.Errorf("SSO sign-up landed on %s, want the consent page", got)
}
viaSSO.acceptConsent()
if got := viaSSO.visit("/"); got.Path != "/orgs/new" {
t.Errorf("after consenting the new SSO account landed on %s, want /orgs/new", got)
}
}
func TestSuspendedAccount(t *testing.T) {
e := newEnv(t)
ctx := context.Background()
admin := e.browser(t)
admin.signup("a@"+uniq("su")+".test", uniq("su-"))
if err := tenant.New(e.dbPool).Tx(ctx, tenant.Global(), func(q *store.Queries) error {
return q.MakeAdmin(ctx, admin.userIDSelf())
}); err != nil {
t.Fatal(err)
}
email := "s@" + uniq("su") + ".test"
user := e.browser(t)
user.signup(email, uniq("su-"))
userID := user.userIDSelf()
org := uuid.MustParse(user.orgID())
user.do("POST", "/api/v1/org/monitors", map[string]any{"name": "web", "type": "heartbeat", "interval_seconds": 3600})
_, tok := user.do("POST", "/api/v1/org/tokens", map[string]any{"name": "ci", "permissions": []string{"monitors.read"}})
if st, body := admin.do("PUT", "/api/v1/admin/users/"+userID.String()+"/suspension", map[string]any{"suspended": true, "reason": "Unpaid invoice"}); st != http.StatusNoContent {
t.Fatalf("suspend = %d %v", st, body)
}
api := &browser{t: t, base: user.base, hc: e.srv.Client(), bearer: tok["token"].(string)}
if st, _ := api.do("GET", "/api/v1/org/monitors", nil); st != http.StatusUnauthorized {
t.Errorf("API token of a suspended account = %d, want 401", st)
}
// It signs in again, but only to take its data along or delete itself.
back := e.browser(t)
if st, body := back.do("POST", "/api/v1/auth/login", map[string]any{"email": email, "password": password}); st != http.StatusOK {
t.Fatalf("suspended account signs in = %d %v", st, body)
}
if got := back.visit("/"); got.Path != "/account/suspended" {
t.Errorf("console of a suspended account landed on %s", got)
}
_, _, page := back.page("/account/suspended")
if !strings.Contains(page, "Unpaid invoice") || !strings.Contains(page, "Delete account") || !strings.Contains(page, "You own these organizations") {
t.Error("the suspension page lacks the reason or the way out")
}
st, body := back.do("GET", "/api/v1/org/monitors", nil)
expect(t, "API of a suspended account", st, body, http.StatusForbidden, "account_suspended")
if st, _, _ := back.page("/api/v1/me/export"); st != http.StatusOK {
t.Errorf("export of a suspended account = %d", st)
}
if st, body := back.do("POST", "/api/v1/me/delete", map[string]any{"password": password}); st != http.StatusOK {
t.Fatalf("suspended account deletes itself = %d %v", st, body)
}
for q, arg := range map[string]any{`SELECT count(*) FROM users WHERE id = $1`: userID, `SELECT count(*) FROM orgs WHERE id = $1`: org, `SELECT count(*) FROM monitors WHERE org_id = $1`: org} {
if n := e.count(t, q, arg); n != 0 {
t.Errorf("%s = %d after deletion", q, n)
}
}
}
+29 -25
View File
@@ -31,9 +31,17 @@ type accountExport struct {
Organizations []exportMembership `json:"organizations"`
Identities []exportIdentity `json:"sso_identities"`
Tokens []exportToken `json:"api_tokens"`
Consents []exportConsent `json:"consents"`
Activity []exportActivity `json:"activity"`
}
// exportConsent is an accepted version of the privacy policy or terms.
type exportConsent struct {
Kind string `json:"kind"`
Version int64 `json:"version"`
AcceptedAt time.Time `json:"accepted_at"`
}
type exportAccount struct {
ID uuid.UUID `json:"id"`
Email string `json:"email"`
@@ -133,6 +141,14 @@ func (s *Server) buildAccountExport(ctx context.Context, userID uuid.UUID) (acco
if err != nil {
return err
}
consents, err := q.LegalAcceptances(ctx, u.ID)
if err != nil {
return err
}
x.Consents = []exportConsent{}
for _, r := range consents {
x.Consents = append(x.Consents, exportConsent{Kind: r.Kind, Version: r.Version, AcceptedAt: r.AcceptedAt})
}
x.Tokens = []exportToken{}
for _, t := range toks {
x.Tokens = append(x.Tokens, exportToken{
@@ -586,9 +602,12 @@ func purgeOrg(ctx context.Context, q *store.Queries, org uuid.UUID) error {
return err
}
// deleteAccount erases the signed-in user (Art. 17). Organizations only the
// user belongs to go with the account; an organization shared with others
// must be handed over or deleted first, so nobody loses access to it.
// deleteAccount erases the signed-in user (Art. 17). Organizations the
// user owns go with the account, monitors and all, even when they have
// other members: an organization has exactly one owner, and nobody would be
// left to run it.
// Suspended accounts and those that have not accepted the terms may do
// this too.
func (s *Server) deleteAccount(c *gin.Context) {
var req deletionRequest
if !bind(c, &req) {
@@ -609,17 +628,11 @@ func (s *Server) deleteAccount(c *gin.Context) {
fail(c, http.StatusForbidden, "confirmation_failed")
return
}
shared, orgsDeleted, err := s.eraseAccount(ctx, u)
orgsDeleted, err := s.eraseAccount(ctx, u)
if err != nil {
internalError(c, err)
return
}
if len(shared) > 0 {
c.JSON(http.StatusConflict, gin.H{
"error": "owns_shared_orgs", "message": i18n.T(ctx, "error.owns_shared_orgs"), "organizations": shared,
})
return
}
auth.ClearCookie(c)
// Kept as proof of erasure, without saying whose.
s.writeAudit(c, store.InsertAuditEventParams{Kind: "platform", Action: "account.delete", Status: http.StatusOK},
@@ -627,23 +640,14 @@ func (s *Server) deleteAccount(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": "deleted"})
}
// eraseAccount deletes u with the organizations only u belongs to and
// ends u's sessions. If u owns organizations shared with others, nothing
// is deleted and their slugs are returned.
func (s *Server) eraseAccount(ctx context.Context, u store.User) (shared []string, orgsDeleted int, err error) {
// eraseAccount deletes u with the organizations u owns and ends u's
// sessions; u leaves the others.
func (s *Server) eraseAccount(ctx context.Context, u store.User) (orgsDeleted int, err error) {
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
owned, err := q.OwnedOrgs(ctx, u.ID)
if err != nil {
return err
}
for _, o := range owned {
if o.Members > 1 {
shared = append(shared, o.Slug)
}
}
if len(shared) > 0 {
return nil
}
for _, o := range owned {
if err := purgeOrg(ctx, q, o.ID); err != nil {
return err
@@ -663,13 +667,13 @@ func (s *Server) eraseAccount(ctx context.Context, u store.User) (shared []strin
}
return nil
})
if err != nil || len(shared) > 0 {
return shared, 0, err
if err != nil {
return 0, err
}
if err := s.sessions.DeleteAllForUser(ctx, u.ID); err != nil {
s.log.ErrorContext(ctx, "ending sessions of deleted account failed", "error", err)
}
return nil, orgsDeleted, nil
return orgsDeleted, nil
}
type orgDeletionRequest struct {
+20 -4
View File
@@ -228,10 +228,6 @@ func TestDeleteAccount(t *testing.T) {
memberID := member.userIDSelf()
member.do("POST", "/api/v1/org/groups", map[string]any{"name": "By member"})
// An owner of a shared organization must hand it over first.
if st, body := owner.do("POST", "/api/v1/me/delete", map[string]any{"password": password}); st != http.StatusConflict || body["error"] != "owns_shared_orgs" {
t.Errorf("owner of shared org deletes account = %d %v, want 409", st, body)
}
if st, _ := member.do("POST", "/api/v1/me/delete", map[string]any{"password": "wrong password"}); st != http.StatusForbidden {
t.Errorf("wrong password = %d, want 403", st)
}
@@ -273,4 +269,24 @@ func TestDeleteAccount(t *testing.T) {
if e.count(t, `SELECT count(*) FROM orgs WHERE id = $1`, soloOrg) != 0 {
t.Error("sole owner's organization survived")
}
// The owner takes the organization along, monitors and all, even when
// others still belong to it; the security page says so first.
org := uuid.MustParse(owner.orgID())
owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": "web", "type": "heartbeat", "interval_seconds": 3600})
other := e.joinVia(t, owner.invite("x@"+uniq("da")+".test", owner.roleID("viewer")))
if _, _, html := owner.page("/settings/security"); !strings.Contains(html, "You own these organizations") {
t.Error("the security page does not warn that the organization goes with the account")
}
if st, body := owner.do("POST", "/api/v1/me/delete", map[string]any{"password": password}); st != http.StatusOK {
t.Fatalf("last owner deletes account = %d %v", st, body)
}
for _, q := range []string{`SELECT count(*) FROM orgs WHERE id = $1`, `SELECT count(*) FROM monitors WHERE org_id = $1`} {
if n := e.count(t, q, org); n != 0 {
t.Errorf("%s = %d after the last owner left", q, n)
}
}
if st, me := other.do("GET", "/api/v1/me", nil); st != http.StatusOK || len(me["orgs"].([]any)) != 0 {
t.Errorf("remaining member = %d %v, want an account without the organization", st, me)
}
}
+17 -2
View File
@@ -244,8 +244,10 @@ func (s *Server) acceptInvitation(c *gin.Context) {
}
type inviteSignupRequest struct {
DisplayName string `json:"display_name" binding:"max=200"`
Password string `json:"password" binding:"required,max=1024"`
DisplayName string `json:"display_name" binding:"max=200"`
Password string `json:"password" binding:"required,max=1024"`
Consent bool `json:"consent"`
ConsentVersions string `json:"consent_versions" binding:"max=200"`
}
// inviteSignup creates an account for an invited address. It bypasses
@@ -268,6 +270,10 @@ func (s *Server) inviteSignup(c *gin.Context) {
fail(c, http.StatusGone, "invitation_invalid")
return
}
consent, ok := s.signupConsent(c, req.Consent, req.ConsentVersions)
if !ok {
return
}
hash, err := auth.HashPassword(req.Password)
if errors.Is(err, auth.ErrPasswordTooShort) {
fail(c, http.StatusUnprocessableEntity, "password_too_short", "Min", auth.MinPasswordLength)
@@ -288,6 +294,11 @@ func (s *Server) inviteSignup(c *gin.Context) {
})
return err
})
if err == nil {
err = s.db.Tx(ctx, tenant.User(user.ID), func(q *store.Queries) error {
return recordConsent(ctx, q, user.ID, consent)
})
}
if isUniqueViolation(err, "users_email_key") || isUniqueViolation(err, "users_email_key_idx") {
fail(c, http.StatusConflict, "email_taken")
return
@@ -341,5 +352,9 @@ func (s *Server) invitePage(c *gin.Context) {
}
}
}
if view.Consent, err = s.signupConsentView(ctx); err != nil {
internalError(c, err)
return
}
web.Render(c, http.StatusOK, web.InvitationPage(s.pageFor(c, "invite.title"), view))
}
+34 -11
View File
@@ -51,11 +51,20 @@ func (s *Server) platformLegalDocs(ctx context.Context) []agentapi.LegalDoc {
return docs
}
func validLegalKind(kind string) bool { return slices.Contains(web.LegalKinds, kind) }
// legalKinds are the documents org (nil: the platform) can set.
func legalKinds(org *uuid.UUID) []string {
if org == nil {
return web.LegalKinds
}
return web.OrgLegalKinds
}
type legalRequest struct {
URL string `json:"url" binding:"max=2000"`
Markdown string `json:"markdown" binding:"max=100000"`
// NewVersion asks every account to accept the platform's privacy
// policy or terms again.
NewVersion bool `json:"new_version"`
}
// validLegalURL accepts absolute http and https URLs only, so a stored link
@@ -69,7 +78,7 @@ func validLegalURL(raw string) bool {
// nil for the platform.
func (s *Server) saveLegal(c *gin.Context, scope tenant.Scope, org *uuid.UUID) bool {
kind := c.Param("kind")
if !validLegalKind(kind) {
if !slices.Contains(legalKinds(org), kind) {
fail(c, http.StatusNotFound, "not_found")
return false
}
@@ -83,12 +92,16 @@ func (s *Server) saveLegal(c *gin.Context, scope tenant.Scope, org *uuid.UUID) b
return false
}
auditDetail(c, "kind", kind)
newVersion := req.NewVersion && org == nil && slices.Contains(web.ConsentKinds, kind)
if newVersion {
auditDetail(c, "new_version", "true")
}
ctx := c.Request.Context()
err := s.db.Tx(ctx, scope, func(q *store.Queries) error {
if req.URL == "" && req.Markdown == "" {
return q.DeleteLegalDocument(ctx, store.DeleteLegalDocumentParams{OrgID: org, Kind: kind})
}
return q.UpsertLegalDocument(ctx, store.UpsertLegalDocumentParams{OrgID: org, Kind: kind, Url: req.URL, Markdown: req.Markdown})
return q.UpsertLegalDocument(ctx, store.UpsertLegalDocumentParams{OrgID: org, Kind: kind, Url: req.URL, Markdown: req.Markdown, NewVersion: newVersion})
})
if err != nil {
internalError(c, err)
@@ -100,8 +113,11 @@ func (s *Server) saveLegal(c *gin.Context, scope tenant.Scope, org *uuid.UUID) b
func (s *Server) adminSaveLegal(c *gin.Context) {
if s.saveLegal(c, tenant.System(), nil) {
if err := s.legal.bump(c.Request.Context(), s.rdb); err != nil {
s.log.ErrorContext(c.Request.Context(), "announcing legal document change failed", "error", err)
ctx := c.Request.Context()
for _, err := range []error{s.legal.bump(ctx, s.rdb), s.consent.bump(ctx, s.rdb)} {
if err != nil {
s.log.ErrorContext(ctx, "announcing legal document change failed", "error", err)
}
}
}
}
@@ -115,6 +131,8 @@ type legalView struct {
Kind string `json:"kind"`
URL string `json:"url"`
Markdown string `json:"markdown"`
// Version changes whenever accounts have to accept the document again.
Version int64 `json:"version,omitempty"`
}
// ownLegal returns the documents stored for org (nil: the platform),
@@ -126,12 +144,15 @@ func (s *Server) ownLegal(ctx context.Context, scope tenant.Scope, org *uuid.UUI
rows, err = q.LegalDocuments(ctx, org)
return err
})
out := make([]legalView, 0, len(web.LegalKinds))
for _, kind := range web.LegalKinds {
out := make([]legalView, 0, len(legalKinds(org)))
for _, kind := range legalKinds(org) {
v := legalView{Kind: kind}
for _, r := range rows {
if r.Kind == kind && (r.OrgID == nil) == (org == nil) {
v.URL, v.Markdown = r.Url, r.Markdown
if org == nil && slices.Contains(web.ConsentKinds, kind) {
v.Version = r.Version
}
}
}
out = append(out, v)
@@ -190,10 +211,12 @@ func (s *Server) legalPage(c *gin.Context) {
c.Status(http.StatusNotFound)
}
func toLegalForms(docs []legalView) []web.LegalForm {
// toLegalForms prepares the forms; the platform's privacy policy and terms
// can ask everyone to accept them again.
func toLegalForms(docs []legalView, platform bool) []web.LegalForm {
out := make([]web.LegalForm, len(docs))
for i, d := range docs {
out[i] = web.LegalForm{Kind: d.Kind, URL: d.URL, Markdown: d.Markdown}
out[i] = web.LegalForm{Kind: d.Kind, URL: d.URL, Markdown: d.Markdown, Consent: platform && slices.Contains(web.ConsentKinds, d.Kind)}
}
return out
}
@@ -203,7 +226,7 @@ func (s *Server) orgLegalView(c *gin.Context, p *principal, page web.Page, me we
if err != nil {
return nil, err
}
return web.LegalSettingsPage(page, me, "legal.org_title", "legal.org_intro", "/org/legal/", "/settings/legal", toLegalForms(docs)), nil
return web.LegalSettingsPage(page, me, "legal.org_title", "legal.org_intro", "/org/legal/", "/settings/legal", toLegalForms(docs, false)), nil
}
func (s *Server) adminLegalPage(c *gin.Context) {
@@ -216,5 +239,5 @@ func (s *Server) adminLegalPage(c *gin.Context) {
internalError(c, err)
return
}
web.Render(c, http.StatusOK, web.LegalSettingsPage(s.pageFor(c, "legal.platform_title"), me, "legal.platform_title", "legal.platform_intro", "/admin/legal/", "/admin/legal", toLegalForms(docs)))
web.Render(c, http.StatusOK, web.LegalSettingsPage(s.pageFor(c, "legal.platform_title"), me, "legal.platform_title", "legal.platform_intro", "/admin/legal/", "/admin/legal", toLegalForms(docs, true)))
}
+15 -7
View File
@@ -21,11 +21,7 @@ func TestLegalDocuments(t *testing.T) {
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
for _, kind := range []string{"imprint", "privacy"} {
admin.do("PUT", "/api/v1/admin/legal/"+kind, map[string]any{})
}
})
t.Cleanup(func() { clearPlatformLegal(admin) })
imprint := "# Impressum\n\nBetreiber GmbH <script>alert(1)</script>"
st, body := admin.do("PUT", "/api/v1/admin/legal/imprint", map[string]any{"markdown": imprint})
@@ -34,7 +30,8 @@ func TestLegalDocuments(t *testing.T) {
expect(t, "javascript link", st, body, http.StatusUnprocessableEntity, "invalid_legal_url")
st, body = admin.do("PUT", "/api/v1/admin/legal/privacy", map[string]any{"url": "https://operator.example/privacy"})
expect(t, "admin sets privacy link", st, body, http.StatusNoContent, "")
st, body = admin.do("PUT", "/api/v1/admin/legal/terms", map[string]any{"markdown": "x"})
admin.acceptConsent()
st, body = admin.do("PUT", "/api/v1/admin/legal/cookies", map[string]any{"markdown": "x"})
expect(t, "unknown kind", st, body, http.StatusNotFound, "not_found")
// The console footer links them, also before signing in.
@@ -121,7 +118,7 @@ func TestLegalChangeReachesOtherReplicas(t *testing.T) {
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { admin.do("PUT", "/api/v1/admin/legal/imprint", map[string]any{}) })
t.Cleanup(func() { clearPlatformLegal(admin) })
admin.do("PUT", "/api/v1/admin/legal/imprint", map[string]any{})
visitor := b.browser(t)
@@ -147,3 +144,14 @@ func TestMarkdownPreview(t *testing.T) {
t.Errorf("preview = %d %q", st, html)
}
}
// clearPlatformLegal removes the platform's documents again, so other tests
// sign up without consent.
func clearPlatformLegal(admin *browser) {
admin.acceptConsent()
for _, kind := range []string{"imprint", "privacy", "terms"} {
if st, body := admin.do("PUT", "/api/v1/admin/legal/"+kind, map[string]any{}); st != http.StatusNoContent {
admin.t.Errorf("clearing platform %s = %d %v", kind, st, body)
}
}
}
+1 -8
View File
@@ -11,7 +11,6 @@ import (
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
@@ -262,17 +261,11 @@ func (s *Server) adminDeleteUser(c *gin.Context) {
return
}
ctx := c.Request.Context()
shared, orgsDeleted, err := s.eraseAccount(ctx, u)
orgsDeleted, err := s.eraseAccount(ctx, u)
if err != nil {
internalError(c, err)
return
}
if len(shared) > 0 {
c.JSON(http.StatusConflict, gin.H{
"error": "owns_shared_orgs", "message": i18n.T(ctx, "error.user_owns_shared_orgs"), "organizations": shared,
})
return
}
auditDetail(c, "organizations_deleted", orgsDeleted)
c.Status(http.StatusNoContent)
}
+7 -9
View File
@@ -140,7 +140,8 @@ func TestModeration(t *testing.T) {
t.Error("a heartbeat after reinstatement is not recorded")
}
// A suspended account is signed out and kept out, tokens included.
// A suspended account is signed out, its tokens stop working, and
// signing in again only lets it export or delete its data.
suspend("users/"+userID, true, "")
if st, _ := owner.do("GET", "/api/v1/me", nil); st != http.StatusUnauthorized {
t.Errorf("session of a suspended account = %d", st)
@@ -149,8 +150,11 @@ func TestModeration(t *testing.T) {
t.Errorf("token of a suspended account = %d", st)
}
fresh := e.browser(t)
st, body = fresh.do("POST", "/api/v1/auth/login", map[string]any{"email": ownerEmail, "password": testPassword})
expect(t, "sign-in of a suspended account", st, body, http.StatusForbidden, "account_suspended")
if st, body := fresh.do("POST", "/api/v1/auth/login", map[string]any{"email": ownerEmail, "password": testPassword}); st != http.StatusOK {
t.Errorf("sign-in of a suspended account = %d %v", st, body)
}
st, body = fresh.do("GET", "/api/v1/org/monitors", nil)
expect(t, "API of a suspended account", st, body, http.StatusForbidden, "account_suspended")
if st, _ := e.browser(t).do("POST", "/api/v1/auth/login", map[string]any{"email": ownerEmail, "password": "wrong password"}); st != http.StatusUnauthorized {
t.Error("a wrong password reveals the suspension")
}
@@ -165,12 +169,6 @@ func TestModeration(t *testing.T) {
st, body = admin.do("DELETE", "/api/v1/admin/users/"+admin.userIDSelf().String(), nil)
expect(t, "delete an admin", st, body, http.StatusConflict, "target_is_admin")
// An owner of a shared organization cannot be deleted before it.
fresh.do("POST", "/api/v1/me/org", map[string]any{"org_id": orgID})
e.joinVia(t, fresh.invite("m@"+uniq("mod")+".test", fresh.roleID("viewer")))
st, body = admin.do("DELETE", "/api/v1/admin/users/"+userID, nil)
expect(t, "delete the owner of a shared org", st, body, http.StatusConflict, "owns_shared_orgs")
// Deleting: page, organization, account.
if st, _ := admin.do("DELETE", "/api/v1/admin/status-pages/"+page["id"].(string), nil); st != http.StatusNoContent || served() {
t.Errorf("delete page = %d", st)
+12 -1
View File
@@ -48,6 +48,8 @@ func (s *Server) registerPages(r gin.IRouter) {
r.GET("/admin/legal", s.adminLegalPage)
r.GET("/settings/legal", s.orgPage("legal.org_title", authz.OrgManage, s.orgLegalView))
r.GET("/legal/:kind", s.legalPage)
r.GET("/consent", s.consentPage)
r.GET("/account/suspended", s.suspendedPage)
}
// flashErrors lists the codes a redirect may ask a page to display. Anything
@@ -123,7 +125,12 @@ func (s *Server) signupPage(c *gin.Context) {
c.Redirect(http.StatusSeeOther, "/login")
return
}
web.Render(c, http.StatusOK, web.Signup(s.pageFor(c, "auth.signup.title"), providers, email))
consent, err := s.signupConsentView(c.Request.Context())
if err != nil {
internalError(c, err)
return
}
web.Render(c, http.StatusOK, web.Signup(s.pageFor(c, "auth.signup.title"), providers, email, consent))
}
func (s *Server) signupSentPage(c *gin.Context) {
@@ -249,6 +256,10 @@ func (s *Server) securityPage(c *gin.Context) {
internalError(c, err)
return
}
if me.DeletesOrgs, err = s.ownedOrgs(ctx, sess.UserID); err != nil {
internalError(c, err)
return
}
var (
identities []web.Identity
canLink bool
+5 -1
View File
@@ -26,7 +26,11 @@ func (b *browser) invite(email, roleID string) string {
func (e *env) joinVia(t *testing.T, tok string) *browser {
t.Helper()
b := e.browser(t)
st, body := b.do("POST", "/api/v1/invitations/"+tok+"/signup", map[string]any{"password": password})
_, _, form := b.page("/invite/" + tok)
versions := consentShown(form)
st, body := b.do("POST", "/api/v1/invitations/"+tok+"/signup", map[string]any{
"password": password, "consent": versions != "", "consent_versions": versions,
})
if st != http.StatusOK {
t.Fatalf("invite signup = %d %v, want 200", st, body)
}
+2 -4
View File
@@ -168,10 +168,8 @@ func (s *Server) platformCallback(c *gin.Context, f ssoFlow, state string) {
internalError(c, err)
return
}
if user.DisabledAt != nil {
s.ssoAbort(c, uuid.Nil, "account_suspended")
return
}
// Suspended accounts sign in too, but only to export or delete their
// data (accountGate).
// The account's second factor still applies; the provider replaces
// only the password.
if user.TotpSecret != nil {
+5 -1
View File
@@ -44,6 +44,8 @@ type Server struct {
eval *evaluate.Evaluator
smtp *notify.SMTP
legal *versioned[[]agentapi.LegalDoc]
// consent caches the versions of the documents accounts accept.
consent *versioned[map[string]int64]
// checkTypes caches the check types switched off platform-wide.
checkTypes *versioned[map[string]bool]
// checkerNet caches whether platform checkers may reach private
@@ -82,6 +84,7 @@ func New(cfg config.API, d Deps) *Server {
sso: sso.New(sso.SafeHTTPClient(allowPrivate), cfg.PublicURL+"/sso/callback", allowPrivate),
sched: schedule.New(d.Redis),
legal: newVersioned[[]agentapi.LegalDoc]("legal"),
consent: newVersioned[map[string]int64]("consent"),
checkTypes: newVersioned[map[string]bool]("check-types"),
checkerNet: newVersioned[bool]("checker-network"),
limits: newVersioned[Limits]("limits"),
@@ -97,7 +100,7 @@ func (s *Server) Mount(r gin.IRouter) {
s.mountHeartbeats(r)
s.mountAlertmanager(r)
g := r.Group("/", s.sessions.Load(), s.localize(), auth.CSRF(), s.audit())
g := r.Group("/", s.sessions.Load(), s.localize(), auth.CSRF(), s.audit(), s.accountGate())
r.GET("/api/openapi.json", s.openAPIJSON)
r.GET("/install.sh", s.installScript)
@@ -115,6 +118,7 @@ func (s *Server) Mount(r gin.IRouter) {
a.POST("/login", s.login)
a.POST("/login/totp", s.loginTOTP)
a.POST("/logout", s.logout)
v1.POST("/consent", auth.Require(), s.acceptConsent)
me := v1.Group("/me", auth.Require())
me.GET("", s.me)
+2 -4
View File
@@ -261,10 +261,8 @@ func (s *Server) ssoCallback(c *gin.Context) {
internalError(c, err)
return
}
if user.DisabledAt != nil {
s.ssoAbort(c, uuid.Nil, "account_suspended")
return
}
// Suspended accounts sign in too, but only to export or delete their
// data (accountGate).
if old := auth.Current(c); old != nil {
_ = s.sessions.Delete(ctx, old)
}
+28
View File
@@ -13,6 +13,7 @@ import (
"net/http/httptest"
"net/url"
"os"
"regexp"
"strings"
"testing"
"time"
@@ -170,10 +171,37 @@ func (b *browser) visit(path string) *url.URL {
func uniq(prefix string) string { return prefix + strings.ReplaceAll(uuid.NewString()[:8], "-", "") }
var consentVersionsField = regexp.MustCompile(`name="(?:consent_versions|versions)" value="([^"]*)"`)
// consentShown returns the document versions a page asks to accept, empty
// when it asks for none.
func consentShown(html string) string {
if m := consentVersionsField.FindStringSubmatch(html); m != nil {
return m[1]
}
return ""
}
// acceptConsent accepts the documents the console asks for, as someone
// ticking the box on /consent would.
func (b *browser) acceptConsent() {
b.t.Helper()
_, _, html := b.page("/consent")
if v := consentShown(html); v != "" {
if st, body := b.do("POST", "/api/v1/consent", map[string]any{"versions": v, "accept": true}); st != http.StatusOK {
b.t.Fatalf("accept consent = %d %v", st, body)
}
}
}
func (b *browser) signup(email, slug string) {
b.t.Helper()
// Tick the consent box the sign-up page shows, if any.
_, _, form := b.page("/signup")
versions := consentShown(form)
st, body := b.do("POST", "/api/v1/auth/signup", map[string]any{
"email": email, "password": "correct horse battery", "org_name": slug, "org_slug": slug,
"consent": versions != "", "consent_versions": versions,
})
if st != http.StatusOK {
b.t.Fatalf("signup(%s) = %d %v, want 200", email, st, body)
+2 -1
View File
@@ -105,7 +105,8 @@ func (s *Server) buildSnapshot(ctx context.Context, page store.StatusPage) (agen
return err
}
docs, err := q.LegalDocuments(ctx, &page.OrgID)
snap.Legal = mergeLegal(docs)
// Visitors of status pages accept no terms.
snap.Legal = slices.DeleteFunc(mergeLegal(docs), func(d agentapi.LegalDoc) bool { return d.Kind == "terms" })
return err
})
if err != nil {