Debian Codegraph @

asynceapi/_auth.py

raw symbols SCIP
1 # Copyright (c) 2026 Arista Networks, Inc.
2 # Use of this source code is governed by the Apache License 2.0
3 # that can be found in the LICENSE file.
4 """asynceapi session-based (cookie) authentication."""
5
6 from __future__ import annotations
7
8 import asyncio
9 import logging
10 from hashlib import blake2s
11 from http import HTTPStatus
12 from typing import TYPE_CHECKING
13
14 import httpx
15
16 from .errors import EapiAsyncOnlyError, EapiAuthenticationError
17
18 LOGGER = logging.getLogger(__name__)
19
20
21 def _cookie_fingerprint(cookie: str) -> str:
22 """Return a short fingerprint for correlating cookie lifecycle logs."""
23 return blake2s(cookie.encode(), digest_size=6).hexdigest()
24
25
26 if TYPE_CHECKING:
27 from collections.abc import AsyncGenerator, Generator
28
29
30 class EapiSessionAuth(httpx.Auth):
31 """httpx.Auth implementation for eAPI cookie-session authentication.
32
33 Performs a single login on the first request and attaches the session cookie thereafter.
34 A 401 on any request raises EapiAuthenticationError immediately.
35 """
36
37 def __init__(self, host: str, username: str, password: str, login_url: str) -> None:
38 """Initialize EapiSessionAuth with credentials and connection details."""
39 self._host = host
40 self._username = username
41 self._password = password
42 self._login_url = login_url
43 self.session_cookie: str | None = None
44 self._lock = asyncio.Lock()
45
46 @property
47 def logged_in(self) -> bool:
48 """Return whether session authentication currently has a cookie."""
49 return self.session_cookie is not None
50
51 def __repr__(self) -> str:
52 return f"EapiSessionAuth(host={self._host!r}, logged_in={self.logged_in})"
53
54 async def reset(self) -> None:
55 """Invalidate the current session, waiting for any in-progress login to complete first."""
56 async with self._lock:
57 self.session_cookie = None
58
59 def sync_auth_flow(self, request: httpx.Request) -> Generator[httpx.Request, httpx.Response, None]:
60 """Not supported — this auth class requires an async httpx client."""
61 _ = request
62 raise EapiAsyncOnlyError
63
64 async def async_auth_flow(
65 self,
66 request: httpx.Request,
67 ) -> AsyncGenerator[httpx.Request, httpx.Response]:
68 """Authenticate if needed, attach the session cookie, and dispatch the request."""
69 # Login on first use with double-checked locking
70 if not self.logged_in:
71 LOGGER.debug("No session cookie for %s, waiting for login...", self._host)
72 async with self._lock:
73 if not self.logged_in:
74 LOGGER.debug("Performing login for %s...", self._host)
75 # Send login request
76 login_request = httpx.Request("POST", self._login_url, json={"username": self._username, "password": self._password})
77 login_response = yield login_request
78
79 # Validate response
80 if login_response.status_code == HTTPStatus.UNAUTHORIZED:
81 await login_response.aread()
82 raise EapiAuthenticationError(self._host, response_text=login_response.text.strip())
83 login_response.raise_for_status()
84
85 # Extract session cookie
86 cookie = login_response.cookies.get("Session")
87 if not cookie:
88 msg = f"Login to {self._host!r} succeeded (HTTP {login_response.status_code}) but the response contained no Session cookie."
89 raise RuntimeError(msg) # device bug or misconfiguration
90
91 # Update state
92 self.session_cookie = cookie
93 LOGGER.debug("Session authentication established for %s with cookie fingerprint %s", self._host, _cookie_fingerprint(cookie))
94 elif self.session_cookie:
95 LOGGER.debug(
96 "Attempted to login for %s but another coroutine already established session authentication with cookie fingerprint %s",
97 self._host,
98 _cookie_fingerprint(self.session_cookie),
99 )
100
101 # Attach session cookie and dispatch the real request
102 used_cookie = self.session_cookie
103 request.headers["Cookie"] = f"Session={used_cookie}"
104 response = yield request
105
106 if response.status_code == HTTPStatus.UNAUTHORIZED:
107 await response.aread()
108 if self.session_cookie == used_cookie:
109 self.session_cookie = None
110 raise EapiAuthenticationError(self._host, response_text=response.text.strip(), session_expired=True)