fix(copilot): read timezone-naive token expiry as UTC, not host local time (#3216)

## Description

`_parse_expiry` in `headroom/copilot_auth.py` parses an ISO-8601 token
expiry with `datetime.fromisoformat(...).timestamp()`. For a
**timezone-naive** value (no `Z`, no offset), `datetime.timestamp()`
interprets the datetime in the **host's local zone**, so the same expiry
resolves to a different epoch on any non-UTC machine.

`_entry_expired` compares that epoch against `time.time()` (UTC), so the
naive expiry is judged in the wrong frame:

- On a host **ahead** of UTC (e.g. `Asia/Kolkata`, +05:30) a still-valid
  token is treated as already expired — needless re-auth churn.
- On a host **behind** UTC (e.g. US zones) an already-expired token is
  trusted past its expiry, surfacing later as upstream `401`s.

Naive ISO expiries reach this path from the documented
`GITHUB_COPILOT_API_TOKEN_EXPIRES_AT` env var and from credential-store
payloads (`expires_at` / `expiry` / `expires`). The fix treats a naive
datetime as UTC, matching every other ISO parser in the codebase
(`telemetry/traffic_learner._parse_iso_timestamp`,
`proxy/memory_rank_policy.parse_memory_created_at`).

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)

## Changes Made

- `_parse_expiry`: when `datetime.fromisoformat` yields a naive
datetime,
  attach `timezone.utc` before calling `.timestamp()`. Aware values and
  the integer/float epoch paths are unchanged.
- Added regression tests that force a non-UTC host zone so they fail on
  any machine before the fix.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom --ignore-missing-imports`)
- [x] New tests added for new functionality
- [x] Manual testing performed

### Test Output

```text
$ python -m pytest tests/test_copilot_auth.py -q
110 passed, 1 warning in 0.81s

# The two naive-path tests fail before the fix (Z-suffix path already worked):
$ git stash push -- headroom/copilot_auth.py && \
  python -m pytest tests/test_copilot_auth.py -q -k "naive_iso_as_utc or entry_expired_uses_utc or zulu_suffix"
tests/test_copilot_auth.py:1635: assert naive == aware
E   assert 1767205800.0 == 1767225600.0
FAILED ...::test_parse_expiry_reads_naive_iso_as_utc_not_local_time
FAILED ...::test_entry_expired_uses_utc_for_naive_iso_expiry
2 failed, 1 passed, 107 deselected

$ python -m ruff check headroom/copilot_auth.py tests/test_copilot_auth.py
All checks passed!

$ mypy headroom --ignore-missing-imports
Success: no issues found in 527 source files
```

## Real Behavior Proof

- Environment: macOS (Darwin arm64), Python 3.13, `TZ=Asia/Kolkata`
(UTC+05:30). Operator sets a naive ISO expiry via the documented
`GITHUB_COPILOT_API_TOKEN_EXPIRES_AT` env var, 1 hour in the future
(UTC).
- Exact command / steps: with `TZ=Asia/Kolkata` and `time.tzset()`,
parse the env value with `copilot_auth._parse_expiry(<naive iso>)` and
evaluate `copilot_auth._entry_expired({"expires_at": <naive iso>})`;
compare the parsed epoch against the intended UTC epoch. Run once with
the fix stashed (before) and once with it applied (after).
- Observed result: BEFORE the fix the naive expiry was misread as local
time and the live token was reported expired; AFTER the fix it resolves
to UTC and is correctly live.
  ```text
  BEFORE fix (same host, naive ISO expiry 1h in the future):
    parsed epoch : 1787451474
    expected epoch: 1787471275
    skew seconds : -19801   (== -05:30, interpreted as local time)
_entry_expired says token is expired? True (WRONG: token is 1h in the
future)

  AFTER fix:
    parsed epoch : 1787471264
    expected epoch: 1787471265
    skew seconds : -1   (sub-second isoformat truncation; == correct)
    _entry_expired says token is expired? False  (correct)
  ```
- Not tested: live GitHub Copilot token exchange against real
credentials (no account handy); the reachable env-var and
credential-payload paths are exercised directly above.

## Runtime Rollout Safety

- Rollout-managed feature(s): none — unconditional correctness fix in
the token-expiry parser.
- Minimum rollout channel: N/A
- Stable/default behavior changed: only for tz-naive ISO expiries, which
were previously misread; UTC hosts see no change.
- Kill switch / disable path: N/A
- Unsafe override required: no
- Qualification impact: none
- Rollback path: revert this commit.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation (N/A — no
doc surface changed)
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md`

Co-authored-by: JerrettDavis <mxjerrett@gmail.com>
This commit is contained in:
Rajat Nagda
2026-10-01 16:03:43 -05:00
committed by GitHub
co-authored by JerrettDavis
parent 88a1f4e52b
commit 2b2dc1b2c9
2 changed files with 37 additions and 2 deletions
+12 -2
View File
@@ -15,7 +15,7 @@ from collections.abc import Mapping
from contextvars import ContextVar
from ctypes import wintypes
from dataclasses import dataclass
from datetime import datetime
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from urllib import error as urllib_error
@@ -591,9 +591,19 @@ def _parse_expiry(value: Any) -> float | None:
pass
try:
normalized = raw.replace("Z", "+00:00")
return datetime.fromisoformat(normalized).timestamp()
parsed = datetime.fromisoformat(normalized)
except ValueError:
return None
# A timezone-naive ISO string (no `Z`, no offset) must be read as UTC,
# not the host's local zone. `datetime.timestamp()` assumes local time
# for naive datetimes, so on a non-UTC box the same expiry resolves to a
# different epoch — hours early or late — silently expiring a live token
# or trusting a dead one. Every other ISO parser in the codebase treats
# naive as UTC (see telemetry/traffic_learner, proxy/memory_rank_policy);
# match that here.
if parsed.tzinfo is None:
parsed = parsed.replace(tzinfo=timezone.utc)
return parsed.timestamp()
return None
+25
View File
@@ -1832,6 +1832,31 @@ def test_exchange_token_sync_returns_payload_on_success(monkeypatch: pytest.Monk
assert result == payload
def test_parse_expiry_reads_naive_iso_as_utc() -> None:
assert copilot_auth._parse_expiry("2026-01-01T00:00:00") == 1767225600.0
def test_parse_expiry_reads_zulu_suffix_as_utc() -> None:
assert copilot_auth._parse_expiry("2026-01-01T00:00:00Z") == 1767225600.0
@pytest.mark.skipif(not hasattr(time, "tzset"), reason="time.tzset is POSIX-only")
def test_parse_expiry_naive_iso_is_independent_of_host_timezone(
monkeypatch: pytest.MonkeyPatch,
) -> None:
previous_tz = os.environ.get("TZ")
try:
monkeypatch.setenv("TZ", "Asia/Kolkata")
time.tzset()
assert copilot_auth._parse_expiry("2026-01-01T00:00:00") == 1767225600.0
finally:
if previous_tz is None:
monkeypatch.delenv("TZ", raising=False)
else:
monkeypatch.setenv("TZ", previous_tz)
time.tzset()
def test_exchange_token_sync_uses_configured_corporate_tls_context(
monkeypatch: pytest.MonkeyPatch,
) -> None: