Compare commits
15 Commits
feature/ad
...
fix/purge-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
01acb45320 | ||
|
|
c512d85f9e | ||
|
|
82f67539bd | ||
|
|
e93e7e7021 | ||
|
|
1d51c856b0 | ||
|
|
c92895ffe9 | ||
|
|
b147af43d2 | ||
|
|
aed48bb4a2 | ||
|
|
0e67ebf94f | ||
|
|
0a69910e8b | ||
|
|
576791d19e | ||
|
|
a5796f5437 | ||
|
|
284945ba33 | ||
|
|
fe07638485 | ||
|
|
7120cf64f1 |
217
.gitlab-ci.yml
217
.gitlab-ci.yml
@@ -11,13 +11,6 @@ variables:
|
|||||||
# Environment URLs (used by deploy and test jobs)
|
# Environment URLs (used by deploy and test jobs)
|
||||||
STAGE_URL: https://orchard-stage.common.global.bsf.tools
|
STAGE_URL: https://orchard-stage.common.global.bsf.tools
|
||||||
PROD_URL: https://orchard.common.global.bsf.tools
|
PROD_URL: https://orchard.common.global.bsf.tools
|
||||||
# Stage environment AWS resources (used by reset job)
|
|
||||||
STAGE_RDS_HOST: orchard-stage.cluster-cvw3jzjkozoc.us-gov-west-1.rds.amazonaws.com
|
|
||||||
STAGE_RDS_DBNAME: postgres
|
|
||||||
STAGE_SECRET_ARN: "arn:aws-us-gov:secretsmanager:us-gov-west-1:052673043337:secret:rds!cluster-a573672b-1a38-4665-a654-1b7df37b5297-IaeFQL"
|
|
||||||
STAGE_AUTH_SECRET_ARN: "arn:aws-us-gov:secretsmanager:us-gov-west-1:052673043337:secret:orchard-stage-creds-SMqvQx"
|
|
||||||
STAGE_S3_BUCKET: orchard-artifacts-stage
|
|
||||||
AWS_REGION: us-gov-west-1
|
|
||||||
# Shared pip cache directory
|
# Shared pip cache directory
|
||||||
PIP_CACHE_DIR: "$CI_PROJECT_DIR/.pip-cache"
|
PIP_CACHE_DIR: "$CI_PROJECT_DIR/.pip-cache"
|
||||||
|
|
||||||
@@ -95,10 +88,18 @@ cve_sbom_analysis:
|
|||||||
when: never
|
when: never
|
||||||
- when: on_success
|
- when: on_success
|
||||||
|
|
||||||
# Override release job to wait for stage integration tests before creating tag
|
# Disable prosper_setup for tag pipelines since no build/analysis jobs run
|
||||||
|
# (image is already built when commit was on main, and deploy uses helm directly)
|
||||||
|
prosper_setup:
|
||||||
|
rules:
|
||||||
|
- if: '$CI_COMMIT_TAG'
|
||||||
|
when: never
|
||||||
|
- when: on_success
|
||||||
|
|
||||||
|
# Override release job to wait for stage deployment and smoke tests before creating tag
|
||||||
# This ensures the tag (which triggers prod deploy) is only created after stage passes
|
# This ensures the tag (which triggers prod deploy) is only created after stage passes
|
||||||
release:
|
release:
|
||||||
needs: [integration_test_stage, changelog]
|
needs: [smoke_test_stage, changelog]
|
||||||
|
|
||||||
# Full integration test suite template (for feature/stage deployments)
|
# Full integration test suite template (for feature/stage deployments)
|
||||||
# Runs the complete pytest integration test suite against the deployed environment
|
# Runs the complete pytest integration test suite against the deployed environment
|
||||||
@@ -200,108 +201,6 @@ release:
|
|||||||
sys.exit(0)
|
sys.exit(0)
|
||||||
PYTEST_SCRIPT
|
PYTEST_SCRIPT
|
||||||
|
|
||||||
# Reset stage template - runs from CI runner, uses CI variable for auth
|
|
||||||
# Calls the /api/v1/admin/factory-reset endpoint which handles DB and S3 cleanup
|
|
||||||
.reset_stage_template: &reset_stage_template
|
|
||||||
stage: deploy
|
|
||||||
image: deps.global.bsf.tools/docker/python:3.12-slim
|
|
||||||
timeout: 5m
|
|
||||||
retry: 1
|
|
||||||
before_script:
|
|
||||||
- pip install --index-url "$PIP_INDEX_URL" httpx
|
|
||||||
script:
|
|
||||||
- |
|
|
||||||
python - <<'RESET_SCRIPT'
|
|
||||||
import httpx
|
|
||||||
import sys
|
|
||||||
import os
|
|
||||||
import time
|
|
||||||
|
|
||||||
BASE_URL = os.environ.get("STAGE_URL", "")
|
|
||||||
ADMIN_USER = "admin"
|
|
||||||
ADMIN_PASS = os.environ.get("STAGE_ADMIN_PASSWORD", "")
|
|
||||||
MAX_RETRIES = 3
|
|
||||||
RETRY_DELAY = 5
|
|
||||||
|
|
||||||
if not BASE_URL:
|
|
||||||
print("ERROR: STAGE_URL not set")
|
|
||||||
sys.exit(1)
|
|
||||||
|
|
||||||
if not ADMIN_PASS:
|
|
||||||
print("ERROR: STAGE_ADMIN_PASSWORD not set")
|
|
||||||
sys.exit(1)
|
|
||||||
|
|
||||||
print(f"=== Resetting stage environment at {BASE_URL} ===")
|
|
||||||
|
|
||||||
def do_reset():
|
|
||||||
with httpx.Client(base_url=BASE_URL, timeout=120.0) as client:
|
|
||||||
print("Logging in as admin...")
|
|
||||||
login_response = client.post(
|
|
||||||
"/api/v1/auth/login",
|
|
||||||
json={"username": ADMIN_USER, "password": ADMIN_PASS},
|
|
||||||
)
|
|
||||||
if login_response.status_code != 200:
|
|
||||||
raise Exception(f"Login failed: {login_response.status_code} - {login_response.text}")
|
|
||||||
print("Login successful")
|
|
||||||
|
|
||||||
print("Calling factory reset endpoint...")
|
|
||||||
reset_response = client.post(
|
|
||||||
"/api/v1/admin/factory-reset",
|
|
||||||
headers={"X-Confirm-Reset": "yes-delete-all-data"},
|
|
||||||
)
|
|
||||||
|
|
||||||
if reset_response.status_code == 200:
|
|
||||||
result = reset_response.json()
|
|
||||||
print("Factory reset successful!")
|
|
||||||
print(f" Database tables dropped: {result['results']['database_tables_dropped']}")
|
|
||||||
print(f" S3 objects deleted: {result['results']['s3_objects_deleted']}")
|
|
||||||
print(f" Database reinitialized: {result['results']['database_reinitialized']}")
|
|
||||||
print(f" Seeded: {result['results']['seeded']}")
|
|
||||||
return True
|
|
||||||
else:
|
|
||||||
raise Exception(f"Factory reset failed: {reset_response.status_code} - {reset_response.text}")
|
|
||||||
|
|
||||||
for attempt in range(1, MAX_RETRIES + 1):
|
|
||||||
try:
|
|
||||||
print(f"Attempt {attempt}/{MAX_RETRIES}")
|
|
||||||
if do_reset():
|
|
||||||
sys.exit(0)
|
|
||||||
except Exception as e:
|
|
||||||
print(f"Attempt {attempt} failed: {e}")
|
|
||||||
if attempt < MAX_RETRIES:
|
|
||||||
print(f"Retrying in {RETRY_DELAY} seconds...")
|
|
||||||
time.sleep(RETRY_DELAY)
|
|
||||||
else:
|
|
||||||
print("All retry attempts failed")
|
|
||||||
sys.exit(1)
|
|
||||||
RESET_SCRIPT
|
|
||||||
rules:
|
|
||||||
- if: '$CI_COMMIT_BRANCH == "main"'
|
|
||||||
when: on_success
|
|
||||||
|
|
||||||
# Reset stage BEFORE integration tests (ensure known state)
|
|
||||||
reset_stage_pre:
|
|
||||||
<<: *reset_stage_template
|
|
||||||
needs: [deploy_stage]
|
|
||||||
|
|
||||||
# Integration tests for stage deployment
|
|
||||||
# Uses CI variable STAGE_ADMIN_PASSWORD (set in GitLab CI/CD settings)
|
|
||||||
integration_test_stage:
|
|
||||||
<<: *integration_test_template
|
|
||||||
needs: [reset_stage_pre]
|
|
||||||
variables:
|
|
||||||
ORCHARD_TEST_URL: $STAGE_URL
|
|
||||||
ORCHARD_TEST_PASSWORD: $STAGE_ADMIN_PASSWORD
|
|
||||||
rules:
|
|
||||||
- if: '$CI_COMMIT_BRANCH == "main"'
|
|
||||||
when: on_success
|
|
||||||
|
|
||||||
# Reset stage AFTER integration tests (clean slate for next run)
|
|
||||||
reset_stage:
|
|
||||||
<<: *reset_stage_template
|
|
||||||
needs: [integration_test_stage]
|
|
||||||
allow_failure: true # Don't fail pipeline if reset has issues
|
|
||||||
|
|
||||||
# Integration tests for feature deployment (full suite)
|
# Integration tests for feature deployment (full suite)
|
||||||
# Uses DEV_ADMIN_PASSWORD CI variable (same as deploy_feature)
|
# Uses DEV_ADMIN_PASSWORD CI variable (same as deploy_feature)
|
||||||
integration_test_feature:
|
integration_test_feature:
|
||||||
@@ -412,9 +311,88 @@ frontend_tests:
|
|||||||
echo "Health check failed after 30 attempts"
|
echo "Health check failed after 30 attempts"
|
||||||
exit 1
|
exit 1
|
||||||
|
|
||||||
# Deploy to stage (main branch)
|
# Ephemeral test deployment in stage namespace (main branch only)
|
||||||
deploy_stage:
|
# Runs integration tests before promoting to long-running stage
|
||||||
|
deploy_test:
|
||||||
<<: *deploy_template
|
<<: *deploy_template
|
||||||
|
variables:
|
||||||
|
NAMESPACE: orch-stage-namespace
|
||||||
|
VALUES_FILE: helm/orchard/values-dev.yaml
|
||||||
|
BASE_URL: https://orchard-test.common.global.bsf.tools
|
||||||
|
before_script:
|
||||||
|
- kubectl config use-context esv/bsf/bsf-integration/orchard/orchard-mvp:orchard-stage
|
||||||
|
- *helm_setup
|
||||||
|
script:
|
||||||
|
- echo "Deploying ephemeral test environment"
|
||||||
|
- cd $CI_PROJECT_DIR
|
||||||
|
- |
|
||||||
|
helm upgrade --install orchard-test ./helm/orchard \
|
||||||
|
--namespace $NAMESPACE \
|
||||||
|
-f $VALUES_FILE \
|
||||||
|
--set image.tag=git.linux-amd64-$CI_COMMIT_SHA \
|
||||||
|
--set orchard.auth.adminPassword=$STAGE_ADMIN_PASSWORD \
|
||||||
|
--set ingress.hosts[0].host=orchard-test.common.global.bsf.tools \
|
||||||
|
--set ingress.tls[0].hosts[0]=orchard-test.common.global.bsf.tools \
|
||||||
|
--set ingress.tls[0].secretName=orchard-test-tls \
|
||||||
|
--set minioIngress.host=minio-test.common.global.bsf.tools \
|
||||||
|
--set minioIngress.tls.secretName=minio-test-tls \
|
||||||
|
--wait \
|
||||||
|
--atomic \
|
||||||
|
--timeout 10m
|
||||||
|
- kubectl rollout status deployment/orchard-test-server -n $NAMESPACE --timeout=10m
|
||||||
|
- *verify_deployment
|
||||||
|
environment:
|
||||||
|
name: test
|
||||||
|
url: https://orchard-test.common.global.bsf.tools
|
||||||
|
on_stop: cleanup_test
|
||||||
|
kubernetes:
|
||||||
|
agent: esv/bsf/bsf-integration/orchard/orchard-mvp:orchard-stage
|
||||||
|
rules:
|
||||||
|
- if: '$CI_COMMIT_BRANCH == "main"'
|
||||||
|
when: on_success
|
||||||
|
|
||||||
|
# Integration tests for ephemeral test deployment (main branch)
|
||||||
|
# Runs against orchard-test before promoting to long-running stage
|
||||||
|
integration_test_main:
|
||||||
|
<<: *integration_test_template
|
||||||
|
needs: [deploy_test]
|
||||||
|
variables:
|
||||||
|
ORCHARD_TEST_URL: https://orchard-test.common.global.bsf.tools
|
||||||
|
ORCHARD_TEST_PASSWORD: $STAGE_ADMIN_PASSWORD
|
||||||
|
rules:
|
||||||
|
- if: '$CI_COMMIT_BRANCH == "main"'
|
||||||
|
when: on_success
|
||||||
|
|
||||||
|
# Cleanup ephemeral test deployment after integration tests
|
||||||
|
cleanup_test:
|
||||||
|
stage: deploy
|
||||||
|
needs: [integration_test_main]
|
||||||
|
image: deps.global.bsf.tools/registry-1.docker.io/alpine/k8s:1.29.12
|
||||||
|
timeout: 5m
|
||||||
|
variables:
|
||||||
|
NAMESPACE: orch-stage-namespace
|
||||||
|
GIT_STRATEGY: none
|
||||||
|
before_script:
|
||||||
|
- kubectl config use-context esv/bsf/bsf-integration/orchard/orchard-mvp:orchard-stage
|
||||||
|
script:
|
||||||
|
- echo "Cleaning up ephemeral test deployment orchard-test"
|
||||||
|
- helm uninstall orchard-test --namespace $NAMESPACE || true
|
||||||
|
environment:
|
||||||
|
name: test
|
||||||
|
action: stop
|
||||||
|
kubernetes:
|
||||||
|
agent: esv/bsf/bsf-integration/orchard/orchard-mvp:orchard-stage
|
||||||
|
rules:
|
||||||
|
- if: '$CI_COMMIT_BRANCH == "main"'
|
||||||
|
when: on_success
|
||||||
|
allow_failure: true
|
||||||
|
|
||||||
|
# Deploy to long-running stage (main branch, after ephemeral tests pass)
|
||||||
|
deploy_stage:
|
||||||
|
stage: deploy
|
||||||
|
# Wait for ephemeral test to pass before promoting to long-running stage
|
||||||
|
needs: [cleanup_test]
|
||||||
|
image: deps.global.bsf.tools/registry-1.docker.io/alpine/k8s:1.29.12
|
||||||
variables:
|
variables:
|
||||||
NAMESPACE: orch-stage-namespace
|
NAMESPACE: orch-stage-namespace
|
||||||
VALUES_FILE: helm/orchard/values-stage.yaml
|
VALUES_FILE: helm/orchard/values-stage.yaml
|
||||||
@@ -423,13 +401,14 @@ deploy_stage:
|
|||||||
- kubectl config use-context esv/bsf/bsf-integration/orchard/orchard-mvp:orchard-stage
|
- kubectl config use-context esv/bsf/bsf-integration/orchard/orchard-mvp:orchard-stage
|
||||||
- *helm_setup
|
- *helm_setup
|
||||||
script:
|
script:
|
||||||
- echo "Deploying to stage environment"
|
- echo "Deploying to long-running stage environment"
|
||||||
- cd $CI_PROJECT_DIR
|
- cd $CI_PROJECT_DIR
|
||||||
- |
|
- |
|
||||||
helm upgrade --install orchard-stage ./helm/orchard \
|
helm upgrade --install orchard-stage ./helm/orchard \
|
||||||
--namespace $NAMESPACE \
|
--namespace $NAMESPACE \
|
||||||
-f $VALUES_FILE \
|
-f $VALUES_FILE \
|
||||||
--set image.tag=git.linux-amd64-$CI_COMMIT_SHA \
|
--set image.tag=git.linux-amd64-$CI_COMMIT_SHA \
|
||||||
|
--set orchard.auth.adminPassword=$STAGE_ADMIN_PASSWORD \
|
||||||
--wait \
|
--wait \
|
||||||
--atomic \
|
--atomic \
|
||||||
--timeout 10m
|
--timeout 10m
|
||||||
@@ -444,6 +423,16 @@ deploy_stage:
|
|||||||
- if: '$CI_COMMIT_BRANCH == "main"'
|
- if: '$CI_COMMIT_BRANCH == "main"'
|
||||||
when: on_success
|
when: on_success
|
||||||
|
|
||||||
|
# Smoke test for long-running stage (after promotion)
|
||||||
|
smoke_test_stage:
|
||||||
|
<<: *smoke_test_template
|
||||||
|
needs: [deploy_stage]
|
||||||
|
variables:
|
||||||
|
ORCHARD_TEST_URL: $STAGE_URL
|
||||||
|
rules:
|
||||||
|
- if: '$CI_COMMIT_BRANCH == "main"'
|
||||||
|
when: on_success
|
||||||
|
|
||||||
# Deploy feature branch to dev namespace
|
# Deploy feature branch to dev namespace
|
||||||
deploy_feature:
|
deploy_feature:
|
||||||
<<: *deploy_template
|
<<: *deploy_template
|
||||||
|
|||||||
147
CHANGELOG.md
147
CHANGELOG.md
@@ -6,7 +6,147 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
|||||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
### Fixed
|
||||||
|
- Fixed purge_seed_data crash when deleting access permissions - was comparing UUID to VARCHAR column (#107)
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Upstream source connectivity test no longer follows redirects, fixing "Exceeded maximum allowed redirects" error with Artifactory proxies (#107)
|
||||||
|
- Upstream sources table now has dedicated "Test" column with OK/Error status badges (#107)
|
||||||
|
- Test runs automatically after saving a new or updated upstream source (#107)
|
||||||
|
- Error states in upstream sources table are now clickable to show full error details in a modal (#107)
|
||||||
|
- Source name column no longer wraps text for better table layout (#107)
|
||||||
|
|
||||||
|
### Removed
|
||||||
|
- Removed `is_public` field from upstream sources - all sources are now treated as internal/private (#107)
|
||||||
|
- Removed `allow_public_internet` (air-gap mode) setting from cache settings - not needed for enterprise proxy use case (#107)
|
||||||
|
- Removed seeding of public registry URLs (npm-public, pypi-public, maven-central, docker-hub) (#107)
|
||||||
|
- Removed "Public" badge and checkbox from upstream sources UI (#107)
|
||||||
|
- Removed "Allow Public Internet" toggle from cache settings UI (#107)
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
- Added `ORCHARD_PURGE_SEED_DATA` environment variable support to stage helm values to remove seed data from long-running deployments (#107)
|
||||||
|
- Added frontend system projects visual distinction (#105)
|
||||||
|
- "Cache" badge for system projects in project list
|
||||||
|
- "System Cache" badge on project detail page
|
||||||
|
- Added `is_system` field to Project type
|
||||||
|
- Added frontend admin page for upstream sources and cache settings (#75)
|
||||||
|
- New `/admin/cache` page accessible from user menu (admin only)
|
||||||
|
- Upstream sources table with create/edit/delete/test connectivity
|
||||||
|
- Cache settings section with air-gap mode and auto-create system projects toggles
|
||||||
|
- Visual indicators for env-defined sources (locked, cannot be modified)
|
||||||
|
- Environment variable override badges when settings are overridden
|
||||||
|
- API client functions for all cache admin operations
|
||||||
|
- Added environment variable overrides for cache configuration (#74)
|
||||||
|
- `ORCHARD_CACHE_ALLOW_PUBLIC_INTERNET` - Override allow_public_internet (air-gap mode)
|
||||||
|
- `ORCHARD_CACHE_AUTO_CREATE_SYSTEM_PROJECTS` - Override auto_create_system_projects
|
||||||
|
- `ORCHARD_UPSTREAM__{NAME}__*` - Define upstream sources via env vars
|
||||||
|
- Env-defined sources appear in API with `source: "env"` marker
|
||||||
|
- Env-defined sources cannot be modified/deleted via API (400 error)
|
||||||
|
- Cache settings response includes `*_env_override` fields when overridden
|
||||||
|
- 7 unit tests for env var parsing and configuration
|
||||||
|
- Added Global Cache Settings Admin API (#73)
|
||||||
|
- `GET /api/v1/admin/cache-settings` - Retrieve current cache settings
|
||||||
|
- `PUT /api/v1/admin/cache-settings` - Update cache settings (partial updates)
|
||||||
|
- Admin-only access with audit logging
|
||||||
|
- Controls `allow_public_internet` (air-gap mode) and `auto_create_system_projects`
|
||||||
|
- 7 integration tests for settings management
|
||||||
|
- Added Upstream Sources Admin API for managing cache sources (#72)
|
||||||
|
- `GET /api/v1/admin/upstream-sources` - List sources with filtering
|
||||||
|
- `POST /api/v1/admin/upstream-sources` - Create source with auth configuration
|
||||||
|
- `GET /api/v1/admin/upstream-sources/{id}` - Get source details
|
||||||
|
- `PUT /api/v1/admin/upstream-sources/{id}` - Update source (partial updates)
|
||||||
|
- `DELETE /api/v1/admin/upstream-sources/{id}` - Delete source
|
||||||
|
- `POST /api/v1/admin/upstream-sources/{id}/test` - Test connectivity
|
||||||
|
- Admin-only access with audit logging
|
||||||
|
- Credentials never exposed (only has_password/has_headers flags)
|
||||||
|
- 13 integration tests for all CRUD operations
|
||||||
|
- Added system project restrictions and management (#71)
|
||||||
|
- System projects (`_npm`, `_pypi`, etc.) cannot be deleted (returns 403)
|
||||||
|
- System projects cannot be made private (must remain public)
|
||||||
|
- `GET /api/v1/system-projects` endpoint to list all system cache projects
|
||||||
|
- 5 integration tests for system project restrictions
|
||||||
|
- Added Cache API endpoint for fetching and storing artifacts from upstream URLs (#70)
|
||||||
|
- `POST /api/v1/cache` endpoint to cache artifacts from upstream registries
|
||||||
|
- URL parsing helpers to extract package name/version from npm, PyPI, Maven URLs
|
||||||
|
- Automatic system project creation (`_npm`, `_pypi`, `_maven`, etc.)
|
||||||
|
- URL-to-artifact provenance tracking via `cached_urls` table
|
||||||
|
- Optional user project cross-referencing for custom organization
|
||||||
|
- Cache hit returns existing artifact without re-fetching
|
||||||
|
- Air-gap mode enforcement (blocks public URLs when disabled)
|
||||||
|
- Hash verification for downloaded artifacts
|
||||||
|
- 21 unit tests for URL parsing and cache endpoint
|
||||||
|
- Added HTTP client for fetching artifacts from upstream sources (#69)
|
||||||
|
- `UpstreamClient` class in `backend/app/upstream.py` with streaming downloads
|
||||||
|
- SHA256 hash computation while streaming (doesn't load large files into memory)
|
||||||
|
- Auth support: none, basic auth, bearer token, API key (custom headers)
|
||||||
|
- URL-to-source matching by URL prefix with priority ordering
|
||||||
|
- Configuration options: timeouts, retries with exponential backoff, redirect limits, max file size
|
||||||
|
- Air-gap mode enforcement via `allow_public_internet` setting
|
||||||
|
- Response header capture for provenance tracking
|
||||||
|
- Proper error handling with custom exception types
|
||||||
|
- Connection test method for upstream source validation
|
||||||
|
- 33 unit tests for client functionality
|
||||||
|
- Added upstream artifact caching schema for hermetic builds (#68)
|
||||||
|
- `upstream_sources` table for configuring upstream registries (npm, PyPI, Maven, etc.)
|
||||||
|
- `cache_settings` table for global settings including air-gap mode
|
||||||
|
- `cached_urls` table for URL-to-artifact provenance tracking
|
||||||
|
- `is_system` column on projects for system cache projects (_npm, _pypi, etc.)
|
||||||
|
- Support for multiple auth types: none, basic auth, bearer token, API key
|
||||||
|
- Fernet encryption for credentials using `ORCHARD_CACHE_ENCRYPTION_KEY`
|
||||||
|
- Default upstream sources seeded (npm-public, pypi-public, maven-central, docker-hub) - disabled by default
|
||||||
|
- Migration `010_upstream_caching.sql`
|
||||||
|
- Added team-based multi-tenancy for organizing projects and collaboration (#88-#104)
|
||||||
|
- Teams serve as organizational containers for projects
|
||||||
|
- Users can belong to multiple teams with different roles (owner, admin, member)
|
||||||
|
- Projects can optionally belong to a team
|
||||||
|
- Added database schema for teams (#88):
|
||||||
|
- `teams` table with id, name, slug, description, settings, timestamps
|
||||||
|
- `team_memberships` table mapping users to teams with roles
|
||||||
|
- `team_id` column on projects table for team association
|
||||||
|
- Migrations `009_teams.sql` and `009b_migrate_projects.sql`
|
||||||
|
- Added Team and TeamMembership ORM models with relationships (#89)
|
||||||
|
- Added TeamAuthorizationService for team-level access control (#90):
|
||||||
|
- Team owner/admin gets admin access to all team projects
|
||||||
|
- Team member gets read access to team projects (upgradeable by explicit permission)
|
||||||
|
- Role hierarchy: owner > admin > member
|
||||||
|
- Added Team API endpoints (#92, #93, #94, #95):
|
||||||
|
- `GET /api/v1/teams` - List teams user belongs to (paginated)
|
||||||
|
- `POST /api/v1/teams` - Create team (creator becomes owner)
|
||||||
|
- `GET /api/v1/teams/{slug}` - Get team details
|
||||||
|
- `PUT /api/v1/teams/{slug}` - Update team (requires admin)
|
||||||
|
- `DELETE /api/v1/teams/{slug}` - Delete team (requires owner)
|
||||||
|
- `GET /api/v1/teams/{slug}/members` - List team members
|
||||||
|
- `POST /api/v1/teams/{slug}/members` - Add member (requires admin)
|
||||||
|
- `PUT /api/v1/teams/{slug}/members/{username}` - Update member role
|
||||||
|
- `DELETE /api/v1/teams/{slug}/members/{username}` - Remove member
|
||||||
|
- `GET /api/v1/teams/{slug}/projects` - List team projects (paginated)
|
||||||
|
- Updated project creation to support optional team assignment (#95)
|
||||||
|
- Updated project responses to include team info (team_id, team_slug, team_name)
|
||||||
|
- Added frontend team management (#97-#104):
|
||||||
|
- TeamContext provider for managing current team selection
|
||||||
|
- TeamSelector dropdown component (persists selection in localStorage)
|
||||||
|
- Teams list page at `/teams`
|
||||||
|
- Team dashboard page at `/teams/{slug}` with inline project creation
|
||||||
|
- Team settings page at `/teams/{slug}/settings`
|
||||||
|
- Team members page at `/teams/{slug}/members`
|
||||||
|
- Teams navigation link in header (authenticated users only)
|
||||||
|
- Updated seed data to create a "Demo Team" and assign all seed projects to it
|
||||||
|
- Added TypeScript types and API client functions for teams
|
||||||
|
- Access management now shows team-based permissions alongside explicit permissions
|
||||||
|
- Team-based access displayed as read-only with "Source" column indicating origin
|
||||||
|
- Team members with access show team slug and role
|
||||||
|
- Added integration tests for team CRUD, membership, and project operations
|
||||||
|
- Redesigned teams portal with modern card-based layout
|
||||||
|
- Card grid view with team avatar, name, slug, role badge, and stats
|
||||||
|
- Stats bar showing total teams, owned teams, and total projects
|
||||||
|
- Search functionality for filtering teams (appears when >3 teams)
|
||||||
|
- Empty states for no teams and no search results
|
||||||
|
- Added user autocomplete component for team member invitations
|
||||||
|
- `GET /api/v1/users/search` endpoint for username prefix search
|
||||||
|
- Dropdown shows matching users as you type
|
||||||
|
- Keyboard navigation support (arrow keys, enter, escape)
|
||||||
|
- Debounced search to reduce API calls
|
||||||
|
- Added unit tests for TeamAuthorizationService
|
||||||
- Added `ORCHARD_ADMIN_PASSWORD` environment variable to configure initial admin password (#87)
|
- Added `ORCHARD_ADMIN_PASSWORD` environment variable to configure initial admin password (#87)
|
||||||
- When set, admin user is created with the specified password (no password change required)
|
- When set, admin user is created with the specified password (no password change required)
|
||||||
- When not set, defaults to `changeme123` and requires password change on first login
|
- When not set, defaults to `changeme123` and requires password change on first login
|
||||||
@@ -53,6 +193,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
- Added pre-test stage reset to ensure known environment state before integration tests (#54)
|
- Added pre-test stage reset to ensure known environment state before integration tests (#54)
|
||||||
- Upload endpoint now accepts optional `ensure` file parameter for declaring dependencies
|
- Upload endpoint now accepts optional `ensure` file parameter for declaring dependencies
|
||||||
- Updated upload API documentation with ensure file format and examples
|
- Updated upload API documentation with ensure file format and examples
|
||||||
|
- Converted teams list and team projects to use DataTable component for consistent styling
|
||||||
|
- Centered team members and team settings page content
|
||||||
|
- Added orchard logo icon and dot separator to footer
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- Fixed dark theme styling for team pages - modals, forms, and dropdowns now use correct theme variables
|
||||||
|
- Fixed UserAutocomplete and TeamSelector dropdown backgrounds for dark theme
|
||||||
|
|
||||||
## [0.5.1] - 2026-01-23
|
## [0.5.1] - 2026-01-23
|
||||||
### Changed
|
### Changed
|
||||||
|
|||||||
@@ -663,9 +663,11 @@ class AuthorizationService:
|
|||||||
Checks in order:
|
Checks in order:
|
||||||
1. System admin - gets admin access to all projects
|
1. System admin - gets admin access to all projects
|
||||||
2. Project owner (created_by) - gets admin access
|
2. Project owner (created_by) - gets admin access
|
||||||
3. Explicit permission in access_permissions table
|
3. Team-based access (owner/admin gets admin, member gets read)
|
||||||
|
4. Explicit permission in access_permissions table
|
||||||
|
5. Public access
|
||||||
"""
|
"""
|
||||||
from .models import Project, AccessPermission
|
from .models import Project, AccessPermission, TeamMembership
|
||||||
|
|
||||||
# Get the project
|
# Get the project
|
||||||
project = self.db.query(Project).filter(Project.id == project_id).first()
|
project = self.db.query(Project).filter(Project.id == project_id).first()
|
||||||
@@ -684,6 +686,23 @@ class AuthorizationService:
|
|||||||
if project.created_by == user.username:
|
if project.created_by == user.username:
|
||||||
return "admin"
|
return "admin"
|
||||||
|
|
||||||
|
# Check team-based access if project belongs to a team
|
||||||
|
if project.team_id:
|
||||||
|
membership = (
|
||||||
|
self.db.query(TeamMembership)
|
||||||
|
.filter(
|
||||||
|
TeamMembership.team_id == project.team_id,
|
||||||
|
TeamMembership.user_id == user.id,
|
||||||
|
)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if membership:
|
||||||
|
# Team owner/admin gets admin on all team projects
|
||||||
|
if membership.role in ("owner", "admin"):
|
||||||
|
return "admin"
|
||||||
|
# Team member gets read access (upgradeable by explicit permission)
|
||||||
|
# Continue checking explicit permissions for potential upgrade
|
||||||
|
|
||||||
# Check explicit permissions
|
# Check explicit permissions
|
||||||
permission = (
|
permission = (
|
||||||
self.db.query(AccessPermission)
|
self.db.query(AccessPermission)
|
||||||
@@ -697,8 +716,22 @@ class AuthorizationService:
|
|||||||
if permission:
|
if permission:
|
||||||
# Check expiration
|
# Check expiration
|
||||||
if permission.expires_at and permission.expires_at < datetime.now(timezone.utc):
|
if permission.expires_at and permission.expires_at < datetime.now(timezone.utc):
|
||||||
return "read" if project.is_public else None
|
pass # Permission expired, fall through
|
||||||
return permission.level
|
else:
|
||||||
|
return permission.level
|
||||||
|
|
||||||
|
# Team member gets read access if no explicit permission
|
||||||
|
if project.team_id:
|
||||||
|
membership = (
|
||||||
|
self.db.query(TeamMembership)
|
||||||
|
.filter(
|
||||||
|
TeamMembership.team_id == project.team_id,
|
||||||
|
TeamMembership.user_id == user.id,
|
||||||
|
)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if membership:
|
||||||
|
return "read"
|
||||||
|
|
||||||
# Fall back to public access
|
# Fall back to public access
|
||||||
return "read" if project.is_public else None
|
return "read" if project.is_public else None
|
||||||
@@ -884,6 +917,226 @@ def check_project_access(
|
|||||||
return project
|
return project
|
||||||
|
|
||||||
|
|
||||||
|
# --- Team Authorization ---
|
||||||
|
|
||||||
|
# Team roles in order of increasing privilege
|
||||||
|
TEAM_ROLES = ["member", "admin", "owner"]
|
||||||
|
|
||||||
|
|
||||||
|
def get_team_role_rank(role: str) -> int:
|
||||||
|
"""Get numeric rank for team role comparison."""
|
||||||
|
try:
|
||||||
|
return TEAM_ROLES.index(role)
|
||||||
|
except ValueError:
|
||||||
|
return -1
|
||||||
|
|
||||||
|
|
||||||
|
def has_sufficient_team_role(user_role: str, required_role: str) -> bool:
|
||||||
|
"""Check if user_role is sufficient for required_role.
|
||||||
|
|
||||||
|
Role hierarchy: owner > admin > member
|
||||||
|
"""
|
||||||
|
return get_team_role_rank(user_role) >= get_team_role_rank(required_role)
|
||||||
|
|
||||||
|
|
||||||
|
class TeamAuthorizationService:
|
||||||
|
"""Service for checking team-level authorization."""
|
||||||
|
|
||||||
|
def __init__(self, db: Session):
|
||||||
|
self.db = db
|
||||||
|
|
||||||
|
def get_user_team_role(
|
||||||
|
self, team_id: str, user: Optional[User]
|
||||||
|
) -> Optional[str]:
|
||||||
|
"""Get the user's role in a team.
|
||||||
|
|
||||||
|
Returns the role ('owner', 'admin', 'member') or None if not a member.
|
||||||
|
System admins who are not team members are treated as team admins.
|
||||||
|
"""
|
||||||
|
from .models import Team, TeamMembership
|
||||||
|
|
||||||
|
if not user:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Check actual membership first
|
||||||
|
membership = (
|
||||||
|
self.db.query(TeamMembership)
|
||||||
|
.filter(
|
||||||
|
TeamMembership.team_id == team_id,
|
||||||
|
TeamMembership.user_id == user.id,
|
||||||
|
)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
|
||||||
|
if membership:
|
||||||
|
return membership.role
|
||||||
|
|
||||||
|
# System admins who are not members get admin access
|
||||||
|
if user.is_admin:
|
||||||
|
return "admin"
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
def check_team_access(
|
||||||
|
self,
|
||||||
|
team_id: str,
|
||||||
|
user: Optional[User],
|
||||||
|
required_role: str = "member",
|
||||||
|
) -> bool:
|
||||||
|
"""Check if user has required role in team.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
team_id: Team ID to check
|
||||||
|
user: User to check (None means no access)
|
||||||
|
required_role: Minimum required role ('member', 'admin', 'owner')
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True if user has sufficient role, False otherwise
|
||||||
|
"""
|
||||||
|
user_role = self.get_user_team_role(team_id, user)
|
||||||
|
if not user_role:
|
||||||
|
return False
|
||||||
|
return has_sufficient_team_role(user_role, required_role)
|
||||||
|
|
||||||
|
def can_create_project(self, team_id: str, user: Optional[User]) -> bool:
|
||||||
|
"""Check if user can create projects in team (requires admin+)."""
|
||||||
|
return self.check_team_access(team_id, user, "admin")
|
||||||
|
|
||||||
|
def can_manage_members(self, team_id: str, user: Optional[User]) -> bool:
|
||||||
|
"""Check if user can manage team members (requires admin+)."""
|
||||||
|
return self.check_team_access(team_id, user, "admin")
|
||||||
|
|
||||||
|
def can_delete_team(self, team_id: str, user: Optional[User]) -> bool:
|
||||||
|
"""Check if user can delete the team (requires owner)."""
|
||||||
|
return self.check_team_access(team_id, user, "owner")
|
||||||
|
|
||||||
|
def get_team_by_slug(self, slug: str) -> Optional["Team"]:
|
||||||
|
"""Get a team by its slug."""
|
||||||
|
from .models import Team
|
||||||
|
|
||||||
|
return self.db.query(Team).filter(Team.slug == slug).first()
|
||||||
|
|
||||||
|
def get_user_teams(self, user: User) -> list:
|
||||||
|
"""Get all teams a user is a member of."""
|
||||||
|
from .models import Team, TeamMembership
|
||||||
|
|
||||||
|
return (
|
||||||
|
self.db.query(Team)
|
||||||
|
.join(TeamMembership)
|
||||||
|
.filter(TeamMembership.user_id == user.id)
|
||||||
|
.order_by(Team.name)
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_team_authorization_service(db: Session = Depends(get_db)) -> TeamAuthorizationService:
|
||||||
|
"""Get a TeamAuthorizationService instance."""
|
||||||
|
return TeamAuthorizationService(db)
|
||||||
|
|
||||||
|
|
||||||
|
class TeamAccessChecker:
|
||||||
|
"""Dependency for checking team access in route handlers."""
|
||||||
|
|
||||||
|
def __init__(self, required_role: str = "member"):
|
||||||
|
self.required_role = required_role
|
||||||
|
|
||||||
|
def __call__(
|
||||||
|
self,
|
||||||
|
slug: str,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: Optional[User] = Depends(get_current_user_optional),
|
||||||
|
) -> User:
|
||||||
|
"""Check if user has required role in team.
|
||||||
|
|
||||||
|
Raises 404 if team not found, 401 if not authenticated, 403 if insufficient role.
|
||||||
|
Returns the current user.
|
||||||
|
"""
|
||||||
|
from .models import Team
|
||||||
|
|
||||||
|
# Find team by slug
|
||||||
|
team = db.query(Team).filter(Team.slug == slug).first()
|
||||||
|
if not team:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail=f"Team '{slug}' not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
if not current_user:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Authentication required",
|
||||||
|
headers={"WWW-Authenticate": "Bearer"},
|
||||||
|
)
|
||||||
|
|
||||||
|
auth_service = TeamAuthorizationService(db)
|
||||||
|
|
||||||
|
if not auth_service.check_team_access(str(team.id), current_user, self.required_role):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail=f"Insufficient team permissions. Required role: {self.required_role}",
|
||||||
|
)
|
||||||
|
|
||||||
|
return current_user
|
||||||
|
|
||||||
|
|
||||||
|
# Pre-configured team access checkers
|
||||||
|
require_team_member = TeamAccessChecker("member")
|
||||||
|
require_team_admin = TeamAccessChecker("admin")
|
||||||
|
require_team_owner = TeamAccessChecker("owner")
|
||||||
|
|
||||||
|
|
||||||
|
def check_team_access(
|
||||||
|
db: Session,
|
||||||
|
team_slug: str,
|
||||||
|
user: Optional[User],
|
||||||
|
required_role: str = "member",
|
||||||
|
) -> "Team":
|
||||||
|
"""Check if user has required role in team.
|
||||||
|
|
||||||
|
This is a helper function for use in route handlers.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
db: Database session
|
||||||
|
team_slug: Slug of the team
|
||||||
|
user: Current user (can be None for no access)
|
||||||
|
required_role: Required team role (member, admin, owner)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The Team object if access is granted
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
HTTPException 404: Team not found
|
||||||
|
HTTPException 401: Authentication required
|
||||||
|
HTTPException 403: Insufficient permissions
|
||||||
|
"""
|
||||||
|
from .models import Team
|
||||||
|
|
||||||
|
# Find team by slug
|
||||||
|
team = db.query(Team).filter(Team.slug == team_slug).first()
|
||||||
|
if not team:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_404_NOT_FOUND,
|
||||||
|
detail=f"Team '{team_slug}' not found",
|
||||||
|
)
|
||||||
|
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Authentication required",
|
||||||
|
headers={"WWW-Authenticate": "Bearer"},
|
||||||
|
)
|
||||||
|
|
||||||
|
auth_service = TeamAuthorizationService(db)
|
||||||
|
|
||||||
|
if not auth_service.check_team_access(str(team.id), user, required_role):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail=f"Insufficient team permissions. Required role: {required_role}",
|
||||||
|
)
|
||||||
|
|
||||||
|
return team
|
||||||
|
|
||||||
|
|
||||||
# --- OIDC Configuration Service ---
|
# --- OIDC Configuration Service ---
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
316
backend/app/cache.py
Normal file
316
backend/app/cache.py
Normal file
@@ -0,0 +1,316 @@
|
|||||||
|
"""
|
||||||
|
Cache service for upstream artifact caching.
|
||||||
|
|
||||||
|
Provides URL parsing, system project management, and caching logic
|
||||||
|
for the upstream caching feature.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from typing import Optional
|
||||||
|
from urllib.parse import urlparse, unquote
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
# System project names for each source type
|
||||||
|
SYSTEM_PROJECT_NAMES = {
|
||||||
|
"npm": "_npm",
|
||||||
|
"pypi": "_pypi",
|
||||||
|
"maven": "_maven",
|
||||||
|
"docker": "_docker",
|
||||||
|
"helm": "_helm",
|
||||||
|
"nuget": "_nuget",
|
||||||
|
"deb": "_deb",
|
||||||
|
"rpm": "_rpm",
|
||||||
|
"generic": "_generic",
|
||||||
|
}
|
||||||
|
|
||||||
|
# System project descriptions
|
||||||
|
SYSTEM_PROJECT_DESCRIPTIONS = {
|
||||||
|
"npm": "System cache for npm packages",
|
||||||
|
"pypi": "System cache for PyPI packages",
|
||||||
|
"maven": "System cache for Maven packages",
|
||||||
|
"docker": "System cache for Docker images",
|
||||||
|
"helm": "System cache for Helm charts",
|
||||||
|
"nuget": "System cache for NuGet packages",
|
||||||
|
"deb": "System cache for Debian packages",
|
||||||
|
"rpm": "System cache for RPM packages",
|
||||||
|
"generic": "System cache for generic artifacts",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ParsedUrl:
|
||||||
|
"""Parsed URL information for caching."""
|
||||||
|
|
||||||
|
package_name: str
|
||||||
|
version: Optional[str] = None
|
||||||
|
filename: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
def parse_npm_url(url: str) -> Optional[ParsedUrl]:
|
||||||
|
"""
|
||||||
|
Parse npm registry URL to extract package name and version.
|
||||||
|
|
||||||
|
Formats:
|
||||||
|
- https://registry.npmjs.org/{package}/-/{package}-{version}.tgz
|
||||||
|
- https://registry.npmjs.org/@{scope}/{package}/-/{package}-{version}.tgz
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
- https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz
|
||||||
|
- https://registry.npmjs.org/@types/node/-/node-18.0.0.tgz
|
||||||
|
"""
|
||||||
|
parsed = urlparse(url)
|
||||||
|
path = unquote(parsed.path)
|
||||||
|
|
||||||
|
# Pattern for scoped packages: /@scope/package/-/package-version.tgz
|
||||||
|
scoped_pattern = r"^/@([^/]+)/([^/]+)/-/\2-(.+)\.tgz$"
|
||||||
|
match = re.match(scoped_pattern, path)
|
||||||
|
if match:
|
||||||
|
scope, name, version = match.groups()
|
||||||
|
return ParsedUrl(
|
||||||
|
package_name=f"@{scope}/{name}",
|
||||||
|
version=version,
|
||||||
|
filename=f"{name}-{version}.tgz",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Pattern for unscoped packages: /package/-/package-version.tgz
|
||||||
|
unscoped_pattern = r"^/([^/@]+)/-/\1-(.+)\.tgz$"
|
||||||
|
match = re.match(unscoped_pattern, path)
|
||||||
|
if match:
|
||||||
|
name, version = match.groups()
|
||||||
|
return ParsedUrl(
|
||||||
|
package_name=name,
|
||||||
|
version=version,
|
||||||
|
filename=f"{name}-{version}.tgz",
|
||||||
|
)
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def parse_pypi_url(url: str) -> Optional[ParsedUrl]:
|
||||||
|
"""
|
||||||
|
Parse PyPI URL to extract package name and version.
|
||||||
|
|
||||||
|
Formats:
|
||||||
|
- https://files.pythonhosted.org/packages/.../package-version.tar.gz
|
||||||
|
- https://files.pythonhosted.org/packages/.../package-version-py3-none-any.whl
|
||||||
|
- https://pypi.org/packages/.../package-version.tar.gz
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
- https://files.pythonhosted.org/packages/ab/cd/requests-2.28.0.tar.gz
|
||||||
|
- https://files.pythonhosted.org/packages/ab/cd/requests-2.28.0-py3-none-any.whl
|
||||||
|
"""
|
||||||
|
parsed = urlparse(url)
|
||||||
|
path = unquote(parsed.path)
|
||||||
|
|
||||||
|
# Get the filename from the path
|
||||||
|
filename = path.split("/")[-1]
|
||||||
|
if not filename:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Handle wheel files: package-version-py3-none-any.whl
|
||||||
|
wheel_pattern = r"^([a-zA-Z0-9_-]+)-(\d+[^-]*)-.*\.whl$"
|
||||||
|
match = re.match(wheel_pattern, filename)
|
||||||
|
if match:
|
||||||
|
name, version = match.groups()
|
||||||
|
# Normalize package name (PyPI uses underscores internally)
|
||||||
|
name = name.replace("_", "-").lower()
|
||||||
|
return ParsedUrl(
|
||||||
|
package_name=name,
|
||||||
|
version=version,
|
||||||
|
filename=filename,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Handle source distributions: package-version.tar.gz or package-version.zip
|
||||||
|
sdist_pattern = r"^([a-zA-Z0-9_-]+)-(\d+(?:\.\d+)*(?:[a-zA-Z0-9_.+-]*)?)(?:\.tar\.gz|\.zip|\.tar\.bz2)$"
|
||||||
|
match = re.match(sdist_pattern, filename)
|
||||||
|
if match:
|
||||||
|
name, version = match.groups()
|
||||||
|
name = name.replace("_", "-").lower()
|
||||||
|
return ParsedUrl(
|
||||||
|
package_name=name,
|
||||||
|
version=version,
|
||||||
|
filename=filename,
|
||||||
|
)
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def parse_maven_url(url: str) -> Optional[ParsedUrl]:
|
||||||
|
"""
|
||||||
|
Parse Maven repository URL to extract artifact info.
|
||||||
|
|
||||||
|
Format:
|
||||||
|
- https://repo1.maven.org/maven2/{group}/{artifact}/{version}/{artifact}-{version}.jar
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
- https://repo1.maven.org/maven2/org/apache/commons/commons-lang3/3.12.0/commons-lang3-3.12.0.jar
|
||||||
|
- https://repo1.maven.org/maven2/com/google/guava/guava/31.1-jre/guava-31.1-jre.jar
|
||||||
|
"""
|
||||||
|
parsed = urlparse(url)
|
||||||
|
path = unquote(parsed.path)
|
||||||
|
|
||||||
|
# Find /maven2/ or similar repository path
|
||||||
|
maven2_idx = path.find("/maven2/")
|
||||||
|
if maven2_idx >= 0:
|
||||||
|
path = path[maven2_idx + 8:] # Remove /maven2/
|
||||||
|
elif path.startswith("/"):
|
||||||
|
path = path[1:]
|
||||||
|
|
||||||
|
parts = path.split("/")
|
||||||
|
if len(parts) < 4:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Last part is filename, before that is version, before that is artifact
|
||||||
|
filename = parts[-1]
|
||||||
|
version = parts[-2]
|
||||||
|
artifact = parts[-3]
|
||||||
|
group = ".".join(parts[:-3])
|
||||||
|
|
||||||
|
# Verify filename matches expected pattern
|
||||||
|
if not filename.startswith(f"{artifact}-{version}"):
|
||||||
|
return None
|
||||||
|
|
||||||
|
return ParsedUrl(
|
||||||
|
package_name=f"{group}:{artifact}",
|
||||||
|
version=version,
|
||||||
|
filename=filename,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_docker_url(url: str) -> Optional[ParsedUrl]:
|
||||||
|
"""
|
||||||
|
Parse Docker registry URL to extract image info.
|
||||||
|
|
||||||
|
Note: Docker registries are more complex (manifests, blobs, etc.)
|
||||||
|
This handles basic blob/manifest URLs.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
- https://registry-1.docker.io/v2/library/nginx/blobs/sha256:abc123
|
||||||
|
- https://registry-1.docker.io/v2/myuser/myimage/manifests/latest
|
||||||
|
"""
|
||||||
|
parsed = urlparse(url)
|
||||||
|
path = unquote(parsed.path)
|
||||||
|
|
||||||
|
# Pattern: /v2/{namespace}/{image}/blobs/{digest} or /manifests/{tag}
|
||||||
|
pattern = r"^/v2/([^/]+(?:/[^/]+)?)/([^/]+)/(blobs|manifests)/(.+)$"
|
||||||
|
match = re.match(pattern, path)
|
||||||
|
if match:
|
||||||
|
namespace, image, artifact_type, reference = match.groups()
|
||||||
|
if namespace == "library":
|
||||||
|
package_name = image
|
||||||
|
else:
|
||||||
|
package_name = f"{namespace}/{image}"
|
||||||
|
|
||||||
|
# For manifests, the reference is the tag
|
||||||
|
version = reference if artifact_type == "manifests" else None
|
||||||
|
|
||||||
|
return ParsedUrl(
|
||||||
|
package_name=package_name,
|
||||||
|
version=version,
|
||||||
|
filename=f"{image}-{reference}" if version else reference,
|
||||||
|
)
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def parse_generic_url(url: str) -> ParsedUrl:
|
||||||
|
"""
|
||||||
|
Parse a generic URL to extract filename.
|
||||||
|
|
||||||
|
Attempts to extract meaningful package name and version from filename.
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
- https://example.com/downloads/myapp-1.2.3.tar.gz
|
||||||
|
- https://github.com/user/repo/releases/download/v1.0/release.zip
|
||||||
|
"""
|
||||||
|
parsed = urlparse(url)
|
||||||
|
path = unquote(parsed.path)
|
||||||
|
filename = path.split("/")[-1] or "artifact"
|
||||||
|
|
||||||
|
# List of known compound and simple extensions
|
||||||
|
known_extensions = [
|
||||||
|
".tar.gz", ".tar.bz2", ".tar.xz",
|
||||||
|
".zip", ".tgz", ".gz", ".jar", ".war", ".deb", ".rpm"
|
||||||
|
]
|
||||||
|
|
||||||
|
# Strip extension from filename first
|
||||||
|
base_name = filename
|
||||||
|
matched_ext = None
|
||||||
|
for ext in known_extensions:
|
||||||
|
if filename.endswith(ext):
|
||||||
|
base_name = filename[:-len(ext)]
|
||||||
|
matched_ext = ext
|
||||||
|
break
|
||||||
|
|
||||||
|
if matched_ext is None:
|
||||||
|
# Unknown extension, return filename as package name
|
||||||
|
return ParsedUrl(
|
||||||
|
package_name=filename,
|
||||||
|
version=None,
|
||||||
|
filename=filename,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Try to extract version from base_name
|
||||||
|
# Pattern: name-version or name_version
|
||||||
|
# Version starts with digit(s) and can include dots, dashes, and alphanumeric suffixes
|
||||||
|
version_pattern = r"^(.+?)[-_](v?\d+(?:\.\d+)*(?:[-_][a-zA-Z0-9]+)?)$"
|
||||||
|
match = re.match(version_pattern, base_name)
|
||||||
|
if match:
|
||||||
|
name, version = match.groups()
|
||||||
|
return ParsedUrl(
|
||||||
|
package_name=name,
|
||||||
|
version=version,
|
||||||
|
filename=filename,
|
||||||
|
)
|
||||||
|
|
||||||
|
# No version found, use base_name as package name
|
||||||
|
return ParsedUrl(
|
||||||
|
package_name=base_name,
|
||||||
|
version=None,
|
||||||
|
filename=filename,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def parse_url(url: str, source_type: str) -> ParsedUrl:
|
||||||
|
"""
|
||||||
|
Parse URL to extract package name and version based on source type.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
url: The URL to parse.
|
||||||
|
source_type: The source type (npm, pypi, maven, docker, etc.)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
ParsedUrl with extracted information.
|
||||||
|
"""
|
||||||
|
parsed = None
|
||||||
|
|
||||||
|
if source_type == "npm":
|
||||||
|
parsed = parse_npm_url(url)
|
||||||
|
elif source_type == "pypi":
|
||||||
|
parsed = parse_pypi_url(url)
|
||||||
|
elif source_type == "maven":
|
||||||
|
parsed = parse_maven_url(url)
|
||||||
|
elif source_type == "docker":
|
||||||
|
parsed = parse_docker_url(url)
|
||||||
|
|
||||||
|
# Fall back to generic parsing if type-specific parsing fails
|
||||||
|
if parsed is None:
|
||||||
|
parsed = parse_generic_url(url)
|
||||||
|
|
||||||
|
return parsed
|
||||||
|
|
||||||
|
|
||||||
|
def get_system_project_name(source_type: str) -> str:
|
||||||
|
"""Get the system project name for a source type."""
|
||||||
|
return SYSTEM_PROJECT_NAMES.get(source_type, "_generic")
|
||||||
|
|
||||||
|
|
||||||
|
def get_system_project_description(source_type: str) -> str:
|
||||||
|
"""Get the system project description for a source type."""
|
||||||
|
return SYSTEM_PROJECT_DESCRIPTIONS.get(
|
||||||
|
source_type, "System cache for artifacts"
|
||||||
|
)
|
||||||
@@ -1,5 +1,8 @@
|
|||||||
from pydantic_settings import BaseSettings
|
from pydantic_settings import BaseSettings
|
||||||
from functools import lru_cache
|
from functools import lru_cache
|
||||||
|
from typing import Optional
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
|
||||||
|
|
||||||
class Settings(BaseSettings):
|
class Settings(BaseSettings):
|
||||||
@@ -56,6 +59,11 @@ class Settings(BaseSettings):
|
|||||||
# Initial admin user settings
|
# Initial admin user settings
|
||||||
admin_password: str = "" # Initial admin password (if empty, uses 'changeme123')
|
admin_password: str = "" # Initial admin password (if empty, uses 'changeme123')
|
||||||
|
|
||||||
|
# Cache settings
|
||||||
|
cache_encryption_key: str = "" # Fernet key for encrypting upstream credentials (auto-generated if empty)
|
||||||
|
# Global cache settings override (None = use DB value, True/False = override DB)
|
||||||
|
cache_auto_create_system_projects: Optional[bool] = None # Override auto_create_system_projects
|
||||||
|
|
||||||
# JWT Authentication settings (optional, for external identity providers)
|
# JWT Authentication settings (optional, for external identity providers)
|
||||||
jwt_enabled: bool = False # Enable JWT token validation
|
jwt_enabled: bool = False # Enable JWT token validation
|
||||||
jwt_secret: str = "" # Secret key for HS256, or leave empty for RS256 with JWKS
|
jwt_secret: str = "" # Secret key for HS256, or leave empty for RS256 with JWKS
|
||||||
@@ -88,3 +96,110 @@ class Settings(BaseSettings):
|
|||||||
@lru_cache()
|
@lru_cache()
|
||||||
def get_settings() -> Settings:
|
def get_settings() -> Settings:
|
||||||
return Settings()
|
return Settings()
|
||||||
|
|
||||||
|
|
||||||
|
class EnvUpstreamSource:
|
||||||
|
"""Represents an upstream source defined via environment variables."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
name: str,
|
||||||
|
url: str,
|
||||||
|
source_type: str = "generic",
|
||||||
|
enabled: bool = True,
|
||||||
|
auth_type: str = "none",
|
||||||
|
username: Optional[str] = None,
|
||||||
|
password: Optional[str] = None,
|
||||||
|
priority: int = 100,
|
||||||
|
):
|
||||||
|
self.name = name
|
||||||
|
self.url = url
|
||||||
|
self.source_type = source_type
|
||||||
|
self.enabled = enabled
|
||||||
|
self.auth_type = auth_type
|
||||||
|
self.username = username
|
||||||
|
self.password = password
|
||||||
|
self.priority = priority
|
||||||
|
self.source = "env" # Mark as env-defined
|
||||||
|
|
||||||
|
|
||||||
|
def parse_upstream_sources_from_env() -> list[EnvUpstreamSource]:
|
||||||
|
"""
|
||||||
|
Parse upstream sources from environment variables.
|
||||||
|
|
||||||
|
Uses double underscore (__) as separator to allow source names with single underscores.
|
||||||
|
Pattern: ORCHARD_UPSTREAM__{NAME}__FIELD
|
||||||
|
|
||||||
|
Example:
|
||||||
|
ORCHARD_UPSTREAM__NPM_PRIVATE__URL=https://npm.corp.com
|
||||||
|
ORCHARD_UPSTREAM__NPM_PRIVATE__TYPE=npm
|
||||||
|
ORCHARD_UPSTREAM__NPM_PRIVATE__ENABLED=true
|
||||||
|
ORCHARD_UPSTREAM__NPM_PRIVATE__AUTH_TYPE=basic
|
||||||
|
ORCHARD_UPSTREAM__NPM_PRIVATE__USERNAME=reader
|
||||||
|
ORCHARD_UPSTREAM__NPM_PRIVATE__PASSWORD=secret
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
List of EnvUpstreamSource objects parsed from environment variables.
|
||||||
|
"""
|
||||||
|
# Pattern: ORCHARD_UPSTREAM__{NAME}__{FIELD}
|
||||||
|
pattern = re.compile(r"^ORCHARD_UPSTREAM__([A-Z0-9_]+)__([A-Z_]+)$", re.IGNORECASE)
|
||||||
|
|
||||||
|
# Collect all env vars matching the pattern, grouped by source name
|
||||||
|
sources_data: dict[str, dict[str, str]] = {}
|
||||||
|
|
||||||
|
for key, value in os.environ.items():
|
||||||
|
match = pattern.match(key)
|
||||||
|
if match:
|
||||||
|
source_name = match.group(1).lower() # Normalize to lowercase
|
||||||
|
field = match.group(2).upper()
|
||||||
|
if source_name not in sources_data:
|
||||||
|
sources_data[source_name] = {}
|
||||||
|
sources_data[source_name][field] = value
|
||||||
|
|
||||||
|
# Build source objects from collected data
|
||||||
|
sources: list[EnvUpstreamSource] = []
|
||||||
|
|
||||||
|
for name, data in sources_data.items():
|
||||||
|
# URL is required
|
||||||
|
url = data.get("URL")
|
||||||
|
if not url:
|
||||||
|
continue # Skip sources without URL
|
||||||
|
|
||||||
|
# Parse boolean fields
|
||||||
|
def parse_bool(val: Optional[str], default: bool) -> bool:
|
||||||
|
if val is None:
|
||||||
|
return default
|
||||||
|
return val.lower() in ("true", "1", "yes", "on")
|
||||||
|
|
||||||
|
# Parse integer fields
|
||||||
|
def parse_int(val: Optional[str], default: int) -> int:
|
||||||
|
if val is None:
|
||||||
|
return default
|
||||||
|
try:
|
||||||
|
return int(val)
|
||||||
|
except ValueError:
|
||||||
|
return default
|
||||||
|
|
||||||
|
source = EnvUpstreamSource(
|
||||||
|
name=name.replace("_", "-"), # Convert underscores to hyphens for readability
|
||||||
|
url=url,
|
||||||
|
source_type=data.get("TYPE", "generic").lower(),
|
||||||
|
enabled=parse_bool(data.get("ENABLED"), True),
|
||||||
|
auth_type=data.get("AUTH_TYPE", "none").lower(),
|
||||||
|
username=data.get("USERNAME"),
|
||||||
|
password=data.get("PASSWORD"),
|
||||||
|
priority=parse_int(data.get("PRIORITY"), 100),
|
||||||
|
)
|
||||||
|
sources.append(source)
|
||||||
|
|
||||||
|
return sources
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache()
|
||||||
|
def get_env_upstream_sources() -> tuple[EnvUpstreamSource, ...]:
|
||||||
|
"""
|
||||||
|
Get cached list of upstream sources from environment variables.
|
||||||
|
|
||||||
|
Returns a tuple for hashability (required by lru_cache).
|
||||||
|
"""
|
||||||
|
return tuple(parse_upstream_sources_from_env())
|
||||||
|
|||||||
@@ -1,17 +1,34 @@
|
|||||||
from sqlalchemy import create_engine, text, event
|
from sqlalchemy import create_engine, text, event
|
||||||
from sqlalchemy.orm import sessionmaker, Session
|
from sqlalchemy.orm import sessionmaker, Session
|
||||||
from sqlalchemy.pool import QueuePool
|
from sqlalchemy.pool import QueuePool
|
||||||
from typing import Generator
|
from typing import Generator, NamedTuple
|
||||||
from contextlib import contextmanager
|
from contextlib import contextmanager
|
||||||
import logging
|
import logging
|
||||||
import time
|
import time
|
||||||
|
import hashlib
|
||||||
|
|
||||||
from .config import get_settings
|
from .config import get_settings
|
||||||
from .models import Base
|
from .models import Base
|
||||||
|
from .purge_seed_data import should_purge_seed_data, purge_seed_data
|
||||||
|
|
||||||
settings = get_settings()
|
settings = get_settings()
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(NamedTuple):
|
||||||
|
"""A database migration with a unique name and SQL to execute."""
|
||||||
|
name: str
|
||||||
|
sql: str
|
||||||
|
|
||||||
|
|
||||||
|
# PostgreSQL error codes that indicate "already exists" - safe to skip
|
||||||
|
SAFE_PG_ERROR_CODES = {
|
||||||
|
"42P07", # duplicate_table
|
||||||
|
"42701", # duplicate_column
|
||||||
|
"42710", # duplicate_object (index, constraint, etc.)
|
||||||
|
"42P16", # invalid_table_definition (e.g., column already exists)
|
||||||
|
}
|
||||||
|
|
||||||
# Build connect_args with query timeout if configured
|
# Build connect_args with query timeout if configured
|
||||||
connect_args = {}
|
connect_args = {}
|
||||||
if settings.database_query_timeout > 0:
|
if settings.database_query_timeout > 0:
|
||||||
@@ -64,236 +81,533 @@ def init_db():
|
|||||||
# Run migrations for schema updates
|
# Run migrations for schema updates
|
||||||
_run_migrations()
|
_run_migrations()
|
||||||
|
|
||||||
|
# Purge seed data if requested (for transitioning to production-like environment)
|
||||||
|
if should_purge_seed_data():
|
||||||
|
db = SessionLocal()
|
||||||
|
try:
|
||||||
|
purge_seed_data(db)
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _ensure_migrations_table(conn) -> None:
|
||||||
|
"""Create the migrations tracking table if it doesn't exist."""
|
||||||
|
conn.execute(text("""
|
||||||
|
CREATE TABLE IF NOT EXISTS _schema_migrations (
|
||||||
|
name VARCHAR(255) PRIMARY KEY,
|
||||||
|
checksum VARCHAR(64) NOT NULL,
|
||||||
|
applied_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
|
||||||
|
);
|
||||||
|
"""))
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
|
||||||
|
def _get_applied_migrations(conn) -> dict[str, str]:
|
||||||
|
"""Get all applied migrations and their checksums."""
|
||||||
|
result = conn.execute(text(
|
||||||
|
"SELECT name, checksum FROM _schema_migrations"
|
||||||
|
))
|
||||||
|
return {row[0]: row[1] for row in result}
|
||||||
|
|
||||||
|
|
||||||
|
def _compute_checksum(sql: str) -> str:
|
||||||
|
"""Compute a checksum for migration SQL to detect changes."""
|
||||||
|
return hashlib.sha256(sql.strip().encode()).hexdigest()[:16]
|
||||||
|
|
||||||
|
|
||||||
|
def _is_safe_error(exception: Exception) -> bool:
|
||||||
|
"""Check if the error indicates the migration was already applied."""
|
||||||
|
# Check for psycopg2 errors with pgcode attribute
|
||||||
|
original = getattr(exception, "orig", None)
|
||||||
|
if original is not None:
|
||||||
|
pgcode = getattr(original, "pgcode", None)
|
||||||
|
if pgcode in SAFE_PG_ERROR_CODES:
|
||||||
|
return True
|
||||||
|
|
||||||
|
# Fallback: check error message for common "already exists" patterns
|
||||||
|
error_str = str(exception).lower()
|
||||||
|
safe_patterns = [
|
||||||
|
"already exists",
|
||||||
|
"duplicate key",
|
||||||
|
"relation .* already exists",
|
||||||
|
"column .* already exists",
|
||||||
|
]
|
||||||
|
return any(pattern in error_str for pattern in safe_patterns)
|
||||||
|
|
||||||
|
|
||||||
|
def _record_migration(conn, name: str, checksum: str) -> None:
|
||||||
|
"""Record a migration as applied."""
|
||||||
|
conn.execute(text(
|
||||||
|
"INSERT INTO _schema_migrations (name, checksum) VALUES (:name, :checksum)"
|
||||||
|
), {"name": name, "checksum": checksum})
|
||||||
|
conn.commit()
|
||||||
|
|
||||||
|
|
||||||
def _run_migrations():
|
def _run_migrations():
|
||||||
"""Run manual migrations for schema updates"""
|
"""Run manual migrations for schema updates with tracking and error detection."""
|
||||||
migrations = [
|
migrations = [
|
||||||
# Add format_metadata column to artifacts table
|
Migration(
|
||||||
"""
|
name="001_add_format_metadata",
|
||||||
DO $$
|
sql="""
|
||||||
BEGIN
|
DO $$
|
||||||
IF NOT EXISTS (
|
BEGIN
|
||||||
SELECT 1 FROM information_schema.columns
|
IF NOT EXISTS (
|
||||||
WHERE table_name = 'artifacts' AND column_name = 'format_metadata'
|
SELECT 1 FROM information_schema.columns
|
||||||
) THEN
|
WHERE table_name = 'artifacts' AND column_name = 'format_metadata'
|
||||||
ALTER TABLE artifacts ADD COLUMN format_metadata JSONB DEFAULT '{}';
|
) THEN
|
||||||
END IF;
|
ALTER TABLE artifacts ADD COLUMN format_metadata JSONB DEFAULT '{}';
|
||||||
END $$;
|
|
||||||
""",
|
|
||||||
# Add format column to packages table
|
|
||||||
"""
|
|
||||||
DO $$
|
|
||||||
BEGIN
|
|
||||||
IF NOT EXISTS (
|
|
||||||
SELECT 1 FROM information_schema.columns
|
|
||||||
WHERE table_name = 'packages' AND column_name = 'format'
|
|
||||||
) THEN
|
|
||||||
ALTER TABLE packages ADD COLUMN format VARCHAR(50) DEFAULT 'generic' NOT NULL;
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_packages_format ON packages(format);
|
|
||||||
END IF;
|
|
||||||
END $$;
|
|
||||||
""",
|
|
||||||
# Add platform column to packages table
|
|
||||||
"""
|
|
||||||
DO $$
|
|
||||||
BEGIN
|
|
||||||
IF NOT EXISTS (
|
|
||||||
SELECT 1 FROM information_schema.columns
|
|
||||||
WHERE table_name = 'packages' AND column_name = 'platform'
|
|
||||||
) THEN
|
|
||||||
ALTER TABLE packages ADD COLUMN platform VARCHAR(50) DEFAULT 'any' NOT NULL;
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_packages_platform ON packages(platform);
|
|
||||||
END IF;
|
|
||||||
END $$;
|
|
||||||
""",
|
|
||||||
# Add ref_count index and constraints for artifacts
|
|
||||||
"""
|
|
||||||
DO $$
|
|
||||||
BEGIN
|
|
||||||
-- Add ref_count index
|
|
||||||
IF NOT EXISTS (
|
|
||||||
SELECT 1 FROM pg_indexes WHERE indexname = 'idx_artifacts_ref_count'
|
|
||||||
) THEN
|
|
||||||
CREATE INDEX idx_artifacts_ref_count ON artifacts(ref_count);
|
|
||||||
END IF;
|
|
||||||
|
|
||||||
-- Add ref_count >= 0 constraint
|
|
||||||
IF NOT EXISTS (
|
|
||||||
SELECT 1 FROM pg_constraint WHERE conname = 'check_ref_count_non_negative'
|
|
||||||
) THEN
|
|
||||||
ALTER TABLE artifacts ADD CONSTRAINT check_ref_count_non_negative CHECK (ref_count >= 0);
|
|
||||||
END IF;
|
|
||||||
END $$;
|
|
||||||
""",
|
|
||||||
# Add composite indexes for packages and tags
|
|
||||||
"""
|
|
||||||
DO $$
|
|
||||||
BEGIN
|
|
||||||
-- Composite index for package lookup by project and name
|
|
||||||
IF NOT EXISTS (
|
|
||||||
SELECT 1 FROM pg_indexes WHERE indexname = 'idx_packages_project_name'
|
|
||||||
) THEN
|
|
||||||
CREATE UNIQUE INDEX idx_packages_project_name ON packages(project_id, name);
|
|
||||||
END IF;
|
|
||||||
|
|
||||||
-- Composite index for tag lookup by package and name
|
|
||||||
IF NOT EXISTS (
|
|
||||||
SELECT 1 FROM pg_indexes WHERE indexname = 'idx_tags_package_name'
|
|
||||||
) THEN
|
|
||||||
CREATE UNIQUE INDEX idx_tags_package_name ON tags(package_id, name);
|
|
||||||
END IF;
|
|
||||||
|
|
||||||
-- Composite index for recent tags queries
|
|
||||||
IF NOT EXISTS (
|
|
||||||
SELECT 1 FROM pg_indexes WHERE indexname = 'idx_tags_package_created_at'
|
|
||||||
) THEN
|
|
||||||
CREATE INDEX idx_tags_package_created_at ON tags(package_id, created_at);
|
|
||||||
END IF;
|
|
||||||
END $$;
|
|
||||||
""",
|
|
||||||
# Add package_versions indexes and triggers (007_package_versions.sql)
|
|
||||||
"""
|
|
||||||
DO $$
|
|
||||||
BEGIN
|
|
||||||
-- Create indexes for package_versions if table exists
|
|
||||||
IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'package_versions') THEN
|
|
||||||
-- Indexes for common queries
|
|
||||||
IF NOT EXISTS (SELECT 1 FROM pg_indexes WHERE indexname = 'idx_package_versions_package_id') THEN
|
|
||||||
CREATE INDEX idx_package_versions_package_id ON package_versions(package_id);
|
|
||||||
END IF;
|
END IF;
|
||||||
IF NOT EXISTS (SELECT 1 FROM pg_indexes WHERE indexname = 'idx_package_versions_artifact_id') THEN
|
END $$;
|
||||||
CREATE INDEX idx_package_versions_artifact_id ON package_versions(artifact_id);
|
""",
|
||||||
|
),
|
||||||
|
Migration(
|
||||||
|
name="002_add_package_format",
|
||||||
|
sql="""
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'packages' AND column_name = 'format'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE packages ADD COLUMN format VARCHAR(50) DEFAULT 'generic' NOT NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_packages_format ON packages(format);
|
||||||
END IF;
|
END IF;
|
||||||
IF NOT EXISTS (SELECT 1 FROM pg_indexes WHERE indexname = 'idx_package_versions_package_version') THEN
|
END $$;
|
||||||
CREATE INDEX idx_package_versions_package_version ON package_versions(package_id, version);
|
""",
|
||||||
|
),
|
||||||
|
Migration(
|
||||||
|
name="003_add_package_platform",
|
||||||
|
sql="""
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'packages' AND column_name = 'platform'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE packages ADD COLUMN platform VARCHAR(50) DEFAULT 'any' NOT NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_packages_platform ON packages(platform);
|
||||||
END IF;
|
END IF;
|
||||||
END IF;
|
END $$;
|
||||||
END $$;
|
""",
|
||||||
""",
|
),
|
||||||
# Create ref_count trigger functions for tags (ensures triggers exist even if initial migration wasn't run)
|
Migration(
|
||||||
"""
|
name="004_add_ref_count_index_constraint",
|
||||||
CREATE OR REPLACE FUNCTION increment_artifact_ref_count()
|
sql="""
|
||||||
RETURNS TRIGGER AS $$
|
DO $$
|
||||||
BEGIN
|
BEGIN
|
||||||
UPDATE artifacts SET ref_count = ref_count + 1 WHERE id = NEW.artifact_id;
|
IF NOT EXISTS (
|
||||||
RETURN NEW;
|
SELECT 1 FROM pg_indexes WHERE indexname = 'idx_artifacts_ref_count'
|
||||||
END;
|
) THEN
|
||||||
$$ LANGUAGE plpgsql;
|
CREATE INDEX idx_artifacts_ref_count ON artifacts(ref_count);
|
||||||
""",
|
END IF;
|
||||||
"""
|
|
||||||
CREATE OR REPLACE FUNCTION decrement_artifact_ref_count()
|
IF NOT EXISTS (
|
||||||
RETURNS TRIGGER AS $$
|
SELECT 1 FROM pg_constraint WHERE conname = 'check_ref_count_non_negative'
|
||||||
BEGIN
|
) THEN
|
||||||
UPDATE artifacts SET ref_count = ref_count - 1 WHERE id = OLD.artifact_id;
|
ALTER TABLE artifacts ADD CONSTRAINT check_ref_count_non_negative CHECK (ref_count >= 0);
|
||||||
RETURN OLD;
|
END IF;
|
||||||
END;
|
END $$;
|
||||||
$$ LANGUAGE plpgsql;
|
""",
|
||||||
""",
|
),
|
||||||
"""
|
Migration(
|
||||||
CREATE OR REPLACE FUNCTION update_artifact_ref_count()
|
name="005_add_composite_indexes",
|
||||||
RETURNS TRIGGER AS $$
|
sql="""
|
||||||
BEGIN
|
DO $$
|
||||||
IF OLD.artifact_id != NEW.artifact_id THEN
|
BEGIN
|
||||||
UPDATE artifacts SET ref_count = ref_count - 1 WHERE id = OLD.artifact_id;
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM pg_indexes WHERE indexname = 'idx_packages_project_name'
|
||||||
|
) THEN
|
||||||
|
CREATE UNIQUE INDEX idx_packages_project_name ON packages(project_id, name);
|
||||||
|
END IF;
|
||||||
|
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM pg_indexes WHERE indexname = 'idx_tags_package_name'
|
||||||
|
) THEN
|
||||||
|
CREATE UNIQUE INDEX idx_tags_package_name ON tags(package_id, name);
|
||||||
|
END IF;
|
||||||
|
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM pg_indexes WHERE indexname = 'idx_tags_package_created_at'
|
||||||
|
) THEN
|
||||||
|
CREATE INDEX idx_tags_package_created_at ON tags(package_id, created_at);
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
""",
|
||||||
|
),
|
||||||
|
Migration(
|
||||||
|
name="006_add_package_versions_indexes",
|
||||||
|
sql="""
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'package_versions') THEN
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM pg_indexes WHERE indexname = 'idx_package_versions_package_id') THEN
|
||||||
|
CREATE INDEX idx_package_versions_package_id ON package_versions(package_id);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM pg_indexes WHERE indexname = 'idx_package_versions_artifact_id') THEN
|
||||||
|
CREATE INDEX idx_package_versions_artifact_id ON package_versions(artifact_id);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM pg_indexes WHERE indexname = 'idx_package_versions_package_version') THEN
|
||||||
|
CREATE INDEX idx_package_versions_package_version ON package_versions(package_id, version);
|
||||||
|
END IF;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
""",
|
||||||
|
),
|
||||||
|
Migration(
|
||||||
|
name="007_create_ref_count_trigger_functions",
|
||||||
|
sql="""
|
||||||
|
CREATE OR REPLACE FUNCTION increment_artifact_ref_count()
|
||||||
|
RETURNS TRIGGER AS $$
|
||||||
|
BEGIN
|
||||||
UPDATE artifacts SET ref_count = ref_count + 1 WHERE id = NEW.artifact_id;
|
UPDATE artifacts SET ref_count = ref_count + 1 WHERE id = NEW.artifact_id;
|
||||||
END IF;
|
RETURN NEW;
|
||||||
RETURN NEW;
|
END;
|
||||||
END;
|
$$ LANGUAGE plpgsql;
|
||||||
$$ LANGUAGE plpgsql;
|
|
||||||
""",
|
|
||||||
# Create triggers for tags ref_count management
|
|
||||||
"""
|
|
||||||
DO $$
|
|
||||||
BEGIN
|
|
||||||
-- Drop and recreate triggers to ensure they're current
|
|
||||||
DROP TRIGGER IF EXISTS tags_ref_count_insert_trigger ON tags;
|
|
||||||
CREATE TRIGGER tags_ref_count_insert_trigger
|
|
||||||
AFTER INSERT ON tags
|
|
||||||
FOR EACH ROW
|
|
||||||
EXECUTE FUNCTION increment_artifact_ref_count();
|
|
||||||
|
|
||||||
DROP TRIGGER IF EXISTS tags_ref_count_delete_trigger ON tags;
|
CREATE OR REPLACE FUNCTION decrement_artifact_ref_count()
|
||||||
CREATE TRIGGER tags_ref_count_delete_trigger
|
RETURNS TRIGGER AS $$
|
||||||
AFTER DELETE ON tags
|
BEGIN
|
||||||
FOR EACH ROW
|
UPDATE artifacts SET ref_count = ref_count - 1 WHERE id = OLD.artifact_id;
|
||||||
EXECUTE FUNCTION decrement_artifact_ref_count();
|
RETURN OLD;
|
||||||
|
END;
|
||||||
|
$$ LANGUAGE plpgsql;
|
||||||
|
|
||||||
DROP TRIGGER IF EXISTS tags_ref_count_update_trigger ON tags;
|
CREATE OR REPLACE FUNCTION update_artifact_ref_count()
|
||||||
CREATE TRIGGER tags_ref_count_update_trigger
|
RETURNS TRIGGER AS $$
|
||||||
AFTER UPDATE ON tags
|
BEGIN
|
||||||
FOR EACH ROW
|
IF OLD.artifact_id != NEW.artifact_id THEN
|
||||||
WHEN (OLD.artifact_id IS DISTINCT FROM NEW.artifact_id)
|
UPDATE artifacts SET ref_count = ref_count - 1 WHERE id = OLD.artifact_id;
|
||||||
EXECUTE FUNCTION update_artifact_ref_count();
|
UPDATE artifacts SET ref_count = ref_count + 1 WHERE id = NEW.artifact_id;
|
||||||
END $$;
|
END IF;
|
||||||
""",
|
RETURN NEW;
|
||||||
# Create ref_count trigger functions for package_versions
|
END;
|
||||||
"""
|
$$ LANGUAGE plpgsql;
|
||||||
CREATE OR REPLACE FUNCTION increment_version_ref_count()
|
""",
|
||||||
RETURNS TRIGGER AS $$
|
),
|
||||||
BEGIN
|
Migration(
|
||||||
UPDATE artifacts SET ref_count = ref_count + 1 WHERE id = NEW.artifact_id;
|
name="008_create_tags_ref_count_triggers",
|
||||||
RETURN NEW;
|
sql="""
|
||||||
END;
|
DO $$
|
||||||
$$ LANGUAGE plpgsql;
|
BEGIN
|
||||||
""",
|
DROP TRIGGER IF EXISTS tags_ref_count_insert_trigger ON tags;
|
||||||
"""
|
CREATE TRIGGER tags_ref_count_insert_trigger
|
||||||
CREATE OR REPLACE FUNCTION decrement_version_ref_count()
|
AFTER INSERT ON tags
|
||||||
RETURNS TRIGGER AS $$
|
|
||||||
BEGIN
|
|
||||||
UPDATE artifacts SET ref_count = ref_count - 1 WHERE id = OLD.artifact_id;
|
|
||||||
RETURN OLD;
|
|
||||||
END;
|
|
||||||
$$ LANGUAGE plpgsql;
|
|
||||||
""",
|
|
||||||
# Create triggers for package_versions ref_count
|
|
||||||
"""
|
|
||||||
DO $$
|
|
||||||
BEGIN
|
|
||||||
IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'package_versions') THEN
|
|
||||||
-- Drop and recreate triggers to ensure they're current
|
|
||||||
DROP TRIGGER IF EXISTS package_versions_ref_count_insert ON package_versions;
|
|
||||||
CREATE TRIGGER package_versions_ref_count_insert
|
|
||||||
AFTER INSERT ON package_versions
|
|
||||||
FOR EACH ROW
|
FOR EACH ROW
|
||||||
EXECUTE FUNCTION increment_version_ref_count();
|
EXECUTE FUNCTION increment_artifact_ref_count();
|
||||||
|
|
||||||
DROP TRIGGER IF EXISTS package_versions_ref_count_delete ON package_versions;
|
DROP TRIGGER IF EXISTS tags_ref_count_delete_trigger ON tags;
|
||||||
CREATE TRIGGER package_versions_ref_count_delete
|
CREATE TRIGGER tags_ref_count_delete_trigger
|
||||||
AFTER DELETE ON package_versions
|
AFTER DELETE ON tags
|
||||||
FOR EACH ROW
|
FOR EACH ROW
|
||||||
EXECUTE FUNCTION decrement_version_ref_count();
|
EXECUTE FUNCTION decrement_artifact_ref_count();
|
||||||
END IF;
|
|
||||||
END $$;
|
DROP TRIGGER IF EXISTS tags_ref_count_update_trigger ON tags;
|
||||||
""",
|
CREATE TRIGGER tags_ref_count_update_trigger
|
||||||
# Migrate existing semver tags to package_versions
|
AFTER UPDATE ON tags
|
||||||
r"""
|
FOR EACH ROW
|
||||||
DO $$
|
WHEN (OLD.artifact_id IS DISTINCT FROM NEW.artifact_id)
|
||||||
BEGIN
|
EXECUTE FUNCTION update_artifact_ref_count();
|
||||||
IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'package_versions') THEN
|
END $$;
|
||||||
-- Migrate tags that look like versions (v1.0.0, 1.2.3, 2.0.0-beta, etc.)
|
""",
|
||||||
INSERT INTO package_versions (package_id, artifact_id, version, version_source, created_by, created_at)
|
),
|
||||||
SELECT
|
Migration(
|
||||||
t.package_id,
|
name="009_create_version_ref_count_functions",
|
||||||
t.artifact_id,
|
sql="""
|
||||||
CASE WHEN t.name LIKE 'v%' THEN substring(t.name from 2) ELSE t.name END,
|
CREATE OR REPLACE FUNCTION increment_version_ref_count()
|
||||||
'migrated_from_tag',
|
RETURNS TRIGGER AS $$
|
||||||
t.created_by,
|
BEGIN
|
||||||
t.created_at
|
UPDATE artifacts SET ref_count = ref_count + 1 WHERE id = NEW.artifact_id;
|
||||||
FROM tags t
|
RETURN NEW;
|
||||||
WHERE t.name ~ '^v?[0-9]+\.[0-9]+(\.[0-9]+)?([-.][a-zA-Z0-9]+)?$'
|
END;
|
||||||
ON CONFLICT (package_id, version) DO NOTHING;
|
$$ LANGUAGE plpgsql;
|
||||||
END IF;
|
|
||||||
END $$;
|
CREATE OR REPLACE FUNCTION decrement_version_ref_count()
|
||||||
""",
|
RETURNS TRIGGER AS $$
|
||||||
|
BEGIN
|
||||||
|
UPDATE artifacts SET ref_count = ref_count - 1 WHERE id = OLD.artifact_id;
|
||||||
|
RETURN OLD;
|
||||||
|
END;
|
||||||
|
$$ LANGUAGE plpgsql;
|
||||||
|
""",
|
||||||
|
),
|
||||||
|
Migration(
|
||||||
|
name="010_create_package_versions_triggers",
|
||||||
|
sql="""
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'package_versions') THEN
|
||||||
|
DROP TRIGGER IF EXISTS package_versions_ref_count_insert ON package_versions;
|
||||||
|
CREATE TRIGGER package_versions_ref_count_insert
|
||||||
|
AFTER INSERT ON package_versions
|
||||||
|
FOR EACH ROW
|
||||||
|
EXECUTE FUNCTION increment_version_ref_count();
|
||||||
|
|
||||||
|
DROP TRIGGER IF EXISTS package_versions_ref_count_delete ON package_versions;
|
||||||
|
CREATE TRIGGER package_versions_ref_count_delete
|
||||||
|
AFTER DELETE ON package_versions
|
||||||
|
FOR EACH ROW
|
||||||
|
EXECUTE FUNCTION decrement_version_ref_count();
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
""",
|
||||||
|
),
|
||||||
|
Migration(
|
||||||
|
name="011_migrate_semver_tags_to_versions",
|
||||||
|
sql=r"""
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'package_versions') THEN
|
||||||
|
INSERT INTO package_versions (id, package_id, artifact_id, version, version_source, created_by, created_at)
|
||||||
|
SELECT
|
||||||
|
gen_random_uuid(),
|
||||||
|
t.package_id,
|
||||||
|
t.artifact_id,
|
||||||
|
CASE WHEN t.name LIKE 'v%' THEN substring(t.name from 2) ELSE t.name END,
|
||||||
|
'migrated_from_tag',
|
||||||
|
t.created_by,
|
||||||
|
t.created_at
|
||||||
|
FROM tags t
|
||||||
|
WHERE t.name ~ '^v?[0-9]+\.[0-9]+(\.[0-9]+)?([-.][a-zA-Z0-9]+)?$'
|
||||||
|
ON CONFLICT (package_id, version) DO NOTHING;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
""",
|
||||||
|
),
|
||||||
|
Migration(
|
||||||
|
name="012_create_teams_table",
|
||||||
|
sql="""
|
||||||
|
CREATE TABLE IF NOT EXISTS teams (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
name VARCHAR(255) NOT NULL,
|
||||||
|
slug VARCHAR(255) NOT NULL UNIQUE,
|
||||||
|
description TEXT,
|
||||||
|
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||||
|
created_by VARCHAR(255) NOT NULL,
|
||||||
|
settings JSONB DEFAULT '{}'
|
||||||
|
);
|
||||||
|
""",
|
||||||
|
),
|
||||||
|
Migration(
|
||||||
|
name="013_create_team_memberships_table",
|
||||||
|
sql="""
|
||||||
|
CREATE TABLE IF NOT EXISTS team_memberships (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
team_id UUID NOT NULL REFERENCES teams(id) ON DELETE CASCADE,
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
role VARCHAR(50) NOT NULL DEFAULT 'member',
|
||||||
|
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||||
|
invited_by VARCHAR(255),
|
||||||
|
CONSTRAINT team_memberships_unique UNIQUE (team_id, user_id),
|
||||||
|
CONSTRAINT team_memberships_role_check CHECK (role IN ('owner', 'admin', 'member'))
|
||||||
|
);
|
||||||
|
""",
|
||||||
|
),
|
||||||
|
Migration(
|
||||||
|
name="014_add_team_id_to_projects",
|
||||||
|
sql="""
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'projects' AND column_name = 'team_id'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE projects ADD COLUMN team_id UUID REFERENCES teams(id) ON DELETE SET NULL;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_projects_team_id ON projects(team_id);
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
""",
|
||||||
|
),
|
||||||
|
Migration(
|
||||||
|
name="015_add_teams_indexes",
|
||||||
|
sql="""
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM pg_indexes WHERE indexname = 'idx_teams_slug') THEN
|
||||||
|
CREATE INDEX idx_teams_slug ON teams(slug);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM pg_indexes WHERE indexname = 'idx_teams_created_by') THEN
|
||||||
|
CREATE INDEX idx_teams_created_by ON teams(created_by);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM pg_indexes WHERE indexname = 'idx_team_memberships_team_id') THEN
|
||||||
|
CREATE INDEX idx_team_memberships_team_id ON team_memberships(team_id);
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT 1 FROM pg_indexes WHERE indexname = 'idx_team_memberships_user_id') THEN
|
||||||
|
CREATE INDEX idx_team_memberships_user_id ON team_memberships(user_id);
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
""",
|
||||||
|
),
|
||||||
|
Migration(
|
||||||
|
name="016_add_is_system_to_projects",
|
||||||
|
sql="""
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'projects' AND column_name = 'is_system'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE projects ADD COLUMN is_system BOOLEAN NOT NULL DEFAULT FALSE;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_projects_is_system ON projects(is_system);
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
""",
|
||||||
|
),
|
||||||
|
Migration(
|
||||||
|
name="017_create_upstream_sources",
|
||||||
|
sql="""
|
||||||
|
CREATE TABLE IF NOT EXISTS upstream_sources (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
name VARCHAR(255) NOT NULL UNIQUE,
|
||||||
|
source_type VARCHAR(50) NOT NULL DEFAULT 'generic',
|
||||||
|
url VARCHAR(2048) NOT NULL,
|
||||||
|
enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
auth_type VARCHAR(20) NOT NULL DEFAULT 'none',
|
||||||
|
username VARCHAR(255),
|
||||||
|
password_encrypted BYTEA,
|
||||||
|
headers_encrypted BYTEA,
|
||||||
|
priority INTEGER NOT NULL DEFAULT 100,
|
||||||
|
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||||
|
CONSTRAINT check_source_type CHECK (
|
||||||
|
source_type IN ('npm', 'pypi', 'maven', 'docker', 'helm', 'nuget', 'deb', 'rpm', 'generic')
|
||||||
|
),
|
||||||
|
CONSTRAINT check_auth_type CHECK (
|
||||||
|
auth_type IN ('none', 'basic', 'bearer', 'api_key')
|
||||||
|
),
|
||||||
|
CONSTRAINT check_priority_positive CHECK (priority > 0)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_upstream_sources_enabled ON upstream_sources(enabled);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_upstream_sources_source_type ON upstream_sources(source_type);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_upstream_sources_priority ON upstream_sources(priority);
|
||||||
|
""",
|
||||||
|
),
|
||||||
|
Migration(
|
||||||
|
name="018_create_cache_settings",
|
||||||
|
sql="""
|
||||||
|
CREATE TABLE IF NOT EXISTS cache_settings (
|
||||||
|
id INTEGER PRIMARY KEY DEFAULT 1,
|
||||||
|
auto_create_system_projects BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||||
|
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
|
||||||
|
CONSTRAINT check_cache_settings_singleton CHECK (id = 1)
|
||||||
|
);
|
||||||
|
INSERT INTO cache_settings (id, auto_create_system_projects)
|
||||||
|
VALUES (1, TRUE)
|
||||||
|
ON CONFLICT (id) DO NOTHING;
|
||||||
|
""",
|
||||||
|
),
|
||||||
|
Migration(
|
||||||
|
name="019_create_cached_urls",
|
||||||
|
sql="""
|
||||||
|
CREATE TABLE IF NOT EXISTS cached_urls (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
url VARCHAR(4096) NOT NULL,
|
||||||
|
url_hash VARCHAR(64) NOT NULL UNIQUE,
|
||||||
|
artifact_id VARCHAR(64) NOT NULL REFERENCES artifacts(id),
|
||||||
|
source_id UUID REFERENCES upstream_sources(id) ON DELETE SET NULL,
|
||||||
|
fetched_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
|
||||||
|
response_headers JSONB DEFAULT '{}',
|
||||||
|
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_cached_urls_url_hash ON cached_urls(url_hash);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_cached_urls_artifact_id ON cached_urls(artifact_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_cached_urls_source_id ON cached_urls(source_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_cached_urls_fetched_at ON cached_urls(fetched_at);
|
||||||
|
""",
|
||||||
|
),
|
||||||
|
Migration(
|
||||||
|
name="020_seed_default_upstream_sources",
|
||||||
|
sql="""
|
||||||
|
-- Originally seeded public sources, but these are no longer used.
|
||||||
|
-- Migration 023 deletes any previously seeded sources.
|
||||||
|
-- This migration is now a no-op for fresh installs.
|
||||||
|
SELECT 1;
|
||||||
|
""",
|
||||||
|
),
|
||||||
|
Migration(
|
||||||
|
name="021_remove_is_public_from_upstream_sources",
|
||||||
|
sql="""
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
-- Drop the index if it exists
|
||||||
|
DROP INDEX IF EXISTS idx_upstream_sources_is_public;
|
||||||
|
|
||||||
|
-- Drop the column if it exists
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'upstream_sources' AND column_name = 'is_public'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE upstream_sources DROP COLUMN is_public;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
""",
|
||||||
|
),
|
||||||
|
Migration(
|
||||||
|
name="022_remove_allow_public_internet_from_cache_settings",
|
||||||
|
sql="""
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'cache_settings' AND column_name = 'allow_public_internet'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE cache_settings DROP COLUMN allow_public_internet;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
""",
|
||||||
|
),
|
||||||
|
Migration(
|
||||||
|
name="023_delete_seeded_public_sources",
|
||||||
|
sql="""
|
||||||
|
-- Delete the seeded public sources that were added by migration 020
|
||||||
|
DELETE FROM upstream_sources
|
||||||
|
WHERE name IN ('npm-public', 'pypi-public', 'maven-central', 'docker-hub');
|
||||||
|
""",
|
||||||
|
),
|
||||||
]
|
]
|
||||||
|
|
||||||
with engine.connect() as conn:
|
with engine.connect() as conn:
|
||||||
|
# Ensure migrations tracking table exists
|
||||||
|
_ensure_migrations_table(conn)
|
||||||
|
|
||||||
|
# Get already-applied migrations
|
||||||
|
applied = _get_applied_migrations(conn)
|
||||||
|
|
||||||
for migration in migrations:
|
for migration in migrations:
|
||||||
|
checksum = _compute_checksum(migration.sql)
|
||||||
|
|
||||||
|
# Check if migration was already applied
|
||||||
|
if migration.name in applied:
|
||||||
|
stored_checksum = applied[migration.name]
|
||||||
|
if stored_checksum != checksum:
|
||||||
|
logger.warning(
|
||||||
|
f"Migration '{migration.name}' has changed since it was applied! "
|
||||||
|
f"Stored checksum: {stored_checksum}, current: {checksum}"
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
|
# Run the migration
|
||||||
try:
|
try:
|
||||||
conn.execute(text(migration))
|
logger.info(f"Running migration: {migration.name}")
|
||||||
|
conn.execute(text(migration.sql))
|
||||||
conn.commit()
|
conn.commit()
|
||||||
|
_record_migration(conn, migration.name, checksum)
|
||||||
|
logger.info(f"Migration '{migration.name}' applied successfully")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(f"Migration failed (may already be applied): {e}")
|
conn.rollback()
|
||||||
|
if _is_safe_error(e):
|
||||||
|
# Migration was already applied (schema already exists)
|
||||||
|
logger.info(
|
||||||
|
f"Migration '{migration.name}' already applied (schema exists), recording as complete"
|
||||||
|
)
|
||||||
|
_record_migration(conn, migration.name, checksum)
|
||||||
|
else:
|
||||||
|
# Real error - fail hard
|
||||||
|
logger.error(f"Migration '{migration.name}' failed: {e}")
|
||||||
|
raise RuntimeError(
|
||||||
|
f"Migration '{migration.name}' failed with error: {e}"
|
||||||
|
) from e
|
||||||
|
|
||||||
|
|
||||||
def get_db() -> Generator[Session, None, None]:
|
def get_db() -> Generator[Session, None, None]:
|
||||||
|
|||||||
160
backend/app/encryption.py
Normal file
160
backend/app/encryption.py
Normal file
@@ -0,0 +1,160 @@
|
|||||||
|
"""
|
||||||
|
Encryption utilities for sensitive data storage.
|
||||||
|
|
||||||
|
Uses Fernet symmetric encryption for credentials like upstream passwords.
|
||||||
|
The encryption key is sourced from ORCHARD_CACHE_ENCRYPTION_KEY environment variable.
|
||||||
|
If not set, a random key is generated on startup (with a warning).
|
||||||
|
"""
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import secrets
|
||||||
|
from functools import lru_cache
|
||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from cryptography.fernet import Fernet, InvalidToken
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Module-level storage for auto-generated key (only used if env var not set)
|
||||||
|
_generated_key: Optional[bytes] = None
|
||||||
|
|
||||||
|
|
||||||
|
def _get_key_from_env() -> Optional[bytes]:
|
||||||
|
"""Get encryption key from environment variable."""
|
||||||
|
key_str = os.environ.get("ORCHARD_CACHE_ENCRYPTION_KEY", "")
|
||||||
|
if not key_str:
|
||||||
|
return None
|
||||||
|
|
||||||
|
# Support both raw base64 and url-safe base64 formats
|
||||||
|
try:
|
||||||
|
# Try to decode as-is (Fernet keys are url-safe base64)
|
||||||
|
key_bytes = key_str.encode("utf-8")
|
||||||
|
# Validate it's a valid Fernet key by trying to create a Fernet instance
|
||||||
|
Fernet(key_bytes)
|
||||||
|
return key_bytes
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# Try base64 decoding if it's a raw 32-byte key encoded as base64
|
||||||
|
try:
|
||||||
|
decoded = base64.urlsafe_b64decode(key_str)
|
||||||
|
if len(decoded) == 32:
|
||||||
|
# Re-encode as url-safe base64 for Fernet
|
||||||
|
key_bytes = base64.urlsafe_b64encode(decoded)
|
||||||
|
Fernet(key_bytes)
|
||||||
|
return key_bytes
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
logger.error(
|
||||||
|
"ORCHARD_CACHE_ENCRYPTION_KEY is set but invalid. "
|
||||||
|
"Must be a valid Fernet key (32 bytes, url-safe base64 encoded). "
|
||||||
|
"Generate one with: python -c \"from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())\""
|
||||||
|
)
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def get_encryption_key() -> bytes:
|
||||||
|
"""
|
||||||
|
Get the Fernet encryption key.
|
||||||
|
|
||||||
|
Returns the key from ORCHARD_CACHE_ENCRYPTION_KEY if set and valid,
|
||||||
|
otherwise generates a random key (with a warning logged).
|
||||||
|
|
||||||
|
The generated key is cached for the lifetime of the process.
|
||||||
|
"""
|
||||||
|
global _generated_key
|
||||||
|
|
||||||
|
# Try to get from environment
|
||||||
|
env_key = _get_key_from_env()
|
||||||
|
if env_key:
|
||||||
|
return env_key
|
||||||
|
|
||||||
|
# Generate a new key if needed
|
||||||
|
if _generated_key is None:
|
||||||
|
_generated_key = Fernet.generate_key()
|
||||||
|
logger.warning(
|
||||||
|
"ORCHARD_CACHE_ENCRYPTION_KEY not set - using auto-generated key. "
|
||||||
|
"Encrypted credentials will be lost on restart! "
|
||||||
|
"Set ORCHARD_CACHE_ENCRYPTION_KEY for persistent encryption. "
|
||||||
|
"Generate a key with: python -c \"from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())\""
|
||||||
|
)
|
||||||
|
|
||||||
|
return _generated_key
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache(maxsize=1)
|
||||||
|
def _get_fernet() -> Fernet:
|
||||||
|
"""Get a cached Fernet instance."""
|
||||||
|
return Fernet(get_encryption_key())
|
||||||
|
|
||||||
|
|
||||||
|
def encrypt_value(plaintext: str) -> bytes:
|
||||||
|
"""
|
||||||
|
Encrypt a string value using Fernet.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
plaintext: The string to encrypt
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Encrypted bytes (includes Fernet token with timestamp)
|
||||||
|
"""
|
||||||
|
if not plaintext:
|
||||||
|
raise ValueError("Cannot encrypt empty value")
|
||||||
|
|
||||||
|
fernet = _get_fernet()
|
||||||
|
return fernet.encrypt(plaintext.encode("utf-8"))
|
||||||
|
|
||||||
|
|
||||||
|
def decrypt_value(ciphertext: bytes) -> str:
|
||||||
|
"""
|
||||||
|
Decrypt a Fernet-encrypted value.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
ciphertext: The encrypted bytes
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Decrypted string
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
InvalidToken: If decryption fails (wrong key or corrupted data)
|
||||||
|
"""
|
||||||
|
if not ciphertext:
|
||||||
|
raise ValueError("Cannot decrypt empty value")
|
||||||
|
|
||||||
|
fernet = _get_fernet()
|
||||||
|
return fernet.decrypt(ciphertext).decode("utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
def can_decrypt(ciphertext: bytes) -> bool:
|
||||||
|
"""
|
||||||
|
Check if a value can be decrypted with the current key.
|
||||||
|
|
||||||
|
Useful for checking if credentials are still valid after key rotation.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
ciphertext: The encrypted bytes
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True if decryption succeeds, False otherwise
|
||||||
|
"""
|
||||||
|
if not ciphertext:
|
||||||
|
return False
|
||||||
|
|
||||||
|
try:
|
||||||
|
decrypt_value(ciphertext)
|
||||||
|
return True
|
||||||
|
except (InvalidToken, ValueError):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def generate_key() -> str:
|
||||||
|
"""
|
||||||
|
Generate a new Fernet encryption key.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
A valid Fernet key as a string (url-safe base64 encoded)
|
||||||
|
"""
|
||||||
|
return Fernet.generate_key().decode("utf-8")
|
||||||
@@ -12,6 +12,7 @@ from sqlalchemy import (
|
|||||||
Index,
|
Index,
|
||||||
JSON,
|
JSON,
|
||||||
ARRAY,
|
ARRAY,
|
||||||
|
LargeBinary,
|
||||||
)
|
)
|
||||||
from sqlalchemy.dialects.postgresql import UUID
|
from sqlalchemy.dialects.postgresql import UUID
|
||||||
from sqlalchemy.orm import relationship, declarative_base
|
from sqlalchemy.orm import relationship, declarative_base
|
||||||
@@ -27,11 +28,13 @@ class Project(Base):
|
|||||||
name = Column(String(255), unique=True, nullable=False)
|
name = Column(String(255), unique=True, nullable=False)
|
||||||
description = Column(Text)
|
description = Column(Text)
|
||||||
is_public = Column(Boolean, default=True)
|
is_public = Column(Boolean, default=True)
|
||||||
|
is_system = Column(Boolean, default=False, nullable=False)
|
||||||
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
||||||
updated_at = Column(
|
updated_at = Column(
|
||||||
DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow
|
DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow
|
||||||
)
|
)
|
||||||
created_by = Column(String(255), nullable=False)
|
created_by = Column(String(255), nullable=False)
|
||||||
|
team_id = Column(UUID(as_uuid=True), ForeignKey("teams.id", ondelete="SET NULL"))
|
||||||
|
|
||||||
packages = relationship(
|
packages = relationship(
|
||||||
"Package", back_populates="project", cascade="all, delete-orphan"
|
"Package", back_populates="project", cascade="all, delete-orphan"
|
||||||
@@ -39,10 +42,13 @@ class Project(Base):
|
|||||||
permissions = relationship(
|
permissions = relationship(
|
||||||
"AccessPermission", back_populates="project", cascade="all, delete-orphan"
|
"AccessPermission", back_populates="project", cascade="all, delete-orphan"
|
||||||
)
|
)
|
||||||
|
team = relationship("Team", back_populates="projects")
|
||||||
|
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
Index("idx_projects_name", "name"),
|
Index("idx_projects_name", "name"),
|
||||||
Index("idx_projects_created_by", "created_by"),
|
Index("idx_projects_created_by", "created_by"),
|
||||||
|
Index("idx_projects_team_id", "team_id"),
|
||||||
|
Index("idx_projects_is_system", "is_system"),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -369,6 +375,9 @@ class User(Base):
|
|||||||
sessions = relationship(
|
sessions = relationship(
|
||||||
"Session", back_populates="user", cascade="all, delete-orphan"
|
"Session", back_populates="user", cascade="all, delete-orphan"
|
||||||
)
|
)
|
||||||
|
team_memberships = relationship(
|
||||||
|
"TeamMembership", back_populates="user", cascade="all, delete-orphan"
|
||||||
|
)
|
||||||
|
|
||||||
__table_args__ = (
|
__table_args__ = (
|
||||||
Index("idx_users_username", "username"),
|
Index("idx_users_username", "username"),
|
||||||
@@ -561,3 +570,236 @@ class ArtifactDependency(Base):
|
|||||||
unique=True,
|
unique=True,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class Team(Base):
|
||||||
|
"""Team for organizing projects and users."""
|
||||||
|
|
||||||
|
__tablename__ = "teams"
|
||||||
|
|
||||||
|
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||||
|
name = Column(String(255), nullable=False)
|
||||||
|
slug = Column(String(255), unique=True, nullable=False)
|
||||||
|
description = Column(Text)
|
||||||
|
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
||||||
|
updated_at = Column(
|
||||||
|
DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow
|
||||||
|
)
|
||||||
|
created_by = Column(String(255), nullable=False)
|
||||||
|
settings = Column(JSON, default=dict)
|
||||||
|
|
||||||
|
# Relationships
|
||||||
|
memberships = relationship(
|
||||||
|
"TeamMembership", back_populates="team", cascade="all, delete-orphan"
|
||||||
|
)
|
||||||
|
projects = relationship("Project", back_populates="team")
|
||||||
|
|
||||||
|
__table_args__ = (
|
||||||
|
Index("idx_teams_slug", "slug"),
|
||||||
|
Index("idx_teams_created_by", "created_by"),
|
||||||
|
Index("idx_teams_created_at", "created_at"),
|
||||||
|
CheckConstraint(
|
||||||
|
"slug ~ '^[a-z0-9][a-z0-9-]*[a-z0-9]$' OR slug ~ '^[a-z0-9]$'",
|
||||||
|
name="check_team_slug_format",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class TeamMembership(Base):
|
||||||
|
"""Maps users to teams with their roles."""
|
||||||
|
|
||||||
|
__tablename__ = "team_memberships"
|
||||||
|
|
||||||
|
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||||
|
team_id = Column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("teams.id", ondelete="CASCADE"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
user_id = Column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("users.id", ondelete="CASCADE"),
|
||||||
|
nullable=False,
|
||||||
|
)
|
||||||
|
role = Column(String(20), nullable=False, default="member")
|
||||||
|
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
||||||
|
invited_by = Column(String(255))
|
||||||
|
|
||||||
|
# Relationships
|
||||||
|
team = relationship("Team", back_populates="memberships")
|
||||||
|
user = relationship("User", back_populates="team_memberships")
|
||||||
|
|
||||||
|
__table_args__ = (
|
||||||
|
Index("idx_team_memberships_team_id", "team_id"),
|
||||||
|
Index("idx_team_memberships_user_id", "user_id"),
|
||||||
|
Index("idx_team_memberships_role", "role"),
|
||||||
|
Index("idx_team_memberships_team_role", "team_id", "role"),
|
||||||
|
Index("idx_team_memberships_unique", "team_id", "user_id", unique=True),
|
||||||
|
CheckConstraint(
|
||||||
|
"role IN ('owner', 'admin', 'member')",
|
||||||
|
name="check_team_role",
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
# =============================================================================
|
||||||
|
# Upstream Caching Models
|
||||||
|
# =============================================================================
|
||||||
|
|
||||||
|
# Valid source types for upstream registries
|
||||||
|
SOURCE_TYPES = ["npm", "pypi", "maven", "docker", "helm", "nuget", "deb", "rpm", "generic"]
|
||||||
|
|
||||||
|
# Valid authentication types
|
||||||
|
AUTH_TYPES = ["none", "basic", "bearer", "api_key"]
|
||||||
|
|
||||||
|
|
||||||
|
class UpstreamSource(Base):
|
||||||
|
"""Configuration for an upstream artifact registry.
|
||||||
|
|
||||||
|
Stores connection details and authentication for upstream registries
|
||||||
|
like npm, PyPI, Maven Central, or private Artifactory instances.
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = "upstream_sources"
|
||||||
|
|
||||||
|
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||||
|
name = Column(String(255), unique=True, nullable=False)
|
||||||
|
source_type = Column(String(50), default="generic", nullable=False)
|
||||||
|
url = Column(String(2048), nullable=False)
|
||||||
|
enabled = Column(Boolean, default=False, nullable=False)
|
||||||
|
auth_type = Column(String(20), default="none", nullable=False)
|
||||||
|
username = Column(String(255))
|
||||||
|
password_encrypted = Column(LargeBinary)
|
||||||
|
headers_encrypted = Column(LargeBinary)
|
||||||
|
priority = Column(Integer, default=100, nullable=False)
|
||||||
|
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
||||||
|
updated_at = Column(
|
||||||
|
DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow
|
||||||
|
)
|
||||||
|
|
||||||
|
# Relationships
|
||||||
|
cached_urls = relationship("CachedUrl", back_populates="source")
|
||||||
|
|
||||||
|
__table_args__ = (
|
||||||
|
Index("idx_upstream_sources_enabled", "enabled"),
|
||||||
|
Index("idx_upstream_sources_source_type", "source_type"),
|
||||||
|
Index("idx_upstream_sources_priority", "priority"),
|
||||||
|
CheckConstraint(
|
||||||
|
"source_type IN ('npm', 'pypi', 'maven', 'docker', 'helm', 'nuget', 'deb', 'rpm', 'generic')",
|
||||||
|
name="check_source_type",
|
||||||
|
),
|
||||||
|
CheckConstraint(
|
||||||
|
"auth_type IN ('none', 'basic', 'bearer', 'api_key')",
|
||||||
|
name="check_auth_type",
|
||||||
|
),
|
||||||
|
CheckConstraint("priority > 0", name="check_priority_positive"),
|
||||||
|
)
|
||||||
|
|
||||||
|
def set_password(self, password: str) -> None:
|
||||||
|
"""Encrypt and store a password/token."""
|
||||||
|
from .encryption import encrypt_value
|
||||||
|
|
||||||
|
if password:
|
||||||
|
self.password_encrypted = encrypt_value(password)
|
||||||
|
else:
|
||||||
|
self.password_encrypted = None
|
||||||
|
|
||||||
|
def get_password(self) -> str | None:
|
||||||
|
"""Decrypt and return the stored password/token."""
|
||||||
|
from .encryption import decrypt_value
|
||||||
|
|
||||||
|
if self.password_encrypted:
|
||||||
|
try:
|
||||||
|
return decrypt_value(self.password_encrypted)
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
return None
|
||||||
|
|
||||||
|
def has_password(self) -> bool:
|
||||||
|
"""Check if a password/token is stored."""
|
||||||
|
return self.password_encrypted is not None
|
||||||
|
|
||||||
|
def set_headers(self, headers: dict) -> None:
|
||||||
|
"""Encrypt and store custom headers as JSON."""
|
||||||
|
from .encryption import encrypt_value
|
||||||
|
import json
|
||||||
|
|
||||||
|
if headers:
|
||||||
|
self.headers_encrypted = encrypt_value(json.dumps(headers))
|
||||||
|
else:
|
||||||
|
self.headers_encrypted = None
|
||||||
|
|
||||||
|
def get_headers(self) -> dict | None:
|
||||||
|
"""Decrypt and return custom headers."""
|
||||||
|
from .encryption import decrypt_value
|
||||||
|
import json
|
||||||
|
|
||||||
|
if self.headers_encrypted:
|
||||||
|
try:
|
||||||
|
return json.loads(decrypt_value(self.headers_encrypted))
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class CacheSettings(Base):
|
||||||
|
"""Global cache settings (singleton table).
|
||||||
|
|
||||||
|
Controls behavior of the upstream caching system.
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = "cache_settings"
|
||||||
|
|
||||||
|
id = Column(Integer, primary_key=True, default=1)
|
||||||
|
auto_create_system_projects = Column(Boolean, default=True, nullable=False)
|
||||||
|
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
||||||
|
updated_at = Column(
|
||||||
|
DateTime(timezone=True), default=datetime.utcnow, onupdate=datetime.utcnow
|
||||||
|
)
|
||||||
|
|
||||||
|
__table_args__ = (
|
||||||
|
CheckConstraint("id = 1", name="check_cache_settings_singleton"),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class CachedUrl(Base):
|
||||||
|
"""Tracks URL to artifact mappings for provenance.
|
||||||
|
|
||||||
|
Records which URLs have been cached and maps them to their stored artifacts.
|
||||||
|
Enables "is this URL already cached?" lookups and audit trails.
|
||||||
|
"""
|
||||||
|
|
||||||
|
__tablename__ = "cached_urls"
|
||||||
|
|
||||||
|
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
|
||||||
|
url = Column(String(4096), nullable=False)
|
||||||
|
url_hash = Column(String(64), unique=True, nullable=False)
|
||||||
|
artifact_id = Column(
|
||||||
|
String(64), ForeignKey("artifacts.id"), nullable=False
|
||||||
|
)
|
||||||
|
source_id = Column(
|
||||||
|
UUID(as_uuid=True),
|
||||||
|
ForeignKey("upstream_sources.id", ondelete="SET NULL"),
|
||||||
|
)
|
||||||
|
fetched_at = Column(DateTime(timezone=True), default=datetime.utcnow, nullable=False)
|
||||||
|
response_headers = Column(JSON, default=dict)
|
||||||
|
created_at = Column(DateTime(timezone=True), default=datetime.utcnow)
|
||||||
|
|
||||||
|
# Relationships
|
||||||
|
artifact = relationship("Artifact")
|
||||||
|
source = relationship("UpstreamSource", back_populates="cached_urls")
|
||||||
|
|
||||||
|
__table_args__ = (
|
||||||
|
Index("idx_cached_urls_url_hash", "url_hash"),
|
||||||
|
Index("idx_cached_urls_artifact_id", "artifact_id"),
|
||||||
|
Index("idx_cached_urls_source_id", "source_id"),
|
||||||
|
Index("idx_cached_urls_fetched_at", "fetched_at"),
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def compute_url_hash(url: str) -> str:
|
||||||
|
"""Compute SHA256 hash of a URL for fast lookups."""
|
||||||
|
import hashlib
|
||||||
|
return hashlib.sha256(url.encode("utf-8")).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
212
backend/app/purge_seed_data.py
Normal file
212
backend/app/purge_seed_data.py
Normal file
@@ -0,0 +1,212 @@
|
|||||||
|
"""
|
||||||
|
Purge seed/demo data from the database.
|
||||||
|
|
||||||
|
This is used when transitioning an environment from dev/test to production-like.
|
||||||
|
Triggered by setting ORCHARD_PURGE_SEED_DATA=true environment variable.
|
||||||
|
"""
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from .models import (
|
||||||
|
Project,
|
||||||
|
Package,
|
||||||
|
Artifact,
|
||||||
|
Tag,
|
||||||
|
Upload,
|
||||||
|
PackageVersion,
|
||||||
|
ArtifactDependency,
|
||||||
|
Team,
|
||||||
|
TeamMembership,
|
||||||
|
User,
|
||||||
|
AccessPermission,
|
||||||
|
)
|
||||||
|
from .storage import get_storage
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
# Seed data identifiers (from seed.py)
|
||||||
|
SEED_PROJECT_NAMES = [
|
||||||
|
"frontend-libs",
|
||||||
|
"backend-services",
|
||||||
|
"mobile-apps",
|
||||||
|
"internal-tools",
|
||||||
|
]
|
||||||
|
|
||||||
|
SEED_TEAM_SLUG = "demo-team"
|
||||||
|
|
||||||
|
SEED_USERNAMES = [
|
||||||
|
"alice",
|
||||||
|
"bob",
|
||||||
|
"charlie",
|
||||||
|
"diana",
|
||||||
|
"eve",
|
||||||
|
"frank",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def should_purge_seed_data() -> bool:
|
||||||
|
"""Check if seed data should be purged based on environment variable."""
|
||||||
|
return os.environ.get("ORCHARD_PURGE_SEED_DATA", "").lower() == "true"
|
||||||
|
|
||||||
|
|
||||||
|
def purge_seed_data(db: Session) -> dict:
|
||||||
|
"""
|
||||||
|
Purge all seed/demo data from the database.
|
||||||
|
|
||||||
|
Returns a dict with counts of deleted items.
|
||||||
|
"""
|
||||||
|
logger.warning("PURGING SEED DATA - This will delete demo projects, users, and teams")
|
||||||
|
|
||||||
|
results = {
|
||||||
|
"dependencies_deleted": 0,
|
||||||
|
"tags_deleted": 0,
|
||||||
|
"versions_deleted": 0,
|
||||||
|
"uploads_deleted": 0,
|
||||||
|
"artifacts_deleted": 0,
|
||||||
|
"packages_deleted": 0,
|
||||||
|
"projects_deleted": 0,
|
||||||
|
"permissions_deleted": 0,
|
||||||
|
"team_memberships_deleted": 0,
|
||||||
|
"users_deleted": 0,
|
||||||
|
"teams_deleted": 0,
|
||||||
|
"s3_objects_deleted": 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
storage = get_storage()
|
||||||
|
|
||||||
|
# Find seed projects
|
||||||
|
seed_projects = db.query(Project).filter(Project.name.in_(SEED_PROJECT_NAMES)).all()
|
||||||
|
seed_project_ids = [p.id for p in seed_projects]
|
||||||
|
|
||||||
|
if not seed_projects:
|
||||||
|
logger.info("No seed projects found, nothing to purge")
|
||||||
|
return results
|
||||||
|
|
||||||
|
logger.info(f"Found {len(seed_projects)} seed projects to purge")
|
||||||
|
|
||||||
|
# Find packages in seed projects
|
||||||
|
seed_packages = db.query(Package).filter(Package.project_id.in_(seed_project_ids)).all()
|
||||||
|
seed_package_ids = [p.id for p in seed_packages]
|
||||||
|
|
||||||
|
# Find artifacts in seed packages (via uploads)
|
||||||
|
seed_uploads = db.query(Upload).filter(Upload.package_id.in_(seed_package_ids)).all()
|
||||||
|
seed_artifact_ids = list(set(u.artifact_id for u in seed_uploads))
|
||||||
|
|
||||||
|
# Delete in order (respecting foreign keys)
|
||||||
|
|
||||||
|
# 1. Delete artifact dependencies
|
||||||
|
if seed_artifact_ids:
|
||||||
|
count = db.query(ArtifactDependency).filter(
|
||||||
|
ArtifactDependency.artifact_id.in_(seed_artifact_ids)
|
||||||
|
).delete(synchronize_session=False)
|
||||||
|
results["dependencies_deleted"] = count
|
||||||
|
logger.info(f"Deleted {count} artifact dependencies")
|
||||||
|
|
||||||
|
# 2. Delete tags
|
||||||
|
if seed_package_ids:
|
||||||
|
count = db.query(Tag).filter(Tag.package_id.in_(seed_package_ids)).delete(
|
||||||
|
synchronize_session=False
|
||||||
|
)
|
||||||
|
results["tags_deleted"] = count
|
||||||
|
logger.info(f"Deleted {count} tags")
|
||||||
|
|
||||||
|
# 3. Delete package versions
|
||||||
|
if seed_package_ids:
|
||||||
|
count = db.query(PackageVersion).filter(
|
||||||
|
PackageVersion.package_id.in_(seed_package_ids)
|
||||||
|
).delete(synchronize_session=False)
|
||||||
|
results["versions_deleted"] = count
|
||||||
|
logger.info(f"Deleted {count} package versions")
|
||||||
|
|
||||||
|
# 4. Delete uploads
|
||||||
|
if seed_package_ids:
|
||||||
|
count = db.query(Upload).filter(Upload.package_id.in_(seed_package_ids)).delete(
|
||||||
|
synchronize_session=False
|
||||||
|
)
|
||||||
|
results["uploads_deleted"] = count
|
||||||
|
logger.info(f"Deleted {count} uploads")
|
||||||
|
|
||||||
|
# 5. Delete S3 objects for seed artifacts
|
||||||
|
if seed_artifact_ids:
|
||||||
|
seed_artifacts = db.query(Artifact).filter(Artifact.id.in_(seed_artifact_ids)).all()
|
||||||
|
for artifact in seed_artifacts:
|
||||||
|
if artifact.s3_key:
|
||||||
|
try:
|
||||||
|
storage.client.delete_object(Bucket=storage.bucket, Key=artifact.s3_key)
|
||||||
|
results["s3_objects_deleted"] += 1
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning(f"Failed to delete S3 object {artifact.s3_key}: {e}")
|
||||||
|
logger.info(f"Deleted {results['s3_objects_deleted']} S3 objects")
|
||||||
|
|
||||||
|
# 6. Delete artifacts (only those with ref_count that would be 0 after our deletions)
|
||||||
|
# Since we deleted all tags/versions pointing to these artifacts, we can delete them
|
||||||
|
if seed_artifact_ids:
|
||||||
|
count = db.query(Artifact).filter(Artifact.id.in_(seed_artifact_ids)).delete(
|
||||||
|
synchronize_session=False
|
||||||
|
)
|
||||||
|
results["artifacts_deleted"] = count
|
||||||
|
logger.info(f"Deleted {count} artifacts")
|
||||||
|
|
||||||
|
# 7. Delete packages
|
||||||
|
if seed_package_ids:
|
||||||
|
count = db.query(Package).filter(Package.id.in_(seed_package_ids)).delete(
|
||||||
|
synchronize_session=False
|
||||||
|
)
|
||||||
|
results["packages_deleted"] = count
|
||||||
|
logger.info(f"Deleted {count} packages")
|
||||||
|
|
||||||
|
# 8. Delete access permissions for seed projects
|
||||||
|
if seed_project_ids:
|
||||||
|
count = db.query(AccessPermission).filter(
|
||||||
|
AccessPermission.project_id.in_(seed_project_ids)
|
||||||
|
).delete(synchronize_session=False)
|
||||||
|
results["permissions_deleted"] = count
|
||||||
|
logger.info(f"Deleted {count} access permissions")
|
||||||
|
|
||||||
|
# 9. Delete seed projects
|
||||||
|
count = db.query(Project).filter(Project.name.in_(SEED_PROJECT_NAMES)).delete(
|
||||||
|
synchronize_session=False
|
||||||
|
)
|
||||||
|
results["projects_deleted"] = count
|
||||||
|
logger.info(f"Deleted {count} projects")
|
||||||
|
|
||||||
|
# 10. Find and delete seed team
|
||||||
|
seed_team = db.query(Team).filter(Team.slug == SEED_TEAM_SLUG).first()
|
||||||
|
if seed_team:
|
||||||
|
# Delete team memberships first
|
||||||
|
count = db.query(TeamMembership).filter(
|
||||||
|
TeamMembership.team_id == seed_team.id
|
||||||
|
).delete(synchronize_session=False)
|
||||||
|
results["team_memberships_deleted"] = count
|
||||||
|
logger.info(f"Deleted {count} team memberships")
|
||||||
|
|
||||||
|
# Delete the team
|
||||||
|
db.delete(seed_team)
|
||||||
|
results["teams_deleted"] = 1
|
||||||
|
logger.info(f"Deleted team: {SEED_TEAM_SLUG}")
|
||||||
|
|
||||||
|
# 11. Delete seed users (but NOT admin)
|
||||||
|
seed_users = db.query(User).filter(User.username.in_(SEED_USERNAMES)).all()
|
||||||
|
for user in seed_users:
|
||||||
|
# Delete any remaining team memberships for this user
|
||||||
|
db.query(TeamMembership).filter(TeamMembership.user_id == user.id).delete(
|
||||||
|
synchronize_session=False
|
||||||
|
)
|
||||||
|
# Delete any access permissions for this user
|
||||||
|
# Note: AccessPermission.user_id is VARCHAR (username), not UUID
|
||||||
|
db.query(AccessPermission).filter(AccessPermission.user_id == user.username).delete(
|
||||||
|
synchronize_session=False
|
||||||
|
)
|
||||||
|
db.delete(user)
|
||||||
|
results["users_deleted"] += 1
|
||||||
|
|
||||||
|
if results["users_deleted"] > 0:
|
||||||
|
logger.info(f"Deleted {results['users_deleted']} seed users")
|
||||||
|
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
logger.warning("SEED DATA PURGE COMPLETE")
|
||||||
|
logger.info(f"Purge results: {results}")
|
||||||
|
|
||||||
|
return results
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -25,6 +25,7 @@ class ProjectCreate(BaseModel):
|
|||||||
name: str
|
name: str
|
||||||
description: Optional[str] = None
|
description: Optional[str] = None
|
||||||
is_public: bool = True
|
is_public: bool = True
|
||||||
|
team_id: Optional[UUID] = None
|
||||||
|
|
||||||
|
|
||||||
class ProjectResponse(BaseModel):
|
class ProjectResponse(BaseModel):
|
||||||
@@ -35,6 +36,9 @@ class ProjectResponse(BaseModel):
|
|||||||
created_at: datetime
|
created_at: datetime
|
||||||
updated_at: datetime
|
updated_at: datetime
|
||||||
created_by: str
|
created_by: str
|
||||||
|
team_id: Optional[UUID] = None
|
||||||
|
team_slug: Optional[str] = None
|
||||||
|
team_name: Optional[str] = None
|
||||||
|
|
||||||
class Config:
|
class Config:
|
||||||
from_attributes = True
|
from_attributes = True
|
||||||
@@ -907,6 +911,9 @@ class AccessPermissionResponse(BaseModel):
|
|||||||
level: str
|
level: str
|
||||||
created_at: datetime
|
created_at: datetime
|
||||||
expires_at: Optional[datetime]
|
expires_at: Optional[datetime]
|
||||||
|
source: Optional[str] = "explicit" # "explicit" or "team"
|
||||||
|
team_slug: Optional[str] = None # Team slug if source is "team"
|
||||||
|
team_role: Optional[str] = None # Team role if source is "team"
|
||||||
|
|
||||||
class Config:
|
class Config:
|
||||||
from_attributes = True
|
from_attributes = True
|
||||||
@@ -1053,3 +1060,376 @@ class CircularDependencyError(BaseModel):
|
|||||||
message: str
|
message: str
|
||||||
cycle: List[str] # List of "project/package" strings showing the cycle
|
cycle: List[str] # List of "project/package" strings showing the cycle
|
||||||
|
|
||||||
|
|
||||||
|
# Team schemas
|
||||||
|
TEAM_ROLES = ["owner", "admin", "member"]
|
||||||
|
RESERVED_TEAM_SLUGS = {"new", "api", "admin", "settings", "members", "projects", "search"}
|
||||||
|
|
||||||
|
|
||||||
|
class TeamCreate(BaseModel):
|
||||||
|
"""Create a new team"""
|
||||||
|
name: str
|
||||||
|
slug: str
|
||||||
|
description: Optional[str] = None
|
||||||
|
|
||||||
|
@field_validator('name')
|
||||||
|
@classmethod
|
||||||
|
def validate_name(cls, v: str) -> str:
|
||||||
|
"""Validate team name."""
|
||||||
|
if not v or not v.strip():
|
||||||
|
raise ValueError("Name cannot be empty")
|
||||||
|
if len(v) > 255:
|
||||||
|
raise ValueError("Name must be 255 characters or less")
|
||||||
|
return v.strip()
|
||||||
|
|
||||||
|
@field_validator('slug')
|
||||||
|
@classmethod
|
||||||
|
def validate_slug(cls, v: str) -> str:
|
||||||
|
"""Validate team slug format (lowercase alphanumeric with hyphens)."""
|
||||||
|
import re
|
||||||
|
if not v:
|
||||||
|
raise ValueError("Slug cannot be empty")
|
||||||
|
if len(v) < 2:
|
||||||
|
raise ValueError("Slug must be at least 2 characters")
|
||||||
|
if len(v) > 255:
|
||||||
|
raise ValueError("Slug must be 255 characters or less")
|
||||||
|
if not re.match(r'^[a-z0-9][a-z0-9-]*[a-z0-9]$', v) and not re.match(r'^[a-z0-9]$', v):
|
||||||
|
raise ValueError(
|
||||||
|
"Slug must be lowercase alphanumeric with hyphens, "
|
||||||
|
"starting and ending with alphanumeric characters"
|
||||||
|
)
|
||||||
|
if '--' in v:
|
||||||
|
raise ValueError("Slug cannot contain consecutive hyphens")
|
||||||
|
if v in RESERVED_TEAM_SLUGS:
|
||||||
|
raise ValueError(f"Slug '{v}' is reserved and cannot be used")
|
||||||
|
return v
|
||||||
|
|
||||||
|
@field_validator('description')
|
||||||
|
@classmethod
|
||||||
|
def validate_description(cls, v: Optional[str]) -> Optional[str]:
|
||||||
|
"""Validate team description."""
|
||||||
|
if v is not None and len(v) > 2000:
|
||||||
|
raise ValueError("Description must be 2000 characters or less")
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
class TeamUpdate(BaseModel):
|
||||||
|
"""Update team details"""
|
||||||
|
name: Optional[str] = None
|
||||||
|
description: Optional[str] = None
|
||||||
|
|
||||||
|
@field_validator('name')
|
||||||
|
@classmethod
|
||||||
|
def validate_name(cls, v: Optional[str]) -> Optional[str]:
|
||||||
|
"""Validate team name."""
|
||||||
|
if v is not None:
|
||||||
|
if not v.strip():
|
||||||
|
raise ValueError("Name cannot be empty")
|
||||||
|
if len(v) > 255:
|
||||||
|
raise ValueError("Name must be 255 characters or less")
|
||||||
|
return v.strip()
|
||||||
|
return v
|
||||||
|
|
||||||
|
@field_validator('description')
|
||||||
|
@classmethod
|
||||||
|
def validate_description(cls, v: Optional[str]) -> Optional[str]:
|
||||||
|
"""Validate team description."""
|
||||||
|
if v is not None and len(v) > 2000:
|
||||||
|
raise ValueError("Description must be 2000 characters or less")
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
class TeamResponse(BaseModel):
|
||||||
|
"""Team response with basic info"""
|
||||||
|
id: UUID
|
||||||
|
name: str
|
||||||
|
slug: str
|
||||||
|
description: Optional[str]
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: datetime
|
||||||
|
member_count: int = 0
|
||||||
|
project_count: int = 0
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
class TeamDetailResponse(TeamResponse):
|
||||||
|
"""Team response with user's role"""
|
||||||
|
user_role: Optional[str] = None # 'owner', 'admin', 'member', or None
|
||||||
|
|
||||||
|
|
||||||
|
class TeamMemberCreate(BaseModel):
|
||||||
|
"""Add a member to a team"""
|
||||||
|
username: str
|
||||||
|
role: str = "member"
|
||||||
|
|
||||||
|
@field_validator('role')
|
||||||
|
@classmethod
|
||||||
|
def validate_role(cls, v: str) -> str:
|
||||||
|
if v not in TEAM_ROLES:
|
||||||
|
raise ValueError(f"Role must be one of: {', '.join(TEAM_ROLES)}")
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
class TeamMemberUpdate(BaseModel):
|
||||||
|
"""Update a team member's role"""
|
||||||
|
role: str
|
||||||
|
|
||||||
|
@field_validator('role')
|
||||||
|
@classmethod
|
||||||
|
def validate_role(cls, v: str) -> str:
|
||||||
|
if v not in TEAM_ROLES:
|
||||||
|
raise ValueError(f"Role must be one of: {', '.join(TEAM_ROLES)}")
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
class TeamMemberResponse(BaseModel):
|
||||||
|
"""Team member response"""
|
||||||
|
id: UUID
|
||||||
|
user_id: UUID
|
||||||
|
username: str
|
||||||
|
email: Optional[str]
|
||||||
|
role: str
|
||||||
|
created_at: datetime
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
# =============================================================================
|
||||||
|
# Upstream Caching Schemas
|
||||||
|
# =============================================================================
|
||||||
|
|
||||||
|
# Valid source types
|
||||||
|
SOURCE_TYPES = ["npm", "pypi", "maven", "docker", "helm", "nuget", "deb", "rpm", "generic"]
|
||||||
|
|
||||||
|
# Valid auth types
|
||||||
|
AUTH_TYPES = ["none", "basic", "bearer", "api_key"]
|
||||||
|
|
||||||
|
|
||||||
|
class UpstreamSourceCreate(BaseModel):
|
||||||
|
"""Create a new upstream source"""
|
||||||
|
name: str
|
||||||
|
source_type: str = "generic"
|
||||||
|
url: str
|
||||||
|
enabled: bool = False
|
||||||
|
auth_type: str = "none"
|
||||||
|
username: Optional[str] = None
|
||||||
|
password: Optional[str] = None # Write-only
|
||||||
|
headers: Optional[dict] = None # Write-only, custom headers
|
||||||
|
priority: int = 100
|
||||||
|
|
||||||
|
@field_validator('name')
|
||||||
|
@classmethod
|
||||||
|
def validate_name(cls, v: str) -> str:
|
||||||
|
v = v.strip()
|
||||||
|
if not v:
|
||||||
|
raise ValueError("name cannot be empty")
|
||||||
|
if len(v) > 255:
|
||||||
|
raise ValueError("name must be 255 characters or less")
|
||||||
|
return v
|
||||||
|
|
||||||
|
@field_validator('source_type')
|
||||||
|
@classmethod
|
||||||
|
def validate_source_type(cls, v: str) -> str:
|
||||||
|
if v not in SOURCE_TYPES:
|
||||||
|
raise ValueError(f"source_type must be one of: {', '.join(SOURCE_TYPES)}")
|
||||||
|
return v
|
||||||
|
|
||||||
|
@field_validator('url')
|
||||||
|
@classmethod
|
||||||
|
def validate_url(cls, v: str) -> str:
|
||||||
|
v = v.strip()
|
||||||
|
if not v:
|
||||||
|
raise ValueError("url cannot be empty")
|
||||||
|
if not (v.startswith('http://') or v.startswith('https://')):
|
||||||
|
raise ValueError("url must start with http:// or https://")
|
||||||
|
if len(v) > 2048:
|
||||||
|
raise ValueError("url must be 2048 characters or less")
|
||||||
|
return v
|
||||||
|
|
||||||
|
@field_validator('auth_type')
|
||||||
|
@classmethod
|
||||||
|
def validate_auth_type(cls, v: str) -> str:
|
||||||
|
if v not in AUTH_TYPES:
|
||||||
|
raise ValueError(f"auth_type must be one of: {', '.join(AUTH_TYPES)}")
|
||||||
|
return v
|
||||||
|
|
||||||
|
@field_validator('priority')
|
||||||
|
@classmethod
|
||||||
|
def validate_priority(cls, v: int) -> int:
|
||||||
|
if v <= 0:
|
||||||
|
raise ValueError("priority must be greater than 0")
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
class UpstreamSourceUpdate(BaseModel):
|
||||||
|
"""Update an upstream source (partial)"""
|
||||||
|
name: Optional[str] = None
|
||||||
|
source_type: Optional[str] = None
|
||||||
|
url: Optional[str] = None
|
||||||
|
enabled: Optional[bool] = None
|
||||||
|
auth_type: Optional[str] = None
|
||||||
|
username: Optional[str] = None
|
||||||
|
password: Optional[str] = None # Write-only, None = keep existing, empty string = clear
|
||||||
|
headers: Optional[dict] = None # Write-only
|
||||||
|
priority: Optional[int] = None
|
||||||
|
|
||||||
|
@field_validator('name')
|
||||||
|
@classmethod
|
||||||
|
def validate_name(cls, v: Optional[str]) -> Optional[str]:
|
||||||
|
if v is not None:
|
||||||
|
v = v.strip()
|
||||||
|
if not v:
|
||||||
|
raise ValueError("name cannot be empty")
|
||||||
|
if len(v) > 255:
|
||||||
|
raise ValueError("name must be 255 characters or less")
|
||||||
|
return v
|
||||||
|
|
||||||
|
@field_validator('source_type')
|
||||||
|
@classmethod
|
||||||
|
def validate_source_type(cls, v: Optional[str]) -> Optional[str]:
|
||||||
|
if v is not None and v not in SOURCE_TYPES:
|
||||||
|
raise ValueError(f"source_type must be one of: {', '.join(SOURCE_TYPES)}")
|
||||||
|
return v
|
||||||
|
|
||||||
|
@field_validator('url')
|
||||||
|
@classmethod
|
||||||
|
def validate_url(cls, v: Optional[str]) -> Optional[str]:
|
||||||
|
if v is not None:
|
||||||
|
v = v.strip()
|
||||||
|
if not v:
|
||||||
|
raise ValueError("url cannot be empty")
|
||||||
|
if not (v.startswith('http://') or v.startswith('https://')):
|
||||||
|
raise ValueError("url must start with http:// or https://")
|
||||||
|
if len(v) > 2048:
|
||||||
|
raise ValueError("url must be 2048 characters or less")
|
||||||
|
return v
|
||||||
|
|
||||||
|
@field_validator('auth_type')
|
||||||
|
@classmethod
|
||||||
|
def validate_auth_type(cls, v: Optional[str]) -> Optional[str]:
|
||||||
|
if v is not None and v not in AUTH_TYPES:
|
||||||
|
raise ValueError(f"auth_type must be one of: {', '.join(AUTH_TYPES)}")
|
||||||
|
return v
|
||||||
|
|
||||||
|
@field_validator('priority')
|
||||||
|
@classmethod
|
||||||
|
def validate_priority(cls, v: Optional[int]) -> Optional[int]:
|
||||||
|
if v is not None and v <= 0:
|
||||||
|
raise ValueError("priority must be greater than 0")
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
class UpstreamSourceResponse(BaseModel):
|
||||||
|
"""Upstream source response (credentials never included)"""
|
||||||
|
id: UUID
|
||||||
|
name: str
|
||||||
|
source_type: str
|
||||||
|
url: str
|
||||||
|
enabled: bool
|
||||||
|
auth_type: str
|
||||||
|
username: Optional[str]
|
||||||
|
has_password: bool # True if password is set
|
||||||
|
has_headers: bool # True if custom headers are set
|
||||||
|
priority: int
|
||||||
|
source: str = "database" # "database" or "env" (env = defined via environment variables)
|
||||||
|
created_at: Optional[datetime] = None # May be None for legacy/env data
|
||||||
|
updated_at: Optional[datetime] = None # May be None for legacy/env data
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
class CacheSettingsResponse(BaseModel):
|
||||||
|
"""Global cache settings response"""
|
||||||
|
auto_create_system_projects: bool
|
||||||
|
auto_create_system_projects_env_override: Optional[bool] = None # Set if overridden by env var
|
||||||
|
created_at: Optional[datetime] = None # May be None for legacy data
|
||||||
|
updated_at: Optional[datetime] = None # May be None for legacy data
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
class CacheSettingsUpdate(BaseModel):
|
||||||
|
"""Update cache settings (partial)"""
|
||||||
|
auto_create_system_projects: Optional[bool] = None
|
||||||
|
|
||||||
|
|
||||||
|
class CachedUrlResponse(BaseModel):
|
||||||
|
"""Cached URL response"""
|
||||||
|
id: UUID
|
||||||
|
url: str
|
||||||
|
url_hash: str
|
||||||
|
artifact_id: str
|
||||||
|
source_id: Optional[UUID]
|
||||||
|
source_name: Optional[str] = None # Populated from join
|
||||||
|
fetched_at: datetime
|
||||||
|
created_at: datetime
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
class CacheRequest(BaseModel):
|
||||||
|
"""Request to cache an artifact from an upstream URL"""
|
||||||
|
url: str
|
||||||
|
source_type: str
|
||||||
|
package_name: Optional[str] = None # Auto-derived from URL if not provided
|
||||||
|
tag: Optional[str] = None # Auto-derived from URL if not provided
|
||||||
|
user_project: Optional[str] = None # Cross-reference to user project
|
||||||
|
user_package: Optional[str] = None
|
||||||
|
user_tag: Optional[str] = None
|
||||||
|
expected_hash: Optional[str] = None # Verify downloaded content
|
||||||
|
|
||||||
|
@field_validator('url')
|
||||||
|
@classmethod
|
||||||
|
def validate_url(cls, v: str) -> str:
|
||||||
|
v = v.strip()
|
||||||
|
if not v:
|
||||||
|
raise ValueError("url cannot be empty")
|
||||||
|
if not (v.startswith('http://') or v.startswith('https://')):
|
||||||
|
raise ValueError("url must start with http:// or https://")
|
||||||
|
if len(v) > 4096:
|
||||||
|
raise ValueError("url must be 4096 characters or less")
|
||||||
|
return v
|
||||||
|
|
||||||
|
@field_validator('source_type')
|
||||||
|
@classmethod
|
||||||
|
def validate_source_type(cls, v: str) -> str:
|
||||||
|
if v not in SOURCE_TYPES:
|
||||||
|
raise ValueError(f"source_type must be one of: {', '.join(SOURCE_TYPES)}")
|
||||||
|
return v
|
||||||
|
|
||||||
|
@field_validator('expected_hash')
|
||||||
|
@classmethod
|
||||||
|
def validate_expected_hash(cls, v: Optional[str]) -> Optional[str]:
|
||||||
|
if v is not None:
|
||||||
|
v = v.strip().lower()
|
||||||
|
# Remove sha256: prefix if present
|
||||||
|
if v.startswith('sha256:'):
|
||||||
|
v = v[7:]
|
||||||
|
# Validate hex format
|
||||||
|
if len(v) != 64 or not all(c in '0123456789abcdef' for c in v):
|
||||||
|
raise ValueError("expected_hash must be a 64-character hex string (SHA256)")
|
||||||
|
return v
|
||||||
|
|
||||||
|
|
||||||
|
class CacheResponse(BaseModel):
|
||||||
|
"""Response from caching an artifact"""
|
||||||
|
artifact_id: str
|
||||||
|
sha256: str
|
||||||
|
size: int
|
||||||
|
content_type: Optional[str]
|
||||||
|
already_cached: bool
|
||||||
|
source_url: str
|
||||||
|
source_name: Optional[str]
|
||||||
|
system_project: str
|
||||||
|
system_package: str
|
||||||
|
system_tag: Optional[str]
|
||||||
|
user_reference: Optional[str] = None # e.g., "my-app/npm-deps:lodash-4.17.21"
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -5,8 +5,9 @@ import hashlib
|
|||||||
import logging
|
import logging
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
from .models import Project, Package, Artifact, Tag, Upload, PackageVersion, ArtifactDependency
|
from .models import Project, Package, Artifact, Tag, Upload, PackageVersion, ArtifactDependency, Team, TeamMembership, User
|
||||||
from .storage import get_storage
|
from .storage import get_storage
|
||||||
|
from .auth import hash_password
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -149,6 +150,80 @@ def seed_database(db: Session) -> None:
|
|||||||
logger.info("Seeding database with test data...")
|
logger.info("Seeding database with test data...")
|
||||||
storage = get_storage()
|
storage = get_storage()
|
||||||
|
|
||||||
|
# Find or use admin user for team ownership
|
||||||
|
admin_user = db.query(User).filter(User.username == "admin").first()
|
||||||
|
team_owner_username = admin_user.username if admin_user else "seed-user"
|
||||||
|
|
||||||
|
# Create a demo team
|
||||||
|
demo_team = Team(
|
||||||
|
name="Demo Team",
|
||||||
|
slug="demo-team",
|
||||||
|
description="A demonstration team with sample projects",
|
||||||
|
created_by=team_owner_username,
|
||||||
|
)
|
||||||
|
db.add(demo_team)
|
||||||
|
db.flush()
|
||||||
|
|
||||||
|
# Add admin user as team owner if they exist
|
||||||
|
if admin_user:
|
||||||
|
membership = TeamMembership(
|
||||||
|
team_id=demo_team.id,
|
||||||
|
user_id=admin_user.id,
|
||||||
|
role="owner",
|
||||||
|
invited_by=team_owner_username,
|
||||||
|
)
|
||||||
|
db.add(membership)
|
||||||
|
db.flush()
|
||||||
|
|
||||||
|
logger.info(f"Created team: {demo_team.name} ({demo_team.slug})")
|
||||||
|
|
||||||
|
# Create test users with various roles
|
||||||
|
test_users = [
|
||||||
|
{"username": "alice", "email": "alice@example.com", "role": "admin"},
|
||||||
|
{"username": "bob", "email": "bob@example.com", "role": "admin"},
|
||||||
|
{"username": "charlie", "email": "charlie@example.com", "role": "member"},
|
||||||
|
{"username": "diana", "email": "diana@example.com", "role": "member"},
|
||||||
|
{"username": "eve", "email": "eve@example.com", "role": "member"},
|
||||||
|
{"username": "frank", "email": None, "role": "member"},
|
||||||
|
]
|
||||||
|
|
||||||
|
for user_data in test_users:
|
||||||
|
# Check if user already exists
|
||||||
|
existing_user = db.query(User).filter(User.username == user_data["username"]).first()
|
||||||
|
if existing_user:
|
||||||
|
test_user = existing_user
|
||||||
|
else:
|
||||||
|
# Create the user with password same as username
|
||||||
|
test_user = User(
|
||||||
|
username=user_data["username"],
|
||||||
|
email=user_data["email"],
|
||||||
|
password_hash=hash_password(user_data["username"]),
|
||||||
|
is_admin=False,
|
||||||
|
is_active=True,
|
||||||
|
must_change_password=False,
|
||||||
|
)
|
||||||
|
db.add(test_user)
|
||||||
|
db.flush()
|
||||||
|
logger.info(f"Created test user: {user_data['username']}")
|
||||||
|
|
||||||
|
# Add to demo team with specified role
|
||||||
|
existing_membership = db.query(TeamMembership).filter(
|
||||||
|
TeamMembership.team_id == demo_team.id,
|
||||||
|
TeamMembership.user_id == test_user.id,
|
||||||
|
).first()
|
||||||
|
|
||||||
|
if not existing_membership:
|
||||||
|
membership = TeamMembership(
|
||||||
|
team_id=demo_team.id,
|
||||||
|
user_id=test_user.id,
|
||||||
|
role=user_data["role"],
|
||||||
|
invited_by=team_owner_username,
|
||||||
|
)
|
||||||
|
db.add(membership)
|
||||||
|
logger.info(f"Added {user_data['username']} to {demo_team.slug} as {user_data['role']}")
|
||||||
|
|
||||||
|
db.flush()
|
||||||
|
|
||||||
# Create projects and packages
|
# Create projects and packages
|
||||||
project_map = {}
|
project_map = {}
|
||||||
package_map = {}
|
package_map = {}
|
||||||
@@ -158,7 +233,8 @@ def seed_database(db: Session) -> None:
|
|||||||
name=project_data["name"],
|
name=project_data["name"],
|
||||||
description=project_data["description"],
|
description=project_data["description"],
|
||||||
is_public=project_data["is_public"],
|
is_public=project_data["is_public"],
|
||||||
created_by="seed-user",
|
created_by=team_owner_username,
|
||||||
|
team_id=demo_team.id, # Assign to demo team
|
||||||
)
|
)
|
||||||
db.add(project)
|
db.add(project)
|
||||||
db.flush() # Get the ID
|
db.flush() # Get the ID
|
||||||
@@ -174,7 +250,7 @@ def seed_database(db: Session) -> None:
|
|||||||
db.flush()
|
db.flush()
|
||||||
package_map[(project_data["name"], package_data["name"])] = package
|
package_map[(project_data["name"], package_data["name"])] = package
|
||||||
|
|
||||||
logger.info(f"Created {len(project_map)} projects and {len(package_map)} packages")
|
logger.info(f"Created {len(project_map)} projects and {len(package_map)} packages (assigned to {demo_team.slug})")
|
||||||
|
|
||||||
# Create artifacts, tags, and versions
|
# Create artifacts, tags, and versions
|
||||||
artifact_count = 0
|
artifact_count = 0
|
||||||
@@ -212,7 +288,7 @@ def seed_database(db: Session) -> None:
|
|||||||
size=size,
|
size=size,
|
||||||
content_type=artifact_data["content_type"],
|
content_type=artifact_data["content_type"],
|
||||||
original_name=artifact_data["filename"],
|
original_name=artifact_data["filename"],
|
||||||
created_by="seed-user",
|
created_by=team_owner_username,
|
||||||
s3_key=s3_key,
|
s3_key=s3_key,
|
||||||
ref_count=ref_count,
|
ref_count=ref_count,
|
||||||
)
|
)
|
||||||
@@ -235,7 +311,7 @@ def seed_database(db: Session) -> None:
|
|||||||
artifact_id=sha256_hash,
|
artifact_id=sha256_hash,
|
||||||
version=artifact_data["version"],
|
version=artifact_data["version"],
|
||||||
version_source="explicit",
|
version_source="explicit",
|
||||||
created_by="seed-user",
|
created_by=team_owner_username,
|
||||||
)
|
)
|
||||||
db.add(version)
|
db.add(version)
|
||||||
version_count += 1
|
version_count += 1
|
||||||
@@ -246,7 +322,7 @@ def seed_database(db: Session) -> None:
|
|||||||
package_id=package.id,
|
package_id=package.id,
|
||||||
name=tag_name,
|
name=tag_name,
|
||||||
artifact_id=sha256_hash,
|
artifact_id=sha256_hash,
|
||||||
created_by="seed-user",
|
created_by=team_owner_username,
|
||||||
)
|
)
|
||||||
db.add(tag)
|
db.add(tag)
|
||||||
tag_count += 1
|
tag_count += 1
|
||||||
|
|||||||
565
backend/app/upstream.py
Normal file
565
backend/app/upstream.py
Normal file
@@ -0,0 +1,565 @@
|
|||||||
|
"""
|
||||||
|
HTTP client for fetching artifacts from upstream sources.
|
||||||
|
|
||||||
|
Provides streaming downloads with SHA256 computation, authentication support,
|
||||||
|
and automatic source matching based on URL prefixes.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import hashlib
|
||||||
|
import logging
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import BinaryIO, Optional, TYPE_CHECKING
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
|
||||||
|
if TYPE_CHECKING:
|
||||||
|
from .models import CacheSettings, UpstreamSource
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class UpstreamError(Exception):
|
||||||
|
"""Base exception for upstream client errors."""
|
||||||
|
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class UpstreamConnectionError(UpstreamError):
|
||||||
|
"""Connection to upstream failed (network error, DNS, etc.)."""
|
||||||
|
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class UpstreamTimeoutError(UpstreamError):
|
||||||
|
"""Request to upstream timed out."""
|
||||||
|
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class UpstreamHTTPError(UpstreamError):
|
||||||
|
"""Upstream returned an HTTP error response."""
|
||||||
|
|
||||||
|
def __init__(self, message: str, status_code: int, response_headers: dict = None):
|
||||||
|
super().__init__(message)
|
||||||
|
self.status_code = status_code
|
||||||
|
self.response_headers = response_headers or {}
|
||||||
|
|
||||||
|
|
||||||
|
class UpstreamSSLError(UpstreamError):
|
||||||
|
"""SSL/TLS error when connecting to upstream."""
|
||||||
|
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
class FileSizeExceededError(UpstreamError):
|
||||||
|
"""File size exceeds the maximum allowed."""
|
||||||
|
|
||||||
|
def __init__(self, message: str, content_length: int, max_size: int):
|
||||||
|
super().__init__(message)
|
||||||
|
self.content_length = content_length
|
||||||
|
self.max_size = max_size
|
||||||
|
|
||||||
|
|
||||||
|
class SourceNotFoundError(UpstreamError):
|
||||||
|
"""No matching upstream source found for URL."""
|
||||||
|
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class SourceDisabledError(UpstreamError):
|
||||||
|
"""The matching upstream source is disabled."""
|
||||||
|
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class FetchResult:
|
||||||
|
"""Result of fetching an artifact from upstream."""
|
||||||
|
|
||||||
|
content: BinaryIO # File-like object with content
|
||||||
|
sha256: str # SHA256 hash of content
|
||||||
|
size: int # Size in bytes
|
||||||
|
content_type: Optional[str] # Content-Type header
|
||||||
|
response_headers: dict # All response headers for provenance
|
||||||
|
source_name: Optional[str] = None # Name of matched upstream source
|
||||||
|
temp_path: Optional[Path] = None # Path to temp file (for cleanup)
|
||||||
|
|
||||||
|
def close(self):
|
||||||
|
"""Close and clean up resources."""
|
||||||
|
if self.content:
|
||||||
|
try:
|
||||||
|
self.content.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
if self.temp_path and self.temp_path.exists():
|
||||||
|
try:
|
||||||
|
self.temp_path.unlink()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class UpstreamClientConfig:
|
||||||
|
"""Configuration for the upstream client."""
|
||||||
|
|
||||||
|
connect_timeout: float = 30.0 # Connection timeout in seconds
|
||||||
|
read_timeout: float = 300.0 # Read timeout in seconds (5 minutes for large files)
|
||||||
|
max_retries: int = 3 # Maximum number of retry attempts
|
||||||
|
retry_backoff_base: float = 1.0 # Base delay for exponential backoff
|
||||||
|
retry_backoff_max: float = 30.0 # Maximum delay between retries
|
||||||
|
follow_redirects: bool = True # Whether to follow redirects
|
||||||
|
max_redirects: int = 5 # Maximum number of redirects to follow
|
||||||
|
max_file_size: Optional[int] = None # Maximum file size (None = unlimited)
|
||||||
|
verify_ssl: bool = True # Verify SSL certificates
|
||||||
|
user_agent: str = "Orchard-UpstreamClient/1.0"
|
||||||
|
|
||||||
|
|
||||||
|
class UpstreamClient:
|
||||||
|
"""
|
||||||
|
HTTP client for fetching artifacts from upstream sources.
|
||||||
|
|
||||||
|
Supports streaming downloads, multiple authentication methods,
|
||||||
|
automatic source matching, and air-gap mode enforcement.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
sources: list[UpstreamSource] = None,
|
||||||
|
cache_settings: CacheSettings = None,
|
||||||
|
config: UpstreamClientConfig = None,
|
||||||
|
):
|
||||||
|
"""
|
||||||
|
Initialize the upstream client.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
sources: List of upstream sources for URL matching and auth.
|
||||||
|
Should be sorted by priority (lowest first).
|
||||||
|
cache_settings: Global cache settings including air-gap mode.
|
||||||
|
config: Client configuration options.
|
||||||
|
"""
|
||||||
|
self.sources = sources or []
|
||||||
|
self.cache_settings = cache_settings
|
||||||
|
self.config = config or UpstreamClientConfig()
|
||||||
|
|
||||||
|
# Sort sources by priority (lower = higher priority)
|
||||||
|
self.sources = sorted(self.sources, key=lambda s: s.priority)
|
||||||
|
|
||||||
|
def _match_source(self, url: str) -> Optional[UpstreamSource]:
|
||||||
|
"""
|
||||||
|
Find the upstream source that matches the given URL.
|
||||||
|
|
||||||
|
Matches by URL prefix, returns the highest priority match.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
url: The URL to match.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The matching UpstreamSource or None if no match.
|
||||||
|
"""
|
||||||
|
for source in self.sources:
|
||||||
|
# Check if URL starts with source URL (prefix match)
|
||||||
|
if url.startswith(source.url.rstrip("/")):
|
||||||
|
return source
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _build_auth_headers(self, source: UpstreamSource) -> dict:
|
||||||
|
"""
|
||||||
|
Build authentication headers for the given source.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
source: The upstream source with auth configuration.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Dictionary of headers to add to the request.
|
||||||
|
"""
|
||||||
|
headers = {}
|
||||||
|
|
||||||
|
if source.auth_type == "none":
|
||||||
|
pass
|
||||||
|
elif source.auth_type == "basic":
|
||||||
|
# httpx handles basic auth via auth parameter, but we can also
|
||||||
|
# do it manually if needed. We'll use the auth parameter instead.
|
||||||
|
pass
|
||||||
|
elif source.auth_type == "bearer":
|
||||||
|
password = source.get_password()
|
||||||
|
if password:
|
||||||
|
headers["Authorization"] = f"Bearer {password}"
|
||||||
|
elif source.auth_type == "api_key":
|
||||||
|
# API key auth uses custom headers
|
||||||
|
custom_headers = source.get_headers()
|
||||||
|
if custom_headers:
|
||||||
|
headers.update(custom_headers)
|
||||||
|
|
||||||
|
return headers
|
||||||
|
|
||||||
|
def _get_basic_auth(self, source: UpstreamSource) -> Optional[tuple[str, str]]:
|
||||||
|
"""
|
||||||
|
Get basic auth credentials if applicable.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
source: The upstream source.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Tuple of (username, password) or None.
|
||||||
|
"""
|
||||||
|
if source.auth_type == "basic" and source.username:
|
||||||
|
password = source.get_password() or ""
|
||||||
|
return (source.username, password)
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _should_retry(self, error: Exception, attempt: int) -> bool:
|
||||||
|
"""
|
||||||
|
Determine if a request should be retried.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
error: The exception that occurred.
|
||||||
|
attempt: Current attempt number (0-indexed).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
True if the request should be retried.
|
||||||
|
"""
|
||||||
|
if attempt >= self.config.max_retries - 1:
|
||||||
|
return False
|
||||||
|
|
||||||
|
# Retry on connection errors and timeouts
|
||||||
|
if isinstance(error, (httpx.ConnectError, httpx.ConnectTimeout)):
|
||||||
|
return True
|
||||||
|
|
||||||
|
# Retry on read timeouts
|
||||||
|
if isinstance(error, httpx.ReadTimeout):
|
||||||
|
return True
|
||||||
|
|
||||||
|
# Retry on certain HTTP errors (502, 503, 504)
|
||||||
|
if isinstance(error, httpx.HTTPStatusError):
|
||||||
|
return error.response.status_code in (502, 503, 504)
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
def _calculate_backoff(self, attempt: int) -> float:
|
||||||
|
"""
|
||||||
|
Calculate backoff delay for retry.
|
||||||
|
|
||||||
|
Uses exponential backoff with jitter.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
attempt: Current attempt number (0-indexed).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Delay in seconds.
|
||||||
|
"""
|
||||||
|
import random
|
||||||
|
|
||||||
|
delay = self.config.retry_backoff_base * (2**attempt)
|
||||||
|
# Add jitter (±25%)
|
||||||
|
delay *= 0.75 + random.random() * 0.5
|
||||||
|
return min(delay, self.config.retry_backoff_max)
|
||||||
|
|
||||||
|
def fetch(self, url: str, expected_hash: Optional[str] = None) -> FetchResult:
|
||||||
|
"""
|
||||||
|
Fetch an artifact from the given URL.
|
||||||
|
|
||||||
|
Streams the response to a temp file while computing the SHA256 hash.
|
||||||
|
Handles authentication, retries, and error cases.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
url: The URL to fetch.
|
||||||
|
expected_hash: Optional expected SHA256 hash for verification.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
FetchResult with content, hash, size, and headers.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
SourceDisabledError: If the matching source is disabled.
|
||||||
|
UpstreamConnectionError: On connection failures.
|
||||||
|
UpstreamTimeoutError: On timeout.
|
||||||
|
UpstreamHTTPError: On HTTP error responses.
|
||||||
|
UpstreamSSLError: On SSL/TLS errors.
|
||||||
|
FileSizeExceededError: If Content-Length exceeds max_file_size.
|
||||||
|
"""
|
||||||
|
start_time = time.time()
|
||||||
|
|
||||||
|
# Match URL to source
|
||||||
|
source = self._match_source(url)
|
||||||
|
|
||||||
|
# Check if source is enabled (if we have a match)
|
||||||
|
if source is not None and not source.enabled:
|
||||||
|
raise SourceDisabledError(
|
||||||
|
f"Upstream source '{source.name}' is disabled"
|
||||||
|
)
|
||||||
|
|
||||||
|
source_name = source.name if source else None
|
||||||
|
logger.info(
|
||||||
|
f"Fetching URL: {url} (source: {source_name or 'none'})"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Build request parameters
|
||||||
|
headers = {"User-Agent": self.config.user_agent}
|
||||||
|
auth = None
|
||||||
|
|
||||||
|
if source:
|
||||||
|
headers.update(self._build_auth_headers(source))
|
||||||
|
auth = self._get_basic_auth(source)
|
||||||
|
|
||||||
|
timeout = httpx.Timeout(
|
||||||
|
connect=self.config.connect_timeout,
|
||||||
|
read=self.config.read_timeout,
|
||||||
|
write=30.0,
|
||||||
|
pool=10.0,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Attempt fetch with retries
|
||||||
|
last_error = None
|
||||||
|
for attempt in range(self.config.max_retries):
|
||||||
|
try:
|
||||||
|
return self._do_fetch(
|
||||||
|
url=url,
|
||||||
|
headers=headers,
|
||||||
|
auth=auth,
|
||||||
|
timeout=timeout,
|
||||||
|
source_name=source_name,
|
||||||
|
start_time=start_time,
|
||||||
|
expected_hash=expected_hash,
|
||||||
|
)
|
||||||
|
except (
|
||||||
|
httpx.ConnectError,
|
||||||
|
httpx.ConnectTimeout,
|
||||||
|
httpx.ReadTimeout,
|
||||||
|
httpx.HTTPStatusError,
|
||||||
|
) as e:
|
||||||
|
last_error = e
|
||||||
|
if self._should_retry(e, attempt):
|
||||||
|
delay = self._calculate_backoff(attempt)
|
||||||
|
logger.warning(
|
||||||
|
f"Fetch failed (attempt {attempt + 1}/{self.config.max_retries}), "
|
||||||
|
f"retrying in {delay:.1f}s: {e}"
|
||||||
|
)
|
||||||
|
time.sleep(delay)
|
||||||
|
else:
|
||||||
|
break
|
||||||
|
|
||||||
|
# Convert final error to our exception types
|
||||||
|
self._raise_upstream_error(last_error, url)
|
||||||
|
|
||||||
|
def _do_fetch(
|
||||||
|
self,
|
||||||
|
url: str,
|
||||||
|
headers: dict,
|
||||||
|
auth: Optional[tuple[str, str]],
|
||||||
|
timeout: httpx.Timeout,
|
||||||
|
source_name: Optional[str],
|
||||||
|
start_time: float,
|
||||||
|
expected_hash: Optional[str] = None,
|
||||||
|
) -> FetchResult:
|
||||||
|
"""
|
||||||
|
Perform the actual fetch operation.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
url: URL to fetch.
|
||||||
|
headers: Request headers.
|
||||||
|
auth: Basic auth credentials or None.
|
||||||
|
timeout: Request timeout configuration.
|
||||||
|
source_name: Name of matched source for logging.
|
||||||
|
start_time: Request start time for timing.
|
||||||
|
expected_hash: Optional expected hash for verification.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
FetchResult with content and metadata.
|
||||||
|
"""
|
||||||
|
with httpx.Client(
|
||||||
|
timeout=timeout,
|
||||||
|
follow_redirects=self.config.follow_redirects,
|
||||||
|
max_redirects=self.config.max_redirects,
|
||||||
|
verify=self.config.verify_ssl,
|
||||||
|
) as client:
|
||||||
|
with client.stream("GET", url, headers=headers, auth=auth) as response:
|
||||||
|
# Check for HTTP errors
|
||||||
|
response.raise_for_status()
|
||||||
|
|
||||||
|
# Check Content-Length against max size
|
||||||
|
content_length = response.headers.get("content-length")
|
||||||
|
if content_length:
|
||||||
|
content_length = int(content_length)
|
||||||
|
if (
|
||||||
|
self.config.max_file_size
|
||||||
|
and content_length > self.config.max_file_size
|
||||||
|
):
|
||||||
|
raise FileSizeExceededError(
|
||||||
|
f"File size {content_length} exceeds maximum {self.config.max_file_size}",
|
||||||
|
content_length,
|
||||||
|
self.config.max_file_size,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Stream to temp file while computing hash
|
||||||
|
hasher = hashlib.sha256()
|
||||||
|
size = 0
|
||||||
|
|
||||||
|
# Create temp file
|
||||||
|
temp_file = tempfile.NamedTemporaryFile(
|
||||||
|
delete=False, prefix="orchard_upstream_"
|
||||||
|
)
|
||||||
|
temp_path = Path(temp_file.name)
|
||||||
|
|
||||||
|
try:
|
||||||
|
for chunk in response.iter_bytes(chunk_size=65536):
|
||||||
|
temp_file.write(chunk)
|
||||||
|
hasher.update(chunk)
|
||||||
|
size += len(chunk)
|
||||||
|
|
||||||
|
# Check size while streaming if max_file_size is set
|
||||||
|
if self.config.max_file_size and size > self.config.max_file_size:
|
||||||
|
temp_file.close()
|
||||||
|
temp_path.unlink()
|
||||||
|
raise FileSizeExceededError(
|
||||||
|
f"Downloaded size {size} exceeds maximum {self.config.max_file_size}",
|
||||||
|
size,
|
||||||
|
self.config.max_file_size,
|
||||||
|
)
|
||||||
|
|
||||||
|
temp_file.close()
|
||||||
|
|
||||||
|
sha256 = hasher.hexdigest()
|
||||||
|
|
||||||
|
# Verify hash if expected
|
||||||
|
if expected_hash and sha256 != expected_hash.lower():
|
||||||
|
temp_path.unlink()
|
||||||
|
raise UpstreamError(
|
||||||
|
f"Hash mismatch: expected {expected_hash}, got {sha256}"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Capture response headers
|
||||||
|
response_headers = dict(response.headers)
|
||||||
|
|
||||||
|
# Get content type
|
||||||
|
content_type = response.headers.get("content-type")
|
||||||
|
|
||||||
|
elapsed = time.time() - start_time
|
||||||
|
logger.info(
|
||||||
|
f"Fetched {url}: {size} bytes, sha256={sha256[:12]}..., "
|
||||||
|
f"source={source_name}, time={elapsed:.2f}s"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Return file handle positioned at start
|
||||||
|
content = open(temp_path, "rb")
|
||||||
|
|
||||||
|
return FetchResult(
|
||||||
|
content=content,
|
||||||
|
sha256=sha256,
|
||||||
|
size=size,
|
||||||
|
content_type=content_type,
|
||||||
|
response_headers=response_headers,
|
||||||
|
source_name=source_name,
|
||||||
|
temp_path=temp_path,
|
||||||
|
)
|
||||||
|
|
||||||
|
except Exception:
|
||||||
|
# Clean up on error
|
||||||
|
try:
|
||||||
|
temp_file.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
if temp_path.exists():
|
||||||
|
temp_path.unlink()
|
||||||
|
raise
|
||||||
|
|
||||||
|
def _raise_upstream_error(self, error: Exception, url: str):
|
||||||
|
"""
|
||||||
|
Convert httpx exception to appropriate UpstreamError.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
error: The httpx exception.
|
||||||
|
url: The URL that was being fetched.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
Appropriate UpstreamError subclass.
|
||||||
|
"""
|
||||||
|
if error is None:
|
||||||
|
raise UpstreamError(f"Unknown error fetching {url}")
|
||||||
|
|
||||||
|
if isinstance(error, httpx.ConnectError):
|
||||||
|
raise UpstreamConnectionError(
|
||||||
|
f"Failed to connect to upstream: {error}"
|
||||||
|
) from error
|
||||||
|
|
||||||
|
if isinstance(error, (httpx.ConnectTimeout, httpx.ReadTimeout)):
|
||||||
|
raise UpstreamTimeoutError(
|
||||||
|
f"Request timed out: {error}"
|
||||||
|
) from error
|
||||||
|
|
||||||
|
if isinstance(error, httpx.HTTPStatusError):
|
||||||
|
raise UpstreamHTTPError(
|
||||||
|
f"HTTP {error.response.status_code}: {error}",
|
||||||
|
error.response.status_code,
|
||||||
|
dict(error.response.headers),
|
||||||
|
) from error
|
||||||
|
|
||||||
|
# Check for SSL errors in the error chain
|
||||||
|
if "ssl" in str(error).lower() or "certificate" in str(error).lower():
|
||||||
|
raise UpstreamSSLError(f"SSL/TLS error: {error}") from error
|
||||||
|
|
||||||
|
raise UpstreamError(f"Error fetching {url}: {error}") from error
|
||||||
|
|
||||||
|
def test_connection(self, source: UpstreamSource) -> tuple[bool, Optional[str], Optional[int]]:
|
||||||
|
"""
|
||||||
|
Test connectivity to an upstream source.
|
||||||
|
|
||||||
|
Performs a HEAD request to the source URL to verify connectivity
|
||||||
|
and authentication. Does not follow redirects - a 3xx response
|
||||||
|
is considered successful since it proves the server is reachable.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
source: The upstream source to test.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Tuple of (success, error_message, status_code).
|
||||||
|
"""
|
||||||
|
headers = {"User-Agent": self.config.user_agent}
|
||||||
|
headers.update(self._build_auth_headers(source))
|
||||||
|
auth = self._get_basic_auth(source)
|
||||||
|
|
||||||
|
timeout = httpx.Timeout(
|
||||||
|
connect=self.config.connect_timeout,
|
||||||
|
read=30.0,
|
||||||
|
write=30.0,
|
||||||
|
pool=10.0,
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
with httpx.Client(
|
||||||
|
timeout=timeout,
|
||||||
|
verify=self.config.verify_ssl,
|
||||||
|
) as client:
|
||||||
|
response = client.head(
|
||||||
|
source.url,
|
||||||
|
headers=headers,
|
||||||
|
auth=auth,
|
||||||
|
follow_redirects=False,
|
||||||
|
)
|
||||||
|
# Consider 2xx and 3xx as success, also 405 (Method Not Allowed)
|
||||||
|
# since some servers don't support HEAD
|
||||||
|
if response.status_code < 400 or response.status_code == 405:
|
||||||
|
return (True, None, response.status_code)
|
||||||
|
else:
|
||||||
|
return (
|
||||||
|
False,
|
||||||
|
f"HTTP {response.status_code}",
|
||||||
|
response.status_code,
|
||||||
|
)
|
||||||
|
except httpx.ConnectError as e:
|
||||||
|
return (False, f"Connection failed: {e}", None)
|
||||||
|
except httpx.ConnectTimeout as e:
|
||||||
|
return (False, f"Connection timed out: {e}", None)
|
||||||
|
except httpx.ReadTimeout as e:
|
||||||
|
return (False, f"Read timed out: {e}", None)
|
||||||
|
except httpx.TooManyRedirects as e:
|
||||||
|
return (False, f"Too many redirects: {e}", None)
|
||||||
|
except Exception as e:
|
||||||
|
return (False, f"Error: {e}", None)
|
||||||
@@ -11,10 +11,10 @@ python-jose[cryptography]==3.3.0
|
|||||||
passlib[bcrypt]==1.7.4
|
passlib[bcrypt]==1.7.4
|
||||||
bcrypt==4.0.1
|
bcrypt==4.0.1
|
||||||
slowapi==0.1.9
|
slowapi==0.1.9
|
||||||
|
httpx>=0.25.0
|
||||||
|
|
||||||
# Test dependencies
|
# Test dependencies
|
||||||
pytest>=7.4.0
|
pytest>=7.4.0
|
||||||
pytest-asyncio>=0.21.0
|
pytest-asyncio>=0.21.0
|
||||||
pytest-cov>=4.1.0
|
pytest-cov>=4.1.0
|
||||||
httpx>=0.25.0
|
|
||||||
moto[s3]>=4.2.0
|
moto[s3]>=4.2.0
|
||||||
|
|||||||
@@ -68,13 +68,12 @@ def get_admin_password() -> str:
|
|||||||
Returns the password from ORCHARD_TEST_PASSWORD environment variable,
|
Returns the password from ORCHARD_TEST_PASSWORD environment variable,
|
||||||
or 'changeme123' as the default for local development.
|
or 'changeme123' as the default for local development.
|
||||||
"""
|
"""
|
||||||
# Use 'or' to handle empty string (when CI variable is undefined)
|
return os.environ.get("ORCHARD_TEST_PASSWORD", "changeme123")
|
||||||
return os.environ.get("ORCHARD_TEST_PASSWORD") or "changeme123"
|
|
||||||
|
|
||||||
|
|
||||||
def get_admin_username() -> str:
|
def get_admin_username() -> str:
|
||||||
"""Get the admin username for test authentication."""
|
"""Get the admin username for test authentication."""
|
||||||
return os.environ.get("ORCHARD_TEST_USERNAME") or "admin"
|
return os.environ.get("ORCHARD_TEST_USERNAME", "admin")
|
||||||
|
|
||||||
|
|
||||||
# Re-export factory functions for backward compatibility
|
# Re-export factory functions for backward compatibility
|
||||||
@@ -249,9 +248,9 @@ def integration_client():
|
|||||||
import httpx
|
import httpx
|
||||||
|
|
||||||
# Connect to the running orchard-server container or deployed environment
|
# Connect to the running orchard-server container or deployed environment
|
||||||
base_url = os.environ.get("ORCHARD_TEST_URL") or "http://localhost:8080"
|
base_url = os.environ.get("ORCHARD_TEST_URL", "http://localhost:8080")
|
||||||
username = get_admin_username()
|
username = os.environ.get("ORCHARD_TEST_USERNAME", "admin")
|
||||||
password = get_admin_password()
|
password = os.environ.get("ORCHARD_TEST_PASSWORD", "changeme123")
|
||||||
|
|
||||||
with httpx.Client(base_url=base_url, timeout=30.0) as client:
|
with httpx.Client(base_url=base_url, timeout=30.0) as client:
|
||||||
# Login as admin to enable write operations
|
# Login as admin to enable write operations
|
||||||
|
|||||||
316
backend/tests/integration/test_teams_api.py
Normal file
316
backend/tests/integration/test_teams_api.py
Normal file
@@ -0,0 +1,316 @@
|
|||||||
|
"""
|
||||||
|
Integration tests for Teams API endpoints.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.integration
|
||||||
|
class TestTeamsCRUD:
|
||||||
|
"""Tests for team creation, listing, updating, and deletion."""
|
||||||
|
|
||||||
|
def test_create_team(self, integration_client, unique_test_id):
|
||||||
|
"""Test creating a new team."""
|
||||||
|
team_name = f"Test Team {unique_test_id}"
|
||||||
|
team_slug = f"test-team-{unique_test_id}"
|
||||||
|
|
||||||
|
response = integration_client.post(
|
||||||
|
"/api/v1/teams",
|
||||||
|
json={
|
||||||
|
"name": team_name,
|
||||||
|
"slug": team_slug,
|
||||||
|
"description": "A test team",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert response.status_code == 201, f"Failed to create team: {response.text}"
|
||||||
|
|
||||||
|
data = response.json()
|
||||||
|
assert data["name"] == team_name
|
||||||
|
assert data["slug"] == team_slug
|
||||||
|
assert data["description"] == "A test team"
|
||||||
|
assert data["user_role"] == "owner"
|
||||||
|
assert data["member_count"] == 1
|
||||||
|
assert data["project_count"] == 0
|
||||||
|
|
||||||
|
# Cleanup
|
||||||
|
integration_client.delete(f"/api/v1/teams/{team_slug}")
|
||||||
|
|
||||||
|
def test_create_team_duplicate_slug(self, integration_client, unique_test_id):
|
||||||
|
"""Test that duplicate team slugs are rejected."""
|
||||||
|
team_slug = f"dup-team-{unique_test_id}"
|
||||||
|
|
||||||
|
# Create first team
|
||||||
|
response = integration_client.post(
|
||||||
|
"/api/v1/teams",
|
||||||
|
json={"name": "First Team", "slug": team_slug},
|
||||||
|
)
|
||||||
|
assert response.status_code == 201
|
||||||
|
|
||||||
|
# Try to create second team with same slug
|
||||||
|
response = integration_client.post(
|
||||||
|
"/api/v1/teams",
|
||||||
|
json={"name": "Second Team", "slug": team_slug},
|
||||||
|
)
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert "already exists" in response.json()["detail"].lower()
|
||||||
|
|
||||||
|
# Cleanup
|
||||||
|
integration_client.delete(f"/api/v1/teams/{team_slug}")
|
||||||
|
|
||||||
|
def test_create_team_invalid_slug(self, integration_client):
|
||||||
|
"""Test that invalid team slugs are rejected."""
|
||||||
|
invalid_slugs = [
|
||||||
|
"UPPERCASE",
|
||||||
|
"with spaces",
|
||||||
|
"-starts-with-hyphen",
|
||||||
|
"ends-with-hyphen-",
|
||||||
|
"has--double--hyphen",
|
||||||
|
]
|
||||||
|
|
||||||
|
for invalid_slug in invalid_slugs:
|
||||||
|
response = integration_client.post(
|
||||||
|
"/api/v1/teams",
|
||||||
|
json={"name": "Test", "slug": invalid_slug},
|
||||||
|
)
|
||||||
|
assert response.status_code == 422, f"Slug '{invalid_slug}' should be invalid"
|
||||||
|
|
||||||
|
def test_list_teams(self, integration_client, unique_test_id):
|
||||||
|
"""Test listing teams the user belongs to."""
|
||||||
|
# Create a team
|
||||||
|
team_slug = f"list-team-{unique_test_id}"
|
||||||
|
integration_client.post(
|
||||||
|
"/api/v1/teams",
|
||||||
|
json={"name": "List Test Team", "slug": team_slug},
|
||||||
|
)
|
||||||
|
|
||||||
|
# List teams
|
||||||
|
response = integration_client.get("/api/v1/teams")
|
||||||
|
assert response.status_code == 200
|
||||||
|
|
||||||
|
data = response.json()
|
||||||
|
assert "items" in data
|
||||||
|
assert "pagination" in data
|
||||||
|
|
||||||
|
# Find our team
|
||||||
|
team = next((t for t in data["items"] if t["slug"] == team_slug), None)
|
||||||
|
assert team is not None
|
||||||
|
assert team["name"] == "List Test Team"
|
||||||
|
|
||||||
|
# Cleanup
|
||||||
|
integration_client.delete(f"/api/v1/teams/{team_slug}")
|
||||||
|
|
||||||
|
def test_get_team(self, integration_client, unique_test_id):
|
||||||
|
"""Test getting team details."""
|
||||||
|
team_slug = f"get-team-{unique_test_id}"
|
||||||
|
integration_client.post(
|
||||||
|
"/api/v1/teams",
|
||||||
|
json={"name": "Get Test Team", "slug": team_slug, "description": "Test"},
|
||||||
|
)
|
||||||
|
|
||||||
|
response = integration_client.get(f"/api/v1/teams/{team_slug}")
|
||||||
|
assert response.status_code == 200
|
||||||
|
|
||||||
|
data = response.json()
|
||||||
|
assert data["slug"] == team_slug
|
||||||
|
assert data["name"] == "Get Test Team"
|
||||||
|
assert data["user_role"] == "owner"
|
||||||
|
|
||||||
|
# Cleanup
|
||||||
|
integration_client.delete(f"/api/v1/teams/{team_slug}")
|
||||||
|
|
||||||
|
def test_get_nonexistent_team(self, integration_client):
|
||||||
|
"""Test getting a team that doesn't exist."""
|
||||||
|
response = integration_client.get("/api/v1/teams/nonexistent-team-12345")
|
||||||
|
assert response.status_code == 404
|
||||||
|
|
||||||
|
def test_update_team(self, integration_client, unique_test_id):
|
||||||
|
"""Test updating team details."""
|
||||||
|
team_slug = f"update-team-{unique_test_id}"
|
||||||
|
integration_client.post(
|
||||||
|
"/api/v1/teams",
|
||||||
|
json={"name": "Original Name", "slug": team_slug},
|
||||||
|
)
|
||||||
|
|
||||||
|
response = integration_client.put(
|
||||||
|
f"/api/v1/teams/{team_slug}",
|
||||||
|
json={"name": "Updated Name", "description": "New description"},
|
||||||
|
)
|
||||||
|
assert response.status_code == 200
|
||||||
|
|
||||||
|
data = response.json()
|
||||||
|
assert data["name"] == "Updated Name"
|
||||||
|
assert data["description"] == "New description"
|
||||||
|
assert data["slug"] == team_slug # Slug should not change
|
||||||
|
|
||||||
|
# Cleanup
|
||||||
|
integration_client.delete(f"/api/v1/teams/{team_slug}")
|
||||||
|
|
||||||
|
def test_delete_team(self, integration_client, unique_test_id):
|
||||||
|
"""Test deleting a team."""
|
||||||
|
team_slug = f"delete-team-{unique_test_id}"
|
||||||
|
integration_client.post(
|
||||||
|
"/api/v1/teams",
|
||||||
|
json={"name": "Delete Test Team", "slug": team_slug},
|
||||||
|
)
|
||||||
|
|
||||||
|
response = integration_client.delete(f"/api/v1/teams/{team_slug}")
|
||||||
|
assert response.status_code == 204
|
||||||
|
|
||||||
|
# Verify team is gone
|
||||||
|
response = integration_client.get(f"/api/v1/teams/{team_slug}")
|
||||||
|
assert response.status_code == 404
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.integration
|
||||||
|
class TestTeamMembers:
|
||||||
|
"""Tests for team membership management."""
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def test_team(self, integration_client, unique_test_id):
|
||||||
|
"""Create a test team for member tests."""
|
||||||
|
team_slug = f"member-team-{unique_test_id}"
|
||||||
|
response = integration_client.post(
|
||||||
|
"/api/v1/teams",
|
||||||
|
json={"name": "Member Test Team", "slug": team_slug},
|
||||||
|
)
|
||||||
|
assert response.status_code == 201
|
||||||
|
|
||||||
|
yield team_slug
|
||||||
|
|
||||||
|
# Cleanup
|
||||||
|
try:
|
||||||
|
integration_client.delete(f"/api/v1/teams/{team_slug}")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def test_list_members(self, integration_client, test_team):
|
||||||
|
"""Test listing team members."""
|
||||||
|
response = integration_client.get(f"/api/v1/teams/{test_team}/members")
|
||||||
|
assert response.status_code == 200
|
||||||
|
|
||||||
|
members = response.json()
|
||||||
|
assert len(members) == 1
|
||||||
|
assert members[0]["role"] == "owner"
|
||||||
|
|
||||||
|
def test_owner_is_first_member(self, integration_client, test_team):
|
||||||
|
"""Test that the team creator is automatically the owner."""
|
||||||
|
response = integration_client.get(f"/api/v1/teams/{test_team}/members")
|
||||||
|
members = response.json()
|
||||||
|
|
||||||
|
assert len(members) >= 1
|
||||||
|
owner = next((m for m in members if m["role"] == "owner"), None)
|
||||||
|
assert owner is not None
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.integration
|
||||||
|
class TestTeamProjects:
|
||||||
|
"""Tests for team project management."""
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def test_team(self, integration_client, unique_test_id):
|
||||||
|
"""Create a test team for project tests."""
|
||||||
|
team_slug = f"proj-team-{unique_test_id}"
|
||||||
|
response = integration_client.post(
|
||||||
|
"/api/v1/teams",
|
||||||
|
json={"name": "Project Test Team", "slug": team_slug},
|
||||||
|
)
|
||||||
|
assert response.status_code == 201
|
||||||
|
|
||||||
|
data = response.json()
|
||||||
|
yield {"slug": team_slug, "id": data["id"]}
|
||||||
|
|
||||||
|
# Cleanup
|
||||||
|
try:
|
||||||
|
integration_client.delete(f"/api/v1/teams/{team_slug}")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def test_list_team_projects_empty(self, integration_client, test_team):
|
||||||
|
"""Test listing projects in an empty team."""
|
||||||
|
response = integration_client.get(f"/api/v1/teams/{test_team['slug']}/projects")
|
||||||
|
assert response.status_code == 200
|
||||||
|
|
||||||
|
data = response.json()
|
||||||
|
assert data["items"] == []
|
||||||
|
assert data["pagination"]["total"] == 0
|
||||||
|
|
||||||
|
def test_create_project_in_team(self, integration_client, test_team, unique_test_id):
|
||||||
|
"""Test creating a project within a team."""
|
||||||
|
project_name = f"team-project-{unique_test_id}"
|
||||||
|
|
||||||
|
response = integration_client.post(
|
||||||
|
"/api/v1/projects",
|
||||||
|
json={
|
||||||
|
"name": project_name,
|
||||||
|
"description": "A team project",
|
||||||
|
"team_id": test_team["id"],
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert response.status_code == 200, f"Failed to create project: {response.text}"
|
||||||
|
|
||||||
|
data = response.json()
|
||||||
|
assert data["team_id"] == test_team["id"]
|
||||||
|
assert data["team_slug"] == test_team["slug"]
|
||||||
|
|
||||||
|
# Verify project appears in team projects list
|
||||||
|
response = integration_client.get(f"/api/v1/teams/{test_team['slug']}/projects")
|
||||||
|
assert response.status_code == 200
|
||||||
|
projects = response.json()["items"]
|
||||||
|
assert any(p["name"] == project_name for p in projects)
|
||||||
|
|
||||||
|
# Cleanup
|
||||||
|
integration_client.delete(f"/api/v1/projects/{project_name}")
|
||||||
|
|
||||||
|
def test_project_team_info_in_response(self, integration_client, test_team, unique_test_id):
|
||||||
|
"""Test that project responses include team info."""
|
||||||
|
project_name = f"team-info-project-{unique_test_id}"
|
||||||
|
|
||||||
|
# Create project in team
|
||||||
|
integration_client.post(
|
||||||
|
"/api/v1/projects",
|
||||||
|
json={"name": project_name, "team_id": test_team["id"]},
|
||||||
|
)
|
||||||
|
|
||||||
|
# Get project and verify team info
|
||||||
|
response = integration_client.get(f"/api/v1/projects/{project_name}")
|
||||||
|
assert response.status_code == 200
|
||||||
|
|
||||||
|
data = response.json()
|
||||||
|
assert data["team_id"] == test_team["id"]
|
||||||
|
assert data["team_slug"] == test_team["slug"]
|
||||||
|
assert data["team_name"] == "Project Test Team"
|
||||||
|
|
||||||
|
# Cleanup
|
||||||
|
integration_client.delete(f"/api/v1/projects/{project_name}")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.integration
|
||||||
|
class TestTeamAuthorization:
|
||||||
|
"""Tests for team-based authorization."""
|
||||||
|
|
||||||
|
def test_cannot_delete_team_with_projects(self, integration_client, unique_test_id):
|
||||||
|
"""Test that teams with projects cannot be deleted."""
|
||||||
|
team_slug = f"nodelete-team-{unique_test_id}"
|
||||||
|
project_name = f"nodelete-project-{unique_test_id}"
|
||||||
|
|
||||||
|
# Create team
|
||||||
|
response = integration_client.post(
|
||||||
|
"/api/v1/teams",
|
||||||
|
json={"name": "No Delete Team", "slug": team_slug},
|
||||||
|
)
|
||||||
|
team_id = response.json()["id"]
|
||||||
|
|
||||||
|
# Create project in team
|
||||||
|
integration_client.post(
|
||||||
|
"/api/v1/projects",
|
||||||
|
json={"name": project_name, "team_id": team_id},
|
||||||
|
)
|
||||||
|
|
||||||
|
# Try to delete team - should fail
|
||||||
|
response = integration_client.delete(f"/api/v1/teams/{team_slug}")
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert "project" in response.json()["detail"].lower()
|
||||||
|
|
||||||
|
# Cleanup - delete project first, then team
|
||||||
|
integration_client.delete(f"/api/v1/projects/{project_name}")
|
||||||
|
integration_client.delete(f"/api/v1/teams/{team_slug}")
|
||||||
1946
backend/tests/test_upstream_caching.py
Normal file
1946
backend/tests/test_upstream_caching.py
Normal file
File diff suppressed because it is too large
Load Diff
213
backend/tests/unit/test_team_auth.py
Normal file
213
backend/tests/unit/test_team_auth.py
Normal file
@@ -0,0 +1,213 @@
|
|||||||
|
"""
|
||||||
|
Unit tests for TeamAuthorizationService.
|
||||||
|
"""
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from unittest.mock import MagicMock, patch
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
|
||||||
|
class TestTeamRoleHierarchy:
|
||||||
|
"""Tests for team role hierarchy functions."""
|
||||||
|
|
||||||
|
def test_get_team_role_rank(self):
|
||||||
|
"""Test role ranking."""
|
||||||
|
from app.auth import get_team_role_rank
|
||||||
|
|
||||||
|
assert get_team_role_rank("member") == 0
|
||||||
|
assert get_team_role_rank("admin") == 1
|
||||||
|
assert get_team_role_rank("owner") == 2
|
||||||
|
assert get_team_role_rank("invalid") == -1
|
||||||
|
|
||||||
|
def test_has_sufficient_team_role(self):
|
||||||
|
"""Test role sufficiency checks."""
|
||||||
|
from app.auth import has_sufficient_team_role
|
||||||
|
|
||||||
|
# Same role should be sufficient
|
||||||
|
assert has_sufficient_team_role("member", "member") is True
|
||||||
|
assert has_sufficient_team_role("admin", "admin") is True
|
||||||
|
assert has_sufficient_team_role("owner", "owner") is True
|
||||||
|
|
||||||
|
# Higher role should be sufficient for lower requirements
|
||||||
|
assert has_sufficient_team_role("admin", "member") is True
|
||||||
|
assert has_sufficient_team_role("owner", "member") is True
|
||||||
|
assert has_sufficient_team_role("owner", "admin") is True
|
||||||
|
|
||||||
|
# Lower role should NOT be sufficient for higher requirements
|
||||||
|
assert has_sufficient_team_role("member", "admin") is False
|
||||||
|
assert has_sufficient_team_role("member", "owner") is False
|
||||||
|
assert has_sufficient_team_role("admin", "owner") is False
|
||||||
|
|
||||||
|
|
||||||
|
class TestTeamAuthorizationService:
|
||||||
|
"""Tests for TeamAuthorizationService class."""
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def mock_db(self):
|
||||||
|
"""Create a mock database session."""
|
||||||
|
return MagicMock()
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def mock_user(self):
|
||||||
|
"""Create a mock user."""
|
||||||
|
user = MagicMock()
|
||||||
|
user.id = uuid.uuid4()
|
||||||
|
user.username = "testuser"
|
||||||
|
user.is_admin = False
|
||||||
|
return user
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def mock_admin_user(self):
|
||||||
|
"""Create a mock admin user."""
|
||||||
|
user = MagicMock()
|
||||||
|
user.id = uuid.uuid4()
|
||||||
|
user.username = "adminuser"
|
||||||
|
user.is_admin = True
|
||||||
|
return user
|
||||||
|
|
||||||
|
def test_get_user_team_role_no_user(self, mock_db):
|
||||||
|
"""Test that None is returned for anonymous users."""
|
||||||
|
from app.auth import TeamAuthorizationService
|
||||||
|
|
||||||
|
service = TeamAuthorizationService(mock_db)
|
||||||
|
result = service.get_user_team_role("team-id", None)
|
||||||
|
assert result is None
|
||||||
|
|
||||||
|
def test_get_user_team_role_admin_user(self, mock_db, mock_admin_user):
|
||||||
|
"""Test that system admins who are not members get admin role."""
|
||||||
|
from app.auth import TeamAuthorizationService
|
||||||
|
|
||||||
|
# Mock no membership found
|
||||||
|
mock_db.query.return_value.filter.return_value.first.return_value = None
|
||||||
|
|
||||||
|
service = TeamAuthorizationService(mock_db)
|
||||||
|
result = service.get_user_team_role("team-id", mock_admin_user)
|
||||||
|
assert result == "admin"
|
||||||
|
|
||||||
|
def test_get_user_team_role_member(self, mock_db, mock_user):
|
||||||
|
"""Test getting role for a team member."""
|
||||||
|
from app.auth import TeamAuthorizationService
|
||||||
|
|
||||||
|
# Mock the membership query
|
||||||
|
mock_membership = MagicMock()
|
||||||
|
mock_membership.role = "member"
|
||||||
|
mock_db.query.return_value.filter.return_value.first.return_value = mock_membership
|
||||||
|
|
||||||
|
service = TeamAuthorizationService(mock_db)
|
||||||
|
result = service.get_user_team_role("team-id", mock_user)
|
||||||
|
assert result == "member"
|
||||||
|
|
||||||
|
def test_get_user_team_role_not_member(self, mock_db, mock_user):
|
||||||
|
"""Test getting role for a non-member."""
|
||||||
|
from app.auth import TeamAuthorizationService
|
||||||
|
|
||||||
|
# Mock no membership found
|
||||||
|
mock_db.query.return_value.filter.return_value.first.return_value = None
|
||||||
|
|
||||||
|
service = TeamAuthorizationService(mock_db)
|
||||||
|
result = service.get_user_team_role("team-id", mock_user)
|
||||||
|
assert result is None
|
||||||
|
|
||||||
|
def test_check_team_access_member(self, mock_db, mock_user):
|
||||||
|
"""Test access check for member requiring member role."""
|
||||||
|
from app.auth import TeamAuthorizationService
|
||||||
|
|
||||||
|
# Mock the membership query
|
||||||
|
mock_membership = MagicMock()
|
||||||
|
mock_membership.role = "member"
|
||||||
|
mock_db.query.return_value.filter.return_value.first.return_value = mock_membership
|
||||||
|
|
||||||
|
service = TeamAuthorizationService(mock_db)
|
||||||
|
|
||||||
|
# Member should have member access
|
||||||
|
assert service.check_team_access("team-id", mock_user, "member") is True
|
||||||
|
# Member should not have admin access
|
||||||
|
assert service.check_team_access("team-id", mock_user, "admin") is False
|
||||||
|
# Member should not have owner access
|
||||||
|
assert service.check_team_access("team-id", mock_user, "owner") is False
|
||||||
|
|
||||||
|
def test_check_team_access_admin(self, mock_db, mock_user):
|
||||||
|
"""Test access check for admin role."""
|
||||||
|
from app.auth import TeamAuthorizationService
|
||||||
|
|
||||||
|
# Mock admin membership
|
||||||
|
mock_membership = MagicMock()
|
||||||
|
mock_membership.role = "admin"
|
||||||
|
mock_db.query.return_value.filter.return_value.first.return_value = mock_membership
|
||||||
|
|
||||||
|
service = TeamAuthorizationService(mock_db)
|
||||||
|
|
||||||
|
assert service.check_team_access("team-id", mock_user, "member") is True
|
||||||
|
assert service.check_team_access("team-id", mock_user, "admin") is True
|
||||||
|
assert service.check_team_access("team-id", mock_user, "owner") is False
|
||||||
|
|
||||||
|
def test_check_team_access_owner(self, mock_db, mock_user):
|
||||||
|
"""Test access check for owner role."""
|
||||||
|
from app.auth import TeamAuthorizationService
|
||||||
|
|
||||||
|
# Mock owner membership
|
||||||
|
mock_membership = MagicMock()
|
||||||
|
mock_membership.role = "owner"
|
||||||
|
mock_db.query.return_value.filter.return_value.first.return_value = mock_membership
|
||||||
|
|
||||||
|
service = TeamAuthorizationService(mock_db)
|
||||||
|
|
||||||
|
assert service.check_team_access("team-id", mock_user, "member") is True
|
||||||
|
assert service.check_team_access("team-id", mock_user, "admin") is True
|
||||||
|
assert service.check_team_access("team-id", mock_user, "owner") is True
|
||||||
|
|
||||||
|
def test_can_create_project(self, mock_db, mock_user):
|
||||||
|
"""Test can_create_project requires admin role."""
|
||||||
|
from app.auth import TeamAuthorizationService
|
||||||
|
|
||||||
|
service = TeamAuthorizationService(mock_db)
|
||||||
|
|
||||||
|
# Member cannot create projects
|
||||||
|
mock_membership = MagicMock()
|
||||||
|
mock_membership.role = "member"
|
||||||
|
mock_db.query.return_value.filter.return_value.first.return_value = mock_membership
|
||||||
|
assert service.can_create_project("team-id", mock_user) is False
|
||||||
|
|
||||||
|
# Admin can create projects
|
||||||
|
mock_membership.role = "admin"
|
||||||
|
assert service.can_create_project("team-id", mock_user) is True
|
||||||
|
|
||||||
|
# Owner can create projects
|
||||||
|
mock_membership.role = "owner"
|
||||||
|
assert service.can_create_project("team-id", mock_user) is True
|
||||||
|
|
||||||
|
def test_can_manage_members(self, mock_db, mock_user):
|
||||||
|
"""Test can_manage_members requires admin role."""
|
||||||
|
from app.auth import TeamAuthorizationService
|
||||||
|
|
||||||
|
service = TeamAuthorizationService(mock_db)
|
||||||
|
|
||||||
|
# Member cannot manage members
|
||||||
|
mock_membership = MagicMock()
|
||||||
|
mock_membership.role = "member"
|
||||||
|
mock_db.query.return_value.filter.return_value.first.return_value = mock_membership
|
||||||
|
assert service.can_manage_members("team-id", mock_user) is False
|
||||||
|
|
||||||
|
# Admin can manage members
|
||||||
|
mock_membership.role = "admin"
|
||||||
|
assert service.can_manage_members("team-id", mock_user) is True
|
||||||
|
|
||||||
|
def test_can_delete_team(self, mock_db, mock_user):
|
||||||
|
"""Test can_delete_team requires owner role."""
|
||||||
|
from app.auth import TeamAuthorizationService
|
||||||
|
|
||||||
|
service = TeamAuthorizationService(mock_db)
|
||||||
|
|
||||||
|
# Member cannot delete team
|
||||||
|
mock_membership = MagicMock()
|
||||||
|
mock_membership.role = "member"
|
||||||
|
mock_db.query.return_value.filter.return_value.first.return_value = mock_membership
|
||||||
|
assert service.can_delete_team("team-id", mock_user) is False
|
||||||
|
|
||||||
|
# Admin cannot delete team
|
||||||
|
mock_membership.role = "admin"
|
||||||
|
assert service.can_delete_team("team-id", mock_user) is False
|
||||||
|
|
||||||
|
# Only owner can delete team
|
||||||
|
mock_membership.role = "owner"
|
||||||
|
assert service.can_delete_team("team-id", mock_user) is True
|
||||||
672
docs/epic-upstream-caching.md
Normal file
672
docs/epic-upstream-caching.md
Normal file
@@ -0,0 +1,672 @@
|
|||||||
|
# Epic: Upstream Artifact Caching for Hermetic Builds
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
Orchard will act as a permanent, content-addressable cache for upstream artifacts (npm, PyPI, Maven, Docker, etc.). Once an artifact is cached, it is stored forever by SHA256 hash - enabling reproducible builds years later regardless of whether the upstream source still exists.
|
||||||
|
|
||||||
|
## Problem Statement
|
||||||
|
|
||||||
|
Build reproducibility is critical for enterprise environments:
|
||||||
|
- Packages get deleted, yanked, or modified upstream
|
||||||
|
- Registries go down or change URLs
|
||||||
|
- Version constraints resolve differently over time
|
||||||
|
- Air-gapped environments cannot access public internet
|
||||||
|
|
||||||
|
Teams need to guarantee that a build from 5 years ago produces the exact same output today.
|
||||||
|
|
||||||
|
## Solution
|
||||||
|
|
||||||
|
Orchard becomes "the cache that never forgets":
|
||||||
|
|
||||||
|
1. **Fetch once, store forever** - When a build needs `lodash@4.17.21`, Orchard fetches it from npm, stores it by SHA256 hash, and never deletes it
|
||||||
|
2. **Content-addressable** - Same hash = same bytes, guaranteed
|
||||||
|
3. **Format-agnostic** - Orchard doesn't need to understand npm/PyPI/Maven protocols; the client provides the URL, Orchard fetches and stores
|
||||||
|
4. **Air-gap support** - Disable public internet entirely, only allow configured private upstreams
|
||||||
|
|
||||||
|
## User Workflow
|
||||||
|
|
||||||
|
```
|
||||||
|
1. Build tool resolves dependencies npm install / pip install / mvn resolve
|
||||||
|
↓
|
||||||
|
2. Generate lockfile with URLs package-lock.json / requirements.txt
|
||||||
|
↓
|
||||||
|
3. Cache all URLs in Orchard orchard cache --file urls.txt
|
||||||
|
↓
|
||||||
|
4. Pin by SHA256 hash lodash = "sha256:abc123..."
|
||||||
|
↓
|
||||||
|
5. Future builds fetch by hash Always get exact same bytes
|
||||||
|
```
|
||||||
|
|
||||||
|
## Key Features
|
||||||
|
|
||||||
|
- **Multiple upstream sources** - Configure npm, PyPI, Maven Central, private Artifactory, etc.
|
||||||
|
- **Per-source authentication** - Basic auth, bearer tokens, API keys
|
||||||
|
- **System cache projects** - `_npm`, `_pypi`, `_maven` organize cached packages by format
|
||||||
|
- **Cross-referencing** - Link cached artifacts to user projects for visibility
|
||||||
|
- **URL tracking** - Know which URLs map to which hashes, audit provenance
|
||||||
|
- **Air-gap mode** - Global kill switch for all public internet access
|
||||||
|
- **Environment variable config** - 12-factor friendly for containerized deployments
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────────────────────┐
|
||||||
|
│ Orchard Server │
|
||||||
|
├─────────────────────────────────────────────────────────────────┤
|
||||||
|
│ POST /api/v1/cache │
|
||||||
|
│ ├── Check if URL already cached (url_hash lookup) │
|
||||||
|
│ ├── Match URL to upstream source (get auth) │
|
||||||
|
│ ├── Fetch via UpstreamClient (stream + compute SHA256) │
|
||||||
|
│ ├── Store artifact in S3 (content-addressable) │
|
||||||
|
│ ├── Create tag in system project (_npm/lodash:4.17.21) │
|
||||||
|
│ ├── Optionally create tag in user project │
|
||||||
|
│ └── Record in cached_urls table (provenance) │
|
||||||
|
├─────────────────────────────────────────────────────────────────┤
|
||||||
|
│ Tables │
|
||||||
|
│ ├── upstream_sources (npm-public, pypi-public, artifactory) │
|
||||||
|
│ ├── cache_settings (allow_public_internet, etc.) │
|
||||||
|
│ ├── cached_urls (url → artifact_id mapping) │
|
||||||
|
│ └── projects.is_system (for _npm, _pypi, etc.) │
|
||||||
|
└─────────────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
## Issues Summary
|
||||||
|
|
||||||
|
| Issue | Title | Status | Dependencies |
|
||||||
|
|-------|-------|--------|--------------|
|
||||||
|
| #68 | Schema: Upstream Sources & Cache Tracking | ✅ Complete | None |
|
||||||
|
| #69 | HTTP Client: Generic URL Fetcher | Pending | None |
|
||||||
|
| #70 | Cache API Endpoint | Pending | #68, #69 |
|
||||||
|
| #71 | System Projects (Cache Namespaces) | Pending | #68, #70 |
|
||||||
|
| #72 | Upstream Sources Admin API | Pending | #68 |
|
||||||
|
| #73 | Global Cache Settings API | Pending | #68 |
|
||||||
|
| #74 | Environment Variable Overrides | Pending | #68, #72, #73 |
|
||||||
|
| #75 | Frontend: Upstream Sources Management | Pending | #72, #73 |
|
||||||
|
| #105 | Frontend: System Projects Integration | Pending | #71 |
|
||||||
|
| #77 | CLI: Cache Command | Pending | #70 |
|
||||||
|
|
||||||
|
## Implementation Phases
|
||||||
|
|
||||||
|
**Phase 1 - Core (MVP):**
|
||||||
|
- #68 Schema ✅
|
||||||
|
- #69 HTTP Client
|
||||||
|
- #70 Cache API
|
||||||
|
- #71 System Projects
|
||||||
|
|
||||||
|
**Phase 2 - Admin:**
|
||||||
|
- #72 Upstream Sources API
|
||||||
|
- #73 Cache Settings API
|
||||||
|
- #74 Environment Variables
|
||||||
|
|
||||||
|
**Phase 3 - Frontend:**
|
||||||
|
- #75 Upstream Sources UI
|
||||||
|
- #105 System Projects UI
|
||||||
|
|
||||||
|
**Phase 4 - CLI:**
|
||||||
|
- #77 Cache Command
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Issue #68: Schema - Upstream Sources & Cache Tracking
|
||||||
|
|
||||||
|
**Status: ✅ Complete**
|
||||||
|
|
||||||
|
## Description
|
||||||
|
|
||||||
|
Create database schema for flexible multi-source upstream configuration and URL-to-artifact tracking. This replaces the previous singleton proxy_config design with a more flexible model supporting multiple upstream sources, air-gap mode, and provenance tracking.
|
||||||
|
|
||||||
|
## Acceptance Criteria
|
||||||
|
|
||||||
|
- [x] `upstream_sources` table:
|
||||||
|
- id (UUID, primary key)
|
||||||
|
- name (VARCHAR(255), unique, e.g., "npm-public", "artifactory-private")
|
||||||
|
- source_type (VARCHAR(50), enum: npm, pypi, maven, docker, helm, nuget, deb, rpm, generic)
|
||||||
|
- url (VARCHAR(2048), base URL of upstream)
|
||||||
|
- enabled (BOOLEAN, default false)
|
||||||
|
- is_public (BOOLEAN, true if this is a public internet source)
|
||||||
|
- auth_type (VARCHAR(20), enum: none, basic, bearer, api_key)
|
||||||
|
- username (VARCHAR(255), nullable)
|
||||||
|
- password_encrypted (BYTEA, nullable, Fernet encrypted)
|
||||||
|
- headers_encrypted (BYTEA, nullable, for custom headers like API keys)
|
||||||
|
- priority (INTEGER, default 100, lower = checked first)
|
||||||
|
- created_at, updated_at timestamps
|
||||||
|
- [x] `cache_settings` table (singleton, id always 1):
|
||||||
|
- id (INTEGER, primary key, check id = 1)
|
||||||
|
- allow_public_internet (BOOLEAN, default true, air-gap kill switch)
|
||||||
|
- auto_create_system_projects (BOOLEAN, default true)
|
||||||
|
- created_at, updated_at timestamps
|
||||||
|
- [x] `cached_urls` table:
|
||||||
|
- id (UUID, primary key)
|
||||||
|
- url (VARCHAR(4096), original URL fetched)
|
||||||
|
- url_hash (VARCHAR(64), SHA256 of URL for fast lookup, indexed)
|
||||||
|
- artifact_id (VARCHAR(64), FK to artifacts)
|
||||||
|
- source_id (UUID, FK to upstream_sources, nullable for manual imports)
|
||||||
|
- fetched_at (TIMESTAMP WITH TIME ZONE)
|
||||||
|
- response_headers (JSONB, original upstream headers for provenance)
|
||||||
|
- created_at timestamp
|
||||||
|
- [x] Add `is_system` BOOLEAN column to projects table (default false)
|
||||||
|
- [x] Migration SQL file in migrations/
|
||||||
|
- [x] Runtime migration in database.py
|
||||||
|
- [x] SQLAlchemy models for all new tables
|
||||||
|
- [x] Pydantic schemas for API input/output (passwords write-only)
|
||||||
|
- [x] Encryption helpers for password/headers fields
|
||||||
|
- [x] Seed default upstream sources (disabled by default):
|
||||||
|
- npm-public: https://registry.npmjs.org
|
||||||
|
- pypi-public: https://pypi.org/simple
|
||||||
|
- maven-central: https://repo1.maven.org/maven2
|
||||||
|
- docker-hub: https://registry-1.docker.io
|
||||||
|
- [x] Unit tests for models and schemas
|
||||||
|
|
||||||
|
## Files Modified
|
||||||
|
|
||||||
|
- `migrations/010_upstream_caching.sql`
|
||||||
|
- `backend/app/database.py` (migrations 016-020)
|
||||||
|
- `backend/app/models.py` (UpstreamSource, CacheSettings, CachedUrl, Project.is_system)
|
||||||
|
- `backend/app/schemas.py` (all caching schemas)
|
||||||
|
- `backend/app/encryption.py` (renamed env var)
|
||||||
|
- `backend/app/config.py` (renamed setting)
|
||||||
|
- `backend/tests/test_upstream_caching.py` (37 tests)
|
||||||
|
- `frontend/src/components/Layout.tsx` (footer tagline)
|
||||||
|
- `CHANGELOG.md`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Issue #69: HTTP Client - Generic URL Fetcher
|
||||||
|
|
||||||
|
**Status: Pending**
|
||||||
|
|
||||||
|
## Description
|
||||||
|
|
||||||
|
Create a reusable HTTP client for fetching artifacts from upstream sources. Supports multiple auth methods, streaming for large files, and computes SHA256 while downloading.
|
||||||
|
|
||||||
|
## Acceptance Criteria
|
||||||
|
|
||||||
|
- [ ] `UpstreamClient` class in `backend/app/upstream.py`
|
||||||
|
- [ ] `fetch(url)` method that:
|
||||||
|
- Streams response body (doesn't load large files into memory)
|
||||||
|
- Computes SHA256 hash while streaming
|
||||||
|
- Returns file content, hash, size, and response headers
|
||||||
|
- [ ] Auth support based on upstream source configuration:
|
||||||
|
- None (anonymous)
|
||||||
|
- Basic auth (username/password)
|
||||||
|
- Bearer token (Authorization: Bearer {token})
|
||||||
|
- API key (custom header name/value)
|
||||||
|
- [ ] URL-to-source matching:
|
||||||
|
- Match URL to configured upstream source by URL prefix
|
||||||
|
- Apply auth from matched source
|
||||||
|
- Respect source priority for multiple matches
|
||||||
|
- [ ] Configuration options:
|
||||||
|
- Timeout (connect and read, default 30s/300s)
|
||||||
|
- Max retries (default 3)
|
||||||
|
- Follow redirects (default true, max 5)
|
||||||
|
- Max file size (reject if Content-Length exceeds limit)
|
||||||
|
- [ ] Respect `allow_public_internet` setting:
|
||||||
|
- If false, reject URLs matching `is_public=true` sources
|
||||||
|
- If false, reject URLs not matching any configured source
|
||||||
|
- [ ] Capture response headers for provenance tracking
|
||||||
|
- [ ] Proper error handling:
|
||||||
|
- Connection errors (retry with backoff)
|
||||||
|
- HTTP errors (4xx, 5xx)
|
||||||
|
- Timeout errors
|
||||||
|
- SSL/TLS errors
|
||||||
|
- [ ] Logging for debugging (URL, source matched, status, timing)
|
||||||
|
- [ ] Unit tests with mocked HTTP responses
|
||||||
|
- [ ] Integration tests against httpbin.org or similar (optional, marked)
|
||||||
|
|
||||||
|
## Technical Notes
|
||||||
|
|
||||||
|
- Use `httpx` for async HTTP support (already in requirements)
|
||||||
|
- Stream to temp file to avoid memory issues with large artifacts
|
||||||
|
- Consider checksum verification if upstream provides it (e.g., npm provides shasum)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Issue #70: Cache API Endpoint
|
||||||
|
|
||||||
|
**Status: Pending**
|
||||||
|
|
||||||
|
## Description
|
||||||
|
|
||||||
|
API endpoint to cache an artifact from an upstream URL. This is the core endpoint that fetches from upstream, stores in Orchard, and creates appropriate tags.
|
||||||
|
|
||||||
|
## Acceptance Criteria
|
||||||
|
|
||||||
|
- [ ] `POST /api/v1/cache` endpoint
|
||||||
|
- [ ] Request body:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"url": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
|
||||||
|
"source_type": "npm",
|
||||||
|
"package_name": "lodash",
|
||||||
|
"tag": "4.17.21",
|
||||||
|
"user_project": "my-app",
|
||||||
|
"user_package": "npm-deps",
|
||||||
|
"user_tag": "lodash-4.17.21",
|
||||||
|
"expected_hash": "sha256:abc123..."
|
||||||
|
}
|
||||||
|
```
|
||||||
|
- `url` (required): URL to fetch
|
||||||
|
- `source_type` (required): Determines system project (_npm, _pypi, etc.)
|
||||||
|
- `package_name` (optional): Package name in system project, derived from URL if not provided
|
||||||
|
- `tag` (optional): Tag name in system project, derived from URL if not provided
|
||||||
|
- `user_project`, `user_package`, `user_tag` (optional): Cross-reference in user's project
|
||||||
|
- `expected_hash` (optional): Verify downloaded content matches
|
||||||
|
- [ ] Response:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"artifact_id": "abc123...",
|
||||||
|
"sha256": "abc123...",
|
||||||
|
"size": 12345,
|
||||||
|
"content_type": "application/gzip",
|
||||||
|
"already_cached": false,
|
||||||
|
"source_url": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
|
||||||
|
"source_name": "npm-public",
|
||||||
|
"system_project": "_npm",
|
||||||
|
"system_package": "lodash",
|
||||||
|
"system_tag": "4.17.21",
|
||||||
|
"user_reference": "my-app/npm-deps:lodash-4.17.21"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
- [ ] Behavior:
|
||||||
|
- Check if URL already cached (by url_hash in cached_urls)
|
||||||
|
- If cached: return existing artifact, optionally create user tag
|
||||||
|
- If not cached: fetch via UpstreamClient, store artifact, create tags
|
||||||
|
- Create/get system project if needed (e.g., `_npm`)
|
||||||
|
- Create package in system project (e.g., `_npm/lodash`)
|
||||||
|
- Create tag in system project (e.g., `_npm/lodash:4.17.21`)
|
||||||
|
- If user reference provided, create tag in user's project
|
||||||
|
- Record in cached_urls table with provenance
|
||||||
|
- [ ] Error handling:
|
||||||
|
- 400: Invalid request (bad URL format, missing required fields)
|
||||||
|
- 403: Air-gap mode enabled and URL is from public source
|
||||||
|
- 404: Upstream returned 404
|
||||||
|
- 409: Hash mismatch (if expected_hash provided)
|
||||||
|
- 502: Upstream fetch failed (connection error, timeout)
|
||||||
|
- 503: Upstream source disabled
|
||||||
|
- [ ] Authentication required (any authenticated user can cache)
|
||||||
|
- [ ] Audit logging for cache operations
|
||||||
|
- [ ] Integration tests covering success and error cases
|
||||||
|
|
||||||
|
## Technical Notes
|
||||||
|
|
||||||
|
- URL parsing for package_name/tag derivation is format-specific:
|
||||||
|
- npm: `/{package}/-/{package}-{version}.tgz` → package=lodash, tag=4.17.21
|
||||||
|
- pypi: `/packages/.../requests-2.28.0.tar.gz` → package=requests, tag=2.28.0
|
||||||
|
- maven: `/{group}/{artifact}/{version}/{artifact}-{version}.jar`
|
||||||
|
- Deduplication: if same SHA256 already exists, just create new tag pointing to it
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Issue #71: System Projects (Cache Namespaces)
|
||||||
|
|
||||||
|
**Status: Pending**
|
||||||
|
|
||||||
|
## Description
|
||||||
|
|
||||||
|
Implement auto-created system projects for organizing cached artifacts by format type. These are special projects that provide a browsable namespace for all cached upstream packages.
|
||||||
|
|
||||||
|
## Acceptance Criteria
|
||||||
|
|
||||||
|
- [ ] System project names: `_npm`, `_pypi`, `_maven`, `_docker`, `_helm`, `_nuget`, `_deb`, `_rpm`, `_generic`
|
||||||
|
- [ ] Auto-creation:
|
||||||
|
- Created automatically on first cache request for that format
|
||||||
|
- Created by cache endpoint, not at startup
|
||||||
|
- Uses system user as creator (`created_by = "system"`)
|
||||||
|
- [ ] System project properties:
|
||||||
|
- `is_system = true`
|
||||||
|
- `is_public = true` (readable by all authenticated users)
|
||||||
|
- `description` = "System cache for {format} packages"
|
||||||
|
- [ ] Restrictions:
|
||||||
|
- Cannot be deleted (return 403 with message)
|
||||||
|
- Cannot be renamed
|
||||||
|
- Cannot change `is_public` to false
|
||||||
|
- Only admins can modify description
|
||||||
|
- [ ] Helper function: `get_or_create_system_project(source_type)` in routes.py or new cache.py module
|
||||||
|
- [ ] Update project deletion endpoint to check `is_system` flag
|
||||||
|
- [ ] Update project update endpoint to enforce restrictions
|
||||||
|
- [ ] Query helper: list all system projects for UI dropdown
|
||||||
|
- [ ] Unit tests for restrictions
|
||||||
|
- [ ] Integration tests for auto-creation and restrictions
|
||||||
|
|
||||||
|
## Technical Notes
|
||||||
|
|
||||||
|
- System projects are identified by `is_system=true`, not just naming convention
|
||||||
|
- The `_` prefix is a convention for display purposes
|
||||||
|
- Packages within system projects follow upstream naming (e.g., `_npm/lodash`, `_npm/@types/node`)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Issue #72: Upstream Sources Admin API
|
||||||
|
|
||||||
|
**Status: Pending**
|
||||||
|
|
||||||
|
## Description
|
||||||
|
|
||||||
|
CRUD API endpoints for managing upstream sources configuration. Admin-only access.
|
||||||
|
|
||||||
|
## Acceptance Criteria
|
||||||
|
|
||||||
|
- [ ] `GET /api/v1/admin/upstream-sources` - List all upstream sources
|
||||||
|
- Returns array of sources with id, name, source_type, url, enabled, is_public, auth_type, priority, has_credentials, created_at, updated_at
|
||||||
|
- Supports `?enabled=true/false` filter
|
||||||
|
- Supports `?source_type=npm,pypi` filter
|
||||||
|
- Passwords/tokens never returned
|
||||||
|
- [ ] `POST /api/v1/admin/upstream-sources` - Create upstream source
|
||||||
|
- Request: name, source_type, url, enabled, is_public, auth_type, username, password, headers, priority
|
||||||
|
- Validates unique name
|
||||||
|
- Validates URL format
|
||||||
|
- Encrypts password/headers before storage
|
||||||
|
- Returns created source (without secrets)
|
||||||
|
- [ ] `GET /api/v1/admin/upstream-sources/{id}` - Get source details
|
||||||
|
- Returns source with `has_credentials` boolean, not actual credentials
|
||||||
|
- [ ] `PUT /api/v1/admin/upstream-sources/{id}` - Update source
|
||||||
|
- Partial update supported
|
||||||
|
- If password provided, re-encrypt; if omitted, keep existing
|
||||||
|
- Special value `password: null` clears credentials
|
||||||
|
- [ ] `DELETE /api/v1/admin/upstream-sources/{id}` - Delete source
|
||||||
|
- Returns 400 if source has cached_urls referencing it (optional: cascade or reassign)
|
||||||
|
- [ ] `POST /api/v1/admin/upstream-sources/{id}/test` - Test connectivity
|
||||||
|
- Attempts HEAD request to source URL
|
||||||
|
- Returns success/failure with status code and timing
|
||||||
|
- Does not cache anything
|
||||||
|
- [ ] All endpoints require admin role
|
||||||
|
- [ ] Audit logging for all mutations
|
||||||
|
- [ ] Pydantic schemas: UpstreamSourceCreate, UpstreamSourceUpdate, UpstreamSourceResponse
|
||||||
|
- [ ] Integration tests for all endpoints
|
||||||
|
|
||||||
|
## Technical Notes
|
||||||
|
|
||||||
|
- Test endpoint should respect auth configuration to verify credentials work
|
||||||
|
- Consider adding `last_used_at` and `last_error` fields for observability (future enhancement)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Issue #73: Global Cache Settings API
|
||||||
|
|
||||||
|
**Status: Pending**
|
||||||
|
|
||||||
|
## Description
|
||||||
|
|
||||||
|
API endpoints for managing global cache settings including air-gap mode.
|
||||||
|
|
||||||
|
## Acceptance Criteria
|
||||||
|
|
||||||
|
- [ ] `GET /api/v1/admin/cache-settings` - Get current settings
|
||||||
|
- Returns: allow_public_internet, auto_create_system_projects, created_at, updated_at
|
||||||
|
- [ ] `PUT /api/v1/admin/cache-settings` - Update settings
|
||||||
|
- Partial update supported
|
||||||
|
- Returns updated settings
|
||||||
|
- [ ] Settings fields:
|
||||||
|
- `allow_public_internet` (boolean): When false, blocks all requests to sources marked `is_public=true`
|
||||||
|
- `auto_create_system_projects` (boolean): When false, system projects must be created manually
|
||||||
|
- [ ] Admin-only access
|
||||||
|
- [ ] Audit logging for changes (especially air-gap mode changes)
|
||||||
|
- [ ] Pydantic schemas: CacheSettingsResponse, CacheSettingsUpdate
|
||||||
|
- [ ] Initialize singleton row on first access if not exists
|
||||||
|
- [ ] Integration tests
|
||||||
|
|
||||||
|
## Technical Notes
|
||||||
|
|
||||||
|
- Air-gap mode change should be logged prominently (security-relevant)
|
||||||
|
- Consider requiring confirmation header for disabling air-gap mode (similar to factory reset)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Issue #74: Environment Variable Overrides
|
||||||
|
|
||||||
|
**Status: Pending**
|
||||||
|
|
||||||
|
## Description
|
||||||
|
|
||||||
|
Allow cache and upstream configuration via environment variables for containerized deployments. Environment variables override database settings following 12-factor app principles.
|
||||||
|
|
||||||
|
## Acceptance Criteria
|
||||||
|
|
||||||
|
- [ ] Global settings overrides:
|
||||||
|
- `ORCHARD_CACHE_ALLOW_PUBLIC_INTERNET=true/false`
|
||||||
|
- `ORCHARD_CACHE_AUTO_CREATE_SYSTEM_PROJECTS=true/false`
|
||||||
|
- `ORCHARD_CACHE_ENCRYPTION_KEY` (Fernet key for credential encryption)
|
||||||
|
- [ ] Upstream source definition via env vars:
|
||||||
|
- `ORCHARD_UPSTREAM__{NAME}__URL` (double underscore as separator)
|
||||||
|
- `ORCHARD_UPSTREAM__{NAME}__TYPE` (npm, pypi, maven, etc.)
|
||||||
|
- `ORCHARD_UPSTREAM__{NAME}__ENABLED` (true/false)
|
||||||
|
- `ORCHARD_UPSTREAM__{NAME}__IS_PUBLIC` (true/false)
|
||||||
|
- `ORCHARD_UPSTREAM__{NAME}__AUTH_TYPE` (none, basic, bearer, api_key)
|
||||||
|
- `ORCHARD_UPSTREAM__{NAME}__USERNAME`
|
||||||
|
- `ORCHARD_UPSTREAM__{NAME}__PASSWORD`
|
||||||
|
- `ORCHARD_UPSTREAM__{NAME}__PRIORITY`
|
||||||
|
- Example: `ORCHARD_UPSTREAM__NPM_PRIVATE__URL=https://npm.corp.com`
|
||||||
|
- [ ] Env var sources:
|
||||||
|
- Loaded at startup
|
||||||
|
- Merged with database sources
|
||||||
|
- Env var sources have `source = "env"` marker
|
||||||
|
- Cannot be modified via API (return 400)
|
||||||
|
- Cannot be deleted via API (return 400)
|
||||||
|
- [ ] Update Settings class in config.py
|
||||||
|
- [ ] Update get/list endpoints to include env-defined sources
|
||||||
|
- [ ] Document all env vars in CLAUDE.md
|
||||||
|
- [ ] Unit tests for env var parsing
|
||||||
|
- [ ] Integration tests with env vars set
|
||||||
|
|
||||||
|
## Technical Notes
|
||||||
|
|
||||||
|
- Double underscore (`__`) separator allows source names with single underscores
|
||||||
|
- Env-defined sources should appear in API responses but marked as read-only
|
||||||
|
- Consider startup validation that warns about invalid env var combinations
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Issue #75: Frontend - Upstream Sources Management
|
||||||
|
|
||||||
|
**Status: Pending**
|
||||||
|
|
||||||
|
## Description
|
||||||
|
|
||||||
|
Admin UI for managing upstream sources and cache settings.
|
||||||
|
|
||||||
|
## Acceptance Criteria
|
||||||
|
|
||||||
|
- [ ] New admin page: `/admin/cache` or `/admin/upstream-sources`
|
||||||
|
- [ ] Upstream sources section:
|
||||||
|
- Table listing all sources with: name, type, URL, enabled toggle, public badge, priority, actions
|
||||||
|
- Visual distinction for env-defined sources (locked icon, no edit/delete)
|
||||||
|
- Create button opens modal/form
|
||||||
|
- Edit button for DB-defined sources
|
||||||
|
- Delete with confirmation modal
|
||||||
|
- Test connection button with status indicator
|
||||||
|
- [ ] Create/edit form fields:
|
||||||
|
- Name (text, required)
|
||||||
|
- Source type (dropdown)
|
||||||
|
- URL (text, required)
|
||||||
|
- Priority (number)
|
||||||
|
- Is public (checkbox)
|
||||||
|
- Enabled (checkbox)
|
||||||
|
- Auth type (dropdown: none, basic, bearer, api_key)
|
||||||
|
- Conditional auth fields based on type:
|
||||||
|
- Basic: username, password
|
||||||
|
- Bearer: token
|
||||||
|
- API key: header name, header value
|
||||||
|
- Password fields masked, "unchanged" placeholder on edit
|
||||||
|
- [ ] Cache settings section:
|
||||||
|
- Air-gap mode toggle with warning
|
||||||
|
- Auto-create system projects toggle
|
||||||
|
- "Air-gap mode" shows prominent warning banner when enabled
|
||||||
|
- [ ] Link from main admin navigation
|
||||||
|
- [ ] Loading and error states
|
||||||
|
- [ ] Success/error toast notifications
|
||||||
|
|
||||||
|
## Technical Notes
|
||||||
|
|
||||||
|
- Use existing admin page patterns from user management
|
||||||
|
- Air-gap toggle should require confirmation (modal with warning text)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Issue #105: Frontend - System Projects Integration
|
||||||
|
|
||||||
|
**Status: Pending**
|
||||||
|
|
||||||
|
## Description
|
||||||
|
|
||||||
|
Integrate system projects into the frontend UI with appropriate visual treatment and navigation.
|
||||||
|
|
||||||
|
## Acceptance Criteria
|
||||||
|
|
||||||
|
- [ ] Home page project dropdown:
|
||||||
|
- System projects shown in separate "Cached Packages" section
|
||||||
|
- Visual distinction (icon, different background, or badge)
|
||||||
|
- Format icon for each type (npm, pypi, maven, etc.)
|
||||||
|
- [ ] Project list/grid:
|
||||||
|
- System projects can be filtered: "Show system projects" toggle
|
||||||
|
- Or separate tab: "Projects" | "Package Cache"
|
||||||
|
- [ ] System project page:
|
||||||
|
- "System Cache" badge in header
|
||||||
|
- Description explains this is auto-managed cache
|
||||||
|
- Settings/delete buttons hidden or disabled
|
||||||
|
- Shows format type prominently
|
||||||
|
- [ ] Package page within system project:
|
||||||
|
- Shows "Cached from" with source URL (linked)
|
||||||
|
- Shows "First cached" timestamp
|
||||||
|
- Shows which upstream source provided it
|
||||||
|
- [ ] Artifact page:
|
||||||
|
- If artifact came from cache, show provenance:
|
||||||
|
- Original URL
|
||||||
|
- Upstream source name
|
||||||
|
- Fetch timestamp
|
||||||
|
- [ ] Search includes system projects (with filter option)
|
||||||
|
|
||||||
|
## Technical Notes
|
||||||
|
|
||||||
|
- Use React context or query params for system project filtering
|
||||||
|
- Consider dedicated route: `/cache/npm/lodash` as alias for `/_npm/lodash`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
# Issue #77: CLI - Cache Command
|
||||||
|
|
||||||
|
**Status: Pending**
|
||||||
|
|
||||||
|
## Description
|
||||||
|
|
||||||
|
Add a new `orchard cache` command to the existing CLI for caching artifacts from upstream URLs. This integrates with the new cache API endpoint and can optionally update `orchard.ensure` with cached artifacts.
|
||||||
|
|
||||||
|
## Acceptance Criteria
|
||||||
|
|
||||||
|
- [ ] New command: `orchard cache <url>` in `orchard/commands/cache.py`
|
||||||
|
- [ ] Basic usage:
|
||||||
|
```bash
|
||||||
|
# Cache a URL, print artifact info
|
||||||
|
orchard cache https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz
|
||||||
|
|
||||||
|
# Output:
|
||||||
|
# Caching https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz...
|
||||||
|
# Source type: npm
|
||||||
|
# Package: lodash
|
||||||
|
# Version: 4.17.21
|
||||||
|
#
|
||||||
|
# Successfully cached artifact
|
||||||
|
# Artifact ID: abc123...
|
||||||
|
# Size: 1.2 MB
|
||||||
|
# System project: _npm
|
||||||
|
# System package: lodash
|
||||||
|
# System tag: 4.17.21
|
||||||
|
```
|
||||||
|
- [ ] Options:
|
||||||
|
| Option | Description |
|
||||||
|
|--------|-------------|
|
||||||
|
| `--type, -t TYPE` | Source type: npm, pypi, maven, docker, helm, generic (auto-detected from URL if not provided) |
|
||||||
|
| `--package, -p NAME` | Package name in system project (auto-derived from URL if not provided) |
|
||||||
|
| `--tag TAG` | Tag name in system project (auto-derived from URL if not provided) |
|
||||||
|
| `--project PROJECT` | Also create tag in this user project |
|
||||||
|
| `--user-package PKG` | Package name in user project (required if --project specified) |
|
||||||
|
| `--user-tag TAG` | Tag name in user project (default: same as system tag) |
|
||||||
|
| `--expected-hash HASH` | Verify downloaded content matches this SHA256 |
|
||||||
|
| `--add` | Add to orchard.ensure after caching |
|
||||||
|
| `--add-path PATH` | Extraction path for --add (default: `<package>/`) |
|
||||||
|
| `--file, -f FILE` | Path to orchard.ensure file |
|
||||||
|
| `--verbose, -v` | Show detailed output |
|
||||||
|
- [ ] URL type auto-detection:
|
||||||
|
- `registry.npmjs.org` → npm
|
||||||
|
- `pypi.org` or `files.pythonhosted.org` → pypi
|
||||||
|
- `repo1.maven.org` or contains `/maven2/` → maven
|
||||||
|
- `registry-1.docker.io` or `docker.io` → docker
|
||||||
|
- Otherwise → generic
|
||||||
|
- [ ] Package/version extraction from URL patterns:
|
||||||
|
- npm: `/{package}/-/{package}-{version}.tgz`
|
||||||
|
- pypi: `/packages/.../requests-{version}.tar.gz`
|
||||||
|
- maven: `/{group}/{artifact}/{version}/{artifact}-{version}.jar`
|
||||||
|
- [ ] Add `cache_artifact()` function to `orchard/api.py`
|
||||||
|
- [ ] Integration with `--add` flag:
|
||||||
|
- Parse existing orchard.ensure
|
||||||
|
- Add new dependency entry pointing to cached artifact
|
||||||
|
- Use artifact_id (SHA256) for hermetic pinning
|
||||||
|
- [ ] Batch mode: `orchard cache --file urls.txt`
|
||||||
|
- One URL per line
|
||||||
|
- Lines starting with `#` are comments
|
||||||
|
- Report success/failure for each
|
||||||
|
- [ ] Exit codes:
|
||||||
|
- 0: Success (or already cached)
|
||||||
|
- 1: Fetch failed
|
||||||
|
- 2: Hash mismatch
|
||||||
|
- 3: Air-gap mode blocked request
|
||||||
|
- [ ] Error handling consistent with existing CLI patterns
|
||||||
|
- [ ] Unit tests in `test/test_cache.py`
|
||||||
|
- [ ] Update README.md with cache command documentation
|
||||||
|
|
||||||
|
## Technical Notes
|
||||||
|
|
||||||
|
- Follow existing Click patterns from other commands
|
||||||
|
- Use `get_auth_headers()` from `orchard/auth.py`
|
||||||
|
- URL parsing can use `urllib.parse`
|
||||||
|
- Consider adding URL pattern registry for extensibility
|
||||||
|
- The `--add` flag should integrate with existing ensure file parsing in `orchard/ensure.py`
|
||||||
|
|
||||||
|
## Example Workflows
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Simple: cache a single URL
|
||||||
|
orchard cache https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz
|
||||||
|
|
||||||
|
# Cache and add to orchard.ensure for current project
|
||||||
|
orchard cache https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz \
|
||||||
|
--add --add-path libs/lodash/
|
||||||
|
|
||||||
|
# Cache with explicit metadata
|
||||||
|
orchard cache https://internal.corp/files/custom-lib.tar.gz \
|
||||||
|
--type generic \
|
||||||
|
--package custom-lib \
|
||||||
|
--tag v1.0.0
|
||||||
|
|
||||||
|
# Cache and cross-reference to user project
|
||||||
|
orchard cache https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz \
|
||||||
|
--project my-app \
|
||||||
|
--user-package npm-deps \
|
||||||
|
--user-tag lodash-4.17.21
|
||||||
|
|
||||||
|
# Batch cache from file
|
||||||
|
orchard cache --file deps-urls.txt
|
||||||
|
|
||||||
|
# Verify hash while caching
|
||||||
|
orchard cache https://example.com/file.tar.gz \
|
||||||
|
--expected-hash sha256:abc123...
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Out of Scope (Future Enhancements)
|
||||||
|
|
||||||
|
- Automatic transitive dependency resolution (client's responsibility)
|
||||||
|
- Lockfile parsing (`package-lock.json`, `requirements.txt`) - stretch goal for CLI
|
||||||
|
- Cache eviction policies (we cache forever by design)
|
||||||
|
- Mirroring/sync between Orchard instances
|
||||||
|
- Format-specific metadata extraction (npm package.json parsing, etc.)
|
||||||
|
|
||||||
|
## Success Criteria
|
||||||
|
|
||||||
|
- [ ] Can cache any URL and retrieve by SHA256 hash
|
||||||
|
- [ ] Cached artifacts persist indefinitely
|
||||||
|
- [ ] Air-gap mode blocks all public internet access
|
||||||
|
- [ ] Multiple upstream sources with different auth
|
||||||
|
- [ ] System projects organize cached packages by format
|
||||||
|
- [ ] CLI can cache URLs and update orchard.ensure
|
||||||
|
- [ ] Admin UI for upstream source management
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
import { Routes, Route, Navigate, useLocation } from 'react-router-dom';
|
import { Routes, Route, Navigate, useLocation } from 'react-router-dom';
|
||||||
import { AuthProvider, useAuth } from './contexts/AuthContext';
|
import { AuthProvider, useAuth } from './contexts/AuthContext';
|
||||||
|
import { TeamProvider } from './contexts/TeamContext';
|
||||||
import Layout from './components/Layout';
|
import Layout from './components/Layout';
|
||||||
import Home from './pages/Home';
|
import Home from './pages/Home';
|
||||||
import ProjectPage from './pages/ProjectPage';
|
import ProjectPage from './pages/ProjectPage';
|
||||||
@@ -10,7 +11,12 @@ import ChangePasswordPage from './pages/ChangePasswordPage';
|
|||||||
import APIKeysPage from './pages/APIKeysPage';
|
import APIKeysPage from './pages/APIKeysPage';
|
||||||
import AdminUsersPage from './pages/AdminUsersPage';
|
import AdminUsersPage from './pages/AdminUsersPage';
|
||||||
import AdminOIDCPage from './pages/AdminOIDCPage';
|
import AdminOIDCPage from './pages/AdminOIDCPage';
|
||||||
|
import AdminCachePage from './pages/AdminCachePage';
|
||||||
import ProjectSettingsPage from './pages/ProjectSettingsPage';
|
import ProjectSettingsPage from './pages/ProjectSettingsPage';
|
||||||
|
import TeamsPage from './pages/TeamsPage';
|
||||||
|
import TeamDashboardPage from './pages/TeamDashboardPage';
|
||||||
|
import TeamSettingsPage from './pages/TeamSettingsPage';
|
||||||
|
import TeamMembersPage from './pages/TeamMembersPage';
|
||||||
|
|
||||||
// Component that checks if user must change password
|
// Component that checks if user must change password
|
||||||
function RequirePasswordChange({ children }: { children: React.ReactNode }) {
|
function RequirePasswordChange({ children }: { children: React.ReactNode }) {
|
||||||
@@ -45,6 +51,11 @@ function AppRoutes() {
|
|||||||
<Route path="/settings/api-keys" element={<APIKeysPage />} />
|
<Route path="/settings/api-keys" element={<APIKeysPage />} />
|
||||||
<Route path="/admin/users" element={<AdminUsersPage />} />
|
<Route path="/admin/users" element={<AdminUsersPage />} />
|
||||||
<Route path="/admin/oidc" element={<AdminOIDCPage />} />
|
<Route path="/admin/oidc" element={<AdminOIDCPage />} />
|
||||||
|
<Route path="/admin/cache" element={<AdminCachePage />} />
|
||||||
|
<Route path="/teams" element={<TeamsPage />} />
|
||||||
|
<Route path="/teams/:slug" element={<TeamDashboardPage />} />
|
||||||
|
<Route path="/teams/:slug/settings" element={<TeamSettingsPage />} />
|
||||||
|
<Route path="/teams/:slug/members" element={<TeamMembersPage />} />
|
||||||
<Route path="/project/:projectName" element={<ProjectPage />} />
|
<Route path="/project/:projectName" element={<ProjectPage />} />
|
||||||
<Route path="/project/:projectName/settings" element={<ProjectSettingsPage />} />
|
<Route path="/project/:projectName/settings" element={<ProjectSettingsPage />} />
|
||||||
<Route path="/project/:projectName/:packageName" element={<PackagePage />} />
|
<Route path="/project/:projectName/:packageName" element={<PackagePage />} />
|
||||||
@@ -60,7 +71,9 @@ function AppRoutes() {
|
|||||||
function App() {
|
function App() {
|
||||||
return (
|
return (
|
||||||
<AuthProvider>
|
<AuthProvider>
|
||||||
<AppRoutes />
|
<TeamProvider>
|
||||||
|
<AppRoutes />
|
||||||
|
</TeamProvider>
|
||||||
</AuthProvider>
|
</AuthProvider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -36,6 +36,18 @@ import {
|
|||||||
ArtifactDependenciesResponse,
|
ArtifactDependenciesResponse,
|
||||||
ReverseDependenciesResponse,
|
ReverseDependenciesResponse,
|
||||||
DependencyResolutionResponse,
|
DependencyResolutionResponse,
|
||||||
|
TeamDetail,
|
||||||
|
TeamMember,
|
||||||
|
TeamCreate,
|
||||||
|
TeamUpdate,
|
||||||
|
TeamMemberCreate,
|
||||||
|
TeamMemberUpdate,
|
||||||
|
UpstreamSource,
|
||||||
|
UpstreamSourceCreate,
|
||||||
|
UpstreamSourceUpdate,
|
||||||
|
UpstreamSourceTestResult,
|
||||||
|
CacheSettings,
|
||||||
|
CacheSettingsUpdate,
|
||||||
} from './types';
|
} from './types';
|
||||||
|
|
||||||
const API_BASE = '/api/v1';
|
const API_BASE = '/api/v1';
|
||||||
@@ -160,7 +172,7 @@ export async function listProjectsSimple(params: ListParams = {}): Promise<Proje
|
|||||||
return data.items;
|
return data.items;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function createProject(data: { name: string; description?: string; is_public?: boolean }): Promise<Project> {
|
export async function createProject(data: { name: string; description?: string; is_public?: boolean; team_id?: string }): Promise<Project> {
|
||||||
const response = await fetch(`${API_BASE}/projects`, {
|
const response = await fetch(`${API_BASE}/projects`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
@@ -562,3 +574,195 @@ export async function getEnsureFile(
|
|||||||
}
|
}
|
||||||
return response.text();
|
return response.text();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Team API
|
||||||
|
export async function listTeams(params: ListParams = {}): Promise<PaginatedResponse<TeamDetail>> {
|
||||||
|
const query = buildQueryString(params as Record<string, unknown>);
|
||||||
|
const response = await fetch(`${API_BASE}/teams${query}`, {
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
return handleResponse<PaginatedResponse<TeamDetail>>(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createTeam(data: TeamCreate): Promise<TeamDetail> {
|
||||||
|
const response = await fetch(`${API_BASE}/teams`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
return handleResponse<TeamDetail>(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getTeam(slug: string): Promise<TeamDetail> {
|
||||||
|
const response = await fetch(`${API_BASE}/teams/${slug}`, {
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
return handleResponse<TeamDetail>(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateTeam(slug: string, data: TeamUpdate): Promise<TeamDetail> {
|
||||||
|
const response = await fetch(`${API_BASE}/teams/${slug}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
return handleResponse<TeamDetail>(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteTeam(slug: string): Promise<void> {
|
||||||
|
const response = await fetch(`${API_BASE}/teams/${slug}`, {
|
||||||
|
method: 'DELETE',
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = await response.json().catch(() => ({ detail: 'Unknown error' }));
|
||||||
|
throw new ApiError(error.detail || `HTTP ${response.status}`, response.status);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listTeamMembers(slug: string): Promise<TeamMember[]> {
|
||||||
|
const response = await fetch(`${API_BASE}/teams/${slug}/members`, {
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
return handleResponse<TeamMember[]>(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function addTeamMember(slug: string, data: TeamMemberCreate): Promise<TeamMember> {
|
||||||
|
const response = await fetch(`${API_BASE}/teams/${slug}/members`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
return handleResponse<TeamMember>(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateTeamMember(
|
||||||
|
slug: string,
|
||||||
|
username: string,
|
||||||
|
data: TeamMemberUpdate
|
||||||
|
): Promise<TeamMember> {
|
||||||
|
const response = await fetch(`${API_BASE}/teams/${slug}/members/${username}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
return handleResponse<TeamMember>(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function removeTeamMember(slug: string, username: string): Promise<void> {
|
||||||
|
const response = await fetch(`${API_BASE}/teams/${slug}/members/${username}`, {
|
||||||
|
method: 'DELETE',
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = await response.json().catch(() => ({ detail: 'Unknown error' }));
|
||||||
|
throw new ApiError(error.detail || `HTTP ${response.status}`, response.status);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listTeamProjects(
|
||||||
|
slug: string,
|
||||||
|
params: ProjectListParams = {}
|
||||||
|
): Promise<PaginatedResponse<Project>> {
|
||||||
|
const query = buildQueryString(params as Record<string, unknown>);
|
||||||
|
const response = await fetch(`${API_BASE}/teams/${slug}/projects${query}`, {
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
return handleResponse<PaginatedResponse<Project>>(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
// User search (for autocomplete)
|
||||||
|
export interface UserSearchResult {
|
||||||
|
id: string;
|
||||||
|
username: string;
|
||||||
|
is_admin: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function searchUsers(query: string, limit: number = 10): Promise<UserSearchResult[]> {
|
||||||
|
const response = await fetch(`${API_BASE}/users/search?q=${encodeURIComponent(query)}&limit=${limit}`, {
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
return handleResponse<UserSearchResult[]>(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Upstream Sources Admin API
|
||||||
|
export interface UpstreamSourceListParams {
|
||||||
|
enabled?: boolean;
|
||||||
|
source_type?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listUpstreamSources(params: UpstreamSourceListParams = {}): Promise<UpstreamSource[]> {
|
||||||
|
const query = buildQueryString(params as Record<string, unknown>);
|
||||||
|
const response = await fetch(`${API_BASE}/admin/upstream-sources${query}`, {
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
return handleResponse<UpstreamSource[]>(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createUpstreamSource(data: UpstreamSourceCreate): Promise<UpstreamSource> {
|
||||||
|
const response = await fetch(`${API_BASE}/admin/upstream-sources`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
return handleResponse<UpstreamSource>(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function getUpstreamSource(id: string): Promise<UpstreamSource> {
|
||||||
|
const response = await fetch(`${API_BASE}/admin/upstream-sources/${id}`, {
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
return handleResponse<UpstreamSource>(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateUpstreamSource(id: string, data: UpstreamSourceUpdate): Promise<UpstreamSource> {
|
||||||
|
const response = await fetch(`${API_BASE}/admin/upstream-sources/${id}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
return handleResponse<UpstreamSource>(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteUpstreamSource(id: string): Promise<void> {
|
||||||
|
const response = await fetch(`${API_BASE}/admin/upstream-sources/${id}`, {
|
||||||
|
method: 'DELETE',
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = await response.json().catch(() => ({ detail: 'Unknown error' }));
|
||||||
|
throw new ApiError(error.detail || `HTTP ${response.status}`, response.status);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function testUpstreamSource(id: string): Promise<UpstreamSourceTestResult> {
|
||||||
|
const response = await fetch(`${API_BASE}/admin/upstream-sources/${id}/test`, {
|
||||||
|
method: 'POST',
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
return handleResponse<UpstreamSourceTestResult>(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cache Settings Admin API
|
||||||
|
export async function getCacheSettings(): Promise<CacheSettings> {
|
||||||
|
const response = await fetch(`${API_BASE}/admin/cache-settings`, {
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
return handleResponse<CacheSettings>(response);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateCacheSettings(data: CacheSettingsUpdate): Promise<CacheSettings> {
|
||||||
|
const response = await fetch(`${API_BASE}/admin/cache-settings`, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
return handleResponse<CacheSettings>(response);
|
||||||
|
}
|
||||||
|
|||||||
@@ -114,3 +114,32 @@
|
|||||||
font-size: 0.875rem;
|
font-size: 0.875rem;
|
||||||
color: var(--text-primary);
|
color: var(--text-primary);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Access source styling */
|
||||||
|
.access-source {
|
||||||
|
display: inline-block;
|
||||||
|
padding: 0.2rem 0.4rem;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.access-source--explicit {
|
||||||
|
background: var(--bg-tertiary);
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.access-source--team {
|
||||||
|
background: var(--color-info-bg, #e3f2fd);
|
||||||
|
color: var(--color-info, #1976d2);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Team access row styling */
|
||||||
|
.team-access-row {
|
||||||
|
background: var(--bg-secondary, #fafafa);
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-access-row td.actions .text-muted {
|
||||||
|
font-size: 0.8125rem;
|
||||||
|
font-style: italic;
|
||||||
|
}
|
||||||
|
|||||||
@@ -208,85 +208,104 @@ export function AccessManagement({ projectName }: AccessManagementProps) {
|
|||||||
<tr>
|
<tr>
|
||||||
<th>User</th>
|
<th>User</th>
|
||||||
<th>Access Level</th>
|
<th>Access Level</th>
|
||||||
|
<th>Source</th>
|
||||||
<th>Granted</th>
|
<th>Granted</th>
|
||||||
<th>Expires</th>
|
<th>Expires</th>
|
||||||
<th>Actions</th>
|
<th>Actions</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody>
|
||||||
{permissions.map((p) => (
|
{permissions.map((p) => {
|
||||||
<tr key={p.id}>
|
const isTeamBased = p.source === 'team';
|
||||||
<td>{p.user_id}</td>
|
return (
|
||||||
<td>
|
<tr key={p.id} className={isTeamBased ? 'team-access-row' : ''}>
|
||||||
{editingUser === p.user_id ? (
|
<td>{p.user_id}</td>
|
||||||
<select
|
<td>
|
||||||
value={editLevel}
|
{editingUser === p.user_id && !isTeamBased ? (
|
||||||
onChange={(e) => setEditLevel(e.target.value as AccessLevel)}
|
<select
|
||||||
disabled={submitting}
|
value={editLevel}
|
||||||
>
|
onChange={(e) => setEditLevel(e.target.value as AccessLevel)}
|
||||||
<option value="read">Read</option>
|
|
||||||
<option value="write">Write</option>
|
|
||||||
<option value="admin">Admin</option>
|
|
||||||
</select>
|
|
||||||
) : (
|
|
||||||
<span className={`access-badge access-badge--${p.level}`}>
|
|
||||||
{p.level}
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</td>
|
|
||||||
<td>{new Date(p.created_at).toLocaleDateString()}</td>
|
|
||||||
<td>
|
|
||||||
{editingUser === p.user_id ? (
|
|
||||||
<input
|
|
||||||
type="date"
|
|
||||||
value={editExpiresAt}
|
|
||||||
onChange={(e) => setEditExpiresAt(e.target.value)}
|
|
||||||
disabled={submitting}
|
|
||||||
min={new Date().toISOString().split('T')[0]}
|
|
||||||
/>
|
|
||||||
) : (
|
|
||||||
formatExpiration(p.expires_at)
|
|
||||||
)}
|
|
||||||
</td>
|
|
||||||
<td className="actions">
|
|
||||||
{editingUser === p.user_id ? (
|
|
||||||
<>
|
|
||||||
<button
|
|
||||||
className="btn btn-sm btn-primary"
|
|
||||||
onClick={() => handleUpdate(p.user_id)}
|
|
||||||
disabled={submitting}
|
disabled={submitting}
|
||||||
>
|
>
|
||||||
Save
|
<option value="read">Read</option>
|
||||||
</button>
|
<option value="write">Write</option>
|
||||||
<button
|
<option value="admin">Admin</option>
|
||||||
className="btn btn-sm"
|
</select>
|
||||||
onClick={cancelEdit}
|
) : (
|
||||||
|
<span className={`access-badge access-badge--${p.level}`}>
|
||||||
|
{p.level}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
{isTeamBased ? (
|
||||||
|
<span className="access-source access-source--team" title={`Team role: ${p.team_role}`}>
|
||||||
|
Team: {p.team_slug}
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span className="access-source access-source--explicit">
|
||||||
|
Explicit
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
<td>{new Date(p.created_at).toLocaleDateString()}</td>
|
||||||
|
<td>
|
||||||
|
{editingUser === p.user_id && !isTeamBased ? (
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
value={editExpiresAt}
|
||||||
|
onChange={(e) => setEditExpiresAt(e.target.value)}
|
||||||
disabled={submitting}
|
disabled={submitting}
|
||||||
>
|
min={new Date().toISOString().split('T')[0]}
|
||||||
Cancel
|
/>
|
||||||
</button>
|
) : (
|
||||||
</>
|
formatExpiration(p.expires_at)
|
||||||
) : (
|
)}
|
||||||
<>
|
</td>
|
||||||
<button
|
<td className="actions">
|
||||||
className="btn btn-sm"
|
{isTeamBased ? (
|
||||||
onClick={() => startEdit(p)}
|
<span className="text-muted" title="Manage access via team settings">
|
||||||
disabled={submitting}
|
Via team
|
||||||
>
|
</span>
|
||||||
Edit
|
) : editingUser === p.user_id ? (
|
||||||
</button>
|
<>
|
||||||
<button
|
<button
|
||||||
className="btn btn-sm btn-danger"
|
className="btn btn-sm btn-primary"
|
||||||
onClick={() => handleRevoke(p.user_id)}
|
onClick={() => handleUpdate(p.user_id)}
|
||||||
disabled={submitting}
|
disabled={submitting}
|
||||||
>
|
>
|
||||||
Revoke
|
Save
|
||||||
</button>
|
</button>
|
||||||
</>
|
<button
|
||||||
)}
|
className="btn btn-sm"
|
||||||
</td>
|
onClick={cancelEdit}
|
||||||
</tr>
|
disabled={submitting}
|
||||||
))}
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
className="btn btn-sm"
|
||||||
|
onClick={() => startEdit(p)}
|
||||||
|
disabled={submitting}
|
||||||
|
>
|
||||||
|
Edit
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className="btn btn-sm btn-danger"
|
||||||
|
onClick={() => handleRevoke(p.user_id)}
|
||||||
|
disabled={submitting}
|
||||||
|
>
|
||||||
|
Revoke
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
);
|
||||||
|
})}
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -284,7 +284,11 @@
|
|||||||
.footer-brand {
|
.footer-brand {
|
||||||
display: flex;
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
gap: 12px;
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.footer-icon {
|
||||||
|
color: var(--accent-primary);
|
||||||
}
|
}
|
||||||
|
|
||||||
.footer-logo {
|
.footer-logo {
|
||||||
@@ -292,6 +296,10 @@
|
|||||||
color: var(--text-primary);
|
color: var(--text-primary);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.footer-separator {
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
.footer-tagline {
|
.footer-tagline {
|
||||||
color: var(--text-secondary);
|
color: var(--text-secondary);
|
||||||
font-size: 0.875rem;
|
font-size: 0.875rem;
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ import { ReactNode, useState, useRef, useEffect } from 'react';
|
|||||||
import { Link, NavLink, useLocation, useNavigate } from 'react-router-dom';
|
import { Link, NavLink, useLocation, useNavigate } from 'react-router-dom';
|
||||||
import { useAuth } from '../contexts/AuthContext';
|
import { useAuth } from '../contexts/AuthContext';
|
||||||
import { GlobalSearch } from './GlobalSearch';
|
import { GlobalSearch } from './GlobalSearch';
|
||||||
|
import { listTeams } from '../api';
|
||||||
|
import { TeamDetail } from '../types';
|
||||||
import './Layout.css';
|
import './Layout.css';
|
||||||
|
|
||||||
interface LayoutProps {
|
interface LayoutProps {
|
||||||
@@ -13,8 +15,22 @@ function Layout({ children }: LayoutProps) {
|
|||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
const { user, loading, logout } = useAuth();
|
const { user, loading, logout } = useAuth();
|
||||||
const [showUserMenu, setShowUserMenu] = useState(false);
|
const [showUserMenu, setShowUserMenu] = useState(false);
|
||||||
|
const [userTeams, setUserTeams] = useState<TeamDetail[]>([]);
|
||||||
const menuRef = useRef<HTMLDivElement>(null);
|
const menuRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
// Fetch user's teams
|
||||||
|
useEffect(() => {
|
||||||
|
if (user) {
|
||||||
|
listTeams({ limit: 10 }).then(data => {
|
||||||
|
setUserTeams(data.items);
|
||||||
|
}).catch(() => {
|
||||||
|
setUserTeams([]);
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
setUserTeams([]);
|
||||||
|
}
|
||||||
|
}, [user]);
|
||||||
|
|
||||||
// Close menu when clicking outside
|
// Close menu when clicking outside
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
function handleClickOutside(event: MouseEvent) {
|
function handleClickOutside(event: MouseEvent) {
|
||||||
@@ -77,6 +93,20 @@ function Layout({ children }: LayoutProps) {
|
|||||||
</svg>
|
</svg>
|
||||||
Dashboard
|
Dashboard
|
||||||
</Link>
|
</Link>
|
||||||
|
{user && userTeams.length > 0 && (
|
||||||
|
<Link
|
||||||
|
to={userTeams.length === 1 ? `/teams/${userTeams[0].slug}` : '/teams'}
|
||||||
|
className={location.pathname.startsWith('/teams') ? 'active' : ''}
|
||||||
|
>
|
||||||
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||||
|
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/>
|
||||||
|
<circle cx="9" cy="7" r="4"/>
|
||||||
|
<path d="M23 21v-2a4 4 0 0 0-3-3.87"/>
|
||||||
|
<path d="M16 3.13a4 4 0 0 1 0 7.75"/>
|
||||||
|
</svg>
|
||||||
|
{userTeams.length === 1 ? 'Team' : 'Teams'}
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
<a href="/docs" className="nav-link-muted">
|
<a href="/docs" className="nav-link-muted">
|
||||||
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||||
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
|
<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/>
|
||||||
@@ -153,6 +183,18 @@ function Layout({ children }: LayoutProps) {
|
|||||||
</svg>
|
</svg>
|
||||||
SSO Configuration
|
SSO Configuration
|
||||||
</NavLink>
|
</NavLink>
|
||||||
|
<NavLink
|
||||||
|
to="/admin/cache"
|
||||||
|
className="user-menu-item"
|
||||||
|
onClick={() => setShowUserMenu(false)}
|
||||||
|
>
|
||||||
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||||
|
<path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/>
|
||||||
|
<polyline points="3.27 6.96 12 12.01 20.73 6.96"/>
|
||||||
|
<line x1="12" y1="22.08" x2="12" y2="12"/>
|
||||||
|
</svg>
|
||||||
|
Cache Management
|
||||||
|
</NavLink>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
<div className="user-menu-divider"></div>
|
<div className="user-menu-divider"></div>
|
||||||
@@ -188,8 +230,18 @@ function Layout({ children }: LayoutProps) {
|
|||||||
<footer className="footer">
|
<footer className="footer">
|
||||||
<div className="container footer-content">
|
<div className="container footer-content">
|
||||||
<div className="footer-brand">
|
<div className="footer-brand">
|
||||||
|
<svg className="footer-icon" width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||||
|
<path d="M6 14 Q6 8 3 8 Q6 4 6 4 Q6 4 9 8 Q6 8 6 14" fill="currentColor" opacity="0.6"/>
|
||||||
|
<rect x="5.25" y="13" width="1.5" height="4" fill="currentColor" opacity="0.6"/>
|
||||||
|
<path d="M12 12 Q12 5 8 5 Q12 1 12 1 Q12 1 16 5 Q12 5 12 12" fill="currentColor"/>
|
||||||
|
<rect x="11.25" y="11" width="1.5" height="5" fill="currentColor"/>
|
||||||
|
<path d="M18 14 Q18 8 15 8 Q18 4 18 4 Q18 4 21 8 Q18 8 18 14" fill="currentColor" opacity="0.6"/>
|
||||||
|
<rect x="17.25" y="13" width="1.5" height="4" fill="currentColor" opacity="0.6"/>
|
||||||
|
<ellipse cx="12" cy="19" rx="9" ry="1.5" fill="currentColor" opacity="0.3"/>
|
||||||
|
</svg>
|
||||||
<span className="footer-logo">Orchard</span>
|
<span className="footer-logo">Orchard</span>
|
||||||
<span className="footer-tagline">Content-Addressable Storage</span>
|
<span className="footer-separator">·</span>
|
||||||
|
<span className="footer-tagline">The cache that never forgets</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="footer-links">
|
<div className="footer-links">
|
||||||
<a href="/docs">Documentation</a>
|
<a href="/docs">Documentation</a>
|
||||||
|
|||||||
163
frontend/src/components/TeamSelector.css
Normal file
163
frontend/src/components/TeamSelector.css
Normal file
@@ -0,0 +1,163 @@
|
|||||||
|
.team-selector {
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-selector-trigger {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
padding: 0.375rem 0.75rem;
|
||||||
|
background: var(--bg-secondary);
|
||||||
|
border: 1px solid var(--border-primary);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
color: var(--text-primary);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.15s ease;
|
||||||
|
min-width: 160px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-selector-trigger:hover:not(:disabled) {
|
||||||
|
background: var(--bg-tertiary);
|
||||||
|
border-color: var(--border-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-selector-trigger:disabled {
|
||||||
|
opacity: 0.6;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-selector-name {
|
||||||
|
flex: 1;
|
||||||
|
text-align: left;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-selector-chevron {
|
||||||
|
transition: transform 0.15s ease;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-selector-chevron.open {
|
||||||
|
transform: rotate(180deg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-selector-dropdown {
|
||||||
|
position: absolute;
|
||||||
|
top: 100%;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
min-width: 240px;
|
||||||
|
margin-top: 0.25rem;
|
||||||
|
background: var(--bg-secondary);
|
||||||
|
border: 1px solid var(--border-primary);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
box-shadow: var(--shadow-lg);
|
||||||
|
z-index: 100;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-selector-empty {
|
||||||
|
padding: 1rem;
|
||||||
|
text-align: center;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-selector-empty p {
|
||||||
|
margin: 0 0 0.75rem;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-selector-create-link {
|
||||||
|
color: var(--accent-primary);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-selector-create-link:hover {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-selector-list {
|
||||||
|
list-style: none;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0.25rem 0;
|
||||||
|
max-height: 280px;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-selector-item {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
width: 100%;
|
||||||
|
padding: 0.5rem 0.75rem;
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
color: var(--text-primary);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
cursor: pointer;
|
||||||
|
text-align: left;
|
||||||
|
transition: background 0.1s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-selector-item:hover {
|
||||||
|
background: var(--bg-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-selector-item.selected {
|
||||||
|
background: rgba(16, 185, 129, 0.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-selector-item-info {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-selector-item-name {
|
||||||
|
display: block;
|
||||||
|
font-weight: 500;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-selector-item-meta {
|
||||||
|
display: block;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-selector-item-role {
|
||||||
|
font-size: 0.75rem;
|
||||||
|
text-transform: capitalize;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-selector-footer {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
padding: 0.5rem 0.75rem;
|
||||||
|
border-top: 1px solid var(--border-primary);
|
||||||
|
background: var(--bg-tertiary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-selector-link {
|
||||||
|
font-size: 0.8125rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-selector-link:hover {
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-selector-link-primary {
|
||||||
|
color: var(--accent-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-selector-link-primary:hover {
|
||||||
|
color: var(--accent-primary-hover);
|
||||||
|
}
|
||||||
141
frontend/src/components/TeamSelector.tsx
Normal file
141
frontend/src/components/TeamSelector.tsx
Normal file
@@ -0,0 +1,141 @@
|
|||||||
|
import { useState, useRef, useEffect } from 'react';
|
||||||
|
import { Link } from 'react-router-dom';
|
||||||
|
import { useTeam } from '../contexts/TeamContext';
|
||||||
|
import { useAuth } from '../contexts/AuthContext';
|
||||||
|
import { TeamDetail } from '../types';
|
||||||
|
import './TeamSelector.css';
|
||||||
|
|
||||||
|
export function TeamSelector() {
|
||||||
|
const { user } = useAuth();
|
||||||
|
const { teams, currentTeam, loading, setCurrentTeam } = useTeam();
|
||||||
|
const [isOpen, setIsOpen] = useState(false);
|
||||||
|
const dropdownRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
// Close dropdown when clicking outside
|
||||||
|
useEffect(() => {
|
||||||
|
function handleClickOutside(event: MouseEvent) {
|
||||||
|
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
|
||||||
|
setIsOpen(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
document.addEventListener('mousedown', handleClickOutside);
|
||||||
|
return () => document.removeEventListener('mousedown', handleClickOutside);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Don't show if not authenticated
|
||||||
|
if (!user) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleTeamSelect = (team: TeamDetail) => {
|
||||||
|
setCurrentTeam(team);
|
||||||
|
setIsOpen(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
const roleColors: Record<string, string> = {
|
||||||
|
owner: 'var(--color-success)',
|
||||||
|
admin: 'var(--color-primary)',
|
||||||
|
member: 'var(--color-text-muted)',
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="team-selector" ref={dropdownRef}>
|
||||||
|
<button
|
||||||
|
className="team-selector-trigger"
|
||||||
|
onClick={() => setIsOpen(!isOpen)}
|
||||||
|
disabled={loading}
|
||||||
|
aria-expanded={isOpen}
|
||||||
|
aria-haspopup="listbox"
|
||||||
|
>
|
||||||
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||||
|
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/>
|
||||||
|
<circle cx="9" cy="7" r="4"/>
|
||||||
|
<path d="M23 21v-2a4 4 0 0 0-3-3.87"/>
|
||||||
|
<path d="M16 3.13a4 4 0 0 1 0 7.75"/>
|
||||||
|
</svg>
|
||||||
|
<span className="team-selector-name">
|
||||||
|
{loading ? 'Loading...' : currentTeam?.name || 'Select Team'}
|
||||||
|
</span>
|
||||||
|
<svg
|
||||||
|
className={`team-selector-chevron ${isOpen ? 'open' : ''}`}
|
||||||
|
width="12"
|
||||||
|
height="12"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="2"
|
||||||
|
>
|
||||||
|
<polyline points="6 9 12 15 18 9"/>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{isOpen && (
|
||||||
|
<div className="team-selector-dropdown" role="listbox">
|
||||||
|
{teams.length === 0 ? (
|
||||||
|
<div className="team-selector-empty">
|
||||||
|
<p>You're not a member of any teams yet.</p>
|
||||||
|
<Link
|
||||||
|
to="/teams/new"
|
||||||
|
className="team-selector-create-link"
|
||||||
|
onClick={() => setIsOpen(false)}
|
||||||
|
>
|
||||||
|
Create your first team
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<ul className="team-selector-list">
|
||||||
|
{teams.map(team => (
|
||||||
|
<li key={team.id}>
|
||||||
|
<button
|
||||||
|
className={`team-selector-item ${currentTeam?.id === team.id ? 'selected' : ''}`}
|
||||||
|
onClick={() => handleTeamSelect(team)}
|
||||||
|
role="option"
|
||||||
|
aria-selected={currentTeam?.id === team.id}
|
||||||
|
>
|
||||||
|
<div className="team-selector-item-info">
|
||||||
|
<span className="team-selector-item-name">{team.name}</span>
|
||||||
|
<span className="team-selector-item-meta">
|
||||||
|
{team.project_count} project{team.project_count !== 1 ? 's' : ''}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{team.user_role && (
|
||||||
|
<span
|
||||||
|
className="team-selector-item-role"
|
||||||
|
style={{ color: roleColors[team.user_role] || roleColors.member }}
|
||||||
|
>
|
||||||
|
{team.user_role}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{currentTeam?.id === team.id && (
|
||||||
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||||
|
<polyline points="20 6 9 17 4 12"/>
|
||||||
|
</svg>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
<div className="team-selector-footer">
|
||||||
|
<Link
|
||||||
|
to="/teams"
|
||||||
|
className="team-selector-link"
|
||||||
|
onClick={() => setIsOpen(false)}
|
||||||
|
>
|
||||||
|
View all teams
|
||||||
|
</Link>
|
||||||
|
<Link
|
||||||
|
to="/teams/new"
|
||||||
|
className="team-selector-link team-selector-link-primary"
|
||||||
|
onClick={() => setIsOpen(false)}
|
||||||
|
>
|
||||||
|
+ New Team
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
105
frontend/src/components/UserAutocomplete.css
Normal file
105
frontend/src/components/UserAutocomplete.css
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
.user-autocomplete {
|
||||||
|
position: relative;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-autocomplete__input-wrapper {
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-autocomplete__input {
|
||||||
|
width: 100%;
|
||||||
|
padding: 0.625rem 2.5rem 0.625rem 0.75rem;
|
||||||
|
border: 1px solid var(--border-primary);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
background: var(--bg-tertiary);
|
||||||
|
color: var(--text-primary);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-autocomplete__input:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: var(--accent-primary);
|
||||||
|
box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-autocomplete__spinner {
|
||||||
|
position: absolute;
|
||||||
|
right: 0.75rem;
|
||||||
|
top: 50%;
|
||||||
|
transform: translateY(-50%);
|
||||||
|
width: 16px;
|
||||||
|
height: 16px;
|
||||||
|
border: 2px solid var(--border-primary);
|
||||||
|
border-top-color: var(--accent-primary);
|
||||||
|
border-radius: 50%;
|
||||||
|
animation: spin 0.6s linear infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes spin {
|
||||||
|
to { transform: translateY(-50%) rotate(360deg); }
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-autocomplete__dropdown {
|
||||||
|
position: absolute;
|
||||||
|
top: 100%;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
margin-top: 4px;
|
||||||
|
padding: 0.25rem;
|
||||||
|
background: var(--bg-secondary);
|
||||||
|
border: 1px solid var(--border-primary);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
box-shadow: var(--shadow-lg);
|
||||||
|
z-index: 100;
|
||||||
|
max-height: 240px;
|
||||||
|
overflow-y: auto;
|
||||||
|
list-style: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-autocomplete__option {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.75rem;
|
||||||
|
padding: 0.5rem 0.75rem;
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background 0.1s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-autocomplete__option:hover,
|
||||||
|
.user-autocomplete__option.selected {
|
||||||
|
background: var(--bg-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-autocomplete__avatar {
|
||||||
|
width: 32px;
|
||||||
|
height: 32px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--accent-primary);
|
||||||
|
color: white;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
font-weight: 600;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-autocomplete__user-info {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-autocomplete__username {
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.user-autocomplete__admin-badge {
|
||||||
|
font-size: 0.6875rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.025em;
|
||||||
|
}
|
||||||
171
frontend/src/components/UserAutocomplete.tsx
Normal file
171
frontend/src/components/UserAutocomplete.tsx
Normal file
@@ -0,0 +1,171 @@
|
|||||||
|
import { useState, useEffect, useRef, useCallback } from 'react';
|
||||||
|
import { searchUsers, UserSearchResult } from '../api';
|
||||||
|
import './UserAutocomplete.css';
|
||||||
|
|
||||||
|
interface UserAutocompleteProps {
|
||||||
|
value: string;
|
||||||
|
onChange: (username: string) => void;
|
||||||
|
placeholder?: string;
|
||||||
|
disabled?: boolean;
|
||||||
|
autoFocus?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function UserAutocomplete({
|
||||||
|
value,
|
||||||
|
onChange,
|
||||||
|
placeholder = 'Search users...',
|
||||||
|
disabled = false,
|
||||||
|
autoFocus = false,
|
||||||
|
}: UserAutocompleteProps) {
|
||||||
|
const [query, setQuery] = useState(value);
|
||||||
|
const [results, setResults] = useState<UserSearchResult[]>([]);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [isOpen, setIsOpen] = useState(false);
|
||||||
|
const [selectedIndex, setSelectedIndex] = useState(-1);
|
||||||
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const debounceRef = useRef<ReturnType<typeof setTimeout>>();
|
||||||
|
|
||||||
|
// Search for users with debounce
|
||||||
|
const doSearch = useCallback(async (searchQuery: string) => {
|
||||||
|
if (searchQuery.length < 1) {
|
||||||
|
setResults([]);
|
||||||
|
setIsOpen(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoading(true);
|
||||||
|
try {
|
||||||
|
const users = await searchUsers(searchQuery);
|
||||||
|
setResults(users);
|
||||||
|
setIsOpen(users.length > 0);
|
||||||
|
setSelectedIndex(-1);
|
||||||
|
} catch {
|
||||||
|
setResults([]);
|
||||||
|
setIsOpen(false);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Handle input change with debounce
|
||||||
|
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||||
|
const newValue = e.target.value;
|
||||||
|
setQuery(newValue);
|
||||||
|
onChange(newValue); // Update parent immediately for form validation
|
||||||
|
|
||||||
|
// Debounce the search
|
||||||
|
if (debounceRef.current) {
|
||||||
|
clearTimeout(debounceRef.current);
|
||||||
|
}
|
||||||
|
debounceRef.current = setTimeout(() => {
|
||||||
|
doSearch(newValue);
|
||||||
|
}, 200);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handle selecting a user
|
||||||
|
const handleSelect = (user: UserSearchResult) => {
|
||||||
|
setQuery(user.username);
|
||||||
|
onChange(user.username);
|
||||||
|
setIsOpen(false);
|
||||||
|
setResults([]);
|
||||||
|
inputRef.current?.focus();
|
||||||
|
};
|
||||||
|
|
||||||
|
// Handle keyboard navigation
|
||||||
|
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||||
|
if (!isOpen) return;
|
||||||
|
|
||||||
|
switch (e.key) {
|
||||||
|
case 'ArrowDown':
|
||||||
|
e.preventDefault();
|
||||||
|
setSelectedIndex(prev => (prev < results.length - 1 ? prev + 1 : prev));
|
||||||
|
break;
|
||||||
|
case 'ArrowUp':
|
||||||
|
e.preventDefault();
|
||||||
|
setSelectedIndex(prev => (prev > 0 ? prev - 1 : -1));
|
||||||
|
break;
|
||||||
|
case 'Enter':
|
||||||
|
e.preventDefault();
|
||||||
|
if (selectedIndex >= 0 && results[selectedIndex]) {
|
||||||
|
handleSelect(results[selectedIndex]);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case 'Escape':
|
||||||
|
setIsOpen(false);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Close dropdown when clicking outside
|
||||||
|
useEffect(() => {
|
||||||
|
const handleClickOutside = (e: MouseEvent) => {
|
||||||
|
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
|
||||||
|
setIsOpen(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
document.addEventListener('mousedown', handleClickOutside);
|
||||||
|
return () => document.removeEventListener('mousedown', handleClickOutside);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// Sync external value changes
|
||||||
|
useEffect(() => {
|
||||||
|
setQuery(value);
|
||||||
|
}, [value]);
|
||||||
|
|
||||||
|
// Cleanup debounce on unmount
|
||||||
|
useEffect(() => {
|
||||||
|
return () => {
|
||||||
|
if (debounceRef.current) {
|
||||||
|
clearTimeout(debounceRef.current);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="user-autocomplete" ref={containerRef}>
|
||||||
|
<div className="user-autocomplete__input-wrapper">
|
||||||
|
<input
|
||||||
|
ref={inputRef}
|
||||||
|
type="text"
|
||||||
|
value={query}
|
||||||
|
onChange={handleInputChange}
|
||||||
|
onKeyDown={handleKeyDown}
|
||||||
|
onFocus={() => query.length >= 1 && results.length > 0 && setIsOpen(true)}
|
||||||
|
placeholder={placeholder}
|
||||||
|
disabled={disabled}
|
||||||
|
autoFocus={autoFocus}
|
||||||
|
autoComplete="off"
|
||||||
|
className="user-autocomplete__input"
|
||||||
|
/>
|
||||||
|
{loading && (
|
||||||
|
<div className="user-autocomplete__spinner" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{isOpen && results.length > 0 && (
|
||||||
|
<ul className="user-autocomplete__dropdown">
|
||||||
|
{results.map((user, index) => (
|
||||||
|
<li
|
||||||
|
key={user.id}
|
||||||
|
className={`user-autocomplete__option ${index === selectedIndex ? 'selected' : ''}`}
|
||||||
|
onClick={() => handleSelect(user)}
|
||||||
|
onMouseEnter={() => setSelectedIndex(index)}
|
||||||
|
>
|
||||||
|
<div className="user-autocomplete__avatar">
|
||||||
|
{user.username.charAt(0).toUpperCase()}
|
||||||
|
</div>
|
||||||
|
<div className="user-autocomplete__user-info">
|
||||||
|
<span className="user-autocomplete__username">{user.username}</span>
|
||||||
|
{user.is_admin && (
|
||||||
|
<span className="user-autocomplete__admin-badge">Admin</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
110
frontend/src/contexts/TeamContext.tsx
Normal file
110
frontend/src/contexts/TeamContext.tsx
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
import { createContext, useContext, useState, useEffect, useCallback, ReactNode } from 'react';
|
||||||
|
import { TeamDetail } from '../types';
|
||||||
|
import { listTeams } from '../api';
|
||||||
|
import { useAuth } from './AuthContext';
|
||||||
|
|
||||||
|
const SELECTED_TEAM_KEY = 'orchard_selected_team';
|
||||||
|
|
||||||
|
interface TeamContextType {
|
||||||
|
teams: TeamDetail[];
|
||||||
|
currentTeam: TeamDetail | null;
|
||||||
|
loading: boolean;
|
||||||
|
error: string | null;
|
||||||
|
setCurrentTeam: (team: TeamDetail | null) => void;
|
||||||
|
refreshTeams: () => Promise<void>;
|
||||||
|
clearError: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
const TeamContext = createContext<TeamContextType | undefined>(undefined);
|
||||||
|
|
||||||
|
interface TeamProviderProps {
|
||||||
|
children: ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function TeamProvider({ children }: TeamProviderProps) {
|
||||||
|
const { user } = useAuth();
|
||||||
|
const [teams, setTeams] = useState<TeamDetail[]>([]);
|
||||||
|
const [currentTeam, setCurrentTeamState] = useState<TeamDetail | null>(null);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const loadTeams = useCallback(async () => {
|
||||||
|
if (!user) {
|
||||||
|
setTeams([]);
|
||||||
|
setCurrentTeamState(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const response = await listTeams({ limit: 100 });
|
||||||
|
setTeams(response.items);
|
||||||
|
|
||||||
|
// Try to restore previously selected team
|
||||||
|
const savedSlug = localStorage.getItem(SELECTED_TEAM_KEY);
|
||||||
|
if (savedSlug) {
|
||||||
|
const savedTeam = response.items.find(t => t.slug === savedSlug);
|
||||||
|
if (savedTeam) {
|
||||||
|
setCurrentTeamState(savedTeam);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Auto-select first team if none selected
|
||||||
|
if (response.items.length > 0 && !currentTeam) {
|
||||||
|
setCurrentTeamState(response.items[0]);
|
||||||
|
localStorage.setItem(SELECTED_TEAM_KEY, response.items[0].slug);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
const message = err instanceof Error ? err.message : 'Failed to load teams';
|
||||||
|
setError(message);
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, [user, currentTeam]);
|
||||||
|
|
||||||
|
// Load teams when user changes
|
||||||
|
useEffect(() => {
|
||||||
|
loadTeams();
|
||||||
|
}, [user]); // eslint-disable-line react-hooks/exhaustive-deps
|
||||||
|
|
||||||
|
const setCurrentTeam = useCallback((team: TeamDetail | null) => {
|
||||||
|
setCurrentTeamState(team);
|
||||||
|
if (team) {
|
||||||
|
localStorage.setItem(SELECTED_TEAM_KEY, team.slug);
|
||||||
|
} else {
|
||||||
|
localStorage.removeItem(SELECTED_TEAM_KEY);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const refreshTeams = useCallback(async () => {
|
||||||
|
await loadTeams();
|
||||||
|
}, [loadTeams]);
|
||||||
|
|
||||||
|
const clearError = useCallback(() => {
|
||||||
|
setError(null);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<TeamContext.Provider value={{
|
||||||
|
teams,
|
||||||
|
currentTeam,
|
||||||
|
loading,
|
||||||
|
error,
|
||||||
|
setCurrentTeam,
|
||||||
|
refreshTeams,
|
||||||
|
clearError,
|
||||||
|
}}>
|
||||||
|
{children}
|
||||||
|
</TeamContext.Provider>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function useTeam() {
|
||||||
|
const context = useContext(TeamContext);
|
||||||
|
if (context === undefined) {
|
||||||
|
throw new Error('useTeam must be used within a TeamProvider');
|
||||||
|
}
|
||||||
|
return context;
|
||||||
|
}
|
||||||
414
frontend/src/pages/AdminCachePage.css
Normal file
414
frontend/src/pages/AdminCachePage.css
Normal file
@@ -0,0 +1,414 @@
|
|||||||
|
.admin-cache-page {
|
||||||
|
padding: 2rem;
|
||||||
|
max-width: 1400px;
|
||||||
|
margin: 0 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-cache-page h1 {
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.admin-cache-page h2 {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
color: var(--text-primary);
|
||||||
|
font-size: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Success/Error Messages */
|
||||||
|
.success-message {
|
||||||
|
padding: 0.75rem 1rem;
|
||||||
|
background-color: #d4edda;
|
||||||
|
border: 1px solid #c3e6cb;
|
||||||
|
border-radius: 4px;
|
||||||
|
color: #155724;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-message {
|
||||||
|
padding: 0.75rem 1rem;
|
||||||
|
background-color: #f8d7da;
|
||||||
|
border: 1px solid #f5c6cb;
|
||||||
|
border-radius: 4px;
|
||||||
|
color: #721c24;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Settings Section */
|
||||||
|
.settings-section {
|
||||||
|
background: var(--bg-secondary);
|
||||||
|
border: 1px solid var(--border-color);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 1.5rem;
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-grid {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.setting-item {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
padding: 1rem;
|
||||||
|
background: var(--bg-primary);
|
||||||
|
border: 1px solid var(--border-color);
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toggle-label {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.setting-name {
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--text-primary);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.setting-description {
|
||||||
|
font-size: 0.85rem;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.toggle-button {
|
||||||
|
padding: 0.5rem 1rem;
|
||||||
|
border: none;
|
||||||
|
border-radius: 4px;
|
||||||
|
cursor: pointer;
|
||||||
|
font-weight: 500;
|
||||||
|
min-width: 100px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toggle-button.on {
|
||||||
|
background-color: #28a745;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toggle-button.off {
|
||||||
|
background-color: #dc3545;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.toggle-button:disabled {
|
||||||
|
opacity: 0.6;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Sources Section */
|
||||||
|
.sources-section {
|
||||||
|
background: var(--bg-secondary);
|
||||||
|
border: 1px solid var(--border-color);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.section-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.section-header h2 {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Sources Table */
|
||||||
|
.sources-table {
|
||||||
|
width: 100%;
|
||||||
|
border-collapse: collapse;
|
||||||
|
background: var(--bg-primary);
|
||||||
|
border-radius: 4px;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sources-table th,
|
||||||
|
.sources-table td {
|
||||||
|
padding: 0.75rem 1rem;
|
||||||
|
text-align: left;
|
||||||
|
border-bottom: 1px solid var(--border-color);
|
||||||
|
}
|
||||||
|
|
||||||
|
.sources-table th {
|
||||||
|
background: var(--bg-tertiary);
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
font-size: 0.85rem;
|
||||||
|
text-transform: uppercase;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sources-table tr:last-child td {
|
||||||
|
border-bottom: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sources-table tr.disabled-row {
|
||||||
|
opacity: 0.6;
|
||||||
|
}
|
||||||
|
|
||||||
|
.source-name {
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--text-primary);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.url-cell {
|
||||||
|
font-family: monospace;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
max-width: 300px;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Badges */
|
||||||
|
.env-badge,
|
||||||
|
.status-badge {
|
||||||
|
display: inline-block;
|
||||||
|
padding: 0.2rem 0.5rem;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 500;
|
||||||
|
margin-left: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.env-badge {
|
||||||
|
background-color: #fff3e0;
|
||||||
|
color: #e65100;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-badge.enabled {
|
||||||
|
background-color: #e8f5e9;
|
||||||
|
color: #2e7d32;
|
||||||
|
}
|
||||||
|
|
||||||
|
.status-badge.disabled {
|
||||||
|
background-color: #ffebee;
|
||||||
|
color: #c62828;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Actions */
|
||||||
|
.actions-cell {
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.actions-cell .btn {
|
||||||
|
margin-right: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.actions-cell .btn:last-child {
|
||||||
|
margin-right: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.test-result {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.25rem;
|
||||||
|
padding: 0.2rem 0.5rem;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: 500;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.test-result.success {
|
||||||
|
background-color: #e8f5e9;
|
||||||
|
color: #2e7d32;
|
||||||
|
}
|
||||||
|
|
||||||
|
.test-result.failure {
|
||||||
|
background-color: #ffebee;
|
||||||
|
color: #c62828;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.test-result.failure:hover {
|
||||||
|
background-color: #ffcdd2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.test-result.testing {
|
||||||
|
background-color: #e3f2fd;
|
||||||
|
color: #1976d2;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Error Modal */
|
||||||
|
.error-modal-content {
|
||||||
|
background: var(--bg-primary);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 2rem;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 500px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-modal-content h3 {
|
||||||
|
margin-top: 0;
|
||||||
|
color: #c62828;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-modal-content .error-details {
|
||||||
|
background: var(--bg-tertiary);
|
||||||
|
padding: 1rem;
|
||||||
|
border-radius: 4px;
|
||||||
|
font-family: monospace;
|
||||||
|
font-size: 0.9rem;
|
||||||
|
word-break: break-word;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-modal-content .modal-actions {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
margin-top: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Buttons */
|
||||||
|
.btn {
|
||||||
|
padding: 0.5rem 1rem;
|
||||||
|
border: 1px solid var(--border-color);
|
||||||
|
border-radius: 4px;
|
||||||
|
background: var(--bg-primary);
|
||||||
|
color: var(--text-primary);
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn:hover {
|
||||||
|
background: var(--bg-tertiary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn:disabled {
|
||||||
|
opacity: 0.6;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary {
|
||||||
|
background-color: var(--color-primary);
|
||||||
|
border-color: var(--color-primary);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary:hover {
|
||||||
|
background-color: var(--color-primary-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-danger {
|
||||||
|
background-color: #dc3545;
|
||||||
|
border-color: #dc3545;
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-danger:hover {
|
||||||
|
background-color: #c82333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-sm {
|
||||||
|
padding: 0.25rem 0.5rem;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-message {
|
||||||
|
color: var(--text-secondary);
|
||||||
|
font-style: italic;
|
||||||
|
padding: 2rem;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Modal */
|
||||||
|
.modal-overlay {
|
||||||
|
position: fixed;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0;
|
||||||
|
background: rgba(0, 0, 0, 0.5);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
z-index: 1000;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-content {
|
||||||
|
background: var(--bg-primary);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 2rem;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 600px;
|
||||||
|
max-height: 90vh;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-content h2 {
|
||||||
|
margin-top: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Form */
|
||||||
|
.form-group {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group label {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group input,
|
||||||
|
.form-group select {
|
||||||
|
width: 100%;
|
||||||
|
padding: 0.5rem;
|
||||||
|
border: 1px solid var(--border-color);
|
||||||
|
border-radius: 4px;
|
||||||
|
background: var(--bg-primary);
|
||||||
|
color: var(--text-primary);
|
||||||
|
font-size: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group input:focus,
|
||||||
|
.form-group select:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: var(--color-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-row {
|
||||||
|
display: flex;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-row .form-group {
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.checkbox-group label {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.checkbox-group input[type="checkbox"] {
|
||||||
|
width: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.help-text {
|
||||||
|
display: block;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
margin-top: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-actions {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: 0.5rem;
|
||||||
|
margin-top: 1.5rem;
|
||||||
|
padding-top: 1rem;
|
||||||
|
border-top: 1px solid var(--border-color);
|
||||||
|
}
|
||||||
594
frontend/src/pages/AdminCachePage.tsx
Normal file
594
frontend/src/pages/AdminCachePage.tsx
Normal file
@@ -0,0 +1,594 @@
|
|||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import { useNavigate } from 'react-router-dom';
|
||||||
|
import { useAuth } from '../contexts/AuthContext';
|
||||||
|
import {
|
||||||
|
listUpstreamSources,
|
||||||
|
createUpstreamSource,
|
||||||
|
updateUpstreamSource,
|
||||||
|
deleteUpstreamSource,
|
||||||
|
testUpstreamSource,
|
||||||
|
getCacheSettings,
|
||||||
|
updateCacheSettings,
|
||||||
|
} from '../api';
|
||||||
|
import { UpstreamSource, CacheSettings, SourceType, AuthType } from '../types';
|
||||||
|
import './AdminCachePage.css';
|
||||||
|
|
||||||
|
const SOURCE_TYPES: SourceType[] = ['npm', 'pypi', 'maven', 'docker', 'helm', 'nuget', 'deb', 'rpm', 'generic'];
|
||||||
|
const AUTH_TYPES: AuthType[] = ['none', 'basic', 'bearer', 'api_key'];
|
||||||
|
|
||||||
|
function AdminCachePage() {
|
||||||
|
const { user, loading: authLoading } = useAuth();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
|
||||||
|
// Upstream sources state
|
||||||
|
const [sources, setSources] = useState<UpstreamSource[]>([]);
|
||||||
|
const [loadingSources, setLoadingSources] = useState(true);
|
||||||
|
const [sourcesError, setSourcesError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Cache settings state
|
||||||
|
const [settings, setSettings] = useState<CacheSettings | null>(null);
|
||||||
|
const [loadingSettings, setLoadingSettings] = useState(true);
|
||||||
|
const [settingsError, setSettingsError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Create/Edit form state
|
||||||
|
const [showForm, setShowForm] = useState(false);
|
||||||
|
const [editingSource, setEditingSource] = useState<UpstreamSource | null>(null);
|
||||||
|
const [formData, setFormData] = useState({
|
||||||
|
name: '',
|
||||||
|
source_type: 'generic' as SourceType,
|
||||||
|
url: '',
|
||||||
|
enabled: true,
|
||||||
|
auth_type: 'none' as AuthType,
|
||||||
|
username: '',
|
||||||
|
password: '',
|
||||||
|
priority: 100,
|
||||||
|
});
|
||||||
|
const [formError, setFormError] = useState<string | null>(null);
|
||||||
|
const [isSaving, setIsSaving] = useState(false);
|
||||||
|
|
||||||
|
// Test result state
|
||||||
|
const [testingId, setTestingId] = useState<string | null>(null);
|
||||||
|
const [testResults, setTestResults] = useState<Record<string, { success: boolean; message: string }>>({});
|
||||||
|
|
||||||
|
// Delete confirmation state
|
||||||
|
const [deletingId, setDeletingId] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Settings update state
|
||||||
|
const [updatingSettings, setUpdatingSettings] = useState(false);
|
||||||
|
|
||||||
|
// Success message
|
||||||
|
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
||||||
|
|
||||||
|
// Error modal state
|
||||||
|
const [showErrorModal, setShowErrorModal] = useState(false);
|
||||||
|
const [selectedError, setSelectedError] = useState<{ sourceName: string; error: string } | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!authLoading && !user) {
|
||||||
|
navigate('/login', { state: { from: '/admin/cache' } });
|
||||||
|
}
|
||||||
|
}, [user, authLoading, navigate]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (user && user.is_admin) {
|
||||||
|
loadSources();
|
||||||
|
loadSettings();
|
||||||
|
}
|
||||||
|
}, [user]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (successMessage) {
|
||||||
|
const timer = setTimeout(() => setSuccessMessage(null), 3000);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}
|
||||||
|
}, [successMessage]);
|
||||||
|
|
||||||
|
async function loadSources() {
|
||||||
|
setLoadingSources(true);
|
||||||
|
setSourcesError(null);
|
||||||
|
try {
|
||||||
|
const data = await listUpstreamSources();
|
||||||
|
setSources(data);
|
||||||
|
} catch (err) {
|
||||||
|
setSourcesError(err instanceof Error ? err.message : 'Failed to load sources');
|
||||||
|
} finally {
|
||||||
|
setLoadingSources(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadSettings() {
|
||||||
|
setLoadingSettings(true);
|
||||||
|
setSettingsError(null);
|
||||||
|
try {
|
||||||
|
const data = await getCacheSettings();
|
||||||
|
setSettings(data);
|
||||||
|
} catch (err) {
|
||||||
|
setSettingsError(err instanceof Error ? err.message : 'Failed to load settings');
|
||||||
|
} finally {
|
||||||
|
setLoadingSettings(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function openCreateForm() {
|
||||||
|
setEditingSource(null);
|
||||||
|
setFormData({
|
||||||
|
name: '',
|
||||||
|
source_type: 'generic',
|
||||||
|
url: '',
|
||||||
|
enabled: true,
|
||||||
|
auth_type: 'none',
|
||||||
|
username: '',
|
||||||
|
password: '',
|
||||||
|
priority: 100,
|
||||||
|
});
|
||||||
|
setFormError(null);
|
||||||
|
setShowForm(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
function openEditForm(source: UpstreamSource) {
|
||||||
|
setEditingSource(source);
|
||||||
|
setFormData({
|
||||||
|
name: source.name,
|
||||||
|
source_type: source.source_type,
|
||||||
|
url: source.url,
|
||||||
|
enabled: source.enabled,
|
||||||
|
auth_type: source.auth_type,
|
||||||
|
username: source.username || '',
|
||||||
|
password: '',
|
||||||
|
priority: source.priority,
|
||||||
|
});
|
||||||
|
setFormError(null);
|
||||||
|
setShowForm(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleFormSubmit(e: React.FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!formData.name.trim()) {
|
||||||
|
setFormError('Name is required');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!formData.url.trim()) {
|
||||||
|
setFormError('URL is required');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsSaving(true);
|
||||||
|
setFormError(null);
|
||||||
|
|
||||||
|
try {
|
||||||
|
let savedSourceId: string | null = null;
|
||||||
|
|
||||||
|
if (editingSource) {
|
||||||
|
// Update existing source
|
||||||
|
await updateUpstreamSource(editingSource.id, {
|
||||||
|
name: formData.name.trim(),
|
||||||
|
source_type: formData.source_type,
|
||||||
|
url: formData.url.trim(),
|
||||||
|
enabled: formData.enabled,
|
||||||
|
auth_type: formData.auth_type,
|
||||||
|
username: formData.username.trim() || undefined,
|
||||||
|
password: formData.password || undefined,
|
||||||
|
priority: formData.priority,
|
||||||
|
});
|
||||||
|
savedSourceId = editingSource.id;
|
||||||
|
setSuccessMessage('Source updated successfully');
|
||||||
|
} else {
|
||||||
|
// Create new source
|
||||||
|
const newSource = await createUpstreamSource({
|
||||||
|
name: formData.name.trim(),
|
||||||
|
source_type: formData.source_type,
|
||||||
|
url: formData.url.trim(),
|
||||||
|
enabled: formData.enabled,
|
||||||
|
auth_type: formData.auth_type,
|
||||||
|
username: formData.username.trim() || undefined,
|
||||||
|
password: formData.password || undefined,
|
||||||
|
priority: formData.priority,
|
||||||
|
});
|
||||||
|
savedSourceId = newSource.id;
|
||||||
|
setSuccessMessage('Source created successfully');
|
||||||
|
}
|
||||||
|
setShowForm(false);
|
||||||
|
await loadSources();
|
||||||
|
|
||||||
|
// Auto-test the source after save
|
||||||
|
if (savedSourceId) {
|
||||||
|
testSourceById(savedSourceId);
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
setFormError(err instanceof Error ? err.message : 'Failed to save source');
|
||||||
|
} finally {
|
||||||
|
setIsSaving(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleDelete(source: UpstreamSource) {
|
||||||
|
if (!window.confirm(`Delete upstream source "${source.name}"? This cannot be undone.`)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setDeletingId(source.id);
|
||||||
|
try {
|
||||||
|
await deleteUpstreamSource(source.id);
|
||||||
|
setSuccessMessage(`Source "${source.name}" deleted`);
|
||||||
|
await loadSources();
|
||||||
|
} catch (err) {
|
||||||
|
setSourcesError(err instanceof Error ? err.message : 'Failed to delete source');
|
||||||
|
} finally {
|
||||||
|
setDeletingId(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleTest(source: UpstreamSource) {
|
||||||
|
testSourceById(source.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function testSourceById(sourceId: string) {
|
||||||
|
setTestingId(sourceId);
|
||||||
|
setTestResults((prev) => ({ ...prev, [sourceId]: { success: true, message: 'Testing...' } }));
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await testUpstreamSource(sourceId);
|
||||||
|
setTestResults((prev) => ({
|
||||||
|
...prev,
|
||||||
|
[sourceId]: {
|
||||||
|
success: result.success,
|
||||||
|
message: result.success
|
||||||
|
? `OK (${result.elapsed_ms}ms)`
|
||||||
|
: result.error || `HTTP ${result.status_code}`,
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
} catch (err) {
|
||||||
|
setTestResults((prev) => ({
|
||||||
|
...prev,
|
||||||
|
[sourceId]: {
|
||||||
|
success: false,
|
||||||
|
message: err instanceof Error ? err.message : 'Test failed',
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
} finally {
|
||||||
|
setTestingId(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function showError(sourceName: string, error: string) {
|
||||||
|
setSelectedError({ sourceName, error });
|
||||||
|
setShowErrorModal(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSettingsToggle(field: 'auto_create_system_projects') {
|
||||||
|
if (!settings) return;
|
||||||
|
|
||||||
|
// Check if env override is active
|
||||||
|
const isOverridden = field === 'auto_create_system_projects' && settings.auto_create_system_projects_env_override !== null;
|
||||||
|
|
||||||
|
if (isOverridden) {
|
||||||
|
alert('This setting is overridden by an environment variable and cannot be changed via UI.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setUpdatingSettings(true);
|
||||||
|
try {
|
||||||
|
const update = { [field]: !settings[field] };
|
||||||
|
const newSettings = await updateCacheSettings(update);
|
||||||
|
setSettings(newSettings);
|
||||||
|
setSuccessMessage(`Setting "${field}" updated`);
|
||||||
|
} catch (err) {
|
||||||
|
setSettingsError(err instanceof Error ? err.message : 'Failed to update settings');
|
||||||
|
} finally {
|
||||||
|
setUpdatingSettings(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (authLoading) {
|
||||||
|
return <div className="admin-cache-page">Loading...</div>;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!user?.is_admin) {
|
||||||
|
return (
|
||||||
|
<div className="admin-cache-page">
|
||||||
|
<div className="error-message">Access denied. Admin privileges required.</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="admin-cache-page">
|
||||||
|
<h1>Cache Management</h1>
|
||||||
|
|
||||||
|
{successMessage && <div className="success-message">{successMessage}</div>}
|
||||||
|
|
||||||
|
{/* Cache Settings Section */}
|
||||||
|
<section className="settings-section">
|
||||||
|
<h2>Global Settings</h2>
|
||||||
|
{loadingSettings ? (
|
||||||
|
<p>Loading settings...</p>
|
||||||
|
) : settingsError ? (
|
||||||
|
<div className="error-message">{settingsError}</div>
|
||||||
|
) : settings ? (
|
||||||
|
<div className="settings-grid">
|
||||||
|
<div className="setting-item">
|
||||||
|
<label className="toggle-label">
|
||||||
|
<span className="setting-name">
|
||||||
|
Auto-create System Projects
|
||||||
|
{settings.auto_create_system_projects_env_override !== null && (
|
||||||
|
<span className="env-badge" title="Overridden by environment variable">
|
||||||
|
ENV
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
<span className="setting-description">
|
||||||
|
Automatically create system projects (_npm, _pypi, etc.) on first cache request.
|
||||||
|
</span>
|
||||||
|
</label>
|
||||||
|
<button
|
||||||
|
className={`toggle-button ${settings.auto_create_system_projects ? 'on' : 'off'}`}
|
||||||
|
onClick={() => handleSettingsToggle('auto_create_system_projects')}
|
||||||
|
disabled={updatingSettings || settings.auto_create_system_projects_env_override !== null}
|
||||||
|
>
|
||||||
|
{settings.auto_create_system_projects ? 'Enabled' : 'Disabled'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* Upstream Sources Section */}
|
||||||
|
<section className="sources-section">
|
||||||
|
<div className="section-header">
|
||||||
|
<h2>Upstream Sources</h2>
|
||||||
|
<button className="btn btn-primary" onClick={openCreateForm}>
|
||||||
|
Add Source
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{loadingSources ? (
|
||||||
|
<p>Loading sources...</p>
|
||||||
|
) : sourcesError ? (
|
||||||
|
<div className="error-message">{sourcesError}</div>
|
||||||
|
) : sources.length === 0 ? (
|
||||||
|
<p className="empty-message">No upstream sources configured.</p>
|
||||||
|
) : (
|
||||||
|
<table className="sources-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Name</th>
|
||||||
|
<th>Type</th>
|
||||||
|
<th>URL</th>
|
||||||
|
<th>Priority</th>
|
||||||
|
<th>Status</th>
|
||||||
|
<th>Source</th>
|
||||||
|
<th>Test</th>
|
||||||
|
<th>Actions</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{sources.map((source) => (
|
||||||
|
<tr key={source.id} className={source.enabled ? '' : 'disabled-row'}>
|
||||||
|
<td>
|
||||||
|
<span className="source-name">{source.name}</span>
|
||||||
|
</td>
|
||||||
|
<td>{source.source_type}</td>
|
||||||
|
<td className="url-cell">{source.url}</td>
|
||||||
|
<td>{source.priority}</td>
|
||||||
|
<td>
|
||||||
|
<span className={`status-badge ${source.enabled ? 'enabled' : 'disabled'}`}>
|
||||||
|
{source.enabled ? 'Enabled' : 'Disabled'}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
{source.source === 'env' ? (
|
||||||
|
<span className="env-badge" title="Defined via environment variable">
|
||||||
|
ENV
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
'Database'
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
<td>
|
||||||
|
{testingId === source.id ? (
|
||||||
|
<span className="test-result testing">Testing...</span>
|
||||||
|
) : testResults[source.id] ? (
|
||||||
|
testResults[source.id].success ? (
|
||||||
|
<span className="test-result success" title={testResults[source.id].message}>
|
||||||
|
OK
|
||||||
|
</span>
|
||||||
|
) : (
|
||||||
|
<span
|
||||||
|
className="test-result failure"
|
||||||
|
title="Click to see details"
|
||||||
|
onClick={() => showError(source.name, testResults[source.id].message)}
|
||||||
|
>
|
||||||
|
Error
|
||||||
|
</span>
|
||||||
|
)
|
||||||
|
) : (
|
||||||
|
<span className="test-result" style={{ opacity: 0.5 }}>—</span>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
<td className="actions-cell">
|
||||||
|
<button
|
||||||
|
className="btn btn-sm"
|
||||||
|
onClick={() => handleTest(source)}
|
||||||
|
disabled={testingId === source.id}
|
||||||
|
>
|
||||||
|
Test
|
||||||
|
</button>
|
||||||
|
{source.source !== 'env' && (
|
||||||
|
<>
|
||||||
|
<button className="btn btn-sm" onClick={() => openEditForm(source)}>
|
||||||
|
Edit
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
className="btn btn-sm btn-danger"
|
||||||
|
onClick={() => handleDelete(source)}
|
||||||
|
disabled={deletingId === source.id}
|
||||||
|
>
|
||||||
|
{deletingId === source.id ? 'Deleting...' : 'Delete'}
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
|
||||||
|
{/* Create/Edit Modal */}
|
||||||
|
{showForm && (
|
||||||
|
<div className="modal-overlay" onClick={() => setShowForm(false)}>
|
||||||
|
<div className="modal-content" onClick={(e) => e.stopPropagation()}>
|
||||||
|
<h2>{editingSource ? 'Edit Upstream Source' : 'Add Upstream Source'}</h2>
|
||||||
|
<form onSubmit={handleFormSubmit}>
|
||||||
|
{formError && <div className="error-message">{formError}</div>}
|
||||||
|
|
||||||
|
<div className="form-group">
|
||||||
|
<label htmlFor="name">Name</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
id="name"
|
||||||
|
value={formData.name}
|
||||||
|
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
|
||||||
|
placeholder="e.g., npm-private"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="form-row">
|
||||||
|
<div className="form-group">
|
||||||
|
<label htmlFor="source_type">Type</label>
|
||||||
|
<select
|
||||||
|
id="source_type"
|
||||||
|
value={formData.source_type}
|
||||||
|
onChange={(e) => setFormData({ ...formData, source_type: e.target.value as SourceType })}
|
||||||
|
>
|
||||||
|
{SOURCE_TYPES.map((type) => (
|
||||||
|
<option key={type} value={type}>
|
||||||
|
{type}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="form-group">
|
||||||
|
<label htmlFor="priority">Priority</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
id="priority"
|
||||||
|
value={formData.priority}
|
||||||
|
onChange={(e) => setFormData({ ...formData, priority: parseInt(e.target.value) || 100 })}
|
||||||
|
min="1"
|
||||||
|
/>
|
||||||
|
<span className="help-text">Lower = higher priority</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="form-group">
|
||||||
|
<label htmlFor="url">URL</label>
|
||||||
|
<input
|
||||||
|
type="url"
|
||||||
|
id="url"
|
||||||
|
value={formData.url}
|
||||||
|
onChange={(e) => setFormData({ ...formData, url: e.target.value })}
|
||||||
|
placeholder="https://registry.example.com"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="form-row">
|
||||||
|
<div className="form-group checkbox-group">
|
||||||
|
<label>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={formData.enabled}
|
||||||
|
onChange={(e) => setFormData({ ...formData, enabled: e.target.checked })}
|
||||||
|
/>
|
||||||
|
Enabled
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="form-group">
|
||||||
|
<label htmlFor="auth_type">Authentication</label>
|
||||||
|
<select
|
||||||
|
id="auth_type"
|
||||||
|
value={formData.auth_type}
|
||||||
|
onChange={(e) => setFormData({ ...formData, auth_type: e.target.value as AuthType })}
|
||||||
|
>
|
||||||
|
{AUTH_TYPES.map((type) => (
|
||||||
|
<option key={type} value={type}>
|
||||||
|
{type === 'none' ? 'None' : type === 'api_key' ? 'API Key' : type.charAt(0).toUpperCase() + type.slice(1)}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{formData.auth_type !== 'none' && (
|
||||||
|
<div className="form-row">
|
||||||
|
{(formData.auth_type === 'basic' || formData.auth_type === 'api_key') && (
|
||||||
|
<div className="form-group">
|
||||||
|
<label htmlFor="username">{formData.auth_type === 'api_key' ? 'Header Name' : 'Username'}</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
id="username"
|
||||||
|
value={formData.username}
|
||||||
|
onChange={(e) => setFormData({ ...formData, username: e.target.value })}
|
||||||
|
placeholder={formData.auth_type === 'api_key' ? 'X-API-Key' : 'username'}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="form-group">
|
||||||
|
<label htmlFor="password">
|
||||||
|
{formData.auth_type === 'bearer'
|
||||||
|
? 'Token'
|
||||||
|
: formData.auth_type === 'api_key'
|
||||||
|
? 'API Key Value'
|
||||||
|
: 'Password'}
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
id="password"
|
||||||
|
value={formData.password}
|
||||||
|
onChange={(e) => setFormData({ ...formData, password: e.target.value })}
|
||||||
|
placeholder={editingSource ? '(unchanged)' : ''}
|
||||||
|
/>
|
||||||
|
{editingSource && (
|
||||||
|
<span className="help-text">Leave empty to keep existing {formData.auth_type === 'bearer' ? 'token' : 'credentials'}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="form-actions">
|
||||||
|
<button type="button" className="btn" onClick={() => setShowForm(false)}>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button type="submit" className="btn btn-primary" disabled={isSaving}>
|
||||||
|
{isSaving ? 'Saving...' : editingSource ? 'Update' : 'Create'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Error Details Modal */}
|
||||||
|
{showErrorModal && selectedError && (
|
||||||
|
<div className="modal-overlay" onClick={() => setShowErrorModal(false)}>
|
||||||
|
<div className="error-modal-content" onClick={(e) => e.stopPropagation()}>
|
||||||
|
<h3>Connection Error: {selectedError.sourceName}</h3>
|
||||||
|
<div className="error-details">{selectedError.error}</div>
|
||||||
|
<div className="modal-actions">
|
||||||
|
<button className="btn" onClick={() => setShowErrorModal(false)}>
|
||||||
|
Close
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default AdminCachePage;
|
||||||
@@ -493,3 +493,16 @@
|
|||||||
gap: 6px;
|
gap: 6px;
|
||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Cell name styles */
|
||||||
|
.cell-name {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* System project badge */
|
||||||
|
.system-badge {
|
||||||
|
font-size: 0.7rem;
|
||||||
|
padding: 2px 6px;
|
||||||
|
}
|
||||||
|
|||||||
@@ -179,16 +179,18 @@ function Home() {
|
|||||||
</form>
|
</form>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="list-controls">
|
{user && (
|
||||||
<FilterDropdown
|
<div className="list-controls">
|
||||||
label="Visibility"
|
<FilterDropdown
|
||||||
options={VISIBILITY_OPTIONS}
|
label="Visibility"
|
||||||
value={visibility}
|
options={VISIBILITY_OPTIONS}
|
||||||
onChange={handleVisibilityChange}
|
value={visibility}
|
||||||
/>
|
onChange={handleVisibilityChange}
|
||||||
</div>
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{hasActiveFilters && (
|
{user && hasActiveFilters && (
|
||||||
<FilterChipGroup onClearAll={clearFilters}>
|
<FilterChipGroup onClearAll={clearFilters}>
|
||||||
{visibility && (
|
{visibility && (
|
||||||
<FilterChip
|
<FilterChip
|
||||||
@@ -222,6 +224,9 @@ function Home() {
|
|||||||
<span className="cell-name">
|
<span className="cell-name">
|
||||||
{!project.is_public && <LockIcon />}
|
{!project.is_public && <LockIcon />}
|
||||||
{project.name}
|
{project.name}
|
||||||
|
{project.is_system && (
|
||||||
|
<Badge variant="warning" className="system-badge">Cache</Badge>
|
||||||
|
)}
|
||||||
</span>
|
</span>
|
||||||
),
|
),
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -195,6 +195,9 @@ function ProjectPage() {
|
|||||||
<Badge variant={project.is_public ? 'public' : 'private'}>
|
<Badge variant={project.is_public ? 'public' : 'private'}>
|
||||||
{project.is_public ? 'Public' : 'Private'}
|
{project.is_public ? 'Public' : 'Private'}
|
||||||
</Badge>
|
</Badge>
|
||||||
|
{project.is_system && (
|
||||||
|
<Badge variant="warning">System Cache</Badge>
|
||||||
|
)}
|
||||||
{accessLevel && (
|
{accessLevel && (
|
||||||
<Badge variant={accessLevel === 'admin' ? 'success' : accessLevel === 'write' ? 'info' : 'default'}>
|
<Badge variant={accessLevel === 'admin' ? 'success' : accessLevel === 'write' ? 'info' : 'default'}>
|
||||||
{isOwner ? 'Owner' : accessLevel.charAt(0).toUpperCase() + accessLevel.slice(1)}
|
{isOwner ? 'Owner' : accessLevel.charAt(0).toUpperCase() + accessLevel.slice(1)}
|
||||||
@@ -211,7 +214,7 @@ function ProjectPage() {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="page-header__actions">
|
<div className="page-header__actions">
|
||||||
{canAdmin && (
|
{canAdmin && !project.team_id && (
|
||||||
<button
|
<button
|
||||||
className="btn btn-secondary"
|
className="btn btn-secondary"
|
||||||
onClick={() => navigate(`/project/${projectName}/settings`)}
|
onClick={() => navigate(`/project/${projectName}/settings`)}
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ import {
|
|||||||
ForbiddenError,
|
ForbiddenError,
|
||||||
} from '../api';
|
} from '../api';
|
||||||
import { Breadcrumb } from '../components/Breadcrumb';
|
import { Breadcrumb } from '../components/Breadcrumb';
|
||||||
import { AccessManagement } from '../components/AccessManagement';
|
|
||||||
import { useAuth } from '../contexts/AuthContext';
|
import { useAuth } from '../contexts/AuthContext';
|
||||||
import './ProjectSettingsPage.css';
|
import './ProjectSettingsPage.css';
|
||||||
|
|
||||||
@@ -236,9 +235,6 @@ function ProjectSettingsPage() {
|
|||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Access Management Section */}
|
|
||||||
<AccessManagement projectName={projectName!} />
|
|
||||||
|
|
||||||
{/* Danger Zone Section */}
|
{/* Danger Zone Section */}
|
||||||
<div className="project-settings-danger-zone">
|
<div className="project-settings-danger-zone">
|
||||||
<h2>Danger Zone</h2>
|
<h2>Danger Zone</h2>
|
||||||
|
|||||||
270
frontend/src/pages/TeamDashboardPage.css
Normal file
270
frontend/src/pages/TeamDashboardPage.css
Normal file
@@ -0,0 +1,270 @@
|
|||||||
|
.team-dashboard {
|
||||||
|
padding: 1.5rem 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: 1.5rem;
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-header-left {
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-header-title {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.75rem;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-header h1 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 1.5rem;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-slug {
|
||||||
|
font-size: 0.875rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-description {
|
||||||
|
margin: 0 0 0.5rem;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
font-size: 0.9375rem;
|
||||||
|
max-width: 600px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-header-actions {
|
||||||
|
display: flex;
|
||||||
|
gap: 0.5rem;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-section {
|
||||||
|
margin-top: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.section-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.section-header h2 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Table utility classes */
|
||||||
|
.text-muted {
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-ghost {
|
||||||
|
background: transparent;
|
||||||
|
color: var(--text-muted);
|
||||||
|
border: none;
|
||||||
|
padding: 0.375rem;
|
||||||
|
cursor: pointer;
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-ghost:hover {
|
||||||
|
background: var(--bg-tertiary);
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.section-footer {
|
||||||
|
margin-top: 1rem;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.view-all-link {
|
||||||
|
font-size: 0.875rem;
|
||||||
|
color: var(--accent-primary);
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.view-all-link:hover {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* States */
|
||||||
|
.loading-state,
|
||||||
|
.error-state {
|
||||||
|
text-align: center;
|
||||||
|
padding: 4rem 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-state h2 {
|
||||||
|
margin: 0 0 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-state p {
|
||||||
|
margin: 0 0 1.5rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-state {
|
||||||
|
text-align: center;
|
||||||
|
padding: 2rem;
|
||||||
|
background: var(--bg-secondary);
|
||||||
|
border: 1px dashed var(--border-primary);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-state p {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-hint {
|
||||||
|
margin-top: 0.5rem !important;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Buttons */
|
||||||
|
.btn {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
padding: 0.5rem 1rem;
|
||||||
|
border: none;
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
font-weight: 500;
|
||||||
|
cursor: pointer;
|
||||||
|
text-decoration: none;
|
||||||
|
transition: all 0.15s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-sm {
|
||||||
|
padding: 0.375rem 0.75rem;
|
||||||
|
font-size: 0.8125rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary {
|
||||||
|
background: var(--accent-primary);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary:hover {
|
||||||
|
background: var(--accent-primary-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary {
|
||||||
|
background: var(--bg-tertiary);
|
||||||
|
color: var(--text-primary);
|
||||||
|
border: 1px solid var(--border-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary:hover {
|
||||||
|
background: var(--bg-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Modal */
|
||||||
|
.modal-overlay {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
background: rgba(0, 0, 0, 0.7);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
z-index: 1000;
|
||||||
|
padding: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-content {
|
||||||
|
background: var(--bg-secondary);
|
||||||
|
border: 1px solid var(--border-primary);
|
||||||
|
border-radius: var(--radius-lg);
|
||||||
|
padding: 1.5rem;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 480px;
|
||||||
|
max-height: 90vh;
|
||||||
|
box-shadow: var(--shadow-lg);
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-content h2 {
|
||||||
|
margin: 0 0 1.5rem;
|
||||||
|
font-size: 1.25rem;
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Form */
|
||||||
|
.form-group {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group label {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
font-weight: 500;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group input[type="text"],
|
||||||
|
.form-group textarea {
|
||||||
|
width: 100%;
|
||||||
|
padding: 0.625rem 0.75rem;
|
||||||
|
border: 1px solid var(--border-primary);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
background: var(--bg-tertiary);
|
||||||
|
color: var(--text-primary);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group input:focus,
|
||||||
|
.form-group textarea:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: var(--accent-primary);
|
||||||
|
box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group textarea {
|
||||||
|
resize: vertical;
|
||||||
|
min-height: 80px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.checkbox-group label {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.checkbox-group input[type="checkbox"] {
|
||||||
|
width: 1rem;
|
||||||
|
height: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-hint {
|
||||||
|
display: block;
|
||||||
|
font-size: 0.8125rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
margin-top: 0.375rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-actions {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: 0.75rem;
|
||||||
|
margin-top: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn:disabled {
|
||||||
|
opacity: 0.6;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
.empty-state .btn {
|
||||||
|
margin-top: 1rem;
|
||||||
|
}
|
||||||
279
frontend/src/pages/TeamDashboardPage.tsx
Normal file
279
frontend/src/pages/TeamDashboardPage.tsx
Normal file
@@ -0,0 +1,279 @@
|
|||||||
|
import { useState, useEffect, useCallback } from 'react';
|
||||||
|
import { Link, useParams, useNavigate } from 'react-router-dom';
|
||||||
|
import { TeamDetail, Project, PaginatedResponse } from '../types';
|
||||||
|
import { getTeam, listTeamProjects, createProject } from '../api';
|
||||||
|
import { useAuth } from '../contexts/AuthContext';
|
||||||
|
import { Badge } from '../components/Badge';
|
||||||
|
import { Breadcrumb } from '../components/Breadcrumb';
|
||||||
|
import { DataTable } from '../components/DataTable';
|
||||||
|
import './TeamDashboardPage.css';
|
||||||
|
|
||||||
|
function TeamDashboardPage() {
|
||||||
|
const { slug } = useParams<{ slug: string }>();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const { user } = useAuth();
|
||||||
|
const [team, setTeam] = useState<TeamDetail | null>(null);
|
||||||
|
const [projects, setProjects] = useState<PaginatedResponse<Project> | null>(null);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [showProjectForm, setShowProjectForm] = useState(false);
|
||||||
|
const [newProject, setNewProject] = useState({ name: '', description: '', is_public: true });
|
||||||
|
const [creating, setCreating] = useState(false);
|
||||||
|
|
||||||
|
const loadTeamData = useCallback(async () => {
|
||||||
|
if (!slug) return;
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
const [teamData, projectsData] = await Promise.all([
|
||||||
|
getTeam(slug),
|
||||||
|
listTeamProjects(slug, { limit: 10 }),
|
||||||
|
]);
|
||||||
|
setTeam(teamData);
|
||||||
|
setProjects(projectsData);
|
||||||
|
setError(null);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Failed to load team');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, [slug]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadTeamData();
|
||||||
|
}, [loadTeamData]);
|
||||||
|
|
||||||
|
async function handleCreateProject(e: React.FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!team) return;
|
||||||
|
try {
|
||||||
|
setCreating(true);
|
||||||
|
const project = await createProject({ ...newProject, team_id: team.id });
|
||||||
|
setNewProject({ name: '', description: '', is_public: true });
|
||||||
|
setShowProjectForm(false);
|
||||||
|
navigate(`/project/${project.name}`);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Failed to create project');
|
||||||
|
} finally {
|
||||||
|
setCreating(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div className="team-dashboard">
|
||||||
|
<div className="loading-state">Loading team...</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error || !team) {
|
||||||
|
return (
|
||||||
|
<div className="team-dashboard">
|
||||||
|
<div className="error-state">
|
||||||
|
<h2>Error loading team</h2>
|
||||||
|
<p>{error || 'Team not found'}</p>
|
||||||
|
<Link to="/teams" className="btn btn-primary">Back to Teams</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const isAdminOrOwner = team.user_role === 'owner' || team.user_role === 'admin' || user?.is_admin;
|
||||||
|
|
||||||
|
const roleVariants: Record<string, 'success' | 'info' | 'default'> = {
|
||||||
|
owner: 'success',
|
||||||
|
admin: 'info',
|
||||||
|
member: 'default',
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="team-dashboard">
|
||||||
|
<Breadcrumb
|
||||||
|
items={[
|
||||||
|
{ label: 'Teams', href: '/teams' },
|
||||||
|
{ label: team.name },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="team-header">
|
||||||
|
<div className="team-header-left">
|
||||||
|
<div className="team-header-title">
|
||||||
|
<h1>{team.name}</h1>
|
||||||
|
{team.user_role && (
|
||||||
|
<Badge variant={roleVariants[team.user_role] || 'default'}>
|
||||||
|
{team.user_role}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
<span className="team-slug">@{team.slug}</span>
|
||||||
|
</div>
|
||||||
|
{team.description && (
|
||||||
|
<p className="team-description">{team.description}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{isAdminOrOwner && (
|
||||||
|
<div className="team-header-actions">
|
||||||
|
<Link to={`/teams/${slug}/members`} className="btn btn-secondary">
|
||||||
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||||
|
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/>
|
||||||
|
<circle cx="9" cy="7" r="4"/>
|
||||||
|
<path d="M23 21v-2a4 4 0 0 0-3-3.87"/>
|
||||||
|
<path d="M16 3.13a4 4 0 0 1 0 7.75"/>
|
||||||
|
</svg>
|
||||||
|
Members
|
||||||
|
</Link>
|
||||||
|
<Link to={`/teams/${slug}/settings`} className="btn btn-secondary">
|
||||||
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||||
|
<circle cx="12" cy="12" r="3"/>
|
||||||
|
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/>
|
||||||
|
</svg>
|
||||||
|
Settings
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{showProjectForm && (
|
||||||
|
<div className="modal-overlay" onClick={() => setShowProjectForm(false)}>
|
||||||
|
<div className="modal-content" onClick={e => e.stopPropagation()}>
|
||||||
|
<h2>Create New Project</h2>
|
||||||
|
<form onSubmit={handleCreateProject}>
|
||||||
|
<div className="form-group">
|
||||||
|
<label htmlFor="project-name">Project Name</label>
|
||||||
|
<input
|
||||||
|
id="project-name"
|
||||||
|
type="text"
|
||||||
|
value={newProject.name}
|
||||||
|
onChange={e => setNewProject({ ...newProject, name: e.target.value })}
|
||||||
|
placeholder="my-project"
|
||||||
|
required
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="form-group">
|
||||||
|
<label htmlFor="project-description">Description (optional)</label>
|
||||||
|
<textarea
|
||||||
|
id="project-description"
|
||||||
|
value={newProject.description}
|
||||||
|
onChange={e => setNewProject({ ...newProject, description: e.target.value })}
|
||||||
|
placeholder="What is this project for?"
|
||||||
|
rows={3}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="form-group checkbox-group">
|
||||||
|
<label>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={newProject.is_public}
|
||||||
|
onChange={e => setNewProject({ ...newProject, is_public: e.target.checked })}
|
||||||
|
/>
|
||||||
|
Public project
|
||||||
|
</label>
|
||||||
|
<span className="form-hint">Public projects are visible to everyone</span>
|
||||||
|
</div>
|
||||||
|
<div className="form-actions">
|
||||||
|
<button type="button" className="btn btn-secondary" onClick={() => setShowProjectForm(false)}>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button type="submit" className="btn btn-primary" disabled={creating}>
|
||||||
|
{creating ? 'Creating...' : 'Create Project'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="team-section">
|
||||||
|
<div className="section-header">
|
||||||
|
<h2>Projects</h2>
|
||||||
|
{isAdminOrOwner && (
|
||||||
|
<button className="btn btn-primary btn-sm" onClick={() => setShowProjectForm(true)}>
|
||||||
|
+ New Project
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{projects?.items.length === 0 ? (
|
||||||
|
<div className="empty-state">
|
||||||
|
<p>No projects in this team yet.</p>
|
||||||
|
{isAdminOrOwner && (
|
||||||
|
<button className="btn btn-primary" onClick={() => setShowProjectForm(true)}>
|
||||||
|
Create Project
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<DataTable
|
||||||
|
data={projects?.items || []}
|
||||||
|
keyExtractor={(project) => project.id}
|
||||||
|
onRowClick={(project) => navigate(`/project/${project.name}`)}
|
||||||
|
columns={[
|
||||||
|
{
|
||||||
|
key: 'name',
|
||||||
|
header: 'Name',
|
||||||
|
render: (project) => (
|
||||||
|
<Link
|
||||||
|
to={`/project/${project.name}`}
|
||||||
|
className="cell-name"
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
{project.name}
|
||||||
|
</Link>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'description',
|
||||||
|
header: 'Description',
|
||||||
|
className: 'cell-description',
|
||||||
|
render: (project) => project.description || <span className="text-muted">—</span>,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'visibility',
|
||||||
|
header: 'Visibility',
|
||||||
|
render: (project) => (
|
||||||
|
<Badge variant={project.is_public ? 'public' : 'private'}>
|
||||||
|
{project.is_public ? 'Public' : 'Private'}
|
||||||
|
</Badge>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'created_by',
|
||||||
|
header: 'Created By',
|
||||||
|
render: (project) => <span className="text-muted">{project.created_by}</span>,
|
||||||
|
},
|
||||||
|
...(isAdminOrOwner ? [{
|
||||||
|
key: 'actions',
|
||||||
|
header: '',
|
||||||
|
render: (project: Project) => (
|
||||||
|
<button
|
||||||
|
className="btn btn-sm btn-ghost"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
navigate(`/project/${project.name}/settings`);
|
||||||
|
}}
|
||||||
|
title="Settings"
|
||||||
|
>
|
||||||
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||||
|
<circle cx="12" cy="12" r="3"/>
|
||||||
|
<path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"/>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
),
|
||||||
|
}] : []),
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{projects && projects.pagination.total > 10 && (
|
||||||
|
<div className="section-footer">
|
||||||
|
<Link to={`/teams/${slug}/projects`} className="view-all-link">
|
||||||
|
View all {projects.pagination.total} projects
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default TeamDashboardPage;
|
||||||
247
frontend/src/pages/TeamMembersPage.css
Normal file
247
frontend/src/pages/TeamMembersPage.css
Normal file
@@ -0,0 +1,247 @@
|
|||||||
|
.team-members {
|
||||||
|
padding: 1.5rem 0;
|
||||||
|
max-width: 800px;
|
||||||
|
margin: 0 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 1.5rem;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-header h1 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 1.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Member cell in table */
|
||||||
|
.member-cell {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.member-avatar {
|
||||||
|
width: 40px;
|
||||||
|
height: 40px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--accent-primary);
|
||||||
|
color: white;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
font-weight: 600;
|
||||||
|
font-size: 1rem;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.member-details {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.member-username {
|
||||||
|
font-weight: 500;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.you-badge {
|
||||||
|
font-size: 0.75rem;
|
||||||
|
font-weight: normal;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.member-email {
|
||||||
|
font-size: 0.8125rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.text-muted {
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.role-select {
|
||||||
|
padding: 0.375rem 0.75rem;
|
||||||
|
border: 1px solid var(--border-primary);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
background: var(--bg-tertiary);
|
||||||
|
color: var(--text-primary);
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.role-select:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: var(--accent-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Messages */
|
||||||
|
.error-message {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
padding: 0.75rem 1rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
background: var(--error-bg);
|
||||||
|
border: 1px solid var(--error);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
color: var(--error);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-dismiss {
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
font-size: 1.25rem;
|
||||||
|
cursor: pointer;
|
||||||
|
color: inherit;
|
||||||
|
padding: 0;
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* States */
|
||||||
|
.loading-state,
|
||||||
|
.error-state {
|
||||||
|
text-align: center;
|
||||||
|
padding: 4rem 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-state h2 {
|
||||||
|
margin: 0 0 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-state p {
|
||||||
|
margin: 0 0 1.5rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Modal */
|
||||||
|
.modal-overlay {
|
||||||
|
position: fixed;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0;
|
||||||
|
background: rgba(0, 0, 0, 0.7);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
z-index: 1000;
|
||||||
|
padding: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-content {
|
||||||
|
background: var(--bg-secondary);
|
||||||
|
border: 1px solid var(--border-primary);
|
||||||
|
border-radius: var(--radius-lg);
|
||||||
|
padding: 1.5rem;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 400px;
|
||||||
|
box-shadow: var(--shadow-lg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-content h2 {
|
||||||
|
margin: 0 0 1.5rem;
|
||||||
|
font-size: 1.25rem;
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Form */
|
||||||
|
.form-group {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group label {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 0.375rem;
|
||||||
|
font-weight: 500;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group input,
|
||||||
|
.form-group select {
|
||||||
|
width: 100%;
|
||||||
|
padding: 0.5rem 0.75rem;
|
||||||
|
border: 1px solid var(--border-primary);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
font-size: 0.9375rem;
|
||||||
|
background: var(--bg-tertiary);
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group input:focus,
|
||||||
|
.form-group select:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: var(--accent-primary);
|
||||||
|
box-shadow: 0 0 0 2px rgba(16, 185, 129, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-actions {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: 0.75rem;
|
||||||
|
margin-top: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Buttons */
|
||||||
|
.btn {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
padding: 0.5rem 1rem;
|
||||||
|
border: none;
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
font-weight: 500;
|
||||||
|
cursor: pointer;
|
||||||
|
text-decoration: none;
|
||||||
|
transition: all 0.15s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn:disabled {
|
||||||
|
opacity: 0.6;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary {
|
||||||
|
background: var(--accent-primary);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary:hover:not(:disabled) {
|
||||||
|
background: var(--accent-primary-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary {
|
||||||
|
background: var(--bg-tertiary);
|
||||||
|
color: var(--text-primary);
|
||||||
|
border: 1px solid var(--border-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary:hover:not(:disabled) {
|
||||||
|
background: var(--bg-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-icon {
|
||||||
|
padding: 0.375rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-danger-ghost {
|
||||||
|
background: transparent;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-danger-ghost:hover:not(:disabled) {
|
||||||
|
background: var(--error-bg);
|
||||||
|
color: var(--error);
|
||||||
|
}
|
||||||
311
frontend/src/pages/TeamMembersPage.tsx
Normal file
311
frontend/src/pages/TeamMembersPage.tsx
Normal file
@@ -0,0 +1,311 @@
|
|||||||
|
import { useState, useEffect, useCallback } from 'react';
|
||||||
|
import { useParams, Link } from 'react-router-dom';
|
||||||
|
import { TeamDetail, TeamMember, TeamMemberCreate, TeamRole } from '../types';
|
||||||
|
import {
|
||||||
|
getTeam,
|
||||||
|
listTeamMembers,
|
||||||
|
addTeamMember,
|
||||||
|
updateTeamMember,
|
||||||
|
removeTeamMember,
|
||||||
|
} from '../api';
|
||||||
|
import { useAuth } from '../contexts/AuthContext';
|
||||||
|
import { Badge } from '../components/Badge';
|
||||||
|
import { Breadcrumb } from '../components/Breadcrumb';
|
||||||
|
import { DataTable } from '../components/DataTable';
|
||||||
|
import { UserAutocomplete } from '../components/UserAutocomplete';
|
||||||
|
import './TeamMembersPage.css';
|
||||||
|
|
||||||
|
function TeamMembersPage() {
|
||||||
|
const { slug } = useParams<{ slug: string }>();
|
||||||
|
const { user } = useAuth();
|
||||||
|
const [team, setTeam] = useState<TeamDetail | null>(null);
|
||||||
|
const [members, setMembers] = useState<TeamMember[]>([]);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [showAddForm, setShowAddForm] = useState(false);
|
||||||
|
const [adding, setAdding] = useState(false);
|
||||||
|
const [newMember, setNewMember] = useState<TeamMemberCreate>({ username: '', role: 'member' });
|
||||||
|
const [editingMember, setEditingMember] = useState<string | null>(null);
|
||||||
|
const [removingMember, setRemovingMember] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const loadData = useCallback(async () => {
|
||||||
|
if (!slug) return;
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
const [teamData, membersData] = await Promise.all([
|
||||||
|
getTeam(slug),
|
||||||
|
listTeamMembers(slug),
|
||||||
|
]);
|
||||||
|
setTeam(teamData);
|
||||||
|
setMembers(membersData);
|
||||||
|
setError(null);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Failed to load team');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, [slug]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadData();
|
||||||
|
}, [loadData]);
|
||||||
|
|
||||||
|
async function handleAddMember(e: React.FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!slug) return;
|
||||||
|
try {
|
||||||
|
setAdding(true);
|
||||||
|
setError(null);
|
||||||
|
await addTeamMember(slug, newMember);
|
||||||
|
setNewMember({ username: '', role: 'member' });
|
||||||
|
setShowAddForm(false);
|
||||||
|
loadData();
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Failed to add member');
|
||||||
|
} finally {
|
||||||
|
setAdding(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleRoleChange(username: string, newRole: TeamRole) {
|
||||||
|
if (!slug) return;
|
||||||
|
try {
|
||||||
|
setEditingMember(username);
|
||||||
|
setError(null);
|
||||||
|
await updateTeamMember(slug, username, { role: newRole });
|
||||||
|
loadData();
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Failed to update member');
|
||||||
|
} finally {
|
||||||
|
setEditingMember(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleRemoveMember(username: string) {
|
||||||
|
if (!slug) return;
|
||||||
|
if (!confirm(`Remove ${username} from the team?`)) return;
|
||||||
|
try {
|
||||||
|
setRemovingMember(username);
|
||||||
|
setError(null);
|
||||||
|
await removeTeamMember(slug, username);
|
||||||
|
loadData();
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Failed to remove member');
|
||||||
|
} finally {
|
||||||
|
setRemovingMember(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div className="team-members">
|
||||||
|
<div className="loading-state">Loading team members...</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error && !team) {
|
||||||
|
return (
|
||||||
|
<div className="team-members">
|
||||||
|
<div className="error-state">
|
||||||
|
<h2>Error loading team</h2>
|
||||||
|
<p>{error}</p>
|
||||||
|
<Link to="/teams" className="btn btn-primary">Back to Teams</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!team) return null;
|
||||||
|
|
||||||
|
const isOwner = team.user_role === 'owner' || user?.is_admin;
|
||||||
|
const isAdmin = team.user_role === 'admin' || isOwner;
|
||||||
|
|
||||||
|
const roleVariants: Record<string, 'success' | 'info' | 'default'> = {
|
||||||
|
owner: 'success',
|
||||||
|
admin: 'info',
|
||||||
|
member: 'default',
|
||||||
|
};
|
||||||
|
|
||||||
|
const roles: TeamRole[] = ['owner', 'admin', 'member'];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="team-members">
|
||||||
|
<Breadcrumb
|
||||||
|
items={[
|
||||||
|
{ label: 'Teams', href: '/teams' },
|
||||||
|
{ label: team.name, href: `/teams/${slug}` },
|
||||||
|
{ label: 'Members' },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<div className="page-header">
|
||||||
|
<h1>Team Members</h1>
|
||||||
|
{isAdmin && (
|
||||||
|
<button className="btn btn-primary" onClick={() => setShowAddForm(true)}>
|
||||||
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||||
|
<path d="M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/>
|
||||||
|
<circle cx="8.5" cy="7" r="4"/>
|
||||||
|
<line x1="20" y1="8" x2="20" y2="14"/>
|
||||||
|
<line x1="23" y1="11" x2="17" y2="11"/>
|
||||||
|
</svg>
|
||||||
|
Invite Member
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div className="error-message">
|
||||||
|
{error}
|
||||||
|
<button onClick={() => setError(null)} className="error-dismiss">×</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{showAddForm && (
|
||||||
|
<div className="modal-overlay" onClick={() => setShowAddForm(false)}>
|
||||||
|
<div className="modal-content" onClick={e => e.stopPropagation()}>
|
||||||
|
<h2>Invite Member</h2>
|
||||||
|
<form onSubmit={handleAddMember}>
|
||||||
|
<div className="form-group">
|
||||||
|
<label htmlFor="username">Username</label>
|
||||||
|
<UserAutocomplete
|
||||||
|
value={newMember.username}
|
||||||
|
onChange={(username) => setNewMember({ ...newMember, username })}
|
||||||
|
placeholder="Search for a user..."
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="form-group">
|
||||||
|
<label htmlFor="role">Role</label>
|
||||||
|
<select
|
||||||
|
id="role"
|
||||||
|
value={newMember.role}
|
||||||
|
onChange={e => setNewMember({ ...newMember, role: e.target.value as TeamRole })}
|
||||||
|
>
|
||||||
|
<option value="member">Member - Can view team projects</option>
|
||||||
|
<option value="admin">Admin - Can manage team settings and members</option>
|
||||||
|
{isOwner && (
|
||||||
|
<option value="owner">Owner - Full control, can delete team</option>
|
||||||
|
)}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div className="form-actions">
|
||||||
|
<button type="button" className="btn btn-secondary" onClick={() => setShowAddForm(false)}>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button type="submit" className="btn btn-primary" disabled={adding}>
|
||||||
|
{adding ? 'Adding...' : 'Add Member'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<DataTable
|
||||||
|
data={members}
|
||||||
|
keyExtractor={(member) => member.id}
|
||||||
|
emptyMessage="No members in this team yet."
|
||||||
|
columns={[
|
||||||
|
{
|
||||||
|
key: 'member',
|
||||||
|
header: 'Member',
|
||||||
|
render: (member) => {
|
||||||
|
const isCurrentUser = user?.username === member.username;
|
||||||
|
return (
|
||||||
|
<div className="member-cell">
|
||||||
|
<div className="member-avatar">
|
||||||
|
{member.username.charAt(0).toUpperCase()}
|
||||||
|
</div>
|
||||||
|
<div className="member-details">
|
||||||
|
<span className="member-username">
|
||||||
|
{member.username}
|
||||||
|
{isCurrentUser && <span className="you-badge">(you)</span>}
|
||||||
|
</span>
|
||||||
|
{member.email && (
|
||||||
|
<span className="member-email">{member.email}</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'role',
|
||||||
|
header: 'Role',
|
||||||
|
render: (member) => {
|
||||||
|
const isCurrentUser = user?.username === member.username;
|
||||||
|
const canModify = isAdmin && !isCurrentUser && (isOwner || member.role !== 'owner');
|
||||||
|
|
||||||
|
if (canModify) {
|
||||||
|
return (
|
||||||
|
<select
|
||||||
|
value={member.role}
|
||||||
|
onChange={e => handleRoleChange(member.username, e.target.value as TeamRole)}
|
||||||
|
disabled={editingMember === member.username}
|
||||||
|
className="role-select"
|
||||||
|
onClick={e => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
{roles.map(role => (
|
||||||
|
<option
|
||||||
|
key={role}
|
||||||
|
value={role}
|
||||||
|
disabled={role === 'owner' && !isOwner}
|
||||||
|
>
|
||||||
|
{role.charAt(0).toUpperCase() + role.slice(1)}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<Badge variant={roleVariants[member.role] || 'default'}>
|
||||||
|
{member.role}
|
||||||
|
</Badge>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'joined',
|
||||||
|
header: 'Joined',
|
||||||
|
render: (member) => (
|
||||||
|
<span className="text-muted">
|
||||||
|
{new Date(member.created_at).toLocaleDateString()}
|
||||||
|
</span>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
...(isAdmin ? [{
|
||||||
|
key: 'actions',
|
||||||
|
header: '',
|
||||||
|
render: (member: TeamMember) => {
|
||||||
|
const isCurrentUser = user?.username === member.username;
|
||||||
|
const canModify = isAdmin && !isCurrentUser && (isOwner || member.role !== 'owner');
|
||||||
|
|
||||||
|
if (!canModify) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
className="btn btn-icon btn-danger-ghost"
|
||||||
|
onClick={(e) => {
|
||||||
|
e.stopPropagation();
|
||||||
|
handleRemoveMember(member.username);
|
||||||
|
}}
|
||||||
|
disabled={removingMember === member.username}
|
||||||
|
title="Remove member"
|
||||||
|
>
|
||||||
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||||
|
<path d="M3 6h18"/>
|
||||||
|
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"/>
|
||||||
|
<path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
},
|
||||||
|
}] : []),
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default TeamMembersPage;
|
||||||
239
frontend/src/pages/TeamSettingsPage.css
Normal file
239
frontend/src/pages/TeamSettingsPage.css
Normal file
@@ -0,0 +1,239 @@
|
|||||||
|
.team-settings {
|
||||||
|
padding: 1.5rem 0;
|
||||||
|
max-width: 640px;
|
||||||
|
margin: 0 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-settings h1 {
|
||||||
|
margin: 0 0 1.5rem;
|
||||||
|
font-size: 1.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.settings-form {
|
||||||
|
margin-bottom: 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section {
|
||||||
|
background: var(--bg-secondary);
|
||||||
|
border: 1px solid var(--border-primary);
|
||||||
|
border-radius: var(--radius-lg);
|
||||||
|
padding: 1.5rem;
|
||||||
|
margin-bottom: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-section h2 {
|
||||||
|
margin: 0 0 1rem;
|
||||||
|
font-size: 1.125rem;
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group label {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 0.375rem;
|
||||||
|
font-weight: 500;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group input,
|
||||||
|
.form-group textarea {
|
||||||
|
width: 100%;
|
||||||
|
padding: 0.5rem 0.75rem;
|
||||||
|
border: 1px solid var(--border-primary);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
font-size: 0.9375rem;
|
||||||
|
background: var(--bg-tertiary);
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group input:focus,
|
||||||
|
.form-group textarea:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: var(--accent-primary);
|
||||||
|
box-shadow: 0 0 0 2px rgba(16, 185, 129, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.input-disabled {
|
||||||
|
background: var(--bg-elevated) !important;
|
||||||
|
color: var(--text-muted) !important;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-hint {
|
||||||
|
display: block;
|
||||||
|
margin-top: 0.25rem;
|
||||||
|
font-size: 0.8125rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Danger zone */
|
||||||
|
.danger-zone {
|
||||||
|
border-color: var(--error);
|
||||||
|
background: var(--error-bg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.danger-zone h2 {
|
||||||
|
color: var(--error);
|
||||||
|
}
|
||||||
|
|
||||||
|
.danger-warning {
|
||||||
|
margin: 0 0 1rem;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Messages */
|
||||||
|
.error-message {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
padding: 0.75rem 1rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
background: var(--error-bg);
|
||||||
|
border: 1px solid var(--error);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
color: var(--error);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-dismiss {
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
font-size: 1.25rem;
|
||||||
|
cursor: pointer;
|
||||||
|
color: inherit;
|
||||||
|
padding: 0;
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.success-message {
|
||||||
|
padding: 0.75rem 1rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
background: var(--success-bg);
|
||||||
|
border: 1px solid var(--success);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
color: var(--success);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* States */
|
||||||
|
.loading-state,
|
||||||
|
.error-state {
|
||||||
|
text-align: center;
|
||||||
|
padding: 4rem 2rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-state h2 {
|
||||||
|
margin: 0 0 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-state p {
|
||||||
|
margin: 0 0 1.5rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Modal */
|
||||||
|
.modal-overlay {
|
||||||
|
position: fixed;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0;
|
||||||
|
background: rgba(0, 0, 0, 0.7);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
z-index: 1000;
|
||||||
|
padding: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-content {
|
||||||
|
background: var(--bg-secondary);
|
||||||
|
border: 1px solid var(--border-primary);
|
||||||
|
border-radius: var(--radius-lg);
|
||||||
|
padding: 1.5rem;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 400px;
|
||||||
|
box-shadow: var(--shadow-lg);
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-content h2 {
|
||||||
|
margin: 0 0 1rem;
|
||||||
|
font-size: 1.25rem;
|
||||||
|
color: var(--error);
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-content p {
|
||||||
|
margin: 0 0 1rem;
|
||||||
|
font-size: 0.9375rem;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.delete-confirm-input {
|
||||||
|
width: 100%;
|
||||||
|
padding: 0.5rem 0.75rem;
|
||||||
|
border: 1px solid var(--border-primary);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
font-size: 0.9375rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
background: var(--bg-tertiary);
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-actions {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: 0.75rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Buttons */
|
||||||
|
.btn {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
padding: 0.5rem 1rem;
|
||||||
|
border: none;
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
font-weight: 500;
|
||||||
|
cursor: pointer;
|
||||||
|
text-decoration: none;
|
||||||
|
transition: all 0.15s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn:disabled {
|
||||||
|
opacity: 0.6;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary {
|
||||||
|
background: var(--accent-primary);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary:hover:not(:disabled) {
|
||||||
|
background: var(--accent-primary-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary {
|
||||||
|
background: var(--bg-tertiary);
|
||||||
|
color: var(--text-primary);
|
||||||
|
border: 1px solid var(--border-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary:hover:not(:disabled) {
|
||||||
|
background: var(--bg-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-danger {
|
||||||
|
background: var(--error);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-danger:hover:not(:disabled) {
|
||||||
|
background: #b91c1c;
|
||||||
|
}
|
||||||
251
frontend/src/pages/TeamSettingsPage.tsx
Normal file
251
frontend/src/pages/TeamSettingsPage.tsx
Normal file
@@ -0,0 +1,251 @@
|
|||||||
|
import { useState, useEffect, useCallback } from 'react';
|
||||||
|
import { useParams, useNavigate, Link } from 'react-router-dom';
|
||||||
|
import { TeamDetail, TeamUpdate } from '../types';
|
||||||
|
import { getTeam, updateTeam, deleteTeam } from '../api';
|
||||||
|
import { useAuth } from '../contexts/AuthContext';
|
||||||
|
import { Breadcrumb } from '../components/Breadcrumb';
|
||||||
|
import './TeamSettingsPage.css';
|
||||||
|
|
||||||
|
function TeamSettingsPage() {
|
||||||
|
const { slug } = useParams<{ slug: string }>();
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const { user } = useAuth();
|
||||||
|
const [team, setTeam] = useState<TeamDetail | null>(null);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [deleting, setDeleting] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [successMessage, setSuccessMessage] = useState<string | null>(null);
|
||||||
|
const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
|
||||||
|
const [deleteConfirmText, setDeleteConfirmText] = useState('');
|
||||||
|
|
||||||
|
const [formData, setFormData] = useState<TeamUpdate>({
|
||||||
|
name: '',
|
||||||
|
description: '',
|
||||||
|
});
|
||||||
|
|
||||||
|
const loadTeam = useCallback(async () => {
|
||||||
|
if (!slug) return;
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
const teamData = await getTeam(slug);
|
||||||
|
setTeam(teamData);
|
||||||
|
setFormData({
|
||||||
|
name: teamData.name,
|
||||||
|
description: teamData.description || '',
|
||||||
|
});
|
||||||
|
setError(null);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Failed to load team');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, [slug]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadTeam();
|
||||||
|
}, [loadTeam]);
|
||||||
|
|
||||||
|
async function handleSubmit(e: React.FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!slug || !team) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
setSaving(true);
|
||||||
|
setError(null);
|
||||||
|
const updatedTeam = await updateTeam(slug, formData);
|
||||||
|
setTeam(updatedTeam);
|
||||||
|
setSuccessMessage('Settings saved successfully');
|
||||||
|
setTimeout(() => setSuccessMessage(null), 3000);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Failed to save settings');
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleDelete() {
|
||||||
|
if (!slug || !team) return;
|
||||||
|
if (deleteConfirmText !== team.slug) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
setDeleting(true);
|
||||||
|
await deleteTeam(slug);
|
||||||
|
navigate('/teams');
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Failed to delete team');
|
||||||
|
setShowDeleteConfirm(false);
|
||||||
|
} finally {
|
||||||
|
setDeleting(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (loading) {
|
||||||
|
return (
|
||||||
|
<div className="team-settings">
|
||||||
|
<div className="loading-state">Loading team settings...</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (error && !team) {
|
||||||
|
return (
|
||||||
|
<div className="team-settings">
|
||||||
|
<div className="error-state">
|
||||||
|
<h2>Error loading team</h2>
|
||||||
|
<p>{error}</p>
|
||||||
|
<Link to="/teams" className="btn btn-primary">Back to Teams</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!team) return null;
|
||||||
|
|
||||||
|
const isOwner = team.user_role === 'owner' || user?.is_admin;
|
||||||
|
const isAdmin = team.user_role === 'admin' || isOwner;
|
||||||
|
|
||||||
|
if (!isAdmin) {
|
||||||
|
return (
|
||||||
|
<div className="team-settings">
|
||||||
|
<div className="error-state">
|
||||||
|
<h2>Access Denied</h2>
|
||||||
|
<p>You need admin privileges to access team settings.</p>
|
||||||
|
<Link to={`/teams/${slug}`} className="btn btn-primary">Back to Team</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="team-settings">
|
||||||
|
<Breadcrumb
|
||||||
|
items={[
|
||||||
|
{ label: 'Teams', href: '/teams' },
|
||||||
|
{ label: team.name, href: `/teams/${slug}` },
|
||||||
|
{ label: 'Settings' },
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<h1>Team Settings</h1>
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div className="error-message">
|
||||||
|
{error}
|
||||||
|
<button onClick={() => setError(null)} className="error-dismiss">×</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{successMessage && (
|
||||||
|
<div className="success-message">
|
||||||
|
{successMessage}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit} className="settings-form">
|
||||||
|
<div className="form-section">
|
||||||
|
<h2>General</h2>
|
||||||
|
|
||||||
|
<div className="form-group">
|
||||||
|
<label htmlFor="team-name">Team Name</label>
|
||||||
|
<input
|
||||||
|
id="team-name"
|
||||||
|
type="text"
|
||||||
|
value={formData.name}
|
||||||
|
onChange={e => setFormData({ ...formData, name: e.target.value })}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="form-group">
|
||||||
|
<label htmlFor="team-slug">Slug</label>
|
||||||
|
<input
|
||||||
|
id="team-slug"
|
||||||
|
type="text"
|
||||||
|
value={team.slug}
|
||||||
|
disabled
|
||||||
|
className="input-disabled"
|
||||||
|
/>
|
||||||
|
<span className="form-hint">Team slug cannot be changed</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="form-group">
|
||||||
|
<label htmlFor="team-description">Description</label>
|
||||||
|
<textarea
|
||||||
|
id="team-description"
|
||||||
|
value={formData.description}
|
||||||
|
onChange={e => setFormData({ ...formData, description: e.target.value })}
|
||||||
|
rows={3}
|
||||||
|
placeholder="What is this team for?"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button type="submit" className="btn btn-primary" disabled={saving}>
|
||||||
|
{saving ? 'Saving...' : 'Save Changes'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
{isOwner && (
|
||||||
|
<div className="form-section danger-zone">
|
||||||
|
<h2>Danger Zone</h2>
|
||||||
|
<p className="danger-warning">
|
||||||
|
Deleting a team is permanent and cannot be undone.
|
||||||
|
You must move or delete all projects in this team first.
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-danger"
|
||||||
|
onClick={() => setShowDeleteConfirm(true)}
|
||||||
|
>
|
||||||
|
Delete Team
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{showDeleteConfirm && (
|
||||||
|
<div className="modal-overlay" onClick={() => setShowDeleteConfirm(false)}>
|
||||||
|
<div className="modal-content" onClick={e => e.stopPropagation()}>
|
||||||
|
<h2>Delete Team</h2>
|
||||||
|
<p>
|
||||||
|
This will permanently delete the team <strong>{team.name}</strong>.
|
||||||
|
This action cannot be undone.
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
To confirm, type <strong>{team.slug}</strong> below:
|
||||||
|
</p>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={deleteConfirmText}
|
||||||
|
onChange={e => setDeleteConfirmText(e.target.value)}
|
||||||
|
placeholder={team.slug}
|
||||||
|
className="delete-confirm-input"
|
||||||
|
/>
|
||||||
|
<div className="form-actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-secondary"
|
||||||
|
onClick={() => {
|
||||||
|
setShowDeleteConfirm(false);
|
||||||
|
setDeleteConfirmText('');
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn btn-danger"
|
||||||
|
disabled={deleteConfirmText !== team.slug || deleting}
|
||||||
|
onClick={handleDelete}
|
||||||
|
>
|
||||||
|
{deleting ? 'Deleting...' : 'Delete Team'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default TeamSettingsPage;
|
||||||
376
frontend/src/pages/TeamsPage.css
Normal file
376
frontend/src/pages/TeamsPage.css
Normal file
@@ -0,0 +1,376 @@
|
|||||||
|
.teams-page {
|
||||||
|
padding: 1.5rem 0;
|
||||||
|
max-width: 1200px;
|
||||||
|
margin: 0 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Header */
|
||||||
|
.teams-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 1.5rem;
|
||||||
|
gap: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.teams-header h1 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 1.5rem;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Search */
|
||||||
|
.teams-search {
|
||||||
|
position: relative;
|
||||||
|
margin-bottom: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.teams-search__icon {
|
||||||
|
position: absolute;
|
||||||
|
left: 0.875rem;
|
||||||
|
top: 50%;
|
||||||
|
transform: translateY(-50%);
|
||||||
|
color: var(--text-muted);
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.teams-search__input {
|
||||||
|
width: 100%;
|
||||||
|
padding: 0.625rem 2.5rem 0.625rem 2.75rem;
|
||||||
|
border: 1px solid var(--border-primary);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
background: var(--bg-primary);
|
||||||
|
color: var(--text-primary);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.teams-search__input:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: var(--accent-primary);
|
||||||
|
box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.teams-search__input::placeholder {
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.teams-search__clear {
|
||||||
|
position: absolute;
|
||||||
|
right: 0.5rem;
|
||||||
|
top: 50%;
|
||||||
|
transform: translateY(-50%);
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
padding: 0.375rem;
|
||||||
|
cursor: pointer;
|
||||||
|
color: var(--text-muted);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
}
|
||||||
|
|
||||||
|
.teams-search__clear:hover {
|
||||||
|
color: var(--text-primary);
|
||||||
|
background: var(--bg-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Error */
|
||||||
|
.teams-error {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
padding: 0.75rem 1rem;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
background: var(--error-bg);
|
||||||
|
border: 1px solid var(--error);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
color: var(--error);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.teams-error__dismiss {
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
font-size: 1.25rem;
|
||||||
|
cursor: pointer;
|
||||||
|
color: inherit;
|
||||||
|
padding: 0;
|
||||||
|
line-height: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Loading */
|
||||||
|
.teams-loading {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
gap: 1rem;
|
||||||
|
padding: 4rem 2rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.teams-loading__spinner {
|
||||||
|
width: 32px;
|
||||||
|
height: 32px;
|
||||||
|
border: 3px solid var(--border-primary);
|
||||||
|
border-top-color: var(--accent-primary);
|
||||||
|
border-radius: 50%;
|
||||||
|
animation: teams-spin 0.8s linear infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes teams-spin {
|
||||||
|
to { transform: rotate(360deg); }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Empty State */
|
||||||
|
.teams-empty-state {
|
||||||
|
text-align: center;
|
||||||
|
padding: 4rem 2rem;
|
||||||
|
background: var(--bg-secondary);
|
||||||
|
border-radius: var(--radius-lg);
|
||||||
|
border: 1px solid var(--border-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.teams-empty-icon {
|
||||||
|
color: var(--text-muted);
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.teams-empty-state h2 {
|
||||||
|
margin: 0 0 0.5rem;
|
||||||
|
font-size: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.teams-empty-state p {
|
||||||
|
margin: 0 0 1.5rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Table cell styles */
|
||||||
|
|
||||||
|
.team-name-cell {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 0.125rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-name-link {
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--text-primary);
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-name-link:hover {
|
||||||
|
color: var(--accent-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-slug {
|
||||||
|
font-size: 0.8125rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.team-description-cell {
|
||||||
|
color: var(--text-secondary);
|
||||||
|
max-width: 300px;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.text-muted {
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Modal */
|
||||||
|
.modal-overlay {
|
||||||
|
position: fixed;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0;
|
||||||
|
background: rgba(0, 0, 0, 0.7);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
z-index: 1000;
|
||||||
|
padding: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-content {
|
||||||
|
background: var(--bg-secondary);
|
||||||
|
border: 1px solid var(--border-primary);
|
||||||
|
border-radius: var(--radius-lg);
|
||||||
|
width: 100%;
|
||||||
|
max-width: 480px;
|
||||||
|
box-shadow: var(--shadow-lg);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
padding: 1.25rem 1.5rem;
|
||||||
|
border-bottom: 1px solid var(--border-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-header h2 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 1.125rem;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-close {
|
||||||
|
background: none;
|
||||||
|
border: none;
|
||||||
|
padding: 0.25rem;
|
||||||
|
cursor: pointer;
|
||||||
|
color: var(--text-muted);
|
||||||
|
display: flex;
|
||||||
|
border-radius: var(--radius-sm);
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-close:hover {
|
||||||
|
color: var(--text-primary);
|
||||||
|
background: var(--bg-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
.modal-content form {
|
||||||
|
padding: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Form */
|
||||||
|
.form-group {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group label {
|
||||||
|
display: block;
|
||||||
|
margin-bottom: 0.375rem;
|
||||||
|
font-weight: 500;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group .optional {
|
||||||
|
font-weight: 400;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group input,
|
||||||
|
.form-group textarea {
|
||||||
|
width: 100%;
|
||||||
|
padding: 0.625rem 0.75rem;
|
||||||
|
border: 1px solid var(--border-primary);
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
background: var(--bg-tertiary);
|
||||||
|
color: var(--text-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group input:focus,
|
||||||
|
.form-group textarea:focus {
|
||||||
|
outline: none;
|
||||||
|
border-color: var(--accent-primary);
|
||||||
|
box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.2);
|
||||||
|
}
|
||||||
|
|
||||||
|
.input-with-prefix {
|
||||||
|
display: flex;
|
||||||
|
align-items: stretch;
|
||||||
|
}
|
||||||
|
|
||||||
|
.input-prefix {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
padding: 0 0.75rem;
|
||||||
|
background: var(--bg-elevated);
|
||||||
|
border: 1px solid var(--border-primary);
|
||||||
|
border-right: none;
|
||||||
|
border-radius: var(--radius-md) 0 0 var(--radius-md);
|
||||||
|
color: var(--text-muted);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.input-with-prefix input {
|
||||||
|
border-radius: 0 var(--radius-md) var(--radius-md) 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-hint {
|
||||||
|
display: block;
|
||||||
|
margin-top: 0.25rem;
|
||||||
|
font-size: 0.75rem;
|
||||||
|
color: var(--text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-actions {
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: 0.75rem;
|
||||||
|
margin-top: 1.5rem;
|
||||||
|
padding-top: 1rem;
|
||||||
|
border-top: 1px solid var(--border-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Buttons */
|
||||||
|
.btn {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.5rem;
|
||||||
|
padding: 0.5rem 1rem;
|
||||||
|
border: none;
|
||||||
|
border-radius: var(--radius-md);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
font-weight: 500;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.15s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn:disabled {
|
||||||
|
opacity: 0.6;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary {
|
||||||
|
background: var(--accent-primary);
|
||||||
|
color: white;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-primary:hover:not(:disabled) {
|
||||||
|
background: var(--accent-primary-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary {
|
||||||
|
background: var(--bg-tertiary);
|
||||||
|
color: var(--text-primary);
|
||||||
|
border: 1px solid var(--border-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-secondary:hover:not(:disabled) {
|
||||||
|
background: var(--bg-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Responsive */
|
||||||
|
@media (max-width: 640px) {
|
||||||
|
.teams-header {
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: stretch;
|
||||||
|
}
|
||||||
|
|
||||||
|
.teams-header .btn {
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.teams-stats {
|
||||||
|
justify-content: space-around;
|
||||||
|
}
|
||||||
|
|
||||||
|
.teams-table-container {
|
||||||
|
overflow-x: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.teams-table {
|
||||||
|
min-width: 600px;
|
||||||
|
}
|
||||||
|
}
|
||||||
310
frontend/src/pages/TeamsPage.tsx
Normal file
310
frontend/src/pages/TeamsPage.tsx
Normal file
@@ -0,0 +1,310 @@
|
|||||||
|
import { useState, useEffect, useCallback } from 'react';
|
||||||
|
import { Link, useNavigate } from 'react-router-dom';
|
||||||
|
import { TeamDetail, TeamCreate, PaginatedResponse } from '../types';
|
||||||
|
import { listTeams, createTeam } from '../api';
|
||||||
|
import { useAuth } from '../contexts/AuthContext';
|
||||||
|
import { Badge } from '../components/Badge';
|
||||||
|
import { DataTable } from '../components/DataTable';
|
||||||
|
import './TeamsPage.css';
|
||||||
|
|
||||||
|
function TeamsPage() {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const { user } = useAuth();
|
||||||
|
const [teamsData, setTeamsData] = useState<PaginatedResponse<TeamDetail> | null>(null);
|
||||||
|
const [loading, setLoading] = useState(true);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [showForm, setShowForm] = useState(false);
|
||||||
|
const [newTeam, setNewTeam] = useState<TeamCreate>({ name: '', slug: '', description: '' });
|
||||||
|
const [creating, setCreating] = useState(false);
|
||||||
|
const [slugManuallySet, setSlugManuallySet] = useState(false);
|
||||||
|
const [searchQuery, setSearchQuery] = useState('');
|
||||||
|
|
||||||
|
const loadTeams = useCallback(async () => {
|
||||||
|
try {
|
||||||
|
setLoading(true);
|
||||||
|
const data = await listTeams({ limit: 100 });
|
||||||
|
setTeamsData(data);
|
||||||
|
setError(null);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Failed to load teams');
|
||||||
|
} finally {
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
loadTeams();
|
||||||
|
}, [loadTeams]);
|
||||||
|
|
||||||
|
// Auto-generate slug from name
|
||||||
|
const handleNameChange = (name: string) => {
|
||||||
|
setNewTeam(prev => ({
|
||||||
|
...prev,
|
||||||
|
name,
|
||||||
|
slug: slugManuallySet ? prev.slug : name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, ''),
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSlugChange = (slug: string) => {
|
||||||
|
setSlugManuallySet(true);
|
||||||
|
setNewTeam(prev => ({ ...prev, slug }));
|
||||||
|
};
|
||||||
|
|
||||||
|
async function handleCreateTeam(e: React.FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
try {
|
||||||
|
setCreating(true);
|
||||||
|
const team = await createTeam(newTeam);
|
||||||
|
setNewTeam({ name: '', slug: '', description: '' });
|
||||||
|
setSlugManuallySet(false);
|
||||||
|
setShowForm(false);
|
||||||
|
navigate(`/teams/${team.slug}`);
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : 'Failed to create team');
|
||||||
|
} finally {
|
||||||
|
setCreating(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const closeModal = () => {
|
||||||
|
setShowForm(false);
|
||||||
|
setNewTeam({ name: '', slug: '', description: '' });
|
||||||
|
setSlugManuallySet(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Filter teams by search
|
||||||
|
const filteredTeams = teamsData?.items.filter(team =>
|
||||||
|
team.name.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||||
|
team.slug.toLowerCase().includes(searchQuery.toLowerCase()) ||
|
||||||
|
(team.description?.toLowerCase().includes(searchQuery.toLowerCase()))
|
||||||
|
) || [];
|
||||||
|
|
||||||
|
const totalTeams = teamsData?.items.length || 0;
|
||||||
|
|
||||||
|
const roleConfig: Record<string, { variant: 'success' | 'info' | 'default'; label: string }> = {
|
||||||
|
owner: { variant: 'success', label: 'Owner' },
|
||||||
|
admin: { variant: 'info', label: 'Admin' },
|
||||||
|
member: { variant: 'default', label: 'Member' },
|
||||||
|
};
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
return (
|
||||||
|
<div className="teams-page">
|
||||||
|
<div className="teams-empty-state">
|
||||||
|
<div className="teams-empty-icon">
|
||||||
|
<svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
|
||||||
|
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/>
|
||||||
|
<circle cx="9" cy="7" r="4"/>
|
||||||
|
<path d="M23 21v-2a4 4 0 0 0-3-3.87"/>
|
||||||
|
<path d="M16 3.13a4 4 0 0 1 0 7.75"/>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
<h2>Sign in to view your teams</h2>
|
||||||
|
<p>Teams help you organize projects and collaborate with others.</p>
|
||||||
|
<Link to="/login" className="btn btn-primary">Sign In</Link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="teams-page">
|
||||||
|
{/* Header */}
|
||||||
|
<div className="teams-header">
|
||||||
|
<h1>Teams</h1>
|
||||||
|
<button className="btn btn-primary" onClick={() => setShowForm(true)}>
|
||||||
|
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||||
|
<line x1="12" y1="5" x2="12" y2="19" />
|
||||||
|
<line x1="5" y1="12" x2="19" y2="12" />
|
||||||
|
</svg>
|
||||||
|
Create Team
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Search */}
|
||||||
|
{!loading && totalTeams > 3 && (
|
||||||
|
<div className="teams-search">
|
||||||
|
<svg className="teams-search__icon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||||
|
<circle cx="11" cy="11" r="8"/>
|
||||||
|
<line x1="21" y1="21" x2="16.65" y2="16.65"/>
|
||||||
|
</svg>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
placeholder="Search teams..."
|
||||||
|
value={searchQuery}
|
||||||
|
onChange={(e) => setSearchQuery(e.target.value)}
|
||||||
|
className="teams-search__input"
|
||||||
|
/>
|
||||||
|
{searchQuery && (
|
||||||
|
<button className="teams-search__clear" onClick={() => setSearchQuery('')}>
|
||||||
|
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||||
|
<line x1="18" y1="6" x2="6" y2="18"/>
|
||||||
|
<line x1="6" y1="6" x2="18" y2="18"/>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{error && (
|
||||||
|
<div className="teams-error">
|
||||||
|
{error}
|
||||||
|
<button onClick={() => setError(null)} className="teams-error__dismiss">×</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Create Team Modal */}
|
||||||
|
{showForm && (
|
||||||
|
<div className="modal-overlay" onClick={closeModal}>
|
||||||
|
<div className="modal-content" onClick={e => e.stopPropagation()}>
|
||||||
|
<div className="modal-header">
|
||||||
|
<h2>Create New Team</h2>
|
||||||
|
<button className="modal-close" onClick={closeModal}>
|
||||||
|
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
|
||||||
|
<line x1="18" y1="6" x2="6" y2="18"/>
|
||||||
|
<line x1="6" y1="6" x2="18" y2="18"/>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<form onSubmit={handleCreateTeam}>
|
||||||
|
<div className="form-group">
|
||||||
|
<label htmlFor="team-name">Team Name</label>
|
||||||
|
<input
|
||||||
|
id="team-name"
|
||||||
|
type="text"
|
||||||
|
value={newTeam.name}
|
||||||
|
onChange={e => handleNameChange(e.target.value)}
|
||||||
|
placeholder="Engineering"
|
||||||
|
required
|
||||||
|
autoFocus
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="form-group">
|
||||||
|
<label htmlFor="team-slug">URL Slug</label>
|
||||||
|
<div className="input-with-prefix">
|
||||||
|
<span className="input-prefix">@</span>
|
||||||
|
<input
|
||||||
|
id="team-slug"
|
||||||
|
type="text"
|
||||||
|
value={newTeam.slug}
|
||||||
|
onChange={e => handleSlugChange(e.target.value)}
|
||||||
|
placeholder="engineering"
|
||||||
|
pattern="^[a-z0-9][a-z0-9-]*[a-z0-9]$|^[a-z0-9]$"
|
||||||
|
title="Lowercase letters, numbers, and hyphens only"
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<span className="form-hint">Used in URLs. Lowercase letters, numbers, and hyphens.</span>
|
||||||
|
</div>
|
||||||
|
<div className="form-group">
|
||||||
|
<label htmlFor="team-description">Description <span className="optional">(optional)</span></label>
|
||||||
|
<textarea
|
||||||
|
id="team-description"
|
||||||
|
value={newTeam.description}
|
||||||
|
onChange={e => setNewTeam({ ...newTeam, description: e.target.value })}
|
||||||
|
placeholder="What is this team for?"
|
||||||
|
rows={3}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="form-actions">
|
||||||
|
<button type="button" className="btn btn-secondary" onClick={closeModal}>
|
||||||
|
Cancel
|
||||||
|
</button>
|
||||||
|
<button type="submit" className="btn btn-primary" disabled={creating}>
|
||||||
|
{creating ? 'Creating...' : 'Create Team'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Content */}
|
||||||
|
{loading ? (
|
||||||
|
<div className="teams-loading">
|
||||||
|
<div className="teams-loading__spinner" />
|
||||||
|
<span>Loading teams...</span>
|
||||||
|
</div>
|
||||||
|
) : filteredTeams.length === 0 ? (
|
||||||
|
<div className="teams-empty-state">
|
||||||
|
<div className="teams-empty-icon">
|
||||||
|
<svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
|
||||||
|
<path d="M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"/>
|
||||||
|
<circle cx="9" cy="7" r="4"/>
|
||||||
|
<path d="M23 21v-2a4 4 0 0 0-3-3.87"/>
|
||||||
|
<path d="M16 3.13a4 4 0 0 1 0 7.75"/>
|
||||||
|
</svg>
|
||||||
|
</div>
|
||||||
|
{searchQuery ? (
|
||||||
|
<>
|
||||||
|
<h2>No teams found</h2>
|
||||||
|
<p>No teams match "{searchQuery}"</p>
|
||||||
|
<button className="btn btn-secondary" onClick={() => setSearchQuery('')}>
|
||||||
|
Clear search
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<h2>No teams yet</h2>
|
||||||
|
<p>Create your first team to start organizing your projects.</p>
|
||||||
|
<button className="btn btn-primary" onClick={() => setShowForm(true)}>
|
||||||
|
Create Team
|
||||||
|
</button>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<DataTable
|
||||||
|
data={filteredTeams}
|
||||||
|
keyExtractor={(team) => team.id}
|
||||||
|
onRowClick={(team) => navigate(`/teams/${team.slug}`)}
|
||||||
|
columns={[
|
||||||
|
{
|
||||||
|
key: 'name',
|
||||||
|
header: 'Name',
|
||||||
|
render: (team) => (
|
||||||
|
<div className="team-name-cell">
|
||||||
|
<Link
|
||||||
|
to={`/teams/${team.slug}`}
|
||||||
|
className="cell-name"
|
||||||
|
onClick={(e) => e.stopPropagation()}
|
||||||
|
>
|
||||||
|
{team.name}
|
||||||
|
</Link>
|
||||||
|
<span className="team-slug">@{team.slug}</span>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'description',
|
||||||
|
header: 'Description',
|
||||||
|
className: 'cell-description',
|
||||||
|
render: (team) => team.description || <span className="text-muted">—</span>,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'role',
|
||||||
|
header: 'Role',
|
||||||
|
render: (team) => team.user_role ? (
|
||||||
|
<Badge variant={roleConfig[team.user_role]?.variant || 'default'}>
|
||||||
|
{roleConfig[team.user_role]?.label || team.user_role}
|
||||||
|
</Badge>
|
||||||
|
) : null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'members',
|
||||||
|
header: 'Members',
|
||||||
|
render: (team) => <span className="text-muted">{team.member_count}</span>,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: 'projects',
|
||||||
|
header: 'Projects',
|
||||||
|
render: (team) => <span className="text-muted">{team.project_count}</span>,
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default TeamsPage;
|
||||||
@@ -6,12 +6,17 @@ export interface Project {
|
|||||||
name: string;
|
name: string;
|
||||||
description: string | null;
|
description: string | null;
|
||||||
is_public: boolean;
|
is_public: boolean;
|
||||||
|
is_system?: boolean; // True for system cache projects (_npm, _pypi, etc.)
|
||||||
created_at: string;
|
created_at: string;
|
||||||
updated_at: string;
|
updated_at: string;
|
||||||
created_by: string;
|
created_by: string;
|
||||||
// Access level info (populated when listing projects)
|
// Access level info (populated when listing projects)
|
||||||
access_level?: AccessLevel | null;
|
access_level?: AccessLevel | null;
|
||||||
is_owner?: boolean;
|
is_owner?: boolean;
|
||||||
|
// Team info
|
||||||
|
team_id?: string | null;
|
||||||
|
team_slug?: string | null;
|
||||||
|
team_name?: string | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface TagSummary {
|
export interface TagSummary {
|
||||||
@@ -316,6 +321,8 @@ export interface UserUpdate {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Access Permission types
|
// Access Permission types
|
||||||
|
export type AccessSource = 'explicit' | 'team';
|
||||||
|
|
||||||
export interface AccessPermission {
|
export interface AccessPermission {
|
||||||
id: string;
|
id: string;
|
||||||
project_id: string;
|
project_id: string;
|
||||||
@@ -323,6 +330,9 @@ export interface AccessPermission {
|
|||||||
level: AccessLevel;
|
level: AccessLevel;
|
||||||
created_at: string;
|
created_at: string;
|
||||||
expires_at: string | null;
|
expires_at: string | null;
|
||||||
|
source?: AccessSource; // "explicit" or "team"
|
||||||
|
team_slug?: string; // Team slug if source is "team"
|
||||||
|
team_role?: string; // Team role if source is "team"
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface AccessPermissionCreate {
|
export interface AccessPermissionCreate {
|
||||||
@@ -447,3 +457,115 @@ export interface DependencyResolutionError {
|
|||||||
}>;
|
}>;
|
||||||
}>;
|
}>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Team types
|
||||||
|
export type TeamRole = 'owner' | 'admin' | 'member';
|
||||||
|
|
||||||
|
export interface Team {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
slug: string;
|
||||||
|
description: string | null;
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
member_count: number;
|
||||||
|
project_count: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TeamDetail extends Team {
|
||||||
|
user_role: TeamRole | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TeamMember {
|
||||||
|
id: string;
|
||||||
|
user_id: string;
|
||||||
|
username: string;
|
||||||
|
email: string | null;
|
||||||
|
role: TeamRole;
|
||||||
|
created_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TeamCreate {
|
||||||
|
name: string;
|
||||||
|
slug: string;
|
||||||
|
description?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TeamUpdate {
|
||||||
|
name?: string;
|
||||||
|
description?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TeamMemberCreate {
|
||||||
|
username: string;
|
||||||
|
role: TeamRole;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TeamMemberUpdate {
|
||||||
|
role: TeamRole;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Upstream Source types
|
||||||
|
export type SourceType = 'npm' | 'pypi' | 'maven' | 'docker' | 'helm' | 'nuget' | 'deb' | 'rpm' | 'generic';
|
||||||
|
export type AuthType = 'none' | 'basic' | 'bearer' | 'api_key';
|
||||||
|
|
||||||
|
export interface UpstreamSource {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
source_type: SourceType;
|
||||||
|
url: string;
|
||||||
|
enabled: boolean;
|
||||||
|
auth_type: AuthType;
|
||||||
|
username: string | null;
|
||||||
|
has_password: boolean;
|
||||||
|
has_headers: boolean;
|
||||||
|
priority: number;
|
||||||
|
source: 'database' | 'env';
|
||||||
|
created_at: string | null;
|
||||||
|
updated_at: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UpstreamSourceCreate {
|
||||||
|
name: string;
|
||||||
|
source_type: SourceType;
|
||||||
|
url: string;
|
||||||
|
enabled?: boolean;
|
||||||
|
auth_type?: AuthType;
|
||||||
|
username?: string;
|
||||||
|
password?: string;
|
||||||
|
headers?: Record<string, string>;
|
||||||
|
priority?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UpstreamSourceUpdate {
|
||||||
|
name?: string;
|
||||||
|
source_type?: SourceType;
|
||||||
|
url?: string;
|
||||||
|
enabled?: boolean;
|
||||||
|
auth_type?: AuthType;
|
||||||
|
username?: string;
|
||||||
|
password?: string;
|
||||||
|
headers?: Record<string, string> | null;
|
||||||
|
priority?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface UpstreamSourceTestResult {
|
||||||
|
success: boolean;
|
||||||
|
status_code: number | null;
|
||||||
|
elapsed_ms: number;
|
||||||
|
error: string | null;
|
||||||
|
source_id: string;
|
||||||
|
source_name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cache Settings types
|
||||||
|
export interface CacheSettings {
|
||||||
|
auto_create_system_projects: boolean;
|
||||||
|
auto_create_system_projects_env_override: boolean | null;
|
||||||
|
created_at: string | null;
|
||||||
|
updated_at: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CacheSettingsUpdate {
|
||||||
|
auto_create_system_projects?: boolean;
|
||||||
|
}
|
||||||
|
|||||||
@@ -128,6 +128,22 @@ spec:
|
|||||||
value: {{ .Values.orchard.rateLimit.login | quote }}
|
value: {{ .Values.orchard.rateLimit.login | quote }}
|
||||||
{{- end }}
|
{{- end }}
|
||||||
{{- end }}
|
{{- end }}
|
||||||
|
{{- if .Values.orchard.purgeSeedData }}
|
||||||
|
- name: ORCHARD_PURGE_SEED_DATA
|
||||||
|
value: "true"
|
||||||
|
{{- end }}
|
||||||
|
{{- if .Values.orchard.database.poolSize }}
|
||||||
|
- name: ORCHARD_DATABASE_POOL_SIZE
|
||||||
|
value: {{ .Values.orchard.database.poolSize | quote }}
|
||||||
|
{{- end }}
|
||||||
|
{{- if .Values.orchard.database.maxOverflow }}
|
||||||
|
- name: ORCHARD_DATABASE_MAX_OVERFLOW
|
||||||
|
value: {{ .Values.orchard.database.maxOverflow | quote }}
|
||||||
|
{{- end }}
|
||||||
|
{{- if .Values.orchard.database.poolTimeout }}
|
||||||
|
- name: ORCHARD_DATABASE_POOL_TIMEOUT
|
||||||
|
value: {{ .Values.orchard.database.poolTimeout | quote }}
|
||||||
|
{{- end }}
|
||||||
{{- if .Values.orchard.auth }}
|
{{- if .Values.orchard.auth }}
|
||||||
{{- if or .Values.orchard.auth.secretsManager .Values.orchard.auth.existingSecret .Values.orchard.auth.adminPassword }}
|
{{- if or .Values.orchard.auth.secretsManager .Values.orchard.auth.existingSecret .Values.orchard.auth.adminPassword }}
|
||||||
- name: ORCHARD_ADMIN_PASSWORD
|
- name: ORCHARD_ADMIN_PASSWORD
|
||||||
|
|||||||
@@ -53,15 +53,16 @@ ingress:
|
|||||||
hosts:
|
hosts:
|
||||||
- orchard-dev.common.global.bsf.tools # Overridden by CI
|
- orchard-dev.common.global.bsf.tools # Overridden by CI
|
||||||
|
|
||||||
# Lighter resources for ephemeral environments
|
# Resources for dev/feature environments
|
||||||
|
# Bumped to handle concurrent integration tests
|
||||||
# Note: memory requests must equal limits per cluster policy
|
# Note: memory requests must equal limits per cluster policy
|
||||||
resources:
|
resources:
|
||||||
limits:
|
limits:
|
||||||
cpu: 250m
|
cpu: 500m
|
||||||
memory: 256Mi
|
memory: 512Mi
|
||||||
requests:
|
requests:
|
||||||
cpu: 100m
|
cpu: 200m
|
||||||
memory: 256Mi
|
memory: 512Mi
|
||||||
|
|
||||||
livenessProbe:
|
livenessProbe:
|
||||||
httpGet:
|
httpGet:
|
||||||
@@ -103,6 +104,10 @@ orchard:
|
|||||||
sslmode: disable
|
sslmode: disable
|
||||||
existingSecret: ""
|
existingSecret: ""
|
||||||
existingSecretPasswordKey: "password"
|
existingSecretPasswordKey: "password"
|
||||||
|
# Increased pool settings for concurrent integration tests
|
||||||
|
poolSize: 10
|
||||||
|
maxOverflow: 20
|
||||||
|
poolTimeout: 60
|
||||||
|
|
||||||
s3:
|
s3:
|
||||||
endpoint: ""
|
endpoint: ""
|
||||||
@@ -138,15 +143,16 @@ postgresql:
|
|||||||
primary:
|
primary:
|
||||||
persistence:
|
persistence:
|
||||||
enabled: false
|
enabled: false
|
||||||
# Resources with memory requests = limits per cluster policy
|
# Bumped resources for concurrent integration tests
|
||||||
|
# Note: memory requests must equal limits per cluster policy
|
||||||
resourcesPreset: "none"
|
resourcesPreset: "none"
|
||||||
resources:
|
resources:
|
||||||
limits:
|
limits:
|
||||||
cpu: 250m
|
cpu: 500m
|
||||||
memory: 256Mi
|
memory: 512Mi
|
||||||
requests:
|
requests:
|
||||||
cpu: 100m
|
cpu: 200m
|
||||||
memory: 256Mi
|
memory: 512Mi
|
||||||
# Volume permissions init container
|
# Volume permissions init container
|
||||||
volumePermissions:
|
volumePermissions:
|
||||||
resourcesPreset: "none"
|
resourcesPreset: "none"
|
||||||
@@ -172,15 +178,16 @@ minio:
|
|||||||
defaultBuckets: "orchard-artifacts"
|
defaultBuckets: "orchard-artifacts"
|
||||||
persistence:
|
persistence:
|
||||||
enabled: false
|
enabled: false
|
||||||
# Resources with memory requests = limits per cluster policy
|
# Bumped resources for concurrent integration tests
|
||||||
|
# Note: memory requests must equal limits per cluster policy
|
||||||
resourcesPreset: "none" # Disable preset to use explicit resources
|
resourcesPreset: "none" # Disable preset to use explicit resources
|
||||||
resources:
|
resources:
|
||||||
limits:
|
limits:
|
||||||
cpu: 250m
|
cpu: 500m
|
||||||
memory: 256Mi
|
memory: 512Mi
|
||||||
requests:
|
requests:
|
||||||
cpu: 100m
|
cpu: 200m
|
||||||
memory: 256Mi
|
memory: 512Mi
|
||||||
# Init container resources
|
# Init container resources
|
||||||
defaultInitContainers:
|
defaultInitContainers:
|
||||||
volumePermissions:
|
volumePermissions:
|
||||||
|
|||||||
@@ -91,16 +91,14 @@ affinity: {}
|
|||||||
# Orchard server configuration
|
# Orchard server configuration
|
||||||
orchard:
|
orchard:
|
||||||
env: "development" # Allows seed data for testing
|
env: "development" # Allows seed data for testing
|
||||||
|
purgeSeedData: true # Remove public seed data (npm-public, pypi-public, etc.)
|
||||||
server:
|
server:
|
||||||
host: "0.0.0.0"
|
host: "0.0.0.0"
|
||||||
port: 8080
|
port: 8080
|
||||||
|
|
||||||
# Authentication settings
|
# Authentication settings
|
||||||
auth:
|
# Admin password is set via CI variable (STAGE_ADMIN_PASSWORD) passed as --set flag
|
||||||
# Admin password from AWS Secrets Manager
|
# This keeps the password out of version control
|
||||||
secretsManager:
|
|
||||||
enabled: true
|
|
||||||
secretArn: "arn:aws-us-gov:secretsmanager:us-gov-west-1:052673043337:secret:orchard-stage-creds-SMqvQx"
|
|
||||||
|
|
||||||
# Database configuration - uses AWS Secrets Manager via CSI driver
|
# Database configuration - uses AWS Secrets Manager via CSI driver
|
||||||
database:
|
database:
|
||||||
|
|||||||
62
migrations/009_teams.sql
Normal file
62
migrations/009_teams.sql
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
-- Migration 009: Teams and Multi-Tenancy
|
||||||
|
-- Adds support for team-based multi-tenancy
|
||||||
|
-- Part of Multi-Tenancy with Teams feature
|
||||||
|
|
||||||
|
-- Create teams table
|
||||||
|
CREATE TABLE IF NOT EXISTS teams (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
name VARCHAR(255) NOT NULL,
|
||||||
|
slug VARCHAR(255) NOT NULL UNIQUE,
|
||||||
|
description TEXT,
|
||||||
|
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
created_by VARCHAR(255) NOT NULL,
|
||||||
|
settings JSONB DEFAULT '{}'::jsonb,
|
||||||
|
|
||||||
|
-- Slug must be lowercase alphanumeric with hyphens
|
||||||
|
CONSTRAINT check_team_slug_format CHECK (slug ~ '^[a-z0-9][a-z0-9-]*[a-z0-9]$' OR slug ~ '^[a-z0-9]$')
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Create team_memberships table
|
||||||
|
CREATE TABLE IF NOT EXISTS team_memberships (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
team_id UUID NOT NULL REFERENCES teams(id) ON DELETE CASCADE,
|
||||||
|
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
role VARCHAR(20) NOT NULL DEFAULT 'member',
|
||||||
|
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
invited_by VARCHAR(255),
|
||||||
|
|
||||||
|
-- Each user can only be a member of a team once
|
||||||
|
CONSTRAINT unique_team_membership UNIQUE (team_id, user_id),
|
||||||
|
|
||||||
|
-- Role must be one of: owner, admin, member
|
||||||
|
CONSTRAINT check_team_role CHECK (role IN ('owner', 'admin', 'member'))
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Add team_id column to projects table (nullable for migration compatibility)
|
||||||
|
ALTER TABLE projects ADD COLUMN IF NOT EXISTS team_id UUID REFERENCES teams(id) ON DELETE SET NULL;
|
||||||
|
|
||||||
|
-- Indexes for teams table
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_teams_slug ON teams(slug);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_teams_created_by ON teams(created_by);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_teams_created_at ON teams(created_at);
|
||||||
|
|
||||||
|
-- Indexes for team_memberships table
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_team_memberships_team_id ON team_memberships(team_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_team_memberships_user_id ON team_memberships(user_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_team_memberships_role ON team_memberships(role);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_team_memberships_team_role ON team_memberships(team_id, role);
|
||||||
|
|
||||||
|
-- Index for projects team_id
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_projects_team_id ON projects(team_id);
|
||||||
|
|
||||||
|
-- Comments
|
||||||
|
COMMENT ON TABLE teams IS 'Teams serve as organizational containers for projects';
|
||||||
|
COMMENT ON COLUMN teams.slug IS 'URL-friendly unique identifier (lowercase alphanumeric with hyphens)';
|
||||||
|
COMMENT ON COLUMN teams.settings IS 'JSON object for team-specific settings';
|
||||||
|
|
||||||
|
COMMENT ON TABLE team_memberships IS 'Maps users to teams with their roles';
|
||||||
|
COMMENT ON COLUMN team_memberships.role IS 'User role in the team: owner, admin, or member';
|
||||||
|
COMMENT ON COLUMN team_memberships.invited_by IS 'Username of the user who invited this member';
|
||||||
|
|
||||||
|
COMMENT ON COLUMN projects.team_id IS 'Optional team that owns this project';
|
||||||
99
migrations/009b_migrate_projects.sql
Normal file
99
migrations/009b_migrate_projects.sql
Normal file
@@ -0,0 +1,99 @@
|
|||||||
|
-- Migration 009b: Migrate Existing Projects to Personal Teams
|
||||||
|
-- Creates personal teams for existing users and assigns their projects to those teams.
|
||||||
|
-- This migration is idempotent and can be run multiple times safely.
|
||||||
|
|
||||||
|
-- Create personal teams for users who own projects but don't have a personal team yet
|
||||||
|
INSERT INTO teams (name, slug, description, created_by, settings)
|
||||||
|
SELECT DISTINCT
|
||||||
|
u.username || '''s Team' AS name,
|
||||||
|
LOWER(u.username) || '-personal' AS slug,
|
||||||
|
'Personal team for ' || u.username AS description,
|
||||||
|
u.username AS created_by,
|
||||||
|
'{"personal": true}'::jsonb AS settings
|
||||||
|
FROM users u
|
||||||
|
JOIN projects p ON p.created_by = u.username
|
||||||
|
WHERE NOT EXISTS (
|
||||||
|
SELECT 1 FROM teams t
|
||||||
|
WHERE t.slug = LOWER(u.username) || '-personal'
|
||||||
|
)
|
||||||
|
AND p.team_id IS NULL
|
||||||
|
ON CONFLICT (slug) DO NOTHING;
|
||||||
|
|
||||||
|
-- Add users as owners of their personal teams
|
||||||
|
INSERT INTO team_memberships (team_id, user_id, role, invited_by)
|
||||||
|
SELECT
|
||||||
|
t.id AS team_id,
|
||||||
|
u.id AS user_id,
|
||||||
|
'owner' AS role,
|
||||||
|
u.username AS invited_by
|
||||||
|
FROM teams t
|
||||||
|
JOIN users u ON t.created_by = u.username
|
||||||
|
WHERE t.slug LIKE '%-personal'
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM team_memberships tm
|
||||||
|
WHERE tm.team_id = t.id
|
||||||
|
AND tm.user_id = u.id
|
||||||
|
)
|
||||||
|
ON CONFLICT DO NOTHING;
|
||||||
|
|
||||||
|
-- Assign projects without a team to their creator's personal team
|
||||||
|
UPDATE projects p
|
||||||
|
SET team_id = t.id
|
||||||
|
FROM teams t
|
||||||
|
WHERE t.slug = LOWER(p.created_by) || '-personal'
|
||||||
|
AND p.team_id IS NULL;
|
||||||
|
|
||||||
|
-- Handle orphaned projects (created_by doesn't match any user)
|
||||||
|
-- Create a special orphaned projects team if there are any
|
||||||
|
DO $$
|
||||||
|
DECLARE
|
||||||
|
orphan_count INTEGER;
|
||||||
|
orphan_team_id UUID;
|
||||||
|
BEGIN
|
||||||
|
-- Count orphaned projects
|
||||||
|
SELECT COUNT(*) INTO orphan_count
|
||||||
|
FROM projects p
|
||||||
|
WHERE p.team_id IS NULL
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM users u WHERE u.username = p.created_by
|
||||||
|
);
|
||||||
|
|
||||||
|
IF orphan_count > 0 THEN
|
||||||
|
-- Create or get the orphaned projects team
|
||||||
|
INSERT INTO teams (name, slug, description, created_by, settings)
|
||||||
|
VALUES (
|
||||||
|
'Orphaned Projects',
|
||||||
|
'orphaned-projects',
|
||||||
|
'Projects whose original creators no longer exist',
|
||||||
|
'system',
|
||||||
|
'{"system": true}'::jsonb
|
||||||
|
)
|
||||||
|
ON CONFLICT (slug) DO UPDATE SET name = teams.name
|
||||||
|
RETURNING id INTO orphan_team_id;
|
||||||
|
|
||||||
|
-- Assign orphaned projects to this team
|
||||||
|
UPDATE projects
|
||||||
|
SET team_id = orphan_team_id
|
||||||
|
WHERE team_id IS NULL
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM users u WHERE u.username = projects.created_by
|
||||||
|
);
|
||||||
|
|
||||||
|
RAISE NOTICE 'Migrated % orphaned project(s) to orphaned-projects team', orphan_count;
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
-- Log migration results
|
||||||
|
DO $$
|
||||||
|
DECLARE
|
||||||
|
teams_created INTEGER;
|
||||||
|
memberships_created INTEGER;
|
||||||
|
projects_migrated INTEGER;
|
||||||
|
BEGIN
|
||||||
|
SELECT COUNT(*) INTO teams_created FROM teams WHERE slug LIKE '%-personal';
|
||||||
|
SELECT COUNT(*) INTO memberships_created FROM team_memberships;
|
||||||
|
SELECT COUNT(*) INTO projects_migrated FROM projects WHERE team_id IS NOT NULL;
|
||||||
|
|
||||||
|
RAISE NOTICE 'Migration complete: % personal teams, % memberships, % projects with teams',
|
||||||
|
teams_created, memberships_created, projects_migrated;
|
||||||
|
END $$;
|
||||||
137
migrations/010_upstream_caching.sql
Normal file
137
migrations/010_upstream_caching.sql
Normal file
@@ -0,0 +1,137 @@
|
|||||||
|
-- Migration 010: Upstream Artifact Caching
|
||||||
|
-- Adds support for caching artifacts from upstream registries (npm, PyPI, Maven, etc.)
|
||||||
|
-- Part of "The cache that never forgets" epic for hermetic builds
|
||||||
|
|
||||||
|
-- =============================================================================
|
||||||
|
-- upstream_sources: Configure upstream registries for artifact caching
|
||||||
|
-- =============================================================================
|
||||||
|
CREATE TABLE IF NOT EXISTS upstream_sources (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
name VARCHAR(255) NOT NULL UNIQUE,
|
||||||
|
source_type VARCHAR(50) NOT NULL DEFAULT 'generic',
|
||||||
|
url VARCHAR(2048) NOT NULL,
|
||||||
|
enabled BOOLEAN NOT NULL DEFAULT FALSE,
|
||||||
|
is_public BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
auth_type VARCHAR(20) NOT NULL DEFAULT 'none',
|
||||||
|
username VARCHAR(255),
|
||||||
|
password_encrypted BYTEA,
|
||||||
|
headers_encrypted BYTEA,
|
||||||
|
priority INTEGER NOT NULL DEFAULT 100,
|
||||||
|
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
-- Source type must be one of the supported types
|
||||||
|
CONSTRAINT check_source_type CHECK (
|
||||||
|
source_type IN ('npm', 'pypi', 'maven', 'docker', 'helm', 'nuget', 'deb', 'rpm', 'generic')
|
||||||
|
),
|
||||||
|
|
||||||
|
-- Auth type must be valid
|
||||||
|
CONSTRAINT check_auth_type CHECK (
|
||||||
|
auth_type IN ('none', 'basic', 'bearer', 'api_key')
|
||||||
|
),
|
||||||
|
|
||||||
|
-- Priority must be positive
|
||||||
|
CONSTRAINT check_priority_positive CHECK (priority > 0)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Indexes for upstream_sources
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_upstream_sources_enabled ON upstream_sources(enabled);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_upstream_sources_source_type ON upstream_sources(source_type);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_upstream_sources_is_public ON upstream_sources(is_public);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_upstream_sources_priority ON upstream_sources(priority);
|
||||||
|
|
||||||
|
-- Comments for upstream_sources
|
||||||
|
COMMENT ON TABLE upstream_sources IS 'Configuration for upstream artifact registries (npm, PyPI, Maven, etc.)';
|
||||||
|
COMMENT ON COLUMN upstream_sources.name IS 'Unique human-readable name (e.g., npm-public, artifactory-private)';
|
||||||
|
COMMENT ON COLUMN upstream_sources.source_type IS 'Type of registry: npm, pypi, maven, docker, helm, nuget, deb, rpm, generic';
|
||||||
|
COMMENT ON COLUMN upstream_sources.url IS 'Base URL of the upstream registry';
|
||||||
|
COMMENT ON COLUMN upstream_sources.enabled IS 'Whether this source is active for caching';
|
||||||
|
COMMENT ON COLUMN upstream_sources.is_public IS 'True if this is a public internet source (for air-gap mode)';
|
||||||
|
COMMENT ON COLUMN upstream_sources.auth_type IS 'Authentication type: none, basic, bearer, api_key';
|
||||||
|
COMMENT ON COLUMN upstream_sources.username IS 'Username for basic auth';
|
||||||
|
COMMENT ON COLUMN upstream_sources.password_encrypted IS 'Fernet-encrypted password/token';
|
||||||
|
COMMENT ON COLUMN upstream_sources.headers_encrypted IS 'Fernet-encrypted custom headers (JSON)';
|
||||||
|
COMMENT ON COLUMN upstream_sources.priority IS 'Priority for source selection (lower = higher priority)';
|
||||||
|
|
||||||
|
-- =============================================================================
|
||||||
|
-- cache_settings: Global cache configuration (singleton table)
|
||||||
|
-- =============================================================================
|
||||||
|
CREATE TABLE IF NOT EXISTS cache_settings (
|
||||||
|
id INTEGER PRIMARY KEY DEFAULT 1,
|
||||||
|
allow_public_internet BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
auto_create_system_projects BOOLEAN NOT NULL DEFAULT TRUE,
|
||||||
|
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
-- Singleton constraint
|
||||||
|
CONSTRAINT check_cache_settings_singleton CHECK (id = 1)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Insert default row
|
||||||
|
INSERT INTO cache_settings (id, allow_public_internet, auto_create_system_projects)
|
||||||
|
VALUES (1, TRUE, TRUE)
|
||||||
|
ON CONFLICT (id) DO NOTHING;
|
||||||
|
|
||||||
|
-- Comments for cache_settings
|
||||||
|
COMMENT ON TABLE cache_settings IS 'Global cache settings (singleton table)';
|
||||||
|
COMMENT ON COLUMN cache_settings.allow_public_internet IS 'Air-gap mode: when false, blocks all public internet sources';
|
||||||
|
COMMENT ON COLUMN cache_settings.auto_create_system_projects IS 'Auto-create system projects (_npm, _pypi, etc.) on first cache';
|
||||||
|
|
||||||
|
-- =============================================================================
|
||||||
|
-- cached_urls: Track URL to artifact mappings for provenance
|
||||||
|
-- =============================================================================
|
||||||
|
CREATE TABLE IF NOT EXISTS cached_urls (
|
||||||
|
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
url VARCHAR(4096) NOT NULL,
|
||||||
|
url_hash VARCHAR(64) NOT NULL,
|
||||||
|
artifact_id VARCHAR(64) NOT NULL REFERENCES artifacts(id),
|
||||||
|
source_id UUID REFERENCES upstream_sources(id) ON DELETE SET NULL,
|
||||||
|
fetched_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
response_headers JSONB DEFAULT '{}',
|
||||||
|
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
|
||||||
|
-- URL hash must be unique (same URL = same cached artifact)
|
||||||
|
CONSTRAINT unique_url_hash UNIQUE (url_hash)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Indexes for cached_urls
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_cached_urls_url_hash ON cached_urls(url_hash);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_cached_urls_artifact_id ON cached_urls(artifact_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_cached_urls_source_id ON cached_urls(source_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_cached_urls_fetched_at ON cached_urls(fetched_at);
|
||||||
|
|
||||||
|
-- Comments for cached_urls
|
||||||
|
COMMENT ON TABLE cached_urls IS 'Tracks which URLs have been cached and maps to artifacts';
|
||||||
|
COMMENT ON COLUMN cached_urls.url IS 'Original URL that was fetched';
|
||||||
|
COMMENT ON COLUMN cached_urls.url_hash IS 'SHA256 hash of URL for fast lookup';
|
||||||
|
COMMENT ON COLUMN cached_urls.artifact_id IS 'The cached artifact (by SHA256 content hash)';
|
||||||
|
COMMENT ON COLUMN cached_urls.source_id IS 'Which upstream source provided this (null if manual)';
|
||||||
|
COMMENT ON COLUMN cached_urls.fetched_at IS 'When the URL was fetched from upstream';
|
||||||
|
COMMENT ON COLUMN cached_urls.response_headers IS 'Original response headers from upstream (for debugging)';
|
||||||
|
|
||||||
|
-- =============================================================================
|
||||||
|
-- Add is_system column to projects table for system cache projects
|
||||||
|
-- =============================================================================
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF NOT EXISTS (
|
||||||
|
SELECT 1 FROM information_schema.columns
|
||||||
|
WHERE table_name = 'projects' AND column_name = 'is_system'
|
||||||
|
) THEN
|
||||||
|
ALTER TABLE projects ADD COLUMN is_system BOOLEAN NOT NULL DEFAULT FALSE;
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_projects_is_system ON projects(is_system);
|
||||||
|
END IF;
|
||||||
|
END $$;
|
||||||
|
|
||||||
|
COMMENT ON COLUMN projects.is_system IS 'True for system cache projects (_npm, _pypi, etc.)';
|
||||||
|
|
||||||
|
-- =============================================================================
|
||||||
|
-- Seed default upstream sources (disabled by default for safety)
|
||||||
|
-- =============================================================================
|
||||||
|
INSERT INTO upstream_sources (id, name, source_type, url, enabled, is_public, auth_type, priority)
|
||||||
|
VALUES
|
||||||
|
(gen_random_uuid(), 'npm-public', 'npm', 'https://registry.npmjs.org', FALSE, TRUE, 'none', 100),
|
||||||
|
(gen_random_uuid(), 'pypi-public', 'pypi', 'https://pypi.org/simple', FALSE, TRUE, 'none', 100),
|
||||||
|
(gen_random_uuid(), 'maven-central', 'maven', 'https://repo1.maven.org/maven2', FALSE, TRUE, 'none', 100),
|
||||||
|
(gen_random_uuid(), 'docker-hub', 'docker', 'https://registry-1.docker.io', FALSE, TRUE, 'none', 100)
|
||||||
|
ON CONFLICT (name) DO NOTHING;
|
||||||
Reference in New Issue
Block a user