Skip to content

Add api_tokens() method to retrieve API token details #126

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 2 commits into from
Nov 21, 2024
Merged
Show file tree
Hide file tree
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
4 changes: 2 additions & 2 deletions .gitguardian.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
secret:
ignored-matches:
ignored_matches:
- match: 5e9107aedc48b14af2749703ed3f83c2e1e6aca82ed86af980a2b925708c2da6
name: ''
ignored-paths:
ignored_paths:
- doc/**/*
- README.md
- CONTRIBUTING.md
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<!--
A new scriv changelog fragment.

Uncomment the section that is right (remove the HTML comment wrapper).
-->

<!--
### Removed

- A bullet item for the Removed category.

-->

### Added

- `GGClient` now provides a `api_tokens()` method to retrieve API token details (see https://api.gitguardian.com/docs#tag/API-Tokens).

<!--
### Changed

- A bullet item for the Changed category.

-->
<!--
### Deprecated

- A bullet item for the Deprecated category.

-->
<!--
### Fixed

- A bullet item for the Fixed category.

-->
<!--
### Security

- A bullet item for the Security category.

-->
30 changes: 30 additions & 0 deletions pygitguardian/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
IaCScanResult,
)
from .models import (
ApiTokensResponse,
Detail,
Document,
DocumentSchema,
Expand Down Expand Up @@ -353,6 +354,35 @@ def health_check(self) -> HealthCheckResponse:
secrets_engine_version=self.secrets_engine_version,
)

def api_tokens(
self, token: Optional[str] = None
) -> Union[Detail, ApiTokensResponse]:
"""
api_tokens retrieves details of an API token
If no token is passed, the endpoint retrieves details for the current API token.

use Detail.status_code to check the response status code of the API

200 if server is online, return token details
:return: Detail or ApiTokensReponse and status code
"""
try:
if not token:
token = "self"
resp = self.get(
endpoint=f"api_tokens/{token}",
)
except requests.exceptions.ReadTimeout:
result = Detail("The request timed out.")
result.status_code = 504
else:
if resp.ok:
result = ApiTokensResponse.from_dict(resp.json())
else:
result = load_detail(resp)
result.status_code = resp.status_code
return result

def content_scan(
self,
document: str,
Expand Down
85 changes: 85 additions & 0 deletions pygitguardian/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -756,6 +756,91 @@ def __repr__(self) -> str:
)


class TokenType(str, Enum):
PERSONAL_ACCESS_TOKEN = "personal_access_token"
SERVICE_ACCOUNT = "service_account"


class TokenStatus(str, Enum):
ACTIVE = "active"
EXPIRED = "expired"
REVOKED = "revoked"


class TokenScopes(str, Enum):
SCAN = "scan"
INCIDENTS_READ = "incidents:read"
INCIDENTS_WRITE = "incidents:write"
INCIDENTS_SHARE = "incidents:share"
MEMBERS_READ = "members:read"
MEMBERS_WRITE = "members:write"
TEAMS_READ = "teams:read"
TEAMS_WRITE = "teams:write"
AUDIT_LOGS_READ = "audit_logs:read"
HONEYTOKENS_READ = "honeytokens:read"
HONEYTOKENS_WRITE = "honeytokens:write"
API_TOKENS_READ = "api_tokens:read"
API_TOKENS_WRITE = "api_tokens:write"
IP_ALLOWLIST_READ = "ip_allowlist:read"
IP_ALLOWLIST_WRITE = "ip_allowlist:write"
SOURCES_READ = "sources:read"
SOURCES_WRITE = "sources:write"
NHI_WRITE = "nhi:write"


class ApiTokensResponseSchema(BaseSchema):
id = fields.UUID(required=True)
name = fields.String(required=True)
workspace_id = fields.Int(required=True)
type = fields.Enum(TokenType, by_value=True, required=True)
status = fields.Enum(TokenStatus, by_value=True, required=True)
created_at = fields.AwareDateTime(required=True)
last_used_at = fields.AwareDateTime(allow_none=True)
expire_at = fields.AwareDateTime(allow_none=True)
revoked_at = fields.AwareDateTime(allow_none=True)
member_id = fields.Int(allow_none=True)
creator_id = fields.Int(allow_none=True)
scopes = fields.List(fields.Enum(TokenScopes, by_value=True), required=False)

@post_load
def make_api_tokens_response(
self, data: Dict[str, Any], **kwargs: Any
) -> "ApiTokensResponse":
return ApiTokensResponse(**data)


class ApiTokensResponse(Base, FromDictMixin):
SCHEMA = ApiTokensResponseSchema()

def __init__(
self,
id: UUID,
name: str,
workspace_id: int,
type: TokenType,
status: TokenStatus,
created_at: datetime,
last_used_at: Optional[datetime] = None,
expire_at: Optional[datetime] = None,
revoked_at: Optional[datetime] = None,
member_id: Optional[int] = None,
creator_id: Optional[int] = None,
scopes: Optional[List[TokenScopes]] = None,
):
self.id = id
self.name = name
self.workspace_id = workspace_id
self.type = type
self.status = status
self.created_at = created_at
self.last_used_at = last_used_at
self.expire_at = expire_at
self.revoked_at = revoked_at
self.member_id = member_id
self.creator_id = creator_id
self.scopes = scopes or []


@dataclass
class SecretScanPreferences:
maximum_document_size: int = DOCUMENT_SIZE_THRESHOLD_BYTES
Expand Down
59 changes: 59 additions & 0 deletions tests/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
MULTI_DOCUMENT_LIMIT,
)
from pygitguardian.models import (
ApiTokensResponse,
Detail,
HoneytokenResponse,
HoneytokenWithContextResponse,
Expand Down Expand Up @@ -867,6 +868,64 @@ def test_versions_from_headers(client: GGClient, method):
assert other_client.secrets_engine_version == secrets_engine_version_value


@responses.activate
@pytest.mark.parametrize("token", ["self", "token"])
def test_api_tokens(client: GGClient, token):
"""
GIVEN a ggclient
WHEN calling api_tokens with or without a token
THEN the method returns the token details
"""
mock_response = responses.get(
url=client._url_from_endpoint(f"api_tokens/{token}", "v1"),
content_type="application/json",
status=201,
json={
"id": "5ddaad0c-5a0c-4674-beb5-1cd198d13360",
"name": "myTokenName",
"workspace_id": 42,
"type": "personal_access_token",
"status": "revoked",
"created_at": "2023-05-20T12:40:55.662949Z",
"last_used_at": "2023-05-24T12:40:55.662949Z",
"expire_at": None,
"revoked_at": "2023-05-27T12:40:55.662949Z",
"member_id": 22015,
"creator_id": 22015,
"scopes": ["incidents:read", "scan"],
},
)

result = client.api_tokens(token)

assert mock_response.call_count == 1
assert isinstance(result, ApiTokensResponse)


@responses.activate
def test_api_tokens_error(
client: GGClient,
):
"""
GIVEN a ggclient
WHEN calling api_tokens with an invalid token
THEN the method returns a Detail object containing the error detail
"""
mock_response = responses.get(
url=client._url_from_endpoint("api_tokens/invalid", "v1"),
content_type="application/json",
status=400,
json={
"detail": "Not authorized",
},
)

result = client.api_tokens(token="invalid")

assert mock_response.call_count == 1
assert isinstance(result, Detail)


@responses.activate
def test_create_honeytoken(
client: GGClient,
Expand Down
20 changes: 20 additions & 0 deletions tests/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import pytest

from pygitguardian.models import (
ApiTokensResponse,
ApiTokensResponseSchema,
Detail,
DetailSchema,
Document,
Expand Down Expand Up @@ -63,6 +65,24 @@ def test_document_handle_surrogates(self):
OrderedDict,
{"detail": "hello", "status_code": 200},
),
(
ApiTokensResponseSchema,
ApiTokensResponse,
{
"id": "5ddaad0c-5a0c-4674-beb5-1cd198d13360",
"name": "myTokenName",
"workspace_id": 42,
"type": "personal_access_token",
"status": "revoked",
"created_at": "2023-05-20T12:40:55.662949Z",
"last_used_at": "2023-05-24T12:40:55.662949Z",
"expire_at": None,
"revoked_at": "2023-05-27T12:40:55.662949Z",
"member_id": 22015,
"creator_id": 22015,
"scopes": ["incidents:read", "scan"],
},
),
(MatchSchema, Match, {"match": "hello", "type": "hello"}),
(
MultiScanResultSchema,
Expand Down
Loading