Let each user pick the timezone timestamps are displayed in
Everything stays UTC: ingest still records Unix nanoseconds, ClickHouse
still stores UTC, every API response is still RFC3339 with a Z, and
queries are evaluated exactly as before. This changes only how those
instants are written on screen, so two people in two timezones looking
at one log line see the same instant written two ways -- never two
different lines, and never a different sort order.
Where the preference lives differs by deployment, and the three cases
are genuinely different products rather than one with fallbacks:
- Local login: server-side per named user (display_timezone on users,
PUT /auth/timezone), so it follows the person across browsers and
survives logout. Self-service at the RoleViewer floor, same as the
password change -- a viewer is the role most likely to be *only*
reading logs, so gating it higher would make it useless.
- Public demo: sessionStorage, so every new session starts at UTC. A
shared account's visitors have nothing to do with each other.
- Neither: localStorage, since there's no per-user record to write to.
api/cmd/api/main.go now imports time/tzdata. The image is
distroless/static with no /usr/share/zoneinfo, so LoadLocation would
otherwise reject every real zone name and the validation would refuse
every valid input.
Two details worth knowing when reading $lib/time.ts. Sub-second digits
are copied verbatim from the source string rather than round-tripped
through a JS Date, which is millisecond-precision and would silently
drop six digits of a ClickHouse nanosecond timestamp; expanding a result
row shows the localized value and the full-precision UTC original
together. And chart axes format their own labels, because ECharts'
type: 'time' axis renders in the browser's zone with no override --
which today puts a chart's clock out of step with the table beside it.
Timestamps are detected by value, not by column name: query output is
arbitrary, so a column called "timestamp" holding something else must
not be mangled, and `stats max(timestamp) as newest` must still be
formatted.
Verified against real zones including both sides of a DST boundary
(America/New_York at -05:00 in January, -04:00 in July), a half-hour
offset, and date rollover.
This commit is contained in:
@@ -19,6 +19,13 @@ import (
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
// Embeds the IANA tz database in the binary. This image is
|
||||
// distroless/static -- it has no /usr/share/zoneinfo at all, so
|
||||
// time.LoadLocation would fail for every zone except UTC, and
|
||||
// localauth's timezone validation would reject every real name a
|
||||
// user could pick. ~450KB of binary for a feature whose whole job is
|
||||
// knowing what "America/New_York" means.
|
||||
_ "time/tzdata"
|
||||
|
||||
"github.com/ClickHouse/clickhouse-go/v2"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
@@ -40,7 +40,10 @@ func (f *fakeStore) CreateUser(_ context.Context, username, passwordHash string,
|
||||
}
|
||||
f.nextID++
|
||||
id := "user-" + strconv.Itoa(f.nextID)
|
||||
u := &User{ID: id, Username: username, Role: role, CreatedAt: time.Now()}
|
||||
// DisplayTimezone mirrors the schema's NOT NULL DEFAULT 'UTC' (see
|
||||
// migration 0042) -- a fake that left it empty would let a handler
|
||||
// bug that drops the default pass unnoticed.
|
||||
u := &User{ID: id, Username: username, Role: role, DisplayTimezone: "UTC", CreatedAt: time.Now()}
|
||||
f.users[id] = u
|
||||
f.hashes[id] = passwordHash
|
||||
f.byUsername[username] = id
|
||||
@@ -114,6 +117,18 @@ func (f *fakeStore) SetRole(_ context.Context, userID string, role authz.Role) e
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetDisplayTimezone deliberately does not touch f.sessions -- unlike
|
||||
// SetRole/SetPasswordHash above, changing a rendering preference is not
|
||||
// a reason to sign anyone out, and the test for that asserts it.
|
||||
func (f *fakeStore) SetDisplayTimezone(_ context.Context, userID, tz string) error {
|
||||
u, ok := f.users[userID]
|
||||
if !ok {
|
||||
return ErrNotFound
|
||||
}
|
||||
u.DisplayTimezone = tz
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) CountLocalUsers(_ context.Context) (int, error) {
|
||||
return len(f.users), nil
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ type store interface {
|
||||
DeleteUser(ctx context.Context, id string) error
|
||||
SetPasswordHash(ctx context.Context, userID, hash string) error
|
||||
SetRole(ctx context.Context, userID string, role authz.Role) error
|
||||
SetDisplayTimezone(ctx context.Context, userID, tz string) error
|
||||
CountUsersWithRole(ctx context.Context, role authz.Role) (int, error)
|
||||
CreateSession(ctx context.Context, userID, tenantID string, role authz.Role, ttl time.Duration) (string, error)
|
||||
DeleteSessionByHash(ctx context.Context, tokenHash string) error
|
||||
@@ -113,6 +114,11 @@ func (h *Handler) RegisterRoutes(mux *http.ServeMux) {
|
||||
mux.HandleFunc("POST /auth/logout", h.handleLogout)
|
||||
mux.HandleFunc("GET /auth/session", authz.RequireRole(h.authorizer, authz.RoleViewer, h.handleGetSession))
|
||||
mux.HandleFunc("POST /auth/password", authz.RequireRole(h.authorizer, authz.RoleViewer, h.handleChangeOwnPassword))
|
||||
// Self-service, same RoleViewer floor as the password change above:
|
||||
// how a user's own clock is rendered is nobody else's permission to
|
||||
// grant, and a Viewer -- the role most likely to be *only* reading
|
||||
// logs -- needs it most.
|
||||
mux.HandleFunc("PUT /auth/timezone", authz.RequireRole(h.authorizer, authz.RoleViewer, h.handleSetTimezone))
|
||||
|
||||
mux.HandleFunc("GET /auth/users", authz.RequireRole(h.authorizer, authz.RoleAdmin, h.handleListUsers))
|
||||
mux.HandleFunc("POST /auth/users", authz.RequireRole(h.authorizer, authz.RoleAdmin, h.handleCreateUser))
|
||||
@@ -138,6 +144,12 @@ type sessionResponse struct {
|
||||
TenantID string `json:"tenant_id"`
|
||||
Username string `json:"username"`
|
||||
Role string `json:"role"`
|
||||
// Timezone is the user's stored display preference (IANA zone name,
|
||||
// "UTC" by default). Sent on the session so the web UI knows which
|
||||
// offset to render in from its very first paint, without a second
|
||||
// round trip -- omitted from the login response, where the store
|
||||
// lookup that produces it hasn't happened.
|
||||
Timezone string `json:"timezone,omitempty"`
|
||||
}
|
||||
|
||||
func (h *Handler) handleLogin(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -217,6 +229,7 @@ func (h *Handler) handleGetSession(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
writeJSON(w, http.StatusOK, sessionResponse{
|
||||
UserID: user.ID, TenantID: identity.TenantID, Username: user.Username, Role: string(user.Role),
|
||||
Timezone: user.DisplayTimezone,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -542,6 +555,62 @@ func (h *Handler) handleChangeOwnPassword(w http.ResponseWriter, r *http.Request
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
type setTimezoneRequest struct {
|
||||
Timezone string `json:"timezone"`
|
||||
}
|
||||
|
||||
// maxTimezoneLen bounds the input before it reaches LoadLocation, which
|
||||
// takes the value as a filesystem-ish lookup key. The longest real IANA
|
||||
// name is well under this ("America/Argentina/ComodRivadavia", 31).
|
||||
const maxTimezoneLen = 64
|
||||
|
||||
// handleSetTimezone stores the caller's own display-timezone preference
|
||||
// -- see metadata/migrations/0042_add_user_display_timezone.sql for why
|
||||
// this is presentation-only and can never affect what data a query
|
||||
// returns.
|
||||
//
|
||||
// Validation is time.LoadLocation against the tzdata embedded in this
|
||||
// binary (see the time/tzdata import in cmd/api/main.go), not a
|
||||
// hand-maintained allowlist: the set of valid zone names is the tz
|
||||
// database's to define, and it changes a few times a year. Rejecting
|
||||
// unknown names here matters because the value is echoed back to every
|
||||
// client on the session response -- an unvalidated string would just be
|
||||
// a stored round trip for whatever someone put in.
|
||||
func (h *Handler) handleSetTimezone(w http.ResponseWriter, r *http.Request) {
|
||||
var req setTimezoneRequest
|
||||
if !decodeJSON(w, r, &req) {
|
||||
return
|
||||
}
|
||||
if req.Timezone == "" {
|
||||
writeError(w, http.StatusBadRequest, "timezone must not be empty")
|
||||
return
|
||||
}
|
||||
if len(req.Timezone) > maxTimezoneLen {
|
||||
writeError(w, http.StatusBadRequest, "timezone is not a valid IANA zone name")
|
||||
return
|
||||
}
|
||||
// "Local" is a valid LoadLocation argument but means "whatever zone
|
||||
// the *server* process is in", which is meaningless as a per-user
|
||||
// display preference and would render differently depending on which
|
||||
// host answered. The browser's own zone is the client's business to
|
||||
// resolve into a real name before sending it.
|
||||
if req.Timezone == "Local" {
|
||||
writeError(w, http.StatusBadRequest, "timezone must be a specific IANA zone name, not \"Local\"")
|
||||
return
|
||||
}
|
||||
if _, err := time.LoadLocation(req.Timezone); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "timezone is not a valid IANA zone name")
|
||||
return
|
||||
}
|
||||
|
||||
identity, _ := authz.IdentityFromContext(r.Context())
|
||||
if err := h.store.SetDisplayTimezone(r.Context(), identity.UserID, req.Timezone); err != nil {
|
||||
h.writeStoreErr(w, err, "setting timezone")
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (h *Handler) setCookie(w http.ResponseWriter, raw string, ttl time.Duration) {
|
||||
http.SetCookie(w, &http.Cookie{
|
||||
Name: sessionCookieName,
|
||||
|
||||
@@ -702,3 +702,93 @@ func TestChangeOwnPasswordRequiresAuth(t *testing.T) {
|
||||
t.Fatalf("status = %d, want 401 with no session", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetTimezoneStoresAndReportsOnSession(t *testing.T) {
|
||||
fs := newFakeStore()
|
||||
// RoleViewer deliberately: a viewer is the role most likely to be
|
||||
// only ever reading logs, and reading logs is what this setting is
|
||||
// for -- if it needed a higher role it would be useless.
|
||||
mustCreateUser(t, fs, "vince", "vincepassword", authz.RoleViewer)
|
||||
_, mux := newTestHandler(t, fs)
|
||||
|
||||
login := doRequest(t, mux, http.MethodPost, "/auth/login", `{"username":"vince","password":"vincepassword"}`, nil)
|
||||
cookie := sessionCookieFrom(login)
|
||||
|
||||
// Defaults to UTC before anything is set.
|
||||
before := doRequest(t, mux, http.MethodGet, "/auth/session", "", cookie)
|
||||
if got := decodeSessionTimezone(t, before); got != "UTC" {
|
||||
t.Fatalf("initial session timezone = %q, want %q", got, "UTC")
|
||||
}
|
||||
|
||||
rec := doRequest(t, mux, http.MethodPut, "/auth/timezone", `{"timezone":"America/New_York"}`, cookie)
|
||||
if rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("status = %d, want 204, body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// The same session keeps working -- unlike a password or role
|
||||
// change, a rendering preference is no reason to sign anyone out.
|
||||
after := doRequest(t, mux, http.MethodGet, "/auth/session", "", cookie)
|
||||
if after.Code != http.StatusOK {
|
||||
t.Fatalf("session after timezone change: status = %d, want 200", after.Code)
|
||||
}
|
||||
if got := decodeSessionTimezone(t, after); got != "America/New_York" {
|
||||
t.Errorf("session timezone = %q, want %q", got, "America/New_York")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetTimezoneRejectsInvalidZones(t *testing.T) {
|
||||
fs := newFakeStore()
|
||||
mustCreateUser(t, fs, "vince", "vincepassword", authz.RoleViewer)
|
||||
_, mux := newTestHandler(t, fs)
|
||||
|
||||
login := doRequest(t, mux, http.MethodPost, "/auth/login", `{"username":"vince","password":"vincepassword"}`, nil)
|
||||
cookie := sessionCookieFrom(login)
|
||||
|
||||
cases := map[string]string{
|
||||
"empty": `{"timezone":""}`,
|
||||
"not a zone": `{"timezone":"Mars/Olympus_Mons"}`,
|
||||
"fixed offset": `{"timezone":"-07:00"}`,
|
||||
"server-local": `{"timezone":"Local"}`,
|
||||
"absurdly long": `{"timezone":"` + strings.Repeat("x", 200) + `"}`,
|
||||
"path traversal": `{"timezone":"../../etc/passwd"}`,
|
||||
}
|
||||
for name, body := range cases {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
rec := doRequest(t, mux, http.MethodPut, "/auth/timezone", body, cookie)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400, body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Nothing above should have changed the stored value.
|
||||
sess := doRequest(t, mux, http.MethodGet, "/auth/session", "", cookie)
|
||||
if got := decodeSessionTimezone(t, sess); got != "UTC" {
|
||||
t.Errorf("timezone after rejected requests = %q, want %q", got, "UTC")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetTimezoneRequiresAuth(t *testing.T) {
|
||||
fs := newFakeStore()
|
||||
mustCreateUser(t, fs, "vince", "vincepassword", authz.RoleViewer)
|
||||
_, mux := newTestHandler(t, fs)
|
||||
|
||||
rec := doRequest(t, mux, http.MethodPut, "/auth/timezone", `{"timezone":"Europe/Berlin"}`, nil)
|
||||
if rec.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("status = %d, want 401", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func decodeSessionTimezone(t *testing.T, rec *httptest.ResponseRecorder) string {
|
||||
t.Helper()
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("session status = %d, want 200, body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var body struct {
|
||||
Timezone string `json:"timezone"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil {
|
||||
t.Fatalf("decoding session body: %v", err)
|
||||
}
|
||||
return body.Timezone
|
||||
}
|
||||
|
||||
+30
-6
@@ -52,10 +52,15 @@ var (
|
||||
const defaultTenantID = "default"
|
||||
|
||||
type User struct {
|
||||
ID string
|
||||
Username string
|
||||
Role authz.Role
|
||||
CreatedAt time.Time
|
||||
ID string
|
||||
Username string
|
||||
Role authz.Role
|
||||
// DisplayTimezone is an IANA zone name the web UI renders timestamps
|
||||
// in -- presentation only, never applied to stored or queried data
|
||||
// (see metadata/migrations/0042_add_user_display_timezone.sql).
|
||||
// 'UTC' for any user who has never changed it.
|
||||
DisplayTimezone string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
@@ -174,11 +179,11 @@ func (s *Store) GetUserByID(ctx context.Context, id string) (*User, error) {
|
||||
var u User
|
||||
var role string
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
SELECT u.id, u.username, tm.role, u.created_at
|
||||
SELECT u.id, u.username, tm.role, u.display_timezone, u.created_at
|
||||
FROM users u
|
||||
JOIN tenant_memberships tm ON tm.user_id = u.id AND tm.tenant_id = $1
|
||||
WHERE u.id = $2 AND u.username IS NOT NULL`, defaultTenantID, id).
|
||||
Scan(&u.ID, &u.Username, &role, &u.CreatedAt)
|
||||
Scan(&u.ID, &u.Username, &role, &u.DisplayTimezone, &u.CreatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
@@ -189,6 +194,25 @@ func (s *Store) GetUserByID(ctx context.Context, id string) (*User, error) {
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
// SetDisplayTimezone stores one user's display-timezone preference. It
|
||||
// deliberately does NOT revoke sessions the way SetPasswordHash does --
|
||||
// this is a rendering preference, not a credential, and a user changing
|
||||
// how their clock reads has no reason to be signed out. The caller is
|
||||
// responsible for having validated tz against the tz database first
|
||||
// (see handleSetTimezone); the column has no CHECK constraint.
|
||||
func (s *Store) SetDisplayTimezone(ctx context.Context, id, tz string) error {
|
||||
tag, err := s.pool.Exec(ctx, `
|
||||
UPDATE users SET display_timezone = $1, updated_at = now()
|
||||
WHERE id = $2 AND username IS NOT NULL`, tz, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if tag.RowsAffected() == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteUser cascades to the user's tenant_memberships and
|
||||
// local_sessions rows (both ON DELETE CASCADE) -- a deleted user's
|
||||
// existing sessions stop validating immediately, not just their next
|
||||
|
||||
@@ -286,3 +286,56 @@ func TestIntegrationGetPasswordHashByID(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestIntegrationDisplayTimezoneDefaultsAndPersists is the half
|
||||
// handler_test.go's fake can't prove: that migration 0042's column
|
||||
// actually exists with its NOT NULL DEFAULT 'UTC', that GetUserByID's
|
||||
// SELECT names it correctly, and that a session created before the
|
||||
// change keeps working after it (the UPDATE deliberately doesn't touch
|
||||
// local_sessions, unlike SetPasswordHash/SetRole).
|
||||
func TestIntegrationDisplayTimezoneDefaultsAndPersists(t *testing.T) {
|
||||
store := integrationStore(t)
|
||||
ctx := context.Background()
|
||||
username := testUsername(t)
|
||||
|
||||
hash, _ := HashPassword("password1")
|
||||
user, err := store.CreateUser(ctx, username, hash, authz.RoleViewer)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateUser: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = store.DeleteUser(ctx, user.ID) })
|
||||
|
||||
fetched, err := store.GetUserByID(ctx, user.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetUserByID: %v", err)
|
||||
}
|
||||
if fetched.DisplayTimezone != "UTC" {
|
||||
t.Fatalf("new user DisplayTimezone = %q, want %q (schema default)", fetched.DisplayTimezone, "UTC")
|
||||
}
|
||||
|
||||
raw, err := store.CreateSession(ctx, user.ID, "default", authz.RoleViewer, time.Hour)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateSession: %v", err)
|
||||
}
|
||||
|
||||
if err := store.SetDisplayTimezone(ctx, user.ID, "Australia/Adelaide"); err != nil {
|
||||
t.Fatalf("SetDisplayTimezone: %v", err)
|
||||
}
|
||||
fetched, err = store.GetUserByID(ctx, user.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("GetUserByID after set: %v", err)
|
||||
}
|
||||
if fetched.DisplayTimezone != "Australia/Adelaide" {
|
||||
t.Errorf("DisplayTimezone = %q, want %q", fetched.DisplayTimezone, "Australia/Adelaide")
|
||||
}
|
||||
|
||||
if _, err := store.GetSession(ctx, hashToken(raw)); err != nil {
|
||||
t.Errorf("session after timezone change: %v, want it to still be valid", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIntegrationSetDisplayTimezoneUnknownUser(t *testing.T) {
|
||||
store := integrationStore(t)
|
||||
if err := store.SetDisplayTimezone(context.Background(), uuid.NewString(), "UTC"); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("SetDisplayTimezone on missing user = %v, want ErrNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user