Skip to content
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

add keyring cli get creds mode #127

Merged
merged 1 commit into from
Jun 25, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 16 additions & 5 deletions src/unearth/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import os
import shutil
import subprocess
from typing import TYPE_CHECKING, Optional, Tuple, cast
from typing import TYPE_CHECKING, Literal, Optional, Tuple, cast
from urllib.parse import SplitResult, urlparse, urlsplit

from httpx import URL, Auth, BasicAuth
Expand Down Expand Up @@ -83,20 +83,31 @@ def __init__(self, cmd: str) -> None:
self.keyring = cmd

def get_auth_info(self, url: str, username: str | None) -> AuthInfo | None:
logger.debug("Getting credentials from keyring CLI for url: %s", url)
cred = self._get_secret(url, username or "", mode="creds")
if cred is not None:
username, password = cred.splitlines()
return username, password

if username is None:
username = "__token__"
logger.debug("Getting password from keyring CLI for %s@%s", username, url)
password = self._get_password(url, username)
password = self._get_secret(url, username) # type: ignore[assignment]
if password is not None:
return username, password
return None

def save_auth_info(self, url: str, username: str, password: str) -> None:
return self._set_password(url, username, password)

def _get_password(self, service_name: str, username: str) -> str | None:
"""Mirror the implementation of keyring.get_password using cli"""
cmd = [self.keyring, "get", service_name, username]
def _get_secret(
self,
service_name: str,
username: str,
mode: Literal["password", "creds"] = "password",
) -> str | None:
"""Mirror the implementation of keyring.get_[password|credential] using cli"""
cmd = [self.keyring, f"--mode={mode}", "get", service_name, username]
env = dict(os.environ, PYTHONIOENCODING="utf-8")
res = subprocess.run(
cmd, stdin=subprocess.DEVNULL, capture_output=True, env=env
Expand Down