socketdev 3.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,84 @@
1
+ import logging
2
+ from urllib.parse import urlencode
3
+
4
+ log = logging.getLogger("socketdev")
5
+
6
+
7
+ class Historical:
8
+ def __init__(self, api):
9
+ self.api = api
10
+ self.snapshots = self.Snapshots(api)
11
+
12
+ def list(self, org_slug: str, query_params: dict = None) -> dict:
13
+ """Get historical alerts list for an organization.
14
+
15
+ Args:
16
+ org_slug: Organization slug
17
+ query_params: Optional dictionary of query parameters
18
+ """
19
+ path = f"orgs/{org_slug}/historical/alerts"
20
+ if query_params:
21
+ path += "?" + urlencode(query_params)
22
+
23
+ response = self.api.do_request(path=path)
24
+ if response.status_code == 200:
25
+ return response.json()
26
+
27
+ log.error(f"Error getting historical alerts: {response.status_code}")
28
+ log.error(response.text)
29
+ return {}
30
+
31
+ def trend(self, org_slug: str, query_params: dict = None) -> dict:
32
+ """Get historical alert trends data for an org.
33
+
34
+ Args:
35
+ org_slug: Organization slug
36
+ query_params: Optional dictionary of query parameters
37
+ """
38
+ path = f"orgs/{org_slug}/historical/alerts/trend"
39
+ if query_params:
40
+ path += "?" + urlencode(query_params)
41
+
42
+ response = self.api.do_request(path=path)
43
+ if response.status_code == 200:
44
+ return response.json()
45
+
46
+ log.error(f"Error getting historical trend: {response.status_code}")
47
+ log.error(response.text)
48
+ return {}
49
+
50
+ class Snapshots:
51
+ """Submodule for managing historical snapshots."""
52
+
53
+ def __init__(self, api):
54
+ self.api = api
55
+
56
+ def create(self, org_slug: str) -> dict:
57
+ """Create a new snapshot for an organization.
58
+
59
+ Args:
60
+ org_slug: Organization slug
61
+ data: Dictionary containing snapshot data
62
+ """
63
+ path = f"orgs/{org_slug}/historical/snapshots"
64
+ response = self.api.do_request(path=path, method="POST")
65
+ if response.status_code == 200:
66
+ return response.json()
67
+
68
+ log.error(f"Error creating snapshot: {response.status_code}")
69
+ log.error(response.text)
70
+ return {}
71
+
72
+ def list(self, org_slug: str, query_params: dict = None) -> dict:
73
+ """List historical snapshots for an organization."""
74
+ path = f"orgs/{org_slug}/historical/snapshots"
75
+ if query_params:
76
+ path += "?" + urlencode(query_params)
77
+
78
+ response = self.api.do_request(path=path)
79
+ if response.status_code == 200:
80
+ return response.json()
81
+
82
+ log.error(f"Error listing snapshots: {response.status_code}")
83
+ log.error(response.text)
84
+ return {}
@@ -0,0 +1,121 @@
1
+ import json
2
+ import logging
3
+ from typing import Any
4
+ from urllib.parse import urlencode
5
+
6
+
7
+ log = logging.getLogger("socketdev")
8
+
9
+ class Setting:
10
+ def __init__(self, api):
11
+ self.api = api
12
+
13
+ def create_url(self, org_slug: str, label_id: int):
14
+ return "orgs/" + org_slug + f"/repos/labels/{label_id}/label-setting"
15
+
16
+ def get(self, org_slug: str, label_id: int, setting_key: str):
17
+ url = self.create_url(org_slug, label_id)
18
+ path = f"{url}?setting_key={setting_key}"
19
+ response = self.api.do_request(path=path)
20
+ if response.status_code == 201:
21
+ return response.json()
22
+
23
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
24
+ log.error(f"Error getting label setting {setting_key} for {label_id}: {response.status_code}, message: {error_message}")
25
+ return {}
26
+
27
+ def put(self, org_slug: str, label_id: int, settings: dict[str, dict[str, dict[str, str]]]):
28
+ path = self.create_url(org_slug, label_id)
29
+ response = self.api.do_request(method="PUT", path=path, payload=json.dumps(settings))
30
+
31
+ if response.status_code == 201:
32
+ return response.json()
33
+
34
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
35
+ log.error(f"Error updating label settings for {label_id}: {response.status_code}, message: {error_message}")
36
+ return {}
37
+
38
+ def delete(self, org_slug: str, label_id: int, settings_key: str):
39
+ path = self.create_url(org_slug, label_id)
40
+ path += "?setting_key=" + settings_key
41
+ response = self.api.do_request(path=path, method="DELETE")
42
+
43
+ if response.status_code == 201:
44
+ return response.json()
45
+
46
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
47
+ log.error(f"Error updating label settings for {label_id}: {response.status_code}, message: {error_message}")
48
+ return {}
49
+
50
+
51
+ class Labels:
52
+ def __init__(self, api):
53
+ self.api = api
54
+ self.setting = Setting(api)
55
+
56
+ def list(self, org_slug: str):
57
+ path = f"orgs/" + org_slug + f"/repos/labels"
58
+ response = self.api.do_request(path=path)
59
+ if response.status_code == 200:
60
+ return response.json()
61
+
62
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
63
+ log.error(f"Error getting labels: {response.status_code}, message: {error_message}")
64
+ return {}
65
+
66
+ def post(self, org_slug: str, label_name: str) -> dict:
67
+ path = f"orgs/{org_slug}/repos/labels"
68
+ payload = json.dumps({"name": label_name})
69
+ response = self.api.do_request(path=path, method="POST", payload=payload)
70
+
71
+ if response.status_code == 201:
72
+ result = response.json()
73
+ return result
74
+
75
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
76
+ log.error(f"Failed to create repository label: {response.status_code}, message: {error_message}")
77
+ return {}
78
+
79
+ def get(self, org_slug: str, label_id: str) -> dict:
80
+ path = f"orgs/{org_slug}/repos/labels/{label_id}"
81
+ response = self.api.do_request(path=path)
82
+ if response.status_code == 200:
83
+ result = response.json()
84
+ return result
85
+
86
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
87
+ log.error(f"Failed to get repository label: {response.status_code}, message: {error_message}")
88
+ return {}
89
+
90
+ def delete(self, org_slug: str, label_id: str) -> dict:
91
+ path = f"orgs/{org_slug}/repos/labels/{label_id}"
92
+ response = self.api.do_request(path=path, method="DELETE")
93
+ if response.status_code == 200:
94
+ return response.json()
95
+
96
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
97
+ log.error(f"Error deleting repository label: {response.status_code}, message: {error_message}")
98
+ return {}
99
+
100
+
101
+ def associate(self, org_slug: str, label_id: int, repo_id: str) -> dict:
102
+ path = f"orgs/{org_slug}/repos/labels/{label_id}/associate"
103
+ payload = json.dumps({"repository_id": repo_id})
104
+ response = self.api.do_request(path=path, method="POST", payload=payload)
105
+ if response.status_code == 200:
106
+ return response.json()
107
+
108
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
109
+ log.error(f"Error associating repository label: {response.status_code}, message: {error_message}")
110
+ return {}
111
+
112
+ def disassociate(self, org_slug: str, label_id: int, repo_id: str) -> dict:
113
+ path = f"orgs/{org_slug}/repos/labels/{label_id}/disassociate"
114
+ payload = json.dumps({"repository_id": repo_id})
115
+ response = self.api.do_request(path=path, method="POST", payload=payload)
116
+ if response.status_code == 200:
117
+ return response.json()
118
+
119
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
120
+ log.error(f"Error associating repository label: {response.status_code}, message: {error_message}")
121
+ return {}
@@ -0,0 +1,27 @@
1
+ import json
2
+ import logging
3
+ import urllib.parse
4
+
5
+ log = logging.getLogger("socketdev")
6
+
7
+
8
+ class LicenseMetadata:
9
+ def __init__(self, api):
10
+ self.api = api
11
+
12
+ def post(self, licenses: list, params: dict = None) -> dict:
13
+ path = f"license-metadata"
14
+ if params:
15
+ query_args = urllib.parse.urlencode(params)
16
+ path += f"?{query_args}"
17
+ payload = json.dumps(licenses)
18
+ response = self.api.do_request(path=path, method="POST", payload=payload)
19
+
20
+ if response.status_code == 200:
21
+ result = response.json()
22
+ return result
23
+
24
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
25
+ log.error(f"Failed to create license metadata: {response.status_code}, message: {error_message}")
26
+ return {}
27
+
socketdev/log.py ADDED
@@ -0,0 +1,4 @@
1
+ import logging
2
+
3
+ log = logging.getLogger("socketdev")
4
+ log.addHandler(logging.NullHandler())
@@ -0,0 +1,28 @@
1
+ import logging
2
+
3
+ log = logging.getLogger("socketdev")
4
+
5
+ # TODO: Add response type classes for NPM endpoints
6
+
7
+
8
+ class NPM:
9
+ def __init__(self, api):
10
+ self.api = api
11
+
12
+ def issues(self, package: str, version: str) -> list:
13
+ path = f"npm/{package}/{version}/issues"
14
+ response = self.api.do_request(path=path)
15
+ if response.status_code == 200:
16
+ return response.json()
17
+ log.error(f"Error getting npm issues: {response.status_code}")
18
+ log.error(response.text)
19
+ return []
20
+
21
+ def score(self, package: str, version: str) -> list:
22
+ path = f"npm/{package}/{version}/score"
23
+ response = self.api.do_request(path=path)
24
+ if response.status_code == 200:
25
+ return response.json()
26
+ log.error(f"Error getting npm score: {response.status_code}")
27
+ log.error(response.text)
28
+ return []
@@ -0,0 +1,19 @@
1
+ import logging
2
+
3
+ log = logging.getLogger("socketdev")
4
+
5
+ # TODO: Add response type classes for OpenAPI endpoints
6
+
7
+
8
+ class OpenAPI:
9
+ def __init__(self, api):
10
+ self.api = api
11
+
12
+ def get(self) -> dict:
13
+ path = "openapi"
14
+ response = self.api.do_request(path=path)
15
+ if response.status_code == 200:
16
+ return response.json()
17
+ log.error(f"Error getting OpenAPI spec: {response.status_code}")
18
+ log.error(response.text)
19
+ return {}
@@ -0,0 +1,34 @@
1
+ from typing import TypedDict, Dict
2
+ import logging
3
+
4
+ log = logging.getLogger("socketdev")
5
+
6
+
7
+ class Organization(TypedDict):
8
+ id: str
9
+ name: str
10
+ image: str
11
+ plan: str
12
+ slug: str
13
+
14
+
15
+ class OrganizationsResponse(TypedDict):
16
+ organizations: Dict[str, Organization]
17
+ # Add other fields from the response if needed
18
+
19
+
20
+ class Orgs:
21
+ def __init__(self, api):
22
+ self.api = api
23
+
24
+ def get(self, use_types: bool = False) -> OrganizationsResponse:
25
+ path = "organizations"
26
+ response = self.api.do_request(path=path)
27
+ if response.status_code == 200:
28
+ result = response.json()
29
+ if use_types:
30
+ return OrganizationsResponse(result)
31
+ return result
32
+ log.error(f"Error getting organizations: {response.status_code}")
33
+ log.error(response.text)
34
+ return {"organizations": {}}
@@ -0,0 +1,41 @@
1
+ import json
2
+ import urllib.parse
3
+ from socketdev.log import log
4
+ from ..core.dedupe import Dedupe
5
+
6
+
7
+ class Purl:
8
+ def __init__(self, api):
9
+ self.api = api
10
+
11
+ def post(self, license: str = "false", components: list = None, **kwargs) -> list:
12
+ path = "purl?"
13
+ if components is None:
14
+ components = []
15
+ purls = {"components": components}
16
+ purls = json.dumps(purls)
17
+ query_args = {
18
+ "license": license,
19
+ }
20
+ if kwargs:
21
+ query_args.update(kwargs)
22
+ params = urllib.parse.urlencode(query_args)
23
+ path += params
24
+ response = self.api.do_request(path=path, payload=purls, method="POST")
25
+ if response.status_code == 200:
26
+ purl = []
27
+ result = response.text
28
+ result = result.strip('"').strip()
29
+ for line in result.split("\n"):
30
+ if line and line != '"':
31
+ try:
32
+ item = json.loads(line)
33
+ purl.append(item)
34
+ except json.JSONDecodeError:
35
+ continue
36
+ purl_deduped = Dedupe.dedupe(purl)
37
+ return purl_deduped
38
+
39
+ log.error(f"Error posting {components} to the Purl API: {response.status_code}")
40
+ log.error(response.text)
41
+ return []
@@ -0,0 +1,19 @@
1
+ import logging
2
+
3
+ log = logging.getLogger("socketdev")
4
+
5
+ # TODO: Add response type classes for Quota endpoints
6
+
7
+
8
+ class Quota:
9
+ def __init__(self, api):
10
+ self.api = api
11
+
12
+ def get(self) -> dict:
13
+ path = "quota"
14
+ response = self.api.do_request(path=path)
15
+ if response.status_code == 200:
16
+ return response.json()
17
+ log.error(f"Error getting quota: {response.status_code}")
18
+ log.error(response.text)
19
+ return {}
@@ -0,0 +1,72 @@
1
+ import logging
2
+ from datetime import datetime, timedelta, timezone
3
+
4
+ log = logging.getLogger("socketdev")
5
+
6
+ # TODO: Add response type classes for Report endpoints
7
+
8
+
9
+ class Report:
10
+ def __init__(self, api):
11
+ self.api = api
12
+
13
+ def list(self, from_time: int = None) -> dict:
14
+ """
15
+ This function will return all reports from time specified.
16
+ :param from_time: Unix epoch time in seconds. Will default self, to 30 days
17
+ """
18
+ if from_time is None:
19
+ from_time = int((datetime.now(timezone.utc) - timedelta(days=30)).timestamp())
20
+ else:
21
+ from_time = int((datetime.now(timezone.utc) - timedelta(seconds=from_time)).timestamp())
22
+
23
+ path = "report/list"
24
+ if from_time is not None:
25
+ path += f"?from={from_time}"
26
+ response = self.api.do_request(path=path)
27
+ if response.status_code == 200:
28
+ return response.json()
29
+ log.error(f"Error listing reports: {response.status_code}")
30
+ log.error(response.text)
31
+ return {}
32
+
33
+ def delete(self, report_id: str) -> bool:
34
+ path = f"report/delete/{report_id}"
35
+ response = self.api.do_request(path=path, method="DELETE")
36
+ if response.status_code == 200:
37
+ return True
38
+ log.error(f"Error deleting report: {response.status_code}")
39
+ log.error(response.text)
40
+ return False
41
+
42
+ def view(self, report_id) -> dict:
43
+ path = f"report/view/{report_id}"
44
+ response = self.api.do_request(path=path)
45
+ if response.status_code == 200:
46
+ return response.json()
47
+ log.error(f"Error viewing report: {response.status_code}")
48
+ log.error(response.text)
49
+ return {}
50
+
51
+ def supported(self) -> dict:
52
+ path = "report/supported"
53
+ response = self.api.do_request(path=path)
54
+ if response.status_code == 200:
55
+ return response.json()
56
+ log.error(f"Error getting supported reports: {response.status_code}")
57
+ log.error(response.text)
58
+ return {}
59
+
60
+ def create(self, files: list) -> dict:
61
+ open_files = []
62
+ for name, path in files:
63
+ file_info = (name, (name, open(path, "rb"), "text/plain"))
64
+ open_files.append(file_info)
65
+ path = "report/upload"
66
+ payload = {}
67
+ response = self.api.do_request(path=path, method="PUT", files=open_files, payload=payload)
68
+ if response.status_code == 200:
69
+ return response.json()
70
+ log.error(f"Error creating report: {response.status_code}")
71
+ log.error(response.text)
72
+ return {}
@@ -0,0 +1,165 @@
1
+ import json
2
+ import logging
3
+ from typing import Optional, Union
4
+ from dataclasses import dataclass, asdict
5
+
6
+ log = logging.getLogger("socketdev")
7
+
8
+
9
+ @dataclass
10
+ class RepositoryInfo:
11
+ id: str
12
+ created_at: str # Could be datetime if we want to parse it
13
+ updated_at: str # Could be datetime if we want to parse it
14
+ head_full_scan_id: str
15
+ name: str
16
+ description: str
17
+ homepage: str
18
+ visibility: str
19
+ archived: bool
20
+ default_branch: str
21
+ slug: Optional[str] = None
22
+
23
+ def __getitem__(self, key):
24
+ return getattr(self, key)
25
+
26
+ def to_dict(self):
27
+ return asdict(self)
28
+
29
+ @classmethod
30
+ def from_dict(cls, data: dict) -> "RepositoryInfo":
31
+ return cls(
32
+ id=data["id"],
33
+ created_at=data.get("created_at", ""),
34
+ updated_at=data.get("updated_at", ""),
35
+ head_full_scan_id=data.get("head_full_scan_id", ""),
36
+ name=data["name"],
37
+ description=data.get("description", ""),
38
+ homepage=data.get("homepage", ""),
39
+ visibility=data.get("visibility", "private"),
40
+ archived=data.get("archived", False),
41
+ default_branch=data.get("default_branch", "main"),
42
+ slug=data["slug"]
43
+ )
44
+
45
+
46
+ @dataclass
47
+ class GetRepoResponse:
48
+ success: bool
49
+ status: int
50
+ data: Optional[RepositoryInfo] = None
51
+ message: Optional[str] = None
52
+
53
+ def __getitem__(self, key):
54
+ return getattr(self, key)
55
+
56
+ def to_dict(self):
57
+ return asdict(self)
58
+
59
+ @classmethod
60
+ def from_dict(cls, data: dict) -> "GetRepoResponse":
61
+ return cls(
62
+ success=data["success"],
63
+ status=data["status"],
64
+ message=data.get("message"),
65
+ data=RepositoryInfo.from_dict(data.get("data")) if data.get("data") else None,
66
+ )
67
+
68
+
69
+ class Repos:
70
+ def __init__(self, api):
71
+ self.api = api
72
+
73
+ def get(self, org_slug: str, **kwargs) -> dict[str, list[dict] | int]:
74
+ query_params = kwargs
75
+ path = "orgs/" + org_slug + "/repos"
76
+
77
+ if query_params: # Only add query string if we have parameters
78
+ path += "?"
79
+ for param in query_params:
80
+ value = query_params[param]
81
+ path += f"{param}={value}&"
82
+ path = path.rstrip("&")
83
+
84
+ response = self.api.do_request(path=path)
85
+
86
+ if response.status_code == 200:
87
+ raw_result = response.json()
88
+ per_page = int(query_params.get("per_page", 30))
89
+
90
+ # TEMPORARY: Handle pagination edge case where API returns nextPage=1 even when no more results exist
91
+ if raw_result["nextPage"] != 0 and len(raw_result["results"]) < per_page:
92
+ raw_result["nextPage"] = 0
93
+
94
+ return raw_result
95
+
96
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
97
+ log.error(f"Error getting repositories: {response.status_code}, message: {error_message}")
98
+ return {}
99
+
100
+ def repo(self, org_slug: str, repo_name: str, use_types: bool = False) -> Union[dict, GetRepoResponse]:
101
+ path = f"orgs/{org_slug}/repos/{repo_name}"
102
+ response = self.api.do_request(path=path)
103
+
104
+ if response.status_code == 200:
105
+ result = response.json()
106
+ if use_types:
107
+ return GetRepoResponse.from_dict({"success": True, "status": 200, "data": result})
108
+ return result
109
+
110
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
111
+ log.error(f"Failed to get repository: {response.status_code}, message: {error_message}")
112
+ if use_types:
113
+ return GetRepoResponse.from_dict(
114
+ {"success": False, "status": response.status_code, "message": error_message}
115
+ )
116
+ return {}
117
+
118
+ def delete(self, org_slug: str, name: str) -> dict:
119
+ path = f"orgs/{org_slug}/repos/{name}"
120
+ response = self.api.do_request(path=path, method="DELETE")
121
+
122
+ if response.status_code == 200:
123
+ return response.json()
124
+
125
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
126
+ log.error(f"Error deleting repository: {response.status_code}, message: {error_message}")
127
+ return {}
128
+
129
+ def post(self, org_slug: str, **kwargs) -> dict:
130
+ params = {}
131
+ if kwargs:
132
+ for key, val in kwargs.items():
133
+ params[key] = val
134
+ if len(params) == 0:
135
+ return {}
136
+
137
+ path = "orgs/" + org_slug + "/repos"
138
+ payload = json.dumps(params)
139
+ response = self.api.do_request(path=path, method="POST", payload=payload)
140
+
141
+ if response.status_code == 201:
142
+ return response.json()
143
+
144
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
145
+ log.error(f"Error creating repository: {response.status_code}, message: {error_message}")
146
+ return {}
147
+
148
+ def update(self, org_slug: str, repo_name: str, **kwargs) -> dict:
149
+ params = {}
150
+ if kwargs:
151
+ for key, val in kwargs.keys():
152
+ params[key] = val
153
+ if len(params) == 0:
154
+ return {}
155
+
156
+ path = f"orgs/{org_slug}/repos/{repo_name}"
157
+ payload = json.dumps(params)
158
+ response = self.api.do_request(path=path, method="POST", payload=payload)
159
+
160
+ if response.status_code == 200:
161
+ return response.json()
162
+
163
+ error_message = response.json().get("error", {}).get("message", "Unknown error")
164
+ log.error(f"Error updating repository: {response.status_code}, message: {error_message}")
165
+ return {}
@@ -0,0 +1,31 @@
1
+ from typing import TypedDict, Union
2
+ import logging
3
+
4
+ log = logging.getLogger("socketdev")
5
+
6
+
7
+ class Repo(TypedDict):
8
+ name: str
9
+ description: str
10
+ homepage: str
11
+ visibility: str
12
+ archived: bool
13
+ default_branch: str
14
+
15
+
16
+ class Repositories:
17
+ def __init__(self, api):
18
+ self.api = api
19
+
20
+ def list(self, use_types: bool = False) -> Union[dict, list[Repo]]:
21
+ path = "repos"
22
+ response = self.api.do_request(path=path)
23
+ if response.status_code == 200:
24
+ result = response.json()
25
+ if use_types:
26
+ return [Repo(repo) for repo in result]
27
+ return result
28
+
29
+ log.error(f"Error listing repositories: {response.status_code}")
30
+ log.error(response.text)
31
+ return []