Skip to content

Clarify authserver ownership and fix nil error returns - #7071

Merged
jhrozek merged 4 commits into
mainfrom
pr/authserver-resource-ownership
Nov 9, 2026
Merged

jhrozek merged 4 commits into
mainfrom
pr/authserver-resource-ownership

Conversation

@jhrozek

@jhrozek jhrozek commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Embedders need a clear ownership boundary when constructing an authorization server: a failed constructor must leave caller-owned storage open, while a successful server is responsible for closing it. The public API did not explain that distinction, and construction errors returned a non-nil Server interface containing a nil *server. Overlapping shutdown paths could also repeat cleanup and panic when closing memory storage twice.

  • Document storage ownership, possible storage writes before construction failure, and caller ownership of injected HTTP clients. Update package examples to release storage on failure and the server on success.
  • Return an explicit nil Server on construction errors instead of wrapping a typed-nil pointer in the interface.
  • Guard raw-server shutdown with sync.Once, retaining the joined error result for repeated and concurrent callers.
  • Add regression tests for validation and upstream-construction failures, including failure after delegate registration, plus concurrent shutdown and stable error results.

Type of change

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Dependency update
  • Documentation
  • Other (describe):

Test plan

  • Unit tests (task test)
  • E2E tests (task test-e2e)
  • Linting (task lint-fix)
  • Static verification: reviewed constructor cleanup and shutdown paths, inspected SEP and mecatl integration source, and ran git diff --check on the changes.

Tests and lint were deliberately not run locally at the author's request. New regression tests are included but have not been executed locally.

Does this introduce a user-facing change?

For Go API consumers, failed authserver.New calls previously returned a non-nil interface holding a nil pointer alongside the error. They now return a genuinely nil interface alongside the same error.

Previously, repeated raw-server Close calls repeated cleanup and could panic. Now cleanup executes once; concurrent callers wait for that execution, and every call returns the same shutdown result. Failed cleanup is not retried by subsequent calls. The first cleanup's ordering, successful construction, and HTTP behavior are unchanged.

Special notes for reviewers

The ownership documentation applies to authserver.New, not to the embedded runner constructor: after its initial nil-input checks, the runner closes supplied storage on construction failure. Failed raw construction can already have written to storage; this change does not introduce transactional rollback or alter storage capability requirements.

Idempotent closure is per server instance, not shared-storage reference counting or request draining. SEP's generation-specific non-owning storage wrapper and both consumers' existing draining/ownership boundaries remain necessary. Static inspection found no required changes in the inspected SEP and mecatl lifecycle paths; those wrappers already use once-only shutdown and do not rely on raw-close retries.

Make the lifecycle boundary explicit for the authserver package extraction: callers retain storage if New fails, successful servers own it until Close, and injected upstream HTTP clients remain caller-owned. Return a nil Server interface on construction errors.

Co-authored-by: Mecatl <[email protected]>
@github-actions github-actions Bot added the size/XS Extra small PR: < 100 lines changed label Nov 6, 2026
@codecov

codecov Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 80.95238% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 80.89%. Comparing base (3738fc9) to head (e42a64a).
⚠️ Report is 7 commits behind head on main.

Files with missing lines Patch % Lines
pkg/authserver/server_impl.go 76.47% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7071      +/-   ##
==========================================
- Coverage   80.90%   80.89%   -0.02%     
==========================================
  Files         864      864              
  Lines       88634    88639       +5     
==========================================
- Hits        71707    71702       -5     
- Misses      16922    16932      +10     
  Partials        5        5              

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

rdimitrov
rdimitrov previously approved these changes Nov 6, 2026

@rdimitrov rdimitrov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Approving: the typed-nil fix is correct and in the only place it can live, and the ownership docs match what the code already does.

Design: New is the only place *server becomes the Server interface, so returning an explicit nil there fixes the typed-nil-on-error case for every caller. A "typed nil" is a non-nil interface holding a nil pointer, so srv != nil checks pass and srv.Close() panics. The only in-tree caller (runner/embeddedauthserver.go) checks just err and already closes storage itself on failure, so nothing changes for it. External Go embedders now get a real nil on error. There are no CLI, HTTP, CRD or config changes. The regression test compares srv == nil directly rather than using require.Nil, which would accept a typed nil, so it actually catches the bug.

Non-blocking notes (fine as follow-ups):

  1. pkg/authserver/docs.go:20-48: the package-doc examples create storage.NewMemoryStorage(), return on a failed New, and never close the storage. Under the contract this PR documents (caller owns storage on failure), anyone who copies the example leaks MemoryStorage's cleanup goroutine on every failed New. Updating one example to close the storage on error would fix it.
  2. pkg/authserver/server.go:166-175 vs runner.NewEmbeddedAuthServerWithStorage: the two constructors take caller storage but behave in opposite ways on failure. New leaves it open; the runner closes it. You already called this out. A one-line pointer in the New doc would keep the planned extraction from reconciling them by accident.
  3. pkg/authserver/ownership_test.go: both failure cases fail before anything is written to storage. The window after delegate-client registration and migration, where buildProvider or NewHandler fails, is the one most likely to regress if someone adds cleanup there. A case that configures a delegate client and fails in NewHandler would cover it. The doc could also say that a failed New may already have written to storage.
  4. server.Close is documented as possibly panicking when called twice (MemoryStorage.Close closes a channel twice). A sync.Once in server.Close, like the runner's closeOnce, would make the concrete type safe. You scoped this out, so it's only a follow-up.

🤖 Reviewed with Claude Code

jhrozek and others added 3 commits November 7, 2026 17:58
New leaves storage caller-owned when construction fails. The package
examples returned the error without closing MemoryStorage, leaving its
cleanup goroutine running for callers that copied the examples.

Close storage on each error path and defer server cleanup after success,
so the examples demonstrate both sides of the ownership transfer.

Co-authored-by: Mecatl <[email protected]>
Direct embedders could run cleanup twice when shutdown paths overlapped.
Unlike the embedded runner, the raw server had no once-only guard, so
repeated Close calls could panic in MemoryStorage or repeat teardown.

Guard the existing cleanup sequence with sync.Once and retain its joined
error. Concurrent callers wait for cleanup and receive the same result;
later calls do not retry failed cleanup. Update the public contract and
cover concurrent closure, one-time resource release, and stable errors.

This is a per-server guarantee, not shared-storage reference counting.
Embedders must still drain requests and preserve their storage ownership
boundaries when replacing a server.

Co-authored-by: Mecatl <[email protected]>
Keeping storage open after New fails does not mean construction left it
unchanged. Delegate clients can already be registered before an upstream
fails, and callers need to distinguish this from the runner constructor,
which closes supplied storage after its initial nil-input checks.

Document both the possible writes and the different cleanup boundaries.
Add a regression case that registers a delegate, builds one upstream,
and fails the second. Assert that the server is nil, the first upstream
is drained, and storage remains open with the delegate still present.
This pins the existing behavior without adding rollback or changing
constructor ownership.

Co-authored-by: Mecatl <[email protected]>
@github-actions github-actions Bot added size/S Small PR: 100-299 lines changed and removed size/XS Extra small PR: < 100 lines changed labels Nov 7, 2026
@jhrozek

jhrozek commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

@rdimitrov Addressed the four follow-ups in three focused commits:

  • 69b1d41 — Close caller-owned storage on failed New in the package examples and defer server cleanup after success.
  • e42a64a — Document the runner's different failure-ownership boundary and that failed construction may already have written to storage. The new regression case registers a delegate, constructs the first upstream, then fails the second; it checks a genuinely nil server, retained delegate data, unclosed storage, and cleanup of the first provider. This uses a reachable upstream failure rather than forcing a handler failure.
  • bb57c76 — Make raw Server.Close once-only with sync.Once, preserving cleanup order and retaining joined errors. Concurrent/repeated calls return the same result; they do not retry failed cleanup. Added concurrent regression coverage.

I checked SEP and mecatl source through their MCP servers. The inspected paths do not depend on raw-close retries: SEP retires generations over non-owning storage wrappers, and mecatl uses the already-idempotent embedded runner. Both retain their existing draining and shared-storage ownership boundaries; no consumer changes were identified as necessary.

Also updated the PR description to call out the shutdown behavior change explicitly. git diff --check passed. Tests and lint were not run locally, as requested; the new tests remain for CI to verify.

@github-actions github-actions Bot added size/S Small PR: 100-299 lines changed and removed size/S Small PR: 100-299 lines changed labels Nov 7, 2026
@jhrozek
jhrozek merged commit 1df76a3 into main Nov 9, 2026
88 of 90 checks passed
@jhrozek
jhrozek deleted the pr/authserver-resource-ownership branch November 9, 2026 08:28
@github-actions github-actions Bot mentioned this pull request Nov 10, 2026
2 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/S Small PR: 100-299 lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants