diff --git a/.env.example b/.env.example index 4d6aac4..6535d9a 100644 --- a/.env.example +++ b/.env.example @@ -23,6 +23,9 @@ UPTIME_API_URL=http://localhost:8080 UPTIME_TEST_DATABASE_URL=postgres://uptime:uptime@localhost:5432/uptime_test?sslmode=disable UPTIME_TEST_REDIS_URL=redis://localhost:6379/15 +# Reverse proxies allowed to set X-Forwarded-For (comma-separated IPs/CIDRs). +# UPTIME_TRUSTED_PROXIES=10.0.0.0/8 + # Data retention (0 keeps forever). Raw results feed charts up to 24h, the # hourly aggregate 7d and 30d, the daily aggregate up to a year; resolved # incidents follow the daily aggregate. @@ -31,6 +34,8 @@ UPTIME_TEST_REDIS_URL=redis://localhost:6379/15 # UPTIME_RETENTION_DAILY=26280h # Delivered notifications, expired invitations and expired API tokens. # UPTIME_RETENTION_HOUSEKEEPING=720h +# Audit log entries. +# UPTIME_RETENTION_AUDIT=8760h # Status page server: hosts serving pages by slug; enable TLS for custom domains. UPTIME_STATUSPAGE_URL=http://localhost:8082 diff --git a/cmd/api/main.go b/cmd/api/main.go index c093638..2f66829 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -80,6 +80,9 @@ func run(log *slog.Logger, level *slog.LevelVar, args []string) error { srv := api.New(cfg, api.Deps{Log: log, DB: tenant.New(deps.DB), Redis: deps.Redis, Keys: keys, Catalog: catalog}) health := platform.NewHealth(deps.Probes()) r := platform.NewRouter(log) + if err := platform.TrustProxies(r, cfg.TrustedProxies); err != nil { + return err + } health.Register(r) r.StaticFS("/static", web.Static()) srv.Mount(r) diff --git a/cmd/statuspage/main.go b/cmd/statuspage/main.go index 7ae9ce7..b650ed0 100644 --- a/cmd/statuspage/main.go +++ b/cmd/statuspage/main.go @@ -71,6 +71,9 @@ func run(log *slog.Logger, level *slog.LevelVar) error { "pages": func(ctx context.Context) error { return pages.Ready(ctx, apiProbe) }, }) r := platform.NewRouter(log) + if err := platform.TrustProxies(r, cfg.TrustedProxies); err != nil { + return err + } health.Register(r) r.StaticFS("/static", web.Static()) pages.Mount(r) diff --git a/internal/api/audit.go b/internal/api/audit.go new file mode 100644 index 0000000..3d2e458 --- /dev/null +++ b/internal/api/audit.go @@ -0,0 +1,384 @@ +package api + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "net/netip" + "net/url" + "strings" + "time" + + "github.com/a-h/templ" + "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/i18n" + "git.zb-server.de/ZB-Server/uptimesebi/internal/requestid" + "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" +) + +// auditActions names the audited action of every state-changing route. An +// empty name marks a route deliberately not audited. A test fails for +// routes missing here, so new endpoints cannot slip past the log. +var auditActions = map[string]string{ + "POST /api/v1/locale": "", + "POST /api/v1/auth/signup": "account.signup", + "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/me/org": "", + "POST /api/v1/me/totp/setup": "", + "POST /api/v1/me/totp/enable": "account.totp_enable", + "POST /api/v1/me/totp/disable": "account.totp_disable", + "POST /api/v1/me/totp/recovery-codes": "account.recovery_codes", + "POST /api/v1/invitations/:token/accept": "member.join", + "POST /api/v1/invitations/:token/signup": "member.join", + + "PUT /api/v1/org/policy": "org.policy_update", + "POST /api/v1/org/monitors": "monitor.create", + "PUT /api/v1/org/monitors/:id": "monitor.update", + "DELETE /api/v1/org/monitors/:id": "monitor.delete", + "POST /api/v1/org/groups": "group.create", + "PUT /api/v1/org/groups/:id": "group.update", + "DELETE /api/v1/org/groups/:id": "group.delete", + "POST /api/v1/org/regions": "region.create", + "DELETE /api/v1/org/regions/:id": "region.delete", + "POST /api/v1/org/agents": "agent.create", + "DELETE /api/v1/org/agents/:id": "agent.delete", + "POST /api/v1/org/statuspages": "statuspage.create", + "PUT /api/v1/org/statuspages/:id": "statuspage.update", + "DELETE /api/v1/org/statuspages/:id": "statuspage.delete", + "PUT /api/v1/org/statuspages/:id/monitors": "statuspage.monitors_update", + "PUT /api/v1/org/statuspages/:id/domain": "statuspage.domain_update", + "POST /api/v1/org/statuspages/:id/domain/verify": "statuspage.domain_verify", + "POST /api/v1/org/channels": "channel.create", + "PUT /api/v1/org/channels/:id": "channel.update", + "DELETE /api/v1/org/channels/:id": "channel.delete", + "POST /api/v1/org/channels/:id/test": "channel.test", + "POST /api/v1/org/sso": "sso.create", + "PUT /api/v1/org/sso/:id": "sso.update", + "DELETE /api/v1/org/sso/:id": "sso.delete", + "DELETE /api/v1/org/members/:user": "member.remove", + "POST /api/v1/org/members/:user/roles": "member.role_assign", + "DELETE /api/v1/org/assignments/:id": "member.role_unassign", + "POST /api/v1/org/invitations": "invitation.create", + "DELETE /api/v1/org/invitations/:id": "invitation.delete", + "POST /api/v1/org/roles": "role.create", + "PUT /api/v1/org/roles/:id": "role.update", + "DELETE /api/v1/org/roles/:id": "role.delete", + "POST /api/v1/org/tokens": "token.create", + "DELETE /api/v1/org/tokens/:id": "token.delete", + + "POST /api/v1/admin/regions": "platform.region_create", + "DELETE /api/v1/admin/regions/:id": "platform.region_delete", + "POST /api/v1/admin/agents": "platform.agent_create", + "DELETE /api/v1/admin/agents/:id": "platform.agent_delete", +} + +// Failed attempts of these actions are recorded too. +var auditFailures = map[string]bool{"auth.login": true} + +const ( + ctxAuditActor = "api.audit.actor" + ctxAuditOrg = "api.audit.org" + ctxAuditDetails = "api.audit.details" + ctxAuditSkip = "api.audit.skip" +) + +// auditOrg files the entry under org for requests outside the org API, +// such as accepting an invitation. +func auditOrg(c *gin.Context, org uuid.UUID) { c.Set(ctxAuditOrg, org) } + +// auditSkip leaves the current request out, for steps that are not the +// action yet, like a password check awaiting the second factor. +func auditSkip(c *gin.Context) { c.Set(ctxAuditSkip, true) } + +// auditActor names the acting user where no session or principal does yet, +// as when signing in. +func auditActor(c *gin.Context, user uuid.UUID) { c.Set(ctxAuditActor, user) } + +// auditDetail adds a value to the entry of the current request. +func auditDetail(c *gin.Context, key string, v any) { + d, _ := c.Get(ctxAuditDetails) + m, _ := d.(map[string]any) + if m == nil { + m = map[string]any{} + c.Set(ctxAuditDetails, m) + } + m[key] = v +} + +// captureWriter keeps the start of a JSON response to take the target's id +// and name from it. +type captureWriter struct { + gin.ResponseWriter + buf bytes.Buffer +} + +func (w *captureWriter) Write(b []byte) (int, error) { + if room := 8192 - w.buf.Len(); room > 0 { + w.buf.Write(b[:min(len(b), room)]) + } + return w.ResponseWriter.Write(b) +} + +// Response fields worth keeping; anything else may be a secret, such as a +// freshly created token. +var auditFields = []string{"name", "key", "slug", "email", "type", "target", "domain"} + +// audit records state-changing requests after they ran. +func (s *Server) audit() gin.HandlerFunc { + return func(c *gin.Context) { + switch c.Request.Method { + case http.MethodGet, http.MethodHead, http.MethodOptions: + c.Next() + return + } + cw := &captureWriter{ResponseWriter: c.Writer} + c.Writer = cw + c.Next() + + action := auditActions[c.Request.Method+" "+c.FullPath()] + status := c.Writer.Status() + if action == "" || c.GetBool(ctxAuditSkip) || (status >= 400 && !(auditFailures[action] && status < 500)) { + return + } + if status >= 400 { + action += "_failed" + } + e := store.InsertAuditEventParams{Action: action, Status: int32(status), Kind: "user"} + details := map[string]any{} + if d, ok := c.Get(ctxAuditDetails); ok { + for k, v := range d.(map[string]any) { + details[k] = v + } + } + if obj := responseObject(cw.buf.Bytes()); obj != nil { + if id, err := uuid.Parse(asString(obj["id"])); err == nil { + e.TargetID = &id + } + for _, f := range auditFields { + if v := asString(obj[f]); v != "" { + details[f] = v + } + } + } + for _, param := range []string{"id", "user"} { + if id, err := uuid.Parse(c.Param(param)); err == nil { + e.TargetID = &id + } + } + if p, ok := c.Get(ctxPrincipal); ok { + p := p.(*principal) + e.Kind, e.OrgID, e.ActorUserID = "org", &p.Org.ID, &p.UserID + if p.TokenID != uuid.Nil { + e.ActorTokenID = &p.TokenID + } + } else if sess := auth.Current(c); sess != nil { + e.ActorUserID = &sess.UserID + } + if u, ok := c.Get(ctxAuditActor); ok { + id := u.(uuid.UUID) + e.ActorUserID = &id + } + if o, ok := c.Get(ctxAuditOrg); ok { + org := o.(uuid.UUID) + e.Kind, e.OrgID = "org", &org + } + if strings.HasPrefix(c.FullPath(), "/api/v1/admin/") || e.ActorUserID == nil { + e.Kind, e.OrgID = "platform", nil + } + s.writeAudit(c, e, details) + } +} + +// responseObject returns the object a response describes: the response +// itself or, for responses like {"channel": {...}, "signing_secret": ...}, +// the nested object carrying an id. +func responseObject(body []byte) map[string]any { + var resp map[string]any + if json.Unmarshal(body, &resp) != nil { + return nil + } + if _, ok := resp["id"]; ok { + return resp + } + for _, v := range resp { + if m, ok := v.(map[string]any); ok { + if _, ok := m["id"]; ok { + return m + } + } + } + return nil +} + +func asString(v any) string { + s, _ := v.(string) + return s +} + +// writeAudit stores e with the request's origin. A failure is logged, not +// returned: the change it describes has already happened. +func (s *Server) writeAudit(c *gin.Context, e store.InsertAuditEventParams, details map[string]any) { + ctx := context.WithoutCancel(c.Request.Context()) + if len(details) > 0 { + e.Details, _ = json.Marshal(details) + } else { + e.Details = []byte("{}") + } + if ip, err := netip.ParseAddr(c.ClientIP()); err == nil { + e.Ip = &ip + } + if ua := c.Request.UserAgent(); ua != "" { + ua = ua[:min(len(ua), 300)] + e.UserAgent = &ua + } + if id := requestid.FromContext(ctx); id != "" { + e.RequestID = &id + } + err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { return q.InsertAuditEvent(ctx, e) }) + if err != nil { + s.log.ErrorContext(ctx, "writing audit event failed", "action", e.Action, "error", err) + } +} + +const auditPageSize = 100 + +// auditQuery reads one page of entries; before pages back in time. +func (s *Server) auditQuery(ctx context.Context, scope tenant.Scope, p store.ListAuditEventsParams, before string) ([]store.ListAuditEventsRow, error) { + if t, err := time.Parse(time.RFC3339Nano, before); err == nil { + p.Before = &t + } + if p.MaxRows == 0 { + p.MaxRows = auditPageSize + } + var rows []store.ListAuditEventsRow + err := s.db.Tx(ctx, scope, func(q *store.Queries) error { + var err error + rows, err = q.ListAuditEvents(ctx, p) + return err + }) + return rows, err +} + +type auditEventView struct { + ID uuid.UUID `json:"id"` + Time time.Time `json:"time"` + Action string `json:"action"` + ActorID *uuid.UUID `json:"actor_id"` + ActorEmail string `json:"actor_email,omitempty"` + TokenID *uuid.UUID `json:"token_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"` + RequestID string `json:"request_id,omitempty"` +} + +func auditJSON(c *gin.Context, rows []store.ListAuditEventsRow, err error) { + if err != nil { + internalError(c, err) + return + } + out := make([]auditEventView, len(rows)) + for i, r := range rows { + out[i] = auditEventView{ + ID: r.ID, Time: r.Time, Action: r.Action, ActorID: r.ActorUserID, ActorEmail: r.ActorEmail, + TokenID: r.ActorTokenID, TargetID: r.TargetID, Details: r.Details, Status: r.Status, + IP: r.Ip, UserAgent: r.UserAgent, RequestID: r.RequestID, + } + } + resp := gin.H{"events": out} + if len(rows) == auditPageSize { + resp["next_before"] = rows[len(rows)-1].Time.Format(time.RFC3339Nano) + } + c.JSON(http.StatusOK, resp) +} + +func (s *Server) listOrgAudit(c *gin.Context) { + p := current(c) + rows, err := s.auditQuery(c.Request.Context(), p.scope(), store.ListAuditEventsParams{Kind: "org", OrgID: &p.Org.ID}, c.Query("before")) + auditJSON(c, rows, err) +} + +func (s *Server) listMyAudit(c *gin.Context) { + sess := auth.Current(c) + rows, err := s.auditQuery(c.Request.Context(), tenant.User(sess.UserID), store.ListAuditEventsParams{Kind: "user", Actor: &sess.UserID}, c.Query("before")) + auditJSON(c, rows, err) +} + +func (s *Server) listPlatformAudit(c *gin.Context) { + rows, err := s.auditQuery(c.Request.Context(), tenant.System(), store.ListAuditEventsParams{Kind: "platform"}, c.Query("before")) + auditJSON(c, rows, err) +} + +// auditEntries prepares rows for the console. Unknown actions, say from a +// newer release during a rollout, show their raw name. +func auditEntries(c *gin.Context, rows []store.ListAuditEventsRow) []web.AuditEntry { + ctx := c.Request.Context() + out := make([]web.AuditEntry, len(rows)) + for i, r := range rows { + e := web.AuditEntry{ + Time: r.Time.Local().Format("2006-01-02 15:04:05"), Action: r.Action, + IP: r.Ip, RequestID: r.RequestID, Failed: r.Status >= 400, + } + if label := i18n.T(ctx, "audit.action."+r.Action); label != "audit.action."+r.Action { + e.Action = label + } + switch { + case r.ActorEmail != "": + e.Actor = r.ActorEmail + case r.ActorUserID != nil: + e.Actor = i18n.T(ctx, "audit.deleted_user") + } + if r.ActorTokenID != nil { + e.Actor += " · " + i18n.T(ctx, "audit.via_token") + } + var details map[string]any + if json.Unmarshal(r.Details, &details) == nil { + for _, f := range auditFields { + if v := asString(details[f]); v != "" { + e.Target = v + break + } + } + } + out[i] = e + } + return out +} + +func (s *Server) auditView(c *gin.Context, p *principal, page web.Page, me web.Me) (templ.Component, error) { + rows, err := s.auditQuery(c.Request.Context(), p.scope(), store.ListAuditEventsParams{Kind: "org", OrgID: &p.Org.ID}, c.Query("before")) + if err != nil { + return nil, err + } + return web.AuditPage(page, me, "audit.title", "audit.intro", auditEntries(c, rows), nextAuditPage(c, rows)), nil +} + +func (s *Server) adminAuditPage(c *gin.Context) { + me, ok := s.adminMe(c) + if !ok { + return + } + rows, err := s.auditQuery(c.Request.Context(), tenant.System(), store.ListAuditEventsParams{Kind: "platform"}, c.Query("before")) + if err != nil { + internalError(c, err) + return + } + web.Render(c, http.StatusOK, web.AuditPage(s.pageFor(c, "audit.platform_title"), me, "audit.platform_title", "audit.platform_intro", auditEntries(c, rows), nextAuditPage(c, rows))) +} + +func nextAuditPage(c *gin.Context, rows []store.ListAuditEventsRow) string { + if len(rows) < auditPageSize { + return "" + } + return c.Request.URL.Path + "?before=" + url.QueryEscape(rows[len(rows)-1].Time.Format(time.RFC3339Nano)) +} diff --git a/internal/api/audit_test.go b/internal/api/audit_test.go new file mode 100644 index 0000000..6e6a0be --- /dev/null +++ b/internal/api/audit_test.go @@ -0,0 +1,164 @@ +package api_test + +import ( + "context" + "log/slog" + "net/http" + "strings" + "testing" + + "github.com/gin-gonic/gin" + "github.com/jackc/pgx/v5" + + "git.zb-server.de/ZB-Server/uptimesebi/internal/api" + "git.zb-server.de/ZB-Server/uptimesebi/internal/config" + "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" +) + +func TestEveryChangingRouteIsAudited(t *testing.T) { + r := gin.New() + api.New(config.API{}, api.Deps{Log: slog.New(slog.DiscardHandler)}).Mount(r) + for _, rt := range r.Routes() { + if rt.Method == http.MethodGet || rt.Method == http.MethodHead || !strings.HasPrefix(rt.Path, "/api/v1/") { + continue + } + if _, ok := api.AuditActions[rt.Method+" "+rt.Path]; !ok { + t.Errorf("%s %s is missing from auditActions", rt.Method, rt.Path) + } + } +} + +func TestAuditActionsAreTranslated(t *testing.T) { + catalog, err := i18n.Load() + if err != nil { + t.Fatal(err) + } + for _, lang := range catalog.Supported() { + ctx := i18n.NewContext(context.Background(), catalog.Match(lang)) + for _, action := range api.AuditActions { + if action == "" { + continue + } + for _, id := range []string{"audit.action." + action, "audit.action." + action + "_failed"} { + if id == "audit.action."+action+"_failed" && action != "auth.login" { + continue + } + if i18n.T(ctx, id) == id { + t.Errorf("%s: %s is not translated", lang, id) + } + } + } + } +} + +func TestAuditLog(t *testing.T) { + e := newEnv(t) + owner := e.browser(t) + email := "o@" + uniq("au") + ".test" + owner.signup(email, uniq("au-")) + other := e.browser(t) + other.signup("x@"+uniq("au")+".test", uniq("au-")) + + st, body := owner.do("POST", "/api/v1/org/channels", map[string]any{ + "name": "Ops hook", "type": "webhook", "url": "https://hooks.example.com/x", + }) + if st != http.StatusCreated { + t.Fatalf("create channel = %d %v", st, body) + } + signing := body["signing_secret"].(string) + st, body = owner.do("POST", "/api/v1/org/tokens", map[string]any{"name": "ci", "permissions": []string{"monitors.read"}}) + if st != http.StatusCreated { + t.Fatalf("create token = %d %v", st, body) + } + token := body["token"].(string) + // Rejected requests change nothing and are not logged. + owner.do("POST", "/api/v1/org/monitors", map[string]any{"name": ""}) + + _, list := owner.do("GET", "/api/v1/org/audit", nil) + events := list["events"].([]any) + actions := map[string]map[string]any{} + for _, ev := range events { + m := ev.(map[string]any) + actions[m["action"].(string)] = m + } + ch, ok := actions["channel.create"] + if !ok || ch["details"].(map[string]any)["name"] != "Ops hook" || ch["actor_email"] != email || ch["request_id"] == "" { + t.Errorf("channel.create entry = %v", ch) + } + if _, ok := actions["token.create"]; !ok { + t.Error("token.create is not logged") + } + if _, ok := actions["monitor.create"]; ok { + t.Error("a rejected request was logged") + } + + // Nothing secret ends up in the log. + var raw string + _ = e.asSystem(t, func(tx pgx.Tx) error { + return tx.QueryRow(context.Background(), `SELECT coalesce(string_agg(details::text, ' '), '') FROM audit_events`).Scan(&raw) + }) + for _, secret := range []string{token, signing} { + if strings.Contains(raw, secret) { + t.Errorf("audit details contain a secret") + } + } + + // Other organizations see nothing of it. + _, otherList := other.do("GET", "/api/v1/org/audit", nil) + for _, ev := range otherList["events"].([]any) { + if ev.(map[string]any)["action"] == "channel.create" { + t.Error("another organization sees the entry") + } + } + + // Members without audit.read are refused. + viewerEmail := "v@" + uniq("au") + ".test" + viewer := e.joinVia(t, owner.invite(viewerEmail, owner.roleID("viewer"))) + if st, _ := viewer.do("GET", "/api/v1/org/audit", nil); st != http.StatusForbidden { + t.Errorf("viewer GET audit = %d, want 403", st) + } + + // Failed sign-ins show up in the account's own activity. + intruder := e.browser(t) + if st, _ := intruder.do("POST", "/api/v1/auth/login", map[string]any{"email": email, "password": "wrong password"}); st != http.StatusUnauthorized { + t.Fatalf("login with wrong password = %d", st) + } + _, mine := owner.do("GET", "/api/v1/me/audit", nil) + var failed, signedUp bool + for _, ev := range mine["events"].([]any) { + switch ev.(map[string]any)["action"] { + case "auth.login_failed": + failed = true + case "account.signup": + signedUp = true + } + } + if !failed || !signedUp { + t.Errorf("own activity lacks failed sign-in (%t) or signup (%t): %v", failed, signedUp, mine) + } + if _, _, html := owner.page("/settings/security"); !strings.Contains(html, "Sign-in failed") && !strings.Contains(html, "Anmeldung fehlgeschlagen") { + t.Error("security page does not show the failed sign-in") + } + if st, _, html := owner.page("/settings/audit"); st != http.StatusOK || !strings.Contains(html, "Ops hook") { + t.Errorf("audit page = %d, lacks the channel", st) + } + + // Platform admins see sign-in attempts for unknown accounts. + intruder.do("POST", "/api/v1/auth/login", map[string]any{"email": "nobody@" + uniq("n") + ".test", "password": "x"}) + err := tenant.New(e.dbPool).Tx(context.Background(), tenant.Global(), func(q *store.Queries) error { + return q.MakeAdmin(context.Background(), owner.userIDSelf()) + }) + if err != nil { + t.Fatal(err) + } + _, platform := owner.do("GET", "/api/v1/admin/audit", nil) + found := false + for _, ev := range platform["events"].([]any) { + found = found || ev.(map[string]any)["action"] == "auth.login_failed" + } + if !found { + t.Error("platform log lacks the failed sign-in for an unknown account") + } +} diff --git a/internal/api/auth.go b/internal/api/auth.go index a022385..ac4a354 100644 --- a/internal/api/auth.go +++ b/internal/api/auth.go @@ -129,6 +129,7 @@ func (s *Server) login(c *gin.Context) { } ctx := c.Request.Context() email := normalizeEmail(req.Email) + auditDetail(c, "email", email) if !s.limit(c, "login:ip:"+c.ClientIP(), 30, 15*time.Minute) || !s.limit(c, "login:email:"+email, 10, 15*time.Minute) { return } @@ -148,6 +149,7 @@ func (s *Server) login(c *gin.Context) { internalError(c, err) return } + auditActor(c, user.ID) ok, rehash, err := auth.VerifyPassword(*user.PasswordHash, req.Password) if err != nil { internalError(c, err) @@ -168,6 +170,7 @@ func (s *Server) login(c *gin.Context) { return } setCookie(c, mfaCookie, token, int(mfaTTL.Seconds())) + auditSkip(c) c.JSON(http.StatusOK, gin.H{"status": "totp_required"}) return } @@ -207,6 +210,7 @@ func (s *Server) loginTOTP(c *gin.Context) { internalError(c, err) return } + auditActor(c, userID) ok, err := s.verifySecondFactor(ctx, userID, req.Code) if err != nil { internalError(c, err) @@ -255,6 +259,7 @@ func (s *Server) startSession(c *gin.Context, n auth.NewSession) { internalError(c, err) return } + auditActor(c, n.UserID) auth.SetCookie(c, sess, int(s.cfg.SessionAbsolute.Seconds())) c.JSON(http.StatusOK, gin.H{"status": "ok", "csrf_token": sess.CSRF}) } diff --git a/internal/api/export_test.go b/internal/api/export_test.go index 479680e..346f427 100644 --- a/internal/api/export_test.go +++ b/internal/api/export_test.go @@ -2,3 +2,6 @@ package api // LookupTXT lets tests replace DNS lookups for domain verification. var LookupTXT = &lookupTXT + +// AuditActions exposes the audited routes to tests. +var AuditActions = auditActions diff --git a/internal/api/housekeeping.go b/internal/api/housekeeping.go index f0cc8f8..5bf46e4 100644 --- a/internal/api/housekeeping.go +++ b/internal/api/housekeeping.go @@ -47,7 +47,7 @@ func (s *Server) RunHousekeeping(ctx context.Context) { // tokens and incidents older than the daily aggregate. func (s *Server) Housekeep(ctx context.Context, now time.Time) error { keep := s.cfg.Retention - var counts [4]int64 + var counts [5]int64 err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error { var err error if keep.Housekeeping > 0 { @@ -62,15 +62,20 @@ func (s *Server) Housekeep(ctx context.Context, now time.Time) error { return err } } + if keep.Audit > 0 { + if counts[4], err = q.PurgeAuditEvents(ctx, now.Add(-keep.Audit)); err != nil { + return err + } + } if keep.Daily > 0 { before := now.Add(-keep.Daily) counts[3], err = q.PurgeIncidents(ctx, &before) } return err }) - if err == nil && counts != [4]int64{} { + if err == nil && counts != [5]int64{} { s.log.InfoContext(ctx, "housekeeping purged rows", - "notifications", counts[0], "invitations", counts[1], "api_tokens", counts[2], "incidents", counts[3]) + "notifications", counts[0], "invitations", counts[1], "api_tokens", counts[2], "incidents", counts[3], "audit_events", counts[4]) } return err } diff --git a/internal/api/invitations.go b/internal/api/invitations.go index 31620d1..690eaaf 100644 --- a/internal/api/invitations.go +++ b/internal/api/invitations.go @@ -233,6 +233,7 @@ func (s *Server) acceptInvitation(c *gin.Context) { fail(c, http.StatusGone, code) return } + auditOrg(c, inv.OrgID) if err := s.sessions.SwitchOrg(ctx, sess, inv.OrgID); err != nil { internalError(c, err) return diff --git a/internal/api/pages.go b/internal/api/pages.go index 3538dc6..b1ca1cc 100644 --- a/internal/api/pages.go +++ b/internal/api/pages.go @@ -4,6 +4,7 @@ import ( "context" "errors" "net/http" + "net/url" "slices" "strings" "time" @@ -33,7 +34,9 @@ func (s *Server) registerPages(r gin.IRouter) { r.GET("/settings/roles", s.orgPage("roles.title", authz.MembersRead, s.rolesView)) r.GET("/settings/tokens", s.orgPage("tokens.title", "", s.tokensView)) r.GET("/settings/regions", s.orgPage("regions.title", authz.OrgManage, s.regionsView)) + r.GET("/settings/audit", s.orgPage("audit.title", authz.AuditRead, s.auditView)) r.GET("/admin", s.adminPage) + r.GET("/admin/audit", s.adminAuditPage) } // flashErrors lists the codes a redirect may ask a page to display. Anything @@ -202,7 +205,12 @@ func (s *Server) securityPage(c *gin.Context) { return } } - web.Render(c, http.StatusOK, web.Security(s.pageFor(c, "security.title"), me, identities, canLink)) + rows, err := s.auditQuery(ctx, tenant.User(sess.UserID), store.ListAuditEventsParams{Kind: "user", Actor: &sess.UserID, MaxRows: 20}, "") + if err != nil { + internalError(c, err) + return + } + web.Render(c, http.StatusOK, web.Security(s.pageFor(c, "security.title"), me, identities, canLink, auditEntries(c, rows))) } func toWebRoles(rows []store.Role) []web.Role { @@ -422,22 +430,32 @@ func (s *Server) regionsView(c *gin.Context, p *principal, page web.Page, me web return web.RegionsPage(page, me, v), nil } -func (s *Server) adminPage(c *gin.Context) { +// adminMe loads the console user of an admin page, redirecting anyone else. +func (s *Server) adminMe(c *gin.Context) (web.Me, bool) { sess := auth.Current(c) if sess == nil { - c.Redirect(http.StatusSeeOther, "/login?next=/admin") - return + c.Redirect(http.StatusSeeOther, "/login?next="+url.QueryEscape(c.Request.URL.Path)) + return web.Me{}, false } me, _, err := s.consoleMe(c, sess) if err != nil { internalError(c, err) - return + return web.Me{}, false } if !me.IsAdmin { c.Redirect(http.StatusSeeOther, "/") + return web.Me{}, false + } + return me, true +} + +func (s *Server) adminPage(c *gin.Context) { + me, ok := s.adminMe(c) + if !ok { return } ctx := c.Request.Context() + var err error var ( regions []store.Region agents []store.ListAgentsRow diff --git a/internal/api/server.go b/internal/api/server.go index 166b1db..b035507 100644 --- a/internal/api/server.go +++ b/internal/api/server.go @@ -82,7 +82,7 @@ func (s *Server) Mount(r gin.IRouter) { // the session and CSRF middleware. s.mountAgentAPI(r) - g := r.Group("/", s.sessions.Load(), s.localize(), auth.CSRF()) + g := r.Group("/", s.sessions.Load(), s.localize(), auth.CSRF(), s.audit()) v1 := g.Group("/api/v1") v1.POST("/locale", s.setLocale) @@ -100,6 +100,7 @@ func (s *Server) Mount(r gin.IRouter) { me.POST("/totp/enable", s.totpEnable) me.POST("/totp/disable", s.totpDisable) me.POST("/totp/recovery-codes", s.regenerateRecoveryCodes) + me.GET("/audit", s.listMyAudit) v1.POST("/invitations/:token/accept", auth.Require(), s.acceptInvitation) v1.POST("/invitations/:token/signup", s.inviteSignup) @@ -126,6 +127,7 @@ func (s *Server) Mount(r gin.IRouter) { org.DELETE("/agents/:id", sessionOnly(), can(authz.OrgManage), s.deleteOrgAgent) admin := v1.Group("/admin", s.requireAdmin()) + admin.GET("/audit", s.listPlatformAudit) admin.GET("/regions", s.adminListRegions) admin.POST("/regions", s.adminCreateRegion) admin.DELETE("/regions/:id", s.adminDeleteRegion) @@ -144,6 +146,7 @@ func (s *Server) Mount(r gin.IRouter) { page.GET("/export", canPage(authz.StatusPagesRead), s.exportStatusPage) org.GET("/incidents", can(authz.IncidentsRead), s.listIncidents) + org.GET("/audit", can(authz.AuditRead), s.listOrgAudit) org.GET("/channels", can(authz.NotificationsRead), s.listChannels) org.POST("/channels", can(authz.NotificationsWrite), s.createChannel) diff --git a/internal/api/sso.go b/internal/api/sso.go index 7dbb1ce..5a823f9 100644 --- a/internal/api/sso.go +++ b/internal/api/sso.go @@ -273,6 +273,9 @@ func (s *Server) ssoCallback(c *gin.Context) { return } auth.SetCookie(c, sess, int(s.cfg.SessionAbsolute.Seconds())) + s.writeAudit(c, store.InsertAuditEventParams{ + Kind: "user", ActorUserID: &userID, Action: "auth.login_sso", TargetID: &row.ID, Status: http.StatusSeeOther, + }, map[string]any{"name": row.Name}) c.Redirect(http.StatusSeeOther, "/") } diff --git a/internal/authz/authz.go b/internal/authz/authz.go index 4f79cb8..34e3d94 100644 --- a/internal/authz/authz.go +++ b/internal/authz/authz.go @@ -30,6 +30,7 @@ const ( IncidentsWrite Permission = "incidents.write" NotificationsRead Permission = "notifications.read" NotificationsWrite Permission = "notifications.write" + AuditRead Permission = "audit.read" ) // All lists every permission in display order. @@ -40,6 +41,7 @@ var All = []Permission{ StatusPagesRead, StatusPagesWrite, IncidentsRead, IncidentsWrite, NotificationsRead, NotificationsWrite, + AuditRead, } var implies = map[Permission]Permission{ diff --git a/internal/config/config.go b/internal/config/config.go index 3deaa02..6811d26 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -27,6 +27,10 @@ type Common struct { Edition Edition `env:"UPTIME_EDITION" envDefault:"selfhosted"` LogLevel slog.Level `env:"UPTIME_LOG_LEVEL" envDefault:"info"` ShutdownTimeout time.Duration `env:"UPTIME_SHUTDOWN_TIMEOUT" envDefault:"20s"` + // TrustedProxies are addresses or CIDRs of reverse proxies whose + // X-Forwarded-For is believed. Client addresses feed rate limits and + // the audit log, so the default trusts no proxy. + TrustedProxies []string `env:"UPTIME_TRUSTED_PROXIES" envSeparator:","` } // Storage locates Postgres and Redis. Only the API connects to them; every @@ -100,6 +104,8 @@ type Retention struct { Daily time.Duration `env:"UPTIME_RETENTION_DAILY" envDefault:"26280h"` // Delivered notifications, expired invitations and expired API tokens. Housekeeping time.Duration `env:"UPTIME_RETENTION_HOUSEKEEPING" envDefault:"720h"` + // Audit log entries. + Audit time.Duration `env:"UPTIME_RETENTION_AUDIT" envDefault:"8760h"` } // SSOAllowPrivate resolves SSOPrivateNetworks. diff --git a/internal/i18n/locales/de.json b/internal/i18n/locales/de.json index 4929fc4..c1b7eb8 100644 --- a/internal/i18n/locales/de.json +++ b/internal/i18n/locales/de.json @@ -11,6 +11,61 @@ "agents.revoke_confirm": "Diesen Agent widerrufen? Seine Instanzen hören sofort auf zu arbeiten.", "agents.token_now": "Kopiere den Token jetzt und setze ihn als UPTIME_AGENT_TOKEN. Er wird nicht erneut angezeigt. Beliebig viele Instanzen können ihn teilen.", "app.network_error": "Verbindung fehlgeschlagen.", + "audit.action.account.recovery_codes": "Wiederherstellungscodes neu erzeugt", + "audit.action.account.signup": "Konto erstellt", + "audit.action.account.totp_disable": "Zwei-Faktor-Authentifizierung deaktiviert", + "audit.action.account.totp_enable": "Zwei-Faktor-Authentifizierung aktiviert", + "audit.action.agent.create": "Agent erstellt", + "audit.action.agent.delete": "Agent widerrufen", + "audit.action.auth.login": "Angemeldet", + "audit.action.auth.login_failed": "Anmeldung fehlgeschlagen", + "audit.action.auth.login_sso": "Mit SSO angemeldet", + "audit.action.auth.logout": "Abgemeldet", + "audit.action.channel.create": "Benachrichtigungskanal erstellt", + "audit.action.channel.delete": "Benachrichtigungskanal gelöscht", + "audit.action.channel.test": "Testbenachrichtigung gesendet", + "audit.action.channel.update": "Benachrichtigungskanal geändert", + "audit.action.group.create": "Gruppe erstellt", + "audit.action.group.delete": "Gruppe gelöscht", + "audit.action.group.update": "Gruppe geändert", + "audit.action.invitation.create": "Einladung verschickt", + "audit.action.invitation.delete": "Einladung zurückgezogen", + "audit.action.member.join": "Der Organisation beigetreten", + "audit.action.member.remove": "Mitglied entfernt", + "audit.action.member.role_assign": "Rolle zugewiesen", + "audit.action.member.role_unassign": "Rolle entzogen", + "audit.action.monitor.create": "Monitor erstellt", + "audit.action.monitor.delete": "Monitor gelöscht", + "audit.action.monitor.update": "Monitor geändert", + "audit.action.org.policy_update": "Sicherheitsrichtlinie geändert", + "audit.action.platform.agent_create": "Plattform-Agent erstellt", + "audit.action.platform.agent_delete": "Plattform-Agent widerrufen", + "audit.action.platform.region_create": "Plattform-Region erstellt", + "audit.action.platform.region_delete": "Plattform-Region gelöscht", + "audit.action.region.create": "Region erstellt", + "audit.action.region.delete": "Region gelöscht", + "audit.action.role.create": "Rolle erstellt", + "audit.action.role.delete": "Rolle gelöscht", + "audit.action.role.update": "Rolle geändert", + "audit.action.sso.create": "SSO-Anbieter hinzugefügt", + "audit.action.sso.delete": "SSO-Anbieter entfernt", + "audit.action.sso.update": "SSO-Anbieter geändert", + "audit.action.statuspage.create": "Statusseite erstellt", + "audit.action.statuspage.delete": "Statusseite gelöscht", + "audit.action.statuspage.domain_update": "Eigene Domain geändert", + "audit.action.statuspage.domain_verify": "Eigene Domain verifiziert", + "audit.action.statuspage.monitors_update": "Monitore der Statusseite geändert", + "audit.action.statuspage.update": "Statusseite geändert", + "audit.action.token.create": "API-Token erstellt", + "audit.action.token.delete": "API-Token widerrufen", + "audit.deleted_user": "Gelöschter Benutzer", + "audit.empty": "Noch keine Einträge.", + "audit.intro": "Änderungen in dieser Organisation: wer wann was getan hat und von welcher Adresse. Einträge lassen sich nicht bearbeiten.", + "audit.older": "Ältere Einträge", + "audit.platform_intro": "Änderungen an Plattform-Regionen und -Agents sowie Anmeldeversuche für unbekannte Konten.", + "audit.platform_title": "Plattform-Audit-Log", + "audit.title": "Audit-Log", + "audit.via_token": "API-Token", "auth.field.code": "Code", "auth.field.email": "E-Mail", "auth.field.name": "Name", @@ -279,6 +334,7 @@ "pages.title": "Statuspages", "pages.value": "Wert", "pages.verify": "Prüfen", + "perm.audit.read": "Audit-Log einsehen", "perm.incidents.read": "Incidents sehen", "perm.incidents.write": "Incidents verwalten", "perm.members.manage": "Mitglieder einladen und verwalten", @@ -315,6 +371,8 @@ "roles.title": "Rollen", "scope.monitor_group": "Monitor-Gruppe", "scope.status_page": "Statuspage", + "security.activity": "Kontoaktivität", + "security.activity_intro": "Letzte Anmeldungen und Sicherheitsänderungen an deinem Konto. Wende dich an einen Administrator, wenn du einen Eintrag nicht erkennst.", "security.recovery.left": { "one": "{{.Count}} Wiederherstellungscode übrig", "other": "{{.Count}} Wiederherstellungscodes übrig" @@ -336,6 +394,7 @@ "security.totp.inactive": "nicht eingerichtet", "security.totp.qr_alt": "QR-Code für die Authenticator-App", "security.totp.start": "Einrichten", + "settings.audit": "Wer wann was geändert hat.", "settings.channels": "Webhooks und E-Mail für Incidents", "settings.groups": "Monitore in verschachtelten Gruppen ordnen", "settings.members": "Personen einladen und Rollen vergeben", diff --git a/internal/i18n/locales/en.json b/internal/i18n/locales/en.json index ca2da4a..1608edd 100644 --- a/internal/i18n/locales/en.json +++ b/internal/i18n/locales/en.json @@ -11,6 +11,61 @@ "agents.revoke_confirm": "Revoke this agent? Its instances stop working immediately.", "agents.token_now": "Copy the token now and set it as UPTIME_AGENT_TOKEN. It will not be shown again. Any number of instances may share it.", "app.network_error": "Connection failed.", + "audit.action.account.recovery_codes": "Recovery codes regenerated", + "audit.action.account.signup": "Account created", + "audit.action.account.totp_disable": "Two-factor authentication disabled", + "audit.action.account.totp_enable": "Two-factor authentication enabled", + "audit.action.agent.create": "Agent created", + "audit.action.agent.delete": "Agent revoked", + "audit.action.auth.login": "Signed in", + "audit.action.auth.login_failed": "Sign-in failed", + "audit.action.auth.login_sso": "Signed in with SSO", + "audit.action.auth.logout": "Signed out", + "audit.action.channel.create": "Notification channel created", + "audit.action.channel.delete": "Notification channel deleted", + "audit.action.channel.test": "Test notification sent", + "audit.action.channel.update": "Notification channel changed", + "audit.action.group.create": "Group created", + "audit.action.group.delete": "Group deleted", + "audit.action.group.update": "Group changed", + "audit.action.invitation.create": "Invitation sent", + "audit.action.invitation.delete": "Invitation withdrawn", + "audit.action.member.join": "Joined the organization", + "audit.action.member.remove": "Member removed", + "audit.action.member.role_assign": "Role assigned", + "audit.action.member.role_unassign": "Role removed", + "audit.action.monitor.create": "Monitor created", + "audit.action.monitor.delete": "Monitor deleted", + "audit.action.monitor.update": "Monitor changed", + "audit.action.org.policy_update": "Security policy changed", + "audit.action.platform.agent_create": "Platform agent created", + "audit.action.platform.agent_delete": "Platform agent revoked", + "audit.action.platform.region_create": "Platform region created", + "audit.action.platform.region_delete": "Platform region deleted", + "audit.action.region.create": "Region created", + "audit.action.region.delete": "Region deleted", + "audit.action.role.create": "Role created", + "audit.action.role.delete": "Role deleted", + "audit.action.role.update": "Role changed", + "audit.action.sso.create": "SSO provider added", + "audit.action.sso.delete": "SSO provider removed", + "audit.action.sso.update": "SSO provider changed", + "audit.action.statuspage.create": "Status page created", + "audit.action.statuspage.delete": "Status page deleted", + "audit.action.statuspage.domain_update": "Custom domain changed", + "audit.action.statuspage.domain_verify": "Custom domain verified", + "audit.action.statuspage.monitors_update": "Status page monitors changed", + "audit.action.statuspage.update": "Status page changed", + "audit.action.token.create": "API token created", + "audit.action.token.delete": "API token revoked", + "audit.deleted_user": "Deleted user", + "audit.empty": "No entries yet.", + "audit.intro": "Changes in this organization: who did what and when, from which address. Entries cannot be edited.", + "audit.older": "Older entries", + "audit.platform_intro": "Changes to platform regions and agents, and sign-in attempts for unknown accounts.", + "audit.platform_title": "Platform audit log", + "audit.title": "Audit log", + "audit.via_token": "API token", "auth.field.code": "Code", "auth.field.email": "Email", "auth.field.name": "Name", @@ -279,6 +334,7 @@ "pages.title": "Status pages", "pages.value": "Value", "pages.verify": "Verify", + "perm.audit.read": "View the audit log", "perm.incidents.read": "View incidents", "perm.incidents.write": "Manage incidents", "perm.members.manage": "Invite and manage members", @@ -315,6 +371,8 @@ "roles.title": "Roles", "scope.monitor_group": "monitor group", "scope.status_page": "status page", + "security.activity": "Account activity", + "security.activity_intro": "Recent sign-ins and security changes on your account. Contact an administrator if you do not recognize an entry.", "security.recovery.left": { "one": "{{.Count}} recovery code left", "other": "{{.Count}} recovery codes left" @@ -336,6 +394,7 @@ "security.totp.inactive": "not set up", "security.totp.qr_alt": "QR code for your authenticator app", "security.totp.start": "Set up", + "settings.audit": "Who changed what and when.", "settings.channels": "Webhooks and email for incidents", "settings.groups": "Organize monitors in nested groups", "settings.members": "Invite people and assign roles", diff --git a/internal/migrations/sql/00023_audit_log.sql b/internal/migrations/sql/00023_audit_log.sql new file mode 100644 index 0000000..ad91003 --- /dev/null +++ b/internal/migrations/sql/00023_audit_log.sql @@ -0,0 +1,44 @@ +-- +goose Up +-- Entries are written by the API after a change succeeded and never edited, +-- except that deleting an account removes the person from them. +-- kind decides who reads an entry: 'org' entries the organization's +-- auditors, 'user' entries the user they concern, 'platform' entries +-- platform admins only. +CREATE TABLE audit_events ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + time timestamptz NOT NULL DEFAULT now(), + kind text NOT NULL CHECK (kind IN ('org', 'user', 'platform')), + org_id uuid REFERENCES orgs (id) ON DELETE CASCADE, + actor_user_id uuid, + actor_token_id uuid, + action text NOT NULL, + target_id uuid, + -- Names of the target at the time, so entries stay readable after the + -- target is gone. Never secrets. + details jsonb NOT NULL DEFAULT '{}', + status integer NOT NULL, + ip inet, + user_agent text, + request_id text, + CHECK ((kind = 'org') = (org_id IS NOT NULL)) +); + +CREATE INDEX audit_events_org_idx ON audit_events (org_id, time DESC) WHERE org_id IS NOT NULL; +CREATE INDEX audit_events_actor_idx ON audit_events (actor_user_id, time DESC); +CREATE INDEX audit_events_time_idx ON audit_events (time); + +ALTER TABLE audit_events ENABLE ROW LEVEL SECURITY; +ALTER TABLE audit_events FORCE ROW LEVEL SECURITY; +CREATE POLICY audit_events_read ON audit_events FOR SELECT + USING (app_scope_system() + OR (kind = 'org' AND org_id = app_org_id()) + OR (kind = 'user' AND actor_user_id = app_user_id())); +CREATE POLICY audit_events_write ON audit_events FOR ALL + USING (app_scope_system()) WITH CHECK (app_scope_system()); + +UPDATE roles SET permissions = array_append(permissions, 'audit.read') +WHERE key = 'admin' AND NOT 'audit.read' = ANY (permissions); + +-- +goose Down +UPDATE roles SET permissions = array_remove(permissions, 'audit.read'); +DROP TABLE audit_events; diff --git a/internal/platform/proxy_test.go b/internal/platform/proxy_test.go new file mode 100644 index 0000000..7bd46b5 --- /dev/null +++ b/internal/platform/proxy_test.go @@ -0,0 +1,32 @@ +package platform + +import ( + "log/slog" + "net/http" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" +) + +func TestClientIPIgnoresForwardedForUnlessTrusted(t *testing.T) { + ip := func(r *gin.Engine) string { + r.GET("/ip", func(c *gin.Context) { c.String(http.StatusOK, c.ClientIP()) }) + req := httptest.NewRequest(http.MethodGet, "/ip", nil) + req.RemoteAddr = "192.0.2.10:4000" + req.Header.Set("X-Forwarded-For", "203.0.113.9") + w := httptest.NewRecorder() + r.ServeHTTP(w, req) + return w.Body.String() + } + if got := ip(NewRouter(slog.New(slog.DiscardHandler))); got != "192.0.2.10" { + t.Errorf("ClientIP() without trusted proxies = %s, want the peer address", got) + } + r := NewRouter(slog.New(slog.DiscardHandler)) + if err := TrustProxies(r, []string{"192.0.2.0/24"}); err != nil { + t.Fatal(err) + } + if got := ip(r); got != "203.0.113.9" { + t.Errorf("ClientIP() behind a trusted proxy = %s, want the forwarded address", got) + } +} diff --git a/internal/platform/router.go b/internal/platform/router.go index d9fae7c..22977f1 100644 --- a/internal/platform/router.go +++ b/internal/platform/router.go @@ -21,10 +21,17 @@ func NewRouter(log *slog.Logger) *gin.Engine { gin.DefaultWriter = io.Discard gin.DefaultErrorWriter = io.Discard r := gin.New() + _ = r.SetTrustedProxies(nil) r.Use(requestid.Middleware(), accessLog(log), recovery(log)) return r } +// TrustProxies makes r take client addresses from X-Forwarded-For only when +// the request comes from one of proxies. +func TrustProxies(r *gin.Engine, proxies []string) error { + return r.SetTrustedProxies(proxies) +} + func accessLog(log *slog.Logger) gin.HandlerFunc { return func(c *gin.Context) { start := time.Now() diff --git a/internal/store/audit.sql.go b/internal/store/audit.sql.go new file mode 100644 index 0000000..717d464 --- /dev/null +++ b/internal/store/audit.sql.go @@ -0,0 +1,147 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.31.1 +// source: audit.sql + +package store + +import ( + "context" + "net/netip" + "time" + + "github.com/google/uuid" +) + +const insertAuditEvent = `-- name: InsertAuditEvent :exec +INSERT INTO audit_events (kind, org_id, actor_user_id, actor_token_id, action, target_id, details, status, ip, user_agent, request_id) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) +` + +type InsertAuditEventParams struct { + Kind string + OrgID *uuid.UUID + ActorUserID *uuid.UUID + ActorTokenID *uuid.UUID + Action string + TargetID *uuid.UUID + Details []byte + Status int32 + Ip *netip.Addr + UserAgent *string + RequestID *string +} + +func (q *Queries) InsertAuditEvent(ctx context.Context, arg InsertAuditEventParams) error { + _, err := q.db.Exec(ctx, insertAuditEvent, + arg.Kind, + arg.OrgID, + arg.ActorUserID, + arg.ActorTokenID, + arg.Action, + arg.TargetID, + arg.Details, + arg.Status, + arg.Ip, + arg.UserAgent, + arg.RequestID, + ) + return err +} + +const listAuditEvents = `-- name: ListAuditEvents :many +SELECT e.id, e.time, e.kind, e.org_id, e.actor_user_id, e.actor_token_id, e.action, e.target_id, + e.details, e.status, coalesce(host(e.ip), '')::text AS ip, coalesce(e.user_agent, '') AS user_agent, + coalesce(e.request_id, '') AS request_id, + coalesce(u.email::text, '')::text AS actor_email, coalesce(u.display_name, '') AS actor_name +FROM audit_events e +LEFT JOIN users u ON u.id = e.actor_user_id +WHERE e.kind = $1 + AND ($2::uuid IS NULL OR e.org_id = $2) + AND ($3::uuid IS NULL OR e.actor_user_id = $3) + AND ($4::timestamptz IS NULL OR e.time < $4) +ORDER BY e.time DESC +LIMIT $5 +` + +type ListAuditEventsParams struct { + Kind string + OrgID *uuid.UUID + Actor *uuid.UUID + Before *time.Time + MaxRows int32 +} + +type ListAuditEventsRow struct { + ID uuid.UUID + Time time.Time + Kind string + OrgID *uuid.UUID + ActorUserID *uuid.UUID + ActorTokenID *uuid.UUID + Action string + TargetID *uuid.UUID + Details []byte + Status int32 + Ip string + UserAgent string + RequestID string + ActorEmail string + ActorName string +} + +// Newest first, paged by time. kind narrows to one kind; the row policy +// already limits what the scope can see. +func (q *Queries) ListAuditEvents(ctx context.Context, arg ListAuditEventsParams) ([]ListAuditEventsRow, error) { + rows, err := q.db.Query(ctx, listAuditEvents, + arg.Kind, + arg.OrgID, + arg.Actor, + arg.Before, + arg.MaxRows, + ) + if err != nil { + return nil, err + } + defer rows.Close() + items := []ListAuditEventsRow{} + for rows.Next() { + var i ListAuditEventsRow + if err := rows.Scan( + &i.ID, + &i.Time, + &i.Kind, + &i.OrgID, + &i.ActorUserID, + &i.ActorTokenID, + &i.Action, + &i.TargetID, + &i.Details, + &i.Status, + &i.Ip, + &i.UserAgent, + &i.RequestID, + &i.ActorEmail, + &i.ActorName, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const purgeAuditEvents = `-- name: PurgeAuditEvents :execrows +DELETE FROM audit_events WHERE time < $1 +` + +func (q *Queries) PurgeAuditEvents(ctx context.Context, argTime time.Time) (int64, error) { + result, err := q.db.Exec(ctx, purgeAuditEvents, argTime) + if err != nil { + return 0, err + } + return result.RowsAffected(), nil +} diff --git a/internal/store/models.go b/internal/store/models.go index b08821e..f090333 100644 --- a/internal/store/models.go +++ b/internal/store/models.go @@ -5,6 +5,7 @@ package store import ( + "net/netip" "time" "github.com/google/uuid" @@ -43,6 +44,22 @@ type ApiToken struct { CreatedAt time.Time } +type AuditEvent struct { + ID uuid.UUID + Time time.Time + Kind string + OrgID *uuid.UUID + ActorUserID *uuid.UUID + ActorTokenID *uuid.UUID + Action string + TargetID *uuid.UUID + Details []byte + Status int32 + Ip *netip.Addr + UserAgent *string + RequestID *string +} + type CheckResult struct { Time time.Time OrgID uuid.UUID diff --git a/internal/store/querier.go b/internal/store/querier.go index c64f2a0..86c1cdd 100644 --- a/internal/store/querier.go +++ b/internal/store/querier.go @@ -96,6 +96,7 @@ type Querier interface { IncidentsForMonitors(ctx context.Context, arg IncidentsForMonitorsParams) ([]Incident, error) // Incidents overlapping the time since $1, for SLA calculation. IncidentsSince(ctx context.Context, resolvedAt *time.Time) ([]IncidentsSinceRow, error) + InsertAuditEvent(ctx context.Context, arg InsertAuditEventParams) error // check_results and its aggregates have no row-level security (see // migration 00013). Every query here must filter by org_id. InsertCheckResults(ctx context.Context, arg []InsertCheckResultsParams) (int64, error) @@ -109,6 +110,9 @@ type Querier interface { // Agents owned by org, or platform agents when org is NULL. ListAgents(ctx context.Context, orgID *uuid.UUID) ([]ListAgentsRow, error) ListAssignments(ctx context.Context, orgID uuid.UUID) ([]ListAssignmentsRow, error) + // Newest first, paged by time. kind narrows to one kind; the row policy + // already limits what the scope can see. + ListAuditEvents(ctx context.Context, arg ListAuditEventsParams) ([]ListAuditEventsRow, error) ListChannels(ctx context.Context) ([]NotificationChannel, error) ListEnabledChannelIDs(ctx context.Context, orgID uuid.UUID) ([]uuid.UUID, error) // System scope: every enabled monitor with its regions, for reconciling the @@ -151,6 +155,7 @@ type Querier interface { OpenIncident(ctx context.Context, arg OpenIncidentParams) (Incident, error) OpenIncidents(ctx context.Context) ([]Incident, error) OrgIDBySlug(ctx context.Context, slug string) (uuid.UUID, error) + PurgeAuditEvents(ctx context.Context, argTime time.Time) (int64, error) PurgeExpiredTokens(ctx context.Context, expiresAt *time.Time) (int64, error) // Incidents resolved before the oldest data still charted. PurgeIncidents(ctx context.Context, resolvedAt *time.Time) (int64, error) diff --git a/internal/store/queries/audit.sql b/internal/store/queries/audit.sql new file mode 100644 index 0000000..d3c51f8 --- /dev/null +++ b/internal/store/queries/audit.sql @@ -0,0 +1,22 @@ +-- name: InsertAuditEvent :exec +INSERT INTO audit_events (kind, org_id, actor_user_id, actor_token_id, action, target_id, details, status, ip, user_agent, request_id) +VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11); + +-- name: ListAuditEvents :many +-- Newest first, paged by time. kind narrows to one kind; the row policy +-- already limits what the scope can see. +SELECT e.id, e.time, e.kind, e.org_id, e.actor_user_id, e.actor_token_id, e.action, e.target_id, + e.details, e.status, coalesce(host(e.ip), '')::text AS ip, coalesce(e.user_agent, '') AS user_agent, + coalesce(e.request_id, '') AS request_id, + coalesce(u.email::text, '')::text AS actor_email, coalesce(u.display_name, '') AS actor_name +FROM audit_events e +LEFT JOIN users u ON u.id = e.actor_user_id +WHERE e.kind = sqlc.arg(kind) + AND (sqlc.narg(org_id)::uuid IS NULL OR e.org_id = sqlc.narg(org_id)) + AND (sqlc.narg(actor)::uuid IS NULL OR e.actor_user_id = sqlc.narg(actor)) + AND (sqlc.narg(before)::timestamptz IS NULL OR e.time < sqlc.narg(before)) +ORDER BY e.time DESC +LIMIT sqlc.arg(max_rows); + +-- name: PurgeAuditEvents :execrows +DELETE FROM audit_events WHERE time < $1; diff --git a/internal/web/audit.templ b/internal/web/audit.templ new file mode 100644 index 0000000..e3efc74 --- /dev/null +++ b/internal/web/audit.templ @@ -0,0 +1,48 @@ +package web + +import "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" + +// AuditEntry is one row of an audit log. +type AuditEntry struct { + Time string + Actor string + Action string + Target string + IP string + RequestID string + Failed bool +} + +templ AuditPage(p Page, me Me, titleID, introID string, entries []AuditEntry, next string) { + @consoleShell(p, me) { + @settingsHeading(titleID, introID) + @auditList(entries) + if next != "" { + { i18n.T(ctx, "audit.older") } + } + } +} + +templ auditList(entries []AuditEntry) { + if len(entries) == 0 { +

{ i18n.T(ctx, "audit.empty") }

+ } else { + + } +} diff --git a/internal/web/audit_templ.go b/internal/web/audit_templ.go new file mode 100644 index 0000000..7de0047 --- /dev/null +++ b/internal/web/audit_templ.go @@ -0,0 +1,293 @@ +// Code generated by templ - DO NOT EDIT. + +// templ: version: v0.3.1118 + +package web + +//lint:file-ignore SA4006 This context is only used if a nested component is present. + +import "github.com/a-h/templ" +import templruntime "github.com/a-h/templ/runtime" + +import "git.zb-server.de/ZB-Server/uptimesebi/internal/i18n" + +// AuditEntry is one row of an audit log. +type AuditEntry struct { + Time string + Actor string + Action string + Target string + IP string + RequestID string + Failed bool +} + +func AuditPage(p Page, me Me, titleID, introID string, entries []AuditEntry, next string) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { + return templ_7745c5c3_CtxErr + } + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + ctx = templ.ClearChildren(ctx) + templ_7745c5c3_Var2 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + templ_7745c5c3_Err = settingsHeading(titleID, introID).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = auditList(entries).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + if next != "" { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 1, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var4 string + templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "audit.older")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/audit.templ`, Line: 21, Col: 126} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 3, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + return nil + }) + templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var2), templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + return nil + }) +} + +func auditList(entries []AuditEntry) templ.Component { + return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context + if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { + return templ_7745c5c3_CtxErr + } + templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) + if !templ_7745c5c3_IsBuffer { + defer func() { + templ_7745c5c3_BufErr := templruntime.ReleaseBuffer(templ_7745c5c3_Buffer) + if templ_7745c5c3_Err == nil { + templ_7745c5c3_Err = templ_7745c5c3_BufErr + } + }() + } + ctx = templ.InitializeContext(ctx) + ctx = templ.ClearChildren(ctx) + if len(entries) == 0 { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 4, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var6 string + templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "audit.empty")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/audit.templ`, Line: 28, Col: 60} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 5, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } else { + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 6, "") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } + return nil + }) +} + +var _ = templruntime.GeneratedTemplate diff --git a/internal/web/console.templ b/internal/web/console.templ index 466905e..bc1e843 100644 --- a/internal/web/console.templ +++ b/internal/web/console.templ @@ -83,7 +83,7 @@ type Identity struct { Email string } -templ Security(p Page, me Me, identities []Identity, canLink bool) { +templ Security(p Page, me Me, identities []Identity, canLink bool, activity []AuditEntry) { @consoleShell(p, me) {

{ i18n.T(ctx, "security.title") }

@@ -144,6 +144,11 @@ templ Security(p Page, me Me, identities []Identity, canLink bool) { { i18n.T(ctx, "security.sso.link") } }
+
+ @sectionHeading("security.activity") +

{ i18n.T(ctx, "security.activity_intro") }

+ @auditList(activity) +
} } @@ -194,6 +199,9 @@ templ SettingsIndex(p Page, me Me) { @settingsLink("/settings/org", "console.nav.org", "settings.org") @settingsLink("/settings/sso", "console.nav.sso", "settings.sso") } + if me.Can["audit.read"] { + @settingsLink("/settings/audit", "audit.title", "settings.audit") + } @settingsLink("/settings/security", "console.nav.security", "settings.security") } diff --git a/internal/web/console_templ.go b/internal/web/console_templ.go index 75cb4d2..d667745 100644 --- a/internal/web/console_templ.go +++ b/internal/web/console_templ.go @@ -304,7 +304,7 @@ type Identity struct { Email string } -func Security(p Page, me Me, identities []Identity, canLink bool) templ.Component { +func Security(p Page, me Me, identities []Identity, canLink bool, activity []AuditEntry) templ.Component { return templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context if templ_7745c5c3_CtxErr := ctx.Err(); templ_7745c5c3_CtxErr != nil { @@ -678,7 +678,36 @@ func Security(p Page, me Me, identities []Identity, canLink bool) templ.Componen return templ_7745c5c3_Err } } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, "
") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = sectionHeading("security.activity").Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 57, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var31 string + templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "security.activity_intro")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 149, Col: 88} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 58, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = auditList(activity).Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 59, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -711,33 +740,33 @@ func recoveryOutput() templ.Component { } ctx = templ.InitializeContext(ctx) ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 57, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -762,46 +791,46 @@ func policyBanner(msgID, actionID, href string) templ.Component { } ctx = templ.InitializeContext(ctx) ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 60, "

") - if templ_7745c5c3_Err != nil { - return templ_7745c5c3_Err - } - var templ_7745c5c3_Var35 string - templ_7745c5c3_Var35, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, msgID)) - if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 163, Col: 23} - } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var35)) - if templ_7745c5c3_Err != nil { - return templ_7745c5c3_Err - } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 61, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } var templ_7745c5c3_Var36 string - templ_7745c5c3_Var36, templ_7745c5c3_Err = templruntime.NewAttributeExpression(templ.SafeURL(href)).ResolveURL(ctx) + templ_7745c5c3_Var36, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, msgID)) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 164, Col: 32} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 168, Col: 23} } - _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ_7745c5c3_Var36) + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var36)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 62, "\" class=\"underline underline-offset-2\">") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 64, "

") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 65, "\" class=\"underline underline-offset-2\">") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var38 string + templ_7745c5c3_Var38, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, actionID)) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 169, Col: 95} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var38)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 66, "

") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -826,46 +855,46 @@ func settingsLink(href, titleID, hintID string) templ.Component { } ctx = templ.InitializeContext(ctx) ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 64, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 67, " ") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 68, "\" class=\"block border border-rule p-4 hover:border-ink\">") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } var templ_7745c5c3_Var41 string - templ_7745c5c3_Var41, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, hintID)) + templ_7745c5c3_Var41, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, titleID)) if templ_7745c5c3_Err != nil { - return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 172, Col: 67} + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 176, Col: 56} } _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var41)) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 67, "") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 69, " ") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var42 string + templ_7745c5c3_Var42, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, hintID)) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/console.templ`, Line: 177, Col: 67} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var42)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 70, "") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -891,7 +920,7 @@ func SettingsIndex(p Page, me Me) templ.Component { } ctx = templ.InitializeContext(ctx) ctx = templ.ClearChildren(ctx) - templ_7745c5c3_Var43 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { + templ_7745c5c3_Var44 := templruntime.GeneratedTemplate(func(templ_7745c5c3_Input templruntime.GeneratedComponentInput) (templ_7745c5c3_Err error) { templ_7745c5c3_W, ctx := templ_7745c5c3_Input.Writer, templ_7745c5c3_Input.Context templ_7745c5c3_Buffer, templ_7745c5c3_IsBuffer := templruntime.GetBuffer(templ_7745c5c3_W) if !templ_7745c5c3_IsBuffer { @@ -907,7 +936,7 @@ func SettingsIndex(p Page, me Me) templ.Component { if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 68, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 71, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } @@ -951,17 +980,23 @@ func SettingsIndex(p Page, me Me) templ.Component { return templ_7745c5c3_Err } } + if me.Can["audit.read"] { + templ_7745c5c3_Err = settingsLink("/settings/audit", "audit.title", "settings.audit").Render(ctx, templ_7745c5c3_Buffer) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + } templ_7745c5c3_Err = settingsLink("/settings/security", "console.nav.security", "settings.security").Render(ctx, templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } - templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 69, "
") + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 72, "
") if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } return nil }) - templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var43), templ_7745c5c3_Buffer) + templ_7745c5c3_Err = consoleShell(p, me).Render(templ.WithChildren(ctx, templ_7745c5c3_Var44), templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } diff --git a/internal/web/regions.templ b/internal/web/regions.templ index e6e7d3a..c9cac96 100644 --- a/internal/web/regions.templ +++ b/internal/web/regions.templ @@ -146,6 +146,7 @@ templ RegionsPage(p Page, me Me, v RegionsView) { templ AdminPage(p Page, me Me, v RegionsView, storage StorageView) { @consoleShell(p, me) { @settingsHeading("admin.title", "admin.intro") +

{ i18n.T(ctx, "audit.platform_title") }

@regionsBody(v) @storageSection(storage) } diff --git a/internal/web/regions_templ.go b/internal/web/regions_templ.go index 8ea5f18..ef3abed 100644 --- a/internal/web/regions_templ.go +++ b/internal/web/regions_templ.go @@ -729,6 +729,23 @@ func AdminPage(p Page, me Me, v RegionsView, storage StorageView) templ.Componen if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 55, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + var templ_7745c5c3_Var39 string + templ_7745c5c3_Var39, templ_7745c5c3_Err = templ.JoinStringErrs(i18n.T(ctx, "audit.platform_title")) + if templ_7745c5c3_Err != nil { + return templ.Error{Err: templ_7745c5c3_Err, FileName: `internal/web/regions.templ`, Line: 149, Col: 129} + } + _, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var39)) + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } + templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 56, "

") + if templ_7745c5c3_Err != nil { + return templ_7745c5c3_Err + } templ_7745c5c3_Err = regionsBody(v).Render(ctx, templ_7745c5c3_Buffer) if templ_7745c5c3_Err != nil { return templ_7745c5c3_Err