-
Notifications
You must be signed in to change notification settings - Fork 0
/
pylynk.py
388 lines (314 loc) · 12 KB
/
pylynk.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
# Copyright 2023 Interlynk.io
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import sys
import json
import argparse
import logging
import datetime
import pytz
import time
from lynkctx import LynkContext
def user_time(utc_time):
"""
Convert UTC time to local time and format it as a string.
Args:
utc_time (str): The UTC time in ISO format.
Returns:
str: The local time formatted as a string.
"""
# Parse the input UTC time
timestamp = datetime.datetime.fromisoformat(utc_time[:-1])
# Get the local timezone
local_timezone = datetime.timezone(
datetime.timedelta(seconds=-time.timezone))
# Convert the UTC time to local time
local_time = timestamp.replace(tzinfo=pytz.UTC).astimezone(local_timezone)
# Format and return the local time as a string
return local_time.strftime('%Y-%m-%d %H:%M:%S %Z')
def print_products(lynk_ctx, fmt_json):
"""
Print the products of the Lynk context.
Args:
lynk_ctx (LynkContext): The Lynk context object.
"""
products = lynk_ctx.prods()
if fmt_json:
print(json.dumps(products, indent=4))
return 0
# Calculate dynamic column widths
name_width = max(len("NAME"), max(len(prod['name'])
for prod in products))
updated_at_width = max(len("UPDATED AT"),
max(len(user_time(prod['updatedAt']))
for prod in products))
id_width = max(len("ID"), max(len(prod['id']) for prod in products))
version_width = len("VERSIONS")
header = (
f"{'NAME':<{name_width}} | "
f"{'ID':<{id_width}} | "
f"{'VERSIONS':<{version_width}} | "
f"{'UPDATED AT':<{updated_at_width}} | "
)
print(header)
# Add a horizontal line after the header
# 10 is the total length of separators and spaces
width = sum([name_width, version_width, updated_at_width, id_width]) + 10
line = "-" * width + "|"
print(line)
for prod in products:
row = (
f"{prod['name']:<{name_width}} | "
f"{prod['id']:<{id_width}} | "
f"{prod['versions']:<{version_width}} | "
f"{user_time(prod['updatedAt']):<{updated_at_width}} | "
)
print(row)
return 0
def print_versions(lynk_ctx, fmt_json):
"""
Print the versions of the Lynk context.
Args:
lynk_ctx (LynkContext): The Lynk context object.
"""
versions = lynk_ctx.versions()
if not versions:
print('No versions found')
return 0
if fmt_json:
print(json.dumps(versions, indent=4))
return 0
# Calculate dynamic column widths
id_width = max(len('ID'), max(len(sbom['id']) for sbom in versions))
version_width = max(len('VERSION'), max(
len(str(s.get('primaryComponent', {}).get('version', ''))) for s in versions))
primary_component_width = max(len('PRIMARY COMPONENT'), max(
len(str(sbom.get('primaryComponent', {}) .get('name', ''))) for sbom in versions))
updated_at_width = max(len('UPDATED AT'),
max(len(user_time(sbom['updatedAt'])) for sbom in versions))
# Format the header with dynamic column widths
header = (
f"{'ID':<{id_width}} | "
f"{'VERSION':<{version_width}} | "
f"{'PRIMARY COMPONENT':<{primary_component_width}} | "
f"{'UPDATED AT':<{updated_at_width}} |"
)
print(header)
# Add a horizontal line after the header
# 12 is the total length of separators and spaces
width = sum([id_width, version_width,
primary_component_width,
updated_at_width]) + 10
line = "-" * width + "|"
print(line)
# Format each row with dynamic column widths and a bar between elements
for sbom in versions:
if sbom.get('primaryComponent') is None:
continue
version = sbom.get('primaryComponent', {}).get('version', '')
primary_component = sbom.get('primaryComponent', {}).get('name', '')
row = (
f"{sbom['id']:<{id_width}} | "
f"{str(version):<{version_width}} | "
f"{primary_component:<{primary_component_width}} | "
f"{user_time(sbom['updatedAt']):<{updated_at_width}} |"
)
print(row)
return 0
def print_status(lynk_ctx, fmt_json):
status = lynk_ctx.status()
if status is None:
print('Failed to fetch status for the version')
return 1
if fmt_json:
json.dump(status, sys.stdout, indent=4, ensure_ascii=False)
return 0
# Calculate dynamic column widths
key_width = 20
value_width = 20
# Format the header with dynamic column widths
header = (
f"{'ACTION KEY':<{key_width}} | "
f"{'STATUS':<{value_width}}"
)
print(header)
# Add a horizontal line after the header
# 12 is the total length of separators and spaces
width = key_width + value_width + 5
line = "-" * width + "|"
print(line)
# Format each row with dynamic column widths and a bar between elements
for key, value in status.items():
row = (
f"{key:<{key_width}} | "
f"{value:<{value_width}} |"
)
print(row)
def download_sbom(lynk_ctx):
"""
Download SBOM from the lynk_ctx and save it to a file or print it to stdout.
Args:
lynk_ctx: The lynk context object.
Returns:
int: 0 if successful, 1 if failed to fetch SBOM.
"""
sbom = lynk_ctx.download()
if sbom is None:
print('Failed to fetch SBOM')
return 1
sbom_data = json.loads(sbom.encode('utf-8'))
if lynk_ctx.output_file:
with open(lynk_ctx.output_file, 'w', encoding='utf-8') as f:
json.dump(sbom_data, f, indent=4, ensure_ascii=False)
else:
json.dump(sbom_data, sys.stdout, indent=4, ensure_ascii=False)
return 0
def upload_sbom(lynk_ctx, sbom_file):
"""
Upload SBOM to the lynk_ctx.
Args:
lynk_ctx: The lynk context object.
sbom_file: The path to the SBOM file.
Returns:
The result of the upload operation.
"""
return lynk_ctx.upload(sbom_file)
def add_output_format_group(parser):
"""
Adds mutually exclusive output format arguments (--json and --table) to the parser.
"""
output_group = parser.add_mutually_exclusive_group()
output_group.add_argument(
"--json", action='store_true', help="JSON Formatted (default)")
output_group.add_argument(
"--table", action='store_true', help="Table Formatted")
def setup_args():
"""
Set up command line arguments for the script.
"""
parser = argparse.ArgumentParser(description='Interlynk command line tool')
parser.add_argument('--verbose', '-v', action='count', default=0)
subparsers = parser.add_subparsers(title="subcommands", dest="subcommand")
products_parser = subparsers.add_parser("prods", help="List products")
products_parser.add_argument("--token",
required=False,
help="Security token")
add_output_format_group(products_parser)
vers_parser = subparsers.add_parser("vers", help="List Versions")
vers_group = vers_parser.add_mutually_exclusive_group(required=True)
vers_group.add_argument("--prod", help="Product name")
vers_group.add_argument("--prodId", help="Product ID")
vers_parser.add_argument("--env", help="Environment", required=False)
vers_parser.add_argument("--token",
required=False,
help="Security token")
add_output_format_group(vers_parser)
status_parser = subparsers.add_parser("status", help="SBOM Status")
status_group = status_parser.add_mutually_exclusive_group(required=True)
status_group.add_argument("--prod", help="Product name")
status_group.add_argument("--prodId", help="Product ID")
status_group = status_parser.add_mutually_exclusive_group(required=True)
status_group.add_argument("--ver", help="Version")
status_group.add_argument("--verId", help="Version ID")
status_parser.add_argument("--env", help="Environment", required=False)
status_parser.add_argument("--token",
required=False,
help="Security token")
add_output_format_group(status_parser)
upload_parser = subparsers.add_parser("upload", help="Upload SBOM")
upload_group = upload_parser.add_mutually_exclusive_group(required=True)
upload_group.add_argument("--prod", help="Product name")
upload_group.add_argument("--prodId", help="Product ID")
upload_parser.add_argument("--env", help="Environment", required=False)
upload_parser.add_argument("--sbom", required=True, help="SBOM path")
upload_parser.add_argument("--token",
required=False,
help="Security token")
download_parser = subparsers.add_parser("download", help="Download SBOM")
download_group = download_parser.add_mutually_exclusive_group(
required=True)
download_group.add_argument("--prod", help="Product name")
download_group.add_argument("--prodId", help="Product ID")
download_group = download_parser.add_mutually_exclusive_group(
required=True)
download_group.add_argument("--ver", help="Version")
download_group.add_argument("--verId", help="Version ID")
download_parser.add_argument("--env", help="Environment", required=False)
download_parser.add_argument("--token",
required=False,
help="Security token")
download_parser.add_argument(
"--output", help="Output file", required=False)
args = parser.parse_args()
return args
def setup_log_level(args):
"""
Set up the log level based on the command line arguments.
Args:
args: The command line arguments.
Returns:
None.
"""
if args.verbose == 0:
logging.basicConfig(level=logging.ERROR)
logging.basicConfig(level=logging.DEBUG)
def setup_lynk_context(args):
"""
Set up the LynkContext object based on the command line arguments.
Args:
args: The command line arguments.
Returns:
LynkContext: The LynkContext object.
"""
return LynkContext(
os.environ.get('INTERLYNK_API_URL'),
getattr(args, 'token', None) or os.environ.get(
'INTERLYNK_SECURITY_TOKEN'),
getattr(args, 'prodId', None),
getattr(args, 'prod', None),
getattr(args, 'envId', None),
getattr(args, 'env', None),
getattr(args, 'verId', None),
getattr(args, 'ver', None),
getattr(args, 'output', None)
)
def main() -> int:
"""
Main function that serves as the entry point of the program.
Returns:
int: The exit code of the program.
"""
args = setup_args()
setup_log_level(args)
lynk_ctx = setup_lynk_context(args)
if not lynk_ctx.validate():
exit(1)
fmt_json = not getattr(args, 'table', False)
if args.subcommand == "prods":
print_products(lynk_ctx, fmt_json)
elif args.subcommand == "vers":
print_versions(lynk_ctx, fmt_json)
elif args.subcommand == "status":
print_status(lynk_ctx, fmt_json)
elif args.subcommand == "upload":
upload_sbom(lynk_ctx, args.sbom)
elif args.subcommand == "download":
download_sbom(lynk_ctx)
else:
print("Missing or invalid command. \
Supported commands: {prods, upload, download, sign, verify}")
exit(1)
exit(0)
if __name__ == "__main__":
main()