Skip to content

[test] Add tests for proxy.initGuardPolicy#4333

Merged
lpcox merged 1 commit intomainfrom
test/init-guard-policy-coverage-d00751df591941b8
Apr 22, 2026
Merged

[test] Add tests for proxy.initGuardPolicy#4333
lpcox merged 1 commit intomainfrom
test/init-guard-policy-coverage-d00751df591941b8

Conversation

@github-actions
Copy link
Copy Markdown
Contributor

Test Coverage Improvement: proxy.initGuardPolicy

Function Analyzed

  • Package: internal/proxy
  • Function: (*Server).initGuardPolicy
  • File: internal/proxy/proxy.go (lines 150–213)
  • Previous Coverage: 0% (no direct tests existed)
  • Complexity: High — 6 distinct branches, DIFC enforcement, agent label application

Why This Function?

initGuardPolicy is the core method that connects a proxy Server to its WASM guard, sets up agent DIFC labels (secrecy/integrity), and optionally overrides the enforcement mode. Despite its criticality to the proxy security model, it had zero direct unit tests — it was only exercised indirectly through integration tests that require a real WASM binary.

The function is non-trivial:

  • Parses and validates guard policy JSON
  • Rejects write-sink policies (proxy only supports allow-only)
  • Normalizes legacy allowonly key → allow-only before trusted-user injection
  • Calls LabelAgent on the guard and applies returned secrecy/integrity tags to the agent registry
  • Overrides the server's enforcement mode when the guard's response specifies one

Tests Added

A new test file internal/proxy/init_guard_policy_test.go (264 lines) covers:

  • Invalid JSON"not-valid-json" rejected with "invalid policy JSON" error
  • Validation failure — empty {} rejected with "policy validation failed" error
  • Write-sink rejected{"write-sink":{...}} rejected with "write-sink policies are not supported"
  • LabelAgent error — guard error propagates with "LabelAgent failed" wrapping
  • Happy path — successful initialization sets guardInitialized = true
  • Agent label application — secrecy and integrity tags from guard response applied to proxy agent registry
  • DIFCMode override — guard returning "strict" overrides server started in "filter" mode
  • Invalid DIFCMode silently ignored — unrecognized mode preserves original enforcement mode
  • Empty DIFCMode — skips mode-override block, initial mode preserved
  • Legacy allowonly key — accepted via policy-map normalization
  • Legacy key + trusted users — normalization enables trusted-user injection
  • Trusted bots + users — forwarded alongside policy without error
  • Multiple secrecy tags — all tags applied to agent registry

Test Infrastructure

Added a labelAgentStubGuard test double (implements guard.Guard) with configurable LabelAgent return values, alongside a newTestServerForInitGuardPolicy helper that assembles a minimal *Server. This pattern follows the existing stubGuard in handler_difc_test.go.

Coverage Improvement

Before: 0% — initGuardPolicy had no direct tests
After:  ~100% branch coverage for initGuardPolicy

Generated by Test Coverage Improver
Next run will target the next most complex under-tested function

Warning

⚠️ Firewall blocked 1 domain

The following domain was blocked by the firewall during workflow execution:

  • proxy.golang.org

To allow these domains, add them to the network.allowed list in your workflow frontmatter:

network:
  allowed:
    - defaults
    - "proxy.golang.org"

See Network Configuration for more information.

Generated by Test Coverage Improver · ● 24.1M ·

Adds comprehensive unit tests for initGuardPolicy covering:
- Invalid JSON rejection
- Policy validation failure (empty/malformed policy)
- Write-sink policy rejection (proxy only supports allow-only)
- LabelAgent error propagation
- Happy path: successful guard initialization
- Agent label application (secrecy and integrity tags)
- DIFCMode override from guard response
- Invalid DIFCMode in guard response (silently ignored)
- Empty DIFCMode preservation
- Legacy allowonly key normalization
- Trusted bots and users forwarding
- Multiple secrecy tags applied correctly

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
@lpcox lpcox marked this pull request as ready for review April 22, 2026 14:34
Copilot AI review requested due to automatic review settings April 22, 2026 14:34
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 focused unit tests around internal/proxy.(*Server).initGuardPolicy, which initializes the proxy’s WASM guard policy and applies agent DIFC labels / mode overrides.

Changes:

  • Introduces internal/proxy/init_guard_policy_test.go with table-style coverage across error paths and success paths for policy parsing/validation, write-sink rejection, LabelAgent errors, agent label application, and DIFC mode override behavior.
Show a summary per file
File Description
internal/proxy/init_guard_policy_test.go Adds direct unit tests for initGuardPolicy using a configurable guard stub and minimal Server setup.

Copilot's findings

Tip

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

Comments suppressed due to low confidence (2)

internal/proxy/init_guard_policy_test.go:230

  • TestInitGuardPolicy_LegacyAllowOnlyKeyWithTrustedUsers claims to verify trusted-user injection, but it only checks that initialization succeeds. If normalization/injection regresses (e.g., trusted-users is not injected under allow-only), this test would still pass. Consider recording the LabelAgent input payload in the stub and asserting that allow-only.trusted-users equals the provided list.
// TestInitGuardPolicy_LegacyAllowOnlyKeyWithTrustedUsers verifies that a legacy "allowonly"
// key is normalized before trusted-user injection so that trusted users are injected into
// the correct "allow-only" slot in the payload.
func TestInitGuardPolicy_LegacyAllowOnlyKeyWithTrustedUsers(t *testing.T) {
	g := defaultLabelAgentStub(difc.ModeFilter, []string{}, []string{})
	s := newTestServerForInitGuardPolicy(g, difc.EnforcementFilter)

	legacyPolicy := `{"allowonly":{"repos":"public","min-integrity":"none"}}`
	trustedUsers := []string{"alice", "bob"}

	// If the normalization works, trusted users are injected into "allow-only" and
	// the call succeeds. If it doesn't work, the payload would lack an "allow-only"
	// key and the trusted-user injection would be silently skipped (no error, but
	// we can at least confirm the guard initialized).
	err := s.initGuardPolicy(context.Background(), legacyPolicy, nil, trustedUsers)

	require.NoError(t, err)
	assert.True(t, s.guardInitialized)

internal/proxy/init_guard_policy_test.go:246

  • TestInitGuardPolicy_TrustedBotsAndUsers currently only asserts that no error occurs. To validate that trusted bots/users are actually forwarded, consider having the stub capture the LabelAgent payload and assert it contains the expected top-level trusted-bots entries and nested allow-only.trusted-users entries.
// TestInitGuardPolicy_TrustedBotsAndUsers verifies that trusted bots and users can be
// provided alongside a valid allow-only policy without causing an error.
func TestInitGuardPolicy_TrustedBotsAndUsers(t *testing.T) {
	g := defaultLabelAgentStub(difc.ModeFilter, []string{}, []string{})
	s := newTestServerForInitGuardPolicy(g, difc.EnforcementFilter)

	trustedBots := []string{"dependabot[bot]", "renovate[bot]"}
	trustedUsers := []string{"alice"}

	err := s.initGuardPolicy(context.Background(), validAllowOnlyPolicyJSON, trustedBots, trustedUsers)

	require.NoError(t, err)
	assert.True(t, s.guardInitialized)
}
  • Files reviewed: 1/1 changed files
  • Comments generated: 2

Comment on lines +197 to +210
// TestInitGuardPolicy_LegacyAllowOnlyKey verifies that a policy using the legacy
// "allowonly" key (without the hyphen) is accepted and the guard is initialized.
// The normalization step in initGuardPolicy maps "allowonly" → "allow-only" so that
// trusted-user injection via BuildLabelAgentPayload works correctly.
func TestInitGuardPolicy_LegacyAllowOnlyKey(t *testing.T) {
g := defaultLabelAgentStub(difc.ModeFilter, []string{}, []string{})
s := newTestServerForInitGuardPolicy(g, difc.EnforcementFilter)

legacyPolicy := `{"allowonly":{"repos":"public","min-integrity":"none"}}`

err := s.initGuardPolicy(context.Background(), legacyPolicy, nil, nil)

require.NoError(t, err)
assert.True(t, s.guardInitialized)
Copy link

Copilot AI Apr 22, 2026

Choose a reason for hiding this comment

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

Tests covering legacy allowonly handling don’t currently assert that initGuardPolicy actually normalizes the payload passed to LabelAgent (i.e., that the canonical top-level allow-only key is present). As written, these tests would still pass even if the normalization block were removed, because the stub guard accepts any payload. Consider having the stub guard capture the policy argument and assert it contains the normalized allow-only key (and ideally that it’s the object used for subsequent injection).

This issue also appears in the following locations of the same file:

  • line 213
  • line 233

Copilot uses AI. Check for mistakes.
Comment on lines +15 to +35
// labelAgentStubGuard is a configurable test double for guard.Guard that supports
// controlling the result of LabelAgent. Used specifically for initGuardPolicy tests.
type labelAgentStubGuard struct {
labelAgentResult *guard.LabelAgentResult
labelAgentErr error
}

func (g *labelAgentStubGuard) Name() string { return "stub-label-agent" }

func (g *labelAgentStubGuard) LabelAgent(_ context.Context, _ interface{}, _ guard.BackendCaller, _ *difc.Capabilities) (*guard.LabelAgentResult, error) {
return g.labelAgentResult, g.labelAgentErr
}

func (g *labelAgentStubGuard) LabelResource(_ context.Context, _ string, _ interface{}, _ guard.BackendCaller, _ *difc.Capabilities) (*difc.LabeledResource, difc.OperationType, error) {
return difc.NewLabeledResource("stub"), difc.OperationRead, nil
}

func (g *labelAgentStubGuard) LabelResponse(_ context.Context, _ string, _ interface{}, _ guard.BackendCaller, _ *difc.Capabilities) (difc.LabeledData, error) {
return nil, nil
}

Copy link

Copilot AI Apr 22, 2026

Choose a reason for hiding this comment

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

This file introduces a new labelAgentStubGuard that largely duplicates the existing stubGuard test double in handler_difc_test.go (same package). To reduce duplicated test scaffolding, consider extending/reusing the existing stub (e.g., add configurable LabelAgent result/err fields) rather than maintaining two similar implementations.

Copilot uses AI. Check for mistakes.
@lpcox
Copy link
Copy Markdown
Collaborator

lpcox commented Apr 22, 2026

@copilot address this review feedback #4333 (review)

@lpcox lpcox merged commit 52cd33e into main Apr 22, 2026
26 checks passed
@lpcox lpcox deleted the test/init-guard-policy-coverage-d00751df591941b8 branch April 22, 2026 15:30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants