Skip to content

refactor: simplify code across packages for clarity#196

Merged
appleboy merged 1 commit into
mainfrom
refactor/simplify-codebase
May 23, 2026
Merged

refactor: simplify code across packages for clarity#196
appleboy merged 1 commit into
mainfrom
refactor/simplify-codebase

Conversation

@appleboy
Copy link
Copy Markdown
Member

Summary

Behavior-preserving simplification pass across the codebase, applied package-by-package. Replaces if/else and errors.Is chains with switch/guard clauses, extracts shared helpers for duplicated logic, and removes dead/redundant branches. No functional, API, or schema changes; net −88 lines across 24 files.

AI Authorship

  • No AI was used in this PR
  • AI was used. Details:
    • Tool / model: Claude Code (Opus 4.7), code-simplifier agent dispatched per package
    • AI-authored files: all 24 changed files
    • Human line-by-line reviewed: none yet — reviewer attention required, especially on core paths below

Change classification

  • Core code (broad impact — needs line-by-line review)
  • Leaf node

Touches auth, token issuance, middleware (CSRF/session/metrics-auth), config validation, and the store layer. Security-sensitive invariants (constant-time comparisons, PKCE/RFC 8707 logic, JWT claim namespacing, StringArray null-vs-[] serialization) were explicitly preserved, but should be confirmed by review.

Plan reference

No plan.md. Goal: improve clarity/consistency/maintainability without changing behavior or exported signatures, following the repo's coding conventions (early returns, switch/lookup tables over if/else chains, http.Status* constants).

Verification

  • Existing unit/integration tests pass (make test — full suite green)
  • No new tests added — change is behavior-preserving and covered by the existing suite
  • Stress / soak test: N/A
  • Also verified: make generate (clean), make fmt (clean), make build (OK), make lint (0 issues)
  • Manual verification for reviewer: make generate && make lint && make test

Verifiability check

  • No behavior change intended — existing tests are the contract
  • Reviewer can judge correctness by confirming each hunk is a faithful rewrite of the original
  • Failures would surface in the existing test suite

Security check

  • No secrets in code
  • No external input handling changed (CSRF/session/metrics-auth rewrites preserve exact validation and constant-time compares)
  • No permission/rate-limit/error-leak behavior changed

Risk & rollback

  • Risk: A simplification subtly altering control flow in a core path (e.g. an error switch not matching the original errors.Is chain, or a guard clause changing an edge case). Mitigated by full test + lint pass, but unreviewed.
  • Rollback: Single commit — revert 382c557 or close the PR; no migrations or data changes.

Reviewer guide

  • Read carefully:
    • internal/services/token_exchange.go, internal/token/local.go — token issuance/expiry logic
    • internal/middleware/csrf.go, middleware/auth.go, middleware/metrics_auth.go — security checks and constant-time compares
    • internal/config/config.go — validation helpers (error messages must stay byte-identical)
    • internal/cache/util.go (+ memory.go/rueidis.go) — new generic cache-aside helper, verify singleflight re-check ordering
  • Spot-check OK: internal/util/*, internal/core/client_type.go, internal/handlers/audit.go/auth.go/device.go, internal/store/*, scripts/build_assets.go, internal/metrics/http.go

🤖 Generated with Claude Code

- Replace if/else and errors.Is chains with switch and guard clauses
- Extract shared helpers for duplicated validation and rendering logic
- Deduplicate cache-aside logic behind a single generic helper
- Hoist repeated periodic-job bodies into reusable closures
- Collapse redundant token expiry and audit field-masking checks

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Copilot AI review requested due to automatic review settings May 23, 2026 10:24
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR is a broad, behavior-preserving refactor pass across core AuthGate packages (token issuance, middleware, config validation, caching, handlers, and bootstrap), aiming to simplify control flow, reduce duplication, and centralize repeated helper logic without changing exported APIs or runtime behavior.

Changes:

  • Extracted/shared helpers to reduce duplication (e.g., cache-aside singleflight helper, repeated config validation, shared render/abort helpers).
  • Simplified control flow via guard clauses / switch blocks across handlers, middleware, and services.
  • Small internal cleanups (output file selection in asset build script, context string getter helper, minor bootstrap job refactors).

Reviewed changes

Copilot reviewed 23 out of 24 changed files in this pull request and generated no comments.

Show a summary per file
File Description
scripts/build_assets.go Extracts shared helpers for esbuild error handling and output file selection.
internal/util/url.go Simplifies relative redirect safety checks into a single boolean expression.
internal/util/context.go Adds a shared context string accessor and reuses it for request metadata getters.
internal/token/local.go Simplifies symmetric/asymmetric public key selection and TTL/expiry calculation flow.
internal/store/user.go Refactors username-conflict checks into a switch/guard style without changing outcomes.
internal/store/sqlite.go Simplifies default admin password selection while preserving generated-password tracking.
internal/services/token_exchange.go Preserves device-code metrics while simplifying expired vs invalid branching.
internal/services/audit.go Extracts case-insensitive substring matching helper and reuses it for masking decisions.
internal/middleware/metrics_auth.go Centralizes repeated 401 abort logic while preserving constant-time token compare.
internal/middleware/csrf.go Extracts state-changing method detection and centralizes CSRF-forbidden rendering.
internal/middleware/auth.go Extracts session-clear+save helper to reduce duplication on stale/disabled sessions.
internal/metrics/http.go Adds a small helper for success/failure label mapping and simplifies metrics middleware gating.
internal/handlers/device.go Simplifies default scope assignment and error mapping via switch cases.
internal/handlers/auth.go Centralizes login page rendering props in a helper to reduce duplication.
internal/handlers/audit.go Extracts shared audit filter parsing used by both list and CSV export.
internal/core/client_type.go Reuses OrDefault() to simplify normalization logic.
internal/config/config.go Refactors cache-type validation and repeated duration checks into shared helpers (error strings preserved).
internal/cache/util.go Introduces a shared generic cache-aside + singleflight helper for reuse by cache implementations.
internal/cache/rueidis.go Switches GetWithFetch to reuse the shared cache-aside helper.
internal/cache/memory.go Switches GetWithFetch to reuse the shared cache-aside helper; simplifies reaper enable/disable logic.
internal/bootstrap/server.go Extracts repeated cleanup/update job bodies into local closures for clarity.
internal/bootstrap/ratelimit.go Simplifies enabled/disabled rate limit middleware selection with an early return.
internal/bootstrap/providers.go Removes redundant err declaration while keeping key derivation logic intact.
internal/auth/oauth_provider.go Simplifies display-name fallback branch while preserving provider naming behavior.
Files not reviewed (1)
  • scripts/build_assets.go: Language not supported

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@appleboy appleboy merged commit c50c520 into main May 23, 2026
23 of 27 checks passed
@appleboy appleboy deleted the refactor/simplify-codebase branch May 23, 2026 10:38
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