[test] Add tests for proxy.initGuardPolicy#4333
Conversation
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>
There was a problem hiding this comment.
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.gowith 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_LegacyAllowOnlyKeyWithTrustedUsersclaims to verify trusted-user injection, but it only checks that initialization succeeds. If normalization/injection regresses (e.g.,trusted-usersis not injected underallow-only), this test would still pass. Consider recording theLabelAgentinput payload in the stub and asserting thatallow-only.trusted-usersequals 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_TrustedBotsAndUserscurrently only asserts that no error occurs. To validate that trusted bots/users are actually forwarded, consider having the stub capture theLabelAgentpayload and assert it contains the expected top-leveltrusted-botsentries and nestedallow-only.trusted-usersentries.
// 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
| // 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) |
There was a problem hiding this comment.
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
| // 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 | ||
| } | ||
|
|
There was a problem hiding this comment.
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 address this review feedback #4333 (review) |
Test Coverage Improvement:
proxy.initGuardPolicyFunction Analyzed
internal/proxy(*Server).initGuardPolicyinternal/proxy/proxy.go(lines 150–213)Why This Function?
initGuardPolicyis the core method that connects a proxyServerto 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:
allowonlykey →allow-onlybefore trusted-user injectionLabelAgenton the guard and applies returned secrecy/integrity tags to the agent registryTests Added
A new test file
internal/proxy/init_guard_policy_test.go(264 lines) covers:"not-valid-json"rejected with "invalid policy JSON" error{}rejected with "policy validation failed" error{"write-sink":{...}}rejected with "write-sink policies are not supported"guardInitialized = trueallowonlykey — accepted via policy-map normalizationTest Infrastructure
Added a
labelAgentStubGuardtest double (implementsguard.Guard) with configurableLabelAgentreturn values, alongside anewTestServerForInitGuardPolicyhelper that assembles a minimal*Server. This pattern follows the existingstubGuardinhandler_difc_test.go.Coverage Improvement
Generated by Test Coverage Improver
Next run will target the next most complex under-tested function
Warning
The following domain was blocked by the firewall during workflow execution:
proxy.golang.orgTo allow these domains, add them to the
network.allowedlist in your workflow frontmatter:See Network Configuration for more information.