Skip to content

test: Add inbound JWT validation tests for go-processor - #304

Merged
huang195 merged 2 commits into
rossoctl:mainfrom
huang195:test/inbound-jwt-validation
Apr 14, 2026
Merged

huang195 merged 2 commits into
rossoctl:mainfrom
huang195:test/inbound-jwt-validation

Conversation

@huang195

Copy link
Copy Markdown
Member

Summary

Add 9 test functions covering the previously-untested inbound JWT validation path — the security-critical code that accepts or rejects incoming requests.

Tests added:

  • NotConfigured: Skips validation when JWKS/issuer not set
  • MissingAuthHeader: Rejects requests without Authorization header (401)
  • MalformedAuthHeader: Rejects non-Bearer auth headers (401)
  • InvalidSignature: Rejects JWTs signed with wrong key (401)
  • WrongIssuer: Rejects JWTs from unexpected issuer (401)
  • WrongAudience: Rejects JWTs not scoped to this agent (401)
  • ValidToken: Forwards valid token and removes direction header
  • BypassPath: Skips validation for /.well-known/* paths
  • NoAudienceCheck: Forwards when audience validation is disabled

Uses a test JWKS server with generated RSA keys and lestrrat-go/jwx for JWT signing — the same library used in production.

Coverage: go-processor 39.3% -> 51.2% (+12%)

Test plan

Add 9 test functions covering the previously-untested inbound
validation path (handleInbound, validateInboundJWT, denyRequest):

- NotConfigured: skips validation when JWKS/issuer not set
- MissingAuthHeader: rejects with 401
- MalformedAuthHeader: rejects non-Bearer tokens with 401
- InvalidSignature: rejects JWTs signed with wrong key
- WrongIssuer: rejects JWTs from unexpected issuer
- WrongAudience: rejects JWTs not scoped to this agent
- ValidToken: forwards and removes direction header
- BypassPath: skips validation for /.well-known/* paths
- NoAudienceCheck: forwards when audience validation is disabled

Uses a test JWKS server with generated RSA keys and lestrrat-go/jwx
for JWT signing, matching the production dependency.

go-processor coverage: 39.3% -> 51.2%

Signed-off-by: Hai Huang <[email protected]>

@pdettori pdettori 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.

Well-structured test addition covering 9 scenarios for inbound JWT validation. Test helpers are clean, JWKS setup/teardown is properly handled, and the lestrrat-go/jwx usage matches production patterns. CI is all-green.

Two suggestions: (1) assert on the 401 response body to distinguish rejection reasons, and (2) add an expired-token test for defense-in-depth. Neither is blocking.

Side note (not blocking this PR): The production handleInbound leaks the x-authbridge-direction header in the not-configured path (returns bare HeadersResponse{} without removing it). The test correctly matches current behavior, but this may be worth a follow-up fix.

Areas reviewed: Go tests, security (test key generation), JWT library usage
Commits: 1 commit, signed-off ✓ | CI: all passing

if !ok {
return false
}
return ir.ImmediateResponse.Status.Code == typev3.StatusCode_Unauthorized

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.

suggestion: isDenied401 only checks the status code, but production returns distinct JSON messages per rejection reason ("missing Authorization header", "invalid Authorization header format", "token validation failed: <err>"). Checking the body would ensure each test triggers the right rejection path, not just any 401.

For example:

func isDenied401WithMessage(resp *v3.ProcessingResponse, substr string) bool {
    ir, ok := resp.Response.(*v3.ProcessingResponse_ImmediateResponse)
    if !ok { return false }
    return ir.ImmediateResponse.Status.Code == typev3.StatusCode_Unauthorized &&
        strings.Contains(string(ir.ImmediateResponse.Body), substr)
}


if !isDenied401(resp) {
t.Error("expected 401 for JWT signed with wrong key")
}

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.

suggestion: Consider adding an expired-token test. While jwt.WithValidate(true) handles exp automatically, an explicit test documents that guarantee and catches regressions if the parse options ever change.

func TestHandleInbound_ExpiredToken(t *testing.T) {
    privKey, cleanup := setupTestJWKS(t)
    defer cleanup()
    tok, _ := jwt.NewBuilder().
        Issuer(inboundIssuer).
        Audience([]string{expectedAudience}).
        Expiration(time.Now().Add(-1 * time.Hour)).
        Build()
    signed, _ := jwt.Sign(tok, jwt.WithKey(jwa.RS256, privKey))
    p := &processor{}
    headers := buildInboundHeaders("/api/data", "Bearer "+string(signed))
    resp := p.handleInbound(headers)
    if !isDenied401(resp) {
        t.Error("expected 401 for expired token")
    }
}

func TestHandleInbound_MissingAuthHeader(t *testing.T) {
privKey, cleanup := setupTestJWKS(t)
defer cleanup()
_ = privKey

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.

nit: Idiomatic Go discards unused returns inline: _, cleanup := setupTestJWKS(t) rather than assigning then blanking on a separate line. Same applies in the BypassPath and MalformedAuthHeader tests.

// Serve JWKS via HTTP
jwksServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(keySet)

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.

nit: json.NewEncoder(w).Encode(keySet) discards the error — linters like errcheck will flag it. Minor since it's a test helper, but easy to fix:

if err := json.NewEncoder(w).Encode(keySet); err != nil {
    http.Error(w, err.Error(), http.StatusInternalServerError)
}

Address review feedback from pdettori:

1. isDenied401 now checks response body substring to verify each test
   triggers the correct rejection path (not just any 401)
2. Add TestHandleInbound_ExpiredToken for defense-in-depth against
   jwt.WithValidate regression
3. Use _ directly in assignments instead of assigning then blanking
4. Handle json.NewEncoder error in JWKS test server

Signed-off-by: Hai Huang <[email protected]>
@huang195
huang195 merged commit 8e3e3b9 into rossoctl:main Apr 14, 2026
15 checks passed
@huang195
huang195 deleted the test/inbound-jwt-validation branch April 14, 2026 12:33
huang195 added a commit to huang195/kagenti-extensions that referenced this pull request Apr 14, 2026
…ty branch

Resolve conflict in main_test.go: keep both utility tests (this PR)
and inbound JWT validation tests (from merged PR rossoctl#304).

Signed-off-by: Hai Huang <[email protected]>
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