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
728 lines
23 KiB
Go
728 lines
23 KiB
Go
package api
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/auth"
|
|
"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"
|
|
)
|
|
|
|
// Exports answer GDPR access and portability requests (Art. 15 and 20):
|
|
// the account export holds everything stored about a person, the
|
|
// organization export what an organization configured and recorded.
|
|
// Secrets such as password hashes, token hashes and sealed credentials are
|
|
// never part of them.
|
|
|
|
type accountExport struct {
|
|
GeneratedAt time.Time `json:"generated_at"`
|
|
Account exportAccount `json:"account"`
|
|
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"`
|
|
DisplayName string `json:"display_name"`
|
|
Locale string `json:"locale"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
HasPassword bool `json:"has_password"`
|
|
TOTPEnabledAt *time.Time `json:"totp_enabled_at"`
|
|
PlatformAdmin bool `json:"platform_admin"`
|
|
}
|
|
|
|
type exportMembership struct {
|
|
ID uuid.UUID `json:"id"`
|
|
Slug string `json:"slug"`
|
|
Name string `json:"name"`
|
|
Owner bool `json:"owner"`
|
|
MemberSince time.Time `json:"member_since"`
|
|
Roles []exportRole `json:"roles"`
|
|
}
|
|
|
|
type exportRole struct {
|
|
Name string `json:"name"`
|
|
ResourceType *string `json:"resource_type,omitempty"`
|
|
ResourceID *uuid.UUID `json:"resource_id,omitempty"`
|
|
}
|
|
|
|
type exportIdentity struct {
|
|
Provider string `json:"provider"`
|
|
Organization uuid.UUID `json:"organization_id"`
|
|
Subject string `json:"subject"`
|
|
Email *string `json:"email"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
LastLoginAt time.Time `json:"last_login_at"`
|
|
}
|
|
|
|
type exportToken struct {
|
|
Organization uuid.UUID `json:"organization_id"`
|
|
Name string `json:"name"`
|
|
Prefix string `json:"prefix"`
|
|
Permissions []string `json:"permissions"`
|
|
ExpiresAt *time.Time `json:"expires_at"`
|
|
LastUsedAt *time.Time `json:"last_used_at"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
}
|
|
|
|
type exportActivity struct {
|
|
Time time.Time `json:"time"`
|
|
Action string `json:"action"`
|
|
Organization *uuid.UUID `json:"organization_id,omitempty"`
|
|
TargetID *uuid.UUID `json:"target_id,omitempty"`
|
|
Details json.RawMessage `json:"details"`
|
|
Status int32 `json:"status"`
|
|
IP string `json:"ip,omitempty"`
|
|
UserAgent string `json:"user_agent,omitempty"`
|
|
}
|
|
|
|
func (s *Server) buildAccountExport(ctx context.Context, userID uuid.UUID) (accountExport, error) {
|
|
x := accountExport{GeneratedAt: time.Now().UTC()}
|
|
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
|
|
u, err := q.GetUser(ctx, userID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
x.Account = exportAccount{
|
|
ID: u.ID, Email: u.Email, DisplayName: u.DisplayName, Locale: deref(u.Locale), CreatedAt: u.CreatedAt,
|
|
HasPassword: u.PasswordHash != nil, TOTPEnabledAt: u.TotpEnabledAt, PlatformAdmin: u.IsAdmin,
|
|
}
|
|
roles, err := q.UserRoleNames(ctx, userID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
byOrg := map[uuid.UUID][]exportRole{}
|
|
for _, r := range roles {
|
|
byOrg[r.OrgID] = append(byOrg[r.OrgID], exportRole{Name: r.Name, ResourceType: r.ResourceType, ResourceID: r.ResourceID})
|
|
}
|
|
ms, err := q.UserMemberships(ctx, userID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
x.Organizations = []exportMembership{}
|
|
for _, m := range ms {
|
|
x.Organizations = append(x.Organizations, exportMembership{
|
|
ID: m.ID, Slug: m.Slug, Name: m.Name, Owner: m.IsOwner, MemberSince: m.CreatedAt, Roles: orEmpty(byOrg[m.ID]),
|
|
})
|
|
}
|
|
ids, err := q.UserIdentities(ctx, userID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
x.Identities = []exportIdentity{}
|
|
for _, i := range ids {
|
|
x.Identities = append(x.Identities, exportIdentity{
|
|
Provider: i.Provider, Organization: i.OrgID, Subject: i.Subject, Email: i.Email, CreatedAt: i.CreatedAt, LastLoginAt: i.LastLoginAt,
|
|
})
|
|
}
|
|
toks, err := q.UserTokens(ctx, userID)
|
|
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{
|
|
Organization: t.OrgID, Name: t.Name, Prefix: t.Prefix, Permissions: t.Permissions,
|
|
ExpiresAt: t.ExpiresAt, LastUsedAt: t.LastUsedAt, CreatedAt: t.CreatedAt,
|
|
})
|
|
}
|
|
events, err := q.UserAuditEvents(ctx, &userID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
x.Activity = []exportActivity{}
|
|
for _, e := range events {
|
|
x.Activity = append(x.Activity, exportActivity{
|
|
Time: e.Time, Action: e.Action, Organization: e.OrgID, TargetID: e.TargetID,
|
|
Details: e.Details, Status: e.Status, IP: e.Ip, UserAgent: e.UserAgent,
|
|
})
|
|
}
|
|
return nil
|
|
})
|
|
return x, err
|
|
}
|
|
|
|
func orEmpty[T any](s []T) []T {
|
|
if s == nil {
|
|
return []T{}
|
|
}
|
|
return s
|
|
}
|
|
|
|
func (s *Server) exportAccount(c *gin.Context) {
|
|
sess := auth.Current(c)
|
|
ctx := c.Request.Context()
|
|
x, err := s.buildAccountExport(ctx, sess.UserID)
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
format := exportFormat(c)
|
|
s.writeAudit(c, store.InsertAuditEventParams{Kind: "user", ActorUserID: &sess.UserID, Action: "account.export", Status: http.StatusOK},
|
|
map[string]any{"format": format})
|
|
s.sendExport(c, format, "account-"+x.Account.ID.String()[:8], i18n.T(ctx, "export.account_title"), x)
|
|
}
|
|
|
|
// exportFormat is "json" unless the request asks for "pdf".
|
|
func exportFormat(c *gin.Context) string {
|
|
if c.Query("format") == "pdf" {
|
|
return "pdf"
|
|
}
|
|
return "json"
|
|
}
|
|
|
|
func (s *Server) sendExport(c *gin.Context, format, name, title string, x any) {
|
|
stamp := time.Now().UTC().Format("20060102")
|
|
c.Header("Cache-Control", "no-store")
|
|
if format == "pdf" {
|
|
var buf bytes.Buffer
|
|
if err := renderExportPDF(c.Request.Context(), &buf, title, x); err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
c.Header("Content-Disposition", fmt.Sprintf(`attachment; filename="uptimesebi-%s-%s.pdf"`, name, stamp))
|
|
c.Data(http.StatusOK, "application/pdf", buf.Bytes())
|
|
return
|
|
}
|
|
raw, err := json.MarshalIndent(x, "", " ")
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
c.Header("Content-Disposition", fmt.Sprintf(`attachment; filename="uptimesebi-%s-%s.json"`, name, stamp))
|
|
c.Data(http.StatusOK, "application/json", raw)
|
|
}
|
|
|
|
type orgExport struct {
|
|
AlertGroups []alertGroupView `json:"alert_groups"`
|
|
GeneratedAt time.Time `json:"generated_at"`
|
|
Organization exportOrg `json:"organization"`
|
|
Members []exportMember `json:"members"`
|
|
Roles []exportCustomRole `json:"custom_roles"`
|
|
Groups []exportGroup `json:"monitor_groups"`
|
|
Monitors []exportMonitor `json:"monitors"`
|
|
Channels []exportChannel `json:"notification_channels"`
|
|
StatusPages []exportStatusPage `json:"status_pages"`
|
|
SSO []exportSSO `json:"sso_providers"`
|
|
Agents []exportAgent `json:"agents"`
|
|
Incidents []exportIncident `json:"incidents"`
|
|
Audit []exportAuditEntry `json:"audit_log"`
|
|
DailyStats []exportDailyStat `json:"daily_statistics" pdf:"-"`
|
|
}
|
|
|
|
type exportOrg struct {
|
|
ID uuid.UUID `json:"id"`
|
|
Slug string `json:"slug"`
|
|
Name string `json:"name"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
RequireTOTP bool `json:"require_totp"`
|
|
RequireSSO bool `json:"require_sso"`
|
|
APITokenMaxDays *int32 `json:"api_token_max_days"`
|
|
}
|
|
|
|
type exportMember struct {
|
|
ID uuid.UUID `json:"id"`
|
|
Email string `json:"email"`
|
|
DisplayName string `json:"display_name"`
|
|
Owner bool `json:"owner"`
|
|
MemberSince time.Time `json:"member_since"`
|
|
Roles []exportRole `json:"roles"`
|
|
}
|
|
|
|
type exportCustomRole struct {
|
|
ID uuid.UUID `json:"id"`
|
|
Name string `json:"name"`
|
|
Permissions []string `json:"permissions"`
|
|
}
|
|
|
|
type exportGroup struct {
|
|
ID uuid.UUID `json:"id"`
|
|
Name string `json:"name"`
|
|
ParentID *uuid.UUID `json:"parent_id"`
|
|
}
|
|
|
|
type exportMonitor struct {
|
|
AlertGroupIDs []uuid.UUID `json:"alert_group_ids"`
|
|
ID uuid.UUID `json:"id"`
|
|
Name string `json:"name"`
|
|
Type string `json:"type"`
|
|
Target string `json:"target"`
|
|
IntervalSeconds int32 `json:"interval_seconds"`
|
|
TimeoutMS int32 `json:"timeout_ms"`
|
|
Confirmations int32 `json:"confirmations"`
|
|
Enabled bool `json:"enabled"`
|
|
GroupID *uuid.UUID `json:"group_id"`
|
|
Regions []uuid.UUID `json:"region_ids"`
|
|
Config json.RawMessage `json:"config"`
|
|
CreatedAt time.Time `json:"created_at"`
|
|
}
|
|
|
|
type exportChannel struct {
|
|
ID uuid.UUID `json:"id"`
|
|
Name string `json:"name"`
|
|
Type string `json:"type"`
|
|
Enabled bool `json:"enabled"`
|
|
}
|
|
|
|
type exportStatusPage struct {
|
|
ID uuid.UUID `json:"id"`
|
|
Slug string `json:"slug"`
|
|
Title string `json:"title"`
|
|
Description string `json:"description"`
|
|
Published bool `json:"published"`
|
|
ShowComponentDetails bool `json:"show_component_details"`
|
|
CustomDomain *string `json:"custom_domain"`
|
|
Groups []pageGroupView `json:"groups"`
|
|
Monitors []exportPageMember `json:"monitors"`
|
|
}
|
|
|
|
type exportPageMember struct {
|
|
MonitorID uuid.UUID `json:"monitor_id"`
|
|
GroupID *uuid.UUID `json:"group_id"`
|
|
Section string `json:"section"`
|
|
Label string `json:"label"`
|
|
}
|
|
|
|
type exportSSO struct {
|
|
ID uuid.UUID `json:"id"`
|
|
Name string `json:"name"`
|
|
Issuer string `json:"issuer"`
|
|
ClientID string `json:"client_id"`
|
|
Scopes []string `json:"scopes"`
|
|
AllowedDomains []string `json:"allowed_domains"`
|
|
Enabled bool `json:"enabled"`
|
|
}
|
|
|
|
type exportAgent struct {
|
|
ID uuid.UUID `json:"id"`
|
|
Kind string `json:"kind"`
|
|
Name string `json:"name"`
|
|
Region *string `json:"region"`
|
|
}
|
|
|
|
type exportIncident struct {
|
|
ID uuid.UUID `json:"id"`
|
|
MonitorID uuid.UUID `json:"monitor_id"`
|
|
Monitor *string `json:"monitor"`
|
|
StartedAt time.Time `json:"started_at"`
|
|
ResolvedAt *time.Time `json:"resolved_at"`
|
|
Cause json.RawMessage `json:"cause"`
|
|
}
|
|
|
|
type exportAuditEntry struct {
|
|
Time time.Time `json:"time"`
|
|
Action string `json:"action"`
|
|
Actor string `json:"actor"`
|
|
TargetID *uuid.UUID `json:"target_id,omitempty"`
|
|
Details json.RawMessage `json:"details"`
|
|
Status int32 `json:"status"`
|
|
IP string `json:"ip,omitempty"`
|
|
}
|
|
|
|
type exportDailyStat struct {
|
|
MonitorID uuid.UUID `json:"monitor_id"`
|
|
Region string `json:"region"`
|
|
Day time.Time `json:"day"`
|
|
Total int64 `json:"total"`
|
|
OK int64 `json:"ok"`
|
|
AvgLatencyMS float32 `json:"avg_latency_ms"`
|
|
}
|
|
|
|
func rawJSON(b []byte) json.RawMessage {
|
|
if len(b) == 0 {
|
|
return json.RawMessage("null")
|
|
}
|
|
return b
|
|
}
|
|
|
|
func (s *Server) buildOrgExport(ctx context.Context, p *principal) (orgExport, error) {
|
|
x := orgExport{GeneratedAt: time.Now().UTC()}
|
|
org := p.Org.ID
|
|
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
|
|
o, err := q.GetOrg(ctx, org)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
x.Organization = exportOrg{ID: o.ID, Slug: o.Slug, Name: o.Name, CreatedAt: o.CreatedAt,
|
|
RequireTOTP: o.RequireTotp, RequireSSO: o.RequireSso, APITokenMaxDays: o.ApiTokenMaxDays}
|
|
|
|
assignments, err := q.OrgAssignmentsExport(ctx, org)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
roles := map[uuid.UUID][]exportRole{}
|
|
for _, a := range assignments {
|
|
roles[a.UserID] = append(roles[a.UserID], exportRole{Name: a.Role, ResourceType: a.ResourceType, ResourceID: a.ResourceID})
|
|
}
|
|
members, err := q.OrgMembersExport(ctx, org)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
x.Members = []exportMember{}
|
|
for _, m := range members {
|
|
x.Members = append(x.Members, exportMember{ID: m.ID, Email: m.Email, DisplayName: m.DisplayName, Owner: m.IsOwner, MemberSince: m.CreatedAt, Roles: orEmpty(roles[m.ID])})
|
|
}
|
|
|
|
rs, err := q.ListRoles(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
x.Roles = []exportCustomRole{}
|
|
for _, r := range rs {
|
|
if r.OrgID != nil {
|
|
x.Roles = append(x.Roles, exportCustomRole{ID: r.ID, Name: r.Name, Permissions: r.Permissions})
|
|
}
|
|
}
|
|
groups, err := q.ListGroups(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
x.Groups = []exportGroup{}
|
|
for _, g := range groups {
|
|
x.Groups = append(x.Groups, exportGroup{ID: g.ID, Name: g.Name, ParentID: g.ParentID})
|
|
}
|
|
|
|
alertGroups, err := q.ListAlertGroups(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
x.AlertGroups = []alertGroupView{}
|
|
for _, g := range alertGroups {
|
|
x.AlertGroups = append(x.AlertGroups, alertGroupView{
|
|
ID: g.ID, Name: g.Name, IsDefault: g.IsDefault,
|
|
ChannelIDs: g.ChannelIds, QuietHours: decodeQuietHours(g.QuietHours),
|
|
})
|
|
}
|
|
alertAssignments, err := q.AllMonitorAlertGroups(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
alertGroupsByMonitor := map[uuid.UUID][]uuid.UUID{}
|
|
for _, a := range alertAssignments {
|
|
alertGroupsByMonitor[a.MonitorID] = append(alertGroupsByMonitor[a.MonitorID], a.GroupID)
|
|
}
|
|
regionRows, err := q.AllMonitorRegions(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
regions := map[uuid.UUID][]uuid.UUID{}
|
|
for _, r := range regionRows {
|
|
regions[r.MonitorID] = append(regions[r.MonitorID], r.RegionID)
|
|
}
|
|
monitors, err := q.ListMonitors(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
x.Monitors = []exportMonitor{}
|
|
for _, m := range monitors {
|
|
x.Monitors = append(x.Monitors, exportMonitor{
|
|
ID: m.ID, Name: m.Name, Type: m.Type, Target: m.Target, IntervalSeconds: m.IntervalSeconds,
|
|
TimeoutMS: m.TimeoutMs, Confirmations: m.Confirmations, Enabled: m.Enabled, GroupID: m.GroupID,
|
|
AlertGroupIDs: orEmpty(alertGroupsByMonitor[m.ID]),
|
|
Regions: orEmpty(regions[m.ID]), Config: rawJSON(first(publicMonitorConfig(m.Config))), CreatedAt: m.CreatedAt,
|
|
})
|
|
}
|
|
|
|
channels, err := q.ListChannels(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
x.Channels = []exportChannel{}
|
|
for _, ch := range channels {
|
|
x.Channels = append(x.Channels, exportChannel{ID: ch.ID, Name: ch.Name, Type: ch.Type, Enabled: ch.Enabled})
|
|
}
|
|
|
|
pages, err := q.ListStatusPages(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
x.StatusPages = []exportStatusPage{}
|
|
for _, pg := range pages {
|
|
pgGroups, err := q.ListStatusPageGroups(ctx, pg.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
exportedGroups := []pageGroupView{}
|
|
newPageGroupTree(pgGroups).walk(func(g store.StatusPageGroup, _ int) {
|
|
exportedGroups = append(exportedGroups, pageGroupView{
|
|
ID: g.ID, Name: g.Name, ParentID: g.ParentID, Position: g.Position,
|
|
})
|
|
})
|
|
pm, err := q.StatusPageMonitors(ctx, pg.ID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
members := []exportPageMember{}
|
|
for _, m := range pm {
|
|
members = append(members, exportPageMember{
|
|
MonitorID: m.MonitorID, GroupID: m.GroupID, Section: m.Section, Label: m.Label,
|
|
})
|
|
}
|
|
x.StatusPages = append(x.StatusPages, exportStatusPage{
|
|
ID: pg.ID, Slug: pg.Slug, Title: pg.Title, Description: pg.Description,
|
|
Published: pg.Published, ShowComponentDetails: pg.ShowComponentDetails,
|
|
CustomDomain: pg.CustomDomain, Groups: exportedGroups, Monitors: members,
|
|
})
|
|
}
|
|
|
|
providers, err := q.ListSSOProviders(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
x.SSO = []exportSSO{}
|
|
for _, sp := range providers {
|
|
x.SSO = append(x.SSO, exportSSO{ID: sp.ID, Name: sp.Name, Issuer: sp.Issuer, ClientID: sp.ClientID,
|
|
Scopes: sp.Scopes, AllowedDomains: sp.AllowedDomains, Enabled: sp.Enabled})
|
|
}
|
|
|
|
agents, err := q.ListAgents(ctx, &org)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
x.Agents = []exportAgent{}
|
|
for _, a := range agents {
|
|
x.Agents = append(x.Agents, exportAgent{ID: a.ID, Kind: a.Kind, Name: a.Name, Region: a.RegionName})
|
|
}
|
|
|
|
incidents, err := q.OrgIncidentsExport(ctx, org)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
x.Incidents = []exportIncident{}
|
|
for _, i := range incidents {
|
|
x.Incidents = append(x.Incidents, exportIncident{ID: i.ID, MonitorID: i.MonitorID, Monitor: i.Monitor,
|
|
StartedAt: i.StartedAt, ResolvedAt: i.ResolvedAt, Cause: rawJSON(i.Cause)})
|
|
}
|
|
|
|
audit, err := q.OrgAuditExport(ctx, org)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
x.Audit = []exportAuditEntry{}
|
|
for _, a := range audit {
|
|
x.Audit = append(x.Audit, exportAuditEntry{Time: a.Time, Action: a.Action, Actor: a.Actor, TargetID: a.TargetID,
|
|
Details: rawJSON(a.Details), Status: a.Status, IP: a.Ip})
|
|
}
|
|
|
|
stats, err := q.OrgDailyStats(ctx, org)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
x.DailyStats = []exportDailyStat{}
|
|
for _, st := range stats {
|
|
x.DailyStats = append(x.DailyStats, exportDailyStat{MonitorID: st.MonitorID, Region: st.Region, Day: st.Day,
|
|
Total: st.Total, OK: st.OkCount, AvgLatencyMS: st.AvgLatencyMs})
|
|
}
|
|
return nil
|
|
})
|
|
return x, err
|
|
}
|
|
|
|
func (s *Server) exportOrg(c *gin.Context) {
|
|
p := current(c)
|
|
ctx := c.Request.Context()
|
|
x, err := s.buildOrgExport(ctx, p)
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
format := exportFormat(c)
|
|
s.writeAudit(c, store.InsertAuditEventParams{Kind: "org", OrgID: &p.Org.ID, ActorUserID: &p.UserID, Action: "org.export", Status: http.StatusOK},
|
|
map[string]any{"format": format})
|
|
s.sendExport(c, format, p.Org.Slug, i18n.T(ctx, "export.org_title", "Name", p.Org.Name), x)
|
|
}
|
|
|
|
type deletionRequest struct {
|
|
// Password confirms the deletion; accounts without one, signing in
|
|
// through SSO only, type their email address instead.
|
|
Password string `json:"password" binding:"max=1024"`
|
|
Confirm string `json:"confirm" binding:"max=320"`
|
|
}
|
|
|
|
// confirmIdentity checks the re-entered password, or the typed email for
|
|
// accounts without a password.
|
|
func (s *Server) confirmIdentity(ctx context.Context, u store.User, req deletionRequest) bool {
|
|
if u.PasswordHash == nil {
|
|
return req.Confirm != "" && normalizeEmail(req.Confirm) == normalizeEmail(u.Email)
|
|
}
|
|
ok, _, err := auth.VerifyPassword(*u.PasswordHash, req.Password)
|
|
return err == nil && ok
|
|
}
|
|
|
|
func (s *Server) loadUser(ctx context.Context, id uuid.UUID) (store.User, error) {
|
|
var u store.User
|
|
err := s.db.Tx(ctx, tenant.Global(), func(q *store.Queries) error {
|
|
var err error
|
|
u, err = q.GetUser(ctx, id)
|
|
return err
|
|
})
|
|
return u, err
|
|
}
|
|
|
|
// purgeOrg deletes an organization with everything in it, including check
|
|
// results and status page server storage, which have no foreign key.
|
|
func purgeOrg(ctx context.Context, q *store.Queries, org uuid.UUID) error {
|
|
if err := q.PurgeOrgCheckData(ctx, org); err != nil {
|
|
return err
|
|
}
|
|
if err := q.DeleteOrgStorage(ctx, org); err != nil {
|
|
return err
|
|
}
|
|
_, err := q.DeleteOrg(ctx, org)
|
|
return err
|
|
}
|
|
|
|
// 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) {
|
|
return
|
|
}
|
|
auditSkip(c)
|
|
sess := auth.Current(c)
|
|
ctx := c.Request.Context()
|
|
if !s.limit(c, "delete:"+sess.UserID.String(), 5, 15*time.Minute) {
|
|
return
|
|
}
|
|
u, err := s.loadUser(ctx, sess.UserID)
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
if !s.confirmIdentity(ctx, u, req) {
|
|
fail(c, http.StatusForbidden, "confirmation_failed")
|
|
return
|
|
}
|
|
orgsDeleted, err := s.eraseAccount(ctx, u)
|
|
if err != nil {
|
|
internalError(c, err)
|
|
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},
|
|
map[string]any{"organizations_deleted": orgsDeleted})
|
|
c.JSON(http.StatusOK, gin.H{"status": "deleted"})
|
|
}
|
|
|
|
// 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 err := purgeOrg(ctx, q, o.ID); err != nil {
|
|
return err
|
|
}
|
|
orgsDeleted++
|
|
}
|
|
for _, step := range []func() error{
|
|
func() error { return q.DeleteAccountAudit(ctx, &u.ID) },
|
|
func() error { return q.ForgetAuditActor(ctx, &u.ID) },
|
|
func() error { return q.ScrubAuditEmail(ctx, u.Email) },
|
|
func() error { return q.DeleteInvitationsForEmail(ctx, u.Email) },
|
|
func() error { _, err := q.DeleteUser(ctx, u.ID); return err },
|
|
} {
|
|
if err := step(); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
})
|
|
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 orgsDeleted, nil
|
|
}
|
|
|
|
type orgDeletionRequest struct {
|
|
deletionRequest
|
|
Slug string `json:"slug" binding:"required,max=63"`
|
|
}
|
|
|
|
// deleteOrg erases the current organization. Only its owner may, after
|
|
// typing its slug and confirming their identity.
|
|
func (s *Server) deleteOrg(c *gin.Context) {
|
|
var req orgDeletionRequest
|
|
if !bind(c, &req) {
|
|
return
|
|
}
|
|
auditSkip(c)
|
|
p := current(c)
|
|
ctx := c.Request.Context()
|
|
if !p.Grants.Owner {
|
|
fail(c, http.StatusForbidden, "forbidden")
|
|
return
|
|
}
|
|
if !s.limit(c, "delete:"+p.UserID.String(), 5, 15*time.Minute) {
|
|
return
|
|
}
|
|
u, err := s.loadUser(ctx, p.UserID)
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
if req.Slug != p.Org.Slug || !s.confirmIdentity(ctx, u, req.deletionRequest) {
|
|
fail(c, http.StatusForbidden, "confirmation_failed")
|
|
return
|
|
}
|
|
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { return purgeOrg(ctx, q, p.Org.ID) })
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
fail(c, http.StatusNotFound, "not_found")
|
|
return
|
|
}
|
|
if err != nil {
|
|
internalError(c, err)
|
|
return
|
|
}
|
|
if sess := auth.Current(c); sess != nil {
|
|
_ = s.sessions.SwitchOrg(ctx, sess, uuid.Nil)
|
|
}
|
|
s.writeAudit(c, store.InsertAuditEventParams{Kind: "platform", Action: "org.delete", TargetID: &p.Org.ID, Status: http.StatusOK},
|
|
map[string]any{"slug": p.Org.Slug, "name": p.Org.Name})
|
|
c.JSON(http.StatusOK, gin.H{"status": "deleted"})
|
|
}
|
|
|
|
func first[A, B any](a A, _ B) A { return a }
|