-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1582 lines (1332 loc) · 58.2 KB
/
app.py
File metadata and controls
1582 lines (1332 loc) · 58.2 KB
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Centralized Artifact Repository Manager
A comprehensive single source of truth for all internal and third-party:
- Binaries and executables
- Software components and libraries
- Packages (Docker, APT, NPM, Python, etc.)
- AI/ML models and datasets
- Development tools and artifacts
"""
import os
import json
import hashlib
import mimetypes
import uuid
from datetime import datetime, timedelta, timezone
from typing import Dict, List, Optional, Any
from pathlib import Path
import tempfile
import shutil
import subprocess
try:
import magic
except ImportError:
magic = None
import yaml
from sqlalchemy import or_
from flask import Flask, request, jsonify, send_file, render_template, abort, make_response
from flask_sqlalchemy import SQLAlchemy
from flask_jwt_extended import JWTManager, create_access_token, jwt_required, get_jwt_identity
from flask_cors import CORS
from werkzeug.security import generate_password_hash, check_password_hash
from werkzeug.utils import secure_filename
from werkzeug.middleware.proxy_fix import ProxyFix
from sqlalchemy import desc, func, and_, or_
import uuid
from dotenv import load_dotenv
import logging
# Load environment variables
load_dotenv()
# Initialize Flask app
app = Flask(__name__)
# Configure for reverse proxy (Cloudflare Tunnel)
app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1)
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'dev-key-change-in-production')
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URL', 'sqlite:///artifact_registry.db')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['JWT_SECRET_KEY'] = os.getenv('JWT_SECRET_KEY', 'jwt-secret-change-in-production')
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = timedelta(hours=24)
app.config['UPLOAD_FOLDER'] = os.getenv('UPLOAD_FOLDER', './storage')
app.config['STORAGE_PATH'] = os.getenv('STORAGE_PATH', './storage')
app.config['EXTERNAL_URL'] = os.getenv('EXTERNAL_URL', 'http://localhost:5001')
app.config['MAX_CONTENT_LENGTH'] = 50 * 1024 * 1024 * 1024 # 50GB max file size
# Initialize extensions
db = SQLAlchemy(app)
jwt = JWTManager(app)
CORS(app)
# JWT Error Handlers
@jwt.expired_token_loader
def expired_token_callback(jwt_header, jwt_payload):
print(f"DEBUG JWT: Expired token - header: {jwt_header}, payload: {jwt_payload}")
return jsonify({'error': 'Token has expired'}), 401
@jwt.invalid_token_loader
def invalid_token_callback(error):
print(f"DEBUG JWT: Invalid token - error: {error}")
return jsonify({'error': f'Invalid token: {error}'}), 401
@jwt.unauthorized_loader
def missing_token_callback(error):
print(f"DEBUG JWT: Missing token - error: {error}")
return jsonify({'error': f'Authorization token required: {error}'}), 401
@jwt.needs_fresh_token_loader
def token_not_fresh_callback(jwt_header, jwt_payload):
print(f"DEBUG JWT: Token not fresh - header: {jwt_header}, payload: {jwt_payload}")
return jsonify({'error': 'Fresh token required'}), 401
@jwt.revoked_token_loader
def revoked_token_callback(jwt_header, jwt_payload):
print(f"DEBUG JWT: Revoked token - header: {jwt_header}, payload: {jwt_payload}")
return jsonify({'error': 'Token has been revoked'}), 401
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Ensure upload directory exists
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
# Supported artifact types with their configurations
ARTIFACT_TYPES = {
'docker': {
'name': 'Docker Images',
'extensions': ['.tar', '.tar.gz', '.tar.xz'],
'mime_types': ['application/x-tar', 'application/gzip'],
'storage_path': 'docker',
'api_prefix': '/v2'
},
'apt': {
'name': 'APT Packages',
'extensions': ['.deb'],
'mime_types': ['application/x-debian-package'],
'storage_path': 'apt',
'api_prefix': '/apt'
},
'npm': {
'name': 'NPM Packages',
'extensions': ['.tgz', '.tar.gz'],
'mime_types': ['application/gzip'],
'storage_path': 'npm',
'api_prefix': '/npm'
},
'python': {
'name': 'Python Packages',
'extensions': ['.whl', '.tar.gz', '.zip'],
'mime_types': ['application/zip', 'application/gzip'],
'storage_path': 'python',
'api_prefix': '/pypi'
},
'maven': {
'name': 'Maven Artifacts',
'extensions': ['.jar', '.war', '.ear', '.pom'],
'mime_types': ['application/java-archive', 'application/xml'],
'storage_path': 'maven',
'api_prefix': '/maven'
},
'nuget': {
'name': 'NuGet Packages',
'extensions': ['.nupkg'],
'mime_types': ['application/zip'],
'storage_path': 'nuget',
'api_prefix': '/nuget'
},
'helm': {
'name': 'Helm Charts',
'extensions': ['.tgz'],
'mime_types': ['application/gzip'],
'storage_path': 'helm',
'api_prefix': '/helm'
},
'generic': {
'name': 'Generic Binaries',
'extensions': ['.bin', '.exe', '.dmg', '.msi', '.appimage'],
'mime_types': ['application/octet-stream', 'application/x-executable'],
'storage_path': 'generic',
'api_prefix': '/generic'
},
'ai-model': {
'name': 'AI/ML Models',
'extensions': ['.pkl', '.h5', '.pb', '.onnx', '.pt', '.pth', '.safetensors'],
'mime_types': ['application/octet-stream'],
'storage_path': 'models',
'api_prefix': '/models'
},
'dataset': {
'name': 'Datasets',
'extensions': ['.csv', '.json', '.parquet', '.h5', '.zarr'],
'mime_types': ['text/csv', 'application/json', 'application/octet-stream'],
'storage_path': 'datasets',
'api_prefix': '/datasets'
},
'firmware': {
'name': 'Firmware & BIOS',
'extensions': ['.bin', '.hex', '.fw', '.rom'],
'mime_types': ['application/octet-stream'],
'storage_path': 'firmware',
'api_prefix': '/firmware'
},
'documentation': {
'name': 'Documentation',
'extensions': ['.pdf', '.md', '.html', '.zip'],
'mime_types': ['application/pdf', 'text/markdown', 'text/html', 'application/zip'],
'storage_path': 'docs',
'api_prefix': '/docs'
}
}
# Database Models
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)
password_hash = db.Column(db.String(255), nullable=False)
role = db.Column(db.String(20), default='user') # admin, user, readonly
is_active = db.Column(db.Boolean, default=True)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
last_login = db.Column(db.DateTime)
# Relationships
artifacts = db.relationship('Artifact', backref='owner', lazy=True)
downloads = db.relationship('Download', backref='user', lazy=True)
def check_password(self, password):
"""Check if the provided password matches the user's password hash"""
return check_password_hash(self.password_hash, password)
def set_password(self, password):
"""Set the user's password hash"""
self.password_hash = generate_password_hash(password)
class Organization(db.Model):
__tablename__ = 'organizations'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), unique=True, nullable=False)
display_name = db.Column(db.String(200))
description = db.Column(db.Text)
is_public = db.Column(db.Boolean, default=False)
created_by = db.Column(db.String(100), nullable=False) # Username who created the org
created_at = db.Column(db.DateTime, default=datetime.utcnow)
# Relationships
repositories = db.relationship('Repository', backref='organization', lazy=True)
class Repository(db.Model):
__tablename__ = 'repositories'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
display_name = db.Column(db.String(200))
description = db.Column(db.Text)
artifact_type = db.Column(db.String(50), nullable=False)
is_public = db.Column(db.Boolean, default=False)
org_id = db.Column(db.Integer, db.ForeignKey('organizations.id'))
created_at = db.Column(db.DateTime, default=datetime.utcnow)
# Relationships
artifacts = db.relationship('Artifact', backref='repository', lazy=True)
@property
def package_type(self):
"""Alias for artifact_type to maintain compatibility"""
return self.artifact_type
__table_args__ = (db.UniqueConstraint('name', 'org_id', name='_repo_org_uc'),)
class Artifact(db.Model):
__tablename__ = 'artifacts'
id = db.Column(db.Integer, primary_key=True)
uuid = db.Column(db.String(36), unique=True, default=lambda: str(uuid.uuid4()))
name = db.Column(db.String(200), nullable=False)
version = db.Column(db.String(100), nullable=False)
artifact_type = db.Column(db.String(50), nullable=False)
description = db.Column(db.Text)
tags = db.Column(db.JSON)
labels = db.Column(db.JSON)
# File information
filename = db.Column(db.String(255), nullable=False)
file_path = db.Column(db.String(500), nullable=False)
file_size = db.Column(db.BigInteger, nullable=False)
file_hash_sha256 = db.Column(db.String(64), nullable=False)
file_hash_md5 = db.Column(db.String(32))
mime_type = db.Column(db.String(100))
# Metadata
artifact_metadata = db.Column(db.JSON)
scan_results = db.Column(db.JSON)
vulnerability_scan = db.Column(db.JSON)
# Relationships
owner_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
repo_id = db.Column(db.Integer, db.ForeignKey('repositories.id'))
# Timestamps
created_at = db.Column(db.DateTime, default=datetime.utcnow)
updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
last_accessed = db.Column(db.DateTime)
# Relationships
downloads = db.relationship('Download', backref='artifact', lazy=True)
dependencies = db.relationship('ArtifactDependency',
foreign_keys='ArtifactDependency.artifact_id',
backref='artifact', lazy=True)
__table_args__ = (db.UniqueConstraint('name', 'version', 'repo_id', name='_artifact_version_uc'),)
class ArtifactDependency(db.Model):
__tablename__ = 'artifact_dependencies'
id = db.Column(db.Integer, primary_key=True)
artifact_id = db.Column(db.Integer, db.ForeignKey('artifacts.id'), nullable=False)
dependency_id = db.Column(db.Integer, db.ForeignKey('artifacts.id'))
dependency_name = db.Column(db.String(200))
dependency_version = db.Column(db.String(100))
dependency_type = db.Column(db.String(50))
is_required = db.Column(db.Boolean, default=True)
class Download(db.Model):
__tablename__ = 'downloads'
id = db.Column(db.Integer, primary_key=True)
artifact_id = db.Column(db.Integer, db.ForeignKey('artifacts.id'), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'))
ip_address = db.Column(db.String(45))
user_agent = db.Column(db.String(500))
downloaded_at = db.Column(db.DateTime, default=datetime.utcnow)
class ApiKey(db.Model):
__tablename__ = 'api_keys'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String(100), nullable=False)
key_hash = db.Column(db.String(255), nullable=False)
user_id = db.Column(db.Integer, db.ForeignKey('users.id'), nullable=False)
permissions = db.Column(db.JSON)
is_active = db.Column(db.Boolean, default=True)
expires_at = db.Column(db.DateTime)
created_at = db.Column(db.DateTime, default=datetime.utcnow)
last_used = db.Column(db.DateTime)
# Utility functions
def calculate_file_hash(file_path: str, algorithm: str = 'sha256') -> str:
"""Calculate file hash using specified algorithm."""
hash_obj = hashlib.new(algorithm)
with open(file_path, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_obj.update(chunk)
return hash_obj.hexdigest()
def detect_file_type(file_path: str) -> str:
"""Detect file type using python-magic if available."""
if magic:
try:
return magic.from_file(file_path, mime=True)
except:
pass
return mimetypes.guess_type(file_path)[0] or 'application/octet-stream'
def validate_artifact_type(artifact_type: str) -> bool:
"""Validate if artifact type is supported."""
return artifact_type in ARTIFACT_TYPES
def get_storage_path(artifact_type: str, org_name: str, repo_name: str, artifact_name: str) -> str:
"""Generate storage path for artifact."""
base_path = ARTIFACT_TYPES[artifact_type]['storage_path']
return os.path.join(app.config['UPLOAD_FOLDER'], base_path, org_name, repo_name, artifact_name)
# Authentication helpers
def authenticate_user(username: str, password: str) -> Optional[User]:
"""Authenticate user with username and password."""
user = User.query.filter_by(username=username, is_active=True).first()
if user and check_password_hash(user.password_hash, password):
user.last_login = datetime.now(timezone.utc)
db.session.commit()
return user
return None
# Routes
@app.route('/')
def index():
"""Main dashboard page."""
return render_template('index.html')
@app.route('/api/health')
def health_check():
"""Health check endpoint."""
return jsonify({
'status': 'healthy',
'timestamp': datetime.utcnow().isoformat(),
'version': '1.0.0'
})
@app.route('/api/info')
def system_info():
"""System information endpoint."""
return jsonify({
'name': 'Centralized Artifact Repository Manager',
'version': '1.0.0',
'supported_types': list(ARTIFACT_TYPES.keys()),
'artifact_types': {
k: {'name': v['name'], 'api_prefix': v['api_prefix']}
for k, v in ARTIFACT_TYPES.items()
}
})
# Authentication endpoints
@app.route('/api/auth/login', methods=['POST'])
def login():
"""User login endpoint."""
data = request.get_json()
username = data.get('username')
password = data.get('password')
if not username or not password:
return jsonify({'error': 'Username and password required'}), 400
user = authenticate_user(username, password)
if not user:
return jsonify({'error': 'Invalid credentials'}), 401
access_token = create_access_token(identity=user.username)
return jsonify({
'access_token': access_token,
'user': {
'id': user.id,
'username': user.username,
'email': user.email,
'role': user.role
}
})
@app.route('/api/auth/register', methods=['POST'])
def register():
"""User registration endpoint."""
data = request.get_json()
username = data.get('username')
email = data.get('email')
password = data.get('password')
if not all([username, email, password]):
return jsonify({'error': 'Username, email, and password required'}), 400
if User.query.filter_by(username=username).first():
return jsonify({'error': 'Username already exists'}), 409
if User.query.filter_by(email=email).first():
return jsonify({'error': 'Email already exists'}), 409
user = User(
username=username,
email=email,
password_hash=generate_password_hash(password)
)
db.session.add(user)
db.session.commit()
return jsonify({'message': 'User created successfully'}), 201
@app.route('/api/users/me')
@jwt_required()
def get_current_user():
"""Get current user information."""
user_id = get_jwt_identity()
user = User.query.get(user_id)
return jsonify({
'id': user.id,
'username': user.username,
'email': user.email,
'role': user.role,
'created_at': user.created_at.isoformat(),
'last_login': user.last_login.isoformat() if user.last_login else None
})
# Organization endpoints
@app.route('/api/organizations', methods=['GET'])
def get_organizations():
"""Get all organizations - public endpoint."""
organizations = Organization.query.all()
return jsonify([{
'id': org.id,
'name': org.name,
'description': org.description,
'created_at': org.created_at.isoformat()
} for org in organizations])
@app.route('/api/organizations', methods=['POST'])
@jwt_required()
def create_organization():
"""Create a new organization."""
current_user = get_jwt_identity()
data = request.get_json()
if not data or not data.get('name'):
return jsonify({'error': 'Organization name is required'}), 400
# Check if organization already exists
existing_org = Organization.query.filter_by(name=data['name']).first()
if existing_org:
return jsonify({'error': 'Organization already exists'}), 409
# Handle visibility - convert from 'public'/'private' to boolean
is_public = data.get('visibility', 'private') == 'public'
try:
organization = Organization(
name=data['name'],
description=data.get('description', ''),
is_public=is_public,
created_by=current_user
)
db.session.add(organization)
db.session.commit()
return jsonify({
'id': organization.id,
'name': organization.name,
'description': organization.description,
'is_public': organization.is_public,
'created_by': organization.created_by,
'created_at': organization.created_at.isoformat()
}), 201
except Exception as e:
db.session.rollback()
return jsonify({'error': f'Database error: {str(e)}'}), 422
@app.route('/api/organizations/<org_name>/repositories', methods=['GET'])
def get_repositories(org_name):
"""Get repositories for an organization."""
organization = Organization.query.filter_by(name=org_name).first()
if not organization:
return jsonify({'error': 'Organization not found'}), 404
repositories = Repository.query.filter_by(org_id=organization.id).all()
return jsonify([{
'id': repo.id,
'name': repo.name,
'description': repo.description,
'package_type': repo.artifact_type,
'visibility': 'public' if repo.is_public else 'private',
'created_at': repo.created_at.isoformat()
} for repo in repositories])
@app.route('/api/organizations/<org_name>/repositories', methods=['POST'])
@jwt_required()
def create_repository(org_name):
"""Create a new repository in an organization."""
try:
current_user = get_jwt_identity()
print(f"DEBUG REPO: JWT identity retrieved successfully: {current_user}")
except Exception as e:
print(f"DEBUG REPO: Error getting JWT identity: {str(e)}")
return jsonify({'error': f'JWT error: {str(e)}'}), 401
data = request.get_json()
print(f"DEBUG REPO: Create repository data: {data}")
print(f"DEBUG REPO: Current user: {current_user}")
print(f"DEBUG REPO: Organization name: {org_name}")
if not data or not data.get('name') or not data.get('package_type'):
print("DEBUG REPO: Missing repository name or package_type")
return jsonify({'error': 'Repository name and package type are required'}), 400
# Find organization
organization = Organization.query.filter_by(name=org_name).first()
if not organization:
print(f"DEBUG REPO: Organization {org_name} not found")
return jsonify({'error': 'Organization not found'}), 404
# Check if repository already exists
existing_repo = Repository.query.filter_by(name=data['name'], org_id=organization.id).first()
if existing_repo:
print(f"DEBUG REPO: Repository {data['name']} already exists in {org_name}")
return jsonify({'error': 'Repository already exists in this organization'}), 409
try:
repository = Repository(
name=data['name'],
display_name=data.get('display_name', data['name']),
description=data.get('description', ''),
artifact_type=data['package_type'],
org_id=organization.id,
is_public=data.get('visibility', 'private') == 'public'
)
db.session.add(repository)
db.session.commit()
print(f"DEBUG REPO: Repository {data['name']} created successfully")
return jsonify({
'id': repository.id,
'name': repository.name,
'description': repository.description,
'package_type': repository.artifact_type,
'visibility': 'public' if repository.is_public else 'private',
'created_at': repository.created_at.isoformat()
}), 201
except Exception as e:
print(f"DEBUG REPO: Error creating repository: {str(e)}")
db.session.rollback()
return jsonify({'error': f'Database error: {str(e)}'}), 422
# Search endpoint
@app.route('/api/search', methods=['GET'])
def search():
"""Search for artifacts, organizations, or repositories."""
query = request.args.get('q', '')
search_type = request.args.get('type', 'all')
limit = min(int(request.args.get('limit', 50)), 100)
results = {'results': []}
if search_type in ['all', 'artifact']:
artifacts = Artifact.query
if query:
artifacts = artifacts.filter(Artifact.name.contains(query))
artifacts = artifacts.limit(limit).all()
results['results'].extend([{
'type': 'artifact',
'id': artifact.id,
'name': artifact.name,
'version': artifact.version,
'package_type': artifact.package_type,
'size': artifact.file_size,
'created_at': artifact.created_at.isoformat()
} for artifact in artifacts])
if search_type in ['all', 'organization']:
organizations = Organization.query
if query:
organizations = organizations.filter(Organization.name.contains(query))
organizations = organizations.limit(limit).all()
results['results'].extend([{
'type': 'organization',
'id': org.id,
'name': org.name,
'description': org.description,
'created_at': org.created_at.isoformat()
} for org in organizations])
return jsonify(results)
# Statistics and analytics
@app.route('/api/stats')
def statistics():
"""Get repository statistics - public endpoint with basic stats."""
stats = {
'total_artifacts': Artifact.query.count(),
'total_organizations': Organization.query.count(),
'total_repositories': Repository.query.count(),
'total_downloads': Download.query.count(),
'storage_usage': 0,
'artifact_types': {},
'recent_uploads': [],
'top_artifacts': []
}
# Calculate storage usage
storage_usage = db.session.query(func.sum(Artifact.file_size)).scalar() or 0
stats['storage_usage'] = storage_usage
# Artifact types breakdown
type_counts = db.session.query(
Artifact.artifact_type,
func.count(Artifact.id)
).group_by(Artifact.artifact_type).all()
stats['artifact_types'] = {
artifact_type: {
'count': count,
'name': ARTIFACT_TYPES.get(artifact_type, {}).get('name', artifact_type)
}
for artifact_type, count in type_counts
}
# Recent uploads
recent = Artifact.query.order_by(desc(Artifact.created_at)).limit(10).all()
stats['recent_uploads'] = [{
'uuid': artifact.uuid,
'name': artifact.name,
'version': artifact.version,
'type': artifact.artifact_type,
'created_at': artifact.created_at.isoformat(),
'owner': artifact.owner.username
} for artifact in recent]
return jsonify(stats)
# Error handlers
@app.errorhandler(404)
def not_found(error):
return jsonify({'error': 'Not found'}), 404
@app.errorhandler(500)
def internal_error(error):
db.session.rollback()
return jsonify({'error': 'Internal server error'}), 500
@app.route('/test')
def test_repo_creation():
"""Test page for repository creation debugging."""
return render_template('test_repo_creation.html')
# Docker Registry HTTP API V2 Implementation
# https://docs.docker.com/registry/spec/api/
@app.route('/v2/')
def docker_registry_version_check():
"""Docker Registry API version check endpoint"""
# Check if authentication is provided
auth_header = request.headers.get('Authorization')
if not auth_header:
# Determine the correct realm URL (handle HTTPS proxies)
external_url = os.getenv('EXTERNAL_URL')
if external_url:
realm_url = f"{external_url}/v2/auth"
else:
# Fallback to request-based URL construction
scheme = 'https' if request.headers.get('X-Forwarded-Proto') == 'https' or request.is_secure else 'http'
host = request.headers.get('X-Forwarded-Host') or request.headers.get('Host') or request.host
realm_url = f"{scheme}://{host}/v2/auth"
# Return challenge for authentication
response = make_response('', 401)
response.headers['WWW-Authenticate'] = f'Bearer realm="{realm_url}",service="registry"'
response.headers['Docker-Distribution-API-Version'] = 'registry/2.0'
return response
response = make_response('', 200)
response.headers['Docker-Distribution-API-Version'] = 'registry/2.0'
return response
@app.route('/v2/<path:name>/manifests/<reference>', methods=['GET'])
@jwt_required()
def get_manifest(name, reference):
"""Get image manifest"""
try:
# Parse org/repo from name
parts = name.split('/')
if len(parts) < 2:
return jsonify({'error': 'Invalid repository name'}), 400
org_name = parts[0]
repo_name = '/'.join(parts[1:])
# Find the repository
repo = Repository.query.join(Organization).filter(
Organization.name == org_name,
Repository.name == repo_name,
Repository.artifact_type == 'docker'
).first()
if not repo:
return jsonify({'error': 'Repository not found'}), 404
# Find the artifact (manifest)
# Handle both tag/name references and digest references
if reference.startswith('sha256:'):
# Reference is a digest, search by file hash
digest_hash = reference.replace('sha256:', '')
artifact = Artifact.query.filter(
Artifact.repo_id == repo.id,
Artifact.file_hash_sha256 == digest_hash
).first()
else:
# Reference is a tag or name
artifact = Artifact.query.filter(
Artifact.repo_id == repo.id,
or_(Artifact.version == reference, Artifact.name == reference)
).first()
if not artifact:
return jsonify({'error': 'Manifest not found'}), 404
# Return the manifest
manifest_path = os.path.join(app.config['STORAGE_PATH'], artifact.file_path)
if os.path.exists(manifest_path):
with open(manifest_path, 'r') as f:
manifest_content = f.read()
response = make_response(manifest_content)
response.headers['Content-Type'] = 'application/vnd.docker.distribution.manifest.v2+json'
response.headers['Docker-Content-Digest'] = f"sha256:{artifact.file_hash_sha256}"
return response
return jsonify({'error': 'Manifest file not found'}), 404
except Exception as e:
logger.error(f"Error getting manifest: {e}")
return jsonify({'error': 'Internal server error'}), 500
@app.route('/v2/<path:name>/manifests/<reference>', methods=['PUT'])
@jwt_required()
def put_manifest(name, reference):
"""Upload image manifest"""
try:
# Parse org/repo from name
parts = name.split('/')
if len(parts) < 2:
return jsonify({'error': 'Invalid repository name'}), 400
org_name = parts[0]
repo_name = '/'.join(parts[1:])
# Find the repository
repo = Repository.query.join(Organization).filter(
Organization.name == org_name,
Repository.name == repo_name,
Repository.artifact_type == 'docker'
).first()
if not repo:
return jsonify({'error': 'Repository not found'}), 404
# Get manifest content
manifest_content = request.get_data()
if not manifest_content:
return jsonify({'error': 'Empty manifest'}), 400
# Calculate checksum
checksum = hashlib.sha256(manifest_content).hexdigest()
# Save manifest
manifest_dir = os.path.join(app.config['STORAGE_PATH'], 'docker', org_name, repo_name, 'manifests')
os.makedirs(manifest_dir, exist_ok=True)
manifest_path = os.path.join(manifest_dir, f"{reference}.json")
with open(manifest_path, 'wb') as f:
f.write(manifest_content)
# Create or update artifact record
artifact = Artifact.query.filter(
Artifact.repo_id == repo.id,
Artifact.version == reference
).first()
if not artifact:
artifact = Artifact(
repo_id=repo.id,
name=f"{repo_name}",
version=reference,
filename=f"{reference}.manifest",
file_path=os.path.relpath(manifest_path, app.config['STORAGE_PATH']),
file_size=len(manifest_content),
file_hash_sha256=checksum,
mime_type='application/vnd.docker.distribution.manifest.v2+json',
artifact_type='docker',
owner_id=1 # Assuming admin user has ID 1
)
db.session.add(artifact)
else:
artifact.file_path = os.path.relpath(manifest_path, app.config['STORAGE_PATH'])
artifact.file_size = len(manifest_content)
artifact.file_hash_sha256 = checksum
artifact.updated_at = datetime.utcnow()
db.session.commit()
response = make_response('', 201)
response.headers['Location'] = f"/v2/{name}/manifests/{reference}"
response.headers['Docker-Content-Digest'] = f"sha256:{checksum}"
return response
except Exception as e:
logger.error(f"Error uploading manifest: {e}")
return jsonify({'error': 'Internal server error'}), 500
@app.route('/v2/<path:name>/blobs/<digest>', methods=['GET', 'HEAD'])
@jwt_required()
def get_blob(name, digest):
"""Get image blob (layer) or check if it exists"""
try:
# Parse org/repo from name
parts = name.split('/')
if len(parts) < 2:
return jsonify({'error': 'Invalid repository name'}), 400
org_name = parts[0]
repo_name = '/'.join(parts[1:])
# Find blob file (stored with : replaced by _)
safe_digest = digest.replace(':', '_')
blob_path = os.path.join(app.config['STORAGE_PATH'], 'docker', org_name, repo_name, 'blobs', safe_digest)
if os.path.exists(blob_path):
if request.method == 'HEAD':
# Return headers only for HEAD request
file_size = os.path.getsize(blob_path)
response = make_response('', 200)
response.headers['Docker-Content-Digest'] = digest
response.headers['Content-Length'] = str(file_size)
response.headers['Content-Type'] = 'application/octet-stream'
return response
else:
# Return file content for GET request
return send_file(blob_path, as_attachment=True)
return jsonify({'error': 'Blob not found'}), 404
except Exception as e:
logger.error(f"Error getting blob: {e}")
return jsonify({'error': 'Internal server error'}), 500
@app.route('/v2/<path:name>/blobs/uploads/', methods=['POST'])
@jwt_required()
def initiate_blob_upload(name):
"""Initiate blob upload"""
try:
# Parse org/repo from name
parts = name.split('/')
if len(parts) < 2:
return jsonify({'error': 'Invalid repository name'}), 400
org_name = parts[0]
repo_name = '/'.join(parts[1:])
print(f"DEBUG BLOB POST: Looking for org: {org_name}, repo: {repo_name}")
# Check for blob mount request
mount_digest = request.args.get('mount')
from_repo = request.args.get('from', '')
if mount_digest:
print(f"DEBUG BLOB POST: Mount request for {mount_digest} from {from_repo}")
# TODO: Implement blob mounting - for now, fall through to regular upload
# In a full implementation, we would check if the blob exists and can be mounted
# Find or create the organization
org = Organization.query.filter(Organization.name == org_name).first()
if not org:
print(f"DEBUG BLOB POST: Creating organization: {org_name}")
current_user = get_jwt_identity()
org = Organization(
name=org_name,
display_name=org_name,
description=f"Auto-created organization for {org_name}",
created_by=current_user
)
db.session.add(org)
db.session.commit()
# Find or create the repository
repo = Repository.query.filter(
Repository.org_id == org.id,
Repository.name == repo_name,
Repository.artifact_type == 'docker'
).first()
if not repo:
print(f"DEBUG BLOB POST: Creating repository: {repo_name}")
repo = Repository(
name=repo_name,
org_id=org.id,
artifact_type='docker',
description=f"Auto-created Docker repository for {repo_name}",
is_public=True # You might want to make this configurable
)
db.session.add(repo)
db.session.commit()
print(f"DEBUG BLOB POST: Using org: {org.name}, repo: {repo.name}")
# Generate upload UUID
upload_uuid = str(uuid.uuid4())
# Create upload directory
upload_dir = os.path.join(app.config['STORAGE_PATH'], 'docker', 'uploads')
os.makedirs(upload_dir, exist_ok=True)
response = make_response('', 202)
response.headers['Location'] = f"/v2/{name}/blobs/uploads/{upload_uuid}"
response.headers['Range'] = 'bytes=0-0'
response.headers['Docker-Upload-UUID'] = upload_uuid
response.headers['Content-Length'] = '0'
print(f"DEBUG BLOB POST: Upload initiated, UUID: {upload_uuid}")
return response
except Exception as e:
logger.error(f"Error initiating blob upload: {e}")
return jsonify({'error': 'Internal server error'}), 500
@app.route('/v2/<path:name>/blobs/uploads/<upload_uuid>', methods=['PATCH'])
@jwt_required()
def upload_blob_chunk(name, upload_uuid):
"""Upload blob chunk"""
try:
# Get the uploaded chunk
chunk_data = request.get_data()
content_range = request.headers.get('Content-Range', '')
content_length = int(request.headers.get('Content-Length', 0))
print(f"DEBUG BLOB PATCH: Uploading chunk for {name}, UUID: {upload_uuid}")
print(f"DEBUG BLOB PATCH: Chunk size: {len(chunk_data)} bytes")
print(f"DEBUG BLOB PATCH: Content-Length header: {content_length}")
print(f"DEBUG BLOB PATCH: Content-Type: {request.content_type}")
print(f"DEBUG BLOB PATCH: Content-Range: {content_range}")
# Save chunk to temporary file
upload_dir = os.path.join(app.config['STORAGE_PATH'], 'docker', 'uploads')
temp_path = os.path.join(upload_dir, upload_uuid)
# Parse Content-Range header if present
start_byte = 0
if content_range:
# Content-Range: bytes start-end/total
import re
match = re.match(r'bytes (\d+)-(\d+)/(\d+|\*)', content_range)
if match:
start_byte = int(match.group(1))