-
Notifications
You must be signed in to change notification settings - Fork 12
feat: add api client for diode auth credentials api #104
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -29,3 +29,5 @@ dist/ | |
| # Docker | ||
| docker/coverage | ||
| !docker/netbox/env | ||
| docker/oauth2/secrets/* | ||
| !docker/oauth2/secrets/.gitkeep | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,49 +1,18 @@ | ||
| # !/usr/bin/env python | ||
| # Copyright 2025 NetBox Labs, Inc. | ||
| """Diode NetBox Plugin - Client.""" | ||
|
|
||
| from netbox_diode_plugin.diode.clients import get_api_client | ||
|
|
||
| def create_client(request, client_name, scope): | ||
| ret = { | ||
| "client_name": "client_name1", | ||
| "client_id": "client_id", | ||
| "client_secret": "client_secret", | ||
| "scope": "scope", | ||
| "created_at": "2025-03-14T15:16:17Z" | ||
| } | ||
| return ret | ||
|
|
||
| return get_api_client().create_client(client_name, scope) | ||
|
|
||
| def delete_client(request, client_id): | ||
| pass | ||
|
|
||
|
|
||
| def get_client(request, client_id): | ||
| ret = { | ||
| "client_name": "client_name1", | ||
| "client_id": "client_id", | ||
| "client_secret": "client_secret", | ||
| "scope": "scope", | ||
| "created_at": "2025-03-14T15:16:17Z" | ||
| } | ||
| return ret | ||
|
|
||
| return get_api_client().delete_client(client_id) | ||
|
|
||
| def list_clients(request): | ||
| ret = { | ||
| "data": [ | ||
| { | ||
| "client_name": "My Agent 1", | ||
| "client_id": "my-agent-1-a038dfef", | ||
| "scope": "diode:ingest", | ||
| "created_at": "2025-03-14T15:16:17Z" | ||
| }, | ||
| { | ||
| "client_name": "US East 12", | ||
| "client_id": "us-east-12-f00fa3cd", | ||
| "scope": "diode:ingest", | ||
| "created_at": "2025-04-15T10:11:00Z" | ||
| } | ||
| ], | ||
| "next_page_token": "3", | ||
| } | ||
| return ret["data"] | ||
|
|
||
| response = get_api_client().list_clients() | ||
| return response["data"] | ||
|
|
||
| def get_client(request, client_id): | ||
| return get_api_client().get_client(client_id) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,209 @@ | ||
| #!/usr/bin/env python | ||
| # Copyright 2025 NetBox Labs Inc | ||
| """Diode NetBox Plugin - Diode - Auth.""" | ||
|
|
||
| from dataclasses import dataclass | ||
| import datetime | ||
| import json | ||
| import logging | ||
| import requests | ||
| import threading | ||
| from urllib.parse import urlencode | ||
| from netbox_diode_plugin.plugin_config import ( | ||
| get_diode_auth_base_url, | ||
| get_diode_credentials, | ||
| get_diode_max_auth_retries, | ||
| ) | ||
|
|
||
| SCOPE_DIODE_READ = "diode:read" | ||
| SCOPE_DIODE_WRITE = "diode:write" | ||
|
|
||
| logger = logging.getLogger("netbox.diode_data") | ||
|
|
||
|
|
||
| _client = None | ||
| _client_lock = threading.Lock() | ||
| def get_api_client(): | ||
| """Get the client API client.""" | ||
| global _client | ||
| global _client_lock | ||
|
|
||
| with _client_lock: | ||
| if _client is None: | ||
| client_id, client_secret = get_diode_credentials() | ||
| max_auth_retries = get_diode_max_auth_retries() | ||
| _client = ClientAPI( | ||
| base_url=get_diode_auth_base_url(), | ||
| client_id=client_id, | ||
| client_secret=client_secret, | ||
| max_auth_retries=max_auth_retries, | ||
| ) | ||
| return _client | ||
|
|
||
|
|
||
| class ClientAPIError(Exception): | ||
| """Client API Error.""" | ||
|
|
||
| def __init__(self, message: str, status_code: int = 500): | ||
| """Initialize the ClientAPIError.""" | ||
| self.message = message | ||
| self.status_code = status_code | ||
| super().__init__(self.message) | ||
|
|
||
| def is_auth_error(self) -> bool: | ||
| """Check if the error is an authentication error.""" | ||
| return self.status_code == 401 or self.status_code == 403 | ||
|
|
||
| class ClientAPI: | ||
| """Manages Diode Clients.""" | ||
|
|
||
| def __init__(self, base_url: str, client_id: str, client_secret: str, max_auth_retries: int = 2): | ||
| """Initialize the ClientAPI.""" | ||
| self.base_url = base_url | ||
| self.client_id = client_id | ||
| self.client_secret = client_secret | ||
|
|
||
| self._max_auth_retries = max_auth_retries | ||
| self._client_auth_token = None | ||
| self._client_auth_token_lock = threading.Lock() | ||
|
|
||
| def create_client(self, name: str, scope: str) -> dict: | ||
| """Create a client.""" | ||
| for attempt in range(self._max_auth_retries): | ||
| token = None | ||
| try: | ||
| token = self._get_token() | ||
| url = self.base_url + "/clients" | ||
| headers = {"Authorization": f"Bearer {token}"} | ||
| data = { | ||
| "client_name": name, | ||
| "scope": scope, | ||
| } | ||
| response = requests.post(url, data=data, headers=headers) | ||
| if response.status_code != 200: | ||
| raise ClientAPIError("Failed to create client", response.status_code) | ||
| return response.json() | ||
| except ClientAPIError as e: | ||
| if e.is_auth_error() and attempt < self._max_auth_retries - 1: | ||
| logger.info(f"Retrying create_client due to unauthenticated error, attempt {attempt + 1}") | ||
| self._mark_client_auth_token_invalid(token) | ||
| continue | ||
| raise | ||
| raise ClientAPIError("Failed to create client: unexpected state", 500) | ||
|
|
||
| def get_client(self, client_id: str) -> dict: | ||
| """Get a client.""" | ||
| for attempt in range(self._max_auth_retries): | ||
| token = None | ||
| try: | ||
| token = self._get_token() | ||
| url = self.base_url + f"/clients/{client_id}" | ||
| headers = {"Authorization": f"Bearer {token}"} | ||
| response = requests.get(url, headers=headers) | ||
| if response.status_code == 401 or response.status_code == 403: | ||
| raise ClientAPIError(f"Failed to get client {client_id}", response.status_code) | ||
| if response.status_code != 200: | ||
| raise ClientAPIError(f"Failed to get client {client_id}", response.status_code) | ||
| return response.json() | ||
| except ClientAPIError as e: | ||
| if e.is_auth_error() and attempt < self._max_auth_retries - 1: | ||
| logger.info(f"Retrying delete_client due to unauthenticated error, attempt {attempt + 1}") | ||
| self._mark_client_auth_token_invalid(token) | ||
| continue | ||
| raise | ||
| raise ClientAPIError(f"Failed to get client {client_id}: unexpected state") | ||
|
|
||
| def delete_client(self, client_id: str) -> None: | ||
| """Delete a client.""" | ||
| for attempt in range(self._max_auth_retries): | ||
| token = None | ||
| try: | ||
| token = self._get_token() | ||
| url = self.base_url + f"/clients/{client_id}" | ||
| headers = {"Authorization": f"Bearer {token}"} | ||
| response = requests.delete(url, headers=headers) | ||
| if response.status_code == 401 or response.status_code == 403: | ||
| raise ClientAPIError(f"Failed to delete client {client_id}", response.status_code) | ||
| if response.status_code != 200: | ||
| raise ClientAPIError(f"Failed to delete client {client_id}", response.status_code) | ||
| return response.json() | ||
| except ClientAPIError as e: | ||
| if e.is_auth_error() and attempt < self._max_auth_retries - 1: | ||
| logger.info(f"Retrying delete_client due to unauthenticated error, attempt {attempt + 1}") | ||
| self._mark_client_auth_token_invalid(token) | ||
| continue | ||
| raise | ||
| raise ClientAPIError(f"Failed to delete client {client_id}: unexpected state") | ||
|
|
||
|
|
||
| def list_clients(self, page_token: str | None = None, page_size: int | None = None) -> list[dict]: | ||
| """List all clients.""" | ||
| for attempt in range(self._max_auth_retries): | ||
| token = None | ||
| try: | ||
| token = self._get_token() | ||
| url = self.base_url + "/clients" | ||
| headers = {"Authorization": f"Bearer {token}"} | ||
| params = {} | ||
| if page_token: | ||
| params["page_token"] = page_token | ||
| if page_size: | ||
| params["page_size"] = page_size | ||
| response = requests.get(url, headers=headers, params=params) | ||
| if response.status_code == 401 or response.status_code == 403: | ||
| raise ClientAPIError("Failed to get clients", response.status_code) | ||
| if response.status_code != 200: | ||
| raise ClientAPIError("Failed to get clients", response.status_code) | ||
| return response.json() | ||
| except ClientAPIError as e: | ||
| if e.is_auth_error() and attempt < self._max_auth_retries - 1: | ||
| logger.info(f"Retrying list_clients due to unauthenticated error, attempt {attempt + 1}") | ||
| self._mark_client_auth_token_invalid(token) | ||
| continue | ||
| raise | ||
| raise ClientAPIError("Failed to list clients: unexpected state") | ||
|
|
||
|
|
||
| def _get_token(self) -> str: | ||
| """Get a token for the Diode Auth Service.""" | ||
| with self._client_auth_token_lock: | ||
| if self._client_auth_token: | ||
| return self._client_auth_token | ||
| self._client_auth_token = self._authenticate() | ||
| return self._client_auth_token | ||
|
|
||
| def _mark_client_auth_token_invalid(self, token: str): | ||
| """Mark a client auth token as invalid.""" | ||
| with self._client_auth_token_lock: | ||
| self._client_auth_token = None | ||
|
|
||
| def _authenticate(self) -> str: | ||
| """Get a new access token for the Diode Auth Service.""" | ||
| headers = {"Content-Type": "application/x-www-form-urlencoded"} | ||
| data = urlencode( | ||
| { | ||
| "grant_type": "client_credentials", | ||
| "client_id": self.client_id, | ||
| "client_secret": self.client_secret, | ||
| "scope": f"{SCOPE_DIODE_READ} {SCOPE_DIODE_WRITE}", | ||
| } | ||
| ) | ||
| url = self.base_url + "/token" | ||
| try: | ||
| response = requests.post(url, data=data, headers=headers) | ||
| except Exception as e: | ||
| raise ClientAPIError(f"Failed to obtain access token: {e}", 401) from e | ||
| if response.status_code != 200: | ||
| raise ClientAPIError(f"Failed to obtain access token: {response.reason}", 401) | ||
|
|
||
| try: | ||
| token_info = response.json() | ||
| except Exception as e: | ||
| raise ClientAPIError(f"Failed to parse access token response: {e}", 401) from e | ||
|
|
||
| access_token = token_info.get("access_token") | ||
| if not access_token: | ||
| raise ClientAPIError(f"Failed to obtain access token for client {self._client_id}", 401) | ||
|
|
||
| return access_token | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can we add some basic tests for ClientAPI, please?