Skip to content

Add RestoreHijackPrevention and RestoreSession interface stub#4405

Open
yrobla wants to merge 2 commits intomainfrom
issue-4216
Open

Add RestoreHijackPrevention and RestoreSession interface stub#4405
yrobla wants to merge 2 commits intomainfrom
issue-4216

Conversation

@yrobla
Copy link
Copy Markdown
Contributor

@yrobla yrobla commented Mar 27, 2026

Summary

Add the infrastructure needed to reconstruct hijack-prevention state from Redis-persisted metadata, enabling cross-pod token validation in horizontal scaling scenarios.

  • security.go: Add RestoreHijackPrevention(), the restore counterpart to PreventSessionHijacking(). Rebuilds a hijackPreventionDecorator from persisted tokenHash + tokenSaltHex + hmacSecret without re-hashing a live token. Returns errors for nil session, missing salt on authenticated sessions, and invalid hex salt.

  • factory.go: Add RestoreSession() to the MultiSessionFactory interface with full doc comment (backend ID parsing, session hint lookup, routing-table rebuild, hijack-prevention re-application). Add a stub implementation on defaultMultiSessionFactory (returns "not yet implemented"); full reconnection logic is deferred. Document the cross-replica HMAC secret consistency requirement on defaultHMACSecret.

  • decorating_factory.go: Forward RestoreSession() to the base factory; decorators are not re-applied during restore.

  • mocks/mock_factory.go: Regenerate mock to include RestoreSession().

  • restore_test.go: Unit tests covering nil session, missing salt, invalid hex, anonymous session round-trip, authenticated store→restore→validate round-trip, and cross-replica secret mismatch.

Fixes #4216

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)
  • Manual testing (describe below)

Changes

File Change

Does this introduce a user-facing change?

Special notes for reviewers

…tion

Add MetadataKeyBackendSessionPrefix ("vmcp.backend.session.") constant and
extend populateBackendMetadata to write vmcp.backend.session.{workloadID} →
backend_session_id for each successfully connected backend alongside the
existing MetadataKeyBackendIDs entry.

This closes the gap identified in RC-8 (#4211): per-backend
session IDs were collected at makeSession time but never written to the
serializable transport-session metadata, so they were lost after pod restart.
With this change, the IDs flow through to Redis and are available for future
cross-pod session reconstruction.

Closes #4211
@github-actions github-actions bot added the size/S Small PR: 100-299 lines changed label Mar 27, 2026
@yrobla yrobla requested a review from Copilot March 27, 2026 13:50
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

Adds scaffolding to restore vMCP session hijack-prevention state from Redis-persisted metadata, enabling cross-pod token validation as part of the horizontal scaling effort (Fixes #4216).

Changes:

  • Added RestoreHijackPrevention() to reconstruct the hijack-prevention decorator from persisted token hash/salt + HMAC secret.
  • Extended MultiSessionFactory with RestoreSession() (stubbed in the default factory) and forwarded it through the decorating factory; updated mocks/test factories accordingly.
  • Added unit tests validating restore behavior, including cross-replica secret mismatch.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
pkg/vmcp/session/internal/security/security.go Adds RestoreHijackPrevention() helper for reconstructing token-binding decorator from persisted metadata.
pkg/vmcp/session/internal/security/restore_test.go Adds unit coverage for restore behavior (nil session, malformed salt, anonymous/auth round-trip, secret mismatch).
pkg/vmcp/session/factory.go Adds RestoreSession() to MultiSessionFactory, documents replica HMAC requirements, and stubs default implementation.
pkg/vmcp/session/decorating_factory.go Adds RestoreSession() forwarding on the decorating factory.
pkg/vmcp/session/mocks/mock_factory.go Regenerates GoMock for the interface addition.
pkg/vmcp/server/testfactory_test.go Updates minimal test factory to satisfy the new interface.
pkg/vmcp/server/telemetry_integration_test.go Updates backend-aware test factory to satisfy the new interface.

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

@codecov
Copy link
Copy Markdown

codecov bot commented Mar 27, 2026

Codecov Report

❌ Patch coverage is 91.11111% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 69.54%. Comparing base (2a89245) to head (83e86f0).
⚠�� Report is 20 commits behind head on main.

Files with missing lines Patch % Lines
pkg/vmcp/session/decorating_factory.go 88.23% 1 Missing and 1 partial ⚠️
pkg/vmcp/session/factory.go 50.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4405      +/-   ##
==========================================
+ Coverage   69.46%   69.54%   +0.08%     
==========================================
  Files         485      485              
  Lines       49821    49866      +45     
==========================================
+ Hits        34608    34681      +73     
+ Misses      12535    12506      -29     
- Partials     2678     2679       +1     

☔ View full report in Codecov by Sentry.
📢 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.
@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 Mar 27, 2026
…4216)

Add the infrastructure needed to reconstruct hijack-prevention state from
Redis-persisted metadata, enabling cross-pod token validation in horizontal
scaling scenarios.

- security.go: Add RestoreHijackPrevention(), the restore counterpart to
  PreventSessionHijacking(). Rebuilds a hijackPreventionDecorator from
  persisted tokenHash + tokenSaltHex + hmacSecret without re-hashing a
  live token. Returns errors for nil session, missing salt on authenticated
  sessions, and invalid hex salt.

- factory.go: Add RestoreSession() to the MultiSessionFactory interface with
  full doc comment (backend ID parsing, session hint lookup, routing-table
  rebuild, hijack-prevention re-application). Add a stub implementation on
  defaultMultiSessionFactory (returns "not yet implemented"); full
  reconnection logic is deferred. Document the cross-replica HMAC secret
  consistency requirement on defaultHMACSecret.

- decorating_factory.go: Forward RestoreSession() to the base factory;
  decorators are not re-applied during restore.

- mocks/mock_factory.go: Regenerate mock to include RestoreSession().

- restore_test.go: Unit tests covering nil session, missing salt, invalid
  hex, anonymous session round-trip, authenticated store→restore→validate
  round-trip, and cross-replica secret mismatch.

Closes #4216.
@yrobla yrobla requested a review from Copilot March 27, 2026 14:00
@github-actions github-actions bot added size/M Medium PR: 300-599 lines changed and removed size/S Small PR: 100-299 lines changed labels Mar 27, 2026
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

Copilot reviewed 9 out of 9 changed files in this pull request and generated 3 comments.


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

Comment on lines +378 to +385
// We use a nil-connector session as the inner session (no real backend needed
// to test auth path).
innerSess, err := factory.MakeSessionWithID(context.Background(), uuid.New().String(), identity, false, nil)
require.NoError(t, err)
t.Cleanup(func() { _ = innerSess.Close() })

restored, err := security.RestoreHijackPrevention(innerSess, persistedHash, persistedSalt, hmacSecret)
require.NoError(t, err)
Copy link

Copilot AI Mar 27, 2026

Choose a reason for hiding this comment

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

In this integration test, innerSess is created via factory.MakeSessionWithID(...), which already applies security.PreventSessionHijacking inside the factory. That means auth enforcement may be coming from the inner session even if RestoreHijackPrevention were a no-op, so the test can pass without actually validating the restore logic. Consider using an undecorated base session (e.g., construct a minimal MultiSession directly) so RestoreHijackPrevention is the only layer performing token validation.

Copilot uses AI. Check for mistakes.
Comment on lines +35 to +37
// RestoreSession restores a session from persisted metadata and applies the
// same decorator chain as MakeSessionWithID, ensuring consistent behavior
// between newly created and restored sessions.
Copy link

Copilot AI Mar 27, 2026

Choose a reason for hiding this comment

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

The PR description says decorators are not re-applied during restore, but decoratingMultiSessionFactory.RestoreSession explicitly reapplies the decorator chain. Please reconcile this mismatch by either updating the PR description (if this behavior is intended) or adjusting the implementation to match the documented plan.

Copilot uses AI. Check for mistakes.
Comment on lines +44 to +65
sess, err := f.base.RestoreSession(ctx, id, metadata, backends)
if err != nil {
return nil, err
}
for _, dec := range f.decorators {
var decorated MultiSession
decorated, err = dec(ctx, sess)
if err != nil {
if closeErr := sess.Close(); closeErr != nil {
slog.Warn("failed to close session after decorator error during restore", "error", closeErr)
}
return nil, err
}
if decorated == nil {
if closeErr := sess.Close(); closeErr != nil {
slog.Warn("failed to close session after decorator returned nil during restore", "error", closeErr)
}
return nil, fmt.Errorf("decorator returned nil session without error")
}
sess = decorated
}
return sess, nil
Copy link

Copilot AI Mar 27, 2026

Choose a reason for hiding this comment

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

RestoreSession duplicates the decorator-application loop from MakeSessionWithID with only minor differences in log messages. This duplication increases the risk that future changes (e.g., error handling tweaks) diverge between create vs restore paths; consider extracting a shared helper to apply decorators with a contextual log prefix.

Copilot uses AI. Check for mistakes.
Copy link
Copy Markdown
Contributor

@jerm-dro jerm-dro left a comment

Choose a reason for hiding this comment

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

The RestoreHijackPrevention function and the RestoreSession interface definition both look good — solid tests, clean implementation, and the contract aligns with where we need to go.

Holding off on approval for now because the RestoreSession stub will need to become a real implementation as part of the #4402 rework (see feedback there on SessionDataStorage + reconstruction-on-demand). The direction here is right, but approving before the underlying storage architecture settles would be premature. Happy to re-review once #4402 and #4404 land.

Base automatically changed from issue-4211 to main March 30, 2026 09:12
@github-actions github-actions bot added size/L Large PR: 600-999 lines changed and removed size/M Medium PR: 300-599 lines changed labels Mar 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/L Large PR: 600-999 lines changed

4 participants