Skip to content

Log out after 12 hours#205

Open
alexsapps wants to merge 1 commit intomainfrom
alex/auth-cookie-expiration
Open

Log out after 12 hours#205
alexsapps wants to merge 1 commit intomainfrom
alex/auth-cookie-expiration

Conversation

@alexsapps
Copy link
Collaborator

@alexsapps alexsapps commented Dec 21, 2023

After a Google account is disabled or password reset, we need ADB access to expire in less than 30 days which is the current behavior. However, this change avoids expiring the session too quickly in order to avoid data loss until we can set up sessions to renew automatically before they expire if the user is still working or verify this is already happening.

Summary by CodeRabbit

  • Session Management
    • Authentication session timeout duration has been reduced from 30 days to 12 hours. Users will be required to re-authenticate more frequently.

After a Google account is disabled or password reset, we need ADB access to expire in less than 30 days which is the current behavior. However, this change avoids expiring the session too quickly in order to avoid data loss until we can set up sessions to renew automatically before they expire if the user is still working or verify this is already happening.
Copy link
Member

@jakehobbs jakehobbs left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm but you are gonna make almira's life harder 😆

@alexsapps
Copy link
Collaborator Author

Still thinking about this. In an emergency we could shut down the ADB and start it back up with different keys, and I don't want someone to be in the middle of taking attendance without any indication that their session is expiring imminently.

@alexsapps
Copy link
Collaborator Author

(In addition to rotating the server key in the event of an emergency) Maybe we can make the cookie expire at 5AM to avoid people getting signed out while trying to do something like taking attendance. Might update this PR for that eventually.

ChatGPT and I co-authored this function (not tested)

package main

import (
	"fmt"
	"time"
)

func next5AMPTAfter24Hours() time.Time {
	// Get the current time in PT
	loc, err := time.LoadLocation("America/Los_Angeles")
	if err != nil {
		panic(err)
	}
	now := time.Now().In(loc)

	// Calculate 5 AM PT tomorrow
	tomorrow := now.AddDate(0, 0, 1)
	tomorrow5AM := time.Date(tomorrow.Year(), tomorrow.Month(), tomorrow.Day(), 5, 0, 0, 0, loc)

	// If tomorrow's 5 AM PT is more than 24 hours from now, use it
	if tomorrow5AM.After(now.Add(24 * time.Hour)) {
		return tomorrow5AM
	}

	// Otherwise, calculate 5 AM PT the day after tomorrow
	dayAfterTomorrow := now.AddDate(0, 0, 2)
	dayAfterTomorrow5AM := time.Date(dayAfterTomorrow.Year(), dayAfterTomorrow.Month(), dayAfterTomorrow.Day(), 5, 0, 0, 0, loc)

	return dayAfterTomorrow5AM
}

@jakehobbs
Copy link
Member

@coderabbitai full review

@coderabbitai
Copy link

coderabbitai bot commented Feb 28, 2026

✅ Actions performed

Full review triggered.

@coderabbitai
Copy link

coderabbitai bot commented Feb 28, 2026

📝 Walkthrough

Walkthrough

The auth-session cookie MaxAge in main.go was reduced from 30 days to 12 hours, shortening the session lifetime before re-authentication is required. No logic or error handling modifications were introduced.

Changes

Cohort / File(s) Summary
Auth Session Configuration
main.go
Modified setAuthSession function to reduce auth-session cookie MaxAge from 30 days to 12 hours.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~3 minutes

Poem

🐰 Hops of change, so swift and light,
Sessions now expire faster—kept tight,
From thirty suns to twelve hours' flight,
Security bounds with renewed might!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Log out after 12 hours' directly relates to the main change: updating the auth-session cookie MaxAge from 30 days to 12 hours.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch alex/auth-cookie-expiration

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@main.go`:
- Around line 143-146: The session uses a fixed 12-hour MaxAge and is not
refreshed on authenticated requests; update authRoleMiddleware and
apiRoleMiddleware so they perform rolling renewal by calling setAuthSession(w,
r, user) after authentication succeeds (i.e., immediately after getAuthedADBUser
returns a valid user in authRoleMiddleware, and immediately after successful
authentication in apiRoleMiddleware), ensuring the existing cookie/session is
reset to extend the 12-hour window on each validated request.

ℹ️ Review info

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 446e58a and 1ce0175.

📒 Files selected for processing (1)
  • main.go

Comment on lines +143 to 146
// MaxAge is 12 hours in seconds
MaxAge: 12 * // hours
60 * // minutes
60, // seconds
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== setAuthSession definition + call sites =="
rg -nP --type=go '\bfunc\s+setAuthSession\b|\bsetAuthSession\s*\(' -C2

echo
echo "== auth middlewares and session persistence usage =="
rg -nP --type=go 'authRoleMiddleware|apiRoleMiddleware|sessionStore\.Save\(' -C3

Repository: dxe/adb

Length of output: 3291


🏁 Script executed:

sed -n '311,337p' main.go && echo "---" && sed -n '396,412p' main.go

Repository: dxe/adb

Length of output: 1261


Implement rolling session renewal; current 12-hour MaxAge is a hard cutoff.

The session is only set during sign-in (line 514) with a fixed 12-hour expiry and is never refreshed on authenticated requests. Both authRoleMiddleware and apiRoleMiddleware validate the existing session but do not renew it. This means active users will be logged out 12 hours from login time regardless of ongoing activity, which conflicts with the stated goal of avoiding mid-session disruption.

Add session renewal in both auth middlewares on successful authentication:

  • In authRoleMiddleware after the getAuthedADBUser check succeeds, call setAuthSession(w, r, user) to extend the 12-hour window.
  • In apiRoleMiddleware immediately after successful authentication, call setAuthSession(w, r, user).
Proposed fix example (rolling renewal on authenticated requests)
 func (c MainController) authRoleMiddleware(h http.Handler, allowedRoles []string) http.Handler {
 	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		user, authed := getAuthedADBUser(c.db, r)
 		if !authed {
 			// Delete the cookie if it doesn't auth.
 			c := &http.Cookie{
 				Name:     "auth-session",
 				Path:     "/",
 				MaxAge:   -1,
 				HttpOnly: true,
 				SameSite: http.SameSiteLaxMode,
 			}
 			http.SetCookie(w, c)

 			http.Redirect(w, r, "/login", http.StatusFound)
 			return
 		}

+		// Rolling renewal: keep active sessions alive.
+		if err := setAuthSession(w, r, user); err != nil {
+			log.Println("failed to refresh auth session:", err)
+		}
+
 		if !userIsAllowed(allowedRoles, user) {
 			http.Redirect(w, r.WithContext(setUserContext(r, user)), "/403", http.StatusFound)
 			return
 		}

 		// Request is authed at this point.
 		h.ServeHTTP(w, r.WithContext(setUserContext(r, user)))
 	})
 }

 func (c MainController) apiRoleMiddleware(h http.Handler, allowedRoles []string) http.Handler {
 	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
 		user, authed := getAuthedADBUser(c.db, r)

 		if !authed {
 			http.Error(w, http.StatusText(400), 400)
 			return
 		}
+
+		// Rolling renewal for API activity too.
+		if err := setAuthSession(w, r, user); err != nil {
+			log.Println("failed to refresh auth session:", err)
+		}

 		if !userIsAllowed(allowedRoles, user) {
 			http.Error(w, http.StatusText(403), 403)
 			return
 		}

 		// Request is authed at this point.
 		h.ServeHTTP(w, r)
 	})
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@main.go` around lines 143 - 146, The session uses a fixed 12-hour MaxAge and
is not refreshed on authenticated requests; update authRoleMiddleware and
apiRoleMiddleware so they perform rolling renewal by calling setAuthSession(w,
r, user) after authentication succeeds (i.e., immediately after getAuthedADBUser
returns a valid user in authRoleMiddleware, and immediately after successful
authentication in apiRoleMiddleware), ensuring the existing cookie/session is
reset to extend the 12-hour window on each validated request.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants