Skip to content

[agentserver-core] Harden lifecycle endpoint auth and env-var validation - #49774

Open
Ankit Sultania (ankitsul) wants to merge 3 commits into
Azure:mainfrom
ankitsul:ankitsul/agentserver-core-lifecycle-endpoint-hardening
Open

Ankit Sultania (ankitsul) wants to merge 3 commits into
Azure:mainfrom
ankitsul:ankitsul/agentserver-core-lifecycle-endpoint-hardening

Conversation

@ankitsul

Copy link
Copy Markdown

Description

Summary

azure-ai-agentserver-core 2.3.0b1–2.3.0 register the snapshot lifecycle endpoints (POST /_agent/before-snapshot, POST /_agent/after-restore and the /_before_snapshot / /_after_restore aliases) unconditionally on the same port as the agent routes, and after-restore copies every session_env_overrides entry into os.environ with only basic shape checks. This PR hardens lifecycle endpoint authentication and environment-variable validation and ships it as 2.3.1.

Change

  • Lifecycle token — new env FOUNDRY_LIFECYCLE_TOKEN. When set, lifecycle requests must present the same value in the x-foundry-lifecycle-token header (compared with hmac.compare_digest); otherwise the host returns 401 unauthorized_lifecycle_request.
  • Conditional registration — is_hosted and the token are captured once in AgentServerHost.__init__. When the process is not hosted and no token is configured, the /_agent/* routes are not registered at all (logged once at INFO). Hosted without a token logs a WARNING and keeps the routes so existing platform callers continue to work until they send the header.
  • Override validation (fail closed, no partial apply) in _parse_session_context:
    • key must match ^[A-Za-z_][A-Za-z0-9_]*$, ≤ 256 chars; value ≤ 32 KiB, no NUL; ≤ 256 entries; request body ≤ 1 MiB (checked via content-length and while streaming).
    • case-insensitive deny list: PATH, HOME, NO_PROXY, REQUESTS_CA_BUNDLE, CURL_CA_BUNDLE, FOUNDRY_HOSTING_ENVIRONMENT, FOUNDRY_LIFECYCLE_TOKEN; prefixes LD_, DYLD_, PYTHON, SSL_CERT_, OTEL_, APPLICATIONINSIGHTS_, FOUNDRY_PROJECT_, AZURE_, MSI_, IDENTITY_; suffix _PROXY.
    • Any violation rejects the whole request with 400 before any environment or config mutation.
  • Session-GUID validation now uses the startup-captured is_hosted instead of the (mutable) live config.
  • Version bumped to 2.3.1; CHANGELOG and README updated.

Tests

sdk/agentserver/azure-ai-agentserver-core/tests/test_snapshot_lifecycle.py (53 → 115 cases):

  • missing / empty / wrong token → 401, no env change, no session assignment, no handler call (all 4 paths)
  • valid token → overrides applied
  • token is fixed at startup
  • not hosted + no token → routes absent (404); hosted + no token → routes present
  • 23 denied keys (incl. lowercase variants) → 400, nothing applied
  • malformed keys, NUL values, oversized key/value/count → 400, os.environ unchanged
  • boundary sizes accepted; > 1 MiB body and oversized content-length → 400

Existing lifecycle tests were updated to set the token / header and to use FOUNDRY_AGENT_VERSION instead of the now-denied FOUNDRY_PROJECT_ENDPOINT as the config-hydration probe. Verified the new cases fail (54) without the source change.

Ran locally (Python 3.14, venv with pytest, httpx, pytest-asyncio): pytest sdk/agentserver/azure-ai-agentserver-core/tests → 1387 passed, 1 failed (test_tracing.py::TestSetupDistroExport::test_managed_otlp_handles_mixed_signal_protocols, pre-existing, needs the otlp-grpc extra; test_otlp_protocol.py and test_tracing_e2e.py skipped for the same reason). Changed files are black -l 120 clean.

Compatibility

  • 2.2.0 and earlier: unaffected (no lifecycle routes).
  • 2.3.0b1 / 2.3.0b2 / 2.3.0 → 2.3.1:
    • Hosted deployments keep working without changes; they should set FOUNDRY_LIFECYCLE_TOKEN and send x-foundry-lifecycle-token to enable authentication (platform-side plumbing is a separate change).
    • Self-hosted / local users who call the lifecycle routes must set FOUNDRY_LIFECYCLE_TOKEN; otherwise the routes are not registered.
    • Restore requests that carry any denied variable name are now rejected as a whole.

All SDK Contribution checklist:

  • The pull request does not introduce [breaking changes] — see Compatibility above (behavioural tightening of a private platform endpoint).
  • CHANGELOG is updated for new features, bug fixes or other significant changes.
  • I have read the contribution guidelines.

General Guidelines and Best Practices

  • Title of the pull request is clear and informative.
  • There are a small number of commits, each of which have an informative message.

Testing Guidelines

  • Pull request includes test coverage for the included changes.

…idation

The snapshot lifecycle endpoints (/_agent/before-snapshot,
/_agent/after-restore and their aliases) were registered unconditionally
on the agent port and accepted any session_env_overrides key.

- Require a matching x-foundry-lifecycle-token header (constant-time
  comparison) when FOUNDRY_LIFECYCLE_TOKEN is set; return 401 otherwise.
- Do not register the lifecycle routes when the process is not hosted and
  no token is configured; log the posture once at startup.
- Capture is_hosted and the token once at startup so later environment
  updates cannot change them.
- Validate session_env_overrides as a whole and fail closed: strict key
  pattern, count/size caps, 1 MiB body cap, and a deny list covering
  loader, interpreter, proxy, TLS trust, telemetry, platform identity and
  credential variables.
- Bump to 2.3.1 and document the behaviour in CHANGELOG and README.

Authored-by: GitHub Copilot CLI v1.0.105
Model: Claude Fable 5.1 (claude-fable-5.1)
Co-authored-by: Copilot <[email protected]>
Copilot-Session: a3850a99-7429-42b6-bd69-abc89d315204
@github-actions github-actions Bot added Community Contribution Community members are working on the issue customer-reported Issues that are reported by GitHub users external to the Azure organization. Hosted Agents sdk/agentserver/* labels Oct 30, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Thank you for your contribution Ankit Sultania (@ankitsul)! We will review the pull request and get back to you soon.

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 1 pipeline(s).
7 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Lifecycle restores allow identity and authentication settings to be overridden, while validation gaps can cause failed restores or prevent subprocesses from starting.

4 open issues
What changed in this PR

This PR hardens snapshot lifecycle endpoints in azure-ai-agentserver-core for release 2.3.1, adding authentication controls and stricter restore-request validation while preserving hosted deployments without a token.

Changes:

  • Adds startup-captured lifecycle token authentication and conditional route registration.
  • Adds request-body limits and environment-override validation before restore processing.
  • Expands lifecycle tests and documents compatibility changes.
File Description
sdk/​agentserver/​azure-ai-agentserver-core/​tests/​test_snapshot_lifecycle.py Adds authentication, route-registration, and validation tests; updates existing lifecycle requests.
sdk/​agentserver/​azure-ai-agentserver-core/​README.md Documents token requirements, route availability, and override restrictions.
sdk/​agentserver/​azure-ai-agentserver-core/​CHANGELOG.md Records 2.3.1 hardening and compatibility changes.
sdk/​agentserver/​azure-ai-agentserver-core/​azure/​ai/​agentserver/​core/​_version.py Bumps the package version to 2.3.1.
sdk/​agentserver/​azure-ai-agentserver-core/​azure/​ai/​agentserver/​core/​_base.py Implements lifecycle authentication, conditional routes, and request validation.

Review effort: Balanced

@ankitsul Ankit Sultania (ankitsul) left a comment

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

🤖 Multi-model review: AgentServer lifecycle endpoint hardening (MSRC 161856)

Recommendation: 🔄 Changes requested. This is a comment-only review because the PR is self-authored.

Several parts are good:

  • constant-time token comparison;
  • the 1 MiB body cap, enforced both on the declared length and while streaming;
  • strict JSON-object parsing;
  • denying identity, LD_* and PYTHON* keys.

However, the production hosted path is still unauthenticated, and the env-override policy is a denylist that conflicts with Vienna's after-restore contract. Both need to be coordinated with the platform side before this closes MSRC 161856.

Models GPT-5.6 Sol, GPT-5.5, Gemini 4 Argon; arbiter and safety check by GPT-5.6 Terra
Size ⚠️ 5 files, +502/−51. Over the 400-line guideline. Consider splitting: (1) lifecycle token auth, (2) env-override validation, (3) body-size / JSON hardening and tests
IcM 31000000759303 (could not access the IcM from tooling; reviewed against the PR description)

Active findings (4, inline)

Severity Finding
🟠 High Hosted mode without FOUNDRY_LIFECYCLE_TOKEN authorizes every lifecycle request, and Vienna doesn't send or provision the token yet (_base.py:827)
🟠 High The finite denylist admits process-control variables (BASH_ENV, NODE_OPTIONS, JAVA_TOOL_OPTIONS, DOTNET_STARTUP_HOOKS, …); switch to an allowlist (_base.py:85)
🟡 Medium The OTEL_ / APPLICATIONINSIGHTS_ / AZURE_ prefixes reject payloads that follow Vienna's documented after-restore contract (OTEL_RESOURCE_ATTRIBUTES, connection-backed AZURE_* keys), so restore would get a 400 (_base.py:88-90)
⚪ Low The oversized-body test only hits the declared-length check; the streaming limit is untested

Dismissed after cross-review (confirmed by the GPT-5.6 Terra safety check)

  • The token stays in os.environ (flagged by Sol, dismissed by GPT-5.5). Agent code shares the process with the host and can read self._lifecycle_token anyway, and rotation is out of this contract. Popping it to avoid subprocess inheritance is optional defense in depth.
  • assigned_session_id is not seeded from the boot-time FOUNDRY_AGENT_SESSION_ID (flagged by Gemini, dismissed by GPT-5.5). This is pre-existing behavior, and its exploit depends on the hosted-without-token gap above.

These complement the existing Copilot comments (lines 95, 134, 891, 944) without duplicating them.

Review generated with multi-model cross-validation; reviewed by Ankit Sultania (@ankitsul).

…en env override policy

- Fail closed when hosted lifecycle authentication is not configured, with an explicit temporary compatibility opt-out.
- Validate restore environment overrides against startup-captured allow rules, deny sensitive process controls, and enforce UTF-8 byte limits.
- Preserve startup hosted posture and enforce streaming request size limits with focused tests and documentation.

Authored-by: GitHub Copilot CLI v1.0.105
Model: Claude Fable 5.1
Co-authored-by: Copilot <[email protected]>
Copilot-Session: a3850a99-7429-42b6-bd69-abc89d315204
Copilot AI balanced review requested due to automatic review settings November 2, 2026 07:27

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Restore can expose bearer tokens or redirect FTP traffic, reject newly assigned session GUIDs, and block hosted callers that upgrade without authentication configuration.

4 open issues
4 resolved since last review

Review effort: Balanced

"NO_PROXY",
"REQUESTS_CA_BUNDLE",
"CURL_CA_BUNDLE",
"AZURE_TENANT_ID",
Comment on lines +169 to +170
upper in _DENIED_ENV_KEYS
or upper.startswith(_DENIED_ENV_KEY_PREFIXES)
self._lifecycle_allowed_env_keys: frozenset[str] = (
frozenset(os.environ)
| frozenset(platform_allowed_keys)
| frozenset({_SESSION_ID_ENV, "OTEL_RESOURCE_ATTRIBUTES"})
Comment on lines +948 to +952
if self._lifecycle_is_hosted and not self._lifecycle_allow_unauthenticated:
return create_error_response(
"lifecycle_authentication_not_configured",
"Lifecycle authentication is required but is not configured.",
status_code=403,
…-hardening

Resolve CHANGELOG.md and _version.py conflicts by folding the lifecycle
hardening notes into the 2.3.1b1 (Unreleased) section introduced upstream.

Authored-by: GitHub Copilot CLI v1.0.105
Model: Claude Fable 5.1 (claude-fable-5.1)
Co-authored-by: Copilot <[email protected]>
Copilot-Session: a3850a99-7429-42b6-bd69-abc89d315204
Copilot AI balanced review requested due to automatic review settings November 2, 2026 07:52
@microsoft-github-policy-service

Copy link
Copy Markdown
Contributor

Ankit Sultania (@ankitsul) please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@microsoft-github-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"
Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”),
and conveys certain license rights to Microsoft Corporation and its affiliates (“Microsoft”) for Your
contributions to Microsoft open source projects. This Agreement is effective as of the latest signature
date below.

  1. Definitions.
    “Code” means the computer software code, whether in human-readable or machine-executable form,
    that is delivered by You to Microsoft under this Agreement.
    “Project” means any of the projects owned or managed by Microsoft and offered under a license
    approved by the Open Source Initiative (www.opensource.org).
    “Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
    Project, including but not limited to communication on electronic mailing lists, source code control
    systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
    discussing and improving that Project, but excluding communication that is conspicuously marked or
    otherwise designated in writing by You as “Not a Submission.”
    “Submission” means the Code and any other copyrightable material Submitted by You, including any
    associated comments and documentation.
  2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
    Project. This Agreement covers any and all Submissions that You, now or in the future (except as
    described in Section 4 below), Submit to any Project.
  3. Originality of Work. You represent that each of Your Submissions is entirely Your original work.
    Should You wish to Submit materials that are not Your original work, You may Submit them separately
    to the Project if You (a) retain all copyright and license information that was in the materials as You
    received them, (b) in the description accompanying Your Submission, include the phrase “Submission
    containing materials of a third party:” followed by the names of the third party and any licenses or other
    restrictions of which You are aware, and (c) follow any other instructions in the Project’s written
    guidelines concerning Submissions.
  4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
    for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
    Submission is made in the course of Your work for an employer or Your employer has intellectual
    property rights in Your Submission by contract or applicable law, You must secure permission from Your
    employer to make the Submission before signing this Agreement. In that case, the term “You” in this
    Agreement will refer to You and the employer collectively. If You change employers in the future and
    desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
    and secure permission from the new employer before Submitting those Submissions.
  5. Licenses.
  • Copyright License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the
    Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute
    the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third
    parties.
  • Patent License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under
    Your patent claims that are necessarily infringed by the Submission or the combination of the
    Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
    import or otherwise dispose of the Submission alone or with the Project.
  • Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
    No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
    granted by implication, exhaustion, estoppel or otherwise.
  1. Representations and Warranties. You represent that You are legally entitled to grant the above
    licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
    have disclosed under Section 3). You represent that You have secured permission from Your employer to
    make the Submission in cases where Your Submission is made in the course of Your work for Your
    employer or Your employer has intellectual property rights in Your Submission by contract or applicable
    law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
    have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
    You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
    REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
    EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
    PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
    NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
  2. Notice to Microsoft. You agree to notify Microsoft in writing of any facts or circumstances of which
    You later become aware that would make Your representations in this Agreement inaccurate in any
    respect.
  3. Information about Submissions. You agree that contributions to Projects and information about
    contributions may be maintained indefinitely and disclosed publicly, including Your name and other
    information that You submit with Your Submission.
  4. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
    the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
    Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
    exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
    defenses of lack of personal jurisdiction and forum non-conveniens.
  5. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
    supersedes any and all prior agreements, understandings or communications, written or oral, between
    the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

Default authentication breaks existing hosted snapshot and restore calls, while restore allowlisting rejects valid session variables and deny rules permit proxy and credential overrides.

7 open issues

Review effort: Balanced

Comment on lines +131 to +134
"OTEL_EXPORTER_",
"APPLICATIONINSIGHTS_",
"FOUNDRY_PROJECT_",
"AZURE_CLIENT_",

### Features Added

- Added `FOUNDRY_LIFECYCLE_TOKEN`. Hosted snapshot lifecycle endpoints require
Comment on lines +217 to +218
if key not in allowed_keys:
raise ValueError(f"environment override {key!r} is not allowed")

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Community Contribution Community members are working on the issue customer-reported Issues that are reported by GitHub users external to the Azure organization. Hosted Agents sdk/agentserver/*

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants