From 358b191976b54321f3140bd8e8cb8348a54913e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Sun, 22 Nov 2026 09:59:52 +0100 Subject: [PATCH] feat(api): record an audit log and show it to organizations, users and admins Every state-changing API route is mapped to an action; a test fails for unmapped routes. Successful changes are recorded with actor, API token, target, IP, user agent and request ID; failed sign-ins too. Names are taken from the response, never secrets. Organizations read their log with audit.read under Settings, users their account activity on the security page, admins the platform log. Entries expire after UPTIME_RETENTION_AUDIT. Closes #65 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3 --- internal/api/audit.go | 384 ++++++++++++++++++++++++++++++++++ internal/api/audit_test.go | 164 +++++++++++++++ internal/api/auth.go | 5 + internal/api/export_test.go | 3 + internal/api/housekeeping.go | 11 +- internal/api/invitations.go | 1 + internal/api/pages.go | 28 ++- internal/api/server.go | 5 +- internal/api/sso.go | 3 + internal/authz/authz.go | 2 + internal/i18n/locales/de.json | 59 ++++++ internal/i18n/locales/en.json | 59 ++++++ internal/web/audit.templ | 48 +++++ internal/web/audit_templ.go | 293 ++++++++++++++++++++++++++ internal/web/console.templ | 10 +- internal/web/console_templ.go | 167 +++++++++------ internal/web/regions.templ | 1 + internal/web/regions_templ.go | 17 ++ 18 files changed, 1184 insertions(+), 76 deletions(-) create mode 100644 internal/api/audit.go create mode 100644 internal/api/audit_test.go create mode 100644 internal/web/audit.templ create mode 100644 internal/web/audit_templ.go 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/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/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