Skip to content

Refactor trace configuration and fetching logic to remove API key usage and implement token provider for authentication#652

Merged
nadheesh merged 3 commits intowso2:mainfrom
hanzjk:security
Apr 3, 2026
Merged

Refactor trace configuration and fetching logic to remove API key usage and implement token provider for authentication#652
nadheesh merged 3 commits intowso2:mainfrom
hanzjk:security

Conversation

@hanzjk
Copy link
Copy Markdown
Contributor

@hanzjk hanzjk commented Apr 3, 2026

Purpose

Describe the problems, issues, or needs driving this feature/fix and include links to related issues in the following format: Resolves issue1, issue2, etc.

Trace observer is configured to require JWT authentication. But eval jobs make unauthenticated calls to the trace observer service to fetch traces for evaluation without a token. This PR is to implement token provider for trace observer authentication.

Goals

Describe the solutions that this feature/fix will introduce to resolve the problems described above

Approach

Describe how you are implementing the solutions. Include an animated GIF or screenshot if the change affects the UI (email documentation@wso2.com to review all UI text). Include a link to a Markdown file or Google doc if the feature write-up is too long to paste here.

User stories

Summary of user stories addressed by this change>

Release note

Brief description of the new feature or bug fix as it will appear in the release notes

Documentation

Link(s) to product documentation that addresses the changes of this PR. If no doc impact, enter �N/A� plus brief explanation of why there�s no doc impact

Training

Link to the PR for changes to the training content in https://github.com/wso2/WSO2-Training, if applicable

Certification

Type �Sent� when you have provided new/updated certification questions, plus four answers for each question (correct answer highlighted in bold), based on this change. Certification questions/answers should be sent to certification@wso2.com and NOT pasted in this PR. If there is no impact on certification exams, type �N/A� and explain why.

Marketing

Link to drafts of marketing content that will describe and promote this feature, including product page changes, technical articles, blog posts, videos, etc., if applicable

Automation tests

  • Unit tests

    Code coverage information

  • Integration tests

    Details about the test cases and coverage

Security checks

Samples

Provide high-level details about the samples related to this feature

Related PRs

List any other related PRs

Migrations (if applicable)

Describe migration steps and platforms on which migration has been tested

Test environment

List all JDK versions, operating systems, databases, and browser/versions on which this feature/fix was tested

Learning

Describe the research phase and any blog posts, patterns, libraries, or add-ons you used to solve the problem.

Summary by CodeRabbit

  • Refactor

    • Authentication switched from static API keys to dynamic OAuth2 bearer tokens via a token provider.
    • Removed API URL/key configuration; file-based trace loading is now the supported non-explicit source.
  • Tests

    • Updated tests to remove expectations around removed API URL/key settings and to validate file-path based trace loading.
  • Documentation

    • Updated configuration guidance and example env to reflect the new trace sourcing and auth approach.

…ge and implement token provider for authentication
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 3, 2026

Warning

Rate limit exceeded

@hanzjk has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 7 minutes and 31 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 7 minutes and 31 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: a0ad07b7-c973-4001-ba74-298768c8e4d1

📥 Commits

Reviewing files that changed from the base of the PR and between 9c6e9ff and d6bb886.

📒 Files selected for processing (1)
  • libs/amp-evaluation/src/amp_evaluation/trace/fetcher.py
📝 Walkthrough

Walkthrough

Refactors trace fetching to require a runtime token_provider for OAuth2 bearer tokens, removes api_url/api_key from TraceConfig (leaving file_path), updates runner logic to no longer auto-create a TraceFetcher from config, and passes token_provider=token_manager.get_token where TraceFetcher is instantiated.

Changes

Cohort / File(s) Summary
Runner & entrypoint
evaluation-job/main.py, libs/amp-evaluation/src/amp_evaluation/runner.py
TraceFetcher is now constructed with token_provider=token_manager.get_token in the job entrypoint; BaseRunner._get_fetcher() no longer falls back to creating a TraceFetcher from config.trace.api_url and raises if no explicit fetcher or file path is provided.
Trace Fetcher
libs/amp-evaluation/src/amp_evaluation/trace/fetcher.py
Replaced api_key parameter with required token_provider callable; added _get_auth_headers() which calls token_provider() and always sets Authorization: Bearer <token> for requests.
Configuration & tests
libs/amp-evaluation/src/amp_evaluation/config.py, libs/amp-evaluation/tests/test_config.py
Removed api_url and api_key from TraceConfig; updated/removed tests that referenced those fields, retaining only file_path-based configuration checks.
Documentation / env example
libs/amp-evaluation/.env.example
Removed example variables/comments for AMP_TRACE_API_URL/AMP_TRACE_API_KEY; kept AMP_TRACE_FILE_PATH and added note that live traces require passing a TraceFetcher with a token_provider.

Sequence Diagram(s)

sequenceDiagram
    participant Main as evaluation-job/main
    participant Runner as BaseRunner
    participant Fetcher as TraceFetcher
    participant TokenMgr as OAuth2TokenManager
    participant API as Trace API / Remote

    Main->>Runner: construct runner (trace_fetcher=Fetcher(token_provider=TokenMgr.get_token))
    Runner->>Fetcher: request traces
    Fetcher->>TokenMgr: token = token_provider()
    TokenMgr-->>Fetcher: returns token
    Fetcher->>API: HTTP request (Authorization: Bearer token)
    API-->>Fetcher: trace payload
    Fetcher-->>Runner: return traces
    Runner-->>Main: run proceeds with traces
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Poem

🐰 I swapped the key for a bouncing token,
Fresh every hop, no string left broken.

Calls now ask, the manager replies—
Bearer warmth in azure skies.
Hooray, the traces dance anew! 🎩✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is largely incomplete, with only the Purpose section filled in and all other required sections left as template placeholders. Complete the Goals, Approach, Release note, Documentation, Automation tests, and Security checks sections. Include details on implementation strategy, test coverage, and security validation.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main refactoring: removing API key usage and implementing token provider for trace authentication.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
libs/amp-evaluation/src/amp_evaluation/runner.py (1)

253-274: Add focused tests for the new _get_fetcher() hard-fail path.

Lines 270-274 introduce a stricter runtime branch. Please add a runner-level unit test that validates: (1) explicit trace_fetcher still takes precedence, and (2) missing trace source raises this ValueError.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@libs/amp-evaluation/src/amp_evaluation/runner.py` around lines 253 - 274, Add
unit tests for Runner._get_fetcher(): create a test that constructs the runner
with an explicit trace_fetcher mock/object and with config.trace.file_path set
and assert _get_fetcher() returns the explicit trace_fetcher (verifying
precedence of the trace_fetcher parameter over TraceLoader), and create a
separate test that constructs the runner with no trace_fetcher and
config.trace.file_path empty/None and assert calling _get_fetcher() raises the
ValueError defined in _get_fetcher(). Use the Runner class constructor to set
trace_fetcher and config.trace.file_path and reference the _get_fetcher,
trace_fetcher, config.trace.file_path, and TraceLoader symbols in the
assertions.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@libs/amp-evaluation/src/amp_evaluation/config.py`:
- Around line 49-54: Update libs/amp-evaluation/.env.example to match the new
config comments: remove the now-ignored AMP_TRACE_API_URL and AMP_TRACE_API_KEY
entries and ensure only AMP_TRACE_FILE_PATH is documented (with a short
description that it points to a trace JSON file). Verify the remaining example
env entry uses the exact variable name AMP_TRACE_FILE_PATH so it aligns with the
new behavior described in config.py.

In `@libs/amp-evaluation/src/amp_evaluation/trace/fetcher.py`:
- Around line 419-421: In fetch_trace_by_id (and the other fetch method around
the second occurrence) move the call to _get_auth_headers() inside the
surrounding try block so any exception from token_provider()/auth acquisition is
caught by the existing except handlers; specifically, call _get_auth_headers()
after entering the try in fetch_trace_by_id and the other fetch method (the
block around lines 453–455) and then proceed to requests.get/post so token
errors trigger the same logging/return (e.g., return None) paths rather than
propagating.

---

Nitpick comments:
In `@libs/amp-evaluation/src/amp_evaluation/runner.py`:
- Around line 253-274: Add unit tests for Runner._get_fetcher(): create a test
that constructs the runner with an explicit trace_fetcher mock/object and with
config.trace.file_path set and assert _get_fetcher() returns the explicit
trace_fetcher (verifying precedence of the trace_fetcher parameter over
TraceLoader), and create a separate test that constructs the runner with no
trace_fetcher and config.trace.file_path empty/None and assert calling
_get_fetcher() raises the ValueError defined in _get_fetcher(). Use the Runner
class constructor to set trace_fetcher and config.trace.file_path and reference
the _get_fetcher, trace_fetcher, config.trace.file_path, and TraceLoader symbols
in the assertions.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 7c246993-b9d7-47a4-9d37-9da98bd8a6bd

📥 Commits

Reviewing files that changed from the base of the PR and between 78af657 and f3c5ea8.

📒 Files selected for processing (5)
  • evaluation-job/main.py
  • libs/amp-evaluation/src/amp_evaluation/config.py
  • libs/amp-evaluation/src/amp_evaluation/runner.py
  • libs/amp-evaluation/src/amp_evaluation/trace/fetcher.py
  • libs/amp-evaluation/tests/test_config.py

Comment thread libs/amp-evaluation/src/amp_evaluation/config.py
Comment thread libs/amp-evaluation/src/amp_evaluation/trace/fetcher.py Outdated
@nadheesh nadheesh merged commit 0cc18d9 into wso2:main Apr 3, 2026
13 checks passed
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