From 9e805822a5042391917496a5fd194f7537bd7f55 Mon Sep 17 00:00:00 2001 From: Daniel Lynch Date: Sun, 8 Nov 2026 00:41:51 -0500 Subject: [PATCH 1/5] fix(auth): enforce WorkOS tenant isolation across API and UI --- .dockerignore | 2 + .github/workflows/deploy-docker-compose.yml | 15 +- .github/workflows/deploy.yml | 21 +- .github/workflows/playwright.yml | 169 ++-- .github/workflows/test-backend.yml | 32 +- .github/workflows/test-docker-compose.yml | 17 +- .pre-commit-config.yaml | 36 +- README.md | 67 +- backend/Dockerfile | 8 +- backend/README.md | 269 +++--- backend/alembic-api.ini | 32 + .../8f8f28c9c266_initialize_api_namespace.py | 64 ++ ...cb88acf026a_enforce_api_tenant_security.py | 71 ++ backend/app/alembic/env.py | 200 +++-- backend/app/alembic/native_security.py | 142 +++ backend/app/alembic/security.py | 126 +++ backend/app/api/deps.py | 92 +- backend/app/api/main.py | 9 +- backend/app/api/routes/auth.py | 23 + backend/app/api/routes/items.py | 130 ++- backend/app/api/routes/login.py | 123 --- backend/app/api/routes/private.py | 38 - backend/app/api/routes/users.py | 280 +++--- backend/app/api/routes/utils.py | 25 +- backend/app/core/auth.py | 268 ++++++ backend/app/core/config.py | 108 ++- backend/app/core/db.py | 34 +- backend/app/core/security.py | 117 ++- backend/app/crud.py | 138 +-- backend/app/initial_data.py | 23 - backend/app/models.py | 156 ++-- backend/app/utils.py | 62 -- backend/pyproject.toml | 7 +- backend/scripts/export_openapi.py | 30 + backend/scripts/prestart.sh | 8 +- backend/tests/api/routes/test_items.py | 259 +++--- backend/tests/api/routes/test_login.py | 242 ++--- backend/tests/api/routes/test_private.py | 30 +- backend/tests/api/routes/test_users.py | 830 +++++++----------- backend/tests/conftest.py | 173 +++- backend/tests/crud/test_user.py | 263 +++--- backend/tests/test_data_namespace.py | 145 +++ .../tests/test_data_namespace_postgresql.py | 59 ++ backend/tests/test_data_rls_postgresql.py | 407 +++++++++ backend/tests/test_policy_generation.py | 243 +++++ backend/tests/test_workos_security.py | 201 +++++ backend/tests/utils/item.py | 16 - backend/tests/utils/user.py | 49 -- backend/tests/utils/utils.py | 26 - bun.lock | 5 + compose.deploy.yml | 16 - compose.override.yml | 10 - compose.yml | 65 +- deployment-docker-compose.md | 56 +- deployment.md | 142 +-- development.md | 33 +- frontend/biome.json | 5 + frontend/index.html | 3 +- frontend/package.json | 6 +- frontend/playwright.config.ts | 99 +-- frontend/src/client/index.ts | 4 +- frontend/src/client/sdk.gen.ts | 173 +--- frontend/src/client/types.gen.ts | 401 ++------- frontend/src/components/Admin/AddUser.tsx | 81 +- frontend/src/components/Admin/EditUser.tsx | 84 +- .../src/components/Admin/UserActionsMenu.tsx | 6 +- frontend/src/components/Admin/columns.tsx | 10 +- frontend/src/components/AuthProvider.tsx | 252 ++++++ frontend/src/components/HostedSignIn.tsx | 29 + .../src/components/Items/ItemActionsMenu.tsx | 3 + .../src/components/OrganizationSwitcher.tsx | 25 + .../src/components/Sidebar/AppSidebar.tsx | 2 +- frontend/src/components/Sidebar/User.tsx | 13 +- .../UserSettings/ChangePassword.tsx | 146 --- .../UserSettings/UserInformation.tsx | 8 +- frontend/src/components/ui/password-input.tsx | 51 -- frontend/src/hooks/useAuth.ts | 82 +- frontend/src/lib/session-transport.ts | 15 + frontend/src/main.tsx | 40 +- frontend/src/routeTree.gen.ts | 58 +- frontend/src/routes/_layout.tsx | 47 +- frontend/src/routes/_layout/admin.tsx | 20 +- frontend/src/routes/_layout/items.tsx | 11 +- frontend/src/routes/_layout/settings.tsx | 8 +- frontend/src/routes/login.tsx | 142 +-- frontend/src/routes/recover-password.tsx | 130 --- frontend/src/routes/reset-password.tsx | 166 ---- frontend/src/routes/signup.tsx | 187 +--- frontend/tests/admin.spec.ts | 231 +---- frontend/tests/auth.setup.ts | 13 - frontend/tests/config.ts | 19 - frontend/tests/items.spec.ts | 256 +++--- frontend/tests/login.spec.ts | 168 ++-- frontend/tests/reset-password.spec.ts | 114 --- frontend/tests/session-boundary.spec.ts | 20 + frontend/tests/sign-up.spec.ts | 160 ---- frontend/tests/user-settings.spec.ts | 276 +----- frontend/tests/utils/authkit-fixture.ts | 82 ++ frontend/tests/utils/mailpit.ts | 46 - frontend/tests/utils/privateApi.ts | 26 - frontend/tests/utils/random.ts | 19 - frontend/tests/utils/user.ts | 35 - pyproject.toml | 2 + scripts/generate-client.sh | 12 +- uv.lock | 316 ++++--- 105 files changed, 4981 insertions(+), 5333 deletions(-) create mode 100644 backend/alembic-api.ini create mode 100644 backend/app/alembic/api_versions/8f8f28c9c266_initialize_api_namespace.py create mode 100644 backend/app/alembic/api_versions/9cb88acf026a_enforce_api_tenant_security.py create mode 100644 backend/app/alembic/native_security.py create mode 100644 backend/app/alembic/security.py create mode 100644 backend/app/api/routes/auth.py delete mode 100644 backend/app/api/routes/login.py delete mode 100644 backend/app/api/routes/private.py create mode 100644 backend/app/core/auth.py delete mode 100644 backend/app/initial_data.py create mode 100644 backend/scripts/export_openapi.py create mode 100644 backend/tests/test_data_namespace.py create mode 100644 backend/tests/test_data_namespace_postgresql.py create mode 100644 backend/tests/test_data_rls_postgresql.py create mode 100644 backend/tests/test_policy_generation.py create mode 100644 backend/tests/test_workos_security.py delete mode 100644 backend/tests/utils/item.py delete mode 100644 backend/tests/utils/user.py delete mode 100644 backend/tests/utils/utils.py create mode 100644 frontend/src/components/AuthProvider.tsx create mode 100644 frontend/src/components/HostedSignIn.tsx create mode 100644 frontend/src/components/OrganizationSwitcher.tsx delete mode 100644 frontend/src/components/UserSettings/ChangePassword.tsx delete mode 100644 frontend/src/components/ui/password-input.tsx create mode 100644 frontend/src/lib/session-transport.ts delete mode 100644 frontend/src/routes/recover-password.tsx delete mode 100644 frontend/src/routes/reset-password.tsx delete mode 100644 frontend/tests/auth.setup.ts delete mode 100644 frontend/tests/config.ts delete mode 100644 frontend/tests/reset-password.spec.ts create mode 100644 frontend/tests/session-boundary.spec.ts delete mode 100644 frontend/tests/sign-up.spec.ts create mode 100644 frontend/tests/utils/authkit-fixture.ts delete mode 100644 frontend/tests/utils/mailpit.ts delete mode 100644 frontend/tests/utils/privateApi.ts delete mode 100644 frontend/tests/utils/random.ts delete mode 100644 frontend/tests/utils/user.ts diff --git a/.dockerignore b/.dockerignore index c892b070cd..116b306f6e 100644 --- a/.dockerignore +++ b/.dockerignore @@ -1,4 +1,6 @@ .git +.env +.env.* **/__pycache__ **/.venv backend/htmlcov diff --git a/.github/workflows/deploy-docker-compose.yml b/.github/workflows/deploy-docker-compose.yml index 4062687b1d..c7c518753b 100644 --- a/.github/workflows/deploy-docker-compose.yml +++ b/.github/workflows/deploy-docker-compose.yml @@ -16,17 +16,22 @@ jobs: if: github.repository != 'fastapi/full-stack-fastapi-template' runs-on: self-hosted timeout-minutes: 30 + environment: production + # Required reviewers/environment protection need native owner readback before use. env: DOMAIN: ${{ vars.DOMAIN }} PROJECT_NAME: ${{ vars.PROJECT_NAME }} - SECRET_KEY: ${{ secrets.SECRET_KEY }} - FIRST_SUPERUSER: ${{ vars.FIRST_SUPERUSER }} - FIRST_SUPERUSER_PASSWORD: ${{ secrets.FIRST_SUPERUSER_PASSWORD }} + FRONTEND_HOST: ${{ vars.FRONTEND_HOST }} + WORKOS_CLIENT_ID: ${{ vars.WORKOS_CLIENT_ID }} + WORKOS_ISSUER: ${{ vars.WORKOS_ISSUER }} + WORKOS_JWKS_URL: ${{ vars.WORKOS_JWKS_URL }} + WORKOS_API_HOSTNAME: ${{ vars.WORKOS_API_HOSTNAME }} + DATABASE_URL: ${{ secrets.DATABASE_URL }} + API_MIGRATION_DATABASE_URL: ${{ secrets.API_MIGRATION_DATABASE_URL }} SMTP_HOST: ${{ vars.SMTP_HOST }} SMTP_USER: ${{ vars.SMTP_USER }} SMTP_PASSWORD: ${{ secrets.SMTP_PASSWORD }} EMAILS_FROM_EMAIL: ${{ vars.EMAILS_FROM_EMAIL }} - POSTGRES_PASSWORD: ${{ secrets.POSTGRES_PASSWORD }} SENTRY_DSN: ${{ vars.SENTRY_DSN }} steps: - name: Checkout @@ -36,6 +41,6 @@ jobs: - name: Build run: docker compose -f compose.yml -f compose.deploy.yml build - name: Prepare database - run: docker compose -f compose.yml -f compose.deploy.yml run --rm backend bash scripts/prestart.sh + run: docker compose -f compose.yml -f compose.deploy.yml run --rm migrate - name: Start application run: docker compose -f compose.yml -f compose.deploy.yml up -d diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 9198e13780..6eaca8777c 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -1,11 +1,6 @@ name: Deploy on: - push: - branches: - - master - paths-ignore: - - release-notes.md workflow_dispatch: permissions: @@ -17,6 +12,16 @@ jobs: if: github.repository != 'fastapi/full-stack-fastapi-template' runs-on: ubuntu-latest timeout-minutes: 15 + environment: production + # Required reviewers/environment protection need native owner readback before use. + env: + PROJECT_NAME: ${{ vars.PROJECT_NAME }} + FRONTEND_HOST: ${{ vars.FRONTEND_HOST }} + WORKOS_CLIENT_ID: ${{ vars.WORKOS_CLIENT_ID }} + WORKOS_ISSUER: ${{ vars.WORKOS_ISSUER }} + WORKOS_JWKS_URL: ${{ vars.WORKOS_JWKS_URL }} + WORKOS_API_HOSTNAME: ${{ vars.WORKOS_API_HOSTNAME }} + DATABASE_URL: ${{ secrets.DATABASE_URL }} steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -42,11 +47,7 @@ jobs: run: uv run bash scripts/prestart.sh working-directory: backend env: - DATABASE_URL: ${{ secrets.DATABASE_URL }} - PROJECT_NAME: ${{ vars.PROJECT_NAME }} - SECRET_KEY: ${{ secrets.SECRET_KEY }} - FIRST_SUPERUSER: ${{ vars.FIRST_SUPERUSER }} - FIRST_SUPERUSER_PASSWORD: ${{ secrets.FIRST_SUPERUSER_PASSWORD }} + API_MIGRATION_DATABASE_URL: ${{ secrets.API_MIGRATION_DATABASE_URL }} - name: Deploy to FastAPI Cloud run: uv run fastapi deploy env: diff --git a/.github/workflows/playwright.yml b/.github/workflows/playwright.yml index 2d113b81ec..66c38cb97e 100644 --- a/.github/workflows/playwright.yml +++ b/.github/workflows/playwright.yml @@ -3,14 +3,14 @@ name: Playwright Tests on: push: branches: - - master + - master pull_request: workflow_dispatch: inputs: debug_enabled: - description: 'Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)' + description: "Run the build with tmate debugging enabled (https://github.com/marketplace/actions/debugging-with-tmate)" required: false - default: 'false' + default: "false" permissions: contents: read @@ -23,21 +23,21 @@ jobs: outputs: changed: ${{ steps.filter.outputs.changed }} steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - fetch-depth: 2 - persist-credentials: false - # For pull requests it's not necessary to checkout the code but for the main branch it is - - uses: dorny/paths-filter@ceb8a2b8f2d89434be7ff52d3de7ec3738c5cc9d # v4.0.3 - id: filter - with: - filters: | - changed: - - backend/** - - frontend/** - - .env - - compose*.yml - - .github/workflows/playwright.yml + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 2 + persist-credentials: false + # For pull requests it's not necessary to checkout the code but for the main branch it is + - uses: dorny/paths-filter@ceb8a2b8f2d89434be7ff52d3de7ec3738c5cc9d # v4.0.3 + id: filter + with: + filters: | + changed: + - backend/** + - frontend/** + - .env + - compose*.yml + - .github/workflows/playwright.yml test-playwright: needs: @@ -45,49 +45,58 @@ jobs: if: ${{ needs.changes.outputs.changed == 'true' }} timeout-minutes: 15 runs-on: ubuntu-latest + env: + # Browser network fixtures are not backend JWT/RLS or live WorkOS proof. + PROJECT_NAME: API browser fixture + FRONTEND_HOST: http://backend:8000 + FASTAPI_ENV: development + WORKOS_CLIENT_ID: client_fixture + WORKOS_ISSUER: https://auth.fixture.test/ + WORKOS_JWKS_URL: https://auth.fixture.test/sso/jwks/client_fixture + WORKOS_API_HOSTNAME: auth.fixture.test + DATABASE_URL: postgresql+psycopg://fixture:fixture@localhost/api_test_unconfigured strategy: matrix: shardIndex: [1, 2, 3, 4] shardTotal: [4] fail-fast: false steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 - with: - bun-version: 1.3.12 - - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 - with: - python-version-file: .python-version - - name: Setup tmate session - uses: mxschmitt/action-tmate@35b54afac29c97fb54faba5b513f8fbd1882f113 # v3.24 - if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} - with: - limit-access-to-actor: true - - name: Install uv - uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2 - with: - version: "latest-known" - - run: uv sync - working-directory: backend - - run: bun ci - working-directory: frontend - - run: bash scripts/generate-client.sh - - run: docker compose build - - run: docker compose down -v --remove-orphans - - run: docker compose run --rm backend bash scripts/prestart.sh - - name: Run Playwright tests - run: docker compose run --rm playwright bunx playwright test --fail-on-flaky-tests --trace=retain-on-failure --shard=${{ matrix.shardIndex }}/${{ matrix.shardTotal }} - - run: docker compose down -v --remove-orphans - - name: Upload blob report to GitHub Actions Artifacts - if: ${{ !cancelled() }} - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: blob-report-${{ matrix.shardIndex }} - path: frontend/blob-report - include-hidden-files: true - retention-days: 1 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 + with: + bun-version: 1.3.12 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version-file: .python-version + - name: Setup tmate session + uses: mxschmitt/action-tmate@35b54afac29c97fb54faba5b513f8fbd1882f113 # v3.24 + if: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.debug_enabled == 'true' }} + with: + limit-access-to-actor: true + - name: Install uv + uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2 + with: + version: "latest-known" + - run: uv sync + working-directory: backend + - run: bun ci + working-directory: frontend + - run: bash scripts/generate-client.sh + - run: docker compose build + - run: docker compose down -v --remove-orphans + - name: Run Playwright tests + run: docker compose run --rm playwright bunx playwright test --fail-on-flaky-tests --trace=retain-on-failure --shard=${{ matrix.shardIndex }}/${{ matrix.shardTotal }} + - run: docker compose down -v --remove-orphans + - name: Upload blob report to GitHub Actions Artifacts + if: ${{ !cancelled() }} + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: blob-report-${{ matrix.shardIndex }} + path: frontend/blob-report + include-hidden-files: true + retention-days: 1 merge-playwright-reports: needs: @@ -98,33 +107,33 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 5 steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 - with: - bun-version: 1.3.12 - - name: Install dependencies - run: bun ci - - name: Download blob reports from GitHub Actions Artifacts - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 - with: - path: frontend/all-blob-reports - pattern: blob-report-* - merge-multiple: true - - name: Merge into HTML Report - run: bunx playwright merge-reports --reporter html ./all-blob-reports - working-directory: frontend - - name: Upload HTML report - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: html-report--attempt-${{ github.run_attempt }} - path: frontend/playwright-report - retention-days: 30 - include-hidden-files: true + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0 + with: + bun-version: 1.3.12 + - name: Install dependencies + run: bun ci + - name: Download blob reports from GitHub Actions Artifacts + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + path: frontend/all-blob-reports + pattern: blob-report-* + merge-multiple: true + - name: Merge into HTML Report + run: bunx playwright merge-reports --reporter html ./all-blob-reports + working-directory: frontend + - name: Upload HTML report + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: html-report--attempt-${{ github.run_attempt }} + path: frontend/playwright-report + retention-days: 30 + include-hidden-files: true # https://github.com/marketplace/actions/alls-green#why - alls-green-playwright: # This job does nothing and is only used for the branch protection + alls-green-playwright: # This job does nothing and is only used for the branch protection if: always() needs: - test-playwright diff --git a/.github/workflows/test-backend.yml b/.github/workflows/test-backend.yml index 2a3cf6e308..dfce5f977b 100644 --- a/.github/workflows/test-backend.yml +++ b/.github/workflows/test-backend.yml @@ -12,6 +12,17 @@ jobs: test-backend: runs-on: ubuntu-latest timeout-minutes: 5 + concurrency: + group: api-sql-fixture + cancel-in-progress: false + env: + DATABASE_URL: ${{ secrets.API_TEST_DATABASE_URL }} + API_MIGRATION_DATABASE_URL: ${{ secrets.API_TEST_MIGRATION_DATABASE_URL }} + API_TEST_DATABASE_URL: ${{ secrets.API_TEST_DATABASE_URL }} + API_TEST_ADMIN_DATABASE_URL: ${{ secrets.API_TEST_ADMIN_DATABASE_URL }} + API_TEST_MIGRATION_DATABASE_URL: ${{ secrets.API_TEST_MIGRATION_DATABASE_URL }} + API_TEST_SUPABASE_BRANCH_REF: ${{ vars.API_TEST_SUPABASE_BRANCH_REF }} + API_TEST_ACTORS: ${{ vars.API_TEST_ACTORS }} steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -25,15 +36,24 @@ jobs: uses: astral-sh/setup-uv@07a047e608db84b3d8c06cd9a7c7dcc9c355c18e # v10.3.2 with: version: "latest-known" - - run: docker compose down -v --remove-orphans - - run: docker compose up -d --wait db mailpit + - name: Install locked backend environment + run: uv sync --locked + working-directory: backend + - name: Require isolated SQL fixture + run: | + : "${API_TEST_DATABASE_URL:?configure an isolated runtime fixture}" + : "${API_TEST_ADMIN_DATABASE_URL:?configure an isolated fixture writer}" + : "${API_TEST_MIGRATION_DATABASE_URL:?configure isolated migration authority}" + : "${API_TEST_ACTORS:?configure canonical synthetic fixture actors}" + - name: Verify actual isolated targets before migration + run: uv run --no-active --locked --no-sync python -m tests.test_data_namespace + working-directory: backend - name: Migrate DB - run: uv run bash scripts/prestart.sh + run: uv run --no-active --locked --no-sync bash scripts/prestart.sh working-directory: backend - name: Run tests - run: uv run bash scripts/tests-start.sh "Coverage for ${{ github.sha }}" + run: uv run --no-active --locked --no-sync bash scripts/tests-start.sh "Coverage for ${{ github.sha }}" working-directory: backend - - run: docker compose down -v --remove-orphans - name: Store coverage files uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: @@ -41,5 +61,5 @@ jobs: path: backend/htmlcov include-hidden-files: true - name: Coverage report - run: uv run coverage report --fail-under=90 + run: uv run --no-active --locked --no-sync coverage report --fail-under=90 working-directory: backend diff --git a/.github/workflows/test-docker-compose.yml b/.github/workflows/test-docker-compose.yml index 4551a15760..2ff46014e7 100644 --- a/.github/workflows/test-docker-compose.yml +++ b/.github/workflows/test-docker-compose.yml @@ -9,10 +9,18 @@ permissions: contents: read jobs: - test-docker-compose: runs-on: ubuntu-latest timeout-minutes: 10 + env: + # Public-config/UI smoke fixture only; SQL/RLS runs in Test Backend. + PROJECT_NAME: API container fixture + FRONTEND_HOST: http://localhost:8000 + WORKOS_CLIENT_ID: client_fixture + WORKOS_ISSUER: https://auth.fixture.test/ + WORKOS_JWKS_URL: https://auth.fixture.test/sso/jwks/client_fixture + WORKOS_API_HOSTNAME: auth.fixture.test + DATABASE_URL: postgresql+psycopg://fixture:fixture@localhost/api_test_unconfigured steps: - name: Checkout uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -20,10 +28,9 @@ jobs: persist-credentials: false - run: docker compose build - run: docker compose down -v --remove-orphans - - run: docker compose run --rm backend bash scripts/prestart.sh - - run: docker compose up -d --wait backend adminer - - name: Test backend is up - run: curl http://localhost:8000/api/v1/utils/health-check + - run: docker compose up -d --wait backend + - name: Test public configuration fixture + run: curl --fail http://localhost:8000/api/v1/auth/config - name: Test frontend is up run: curl http://localhost:8000 - run: docker compose down -v --remove-orphans diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index b5bc43cdab..13e0455ed5 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,5 +1,7 @@ -# See https://pre-commit.com for more information -# See https://pre-commit.com/hooks.html for more hooks +# Native prek contract: checks never synchronize dependencies or rewrite sources. +# Mutating vendor hooks have no check API and are deliberately manual-only. +# https://github.com/j178/prek/blob/b7eb6027125de7e3b67dd94039a4f69abf3a5fb0/docs/reference/cli.md +default_stages: [pre-commit] repos: - repo: https://github.com/pre-commit/pre-commit-hooks rev: 3e8a8703264a2f4a69428a0aa4dcb512790b2c8c # v6.0.0 @@ -10,12 +12,14 @@ repos: args: - --unsafe - id: end-of-file-fixer + stages: [manual] exclude: | - (?x)^( - frontend/src/client/.*| - backend/app/email-templates/.* - )$ + (?x)^( + frontend/src/client/.*| + backend/app/email-templates/.* + )$ - id: trailing-whitespace + stages: [manual] exclude: ^frontend/src/client/.* - repo: https://github.com/crate-ci/typos rev: 7f9d0819ca1c008ade73f4b41fa9d258d48f605b # frozen: v1.51.1 @@ -26,40 +30,43 @@ repos: hooks: - id: local-biome-check name: biome check - entry: npm run lint + entry: bun run --filter frontend check language: system types: [text] files: ^frontend/ + pass_filenames: false + require_serial: true - id: local-ruff-check name: ruff check - entry: uv run ruff check --force-exclude --fix --exit-non-zero-on-fix + entry: uv run --frozen --no-sync ruff check --force-exclude require_serial: true language: unsupported types: [python] - id: local-ruff-format name: ruff format - entry: uv run ruff format --force-exclude --exit-non-zero-on-format + entry: uv run --frozen --no-sync ruff format --force-exclude --check require_serial: true language: unsupported types_or: [python, markdown] - id: local-mypy name: mypy check - entry: uv run mypy backend/app + entry: uv run --frozen --no-sync --directory backend mypy app require_serial: true language: unsupported pass_filenames: false - id: local-ty name: ty check - entry: uv run ty check backend/app + entry: uv run --frozen --no-sync --directory backend ty check app require_serial: true language: unsupported pass_filenames: false - id: generate-frontend-sdk + stages: [manual] name: Generate Frontend SDK entry: bash ./scripts/generate-client.sh pass_filenames: false @@ -67,16 +74,17 @@ repos: files: ^backend/app/.*\.py$|^backend/pyproject\.toml$|^uv\.lock$|^frontend/openapi-ts\.config\.ts$|^scripts/generate-client\.sh$ - id: add-release-date + stages: [manual] language: unsupported name: add date to latest release header - entry: uv run python scripts/add_latest_release_date.py + entry: uv run --frozen --no-sync python scripts/add_latest_release_date.py files: ^release-notes\.md$ pass_filenames: false - id: zizmor name: zizmor - language: python - entry: uv run zizmor . + language: unsupported + entry: uv run --frozen --no-sync zizmor . files: ^\.github\/workflows\/ require_serial: true pass_filenames: false diff --git a/README.md b/README.md index ff783583f7..12ffe1c0af 100644 --- a/README.md +++ b/README.md @@ -19,9 +19,9 @@ - ☁️ [FastAPI Cloud](https://fastapicloud.com) for deployment. - 🐋 [Docker Compose](https://www.docker.com) for local services and self-hosted deployment. - 📞 [Traefik](https://traefik.io) as a reverse proxy with automatic HTTPS. -- 🔒 Secure password hashing by default. -- 🔑 JWT (JSON Web Token) authentication. -- 📫 Email-based password recovery. +- WorkOS AuthKit React for browser sessions and organization selection. +- Native PyJWT/JWKS resource-server verification with exact issuer/client binding. +- Canonical product identity crosswalks, tenant-scoped administration and PostgreSQL RLS. - ✉️ [React Email](https://react.email) for email templates. - 📬 [Mailpit](https://mailpit.axllent.org) for local email testing during development. - ✅ Tests with [Pytest](https://pytest.org). @@ -29,6 +29,9 @@ ### Dashboard Login +The screenshots below are historical template illustrations, not the current +WorkOS sign-in UI or evidence of a deployed authentication flow. + ![Dashboard login screenshot](img/login.png) ### Dashboard - Admin @@ -59,6 +62,14 @@ Click the **Use this template** button at the top of this page to create a new repository. +This branch requires an existing canonical product database and explicit WorkOS +application settings; it does not seed a global superuser or accept local +passwords. See [backend configuration and isolated tests](backend/README.md). +Production remains gated by recovery, schema/grant review, real provider settings +and tenant-conformance evidence. The manual deployment workflows select a +`production` environment, whose required reviewers/protection must be verified +through the GitHub owner before use; its name is not itself an approval. + ## Backend Development Backend docs: [backend/README.md](./backend/README.md). @@ -79,6 +90,56 @@ General development docs: [development.md](./development.md). This includes the local FastAPI and Vite workflow, Docker Compose services, `.env` configuration, and more. +### Native hook and branch admission + +This repository declares `.pre-commit-config.yaml` for **prek**, not Lefthook. +The estate's `install-git-hooks [install|validate]` owner +validates that versioned declaration before changing Git configuration. The +`validate` mode installs nothing. Linked worktrees retain private hooks and +installation failures restore their previous worktree-local `core.hooksPath`. +Setup and check-in bind a primary submodule or separate-metadata repository to +Git's actual checkout root when its private/common Git directories match; +the metadata directory reported by `worktree list` is not a checkout. + +Use the existing estate `api-sync` owner to provision this project's locked +Python workspace in the separate `.venv-api` environment. For native checks, +explicitly select that absolute path with `UV_PROJECT_ENVIRONMENT`; check-in +preserves it after direnv loading and checks the existing frozen profile +without resolution or synchronization. It never substitutes the estate's +Python environment or creates a checkout-local one. JavaScript dependencies +belong to the versioned `bun.lock`: use `bun install --frozen-lockfile`. + +From this checkout, run the check-only hook contract with: + +```console +prek run --config .pre-commit-config.yaml --all-files --hook-stage pre-commit +``` + +Biome, Ruff lint/format checks, mypy, ty, spelling and workflow checks do not +rewrite sources. EOF/trailing-whitespace fixers, SDK generation and release-date +updates are manual-only. Select one deliberately, for example: + +```console +prek run --config .pre-commit-config.yaml --all-files --hook-stage manual generate-frontend-sdk +``` + +Manual generation is **not** a freshness check: regenerate from the application's +own exporter, review the resulting client, and commit it before admission. +Neither `--dry-run` nor selecting the manual stage proves the generated files +are current. + +`git-branch-check-in` uses this native all-file contract rather than inherited +parent Mise checks. It requires a clean committed branch and the verified +mutation lease, refuses hook skip selectors, and refuses to publish/unlock if +checks fail, move HEAD or leave any tracked/untracked changes. New linked +project bootstrap remains blocked until its environment and direnv ownership +are separately admitted; setup does not copy environments or invent `.envrc`. +Protected CI/merge admission still needs the isolated fixture and explicitly +provisioned CI inputs; local hook success does not waive that boundary. + +Vendor contracts: [prek's pinned CLI reference](https://github.com/j178/prek/blob/b7eb6027125de7e3b67dd94039a4f69abf3a5fb0/docs/reference/cli.md) +and [the pinned whitespace hook manifest](https://github.com/pre-commit/pre-commit-hooks/blob/3e8a8703264a2f4a69428a0aa4dcb512790b2c8c/.pre-commit-hooks.yaml). + ## Release Notes Check the file [release-notes.md](./release-notes.md). diff --git a/backend/Dockerfile b/backend/Dockerfile index 401eb536a3..88f6aee7ad 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -7,7 +7,7 @@ COPY frontend/package.json /app/frontend/ WORKDIR /app/frontend -RUN bun install +RUN bun install --frozen-lockfile COPY ./frontend /app/frontend @@ -43,11 +43,11 @@ ENV PATH="/app/.venv/bin:$PATH" RUN --mount=type=cache,target=/root/.cache/uv \ --mount=type=bind,source=uv.lock,target=uv.lock \ --mount=type=bind,source=pyproject.toml,target=pyproject.toml \ - uv sync --frozen --no-install-workspace --package app + uv sync --frozen --no-dev --no-install-workspace --package app COPY ./backend/scripts /app/backend/scripts -COPY ./backend/pyproject.toml ./backend/alembic.ini /app/backend/ +COPY ./backend/pyproject.toml ./backend/alembic.ini ./backend/alembic-api.ini /app/backend/ COPY ./backend/app /app/backend/app @@ -58,7 +58,7 @@ COPY --from=frontend-build /app/backend/app/frontend /app/backend/app/frontend RUN --mount=type=cache,target=/root/.cache/uv \ --mount=type=bind,source=uv.lock,target=uv.lock \ --mount=type=bind,source=pyproject.toml,target=pyproject.toml \ - uv sync --frozen --package app + uv sync --frozen --no-dev --package app WORKDIR /app/backend/ diff --git a/backend/README.md b/backend/README.md index 96276b7a68..b67b72ea88 100644 --- a/backend/README.md +++ b/backend/README.md @@ -1,145 +1,170 @@ -# FastAPI Project - Backend - -## Requirements - -* [Docker](https://www.docker.com/). -* [uv](https://docs.astral.sh/uv/) for Python package and environment management. - -## Local Development - -Run the backend locally and connect it to PostgreSQL in Docker Compose. - -From the project root, start PostgreSQL and Mailpit: +# FastAPI backend + +## Runtime contract + +The browser uses WorkOS AuthKit React. The API verifies signed access tokens with +PyJWT's native JWKS client; it does not issue tokens, exchange OAuth codes, store +refresh tokens, or accept local passwords. Signup, password recovery, password +changes, private user provisioning and global-superuser authorization are retired. + +Configure these variables explicitly for the selected environment/application: + +| Variable | Required value | +| --- | --- | +| `PROJECT_NAME` | Application display name | +| `FRONTEND_HOST` | Exact browser origin/SDK redirect destination | +| `DATABASE_URL` | Existing canonical product database, dedicated non-superuser `NOBYPASSRLS` runtime login | +| `WORKOS_CLIENT_ID` | Approved application client ID | +| `WORKOS_ISSUER` | Exact trusted HTTPS issuer | +| `WORKOS_JWKS_URL` | Explicit trusted HTTPS signing-key endpoint | +| `WORKOS_API_HOSTNAME` | Authentication API hostname supplied to AuthKit React | + +`FASTAPI_ENV=development` allows local HTTP browser origins. Leave it unset in +production, which requires HTTPS and a custom Authentication API hostname. +Issuer, signing JWKS and browser API hostname are separately owner-configured; +the API does not infer one from another. Missing settings refuse startup. No +catalog/staging credential fallback exists. No WorkOS API key is needed by this +resource server. SMTP and Sentry settings remain optional non-auth utilities. + +Public `GET /api/v1/auth/config` returns only `client_id`, `api_hostname` and +`redirect_uri`. `GET /api/v1/users/me` returns the stable local UUID/profile, +canonical TEXT tenant ID, canonical identity UUID, and verified `user_role`, +`permissions`, `is_tenant_admin`. Neither endpoint exposes server credentials. + +## Identity and authorization + +The existing product owner maintains `public.tenants`, `identity_entity`, +`identity_external`, WorkOS projections and the private issuer/client cutover +gate. The API reflects their real metadata and never creates or copies them. +The verified WorkOS subject resolves through its provider-scoped canonical +crosswalk, the exact enabled issuer/client gate, the selected organization and +one active projected membership. Unknown, ambiguous or mismatched associations +deny access. Email equality is never an identity link or provisioning rule. +Local `User.id` remains a UUID; tenant IDs retain the canonical owner's TEXT type. + +Every business action requires `org:projects:read`/`org:projects:write` as +appropriate. Administrators are selected-tenant administrators, not global +operators. Ordinary users access their own items; tenant administrators can +access items in their selected tenant only. Account administration also requires +explicit action permission. Profile changes cannot mutate tenant/identity/role; +item changes cannot mutate tenant/owner attribution. + +A tenant administrator may create a local profile only for an existing, +same-tenant canonical user with an explicit WorkOS binding. This is not a WorkOS +invite, membership creation, role grant or reactivation. A profile for a revoked +member confers no access: authentication independently checks active membership. +Other users' private membership rows are not exposed for profile creation. + +Profile emails are unique within a tenant, not globally. PostgreSQL's +`uq_user_tenant_email` constraint is authoritative when RLS hides another profile +or concurrent writes race. Duplicate canonical profiles likewise return the +existing HTTP 409 conflict. These specific violations roll back; unrelated +constraint errors remain visible. Identical emails in different tenants remain +allowed. + +Profile writes flush and capture their public state inside the transaction, +then return it only after commit. They do not re-read a profile after its own +deactivation has revoked access; a successful deactivation response is not +turned into an ambiguous post-commit failure. + +`VerifiedSession` installs the fixed `authenticated` role and verified claims with +transaction-local PostgreSQL settings on every actual transaction, including +post-commit ORM reloads. Reserved `api_*` input claims are discarded. Canonical +resolution then adds `api_tenant_id`, `api_identity_entity_id`, and finally +`api_user_id` after the active local actor resolves. RLS owns the matching +bootstrap/read/write distinction. Commit, rollback and pool return cannot retain +a previous request's role or claims. + +## Native dependency and development commands + +From this upstream repository's root: ```console -$ docker compose up -d db mailpit +uv sync --locked --package app +uv run --package app --directory backend fastapi dev ``` -Then, from `./backend/`, install the dependencies, prepare the database, and start the development server: - -```console -$ uv sync -$ uv run bash scripts/prestart.sh -$ uv run fastapi dev -``` +An embedding workspace must set its declared external `UV_PROJECT_ENVIRONMENT` +(for example its API-owned environment) rather than using or modifying the +parent project's environment. Authentication settings must be supplied even for +OpenAPI generation; use explicit fixture settings for nonproduction generation. -The API is available at `http://localhost:8000`, with automatic interactive docs at `http://localhost:8000/docs`. +## API namespace migrations -## General Workflow +Only API-owned entities, policies and the Alembic ledger belong in schema `api`. +Canonical product schemas and cross-owner grants have separate owners. Do not +run the legacy public migration history, `SQLModel.metadata.create_all`, or any +initial/global-superuser seed against the product database. -Run backend commands from `./backend/` with `uv run`. Make sure your editor uses the Python interpreter at `.venv/bin/python` in the project root. - -Modify or add SQLModel models for data and SQL tables in `./backend/app/models.py`, API endpoints in `./backend/app/api/`, CRUD (Create, Read, Update, Delete) utils in `./backend/app/crud.py`. - -## VS Code - -There are already configurations in place to run the backend through the VS Code debugger, so that you can use breakpoints, pause and explore variables, etc. - -The setup is also already configured so you can run the tests through the VS Code Python tests tab. - -## Full Stack with Docker Compose - -To run the backend and built frontend in Docker Compose: +After native generation, review, isolation, recovery and grant gates, the exact +migration command from `backend/` is: ```console -$ docker compose run --rm backend bash scripts/prestart.sh -$ docker compose watch +uv run --no-active --locked --no-sync alembic -c alembic-api.ini upgrade api@head ``` -The application is available at `http://localhost:8000`. +The migration owner requires a separately supplied +`API_MIGRATION_DATABASE_URL`, distinct from the runtime login, an existing +owner-provisioned `api` schema, and an explicit reviewed API revision branch. +`backend/scripts/prestart.sh` invokes only that command, never a seed. It refuses +application when the reviewed branch or prerequisites are absent. Migration +credentials must not be injected into the long-lived backend process. -### Docker Compose Override +The narrowly scoped actor-status function uses PostgreSQL `SECURITY DEFINER` +with an empty search path and `row_security=off`. Its migration owner must have +native RLS-bypass authority; generation/application refuse insufficient or +incorrect function ownership. The runtime login never receives that authority. -The `compose.override.yml` file contains local settings for published ports, source synchronization, automatic image rebuilds, and backend reloads. Docker Compose applies it automatically when you run `docker compose` without an explicit file list. +Policy autogeneration uses Alembic's documented operation rewriter and the +vendor's SQL statements, preserving permission literals in immutable SQL +operations. Old-policy reflection shares the original repeatable-read snapshot; +runtime/application isolation is unchanged. Review both directions. Restoring +an older revision restores its historical policy semantics, not necessarily a +security-ready rollback target. -To open a shell in the backend container: +## Tests and evidence -```console -$ docker compose exec backend bash -``` - -## Backend Tests - -To test the backend from the `backend` directory, run: +Token/config/schema tests use explicit signed-token and transport fixtures, not +production credentials. From the upstream root: ```console -$ uv run bash scripts/test.sh -``` - -The tests run with Pytest. Modify existing tests or add new ones in `./backend/tests/`. - -If you use GitHub Actions, the tests will run automatically. - -### Test a Running Stack - -If your stack is already up and you just want to run the tests, you can use: - -```bash -docker compose exec backend bash scripts/tests-start.sh +uv run --no-active --locked --no-sync --package app --directory backend pytest tests/test_workos_security.py tests/test_data_namespace.py tests/api/routes/test_login.py tests/api/routes/test_private.py ``` -The `/app/backend/scripts/tests-start.sh` script calls `pytest`. If you need to pass extra arguments to `pytest`, you can pass them to that command and they will be forwarded. - -For example, to stop on first error: - -```bash -docker compose exec backend bash scripts/tests-start.sh -x -``` - -### Test Coverage - -When the tests run, they generate `htmlcov/index.html`. Open it in your browser to inspect the test coverage. - -## Migrations - -Make sure you create a revision of your models and upgrade the database with that revision every time you change them. From the `backend` directory, use `uv` to run Alembic against the PostgreSQL container: - -* Alembic is already configured to import your SQLModel models from `./backend/app/models.py`. - -* After changing a model (for example, adding a column), create a revision: - -```console -$ uv run alembic revision --autogenerate -m "Add column last_name to User model" -``` - -* Commit to the git repository the files generated in the alembic directory. - -* After creating the revision, run the migration in the database (this is what will actually change the database): - -```console -$ uv run alembic upgrade head -``` - -If you don't want to use migrations at all, uncomment the lines in the file at `./backend/app/core/db.py` that end in: - -```python -SQLModel.metadata.create_all(engine) -``` - -and comment the line in the file `scripts/prestart.sh` that contains: - -```console -$ alembic upgrade head -``` - -If you don't want to start with the default models and want to remove them / modify them, from the beginning, without having any previous revision, you can remove the revision files (`.py` Python files) under `./backend/app/alembic/versions/`. And then create a first migration as described above. - -## Email Templates - -The email templates are written with [React Email](https://react.email) in `./packages/react-email/`. The `emails` directory holds one component per email and the `ui` directory holds the shared components (layout, heading, button, link, callout). - -The rendered HTML in `./backend/app/email-templates/` is generated from those components. It is what the application sends and should not be edited by hand. - -To preview the emails while editing them, start the dev server from the root of the project: +SQL/route tests execute real PostgreSQL transactions and RLS. Provision the +approved isolated canonical baseline and reviewed API namespace before running +all tests. Required test inputs are: + +- `API_TEST_DATABASE_URL`: non-superuser `NOBYPASSRLS` runtime login. +- `API_TEST_ADMIN_DATABASE_URL`: isolated fixture writer, never production. +- `API_TEST_MIGRATION_DATABASE_URL`: isolated privileged migration authority. +- `API_TEST_ACTORS`: JSON object with `admin`, `member`, `foreign_admin`, + `unprofiled`, `revoked`; each existing canonical fixture actor supplies + `subject`, `organization_id`, `user_role`, `tenant_id` (TEXT), + `identity_entity_id` (UUID). Admin/member/unprofiled/revoked belong to the first + tenant, foreign_admin to a different tenant; revoked membership is inactive. +- The isolated database name starts `api_test_`, or an approved + `API_TEST_SUPABASE_BRANCH_REF` matches its connection target. Known production + and catalog-staging references are rejected even with a test-shaped database + name; the actual PostgreSQL database must match the selected URI. + +The isolated gate must trust `https://auth.fixture.test/` and `client_fixture`. +Tests create/clean only the named fixture actors' API-local profiles/items. They +never create schema, seed canonical identity, grant roles, or delete all data. +Missing infrastructure fails explicitly; it is not silently replaced by SQLite. ```console -$ bun run email:dev +uv run --no-active --locked --no-sync --package app --directory backend pytest ``` -Values coming from the backend are declared as Jinja placeholders in the component props, for example `username = "{{ username }}"`. The context for each email is built in `generate_*_email()` in `./backend/app/utils.py`, so a new placeholder needs to be added there too. - -Once you are done, regenerate the templates used by the application: - -```console -$ bun run email:export -``` +CI validates all three real targets before applying migrations. Route and RLS +cases share the same canonical actor input and claims producer, rather than +separate copied tenant/identity/claim settings. Docker/browser jobs are public +configuration/UI network-fixture checks, not SQL/RLS or real sign-in evidence. +Run workflow auditing, backend typing/lint, native client regeneration and browser +checks through their owners after all edits land. + +Production admission additionally requires recovery/restore evidence, approved +schema/grants, verified WorkOS domain/URLs, real sign-in/sign-out/external login, +and same/cross-tenant direct/gateway operations. Passing fixtures does not satisfy +those gates. See [deployment](../deployment.md). diff --git a/backend/alembic-api.ini b/backend/alembic-api.ini new file mode 100644 index 0000000000..3af45fb83d --- /dev/null +++ b/backend/alembic-api.ini @@ -0,0 +1,32 @@ +[alembic] +script_location = %(here)s/app/alembic +version_locations = %(here)s/app/alembic/api_versions +api_namespace = api +prepend_sys_path = %(here)s + +[loggers] +keys = root,sqlalchemy,alembic +[handlers] +keys = console +[formatters] +keys = generic +[logger_root] +level = WARN +handlers = console +qualname = +[logger_sqlalchemy] +level = WARN +handlers = +qualname = sqlalchemy.engine +[logger_alembic] +level = INFO +handlers = +qualname = alembic +[handler_console] +class = StreamHandler +args = (sys.stderr,) +level = NOTSET +formatter = generic +[formatter_generic] +format = %(levelname)-5.5s [%(name)s] %(message)s +datefmt = %H:%M:%S diff --git a/backend/app/alembic/api_versions/8f8f28c9c266_initialize_api_namespace.py b/backend/app/alembic/api_versions/8f8f28c9c266_initialize_api_namespace.py new file mode 100644 index 0000000000..d46c752484 --- /dev/null +++ b/backend/app/alembic/api_versions/8f8f28c9c266_initialize_api_namespace.py @@ -0,0 +1,64 @@ +"""initialize API namespace + +Revision ID: 8f8f28c9c266 +Revises: +Create Date: 2026-11-07 23:45:13.139198 + +""" +from alembic import op +import sqlalchemy as sa +import sqlmodel.sql.sqltypes + + +# revision identifiers, used by Alembic. +revision = '8f8f28c9c266' +down_revision = None +branch_labels = ('api',) +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.execute('GRANT USAGE ON SCHEMA api TO authenticated') + op.create_table('user', + sa.Column('email', sqlmodel.sql.sqltypes.AutoString(length=255), nullable=False), + sa.Column('is_active', sa.Boolean(), nullable=False), + sa.Column('full_name', sqlmodel.sql.sqltypes.AutoString(length=255), nullable=True), + sa.Column('id', sa.Uuid(), nullable=False), + sa.Column('tenant_id', sa.Text(), nullable=False), + sa.Column('identity_entity_id', sa.Uuid(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), + sa.ForeignKeyConstraint(['identity_entity_id'], ['public.identity_entity.id'], name='fk_user_identity_entity'), + sa.ForeignKeyConstraint(['tenant_id'], ['public.tenants.id'], name='fk_user_tenant'), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('id', 'tenant_id', name='uq_user_id_tenant'), + sa.UniqueConstraint('tenant_id', 'email', name='uq_user_tenant_email'), + sa.UniqueConstraint('tenant_id', 'identity_entity_id', name='uq_user_tenant_actor'), + schema='api' + ) + op.execute('ALTER TABLE api."user" ENABLE ROW LEVEL SECURITY , FORCE ROW LEVEL SECURITY ') + op.create_index(op.f('ix_api_user_tenant_id'), 'user', ['tenant_id'], unique=False, schema='api') + op.create_table('item', + sa.Column('title', sqlmodel.sql.sqltypes.AutoString(length=255), nullable=False), + sa.Column('description', sqlmodel.sql.sqltypes.AutoString(length=255), nullable=True), + sa.Column('id', sa.Uuid(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('owner_id', sa.Uuid(), nullable=False), + sa.Column('tenant_id', sa.Text(), nullable=False), + sa.ForeignKeyConstraint(['owner_id', 'tenant_id'], ['api.user.id', 'api.user.tenant_id'], name='fk_item_owner_tenant', ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id'), + schema='api' + ) + op.execute('ALTER TABLE api.item ENABLE ROW LEVEL SECURITY , FORCE ROW LEVEL SECURITY ') + op.create_index(op.f('ix_api_item_tenant_id'), 'item', ['tenant_id'], unique=False, schema='api') + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_index(op.f('ix_api_item_tenant_id'), table_name='item', schema='api') + op.drop_table('item', schema='api') + op.drop_index(op.f('ix_api_user_tenant_id'), table_name='user', schema='api') + op.drop_table('user', schema='api') + op.execute('REVOKE USAGE ON SCHEMA api FROM authenticated') + # ### end Alembic commands ### diff --git a/backend/app/alembic/api_versions/9cb88acf026a_enforce_api_tenant_security.py b/backend/app/alembic/api_versions/9cb88acf026a_enforce_api_tenant_security.py new file mode 100644 index 0000000000..1e83d27808 --- /dev/null +++ b/backend/app/alembic/api_versions/9cb88acf026a_enforce_api_tenant_security.py @@ -0,0 +1,71 @@ +"""enforce API tenant security + +Revision ID: 9cb88acf026a +Revises: 8f8f28c9c266 +Create Date: 2026-11-07 23:45:35.196628 + +""" +from alembic import op +import sqlalchemy as sa +import sqlmodel.sql.sqltypes + + +# revision identifiers, used by Alembic. +revision = '9cb88acf026a' +down_revision = '8f8f28c9c266' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.execute('CREATE FUNCTION "api"."current_actor_is_active"() RETURNS boolean LANGUAGE sql STABLE SECURITY DEFINER\n SET search_path = \'\' SET row_security = off AS $$\n SELECT EXISTS (\n SELECT 1 FROM api."user" AS actor\n WHERE actor.id::text = (SELECT auth.jwt()->>\'api_user_id\')\n AND actor.identity_entity_id::text = (SELECT auth.jwt()->>\'api_identity_entity_id\')\n AND actor.tenant_id = (SELECT auth.jwt()->>\'api_tenant_id\')\n AND actor.is_active\n )\n $$') + op.execute('REVOKE EXECUTE ON FUNCTION api.current_actor_is_active () FROM PUBLIC') + op.execute('GRANT EXECUTE ON FUNCTION api.current_actor_is_active () TO authenticated') + op.execute('CREATE POLICY item_select on api.item AS PERMISSIVE FOR SELECT TO authenticated USING ((\n (SELECT auth.jwt()->>\'role\') = \'authenticated\'\n AND api.item.tenant_id = (SELECT auth.jwt()->>\'api_tenant_id\')\n AND (SELECT public.is_workos_token_bound())\n AND (SELECT public.has_active_workos_membership())\n AND EXISTS (\n SELECT 1 FROM public.tenants AS t\n WHERE t.id = api.item.tenant_id\n AND t.workos_org_id = (SELECT public.current_workos_org_id())\n )\n AND 1 = (\n SELECT count(*) FROM public.identity_external AS x\n JOIN public.identity_entity AS e ON e.id = x.entity_id\n WHERE x.provider = \'workos\'\n AND x.external_id = (SELECT auth.jwt()->>\'sub\')\n AND e.kind = \'user\' AND e.tenant_id = api.item.tenant_id\n AND e.id::text = (SELECT auth.jwt()->>\'api_identity_entity_id\')\n )\n) AND (SELECT NULLIF(auth.jwt()->>\'api_user_id\', \'\')) IS NOT NULL AND (owner_id::text = (SELECT auth.jwt()->>\'api_user_id\') OR (SELECT public.current_workos_user_role()) = \'admin\') AND (EXISTS (\n SELECT 1 FROM api."user" AS actor\n WHERE actor.id::text = (SELECT auth.jwt()->>\'api_user_id\')\n AND actor.identity_entity_id::text = (SELECT auth.jwt()->>\'api_identity_entity_id\')\n AND actor.tenant_id = api.item.tenant_id AND actor.is_active\n)) AND ((SELECT public.has_workos_permission(\'org\\:projects\\:read\')) OR (SELECT public.has_workos_permission(\'org\\:projects\\:write\'))))') + op.execute('CREATE POLICY item_insert on api.item AS PERMISSIVE FOR INSERT TO authenticated WITH CHECK ((\n (SELECT auth.jwt()->>\'role\') = \'authenticated\'\n AND api.item.tenant_id = (SELECT auth.jwt()->>\'api_tenant_id\')\n AND (SELECT public.is_workos_token_bound())\n AND (SELECT public.has_active_workos_membership())\n AND EXISTS (\n SELECT 1 FROM public.tenants AS t\n WHERE t.id = api.item.tenant_id\n AND t.workos_org_id = (SELECT public.current_workos_org_id())\n )\n AND 1 = (\n SELECT count(*) FROM public.identity_external AS x\n JOIN public.identity_entity AS e ON e.id = x.entity_id\n WHERE x.provider = \'workos\'\n AND x.external_id = (SELECT auth.jwt()->>\'sub\')\n AND e.kind = \'user\' AND e.tenant_id = api.item.tenant_id\n AND e.id::text = (SELECT auth.jwt()->>\'api_identity_entity_id\')\n )\n) AND (SELECT NULLIF(auth.jwt()->>\'api_user_id\', \'\')) IS NOT NULL AND (owner_id::text = (SELECT auth.jwt()->>\'api_user_id\') OR (SELECT public.current_workos_user_role()) = \'admin\') AND (EXISTS (\n SELECT 1 FROM api."user" AS actor\n WHERE actor.id::text = (SELECT auth.jwt()->>\'api_user_id\')\n AND actor.identity_entity_id::text = (SELECT auth.jwt()->>\'api_identity_entity_id\')\n AND actor.tenant_id = api.item.tenant_id AND actor.is_active\n)) AND (SELECT public.has_workos_permission(\'org\\:projects\\:write\')) AND owner_id::text = (SELECT auth.jwt()->>\'api_user_id\'))') + op.execute('CREATE POLICY item_update on api.item AS PERMISSIVE FOR UPDATE TO authenticated USING ((\n (SELECT auth.jwt()->>\'role\') = \'authenticated\'\n AND api.item.tenant_id = (SELECT auth.jwt()->>\'api_tenant_id\')\n AND (SELECT public.is_workos_token_bound())\n AND (SELECT public.has_active_workos_membership())\n AND EXISTS (\n SELECT 1 FROM public.tenants AS t\n WHERE t.id = api.item.tenant_id\n AND t.workos_org_id = (SELECT public.current_workos_org_id())\n )\n AND 1 = (\n SELECT count(*) FROM public.identity_external AS x\n JOIN public.identity_entity AS e ON e.id = x.entity_id\n WHERE x.provider = \'workos\'\n AND x.external_id = (SELECT auth.jwt()->>\'sub\')\n AND e.kind = \'user\' AND e.tenant_id = api.item.tenant_id\n AND e.id::text = (SELECT auth.jwt()->>\'api_identity_entity_id\')\n )\n) AND (SELECT NULLIF(auth.jwt()->>\'api_user_id\', \'\')) IS NOT NULL AND (owner_id::text = (SELECT auth.jwt()->>\'api_user_id\') OR (SELECT public.current_workos_user_role()) = \'admin\') AND (EXISTS (\n SELECT 1 FROM api."user" AS actor\n WHERE actor.id::text = (SELECT auth.jwt()->>\'api_user_id\')\n AND actor.identity_entity_id::text = (SELECT auth.jwt()->>\'api_identity_entity_id\')\n AND actor.tenant_id = api.item.tenant_id AND actor.is_active\n)) AND (SELECT public.has_workos_permission(\'org\\:projects\\:write\'))) WITH CHECK ((\n (SELECT auth.jwt()->>\'role\') = \'authenticated\'\n AND api.item.tenant_id = (SELECT auth.jwt()->>\'api_tenant_id\')\n AND (SELECT public.is_workos_token_bound())\n AND (SELECT public.has_active_workos_membership())\n AND EXISTS (\n SELECT 1 FROM public.tenants AS t\n WHERE t.id = api.item.tenant_id\n AND t.workos_org_id = (SELECT public.current_workos_org_id())\n )\n AND 1 = (\n SELECT count(*) FROM public.identity_external AS x\n JOIN public.identity_entity AS e ON e.id = x.entity_id\n WHERE x.provider = \'workos\'\n AND x.external_id = (SELECT auth.jwt()->>\'sub\')\n AND e.kind = \'user\' AND e.tenant_id = api.item.tenant_id\n AND e.id::text = (SELECT auth.jwt()->>\'api_identity_entity_id\')\n )\n) AND (SELECT NULLIF(auth.jwt()->>\'api_user_id\', \'\')) IS NOT NULL AND (owner_id::text = (SELECT auth.jwt()->>\'api_user_id\') OR (SELECT public.current_workos_user_role()) = \'admin\') AND (EXISTS (\n SELECT 1 FROM api."user" AS actor\n WHERE actor.id::text = (SELECT auth.jwt()->>\'api_user_id\')\n AND actor.identity_entity_id::text = (SELECT auth.jwt()->>\'api_identity_entity_id\')\n AND actor.tenant_id = api.item.tenant_id AND actor.is_active\n)) AND (SELECT public.has_workos_permission(\'org\\:projects\\:write\')))') + op.execute('CREATE POLICY item_delete on api.item AS PERMISSIVE FOR DELETE TO authenticated USING ((\n (SELECT auth.jwt()->>\'role\') = \'authenticated\'\n AND api.item.tenant_id = (SELECT auth.jwt()->>\'api_tenant_id\')\n AND (SELECT public.is_workos_token_bound())\n AND (SELECT public.has_active_workos_membership())\n AND EXISTS (\n SELECT 1 FROM public.tenants AS t\n WHERE t.id = api.item.tenant_id\n AND t.workos_org_id = (SELECT public.current_workos_org_id())\n )\n AND 1 = (\n SELECT count(*) FROM public.identity_external AS x\n JOIN public.identity_entity AS e ON e.id = x.entity_id\n WHERE x.provider = \'workos\'\n AND x.external_id = (SELECT auth.jwt()->>\'sub\')\n AND e.kind = \'user\' AND e.tenant_id = api.item.tenant_id\n AND e.id::text = (SELECT auth.jwt()->>\'api_identity_entity_id\')\n )\n) AND (SELECT NULLIF(auth.jwt()->>\'api_user_id\', \'\')) IS NOT NULL AND (owner_id::text = (SELECT auth.jwt()->>\'api_user_id\') OR (SELECT public.current_workos_user_role()) = \'admin\') AND (EXISTS (\n SELECT 1 FROM api."user" AS actor\n WHERE actor.id::text = (SELECT auth.jwt()->>\'api_user_id\')\n AND actor.identity_entity_id::text = (SELECT auth.jwt()->>\'api_identity_entity_id\')\n AND actor.tenant_id = api.item.tenant_id AND actor.is_active\n)) AND (SELECT public.has_workos_permission(\'org\\:projects\\:write\')))') + op.execute('GRANT SELECT ( created_at, email, full_name, id, identity_entity_id, is_active, tenant_id ) ON "api"."user" TO "authenticated" ') + op.execute('GRANT DELETE ON "api"."user" TO "authenticated" ') + op.execute('GRANT INSERT ( created_at, email, full_name, id, identity_entity_id, is_active, tenant_id ) ON "api"."user" TO "authenticated" ') + op.execute('GRANT UPDATE ( email, full_name, is_active ) ON "api"."user" TO "authenticated" ') + op.execute('GRANT SELECT ( created_at, description, id, owner_id, tenant_id, title ) ON "api"."item" TO "authenticated" ') + op.execute('GRANT DELETE ON "api"."item" TO "authenticated" ') + op.execute('GRANT INSERT ( created_at, description, id, owner_id, tenant_id, title ) ON "api"."item" TO "authenticated" ') + op.execute('GRANT UPDATE ( description, title ) ON "api"."item" TO "authenticated" ') + op.execute('CREATE FUNCTION "api"."protect_user_attribution"() RETURNS trigger LANGUAGE plpgsql SECURITY INVOKER SET search_path = \'\' AS $$\n BEGIN\n IF ROW(OLD.id, OLD.tenant_id, OLD.identity_entity_id, OLD.created_at) IS DISTINCT FROM ROW(NEW.id, NEW.tenant_id, NEW.identity_entity_id, NEW.created_at) THEN\n RAISE EXCEPTION \'API attribution is immutable\' USING ERRCODE = \'42501\';\n END IF;\n RETURN NEW;\n END;\n $$') + op.execute('CREATE FUNCTION "api"."protect_item_attribution"() RETURNS trigger LANGUAGE plpgsql SECURITY INVOKER SET search_path = \'\' AS $$\n BEGIN\n IF ROW(OLD.id, OLD.tenant_id, OLD.owner_id, OLD.created_at) IS DISTINCT FROM ROW(NEW.id, NEW.tenant_id, NEW.owner_id, NEW.created_at) THEN\n RAISE EXCEPTION \'API attribution is immutable\' USING ERRCODE = \'42501\';\n END IF;\n RETURN NEW;\n END;\n $$') + op.execute('CREATE POLICY user_select on api.user AS PERMISSIVE FOR SELECT TO authenticated USING ((\n (SELECT auth.jwt()->>\'role\') = \'authenticated\'\n AND api."user".tenant_id = (SELECT auth.jwt()->>\'api_tenant_id\')\n AND (SELECT public.is_workos_token_bound())\n AND (SELECT public.has_active_workos_membership())\n AND EXISTS (\n SELECT 1 FROM public.tenants AS t\n WHERE t.id = api."user".tenant_id\n AND t.workos_org_id = (SELECT public.current_workos_org_id())\n )\n AND 1 = (\n SELECT count(*) FROM public.identity_external AS x\n JOIN public.identity_entity AS e ON e.id = x.entity_id\n WHERE x.provider = \'workos\'\n AND x.external_id = (SELECT auth.jwt()->>\'sub\')\n AND e.kind = \'user\' AND e.tenant_id = api."user".tenant_id\n AND e.id::text = (SELECT auth.jwt()->>\'api_identity_entity_id\')\n )\n) AND (EXISTS (\n SELECT 1 FROM public.identity_entity AS target\n JOIN public.identity_external AS target_external\n ON target_external.entity_id = target.id AND target_external.provider = \'workos\'\n WHERE target.id = api."user".identity_entity_id AND target.kind = \'user\'\n AND target.tenant_id = api."user".tenant_id\n)) AND ((identity_entity_id::text = (SELECT auth.jwt()->>\'api_identity_entity_id\') AND is_active) OR ((SELECT NULLIF(auth.jwt()->>\'api_user_id\', \'\')) IS NOT NULL AND (SELECT api.current_actor_is_active()) AND (SELECT public.current_workos_user_role()) = \'admin\' AND ((SELECT public.has_workos_permission(\'org\\:projects\\:read\')) OR (SELECT public.has_workos_permission(\'org\\:projects\\:write\'))))))') + op.execute('CREATE POLICY user_insert on api.user AS PERMISSIVE FOR INSERT TO authenticated WITH CHECK ((\n (SELECT auth.jwt()->>\'role\') = \'authenticated\'\n AND api."user".tenant_id = (SELECT auth.jwt()->>\'api_tenant_id\')\n AND (SELECT public.is_workos_token_bound())\n AND (SELECT public.has_active_workos_membership())\n AND EXISTS (\n SELECT 1 FROM public.tenants AS t\n WHERE t.id = api."user".tenant_id\n AND t.workos_org_id = (SELECT public.current_workos_org_id())\n )\n AND 1 = (\n SELECT count(*) FROM public.identity_external AS x\n JOIN public.identity_entity AS e ON e.id = x.entity_id\n WHERE x.provider = \'workos\'\n AND x.external_id = (SELECT auth.jwt()->>\'sub\')\n AND e.kind = \'user\' AND e.tenant_id = api."user".tenant_id\n AND e.id::text = (SELECT auth.jwt()->>\'api_identity_entity_id\')\n )\n) AND (EXISTS (\n SELECT 1 FROM public.identity_entity AS target\n JOIN public.identity_external AS target_external\n ON target_external.entity_id = target.id AND target_external.provider = \'workos\'\n WHERE target.id = api."user".identity_entity_id AND target.kind = \'user\'\n AND target.tenant_id = api."user".tenant_id\n)) AND (SELECT NULLIF(auth.jwt()->>\'api_user_id\', \'\')) IS NOT NULL AND (SELECT api.current_actor_is_active()) AND (SELECT public.current_workos_user_role()) = \'admin\' AND (SELECT public.has_workos_permission(\'org\\:projects\\:write\')))') + op.execute('CREATE POLICY user_update on api.user AS PERMISSIVE FOR UPDATE TO authenticated USING ((\n (SELECT auth.jwt()->>\'role\') = \'authenticated\'\n AND api."user".tenant_id = (SELECT auth.jwt()->>\'api_tenant_id\')\n AND (SELECT public.is_workos_token_bound())\n AND (SELECT public.has_active_workos_membership())\n AND EXISTS (\n SELECT 1 FROM public.tenants AS t\n WHERE t.id = api."user".tenant_id\n AND t.workos_org_id = (SELECT public.current_workos_org_id())\n )\n AND 1 = (\n SELECT count(*) FROM public.identity_external AS x\n JOIN public.identity_entity AS e ON e.id = x.entity_id\n WHERE x.provider = \'workos\'\n AND x.external_id = (SELECT auth.jwt()->>\'sub\')\n AND e.kind = \'user\' AND e.tenant_id = api."user".tenant_id\n AND e.id::text = (SELECT auth.jwt()->>\'api_identity_entity_id\')\n )\n) AND (EXISTS (\n SELECT 1 FROM public.identity_entity AS target\n JOIN public.identity_external AS target_external\n ON target_external.entity_id = target.id AND target_external.provider = \'workos\'\n WHERE target.id = api."user".identity_entity_id AND target.kind = \'user\'\n AND target.tenant_id = api."user".tenant_id\n)) AND (SELECT NULLIF(auth.jwt()->>\'api_user_id\', \'\')) IS NOT NULL AND (SELECT api.current_actor_is_active()) AND (SELECT public.has_workos_permission(\'org\\:projects\\:write\')) AND (identity_entity_id::text = (SELECT auth.jwt()->>\'api_identity_entity_id\') OR (SELECT public.current_workos_user_role()) = \'admin\')) WITH CHECK ((\n (SELECT auth.jwt()->>\'role\') = \'authenticated\'\n AND api."user".tenant_id = (SELECT auth.jwt()->>\'api_tenant_id\')\n AND (SELECT public.is_workos_token_bound())\n AND (SELECT public.has_active_workos_membership())\n AND EXISTS (\n SELECT 1 FROM public.tenants AS t\n WHERE t.id = api."user".tenant_id\n AND t.workos_org_id = (SELECT public.current_workos_org_id())\n )\n AND 1 = (\n SELECT count(*) FROM public.identity_external AS x\n JOIN public.identity_entity AS e ON e.id = x.entity_id\n WHERE x.provider = \'workos\'\n AND x.external_id = (SELECT auth.jwt()->>\'sub\')\n AND e.kind = \'user\' AND e.tenant_id = api."user".tenant_id\n AND e.id::text = (SELECT auth.jwt()->>\'api_identity_entity_id\')\n )\n) AND (EXISTS (\n SELECT 1 FROM public.identity_entity AS target\n JOIN public.identity_external AS target_external\n ON target_external.entity_id = target.id AND target_external.provider = \'workos\'\n WHERE target.id = api."user".identity_entity_id AND target.kind = \'user\'\n AND target.tenant_id = api."user".tenant_id\n)) AND (SELECT NULLIF(auth.jwt()->>\'api_user_id\', \'\')) IS NOT NULL AND (SELECT api.current_actor_is_active()) AND (SELECT public.has_workos_permission(\'org\\:projects\\:write\')) AND (identity_entity_id::text = (SELECT auth.jwt()->>\'api_identity_entity_id\') OR (SELECT public.current_workos_user_role()) = \'admin\'))') + op.execute('CREATE POLICY user_delete on api.user AS PERMISSIVE FOR DELETE TO authenticated USING ((\n (SELECT auth.jwt()->>\'role\') = \'authenticated\'\n AND api."user".tenant_id = (SELECT auth.jwt()->>\'api_tenant_id\')\n AND (SELECT public.is_workos_token_bound())\n AND (SELECT public.has_active_workos_membership())\n AND EXISTS (\n SELECT 1 FROM public.tenants AS t\n WHERE t.id = api."user".tenant_id\n AND t.workos_org_id = (SELECT public.current_workos_org_id())\n )\n AND 1 = (\n SELECT count(*) FROM public.identity_external AS x\n JOIN public.identity_entity AS e ON e.id = x.entity_id\n WHERE x.provider = \'workos\'\n AND x.external_id = (SELECT auth.jwt()->>\'sub\')\n AND e.kind = \'user\' AND e.tenant_id = api."user".tenant_id\n AND e.id::text = (SELECT auth.jwt()->>\'api_identity_entity_id\')\n )\n) AND (EXISTS (\n SELECT 1 FROM public.identity_entity AS target\n JOIN public.identity_external AS target_external\n ON target_external.entity_id = target.id AND target_external.provider = \'workos\'\n WHERE target.id = api."user".identity_entity_id AND target.kind = \'user\'\n AND target.tenant_id = api."user".tenant_id\n)) AND (SELECT NULLIF(auth.jwt()->>\'api_user_id\', \'\')) IS NOT NULL AND (SELECT api.current_actor_is_active()) AND (SELECT public.has_workos_permission(\'org\\:projects\\:write\')) AND (identity_entity_id::text = (SELECT auth.jwt()->>\'api_identity_entity_id\') OR (SELECT public.current_workos_user_role()) = \'admin\'))') + op.execute('CREATE TRIGGER "protect_user_attribution" BEFORE UPDATE ON api."user" FOR EACH ROW EXECUTE FUNCTION api.protect_user_attribution()') + op.execute('CREATE TRIGGER "protect_item_attribution" BEFORE UPDATE ON api."item" FOR EACH ROW EXECUTE FUNCTION api.protect_item_attribution()') + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.execute('DROP TRIGGER "protect_item_attribution" ON api.item ') + op.execute('DROP TRIGGER "protect_user_attribution" ON api.user ') + op.execute('DROP POLICY user_delete on api.user ') + op.execute('DROP POLICY user_update on api.user ') + op.execute('DROP POLICY user_insert on api.user ') + op.execute('DROP POLICY user_select on api.user ') + op.execute('DROP FUNCTION "api"."protect_item_attribution"() ') + op.execute('DROP FUNCTION "api"."protect_user_attribution"() ') + op.execute('REVOKE UPDATE ON "api"."item" FROM "authenticated"') + op.execute('REVOKE INSERT ON "api"."item" FROM "authenticated"') + op.execute('REVOKE DELETE ON "api"."item" FROM "authenticated"') + op.execute('REVOKE SELECT ON "api"."item" FROM "authenticated"') + op.execute('REVOKE UPDATE ON "api"."user" FROM "authenticated"') + op.execute('REVOKE INSERT ON "api"."user" FROM "authenticated"') + op.execute('REVOKE DELETE ON "api"."user" FROM "authenticated"') + op.execute('REVOKE SELECT ON "api"."user" FROM "authenticated"') + op.execute('DROP POLICY item_delete on api.item ') + op.execute('DROP POLICY item_update on api.item ') + op.execute('DROP POLICY item_insert on api.item ') + op.execute('DROP POLICY item_select on api.item ') + op.execute('DROP FUNCTION "api"."current_actor_is_active"() ') + # ### end Alembic commands ### diff --git a/backend/app/alembic/env.py b/backend/app/alembic/env.py index 919eebf5de..2f30dfe366 100755 --- a/backend/app/alembic/env.py +++ b/backend/app/alembic/env.py @@ -1,86 +1,158 @@ +"""API-only migration ledger; legacy public revisions are historical, not deployable.""" import os +from contextlib import contextmanager from logging.config import fileConfig +from pathlib import Path from alembic import context -from sqlalchemy import engine_from_config, pool +from alembic.script import ScriptDirectory +from alembic_utils.replaceable_entity import register_entities +from sqlalchemy import engine_from_config, pool, text +from sqlalchemy.engine import make_url -# this is the Alembic Config object, which provides -# access to the values within the .ini file in use. -config = context.config - -# Interpret the config file for Python logging. -# This line sets up loggers basically. -assert config.config_file_name is not None -fileConfig(config.config_file_name) - -# add your model's MetaData object here -# for 'autogenerate' support -# from myapp import mymodel -# target_metadata = mymodel.Base.metadata -# target_metadata = None +from app.alembic.native_security import process_revision_directives +from app.alembic.security import entities +from app.models import SQLModel -from app.models import SQLModel # noqa -from app.core.config import settings # noqa +config = context.config +if config.config_file_name: + fileConfig(config.config_file_name) +API_SCHEMA = "api" target_metadata = SQLModel.metadata - -# other values from the config, defined by the needs of env.py, -# can be acquired: -# my_important_option = config.get_main_option("my_important_option") -# ... etc. - - -def get_url(): - return str(settings.DATABASE_URL) - - -def run_migrations_offline(): - """Run migrations in 'offline' mode. - - This configures the context with just a URL - and not an Engine, though an Engine is acceptable - here as well. By skipping the Engine creation - we don't even need a DBAPI to be available. - - Calls to context.execute() here emit the given string to the - script output. - - """ - url = get_url() - context.configure( - url=url, target_metadata=target_metadata, literal_binds=True, compare_type=True - ) - - with context.begin_transaction(): - context.run_migrations() +BOOTSTRAP_TABLES = context.get_x_argument(as_dictionary=True).get("api_bootstrap") == "tables" +register_entities([] if BOOTSTRAP_TABLES else entities) + + +def include_name(name, type_, parent_names): + if type_ == "schema": + return name == API_SCHEMA + return parent_names.get("schema_name") == API_SCHEMA + + +def include_object(object_, name, type_, reflected, compare_to): + if BOOTSTRAP_TABLES and type_ not in { + "table", "column", "index", "unique_constraint", "foreign_key_constraint", "check_constraint", + }: + return False + if type_ == "grant_table" and getattr(object_, "role", None) != "authenticated": + return False + if type_ == "table": + return object_.schema == API_SCHEMA + table = getattr(object_, "table", None) + if table is not None and hasattr(table, "schema"): + return table.schema == API_SCHEMA + return getattr(object_, "schema", None) == API_SCHEMA + + +def migration_url(): + value = os.environ.get("API_MIGRATION_DATABASE_URL") + if not value: + raise RuntimeError("API_MIGRATION_DATABASE_URL must explicitly select the isolated/reviewed migration authority") + url = make_url(value) + if url.get_backend_name() != "postgresql": + raise RuntimeError("API migrations require PostgreSQL, never a substitute database") + runtime = os.environ.get("DATABASE_URL") + if runtime and make_url(runtime).username == url.username: + raise RuntimeError("API migration and runtime users must be distinct") + return value + + +def validate_ledger(): + expected = Path(__file__).parent / "api_versions" + locations = ScriptDirectory.from_config(config).version_locations + if config.get_main_option("api_namespace") != API_SCHEMA or not locations: + raise RuntimeError("Legacy migration replay is disabled; use alembic -c alembic-api.ini") + if len(locations) != 1 or Path(locations[0]).resolve() != expected.resolve(): + raise RuntimeError("Only the API-owned revision directory may be loaded") + script = ScriptDirectory.from_config(config) + revisions = list(script.walk_revisions()) + command = getattr(config.cmd_opts, "cmd", None) + command_name = getattr(command[0], "__name__", "") if command else "" + if not revisions and command_name != "revision": + raise RuntimeError("No reviewed API revision exists; generation is required before application") + for revision in revisions: + if "api" not in revision.branch_labels: + raise RuntimeError("All deployable revisions must belong to the explicit api branch") + + +@contextmanager +def scoped_migration_connection(connectable): + with connectable.connect() as connection: + original_search_path = connection.scalar(text("SHOW search_path")) + connection.rollback() + try: + # Explicit remote-schema reflection must not depend on PUBLIC visibility. + connection.execute(text("SELECT set_config('search_path', 'pg_catalog', false)")) + connection.commit() + yield connection + finally: + connection.rollback() + connection.execute( + text("SELECT set_config('search_path', :value, false)"), + {"value": original_search_path}, + ) + connection.commit() + + +def autogeneration_requested(): + command = getattr(config.cmd_opts, "cmd", None) + command_name = getattr(command[0], "__name__", "") if command else "" + return bool(getattr(config.cmd_opts, "autogenerate", False)) or command_name == "check" def run_migrations_online(): - """Run migrations in 'online' mode. - - In this scenario we need to create an Engine - and associate a connection with the context. - - """ + validate_ledger() configuration = config.get_section(config.config_ini_section) assert configuration is not None - configuration["sqlalchemy.url"] = get_url() + configuration["sqlalchemy.url"] = migration_url() + autogenerating = autogeneration_requested() + isolation = {"isolation_level": "REPEATABLE READ"} if autogenerating else {} connectable = engine_from_config( - configuration, - prefix="sqlalchemy.", - poolclass=pool.NullPool, + configuration, prefix="sqlalchemy.", poolclass=pool.NullPool, **isolation, ) - - with connectable.connect() as connection: + with scoped_migration_connection(connectable) as connection: + if not connection.scalar(text("SELECT EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = 'api')")): + raise RuntimeError("The reviewed native schema owner must provision api before generation/application") + if not connection.scalar(text( + "SELECT rolsuper OR rolbypassrls FROM pg_roles WHERE rolname = current_user" + )): + raise RuntimeError("API live-actor helper requires a separate privileged migration owner; runtime authority is forbidden") + helper_owner_can_bypass = connection.scalar(text( + "SELECT p.prosecdef AND (r.rolsuper OR r.rolbypassrls) " + "FROM pg_proc AS p JOIN pg_namespace AS n ON n.oid=p.pronamespace " + "JOIN pg_roles AS r ON r.oid=p.proowner " + "WHERE n.nspname='api' AND p.proname='current_actor_is_active' AND p.pronargs=0" + )) + if helper_owner_can_bypass is False: + raise RuntimeError("Existing API live-actor helper must retain a verified privileged migration owner") + # A migration identity owns only api. Runtime role authority is checked by + # the request-session owner, never inferred from migration credentials. + # Close the read-only preflight's implicit transaction before Alembic + # starts its own transactional DDL boundary. + connection.rollback() context.configure( - connection=connection, target_metadata=target_metadata, compare_type=True + connection=connection, + target_metadata=target_metadata, + include_schemas=True, + include_name=include_name, + include_object=include_object, + version_table_schema=API_SCHEMA, + version_table="alembic_version", + compare_type=True, + compare_server_default=True, + process_revision_directives=process_revision_directives, ) - with context.begin_transaction(): + if autogenerating: + # Every vendor comparison and downgrade reflection shares this + # native snapshot; apply/runtime transactions keep their defaults. + context.get_context().opts["api_autogen_snapshot"] = connection.scalar( + text("SELECT pg_current_snapshot()::text") + ) context.run_migrations() if context.is_offline_mode(): - run_migrations_offline() -else: - run_migrations_online() + raise RuntimeError("Offline migration emission is disabled: native PostgreSQL ownership preflight is required") +run_migrations_online() diff --git a/backend/app/alembic/native_security.py b/backend/app/alembic/native_security.py new file mode 100644 index 0000000000..0ed1672fa4 --- /dev/null +++ b/backend/app/alembic/native_security.py @@ -0,0 +1,142 @@ +"""Native PostgreSQL AST generation for grammar absent from alembic-utils. + +Alembic owns revision emission; pglast owns PostgreSQL syntax rendering. This +hook adds API schema usage, ENABLE/FORCE RLS and restricted helper execution. +Policies, table/column grants and immutable-attribution triggers use alembic-utils. +""" +from alembic.autogenerate import rewriter +from alembic.operations import ops +from alembic_utils.pg_function import PGFunction +from alembic_utils.replaceable_entity import ReplaceableEntity +from alembic_utils.reversible_op import CreateOp, DropOp, ReplaceOp, RevertOp +from pglast import ast +from pglast.stream import RawStream +from sqlalchemy import text +from sqlalchemy.orm import Session +from sqlalchemy.sql.elements import TextClause + + +def schema_usage(is_grant: bool) -> str: + return RawStream()(ast.GrantStmt( + is_grant=is_grant, + targtype="ACL_TARGET_OBJECT", + objtype="OBJECT_SCHEMA", + objects=(ast.String(sval="api"),), + privileges=(ast.AccessPriv(priv_name="USAGE"),), + grantees=(ast.RoleSpec(roletype="ROLESPEC_CSTRING", rolename="authenticated"),), + grant_option=False, + behavior="DROP_RESTRICT", + )) + + +def table_rls(table: str) -> str: + return RawStream()(ast.AlterTableStmt( + relation=ast.RangeVar(schemaname="api", relname=table, inh=True, relpersistence="p"), + cmds=( + ast.AlterTableCmd(subtype="AT_EnableRowSecurity", behavior="DROP_RESTRICT", missing_ok=False), + ast.AlterTableCmd(subtype="AT_ForceRowSecurity", behavior="DROP_RESTRICT", missing_ok=False), + ), + objtype="OBJECT_TABLE", + missing_ok=False, + )) + + +def actor_helper_execute(is_grant: bool, public: bool) -> str: + role = ast.RoleSpec(roletype="ROLESPEC_PUBLIC") if public else ast.RoleSpec( + roletype="ROLESPEC_CSTRING", rolename="authenticated", + ) + return RawStream()(ast.GrantStmt( + is_grant=is_grant, + targtype="ACL_TARGET_OBJECT", + objtype="OBJECT_FUNCTION", + objects=(ast.ObjectWithArgs( + objname=(ast.String(sval="api"), ast.String(sval="current_actor_is_active")), + objargs=(), args_unspecified=False, + ),), + privileges=(ast.AccessPriv(priv_name="EXECUTE"),), + grantees=(role,), + grant_option=False, + behavior="DROP_RESTRICT", + )) + + +entity_writer = rewriter.Rewriter() + + +@entity_writer.rewrites(CreateOp) +@entity_writer.rewrites(DropOp) +@entity_writer.rewrites(ReplaceOp) +@entity_writer.rewrites(RevertOp) +def lower_entity_sql(context, revision, operation): + """Select Alembic's native SQL artifact mode without replaying constructors.""" + target = operation.target + if not isinstance(target, ReplaceableEntity) or target.schema != "api": + return operation + if isinstance(operation, RevertOp): + connection = context.connection + expected_snapshot = context.opts.get("api_autogen_snapshot") + if ( + connection is None or not connection.in_transaction() + or connection.get_isolation_level() != "REPEATABLE READ" + or expected_snapshot is None + or connection.scalar(text("SELECT pg_current_snapshot()::text")) != expected_snapshot + ): + raise RuntimeError("Entity reversal requires the original autogeneration snapshot") + # Use only the vendor's public reflection factory under the SAME native + # transaction snapshot as its comparator, never its private cache. + with Session(bind=connection, join_transaction_mode="create_savepoint") as session: + old = [ + candidate for candidate in type(target).from_database(session, target.schema) + if candidate.identity == target.identity + ] + if ( + not connection.in_transaction() + or connection.scalar(text("SELECT pg_current_snapshot()::text")) != expected_snapshot + ): + raise RuntimeError("Vendor reflection changed the original autogeneration snapshot") + if len(old) != 1: + raise RuntimeError("Entity reversal snapshot is missing or ambiguous") + statements = old[0].to_sql_statement_create_or_replace() + elif isinstance(operation, DropOp): + statements = [target.to_sql_statement_drop(cascade=operation.cascade)] + elif isinstance(operation, CreateOp): + statements = [target.to_sql_statement_create()] + else: + statements = target.to_sql_statement_create_or_replace() + lowered = [] + for statement in statements: + if not isinstance(statement, TextClause): + raise TypeError("Vendor entity SQL must be a native TextClause") + # Preserve vendor emission verbatim. Native SQLAlchemy execution consumes + # its one bind-colon escape; no extra entity constructor is serialized. + lowered.append(ops.ExecuteSQLOp(statement.text)) + return lowered + + +def process_revision_directives(context, revision, directives): + if not directives: + return + migration = directives[0] + for upgrade in migration.upgrade_ops_list: + expanded = [] + created = False + for operation in upgrade.ops: + expanded.append(operation) + target = getattr(operation, "target", None) + if ( + isinstance(operation, (CreateOp, ReplaceOp)) + and isinstance(target, PGFunction) and target.schema == "api" + and target.signature == "current_actor_is_active()" + ): + expanded.append(ops.ExecuteSQLOp(actor_helper_execute(False, public=True))) + expanded.append(ops.ExecuteSQLOp(actor_helper_execute(True, public=False))) + if isinstance(operation, ops.CreateTableOp) and operation.schema == "api": + created = True + expanded.append(ops.ExecuteSQLOp(table_rls(operation.table_name))) + if created and not revision: + expanded.insert(0, ops.ExecuteSQLOp(schema_usage(True))) + upgrade.ops = expanded + if not revision: + for downgrade in migration.downgrade_ops_list: + downgrade.ops.append(ops.ExecuteSQLOp(schema_usage(False))) + entity_writer(context, revision, directives) diff --git a/backend/app/alembic/security.py b/backend/app/alembic/security.py new file mode 100644 index 0000000000..636599cbcb --- /dev/null +++ b/backend/app/alembic/security.py @@ -0,0 +1,126 @@ +"""API-owned security declarations consumed by native Alembic generators. + +Canonical identity, memberships and the issuer/client gate are external owners. +""" +from alembic_utils.pg_function import PGFunction +from alembic_utils.pg_grant_table import PGGrantTable +from alembic_utils.pg_policy import PGPolicy +from alembic_utils.pg_trigger import PGTrigger + + +# Claims with api_ names are installed only after the backend resolves the +# canonical actor; incoming token fields with those names are discarded. +SCOPE = """ + (SELECT auth.jwt()->>'role') = 'authenticated' + AND {row}.tenant_id = (SELECT auth.jwt()->>'api_tenant_id') + AND (SELECT public.is_workos_token_bound()) + AND (SELECT public.has_active_workos_membership()) + AND EXISTS ( + SELECT 1 FROM public.tenants AS t + WHERE t.id = {row}.tenant_id + AND t.workos_org_id = (SELECT public.current_workos_org_id()) + ) + AND 1 = ( + SELECT count(*) FROM public.identity_external AS x + JOIN public.identity_entity AS e ON e.id = x.entity_id + WHERE x.provider = 'workos' + AND x.external_id = (SELECT auth.jwt()->>'sub') + AND e.kind = 'user' AND e.tenant_id = {row}.tenant_id + AND e.id::text = (SELECT auth.jwt()->>'api_identity_entity_id') + ) +""" +RESOLVED = "(SELECT NULLIF(auth.jwt()->>'api_user_id', '')) IS NOT NULL" +LIVE_ACTOR = "(SELECT api.current_actor_is_active())" +ADMIN = "(SELECT public.current_workos_user_role()) = 'admin'" +READ = "((SELECT public.has_workos_permission('org:projects:read')) OR (SELECT public.has_workos_permission('org:projects:write')))" +WRITE = "(SELECT public.has_workos_permission('org:projects:write'))" +USER_SELF = "identity_entity_id::text = (SELECT auth.jwt()->>'api_identity_entity_id')" +TARGET_ACTOR = """EXISTS ( + SELECT 1 FROM public.identity_entity AS target + JOIN public.identity_external AS target_external + ON target_external.entity_id = target.id AND target_external.provider = 'workos' + WHERE target.id = {row}.identity_entity_id AND target.kind = 'user' + AND target.tenant_id = {row}.tenant_id +)""" +ITEM_OWNER = "(owner_id::text = (SELECT auth.jwt()->>'api_user_id') OR " + ADMIN + ")" +ITEM_ACTOR = """EXISTS ( + SELECT 1 FROM api."user" AS actor + WHERE actor.id::text = (SELECT auth.jwt()->>'api_user_id') + AND actor.identity_entity_id::text = (SELECT auth.jwt()->>'api_identity_entity_id') + AND actor.tenant_id = api.item.tenant_id AND actor.is_active +)""" + + +def policy(table: str, action: str, condition: str) -> PGPolicy: + clauses = f"AS PERMISSIVE FOR {action} TO authenticated " + if action != "INSERT": + clauses += f"USING ({condition}) " + if action in {"INSERT", "UPDATE"}: + clauses += f"WITH CHECK ({condition})" + return PGPolicy(schema="api", signature=f"{table}_{action.lower()}", on_entity=f'api."{table}"', definition=clauses) + + +user_scope = "(" + SCOPE.format(row='api."user"') + ") AND (" + TARGET_ACTOR.format(row='api."user"') + ")" +user_select = f"{user_scope} AND (({USER_SELF} AND is_active) OR ({RESOLVED} AND {LIVE_ACTOR} AND {ADMIN} AND {READ}))" +user_mutation = f"{user_scope} AND {RESOLVED} AND {LIVE_ACTOR} AND {WRITE} AND ({USER_SELF} OR {ADMIN})" +item_scope = "(" + SCOPE.format(row="api.item") + f") AND {RESOLVED} AND {ITEM_OWNER} AND ({ITEM_ACTOR})" + +# User policies cannot recursively query User under RLS. This boolean-only helper +# uses the separately verified migration owner; native ACLs deny PUBLIC execution. +# STABLE uses each statement's snapshot, not a cached principal's earlier state. +entities = [ + PGFunction( + schema="api", signature="current_actor_is_active()", + definition="""RETURNS boolean LANGUAGE sql STABLE SECURITY DEFINER + SET search_path = '' SET row_security = off AS $$ + SELECT EXISTS ( + SELECT 1 FROM api."user" AS actor + WHERE actor.id::text = (SELECT auth.jwt()->>'api_user_id') + AND actor.identity_entity_id::text = (SELECT auth.jwt()->>'api_identity_entity_id') + AND actor.tenant_id = (SELECT auth.jwt()->>'api_tenant_id') + AND actor.is_active + ) + $$""", + ), + policy("user", "SELECT", user_select), + policy("user", "INSERT", f"{user_scope} AND {RESOLVED} AND {LIVE_ACTOR} AND {ADMIN} AND {WRITE}"), + policy("user", "UPDATE", user_mutation), + policy("user", "DELETE", user_mutation), + policy("item", "SELECT", f"{item_scope} AND {READ}"), + policy("item", "INSERT", f"{item_scope} AND {WRITE} AND owner_id::text = (SELECT auth.jwt()->>'api_user_id')"), + policy("item", "UPDATE", f"{item_scope} AND {WRITE}"), + policy("item", "DELETE", f"{item_scope} AND {WRITE}"), +] + +# Column grants complement triggers: attribution cannot be reassigned through +# direct SQL even when a tenant administrator has row-level mutation authority. +for table, insert_columns, update_columns in ( + ("user", ["id", "tenant_id", "identity_entity_id", "email", "is_active", "full_name", "created_at"], ["email", "is_active", "full_name"]), + ("item", ["id", "tenant_id", "owner_id", "title", "description", "created_at"], ["title", "description"]), +): + entities.append(PGGrantTable(schema="api", table=table, role="authenticated", grant="SELECT", columns=insert_columns)) + entities.append(PGGrantTable(schema="api", table=table, role="authenticated", grant="DELETE")) + entities.append(PGGrantTable(schema="api", table=table, role="authenticated", grant="INSERT", columns=insert_columns)) + entities.append(PGGrantTable(schema="api", table=table, role="authenticated", grant="UPDATE", columns=update_columns)) + +for table, attribution in ( + ("user", "id, tenant_id, identity_entity_id, created_at"), + ("item", "id, tenant_id, owner_id, created_at"), +): + old = ", ".join(f"OLD.{column.strip()}" for column in attribution.split(",")) + new = ", ".join(f"NEW.{column.strip()}" for column in attribution.split(",")) + entities.append(PGFunction( + schema="api", signature=f"protect_{table}_attribution()", + definition=f"""RETURNS trigger LANGUAGE plpgsql SECURITY INVOKER SET search_path = '' AS $$ + BEGIN + IF ROW({old}) IS DISTINCT FROM ROW({new}) THEN + RAISE EXCEPTION 'API attribution is immutable' USING ERRCODE = '42501'; + END IF; + RETURN NEW; + END; + $$""", + )) + entities.append(PGTrigger( + schema="api", signature=f"protect_{table}_attribution", on_entity=f'api."{table}"', + definition=f'BEFORE UPDATE ON api."{table}" FOR EACH ROW EXECUTE FUNCTION api.protect_{table}_attribution()', + )) diff --git a/backend/app/api/deps.py b/backend/app/api/deps.py index 5f28ec692a..1dfb1d991f 100644 --- a/backend/app/api/deps.py +++ b/backend/app/api/deps.py @@ -1,57 +1,65 @@ from collections.abc import Generator from typing import Annotated -import jwt -from fastapi import Depends, HTTPException, status -from fastapi.security import OAuth2PasswordBearer -from jwt.exceptions import InvalidTokenError -from pydantic import ValidationError -from sqlmodel import Session - -from app.core import security -from app.core.config import settings -from app.core.db import engine -from app.models import TokenPayload, User - -reusable_oauth2 = OAuth2PasswordBearer( - tokenUrl=f"{settings.API_V1_STR}/login/access-token" -) - - -def get_db() -> Generator[Session]: - with Session(engine) as session: - yield session +from fastapi import Depends, HTTPException +from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer +from jwt import InvalidTokenError, PyJWKClientError +from sqlalchemy.exc import SQLAlchemyError +from app.core.auth import Principal, VerifiedSession, resolve_principal +from app.core.db import engine +from app.core.security import VerifiedAccessToken, get_token_verifier -SessionDep = Annotated[Session, Depends(get_db)] -TokenDep = Annotated[str, Depends(reusable_oauth2)] +bearer = HTTPBearer(auto_error=False) -def get_current_user(session: SessionDep, token: TokenDep) -> User: +def get_verified_token( + credentials: Annotated[HTTPAuthorizationCredentials | None, Depends(bearer)], +) -> VerifiedAccessToken: + if credentials is None: + raise HTTPException( + status_code=401, + detail="Bearer token required", + headers={"WWW-Authenticate": "Bearer"}, + ) try: - payload = jwt.decode( - token, settings.SECRET_KEY, algorithms=[security.ALGORITHM] + return get_token_verifier().verify(credentials.credentials) + except PyJWKClientError: + raise HTTPException( + status_code=401, + detail="Unable to verify access token", + headers={"WWW-Authenticate": "Bearer"}, ) - token_data = TokenPayload(**payload) - except InvalidTokenError, ValidationError: + except InvalidTokenError, ValueError, TypeError: raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="Could not validate credentials", + status_code=401, + detail="Invalid access token", + headers={"WWW-Authenticate": "Bearer"}, ) - user = session.get(User, token_data.sub) - if not user: - raise HTTPException(status_code=404, detail="User not found") - if not user.is_active: - raise HTTPException(status_code=400, detail="Inactive user") - return user -CurrentUser = Annotated[User, Depends(get_current_user)] +VerifiedTokenDep = Annotated[VerifiedAccessToken, Depends(get_verified_token)] -def get_current_active_superuser(current_user: CurrentUser) -> User: - if not current_user.is_superuser: - raise HTTPException( - status_code=403, detail="The user doesn't have enough privileges" - ) - return current_user +def get_db(token: VerifiedTokenDep) -> Generator[VerifiedSession]: + with VerifiedSession(engine, info={"verified_token": token}) as session: + try: + yield session + finally: + try: + session.rollback() + finally: + session.info.clear() + + +SessionDep = Annotated[VerifiedSession, Depends(get_db)] + + +def get_current_principal(session: SessionDep, token: VerifiedTokenDep) -> Principal: + try: + return resolve_principal(session, token) + except SQLAlchemyError: + raise HTTPException(status_code=503, detail="Identity data unavailable") + + +CurrentPrincipal = Annotated[Principal, Depends(get_current_principal)] diff --git a/backend/app/api/main.py b/backend/app/api/main.py index a42e5003ee..bddf142c22 100644 --- a/backend/app/api/main.py +++ b/backend/app/api/main.py @@ -1,14 +1,9 @@ from fastapi import APIRouter -from app.api.routes import items, login, private, users, utils -from app.core.config import settings +from app.api.routes import auth, items, users, utils api_router = APIRouter() -api_router.include_router(login.router) +api_router.include_router(auth.router) api_router.include_router(users.router) api_router.include_router(utils.router) api_router.include_router(items.router) - - -if settings.FASTAPI_ENV == "development": - api_router.include_router(private.router) diff --git a/backend/app/api/routes/auth.py b/backend/app/api/routes/auth.py new file mode 100644 index 0000000000..8406003b5d --- /dev/null +++ b/backend/app/api/routes/auth.py @@ -0,0 +1,23 @@ +from fastapi import APIRouter +from pydantic import BaseModel, ConfigDict + +from app.core.config import settings + +router = APIRouter(prefix="/auth", tags=["auth"]) + + +class AuthConfig(BaseModel): + model_config = ConfigDict(extra="forbid") + client_id: str + api_hostname: str + redirect_uri: str + + +@router.get("/config") +def read_auth_config() -> AuthConfig: + """Public browser configuration; no API key or server session credentials.""" + return AuthConfig( + client_id=settings.WORKOS_CLIENT_ID, + api_hostname=settings.WORKOS_API_HOSTNAME, + redirect_uri=settings.FRONTEND_HOST, + ) diff --git a/backend/app/api/routes/items.py b/backend/app/api/routes/items.py index f0eb30e4ce..398180d61b 100644 --- a/backend/app/api/routes/items.py +++ b/backend/app/api/routes/items.py @@ -1,113 +1,91 @@ import uuid -from typing import Any -from fastapi import APIRouter, HTTPException +from fastapi import APIRouter, HTTPException, Query +from sqlalchemy import ColumnElement from sqlmodel import col, func, select -from app.api.deps import CurrentUser, SessionDep +from app import crud +from app.api.deps import CurrentPrincipal, SessionDep +from app.core.auth import Principal, require_permission from app.models import Item, ItemCreate, ItemPublic, ItemsPublic, ItemUpdate, Message router = APIRouter(prefix="/items", tags=["items"]) +def item_scope(principal: Principal) -> list[ColumnElement[bool]]: + scope: list[ColumnElement[bool]] = [col(Item.tenant_id) == principal.tenant_id] + if not principal.is_tenant_admin: + scope.append(col(Item.owner_id) == principal.user.id) + return scope + + +def scoped_item(session: SessionDep, principal: Principal, item_id: uuid.UUID) -> Item: + item = session.exec( + select(Item).where(Item.id == item_id, *item_scope(principal)) + ).first() + if item is None: + raise HTTPException(status_code=404, detail="Item not found") + return item + + @router.get("/", response_model=ItemsPublic) def read_items( - session: SessionDep, current_user: CurrentUser, skip: int = 0, limit: int = 100 -) -> Any: - """ - Retrieve items. - """ - - if current_user.is_superuser: - count_statement = select(func.count()).select_from(Item) - count = session.exec(count_statement).one() - statement = ( - select(Item).order_by(col(Item.created_at).desc()).offset(skip).limit(limit) - ) - items = session.exec(statement).all() - else: - count_statement = ( - select(func.count()) - .select_from(Item) - .where(Item.owner_id == current_user.id) - ) - count = session.exec(count_statement).one() - statement = ( - select(Item) - .where(Item.owner_id == current_user.id) - .order_by(col(Item.created_at).desc()) - .offset(skip) - .limit(limit) - ) - items = session.exec(statement).all() - - items_public = [ItemPublic.model_validate(item) for item in items] - return ItemsPublic(data=items_public, count=count) + session: SessionDep, + principal: CurrentPrincipal, + skip: int = Query(0, ge=0), + limit: int = Query(100, ge=1, le=100), +) -> ItemsPublic: + require_permission(principal) + scope = item_scope(principal) + count = session.exec(select(func.count()).select_from(Item).where(*scope)).one() + items = session.exec( + select(Item) + .where(*scope) + .order_by(col(Item.created_at).desc(), col(Item.id)) + .offset(skip) + .limit(limit) + ).all() + return ItemsPublic( + data=[ItemPublic.model_validate(item) for item in items], count=count + ) @router.get("/{id}", response_model=ItemPublic) -def read_item(session: SessionDep, current_user: CurrentUser, id: uuid.UUID) -> Any: - """ - Get item by ID. - """ - item = session.get(Item, id) - if not item: - raise HTTPException(status_code=404, detail="Item not found") - if not current_user.is_superuser and (item.owner_id != current_user.id): - raise HTTPException(status_code=403, detail="Not enough permissions") - return item +def read_item(session: SessionDep, principal: CurrentPrincipal, id: uuid.UUID) -> Item: + require_permission(principal) + return scoped_item(session, principal, id) @router.post("/", response_model=ItemPublic) def create_item( - *, session: SessionDep, current_user: CurrentUser, item_in: ItemCreate -) -> Any: - """ - Create new item. - """ - item = Item.model_validate(item_in, update={"owner_id": current_user.id}) - session.add(item) - session.commit() - session.refresh(item) - return item + *, session: SessionDep, principal: CurrentPrincipal, item_in: ItemCreate +) -> Item: + return crud.create_item(session=session, principal=principal, item_in=item_in) @router.put("/{id}", response_model=ItemPublic) def update_item( *, session: SessionDep, - current_user: CurrentUser, + principal: CurrentPrincipal, id: uuid.UUID, item_in: ItemUpdate, -) -> Any: - """ - Update an item. - """ - item = session.get(Item, id) - if not item: - raise HTTPException(status_code=404, detail="Item not found") - if not current_user.is_superuser and (item.owner_id != current_user.id): - raise HTTPException(status_code=403, detail="Not enough permissions") - update_dict = item_in.model_dump(exclude_unset=True) - item.sqlmodel_update(update_dict) +) -> Item: + require_permission(principal, write=True) + item = scoped_item(session, principal, id) + item.sqlmodel_update(item_in.model_dump(exclude_unset=True)) session.add(item) session.commit() session.refresh(item) return item -@router.delete("/{id}") +@router.delete("/{id}", response_model=Message) def delete_item( - session: SessionDep, current_user: CurrentUser, id: uuid.UUID + session: SessionDep, principal: CurrentPrincipal, id: uuid.UUID ) -> Message: - """ - Delete an item. - """ - item = session.get(Item, id) - if not item: - raise HTTPException(status_code=404, detail="Item not found") - if not current_user.is_superuser and (item.owner_id != current_user.id): - raise HTTPException(status_code=403, detail="Not enough permissions") + require_permission(principal, write=True) + item = scoped_item(session, principal, id) session.delete(item) session.commit() return Message(message="Item deleted successfully") diff --git a/backend/app/api/routes/login.py b/backend/app/api/routes/login.py deleted file mode 100644 index 58441e37e9..0000000000 --- a/backend/app/api/routes/login.py +++ /dev/null @@ -1,123 +0,0 @@ -from datetime import timedelta -from typing import Annotated, Any - -from fastapi import APIRouter, Depends, HTTPException -from fastapi.responses import HTMLResponse -from fastapi.security import OAuth2PasswordRequestForm - -from app import crud -from app.api.deps import CurrentUser, SessionDep, get_current_active_superuser -from app.core import security -from app.core.config import settings -from app.models import Message, NewPassword, Token, UserPublic, UserUpdate -from app.utils import ( - generate_password_reset_token, - generate_reset_password_email, - send_email, - verify_password_reset_token, -) - -router = APIRouter(tags=["login"]) - - -@router.post("/login/access-token") -def login_access_token( - session: SessionDep, form_data: Annotated[OAuth2PasswordRequestForm, Depends()] -) -> Token: - """ - OAuth2 compatible token login, get an access token for future requests - """ - user = crud.authenticate( - session=session, email=form_data.username, password=form_data.password - ) - if not user: - raise HTTPException(status_code=400, detail="Incorrect email or password") - elif not user.is_active: - raise HTTPException(status_code=400, detail="Inactive user") - access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES) - return Token( - access_token=security.create_access_token( - user.id, expires_delta=access_token_expires - ) - ) - - -@router.post("/login/test-token", response_model=UserPublic) -def test_token(current_user: CurrentUser) -> Any: - """ - Test access token - """ - return current_user - - -@router.post("/password-recovery/{email}") -def recover_password(email: str, session: SessionDep) -> Message: - """ - Password Recovery - """ - user = crud.get_user_by_email(session=session, email=email) - - # Always return the same response to prevent email enumeration attacks - # Only send email if user actually exists - if user: - password_reset_token = generate_password_reset_token(email=email) - email_data = generate_reset_password_email( - email_to=user.email, email=email, token=password_reset_token - ) - send_email( - email_to=user.email, - subject=email_data.subject, - html_content=email_data.html_content, - ) - return Message( - message="If that email is registered, we sent a password recovery link" - ) - - -@router.post("/reset-password/") -def reset_password(session: SessionDep, body: NewPassword) -> Message: - """ - Reset password - """ - email = verify_password_reset_token(token=body.token) - if not email: - raise HTTPException(status_code=400, detail="Invalid token") - user = crud.get_user_by_email(session=session, email=email) - if not user: - # Don't reveal that the user doesn't exist - use same error as invalid token - raise HTTPException(status_code=400, detail="Invalid token") - elif not user.is_active: - raise HTTPException(status_code=400, detail="Inactive user") - user_in_update = UserUpdate(password=body.new_password) - crud.update_user( - session=session, - db_user=user, - user_in=user_in_update, - ) - return Message(message="Password updated successfully") - - -@router.post( - "/password-recovery-html-content/{email}", - dependencies=[Depends(get_current_active_superuser)], - response_class=HTMLResponse, -) -def recover_password_html_content(email: str, session: SessionDep) -> Any: - """ - HTML Content for Password Recovery - """ - user = crud.get_user_by_email(session=session, email=email) - - if not user: - raise HTTPException( - status_code=404, - detail="The user with this username does not exist in the system.", - ) - password_reset_token = generate_password_reset_token(email=email) - email_data = generate_reset_password_email( - email_to=user.email, email=email, token=password_reset_token - ) - - return HTMLResponse( - content=email_data.html_content, headers={"subject:": email_data.subject} - ) diff --git a/backend/app/api/routes/private.py b/backend/app/api/routes/private.py deleted file mode 100644 index 9f33ef1900..0000000000 --- a/backend/app/api/routes/private.py +++ /dev/null @@ -1,38 +0,0 @@ -from typing import Any - -from fastapi import APIRouter -from pydantic import BaseModel - -from app.api.deps import SessionDep -from app.core.security import get_password_hash -from app.models import ( - User, - UserPublic, -) - -router = APIRouter(tags=["private"], prefix="/private") - - -class PrivateUserCreate(BaseModel): - email: str - password: str - full_name: str - is_verified: bool = False - - -@router.post("/users/", response_model=UserPublic) -def create_user(user_in: PrivateUserCreate, session: SessionDep) -> Any: - """ - Create a new user. - """ - - user = User( - email=user_in.email, - full_name=user_in.full_name, - hashed_password=get_password_hash(user_in.password), - ) - - session.add(user) - session.commit() - - return user diff --git a/backend/app/api/routes/users.py b/backend/app/api/routes/users.py index 1748f58484..12d7c26883 100644 --- a/backend/app/api/routes/users.py +++ b/backend/app/api/routes/users.py @@ -1,232 +1,154 @@ import uuid -from typing import Any -from fastapi import APIRouter, Depends, HTTPException +from fastapi import APIRouter, HTTPException, Query from sqlmodel import col, delete, func, select from app import crud -from app.api.deps import ( - CurrentUser, - SessionDep, - get_current_active_superuser, -) -from app.core.config import settings -from app.core.security import get_password_hash, verify_password +from app.api.deps import CurrentPrincipal, SessionDep +from app.core.auth import Principal, require_permission, require_tenant_admin from app.models import ( + CurrentUserPublic, Item, Message, - UpdatePassword, User, UserCreate, UserPublic, - UserRegister, UsersPublic, UserUpdate, UserUpdateMe, ) -from app.utils import generate_new_account_email, send_email router = APIRouter(prefix="/users", tags=["users"]) -@router.get( - "/", - dependencies=[Depends(get_current_active_superuser)], - response_model=UsersPublic, -) -def read_users(session: SessionDep, skip: int = 0, limit: int = 100) -> Any: - """ - Retrieve users. - """ +def tenant_user(session: SessionDep, principal: Principal, user_id: uuid.UUID) -> User: + user = session.exec( + select(User).where(User.id == user_id, User.tenant_id == principal.tenant_id) + ).first() + if user is None: + raise HTTPException(status_code=404, detail="User not found") + return user + + +def check_profile_email( + session: SessionDep, principal: Principal, user: User, email: str | None +) -> None: + if email: + existing = crud.get_user_by_email( + session=session, tenant_id=principal.tenant_id, email=email + ) + if existing and existing.id != user.id: + raise HTTPException( + status_code=409, + detail="User with this email already exists in this tenant", + ) - count_statement = select(func.count()).select_from(User) - count = session.exec(count_statement).one() - statement = ( - select(User).order_by(col(User.created_at).desc()).offset(skip).limit(limit) +@router.get("/", response_model=UsersPublic) +def read_users( + session: SessionDep, + principal: CurrentPrincipal, + skip: int = Query(0, ge=0), + limit: int = Query(100, ge=1, le=100), +) -> UsersPublic: + require_tenant_admin(principal) + scope = col(User.tenant_id) == principal.tenant_id + count = session.exec(select(func.count()).select_from(User).where(scope)).one() + users = session.exec( + select(User) + .where(scope) + .order_by(col(User.created_at).desc(), col(User.id)) + .offset(skip) + .limit(limit) + ).all() + return UsersPublic( + data=[UserPublic.model_validate(user) for user in users], count=count ) - users = session.exec(statement).all() - users_public = [UserPublic.model_validate(user) for user in users] - return UsersPublic(data=users_public, count=count) +@router.post("/", response_model=UserPublic) +def create_user( + *, session: SessionDep, principal: CurrentPrincipal, user_in: UserCreate +) -> UserPublic: + """Create a local profile for an existing tenant-bound canonical actor.""" + return crud.create_user(session=session, principal=principal, user_create=user_in) -@router.post( - "/", dependencies=[Depends(get_current_active_superuser)], response_model=UserPublic -) -def create_user(*, session: SessionDep, user_in: UserCreate) -> Any: - """ - Create new user. - """ - user = crud.get_user_by_email(session=session, email=user_in.email) - if user: - raise HTTPException( - status_code=400, - detail="The user with this email already exists in the system.", - ) - user = crud.create_user(session=session, user_create=user_in) - if settings.emails_enabled and user_in.email: - email_data = generate_new_account_email( - email_to=user_in.email, username=user_in.email, password=user_in.password - ) - send_email( - email_to=user_in.email, - subject=email_data.subject, - html_content=email_data.html_content, - ) - return user +@router.get("/me", response_model=CurrentUserPublic) +def read_user_me(principal: CurrentPrincipal) -> CurrentUserPublic: + return CurrentUserPublic.model_validate( + principal.user, + update={ + "user_role": principal.user_role, + "permissions": sorted(principal.permissions), + "is_tenant_admin": principal.is_tenant_admin, + }, + ) @router.patch("/me", response_model=UserPublic) def update_user_me( - *, session: SessionDep, user_in: UserUpdateMe, current_user: CurrentUser -) -> Any: - """ - Update own user. - """ - - if user_in.email: - existing_user = crud.get_user_by_email(session=session, email=user_in.email) - if existing_user and existing_user.id != current_user.id: - raise HTTPException( - status_code=409, detail="User with this email already exists" - ) - user_data = user_in.model_dump(exclude_unset=True) - current_user.sqlmodel_update(user_data) - session.add(current_user) - session.commit() - session.refresh(current_user) - return current_user - - -@router.patch("/me/password", response_model=Message) -def update_password_me( - *, session: SessionDep, body: UpdatePassword, current_user: CurrentUser -) -> Any: - """ - Update own password. - """ - verified, _ = verify_password(body.current_password, current_user.hashed_password) - if not verified: - raise HTTPException(status_code=400, detail="Incorrect password") - if body.current_password == body.new_password: - raise HTTPException( - status_code=400, detail="New password cannot be the same as the current one" - ) - hashed_password = get_password_hash(body.new_password) - current_user.hashed_password = hashed_password - session.add(current_user) - session.commit() - return Message(message="Password updated successfully") - - -@router.get("/me", response_model=UserPublic) -def read_user_me(current_user: CurrentUser) -> Any: - """ - Get current user. - """ - return current_user + *, session: SessionDep, principal: CurrentPrincipal, user_in: UserUpdateMe +) -> UserPublic: + require_permission(principal, write=True) + check_profile_email(session, principal, principal.user, user_in.email) + principal.user.sqlmodel_update(user_in.model_dump(exclude_unset=True)) + session.add(principal.user) + return crud.commit_user_profile(session, principal.user) @router.delete("/me", response_model=Message) -def delete_user_me(session: SessionDep, current_user: CurrentUser) -> Any: - """ - Delete own user. - """ - if current_user.is_superuser: - raise HTTPException( - status_code=403, detail="Super users are not allowed to delete themselves" +def delete_user_me(session: SessionDep, principal: CurrentPrincipal) -> Message: + require_permission(principal, write=True) + session.exec( + delete(Item).where( + col(Item.tenant_id) == principal.tenant_id, + col(Item.owner_id) == principal.user.id, ) - session.delete(current_user) + ) + session.delete(principal.user) session.commit() - return Message(message="User deleted successfully") - - -@router.post("/signup", response_model=UserPublic) -def register_user(session: SessionDep, user_in: UserRegister) -> Any: - """ - Create new user without the need to be logged in. - """ - user = crud.get_user_by_email(session=session, email=user_in.email) - if user: - raise HTTPException( - status_code=400, - detail="The user with this email already exists in the system", - ) - user_create = UserCreate.model_validate(user_in) - user = crud.create_user(session=session, user_create=user_create) - return user + return Message(message="Local user profile deleted successfully") @router.get("/{user_id}", response_model=UserPublic) def read_user_by_id( - user_id: uuid.UUID, session: SessionDep, current_user: CurrentUser -) -> Any: - """ - Get a specific user by id. - """ - user = session.get(User, user_id) - if user == current_user: - return user - if not current_user.is_superuser: - raise HTTPException( - status_code=403, - detail="The user doesn't have enough privileges", - ) - if user is None: - raise HTTPException(status_code=404, detail="User not found") - return user + user_id: uuid.UUID, session: SessionDep, principal: CurrentPrincipal +) -> User: + require_permission(principal) + if user_id != principal.user.id: + require_tenant_admin(principal) + return tenant_user(session, principal, user_id) -@router.patch( - "/{user_id}", - dependencies=[Depends(get_current_active_superuser)], - response_model=UserPublic, -) +@router.patch("/{user_id}", response_model=UserPublic) def update_user( *, session: SessionDep, + principal: CurrentPrincipal, user_id: uuid.UUID, user_in: UserUpdate, -) -> Any: - """ - Update a user. - """ - - db_user = session.get(User, user_id) - if not db_user: - raise HTTPException( - status_code=404, - detail="The user with this id does not exist in the system", - ) - if user_in.email: - existing_user = crud.get_user_by_email(session=session, email=user_in.email) - if existing_user and existing_user.id != user_id: - raise HTTPException( - status_code=409, detail="User with this email already exists" - ) - - db_user = crud.update_user(session=session, db_user=db_user, user_in=user_in) - return db_user +) -> UserPublic: + require_tenant_admin(principal, write=True) + user = tenant_user(session, principal, user_id) + check_profile_email(session, principal, user, user_in.email) + return crud.update_user( + session=session, principal=principal, db_user=user, user_in=user_in + ) -@router.delete("/{user_id}", dependencies=[Depends(get_current_active_superuser)]) +@router.delete("/{user_id}", response_model=Message) def delete_user( - session: SessionDep, current_user: CurrentUser, user_id: uuid.UUID + session: SessionDep, principal: CurrentPrincipal, user_id: uuid.UUID ) -> Message: - """ - Delete a user. - """ - user = session.get(User, user_id) - if not user: - raise HTTPException(status_code=404, detail="User not found") - if user == current_user: - raise HTTPException( - status_code=403, detail="Super users are not allowed to delete themselves" + require_tenant_admin(principal, write=True) + user = tenant_user(session, principal, user_id) + session.exec( + delete(Item).where( + col(Item.owner_id) == user_id, + col(Item.tenant_id) == principal.tenant_id, ) - statement = delete(Item).where(col(Item.owner_id) == user_id) - session.exec(statement) + ) session.delete(user) session.commit() - return Message(message="User deleted successfully") + return Message(message="Local user profile deleted successfully") diff --git a/backend/app/api/routes/utils.py b/backend/app/api/routes/utils.py index fc093419b3..e63178e3ac 100644 --- a/backend/app/api/routes/utils.py +++ b/backend/app/api/routes/utils.py @@ -1,31 +1,8 @@ -from fastapi import APIRouter, Depends -from pydantic.networks import EmailStr - -from app.api.deps import get_current_active_superuser -from app.models import Message -from app.utils import generate_test_email, send_email +from fastapi import APIRouter router = APIRouter(prefix="/utils", tags=["utils"]) -@router.post( - "/test-email/", - dependencies=[Depends(get_current_active_superuser)], - status_code=201, -) -def test_email(email_to: EmailStr) -> Message: - """ - Test emails. - """ - email_data = generate_test_email(email_to=email_to) - send_email( - email_to=email_to, - subject=email_data.subject, - html_content=email_data.html_content, - ) - return Message(message="Test email sent") - - @router.get("/health-check/") async def health_check() -> bool: return True diff --git a/backend/app/core/auth.py b/backend/app/core/auth.py new file mode 100644 index 0000000000..0445225812 --- /dev/null +++ b/backend/app/core/auth.py @@ -0,0 +1,268 @@ +"""Request SQL identity and read-only access to the canonical product owners.""" + +import json +from dataclasses import dataclass +from datetime import UTC, datetime +from threading import Lock +from typing import Any +from uuid import UUID +from weakref import WeakKeyDictionary + +from fastapi import HTTPException +from sqlalchemy import MetaData, String, Table, cast, event, select, text +from sqlalchemy.engine import Connection, Engine +from sqlalchemy.orm import SessionTransaction +from sqlmodel import Session, col +from sqlmodel import select as model_select + +from app.core.security import VerifiedAccessToken +from app.models import User + + +class VerifiedSession(Session): + """A request session: identity is reinstalled on EVERY autobegin, not only once.""" + + +@event.listens_for(VerifiedSession, "after_begin") +def install_transaction_identity( + session: VerifiedSession, _transaction: SessionTransaction, connection: Connection +) -> None: + token: VerifiedAccessToken | None = session.info.get("verified_token") + if token is None: + raise RuntimeError("SQL access requires a verified WorkOS token") + if connection.dialect.name != "postgresql": + raise RuntimeError("Verified SQL sessions require PostgreSQL RLS") + if token.claims["exp"] <= datetime.now(UTC).timestamp(): + raise HTTPException(status_code=401, detail="Access token expired") + runtime_role = connection.execute( + text( + "SELECT rolsuper, rolbypassrls FROM pg_catalog.pg_roles WHERE rolname = session_user" + ) + ).one() + if runtime_role.rolsuper or runtime_role.rolbypassrls: + raise RuntimeError("API runtime role must be non-superuser and NOBYPASSRLS") + connection.execute(text("SET LOCAL ROLE authenticated")) + claims = session.info.get("request_claims") + if claims is None: + claims = { + name: value + for name, value in token.claims.items() + if not name.startswith("api_") + } + session.info["request_claims"] = claims + connection.execute( + text("SELECT set_config('request.jwt.claims', :claims, true)"), + {"claims": json.dumps(claims, separators=(",", ":"))}, + ) + # SET LOCAL + the pool's rollback-on-return removes role and claims on both + # success and failure. No request identity is stored on a pooled Connection. + + +@dataclass(frozen=True) +class Principal: + user: User + tenant_id: str + organization_id: str + subject: str + user_role: str + permissions: frozenset[str] + is_tenant_admin: bool + + +class CanonicalIdentity: + def __init__(self, connection: Connection): + # Reflect, never redeclare or create the product's tables in API metadata. + metadata = MetaData() + self.tenants = Table( + "tenants", + metadata, + schema="public", + autoload_with=connection, + resolve_fks=False, + ) + self.entities = Table( + "identity_entity", + metadata, + schema="public", + autoload_with=connection, + resolve_fks=False, + ) + self.external = Table( + "identity_external", + metadata, + schema="public", + autoload_with=connection, + resolve_fks=False, + ) + self.memberships = Table( + "workosorganizationmembership", + metadata, + schema="workos", + autoload_with=connection, + resolve_fks=False, + ) + + +_contracts: WeakKeyDictionary[Engine, CanonicalIdentity] = WeakKeyDictionary() +_contract_lock = Lock() + + +def canonical_identity(session: Session) -> CanonicalIdentity: + connection = session.connection() + engine = connection.engine + with _contract_lock: + contract = _contracts.get(engine) + if contract is None: + contract = CanonicalIdentity(connection) + _contracts[engine] = contract + return contract + + +def deny_mapping() -> HTTPException: + return HTTPException( + status_code=403, detail="No active tenant identity association" + ) + + +def active_membership( + session: Session, contract: CanonicalIdentity, subject: str, organization_id: str +) -> Any: + m = contract.memberships.c + rows = ( + session.connection() + .execute( + select(m.role, m.roles, m.status).where( + m.user_id == subject, + m.organization_id == organization_id, + ) + ) + .all() + ) + if len(rows) != 1: + raise deny_mapping() + membership = rows[0] + if ( + not isinstance(membership.status, str) + or membership.status.strip().lower() != "active" + ): + raise deny_mapping() + if ( + not isinstance(membership.role, str) + or not membership.role + or membership.roles not in ([], [membership.role]) + ): + raise deny_mapping() + return membership + + +def resolve_principal(session: Session, token: VerifiedAccessToken) -> Principal: + # Existing SECURITY DEFINER helper owns private issuer/client/enabled state. + # No alternate gate, private-table read or fallback to a catalog environment. + if ( + session.connection() + .execute(text("SELECT public.current_workos_org_id()")) + .scalar_one() + != token.organization_id + ): + raise deny_mapping() + contract = canonical_identity(session) + membership = active_membership( + session, contract, token.subject, token.organization_id + ) + if membership.role != token.user_role: + raise deny_mapping() + t, e, x = contract.tenants.c, contract.entities.c, contract.external.c + matches = ( + session.connection() + .execute( + select(t.id, e.id.label("identity_entity_id")) + .select_from( + contract.tenants.join( + contract.entities, cast(e.tenant_id, String) == cast(t.id, String) + ).join(contract.external, x.entity_id == e.id) + ) + .where( + t.workos_org_id == token.organization_id, + e.kind == "user", + x.provider == "workos", + x.external_id == token.subject, + ) + ) + .all() + ) + if len(matches) != 1: + raise deny_mapping() + match = matches[0] + tenant_id = str(match.id) + claims = session.info["request_claims"] + claims.update( + api_tenant_id=tenant_id, api_identity_entity_id=str(match.identity_entity_id) + ) + session.connection().execute( + text("SELECT set_config('request.jwt.claims', :claims, true)"), + {"claims": json.dumps(claims, separators=(",", ":"))}, + ) + users = session.exec( + model_select(User).where( + col(User.tenant_id) == tenant_id, + col(User.identity_entity_id) == match.identity_entity_id, + ) + ).all() + if len(users) != 1 or not users[0].is_active: + raise deny_mapping() + claims["api_user_id"] = str(users[0].id) + session.connection().execute( + text("SELECT set_config('request.jwt.claims', :claims, true)"), + {"claims": json.dumps(claims, separators=(",", ":"))}, + ) + return Principal( + user=users[0], + tenant_id=tenant_id, + organization_id=token.organization_id, + subject=token.subject, + user_role=token.user_role, + permissions=token.permissions, + is_tenant_admin=token.user_role == "admin", + ) + + +def require_canonical_actor( + session: Session, principal: Principal, entity_id: UUID +) -> None: + """Verify the existing tenant-bound crosswalk, not private target membership. + + A local profile grants no WorkOS membership or role. The target must pass + the ordinary active-membership/claim checks independently on authentication. + """ + contract = canonical_identity(session) + e, x = contract.entities.c, contract.external.c + rows = ( + session.connection() + .execute( + select(x.external_id) + .select_from(contract.entities.join(contract.external, x.entity_id == e.id)) + .where( + e.id == entity_id, + cast(e.tenant_id, String) == str(principal.tenant_id), + e.kind == "user", + x.provider == "workos", + ) + ) + .all() + ) + if len(rows) != 1: + raise deny_mapping() + + +def require_permission(principal: Principal, *, write: bool = False) -> None: + required = ( + {"org:projects:write"} if write else {"org:projects:read", "org:projects:write"} + ) + if not principal.permissions.intersection(required): + raise HTTPException(status_code=403, detail="Not enough permissions") + + +def require_tenant_admin(principal: Principal, *, write: bool = False) -> None: + require_permission(principal, write=write) + if not principal.is_tenant_admin: + raise HTTPException(status_code=403, detail="Tenant administrator required") diff --git a/backend/app/core/config.py b/backend/app/core/config.py index 095f72eeca..eccd456d1a 100644 --- a/backend/app/core/config.py +++ b/backend/app/core/config.py @@ -1,5 +1,5 @@ -import warnings from typing import Literal, Self +from urllib.parse import urlsplit from pydantic import ( EmailStr, @@ -14,21 +14,19 @@ class Settings(BaseSettings): model_config = SettingsConfigDict( - # Use top level .env file (one level above ./backend/) - env_file="../.env", - env_ignore_empty=True, - extra="ignore", + env_file="../.env", env_ignore_empty=True, extra="ignore" ) - API_V1_STR: str = "/api/v1" - SECRET_KEY: str - # 60 minutes * 24 hours * 8 days = 8 days - ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8 - FRONTEND_HOST: str = "http://localhost:5173" - FASTAPI_ENV: Literal["development"] | None = None + API_V1_STR: str = "/api/v1" PROJECT_NAME: str + FRONTEND_HOST: str + FASTAPI_ENV: Literal["development"] | None = None SENTRY_DSN: HttpUrl | None = None DATABASE_URL: PostgresDsn + WORKOS_CLIENT_ID: str + WORKOS_ISSUER: str + WORKOS_JWKS_URL: str + WORKOS_API_HOSTNAME: str @field_validator("DATABASE_URL", mode="before") @classmethod @@ -39,6 +37,63 @@ def _use_psycopg_driver(cls, value: str | PostgresDsn) -> str: return database_url.replace(scheme, "postgresql+psycopg://", 1) return database_url + @model_validator(mode="after") + def _validate_auth_boundaries(self) -> Self: + origin = urlsplit(self.FRONTEND_HOST) + if ( + origin.scheme not in {"http", "https"} + or not origin.hostname + or origin.username + or origin.password + or origin.query + or origin.fragment + or origin.path not in {"", "/"} + ): + raise ValueError("FRONTEND_HOST must be an explicit browser origin") + if self.FRONTEND_HOST != self.FRONTEND_HOST.strip(): + raise ValueError("FRONTEND_HOST must not contain whitespace") + if self.FASTAPI_ENV != "development" and origin.scheme != "https": + raise ValueError("Production FRONTEND_HOST requires HTTPS") + if ( + not self.WORKOS_CLIENT_ID.startswith("client_") + or self.WORKOS_CLIENT_ID.strip() != self.WORKOS_CLIENT_ID + ): + raise ValueError( + "WORKOS_CLIENT_ID must identify the explicitly selected application" + ) + hostname = self.WORKOS_API_HOSTNAME + if ( + not hostname + or hostname != hostname.lower() + or any(c in hostname for c in "/:@?# ") + ): + raise ValueError("WORKOS_API_HOSTNAME must be a hostname, not a URL") + issuer, jwks = urlsplit(self.WORKOS_ISSUER), urlsplit(self.WORKOS_JWKS_URL) + for value in (issuer, jwks): + if ( + value.scheme != "https" + or not value.hostname + or value.username + or value.password + or value.fragment + ): + raise ValueError("WorkOS issuer and JWKS require explicit HTTPS URLs") + # AuthKit React documents a custom Authentication API domain for production. + # DNS/TLS verification and browser cookie compatibility are admission gates. + if self.FASTAPI_ENV != "development": + if hostname == "api.workos.com" or hostname.endswith(".workos.dev"): + raise ValueError( + "Production AuthKit React requires a custom authentication API domain" + ) + if origin.hostname == hostname: + raise ValueError( + "The WorkOS custom domain cannot also host this application" + ) + for host in self.DATABASE_URL.hosts(): + if host["password"] == "changethis": + raise ValueError("DATABASE_URL must not contain template credentials") + return self + SMTP_TLS: bool = True SMTP_SSL: bool = False SMTP_PORT: int = 587 @@ -54,38 +109,11 @@ def _set_default_emails_from(self) -> Self: self.EMAILS_FROM_NAME = self.PROJECT_NAME return self - EMAIL_RESET_TOKEN_EXPIRE_HOURS: int = 48 - + # Pydantic documents MyPy's decorated-property limitation. @computed_field # type: ignore[prop-decorator] @property def emails_enabled(self) -> bool: return bool(self.SMTP_HOST and self.EMAILS_FROM_EMAIL) - EMAIL_TEST_USER: EmailStr = "test@example.com" - FIRST_SUPERUSER: EmailStr - FIRST_SUPERUSER_PASSWORD: str - - def _check_default_secret(self, var_name: str, value: str | None) -> None: - if value == "changethis": - message = ( - f'The value of {var_name} is "changethis", ' - "for security, please change it, at least for deployments." - ) - if self.FASTAPI_ENV == "development": - warnings.warn(message, stacklevel=1) - else: - raise ValueError(message) - - @model_validator(mode="after") - def _enforce_non_default_secrets(self) -> Self: - self._check_default_secret("SECRET_KEY", self.SECRET_KEY) - for host in self.DATABASE_URL.hosts(): - self._check_default_secret("DATABASE_URL password", host["password"]) - self._check_default_secret( - "FIRST_SUPERUSER_PASSWORD", self.FIRST_SUPERUSER_PASSWORD - ) - - return self - -settings = Settings() # type: ignore # ty: ignore[unused-ignore-comment] +settings = Settings() diff --git a/backend/app/core/db.py b/backend/app/core/db.py index d11b0ebd59..d2e7b4e44f 100644 --- a/backend/app/core/db.py +++ b/backend/app/core/db.py @@ -1,33 +1,7 @@ -from sqlmodel import Session, create_engine, select +from sqlmodel import create_engine -from app import crud from app.core.config import settings -from app.models import User, UserCreate -engine = create_engine(str(settings.DATABASE_URL), pool_pre_ping=True) - - -# make sure all SQLModel models are imported (app.models) before initializing DB -# otherwise, SQLModel might fail to initialize relationships properly -# for more details: https://github.com/fastapi/full-stack-fastapi-template/issues/28 - - -def init_db(session: Session) -> None: - # Tables should be created with Alembic migrations - # But if you don't want to use migrations, create - # the tables un-commenting the next lines - # from sqlmodel import SQLModel - - # This works because the models are already imported and registered from app.models - # SQLModel.metadata.create_all(engine) - - user = session.exec( - select(User).where(User.email == settings.FIRST_SUPERUSER) - ).first() - if not user: - user_in = UserCreate( - email=settings.FIRST_SUPERUSER, - password=settings.FIRST_SUPERUSER_PASSWORD, - is_superuser=True, - ) - user = crud.create_user(session=session, user_create=user_in) +engine = create_engine( + str(settings.DATABASE_URL), pool_pre_ping=True, pool_reset_on_return="rollback" +) diff --git a/backend/app/core/security.py b/backend/app/core/security.py index b9f88adc28..bcb41b48b6 100644 --- a/backend/app/core/security.py +++ b/backend/app/core/security.py @@ -1,36 +1,105 @@ -from datetime import UTC, datetime, timedelta -from typing import Any +"""WorkOS resource-server verification using PyJWT's native JWKS implementation.""" + +import ssl +from dataclasses import dataclass +from functools import lru_cache +from typing import Any, Protocol import jwt -from pwdlib import PasswordHash -from pwdlib.hashers.argon2 import Argon2Hasher -from pwdlib.hashers.bcrypt import BcryptHasher +from jwt import InvalidTokenError, PyJWK, PyJWKClient -from app.core.config import settings +from app.core.config import Settings, settings -password_hash = PasswordHash( - ( - Argon2Hasher(), - BcryptHasher(), - ) -) +class SigningKeys(Protocol): + def get_signing_key_from_jwt(self, token: str) -> PyJWK: ... -ALGORITHM = "HS256" +@dataclass(frozen=True) +class VerifiedAccessToken: + subject: str + session_id: str + organization_id: str + user_role: str + permissions: frozenset[str] + claims: dict[str, Any] -def create_access_token(subject: str | Any, expires_delta: timedelta) -> str: - expire = datetime.now(UTC) + expires_delta - to_encode = {"exp": expire, "sub": str(subject)} - encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=ALGORITHM) - return encoded_jwt +class AccessTokenVerifier: + def __init__(self, config: Settings, *, jwks_client: SigningKeys | None = None): + self.config = config + self.jwks = jwks_client or PyJWKClient( + config.WORKOS_JWKS_URL, + cache_jwk_set=True, + lifespan=300, + timeout=5, + ssl_context=ssl.create_default_context(), + ) -def verify_password( - plain_password: str, hashed_password: str -) -> tuple[bool, str | None]: - return password_hash.verify_and_update(plain_password, hashed_password) + def verify(self, token: str) -> VerifiedAccessToken: + key = self.jwks.get_signing_key_from_jwt(token) + claims = jwt.decode( + token, + key.key, + algorithms=["RS256"], + issuer=self.config.WORKOS_ISSUER, + options={ + "require": [ + "iss", + "exp", + "iat", + "sub", + "sid", + "org_id", + "client_id", + "role", + "user_role", + "permissions", + ], + # AuthKit's documented client binding is client_id, not Clerk's azp. + # Audience is optional; when emitted it must match this same client. + "verify_aud": False, + }, + ) + for name in ("sub", "sid", "org_id", "client_id", "user_role"): + value = claims[name] + if not isinstance(value, str) or not value or value.strip() != value: + raise InvalidTokenError(f"Invalid {name} claim") + for name in ("exp", "iat"): + if type(claims[name]) is not int: + raise InvalidTokenError(f"Invalid {name} claim") + if claims["client_id"] != self.config.WORKOS_CLIENT_ID: + raise InvalidTokenError("Wrong WorkOS application") + if claims["role"] != "authenticated": + raise InvalidTokenError("Invalid database role claim") + if "aud" in claims and claims["aud"] not in ( + self.config.WORKOS_CLIENT_ID, + [self.config.WORKOS_CLIENT_ID], + ): + raise InvalidTokenError("Conflicting audience") + compact = claims.get("o") + if compact is not None and ( + not isinstance(compact, dict) or compact.get("id") != claims["org_id"] + ): + raise InvalidTokenError("Conflicting organization claims") + roles = claims.get("roles") + if roles is not None and roles != [claims["user_role"]]: + raise InvalidTokenError("Multi-role sessions are not admitted") + permissions = claims["permissions"] + if not isinstance(permissions, list) or any( + not isinstance(p, str) or not p or p.strip() != p for p in permissions + ): + raise InvalidTokenError("Invalid permissions claim") + return VerifiedAccessToken( + subject=claims["sub"], + session_id=claims["sid"], + organization_id=claims["org_id"], + user_role=claims["user_role"], + permissions=frozenset(permissions), + claims=claims, + ) -def get_password_hash(password: str) -> str: - return password_hash.hash(password) +@lru_cache(maxsize=1) +def get_token_verifier() -> AccessTokenVerifier: + return AccessTokenVerifier(settings) diff --git a/backend/app/crud.py b/backend/app/crud.py index a8ceba6444..90c621e47c 100644 --- a/backend/app/crud.py +++ b/backend/app/crud.py @@ -1,68 +1,98 @@ -import uuid -from typing import Any - +from fastapi import HTTPException +from psycopg.errors import UniqueViolation +from sqlalchemy.exc import IntegrityError from sqlmodel import Session, select -from app.core.security import get_password_hash, verify_password -from app.models import Item, ItemCreate, User, UserCreate, UserUpdate +from app.core.auth import ( + Principal, + require_canonical_actor, + require_permission, + require_tenant_admin, +) +from app.models import Item, ItemCreate, User, UserCreate, UserPublic, UserUpdate +_PROFILE_CONFLICT_DETAILS = { + "uq_user_tenant_email": "User with this email already exists in this tenant", + "uq_user_tenant_actor": "Local actor profile already exists", +} -def create_user(*, session: Session, user_create: UserCreate) -> User: - db_obj = User.model_validate( - user_create, update={"hashed_password": get_password_hash(user_create.password)} - ) - session.add(db_obj) - session.commit() - session.refresh(db_obj) - return db_obj - -def update_user(*, session: Session, db_user: User, user_in: UserUpdate) -> Any: - user_data = user_in.model_dump(exclude_unset=True) - extra_data = {} - if "password" in user_data: - password = user_data["password"] - hashed_password = get_password_hash(password) - extra_data["hashed_password"] = hashed_password - db_user.sqlmodel_update(user_data, update=extra_data) - session.add(db_user) - session.commit() - session.refresh(db_user) - return db_user +def commit_user_profile(session: Session, profile: User) -> UserPublic: + """Return flushed state only after commit, without a post-revocation read.""" + try: + session.flush() + response = UserPublic.model_validate(profile) + session.commit() + except IntegrityError as error: + session.rollback() + if isinstance(error.orig, UniqueViolation) and error.orig.sqlstate == "23505": + constraint_name = error.orig.diag.constraint_name + if ( + constraint_name is not None + and constraint_name in _PROFILE_CONFLICT_DETAILS + ): + raise HTTPException( + status_code=409, + detail=_PROFILE_CONFLICT_DETAILS[constraint_name], + ) from error + raise + return response -def get_user_by_email(*, session: Session, email: str) -> User | None: - statement = select(User).where(User.email == email) - session_user = session.exec(statement).first() - return session_user +def create_user( + *, session: Session, principal: Principal, user_create: UserCreate +) -> UserPublic: + require_tenant_admin(principal, write=True) + require_canonical_actor(session, principal, user_create.identity_entity_id) + existing = session.exec( + select(User).where( + User.tenant_id == principal.tenant_id, + User.identity_entity_id == user_create.identity_entity_id, + ) + ).first() + if existing: + raise HTTPException( + status_code=409, detail="Local actor profile already exists" + ) + if get_user_by_email( + session=session, tenant_id=principal.tenant_id, email=user_create.email + ): + raise HTTPException( + status_code=409, detail="User with this email already exists in this tenant" + ) + user = User.model_validate(user_create, update={"tenant_id": principal.tenant_id}) + session.add(user) + return commit_user_profile(session, user) -# Dummy hash to use for timing attack prevention when user is not found -# This is an Argon2 hash of a random password, used to ensure constant-time comparison -DUMMY_HASH = "$argon2id$v=19$m=65536,t=3,p=4$MjQyZWE1MzBjYjJlZTI0Yw$YTU4NGM5ZTZmYjE2NzZlZjY0ZWY3ZGRkY2U2OWFjNjk" +def update_user( + *, session: Session, principal: Principal, db_user: User, user_in: UserUpdate +) -> UserPublic: + require_tenant_admin(principal, write=True) + if db_user.tenant_id != principal.tenant_id: + raise HTTPException(status_code=404, detail="User not found") + db_user.sqlmodel_update(user_in.model_dump(exclude_unset=True)) + session.add(db_user) + return commit_user_profile(session, db_user) -def authenticate(*, session: Session, email: str, password: str) -> User | None: - db_user = get_user_by_email(session=session, email=email) - if not db_user: - # Prevent timing attacks by running password verification even when user doesn't exist - # This ensures the response time is similar whether or not the email exists - verify_password(password, DUMMY_HASH) - return None - verified, updated_password_hash = verify_password(password, db_user.hashed_password) - if not verified: - return None - if updated_password_hash: - db_user.hashed_password = updated_password_hash - session.add(db_user) - session.commit() - session.refresh(db_user) - return db_user +def get_user_by_email(*, session: Session, tenant_id: str, email: str) -> User | None: + # Profile uniqueness only: email never resolves or links an authenticated actor. + return session.exec( + select(User).where(User.tenant_id == tenant_id, User.email == email) + ).first() -def create_item(*, session: Session, item_in: ItemCreate, owner_id: uuid.UUID) -> Item: - db_item = Item.model_validate(item_in, update={"owner_id": owner_id}) - session.add(db_item) +def create_item(*, session: Session, principal: Principal, item_in: ItemCreate) -> Item: + require_permission(principal, write=True) + item = Item.model_validate( + item_in, + update={ + "owner_id": principal.user.id, + "tenant_id": principal.tenant_id, + }, + ) + session.add(item) session.commit() - session.refresh(db_item) - return db_item + session.refresh(item) + return item diff --git a/backend/app/initial_data.py b/backend/app/initial_data.py deleted file mode 100644 index d806c3d381..0000000000 --- a/backend/app/initial_data.py +++ /dev/null @@ -1,23 +0,0 @@ -import logging - -from sqlmodel import Session - -from app.core.db import engine, init_db - -logging.basicConfig(level=logging.INFO) -logger = logging.getLogger(__name__) - - -def init() -> None: - with Session(engine) as session: - init_db(session) - - -def main() -> None: - logger.info("Creating initial data") - init() - logger.info("Initial data created") - - -if __name__ == "__main__": - main() diff --git a/backend/app/models.py b/backend/app/models.py index 181acf2bf1..e010b2633d 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -1,64 +1,120 @@ import uuid from datetime import UTC, datetime -from pydantic import EmailStr +from pydantic import EmailStr, field_validator +from sqlalchemy import ( + Column, + DateTime, + ForeignKey, + ForeignKeyConstraint, + MetaData, + Table, + Text, + UniqueConstraint, + Uuid, +) from sqlmodel import Field, Relationship, SQLModel +# Reference targets are external contracts, deliberately absent from API metadata. +_external_metadata = MetaData() +_tenant = Table( + "tenants", _external_metadata, Column("id", Text, primary_key=True), schema="public" +) +_identity_entity = Table( + "identity_entity", + _external_metadata, + Column("id", Uuid, primary_key=True), + schema="public", +) + def get_datetime_utc() -> datetime: return datetime.now(UTC) -# Shared properties +def reject_explicit_null(value: object) -> object: + if value is None: + raise ValueError("This field cannot be null") + return value + + class UserBase(SQLModel): - email: EmailStr = Field(unique=True, index=True, max_length=255) + email: EmailStr = Field(max_length=255) is_active: bool = True - is_superuser: bool = False full_name: str | None = Field(default=None, max_length=255) -# Properties to receive via API on creation class UserCreate(UserBase): - password: str = Field(min_length=8, max_length=128) + model_config = SQLModel.model_config.copy() + model_config["extra"] = "forbid" + identity_entity_id: uuid.UUID -class UserRegister(SQLModel): - email: EmailStr = Field(max_length=255) - password: str = Field(min_length=8, max_length=128) - full_name: str | None = Field(default=None, max_length=255) - - -# Properties to receive via API on update, all are optional class UserUpdate(SQLModel): + model_config = SQLModel.model_config.copy() + model_config["extra"] = "forbid" email: EmailStr | None = Field(default=None, max_length=255) is_active: bool | None = None - is_superuser: bool | None = None full_name: str | None = Field(default=None, max_length=255) - password: str | None = Field(default=None, min_length=8, max_length=128) + + _non_null_fields = field_validator("email", "is_active", mode="before")( + reject_explicit_null + ) class UserUpdateMe(SQLModel): + model_config = SQLModel.model_config.copy() + model_config["extra"] = "forbid" full_name: str | None = Field(default=None, max_length=255) email: EmailStr | None = Field(default=None, max_length=255) + _non_null_fields = field_validator("email", mode="before")(reject_explicit_null) -class UpdatePassword(SQLModel): - current_password: str = Field(min_length=8, max_length=128) - new_password: str = Field(min_length=8, max_length=128) - -# Database model, database table inferred from class name class User(UserBase, table=True): + __table_args__ = ( + UniqueConstraint("id", "tenant_id", name="uq_user_id_tenant"), + UniqueConstraint("tenant_id", "email", name="uq_user_tenant_email"), + UniqueConstraint( + "tenant_id", "identity_entity_id", name="uq_user_tenant_actor" + ), + {"schema": "api"}, + ) id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True) - hashed_password: str - created_at: datetime | None = Field(default_factory=get_datetime_utc) + tenant_id: str = Field( + sa_column=Column( + Text, + ForeignKey(_tenant.c.id, name="fk_user_tenant"), + nullable=False, + index=True, + ) + ) + identity_entity_id: uuid.UUID = Field( + sa_column=Column( + Uuid, + ForeignKey(_identity_entity.c.id, name="fk_user_identity_entity"), + nullable=False, + ) + ) + created_at: datetime = Field( + default_factory=get_datetime_utc, + sa_type=DateTime(timezone=True), + nullable=False, + ) items: list[Item] = Relationship(back_populates="owner", cascade_delete=True) -# Properties to return via API, id is always required class UserPublic(UserBase): id: uuid.UUID - created_at: datetime | None = None + created_at: datetime + tenant_id: str + identity_entity_id: uuid.UUID + + +class CurrentUserPublic(UserPublic): + user_role: str + permissions: list[str] + is_tenant_admin: bool class UsersPublic(SQLModel): @@ -66,38 +122,53 @@ class UsersPublic(SQLModel): count: int -# Shared properties class ItemBase(SQLModel): title: str = Field(min_length=1, max_length=255) description: str | None = Field(default=None, max_length=255) -# Properties to receive on item creation class ItemCreate(ItemBase): - pass + """Item creation accepts content, never caller-supplied attribution.""" + + model_config = SQLModel.model_config.copy() + model_config["extra"] = "forbid" -# Properties to receive on item update class ItemUpdate(SQLModel): + model_config = SQLModel.model_config.copy() + model_config["extra"] = "forbid" title: str | None = Field(default=None, min_length=1, max_length=255) description: str | None = Field(default=None, max_length=255) + _non_null_fields = field_validator("title", mode="before")(reject_explicit_null) + -# Database model, database table inferred from class name class Item(ItemBase, table=True): + __table_args__ = ( + ForeignKeyConstraint( + ["owner_id", "tenant_id"], + ["api.user.id", "api.user.tenant_id"], + name="fk_item_owner_tenant", + ondelete="CASCADE", + ), + {"schema": "api"}, + ) id: uuid.UUID = Field(default_factory=uuid.uuid4, primary_key=True) - created_at: datetime | None = Field(default_factory=get_datetime_utc) - owner_id: uuid.UUID = Field( - foreign_key="user.id", nullable=False, ondelete="CASCADE" + created_at: datetime = Field( + default_factory=get_datetime_utc, + sa_type=DateTime(timezone=True), + nullable=False, ) + owner_id: uuid.UUID = Field(nullable=False) + tenant_id: str = Field(sa_type=Text, nullable=False, index=True) owner: User | None = Relationship(back_populates="items") -# Properties to return via API, id is always required class ItemPublic(ItemBase): id: uuid.UUID owner_id: uuid.UUID - created_at: datetime | None = None + tenant_id: str + created_at: datetime class ItemsPublic(SQLModel): @@ -105,22 +176,5 @@ class ItemsPublic(SQLModel): count: int -# Generic message class Message(SQLModel): message: str - - -# JSON payload containing access token -class Token(SQLModel): - access_token: str - token_type: str = "bearer" - - -# Contents of JWT token -class TokenPayload(SQLModel): - sub: str | None = None - - -class NewPassword(SQLModel): - token: str - new_password: str = Field(min_length=8, max_length=128) diff --git a/backend/app/utils.py b/backend/app/utils.py index d59aefc7bf..95574cda4c 100644 --- a/backend/app/utils.py +++ b/backend/app/utils.py @@ -1,15 +1,11 @@ import logging from dataclasses import dataclass -from datetime import UTC, datetime, timedelta from pathlib import Path from typing import Any import emails -import jwt from jinja2 import Template -from jwt.exceptions import InvalidTokenError -from app.core import security from app.core.config import settings logging.basicConfig(level=logging.INFO) @@ -65,61 +61,3 @@ def generate_test_email(email_to: str) -> EmailData: context={"project_name": settings.PROJECT_NAME, "email": email_to}, ) return EmailData(html_content=html_content, subject=subject) - - -def generate_reset_password_email(email_to: str, email: str, token: str) -> EmailData: - project_name = settings.PROJECT_NAME - subject = f"{project_name} - Password recovery for user {email}" - link = f"{settings.FRONTEND_HOST}/reset-password?token={token}" - html_content = render_email_template( - template_name="reset_password.html", - context={ - "project_name": settings.PROJECT_NAME, - "username": email, - "email": email_to, - "valid_hours": settings.EMAIL_RESET_TOKEN_EXPIRE_HOURS, - "link": link, - }, - ) - return EmailData(html_content=html_content, subject=subject) - - -def generate_new_account_email( - email_to: str, username: str, password: str -) -> EmailData: - project_name = settings.PROJECT_NAME - subject = f"{project_name} - New account for user {username}" - html_content = render_email_template( - template_name="new_account.html", - context={ - "project_name": settings.PROJECT_NAME, - "username": username, - "password": password, - "email": email_to, - "link": settings.FRONTEND_HOST, - }, - ) - return EmailData(html_content=html_content, subject=subject) - - -def generate_password_reset_token(email: str) -> str: - delta = timedelta(hours=settings.EMAIL_RESET_TOKEN_EXPIRE_HOURS) - now = datetime.now(UTC) - expires = now + delta - exp = expires.timestamp() - encoded_jwt = jwt.encode( - {"exp": exp, "nbf": now, "sub": email}, - settings.SECRET_KEY, - algorithm=security.ALGORITHM, - ) - return encoded_jwt - - -def verify_password_reset_token(token: str) -> str | None: - try: - decoded_token = jwt.decode( - token, settings.SECRET_KEY, algorithms=[security.ALGORITHM] - ) - return str(decoded_token["sub"]) - except InvalidTokenError: - return None diff --git a/backend/pyproject.toml b/backend/pyproject.toml index 7892d500d0..bfdd95a27a 100644 --- a/backend/pyproject.toml +++ b/backend/pyproject.toml @@ -16,8 +16,9 @@ dependencies = [ "sqlmodel>=0.0.46,<1.0.0", "pydantic-settings<3.0.0,>=2.2.1", "sentry-sdk[fastapi]>=2.70.0,<3.0.0", - "pyjwt>=2.15.0,<3.0.0", - "pwdlib[argon2,bcrypt]>=0.3.1", + "pyjwt[crypto]>=2.15.0,<3.0.0", + "alembic-utils>=0.8.8", + "pglast>=8.7", ] [dependency-groups] @@ -27,6 +28,7 @@ dev = [ "ty>=0.0.25", "ruff<1.0.0,>=0.16.0", "coverage<8.0.0,>=7.4.3", + "httpx2>=2.0.0", ] [build-system] @@ -34,6 +36,7 @@ requires = ["hatchling"] build-backend = "hatchling.build" [tool.mypy] +plugins = ["pydantic.mypy"] strict = true exclude = ["venv", ".venv", "alembic"] diff --git a/backend/scripts/export_openapi.py b/backend/scripts/export_openapi.py new file mode 100644 index 0000000000..2f6f528bb0 --- /dev/null +++ b/backend/scripts/export_openapi.py @@ -0,0 +1,30 @@ +"""Export the application's contract through FastAPI's native ``app.openapi``. + +Owner: app.main.app; consumed by scripts/generate-client.sh. +Dependency provenance: the FastAPI distribution and digests pinned in uv.lock. +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", required=True, type=Path) + parser.add_argument("--app", default="app.main:app") + args = parser.parse_args() + + from uvicorn.importer import import_from_string + + app = import_from_string(args.app) + + with args.output.open("w", encoding="utf-8") as stream: + json.dump(app.openapi(), stream, ensure_ascii=False, indent=2) + stream.write("\n") + + +if __name__ == "__main__": + main() diff --git a/backend/scripts/prestart.sh b/backend/scripts/prestart.sh index e67852ba07..704fa68d66 100644 --- a/backend/scripts/prestart.sh +++ b/backend/scripts/prestart.sh @@ -3,8 +3,6 @@ set -e set -x -# Run migrations -alembic upgrade head - -# Create initial data in DB -python app/initial_data.py +# API namespace only. This refuses to run without a reviewed API branch and +# distinct API_MIGRATION_DATABASE_URL; never replay the legacy public history. +alembic -c alembic-api.ini upgrade api@head diff --git a/backend/tests/api/routes/test_items.py b/backend/tests/api/routes/test_items.py index 3e82cd0134..54a1653247 100644 --- a/backend/tests/api/routes/test_items.py +++ b/backend/tests/api/routes/test_items.py @@ -1,164 +1,147 @@ -import uuid +import pytest -from fastapi.testclient import TestClient -from sqlmodel import Session -from app.core.config import settings -from tests.utils.item import create_random_item - - -def test_create_item( - client: TestClient, superuser_token_headers: dict[str, str] -) -> None: - data = {"title": "Foo", "description": "Fighters"} - response = client.post( - f"{settings.API_V1_STR}/items/", - headers=superuser_token_headers, - json=data, +def test_same_tenant_crud_and_post_commit_identity(client, fixture_actors, issue_token): + actor = fixture_actors["member"] + headers = issue_token(actor) + created = client.post( + "/api/v1/items/", + headers=headers, + json={"title": "Fixture item", "description": "Original"}, ) - assert response.status_code == 200 - content = response.json() - assert content["title"] == data["title"] - assert content["description"] == data["description"] - assert "id" in content - assert "owner_id" in content + assert created.status_code == 200 + item = created.json() + assert item["owner_id"] == actor["id"] + assert item["tenant_id"] == actor["tenant_id"] + url = f"/api/v1/items/{item['id']}" + assert client.get(url, headers=headers).json()["title"] == "Fixture item" + updated = client.put(url, headers=headers, json={"title": "Changed"}) + assert updated.status_code == 200 + assert updated.json()["title"] == "Changed" + assert updated.json()["owner_id"] == item["owner_id"] + assert updated.json()["tenant_id"] == item["tenant_id"] + deleted = client.delete(url, headers=headers) + assert deleted.status_code == 200 + assert client.get(url, headers=headers).status_code == 404 + + +@pytest.mark.parametrize("method", ["get", "put", "delete"]) +def test_foreign_tenant_admin_cannot_access_item( + client, fixture_actors, issue_token, method +): + owner = issue_token(fixture_actors["member"]) + created = client.post( + "/api/v1/items/", headers=owner, json={"title": "Private tenant fixture"} + ) + assert created.status_code == 200 + url = f"/api/v1/items/{created.json()['id']}" + kwargs = {"json": {"title": "Forbidden"}} if method == "put" else {} + response = getattr(client, method)( + url, headers=issue_token(fixture_actors["foreign_admin"]), **kwargs + ) + assert response.status_code == 404 + assert client.get(url, headers=owner).json()["title"] == "Private tenant fixture" -def test_read_item( - client: TestClient, superuser_token_headers: dict[str, str], db: Session -) -> None: - item = create_random_item(db) +def test_selected_tenant_admin_can_read_member_item( + client, fixture_actors, issue_token +): + created = client.post( + "/api/v1/items/", + headers=issue_token(fixture_actors["member"]), + json={"title": "Member fixture"}, + ) + assert created.status_code == 200 response = client.get( - f"{settings.API_V1_STR}/items/{item.id}", - headers=superuser_token_headers, + f"/api/v1/items/{created.json()['id']}", + headers=issue_token(fixture_actors["admin"]), ) assert response.status_code == 200 - content = response.json() - assert content["title"] == item.title - assert content["description"] == item.description - assert content["id"] == str(item.id) - assert content["owner_id"] == str(item.owner_id) -def test_read_item_not_found( - client: TestClient, superuser_token_headers: dict[str, str] -) -> None: - response = client.get( - f"{settings.API_V1_STR}/items/{uuid.uuid4()}", - headers=superuser_token_headers, +def test_member_cannot_read_another_owner_item(client, fixture_actors, issue_token): + created = client.post( + "/api/v1/items/", + headers=issue_token(fixture_actors["admin"]), + json={"title": "Other owner fixture"}, ) - assert response.status_code == 404 - content = response.json() - assert content["detail"] == "Item not found" - - -def test_read_item_not_enough_permissions( - client: TestClient, normal_user_token_headers: dict[str, str], db: Session -) -> None: - item = create_random_item(db) + assert created.status_code == 200 response = client.get( - f"{settings.API_V1_STR}/items/{item.id}", - headers=normal_user_token_headers, + f"/api/v1/items/{created.json()['id']}", + headers=issue_token(fixture_actors["member"]), ) - assert response.status_code == 403 - content = response.json() - assert content["detail"] == "Not enough permissions" + assert response.status_code == 404 -def test_read_items( - client: TestClient, superuser_token_headers: dict[str, str], db: Session -) -> None: - create_random_item(db) - create_random_item(db) +def test_selected_tenant_list_does_not_leak_foreign_items( + client, fixture_actors, issue_token +): + for name in ("member", "foreign_admin"): + assert ( + client.post( + "/api/v1/items/", + headers=issue_token(fixture_actors[name]), + json={"title": name}, + ).status_code + == 200 + ) response = client.get( - f"{settings.API_V1_STR}/items/", - headers=superuser_token_headers, + "/api/v1/items/", headers=issue_token(fixture_actors["admin"]) ) assert response.status_code == 200 - content = response.json() - assert len(content["data"]) >= 2 - - -def test_update_item( - client: TestClient, superuser_token_headers: dict[str, str], db: Session -) -> None: - item = create_random_item(db) - data = {"title": "Updated title", "description": "Updated description"} - response = client.put( - f"{settings.API_V1_STR}/items/{item.id}", - headers=superuser_token_headers, - json=data, + assert {item["tenant_id"] for item in response.json()["data"]} == { + fixture_actors["admin"]["tenant_id"] + } + + +@pytest.mark.parametrize("field", ["owner_id", "tenant_id"]) +def test_item_attribution_cannot_be_created_or_changed( + client, fixture_actors, issue_token, field +): + headers = issue_token(fixture_actors["member"]) + foreign = fixture_actors["foreign_admin"] + value = foreign["id"] if field == "owner_id" else foreign["tenant_id"] + denied = client.post( + "/api/v1/items/", + headers=headers, + json={"title": "Injected fixture", field: value}, ) - assert response.status_code == 200 - content = response.json() - assert content["title"] == data["title"] - assert content["description"] == data["description"] - assert content["id"] == str(item.id) - assert content["owner_id"] == str(item.owner_id) - - -def test_update_item_not_found( - client: TestClient, superuser_token_headers: dict[str, str] -) -> None: - data = {"title": "Updated title", "description": "Updated description"} - response = client.put( - f"{settings.API_V1_STR}/items/{uuid.uuid4()}", - headers=superuser_token_headers, - json=data, + assert denied.status_code == 422 + created = client.post( + "/api/v1/items/", headers=headers, json={"title": "Owned fixture"} ) - assert response.status_code == 404 - content = response.json() - assert content["detail"] == "Item not found" - - -def test_update_item_not_enough_permissions( - client: TestClient, normal_user_token_headers: dict[str, str], db: Session -) -> None: - item = create_random_item(db) - data = {"title": "Updated title", "description": "Updated description"} - response = client.put( - f"{settings.API_V1_STR}/items/{item.id}", - headers=normal_user_token_headers, - json=data, + assert created.status_code == 200 + assert ( + client.put( + f"/api/v1/items/{created.json()['id']}", + headers=headers, + json={field: value}, + ).status_code + == 422 ) - assert response.status_code == 403 - content = response.json() - assert content["detail"] == "Not enough permissions" - - -def test_delete_item( - client: TestClient, superuser_token_headers: dict[str, str], db: Session -) -> None: - item = create_random_item(db) - response = client.delete( - f"{settings.API_V1_STR}/items/{item.id}", - headers=superuser_token_headers, - ) - assert response.status_code == 200 - content = response.json() - assert content["message"] == "Item deleted successfully" -def test_delete_item_not_found( - client: TestClient, superuser_token_headers: dict[str, str] -) -> None: - response = client.delete( - f"{settings.API_V1_STR}/items/{uuid.uuid4()}", - headers=superuser_token_headers, +@pytest.mark.parametrize("actor_name", ["admin", "member"]) +def test_write_right_is_explicit_even_for_tenant_admin( + client, fixture_actors, issue_token, actor_name +): + headers = issue_token(fixture_actors[actor_name], permissions=["org:projects:read"]) + assert client.get("/api/v1/items/", headers=headers).status_code == 200 + assert ( + client.post( + "/api/v1/items/", headers=headers, json={"title": "Denied"} + ).status_code + == 403 ) - assert response.status_code == 404 - content = response.json() - assert content["detail"] == "Item not found" -def test_delete_item_not_enough_permissions( - client: TestClient, normal_user_token_headers: dict[str, str], db: Session -) -> None: - item = create_random_item(db) - response = client.delete( - f"{settings.API_V1_STR}/items/{item.id}", - headers=normal_user_token_headers, - ) - assert response.status_code == 403 - content = response.json() - assert content["detail"] == "Not enough permissions" +def test_consecutive_tenant_requests_reuse_pool_without_leaking_identity( + client, fixture_actors, issue_token +): + for name in ("admin", "foreign_admin", "member", "admin"): + response = client.get( + "/api/v1/users/me", headers=issue_token(fixture_actors[name]) + ) + assert response.status_code == 200 + assert response.json()["tenant_id"] == fixture_actors[name]["tenant_id"] + assert response.json()["id"] == fixture_actors[name]["id"] diff --git a/backend/tests/api/routes/test_login.py b/backend/tests/api/routes/test_login.py index 96677a25f6..ae4e3078a0 100644 --- a/backend/tests/api/routes/test_login.py +++ b/backend/tests/api/routes/test_login.py @@ -1,191 +1,83 @@ -from unittest.mock import patch - -from fastapi.testclient import TestClient -from pwdlib.hashers.bcrypt import BcryptHasher -from sqlmodel import Session +import pytest from app.core.config import settings -from app.core.security import get_password_hash, verify_password -from app.crud import create_user -from app.models import User, UserCreate -from app.utils import generate_password_reset_token -from tests.utils.user import user_authentication_headers -from tests.utils.utils import random_email, random_lower_string - - -def test_get_access_token(client: TestClient) -> None: - login_data = { - "username": settings.FIRST_SUPERUSER, - "password": settings.FIRST_SUPERUSER_PASSWORD, - } - r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data) - tokens = r.json() - assert r.status_code == 200 - assert "access_token" in tokens - assert tokens["access_token"] - -def test_get_access_token_incorrect_password(client: TestClient) -> None: - login_data = { - "username": settings.FIRST_SUPERUSER, - "password": "incorrect", - } - r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data) - assert r.status_code == 400 +FIXTURE_ACTOR = { + "subject": "user_fixture", + "organization_id": "org_fixture", + "user_role": "member", +} -def test_use_access_token( - client: TestClient, superuser_token_headers: dict[str, str] -) -> None: - r = client.post( - f"{settings.API_V1_STR}/login/test-token", - headers=superuser_token_headers, - ) - result = r.json() - assert r.status_code == 200 - assert "email" in result - - -def test_recovery_password( - client: TestClient, normal_user_token_headers: dict[str, str] -) -> None: - with ( - patch("app.core.config.settings.SMTP_HOST", "smtp.example.com"), - patch("app.core.config.settings.SMTP_USER", "admin@example.com"), - ): - email = "test@example.com" - r = client.post( - f"{settings.API_V1_STR}/password-recovery/{email}", - headers=normal_user_token_headers, - ) - assert r.status_code == 200 - assert r.json() == { - "message": "If that email is registered, we sent a password recovery link" - } - - -def test_recovery_password_user_not_exits( - client: TestClient, normal_user_token_headers: dict[str, str] -) -> None: - email = "jVgQr@example.com" - r = client.post( - f"{settings.API_V1_STR}/password-recovery/{email}", - headers=normal_user_token_headers, - ) - # Should return 200 with generic message to prevent email enumeration attacks - assert r.status_code == 200 - assert r.json() == { - "message": "If that email is registered, we sent a password recovery link" +def test_auth_config_is_public_and_safe(client): + response = client.get("/api/v1/auth/config") + assert response.status_code == 200 + assert response.json() == { + "client_id": "client_fixture", + "api_hostname": "auth.fixture.test", + "redirect_uri": "http://localhost:5173", } -def test_reset_password(client: TestClient, db: Session) -> None: - email = random_email() - password = random_lower_string() - new_password = random_lower_string() - - user_create = UserCreate( - email=email, - full_name="Test User", - password=password, - is_active=True, - is_superuser=False, +@pytest.mark.parametrize( + "path,method", + [ + ("/login/access-token", "post"), + ("/login/test-token", "post"), + ("/password-recovery/fixture@example.com", "post"), + ("/reset-password/", "post"), + ("/users/signup", "post"), + ("/users/me/password", "patch"), + ], +) +def test_password_authentication_surface_is_retired(client, path, method): + response = getattr(client, method)( + f"{settings.API_V1_STR}{path}", json={"password": "fixture"} ) - user = create_user(session=db, user_create=user_create) - token = generate_password_reset_token(email=email) - headers = user_authentication_headers(client=client, email=email, password=password) - data = {"new_password": new_password, "token": token} - - r = client.post( - f"{settings.API_V1_STR}/reset-password/", - headers=headers, - json=data, + assert response.status_code in (404, 405) + + +def test_missing_token_denied_before_sql(client): + response = client.get("/api/v1/users/me") + assert response.status_code == 401 + assert response.headers["www-authenticate"] == "Bearer" + + +@pytest.mark.parametrize( + "claims", + [ + {"iss": "https://foreign.fixture.test/"}, + {"client_id": "client_foreign"}, + {"exp": 1}, + {"sid": None}, + {"org_id": None}, + {"role": "admin"}, + {"user_role": None}, + {"permissions": [True]}, + ], +) +def test_invalid_signed_token_denied_before_sql(client, issue_token, claims): + response = client.get( + "/api/v1/users/me", headers=issue_token(FIXTURE_ACTOR, **claims) ) - - assert r.status_code == 200 - assert r.json() == {"message": "Password updated successfully"} - - db.refresh(user) - verified, _ = verify_password(new_password, user.hashed_password) - assert verified - - -def test_reset_password_invalid_token( - client: TestClient, superuser_token_headers: dict[str, str] -) -> None: - data = {"new_password": "changethis", "token": "invalid"} - r = client.post( - f"{settings.API_V1_STR}/reset-password/", - headers=superuser_token_headers, - json=data, - ) - response = r.json() - - assert "detail" in response - assert r.status_code == 400 - assert response["detail"] == "Invalid token" + assert response.status_code == 401 -def test_login_with_bcrypt_password_upgrades_to_argon2( - client: TestClient, db: Session -) -> None: - """Test that logging in with a bcrypt password hash upgrades it to argon2.""" - email = random_email() - password = random_lower_string() +def test_jwks_network_failure_denies_before_sql(client, issue_token, monkeypatch): + from urllib.error import URLError - # Create a bcrypt hash directly (simulating legacy password) - bcrypt_hasher = BcryptHasher() - bcrypt_hash = bcrypt_hasher.hash(password) - assert bcrypt_hash.startswith("$2") # bcrypt hashes start with $2 + from app.api import deps + from app.core.security import AccessTokenVerifier - user = User(email=email, hashed_password=bcrypt_hash, is_active=True) - db.add(user) - db.commit() - db.refresh(user) + headers = issue_token(FIXTURE_ACTOR) - assert user.hashed_password.startswith("$2") + def unavailable(*_args, **_kwargs): + raise URLError("Fixture JWKS unavailable") - login_data = {"username": email, "password": password} - r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data) - assert r.status_code == 200 - tokens = r.json() - assert "access_token" in tokens - - db.refresh(user) - - # Verify the hash was upgraded to argon2 - assert user.hashed_password.startswith("$argon2") - - verified, updated_hash = verify_password(password, user.hashed_password) - assert verified - # Should not need another update since it's already argon2 - assert updated_hash is None - - -def test_login_with_argon2_password_keeps_hash(client: TestClient, db: Session) -> None: - """Test that logging in with an argon2 password hash does not update it.""" - email = random_email() - password = random_lower_string() - - # Create an argon2 hash (current default) - argon2_hash = get_password_hash(password) - assert argon2_hash.startswith("$argon2") - - # Create user with argon2 hash - user = User(email=email, hashed_password=argon2_hash, is_active=True) - db.add(user) - db.commit() - db.refresh(user) - - original_hash = user.hashed_password - - login_data = {"username": email, "password": password} - r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data) - assert r.status_code == 200 - tokens = r.json() - assert "access_token" in tokens - - db.refresh(user) - - assert user.hashed_password == original_hash - assert user.hashed_password.startswith("$argon2") + monkeypatch.setattr("urllib.request.OpenerDirector.open", unavailable) + monkeypatch.setattr( + deps, "get_token_verifier", lambda: AccessTokenVerifier(settings) + ) + response = client.get("/api/v1/users/me", headers=headers) + assert response.status_code == 401 + assert response.json()["detail"] == "Unable to verify access token" diff --git a/backend/tests/api/routes/test_private.py b/backend/tests/api/routes/test_private.py index 1e1f985021..0944a20b99 100644 --- a/backend/tests/api/routes/test_private.py +++ b/backend/tests/api/routes/test_private.py @@ -1,26 +1,10 @@ -from fastapi.testclient import TestClient -from sqlmodel import Session, select - -from app.core.config import settings -from app.models import User - - -def test_create_user(client: TestClient, db: Session) -> None: - r = client.post( - f"{settings.API_V1_STR}/private/users/", +def test_unauthenticated_private_provisioning_is_retired(client): + response = client.post( + "/api/v1/private/users/", json={ - "email": "pollo@listo.com", - "password": "password123", - "full_name": "Pollo Listo", + "email": "fixture@example.com", + "password": "not-supported", + "full_name": "Untrusted fixture", }, ) - - assert r.status_code == 200 - - data = r.json() - - user = db.exec(select(User).where(User.id == data["id"])).first() - - assert user - assert user.email == "pollo@listo.com" - assert user.full_name == "Pollo Listo" + assert response.status_code in (404, 405) diff --git a/backend/tests/api/routes/test_users.py b/backend/tests/api/routes/test_users.py index 9c4cdd5991..431ae1a087 100644 --- a/backend/tests/api/routes/test_users.py +++ b/backend/tests/api/routes/test_users.py @@ -1,521 +1,367 @@ -import uuid -from unittest.mock import patch - -from fastapi.testclient import TestClient -from sqlmodel import Session, select - -from app import crud -from app.core.config import settings -from app.core.security import verify_password -from app.models import User, UserCreate -from tests.utils.user import create_random_user -from tests.utils.utils import random_email, random_lower_string - - -def test_get_users_superuser_me( - client: TestClient, superuser_token_headers: dict[str, str] -) -> None: - r = client.get(f"{settings.API_V1_STR}/users/me", headers=superuser_token_headers) - current_user = r.json() - assert current_user - assert current_user["is_active"] is True - assert current_user["is_superuser"] - assert current_user["email"] == settings.FIRST_SUPERUSER - - -def test_get_users_normal_user_me( - client: TestClient, normal_user_token_headers: dict[str, str] -) -> None: - r = client.get(f"{settings.API_V1_STR}/users/me", headers=normal_user_token_headers) - current_user = r.json() - assert current_user - assert current_user["is_active"] is True - assert current_user["is_superuser"] is False - assert current_user["email"] == settings.EMAIL_TEST_USER - - -def test_create_user_new_email( - client: TestClient, superuser_token_headers: dict[str, str], db: Session -) -> None: - with ( - patch("app.utils.send_email", return_value=None), - patch("app.core.config.settings.SMTP_HOST", "smtp.example.com"), - patch("app.core.config.settings.SMTP_USER", "admin@example.com"), - ): - username = random_email() - password = random_lower_string() - data = {"email": username, "password": password} - r = client.post( - f"{settings.API_V1_STR}/users/", - headers=superuser_token_headers, - json=data, - ) - assert 200 <= r.status_code < 300 - created_user = r.json() - user = crud.get_user_by_email(session=db, email=username) - assert user - assert user.email == created_user["email"] - - -def test_get_existing_user_as_superuser( - client: TestClient, superuser_token_headers: dict[str, str], db: Session -) -> None: - username = random_email() - password = random_lower_string() - user_in = UserCreate(email=username, password=password) - user = crud.create_user(session=db, user_create=user_in) - user_id = user.id - r = client.get( - f"{settings.API_V1_STR}/users/{user_id}", - headers=superuser_token_headers, - ) - assert 200 <= r.status_code < 300 - api_user = r.json() - existing_user = crud.get_user_by_email(session=db, email=username) - assert existing_user - assert existing_user.email == api_user["email"] - - -def test_get_non_existing_user_as_superuser( - client: TestClient, superuser_token_headers: dict[str, str] -) -> None: - r = client.get( - f"{settings.API_V1_STR}/users/{uuid.uuid4()}", - headers=superuser_token_headers, +from uuid import uuid4 + +import pytest + + +def test_me_preserves_local_actor_and_exposes_verified_role( + client, fixture_actors, issue_token +): + actor = fixture_actors["admin"] + response = client.get("/api/v1/users/me", headers=issue_token(actor)) + assert response.status_code == 200 + assert response.json()["id"] == actor["id"] + assert response.json()["tenant_id"] == actor["tenant_id"] + assert response.json()["identity_entity_id"] == actor["identity_entity_id"] + assert response.json()["user_role"] == "admin" + assert response.json()["is_tenant_admin"] is True + assert "is_superuser" not in response.json() + assert "hashed_password" not in response.json() + + +@pytest.mark.parametrize("method", ["get", "patch", "delete"]) +def test_admin_cannot_access_foreign_tenant_profile( + client, fixture_actors, issue_token, method +): + url = f"/api/v1/users/{fixture_actors['foreign_admin']['id']}" + kwargs = {"json": {"full_name": "Forbidden"}} if method == "patch" else {} + response = getattr(client, method)( + url, headers=issue_token(fixture_actors["admin"]), **kwargs ) - assert r.status_code == 404 - assert r.json() == {"detail": "User not found"} + assert response.status_code == 404 -def test_get_existing_user_current_user(client: TestClient, db: Session) -> None: - username = random_email() - password = random_lower_string() - user_in = UserCreate(email=username, password=password) - user = crud.create_user(session=db, user_create=user_in) - user_id = user.id - - login_data = { - "username": username, - "password": password, - } - r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data) - tokens = r.json() - a_token = tokens["access_token"] - headers = {"Authorization": f"Bearer {a_token}"} - - r = client.get( - f"{settings.API_V1_STR}/users/{user_id}", - headers=headers, - ) - assert 200 <= r.status_code < 300 - api_user = r.json() - existing_user = crud.get_user_by_email(session=db, email=username) - assert existing_user - assert existing_user.email == api_user["email"] - - -def test_get_existing_user_permissions_error( - db: Session, - client: TestClient, - normal_user_token_headers: dict[str, str], -) -> None: - user = create_random_user(db) - - r = client.get( - f"{settings.API_V1_STR}/users/{user.id}", - headers=normal_user_token_headers, - ) - assert r.status_code == 403 - assert r.json() == {"detail": "The user doesn't have enough privileges"} - - -def test_get_non_existing_user_permissions_error( - client: TestClient, - normal_user_token_headers: dict[str, str], -) -> None: - user_id = uuid.uuid4() - - r = client.get( - f"{settings.API_V1_STR}/users/{user_id}", - headers=normal_user_token_headers, - ) - assert r.status_code == 403 - assert r.json() == {"detail": "The user doesn't have enough privileges"} - - -def test_create_user_existing_username( - client: TestClient, superuser_token_headers: dict[str, str], db: Session -) -> None: - username = random_email() - # username = email - password = random_lower_string() - user_in = UserCreate(email=username, password=password) - crud.create_user(session=db, user_create=user_in) - data = {"email": username, "password": password} - r = client.post( - f"{settings.API_V1_STR}/users/", - headers=superuser_token_headers, - json=data, - ) - created_user = r.json() - assert r.status_code == 400 - assert "_id" not in created_user - - -def test_create_user_by_normal_user( - client: TestClient, normal_user_token_headers: dict[str, str] -) -> None: - username = random_email() - password = random_lower_string() - data = {"email": username, "password": password} - r = client.post( - f"{settings.API_V1_STR}/users/", - headers=normal_user_token_headers, - json=data, +def test_admin_list_is_selected_tenant_only(client, fixture_actors, issue_token): + response = client.get( + "/api/v1/users/", headers=issue_token(fixture_actors["admin"]) ) - assert r.status_code == 403 - - -def test_retrieve_users( - client: TestClient, superuser_token_headers: dict[str, str], db: Session -) -> None: - username = random_email() - password = random_lower_string() - user_in = UserCreate(email=username, password=password) - crud.create_user(session=db, user_create=user_in) - - username2 = random_email() - password2 = random_lower_string() - user_in2 = UserCreate(email=username2, password=password2) - crud.create_user(session=db, user_create=user_in2) - - r = client.get(f"{settings.API_V1_STR}/users/", headers=superuser_token_headers) - all_users = r.json() - - assert len(all_users["data"]) > 1 - assert "count" in all_users - for item in all_users["data"]: - assert "email" in item - - -def test_update_user_me( - client: TestClient, normal_user_token_headers: dict[str, str], db: Session -) -> None: - full_name = "Updated Name" - email = random_email() - data = {"full_name": full_name, "email": email} - r = client.patch( - f"{settings.API_V1_STR}/users/me", - headers=normal_user_token_headers, - json=data, - ) - assert r.status_code == 200 - updated_user = r.json() - assert updated_user["email"] == email - assert updated_user["full_name"] == full_name - - user_query = select(User).where(User.email == email) - user_db = db.exec(user_query).first() - assert user_db - assert user_db.email == email - assert user_db.full_name == full_name - - -def test_update_password_me( - client: TestClient, superuser_token_headers: dict[str, str], db: Session -) -> None: - new_password = random_lower_string() - data = { - "current_password": settings.FIRST_SUPERUSER_PASSWORD, - "new_password": new_password, + assert response.status_code == 200 + assert {user["tenant_id"] for user in response.json()["data"]} == { + fixture_actors["admin"]["tenant_id"] } - r = client.patch( - f"{settings.API_V1_STR}/users/me/password", - headers=superuser_token_headers, - json=data, - ) - assert r.status_code == 200 - updated_user = r.json() - assert updated_user["message"] == "Password updated successfully" - - user_query = select(User).where(User.email == settings.FIRST_SUPERUSER) - user_db = db.exec(user_query).first() - assert user_db - assert user_db.email == settings.FIRST_SUPERUSER - verified, _ = verify_password(new_password, user_db.hashed_password) - assert verified - - # Revert to the old password to keep consistency in test - old_data = { - "current_password": new_password, - "new_password": settings.FIRST_SUPERUSER_PASSWORD, + assert fixture_actors["foreign_admin"]["id"] not in { + u["id"] for u in response.json()["data"] } - r = client.patch( - f"{settings.API_V1_STR}/users/me/password", - headers=superuser_token_headers, - json=old_data, - ) - db.refresh(user_db) - assert r.status_code == 200 - verified, _ = verify_password( - settings.FIRST_SUPERUSER_PASSWORD, user_db.hashed_password + +@pytest.mark.parametrize( + "actor_name,overrides", + [ + ("revoked", {}), + ("admin", {"org_id": "org_unmapped_fixture"}), + ("admin", {"org_id": "FOREIGN"}), + ("admin", {"sub": "user_unknown_fixture"}), + ("member", {"user_role": "admin"}), + ], +) +def test_unknown_revoked_or_confused_identity_denied( + client, fixture_actors, issue_token, actor_name, overrides +): + if overrides.get("org_id") == "FOREIGN": + overrides = {"org_id": fixture_actors["foreign_admin"]["organization_id"]} + response = client.get( + "/api/v1/users/me", headers=issue_token(fixture_actors[actor_name], **overrides) ) - assert verified - - -def test_update_password_me_incorrect_password( - client: TestClient, superuser_token_headers: dict[str, str] -) -> None: - new_password = random_lower_string() - data = {"current_password": new_password, "new_password": new_password} - r = client.patch( - f"{settings.API_V1_STR}/users/me/password", - headers=superuser_token_headers, - json=data, + assert response.status_code == 403 + + +def test_email_never_autoprovisions_or_links_actor(client, fixture_actors, issue_token): + response = client.get( + "/api/v1/users/me", + headers=issue_token( + fixture_actors["admin"], + sub="user_unknown_fixture", + email=f"{fixture_actors['admin']['id']}@fixture.example.com", + ), ) - assert r.status_code == 400 - updated_user = r.json() - assert updated_user["detail"] == "Incorrect password" - - -def test_update_user_me_email_exists( - client: TestClient, normal_user_token_headers: dict[str, str], db: Session -) -> None: - username = random_email() - password = random_lower_string() - user_in = UserCreate(email=username, password=password) - user = crud.create_user(session=db, user_create=user_in) - - data = {"email": user.email} - r = client.patch( - f"{settings.API_V1_STR}/users/me", - headers=normal_user_token_headers, - json=data, + assert response.status_code == 403 + + +@pytest.mark.parametrize( + "field,value", + [ + ("tenant_id", "foreign_fixture"), + ("identity_entity_id", str(uuid4())), + ("is_superuser", True), + ("password", "not-a-local-password"), + ], +) +def test_profile_attribution_and_global_role_are_not_mutable( + client, fixture_actors, issue_token, field, value +): + response = client.patch( + "/api/v1/users/me", + headers=issue_token(fixture_actors["admin"]), + json={field: value}, ) - assert r.status_code == 409 - assert r.json()["detail"] == "User with this email already exists" + assert response.status_code == 422 -def test_update_password_me_same_password_error( - client: TestClient, superuser_token_headers: dict[str, str] -) -> None: - data = { - "current_password": settings.FIRST_SUPERUSER_PASSWORD, - "new_password": settings.FIRST_SUPERUSER_PASSWORD, - } - r = client.patch( - f"{settings.API_V1_STR}/users/me/password", - headers=superuser_token_headers, - json=data, - ) - assert r.status_code == 400 - updated_user = r.json() - assert ( - updated_user["detail"] == "New password cannot be the same as the current one" +def test_profile_admin_cannot_grant_membership_or_role( + client, fixture_actors, issue_token +): + admin = fixture_actors["admin"] + response = client.patch( + f"/api/v1/users/{fixture_actors['member']['id']}", + headers=issue_token(admin), + json={"user_role": "admin"}, ) + assert response.status_code == 422 -def test_register_user(client: TestClient, db: Session) -> None: - username = random_email() - password = random_lower_string() - full_name = random_lower_string() - data = {"email": username, "password": password, "full_name": full_name} - r = client.post( - f"{settings.API_V1_STR}/users/signup", - json=data, +def test_admin_create_requires_existing_same_tenant_canonical_actor( + client, fixture_actors, issue_token +): + headers = issue_token(fixture_actors["admin"]) + unknown = client.post( + "/api/v1/users/", + headers=headers, + json={ + "email": "unknown@fixture.example.com", + "identity_entity_id": str(uuid4()), + }, ) - assert r.status_code == 200 - created_user = r.json() - assert created_user["email"] == username - assert created_user["full_name"] == full_name - - user_query = select(User).where(User.email == username) - user_db = db.exec(user_query).first() - assert user_db - assert user_db.email == username - assert user_db.full_name == full_name - verified, _ = verify_password(password, user_db.hashed_password) - assert verified - - -def test_register_user_already_exists_error(client: TestClient) -> None: - password = random_lower_string() - full_name = random_lower_string() - data = { - "email": settings.FIRST_SUPERUSER, - "password": password, - "full_name": full_name, - } - r = client.post( - f"{settings.API_V1_STR}/users/signup", - json=data, + assert unknown.status_code == 403 + foreign = client.post( + "/api/v1/users/", + headers=headers, + json={ + "email": "foreign@fixture.example.com", + "identity_entity_id": fixture_actors["foreign_admin"]["identity_entity_id"], + }, ) - assert r.status_code == 400 - assert r.json()["detail"] == "The user with this email already exists in the system" - - -def test_update_user( - client: TestClient, superuser_token_headers: dict[str, str], db: Session -) -> None: - username = random_email() - password = random_lower_string() - user_in = UserCreate(email=username, password=password) - user = crud.create_user(session=db, user_create=user_in) - - data = {"full_name": "Updated_full_name"} - r = client.patch( - f"{settings.API_V1_STR}/users/{user.id}", - headers=superuser_token_headers, - json=data, + assert foreign.status_code == 403 + revoked = client.post( + "/api/v1/users/", + headers=headers, + json={ + "email": "revoked@fixture.example.com", + "identity_entity_id": fixture_actors["revoked"]["identity_entity_id"], + }, + ) + assert revoked.status_code == 200 + # A local profile does not grant or reactivate provider membership. + assert ( + client.get( + "/api/v1/users/me", headers=issue_token(fixture_actors["revoked"]) + ).status_code + == 403 ) - assert r.status_code == 200 - updated_user = r.json() - - assert updated_user["full_name"] == "Updated_full_name" - - user_query = select(User).where(User.email == username) - user_db = db.exec(user_query).first() - db.refresh(user_db) - assert user_db - assert user_db.full_name == "Updated_full_name" - - -def test_update_user_not_exists( - client: TestClient, superuser_token_headers: dict[str, str] -) -> None: - data = {"full_name": "Updated_full_name"} - r = client.patch( - f"{settings.API_V1_STR}/users/{uuid.uuid4()}", - headers=superuser_token_headers, - json=data, + actor = fixture_actors["unprofiled"] + response = client.post( + "/api/v1/users/", + headers=headers, + json={ + "email": "new-profile@fixture.example.com", + "identity_entity_id": actor["identity_entity_id"], + }, ) - assert r.status_code == 404 - assert r.json()["detail"] == "The user with this id does not exist in the system" - - -def test_update_user_email_exists( - client: TestClient, superuser_token_headers: dict[str, str], db: Session -) -> None: - username = random_email() - password = random_lower_string() - user_in = UserCreate(email=username, password=password) - user = crud.create_user(session=db, user_create=user_in) - - username2 = random_email() - password2 = random_lower_string() - user_in2 = UserCreate(email=username2, password=password2) - user2 = crud.create_user(session=db, user_create=user_in2) - - data = {"email": user2.email} - r = client.patch( - f"{settings.API_V1_STR}/users/{user.id}", - headers=superuser_token_headers, - json=data, + assert response.status_code == 200 + assert response.json()["identity_entity_id"] == actor["identity_entity_id"] + assert response.json()["tenant_id"] == actor["tenant_id"] + assert response.json()["id"] != actor["identity_entity_id"] + me = client.get("/api/v1/users/me", headers=issue_token(actor)) + assert me.status_code == 200 + assert me.json()["id"] == response.json()["id"] + + +def test_ordinary_member_cannot_administer_accounts( + client, fixture_actors, issue_token +): + response = client.get( + "/api/v1/users/", headers=issue_token(fixture_actors["member"]) ) - assert r.status_code == 409 - assert r.json()["detail"] == "User with this email already exists" + assert response.status_code == 403 -def test_delete_user_me(client: TestClient, db: Session) -> None: - username = random_email() - password = random_lower_string() - user_in = UserCreate(email=username, password=password) - user = crud.create_user(session=db, user_create=user_in) - user_id = user.id +def test_admin_without_business_permission_cannot_administer_accounts( + client, fixture_actors, issue_token +): + response = client.get( + "/api/v1/users/", headers=issue_token(fixture_actors["admin"], permissions=[]) + ) + assert response.status_code == 403 - login_data = { - "username": username, - "password": password, - } - r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data) - tokens = r.json() - a_token = tokens["access_token"] - headers = {"Authorization": f"Bearer {a_token}"} - r = client.delete( - f"{settings.API_V1_STR}/users/me", +def test_self_profile_roundtrip_survives_commit(client, fixture_actors, issue_token): + headers = issue_token(fixture_actors["member"]) + changed = client.patch( + "/api/v1/users/me", headers=headers, + json={"full_name": "Changed fixture profile"}, ) - assert r.status_code == 200 - deleted_user = r.json() - assert deleted_user["message"] == "User deleted successfully" - result = db.exec(select(User).where(User.id == user_id)).first() - assert result is None - - user_query = select(User).where(User.id == user_id) - user_db = db.execute(user_query).first() - assert user_db is None - - -def test_delete_user_me_as_superuser( - client: TestClient, superuser_token_headers: dict[str, str] -) -> None: - r = client.delete( - f"{settings.API_V1_STR}/users/me", - headers=superuser_token_headers, - ) - assert r.status_code == 403 - response = r.json() - assert response["detail"] == "Super users are not allowed to delete themselves" - - -def test_delete_user_super_user( - client: TestClient, superuser_token_headers: dict[str, str], db: Session -) -> None: - username = random_email() - password = random_lower_string() - user_in = UserCreate(email=username, password=password) - user = crud.create_user(session=db, user_create=user_in) - user_id = user.id - r = client.delete( - f"{settings.API_V1_STR}/users/{user_id}", - headers=superuser_token_headers, - ) - assert r.status_code == 200 - deleted_user = r.json() - assert deleted_user["message"] == "User deleted successfully" - result = db.exec(select(User).where(User.id == user_id)).first() - assert result is None - - -def test_delete_user_not_found( - client: TestClient, superuser_token_headers: dict[str, str] -) -> None: - r = client.delete( - f"{settings.API_V1_STR}/users/{uuid.uuid4()}", - headers=superuser_token_headers, + assert changed.status_code == 200 + response = client.get("/api/v1/users/me", headers=headers) + assert response.status_code == 200 + assert response.json()["full_name"] == "Changed fixture profile" + + +def test_caller_tenant_header_does_not_select_identity( + client, fixture_actors, issue_token +): + actor = fixture_actors["admin"] + headers = issue_token(actor) | { + "X-Tenant-ID": fixture_actors["foreign_admin"]["tenant_id"] + } + response = client.get("/api/v1/users/me", headers=headers) + assert response.status_code == 200 + assert response.json()["tenant_id"] == actor["tenant_id"] + assert response.json()["id"] == actor["id"] + + +def test_deactivated_local_actor_cannot_authenticate( + client, fixture_actors, issue_token +): + actor = fixture_actors["member"] + response = client.patch( + f"/api/v1/users/{actor['id']}", + headers=issue_token(fixture_actors["admin"]), + json={"is_active": False}, ) - assert r.status_code == 404 - assert r.json()["detail"] == "User not found" - - -def test_delete_user_current_super_user_error( - client: TestClient, superuser_token_headers: dict[str, str], db: Session -) -> None: - super_user = crud.get_user_by_email(session=db, email=settings.FIRST_SUPERUSER) - assert super_user - user_id = super_user.id - - r = client.delete( - f"{settings.API_V1_STR}/users/{user_id}", - headers=superuser_token_headers, + assert response.status_code == 200 + assert client.get("/api/v1/users/me", headers=issue_token(actor)).status_code == 403 + + +@pytest.mark.parametrize("operation", ["self_update", "admin_update", "create"]) +def test_same_tenant_profile_email_collision_returns_existing_conflict( + client, fixture_actors, issue_token, operation +): + admin_headers = issue_token(fixture_actors["admin"]) + member_headers = issue_token(fixture_actors["member"]) + admin = client.get("/api/v1/users/me", headers=admin_headers).json() + member_before = client.get("/api/v1/users/me", headers=member_headers).json() + if operation == "self_update": + # RLS deliberately hides the administrator's profile from this member. + response = client.patch( + "/api/v1/users/me", headers=member_headers, json={"email": admin["email"]} + ) + elif operation == "admin_update": + response = client.patch( + f"/api/v1/users/{fixture_actors['member']['id']}", + headers=admin_headers, + json={"email": admin["email"]}, + ) + else: + response = client.post( + "/api/v1/users/", + headers=admin_headers, + json={ + "email": admin["email"], + "identity_entity_id": fixture_actors["unprofiled"][ + "identity_entity_id" + ], + }, + ) + assert response.status_code == 409 + assert response.json() == { + "detail": "User with this email already exists in this tenant" + } + # The failed native write must roll back, leaving the actor and pooled + # connection usable without widening member profile visibility. + member_after = client.get("/api/v1/users/me", headers=member_headers) + assert member_after.status_code == 200 + assert member_after.json()["email"] == member_before["email"] + + +@pytest.mark.parametrize("operation", ["self_update", "admin_update", "create"]) +def test_profile_email_uniqueness_allows_existing_foreign_tenant_email( + client, fixture_actors, issue_token, operation +): + admin_headers = issue_token(fixture_actors["admin"]) + foreign = client.get( + "/api/v1/users/me", headers=issue_token(fixture_actors["foreign_admin"]) + ).json() + if operation == "self_update": + response = client.patch( + "/api/v1/users/me", + headers=issue_token(fixture_actors["member"]), + json={"email": foreign["email"]}, + ) + elif operation == "admin_update": + response = client.patch( + f"/api/v1/users/{fixture_actors['member']['id']}", + headers=admin_headers, + json={"email": foreign["email"]}, + ) + else: + response = client.post( + "/api/v1/users/", + headers=admin_headers, + json={ + "email": foreign["email"], + "identity_entity_id": fixture_actors["unprofiled"][ + "identity_entity_id" + ], + }, + ) + assert response.status_code == 200 + assert response.json()["email"] == foreign["email"] + assert response.json()["tenant_id"] == fixture_actors["admin"]["tenant_id"] + assert response.json()["tenant_id"] != foreign["tenant_id"] + + +def test_admin_self_deactivation_returns_committed_state( + client, fixture_actors, issue_token +): + actor = fixture_actors["admin"] + headers = issue_token(actor) + response = client.patch( + f"/api/v1/users/{actor['id']}", + headers=headers, + json={"is_active": False}, ) - assert r.status_code == 403 - assert r.json()["detail"] == "Super users are not allowed to delete themselves" - - -def test_delete_user_without_privileges( - client: TestClient, normal_user_token_headers: dict[str, str], db: Session -) -> None: - username = random_email() - password = random_lower_string() - user_in = UserCreate(email=username, password=password) - user = crud.create_user(session=db, user_create=user_in) + assert response.status_code == 200 + assert response.json()["is_active"] is False + assert client.get("/api/v1/users/me", headers=headers).status_code == 403 + + +def test_concurrent_canonical_profile_creation_returns_existing_conflict( + client, fixture_actors, issue_token, runtime_engine, monkeypatch +): + from concurrent.futures import ThreadPoolExecutor + from threading import Barrier + + from sqlmodel import create_engine + + from app import crud + from app.api import deps + + engine = create_engine(runtime_engine.url, pool_size=2, max_overflow=0) + monkeypatch.setattr(deps, "engine", engine) + headers = issue_token(fixture_actors["admin"]) + original_lookup = crud.get_user_by_email + both_prechecks_complete = Barrier(2) + + def synchronized_lookup(**kwargs): + result = original_lookup(**kwargs) + both_prechecks_complete.wait(timeout=30) + return result + + monkeypatch.setattr(crud, "get_user_by_email", synchronized_lookup) + + def create_profile(email): + return client.post( + "/api/v1/users/", + headers=headers, + json={ + "email": email, + "identity_entity_id": fixture_actors["unprofiled"][ + "identity_entity_id" + ], + }, + ) - r = client.delete( - f"{settings.API_V1_STR}/users/{user.id}", - headers=normal_user_token_headers, - ) - assert r.status_code == 403 - assert r.json()["detail"] == "The user doesn't have enough privileges" + try: + with ThreadPoolExecutor(max_workers=2) as executor: + responses = list( + executor.map( + create_profile, + ["first@fixture.example.com", "second@fixture.example.com"], + ) + ) + assert sorted(response.status_code for response in responses) == [200, 409] + conflict = next( + response for response in responses if response.status_code == 409 + ) + assert conflict.json() == {"detail": "Local actor profile already exists"} + finally: + engine.dispose() diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 7cdabf3c45..1dd0a30da3 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -1,42 +1,163 @@ +"""Explicit fixture configuration; never import a production runtime environment. + +SQL integration cases require a preprovisioned isolated product baseline, the API +namespace branch, and API_TEST_ACTORS (JSON fixture actors). No schema creation, +canonical identity seed, or global table cleanup is performed by this suite. +""" + +import json +import os from collections.abc import Generator +from datetime import UTC, datetime, timedelta +from uuid import UUID, uuid4 +import jwt import pytest -from fastapi.testclient import TestClient +from cryptography.hazmat.primitives.asymmetric import rsa +from jwt import PyJWK from sqlmodel import Session, delete +# Always isolate auth/settings even for tests not requiring PostgreSQL. A real +# integration target is selected ONLY by the dedicated fixture below. +os.environ.update( + { + "PROJECT_NAME": "API fixture", + "DATABASE_URL": "postgresql+psycopg://fixture:fixture@localhost/api_test_unconfigured", + "FRONTEND_HOST": "http://localhost:5173", + "FASTAPI_ENV": "development", + "WORKOS_CLIENT_ID": "client_fixture", + "WORKOS_ISSUER": "https://auth.fixture.test/", + "WORKOS_JWKS_URL": "https://auth.fixture.test/sso/jwks/client_fixture", + "WORKOS_API_HOSTNAME": "auth.fixture.test", + } +) + +from fastapi.testclient import TestClient + +from app.api import deps from app.core.config import settings -from app.core.db import engine, init_db +from app.core.security import AccessTokenVerifier from app.main import app from app.models import Item, User -from tests.utils.user import authentication_token_from_email -from tests.utils.utils import get_superuser_token_headers +from tests.test_data_namespace import isolated_data_engine -@pytest.fixture(scope="session", autouse=True) -def db() -> Generator[Session]: - with Session(engine) as session: - init_db(session) - yield session - statement = delete(Item) - session.execute(statement) - statement = delete(User) - session.execute(statement) - session.commit() +@pytest.fixture +def client() -> Generator[TestClient]: + with TestClient(app) as value: + yield value -@pytest.fixture(scope="module") -def client() -> Generator[TestClient]: - with TestClient(app) as c: - yield c +@pytest.fixture +def fixture_claims(): + def build(actor, **overrides): + now = datetime.now(UTC) + return { + "iss": settings.WORKOS_ISSUER, + "client_id": settings.WORKOS_CLIENT_ID, + "sub": actor["subject"], + "sid": "session_fixture", + "org_id": actor["organization_id"], + "role": "authenticated", + "user_role": actor["user_role"], + "permissions": ["org:projects:read", "org:projects:write"], + "iat": int(now.timestamp()), + "exp": int((now + timedelta(minutes=5)).timestamp()), + } | overrides + + return build + +@pytest.fixture +def issue_token(monkeypatch, fixture_claims): + key = rsa.generate_private_key(public_exponent=65537, key_size=2048) + jwk = PyJWK.from_json(jwt.algorithms.RSAAlgorithm.to_jwk(key.public_key())) -@pytest.fixture(scope="module") -def superuser_token_headers(client: TestClient) -> dict[str, str]: - return get_superuser_token_headers(client) + class FixtureKeys: + def get_signing_key_from_jwt(self, _token: str) -> PyJWK: + return jwk + verifier = AccessTokenVerifier(settings, jwks_client=FixtureKeys()) + monkeypatch.setattr(deps, "get_token_verifier", lambda: verifier) -@pytest.fixture(scope="module") -def normal_user_token_headers(client: TestClient, db: Session) -> dict[str, str]: - return authentication_token_from_email( - client=client, email=settings.EMAIL_TEST_USER, db=db - ) + def issue(actor, **overrides): + claims = fixture_claims(actor, **overrides) + return { + "Authorization": "Bearer " + + jwt.encode( + {k: v for k, v in claims.items() if v is not None}, + key, + algorithm="RS256", + headers={"kid": "fixture"}, + ) + } + + return issue + + +@pytest.fixture +def runtime_engine(monkeypatch): + engine = isolated_data_engine("API_TEST_DATABASE_URL") + monkeypatch.setattr(deps, "engine", engine) + try: + yield engine + finally: + engine.dispose() + + +@pytest.fixture +def canonical_actors(): + raw = os.environ.get("API_TEST_ACTORS") + if not raw: + pytest.fail( + "API_TEST_ACTORS must provide admin, member, foreign_admin, unprofiled, revoked fixture actors from the isolated canonical baseline" + ) + return json.loads(raw) + + +@pytest.fixture +def fixture_actors(request: pytest.FixtureRequest, canonical_actors): + """Use existing fixture-only canonical actors; create only API-local profiles.""" + request.getfixturevalue("runtime_engine") + actors = canonical_actors + admin_engine = isolated_data_engine("API_TEST_ADMIN_DATABASE_URL") + created_ids = [] + with Session(admin_engine) as session: + for name in ("admin", "member", "foreign_admin"): + actor = actors[name] + user_id = uuid4() + actor["id"] = str(user_id) + session.add( + User( + id=user_id, + tenant_id=actor["tenant_id"], + identity_entity_id=UUID(actor["identity_entity_id"]), + email=f"{user_id}@fixture.example.com", + full_name=f"Fixture {name}", + ) + ) + created_ids.append(user_id) + session.commit() + try: + yield actors + finally: + with Session(admin_engine) as session: + # Explicit fixture targets may gain local profiles, never memberships. + session.exec(delete(Item).where(Item.owner_id.in_(created_ids))) + session.exec(delete(User).where(User.id.in_(created_ids))) + for name in ("unprofiled", "revoked"): + session.exec( + delete(User).where( + User.tenant_id == actors[name]["tenant_id"], + User.identity_entity_id + == UUID(actors[name]["identity_entity_id"]), + ) + ) + session.commit() + admin_engine.dispose() + + +@pytest.fixture +def db(runtime_engine): + with Session(runtime_engine) as session: + yield session diff --git a/backend/tests/crud/test_user.py b/backend/tests/crud/test_user.py index 3db77ef624..27572eb7f0 100644 --- a/backend/tests/crud/test_user.py +++ b/backend/tests/crud/test_user.py @@ -1,130 +1,135 @@ -from fastapi.encoders import jsonable_encoder -from pwdlib.hashers.bcrypt import BcryptHasher -from sqlmodel import Session - -from app import crud -from app.core.security import verify_password -from app.models import User, UserCreate, UserUpdate -from tests.utils.utils import random_email, random_lower_string - - -def test_create_user(db: Session) -> None: - email = random_email() - password = random_lower_string() - user_in = UserCreate(email=email, password=password) - user = crud.create_user(session=db, user_create=user_in) - assert user.email == email - assert hasattr(user, "hashed_password") - - -def test_authenticate_user(db: Session) -> None: - email = random_email() - password = random_lower_string() - user_in = UserCreate(email=email, password=password) - user = crud.create_user(session=db, user_create=user_in) - authenticated_user = crud.authenticate(session=db, email=email, password=password) - assert authenticated_user - assert user.email == authenticated_user.email - - -def test_not_authenticate_user(db: Session) -> None: - email = random_email() - password = random_lower_string() - user = crud.authenticate(session=db, email=email, password=password) - assert user is None - - -def test_check_if_user_is_active(db: Session) -> None: - email = random_email() - password = random_lower_string() - user_in = UserCreate(email=email, password=password) - user = crud.create_user(session=db, user_create=user_in) - assert user.is_active is True - - -def test_check_if_user_is_active_inactive(db: Session) -> None: - email = random_email() - password = random_lower_string() - user_in = UserCreate(email=email, password=password, is_active=False) - user = crud.create_user(session=db, user_create=user_in) - assert user.is_active is False - - -def test_check_if_user_is_superuser(db: Session) -> None: - email = random_email() - password = random_lower_string() - user_in = UserCreate(email=email, password=password, is_superuser=True) - user = crud.create_user(session=db, user_create=user_in) - assert user.is_superuser is True - - -def test_check_if_user_is_superuser_normal_user(db: Session) -> None: - username = random_email() - password = random_lower_string() - user_in = UserCreate(email=username, password=password) - user = crud.create_user(session=db, user_create=user_in) - assert user.is_superuser is False - - -def test_get_user(db: Session) -> None: - password = random_lower_string() - username = random_email() - user_in = UserCreate(email=username, password=password, is_superuser=True) - user = crud.create_user(session=db, user_create=user_in) - user_2 = db.get(User, user.id) - assert user_2 - assert user.email == user_2.email - assert jsonable_encoder(user) == jsonable_encoder(user_2) - - -def test_update_user(db: Session) -> None: - password = random_lower_string() - email = random_email() - user_in = UserCreate(email=email, password=password, is_superuser=True) - user = crud.create_user(session=db, user_create=user_in) - new_password = random_lower_string() - user_in_update = UserUpdate(password=new_password, is_superuser=True) - if user.id is not None: - crud.update_user(session=db, db_user=user, user_in=user_in_update) - user_2 = db.get(User, user.id) - assert user_2 - assert user.email == user_2.email - verified, _ = verify_password(new_password, user_2.hashed_password) - assert verified - - -def test_authenticate_user_with_bcrypt_upgrades_to_argon2(db: Session) -> None: - """Test that a user with bcrypt password hash gets upgraded to argon2 on login.""" - email = random_email() - password = random_lower_string() - - # Create a bcrypt hash directly (simulating legacy password) - bcrypt_hasher = BcryptHasher() - bcrypt_hash = bcrypt_hasher.hash(password) - assert bcrypt_hash.startswith("$2") # bcrypt hashes start with $2 - - # Create user with bcrypt hash directly in the database - user = User(email=email, hashed_password=bcrypt_hash) - db.add(user) - db.commit() - db.refresh(user) - - # Verify the hash is bcrypt before authentication - assert user.hashed_password.startswith("$2") - - # Authenticate - this should upgrade the hash to argon2 - authenticated_user = crud.authenticate(session=db, email=email, password=password) - assert authenticated_user - assert authenticated_user.email == email - - db.refresh(authenticated_user) - - # Verify the hash was upgraded to argon2 - assert authenticated_user.hashed_password.startswith("$argon2") - - verified, updated_hash = verify_password( - password, authenticated_user.hashed_password +import json +from uuid import UUID + +import pytest +from sqlalchemy import text +from sqlalchemy.exc import DBAPIError +from sqlmodel import select + +from app.api import deps +from app.core.auth import VerifiedSession, resolve_principal +from app.models import Item, User + + +def verified_session(runtime_engine, issue_token, actor, **claims): + encoded = issue_token(actor, **claims)["Authorization"].removeprefix("Bearer ") + token = deps.get_token_verifier().verify(encoded) + return VerifiedSession(runtime_engine, info={"verified_token": token}), token + + +def test_identity_reinstalled_on_every_transaction_and_cleared_on_pool_return( + runtime_engine, fixture_actors, issue_token +): + actor = fixture_actors["admin"] + session, token = verified_session(runtime_engine, issue_token, actor) + with session: + principal = resolve_principal(session, token) + for _ in range(3): + session.commit() + claims = json.loads( + session.execute( + text("SELECT current_setting('request.jwt.claims')") + ).scalar_one() + ) + assert claims["sub"] == actor["subject"] + assert claims["org_id"] == actor["organization_id"] + assert claims["api_tenant_id"] == actor["tenant_id"] + assert claims["api_user_id"] == str(principal.user.id) + assert ( + session.execute(text("SELECT current_user")).scalar_one() + == "authenticated" + ) + # Post-commit ORM expiry uses the same actual listener boundary. + assert session.get(User, UUID(actor["id"])).tenant_id == actor["tenant_id"] + with runtime_engine.connect() as connection: + current, original, claims = connection.execute( + text( + "SELECT current_user, session_user, current_setting('request.jwt.claims', true)" + ) + ).one() + assert current == original + assert claims in (None, "") + + +def test_signed_api_claims_cannot_spoof_local_actor( + runtime_engine, fixture_actors, issue_token +): + actor = fixture_actors["member"] + foreign = fixture_actors["foreign_admin"] + session, token = verified_session( + runtime_engine, + issue_token, + actor, + api_user_id=foreign["id"], + api_tenant_id=foreign["tenant_id"], + api_identity_entity_id=foreign["identity_entity_id"], + ) + with session: + principal = resolve_principal(session, token) + assert str(principal.user.id) == actor["id"] + claims = json.loads( + session.execute( + text("SELECT current_setting('request.jwt.claims')") + ).scalar_one() + ) + assert claims["api_user_id"] == actor["id"] + assert claims["api_tenant_id"] == actor["tenant_id"] + + +def test_direct_sql_does_not_bypass_tenant_rls( + runtime_engine, fixture_actors, issue_token, client +): + owner = fixture_actors["foreign_admin"] + created = client.post( + "/api/v1/items/", + headers=issue_token(owner), + json={"title": "Foreign direct SQL fixture"}, + ) + assert created.status_code == 200 + session, token = verified_session( + runtime_engine, issue_token, fixture_actors["admin"] + ) + with session: + resolve_principal(session, token) + assert ( + session.exec( + select(Item).where(Item.id == UUID(created.json()["id"])) + ).first() + is None + ) + assert ( + session.exec(select(User).where(User.id == UUID(owner["id"]))).first() + is None + ) + + +def test_database_rejects_item_tenant_or_owner_reassignment( + runtime_engine, fixture_actors, issue_token, client +): + actor = fixture_actors["member"] + created = client.post( + "/api/v1/items/", + headers=issue_token(actor), + json={"title": "Immutable direct SQL fixture"}, + ) + assert created.status_code == 200 + session, token = verified_session(runtime_engine, issue_token, actor) + with session: + resolve_principal(session, token) + item = session.get(Item, UUID(created.json()["id"])) + assert item is not None + item.tenant_id = fixture_actors["foreign_admin"]["tenant_id"] + with pytest.raises(DBAPIError): + session.commit() + session.rollback() + session, token = verified_session( + runtime_engine, issue_token, fixture_actors["admin"] ) - assert verified - # Should not need another update since it's already argon2 - assert updated_hash is None + with session: + resolve_principal(session, token) + item = session.get(Item, UUID(created.json()["id"])) + assert item is not None + item.owner_id = UUID(fixture_actors["admin"]["id"]) + with pytest.raises(DBAPIError): + session.commit() + session.rollback() diff --git a/backend/tests/test_data_namespace.py b/backend/tests/test_data_namespace.py new file mode 100644 index 0000000000..1952e35c0c --- /dev/null +++ b/backend/tests/test_data_namespace.py @@ -0,0 +1,145 @@ +"""API-owned model contracts; fixtures are not production identity evidence.""" + +import os +import uuid + +import pytest +from pydantic import ValidationError +from sqlalchemy import create_engine, text +from sqlalchemy.engine import make_url + +from app.models import ( + ItemCreate, + ItemUpdate, + UserCreate, + UserUpdate, + UserUpdateMe, +) + + +def isolated_data_engine(variable: str): + """Admit a real isolated target before fixture data writes are possible.""" + value = os.environ.get(variable) + if not value: + pytest.fail(f"{variable} must explicitly select an isolated PostgreSQL target") + url = make_url(value) + known_estate_refs = {"irlknjrfypumpsqbeaqi", "mflwqmffctzvwyjiafyj"} + host = (url.host or "").lower() + username = (url.username or "").lower() + if url.get_backend_name() != "postgresql" or any( + reference in host or reference in username for reference in known_estate_refs + ): + pytest.fail(f"{variable} cannot target an estate production/staging project") + branch = os.environ.get("API_TEST_SUPABASE_BRANCH_REF") + preview = bool( + branch + and branch not in known_estate_refs + and (host == f"db.{branch}.supabase.co" or username.endswith(f".{branch}")) + ) + dedicated = bool(url.database and url.database.startswith("api_test_")) + if not dedicated and not preview: + pytest.fail( + f"{variable} requires an api_test_* database or explicitly selected Supabase preview branch" + ) + engine = create_engine( + url, pool_size=1, max_overflow=0, pool_reset_on_return="rollback" + ) + try: + with engine.connect() as connection: + actual_database = connection.scalar(text("SELECT current_database()")) + if actual_database != url.database: + pytest.fail( + f"{variable} selected database does not match PostgreSQL current_database()" + ) + except BaseException: + engine.dispose() + raise + return engine + + +def test_user_creation_requires_canonical_actor_without_authority_inputs() -> None: + actor = uuid.uuid4() + profile = UserCreate(email="fixture@example.com", identity_entity_id=actor) + assert profile.identity_entity_id == actor + for field, value in [ + ("password", "unsafe-password"), + ("is_superuser", True), + ("tenant_id", str(uuid.uuid4())), + ]: + with pytest.raises(ValidationError): + UserCreate.model_validate({**profile.model_dump(), field: value}) + + +def test_profile_update_cannot_change_actor_or_tenant() -> None: + for field in ("tenant_id", "identity_entity_id", "is_superuser", "password"): + with pytest.raises(ValidationError): + UserUpdate.model_validate({field: str(uuid.uuid4())}) + + +def test_item_input_cannot_override_attribution() -> None: + for field in ("tenant_id", "owner_id"): + with pytest.raises(ValidationError): + ItemCreate.model_validate({"title": "fixture", field: str(uuid.uuid4())}) + + +@pytest.mark.parametrize( + "model,field", + [ + (UserUpdate, "email"), + (UserUpdate, "is_active"), + (UserUpdateMe, "email"), + (ItemUpdate, "title"), + ], +) +def test_partial_update_rejects_null_required_fields_but_accepts_omission( + model, field +) -> None: + assert model.model_validate({}).model_dump(exclude_unset=True) == {} + with pytest.raises(ValidationError): + model.model_validate({field: None}) + + +def test_partial_update_preserves_explicit_nullable_field_clearing() -> None: + assert UserUpdateMe(full_name=None).model_dump(exclude_unset=True) == { + "full_name": None + } + assert ItemUpdate(description=None).model_dump(exclude_unset=True) == { + "description": None + } + + +@pytest.mark.parametrize( + "url,branch", + [ + ( + "postgresql+psycopg://postgres@db.irlknjrfypumpsqbeaqi.supabase.co/postgres", + "irlknjrfypumpsqbeaqi", + ), + ( + "postgresql+psycopg://postgres@db.mflwqmffctzvwyjiafyj.supabase.co/api_test_named", + "fixturebranchreference", + ), + ("postgresql+psycopg://postgres@localhost/postgres", ""), + ( + "postgresql+psycopg://postgres.irlknjrfypumpsqbeaqi@pooler.supabase.com/api_test_named", + "", + ), + ], +) +def test_data_fixture_refuses_unisolated_or_estate_targets( + monkeypatch, url, branch +) -> None: + monkeypatch.setenv("API_TEST_TARGET_GUARD", url) + monkeypatch.setenv("API_TEST_SUPABASE_BRANCH_REF", branch) + monkeypatch.setenv("API_TEST_ISOLATED_BRANCH_APPROVED", "true") + with pytest.raises(pytest.fail.Exception): + isolated_data_engine("API_TEST_TARGET_GUARD") + + +if __name__ == "__main__": + for variable in ( + "API_TEST_MIGRATION_DATABASE_URL", + "API_TEST_DATABASE_URL", + "API_TEST_ADMIN_DATABASE_URL", + ): + isolated_data_engine(variable).dispose() diff --git a/backend/tests/test_data_namespace_postgresql.py b/backend/tests/test_data_namespace_postgresql.py new file mode 100644 index 0000000000..d73a653122 --- /dev/null +++ b/backend/tests/test_data_namespace_postgresql.py @@ -0,0 +1,59 @@ +"""Run only on the explicitly admitted isolated PostgreSQL acceptance branch. + +The caller supplies existing canonical fixture UUIDs. These tests never create +canonical objects, create a stack, apply migrations, or use a production URL. +""" + +import uuid + +import pytest +from sqlalchemy import select +from sqlalchemy.exc import IntegrityError +from sqlmodel import Session + +from app.models import Item, User +from tests.test_data_namespace import isolated_data_engine + + +@pytest.fixture +def isolated_data_session(): + engine = isolated_data_engine("API_TEST_MIGRATION_DATABASE_URL") + with engine.connect() as connection: + transaction = connection.begin() + with Session( + bind=connection, join_transaction_mode="create_savepoint" + ) as session: + yield session + transaction.rollback() + engine.dispose() + + +def test_postgresql_rejects_foreign_tenant_item_owner( + isolated_data_session, canonical_actors +): + session = isolated_data_session + tenant_id = canonical_actors["admin"]["tenant_id"] + foreign_tenant = canonical_actors["foreign_admin"]["tenant_id"] + actor = uuid.UUID(canonical_actors["admin"]["identity_entity_id"]) + user = User( + email="constraint-fixture@example.com", + tenant_id=tenant_id, + identity_entity_id=actor, + ) + session.add(user) + session.flush() + with pytest.raises(IntegrityError): + with session.begin_nested(): + session.add( + Item(title="foreign", owner_id=user.id, tenant_id=foreign_tenant) + ) + session.flush() + item = Item(title="same tenant", owner_id=user.id, tenant_id=tenant_id) + session.add(item) + session.flush() + assert ( + session.exec(select(Item).where(Item.id == item.id)).scalar_one().tenant_id + == tenant_id + ) + session.refresh(item) + assert item.created_at.utcoffset() is not None diff --git a/backend/tests/test_data_rls_postgresql.py b/backend/tests/test_data_rls_postgresql.py new file mode 100644 index 0000000000..f3bf66b922 --- /dev/null +++ b/backend/tests/test_data_rls_postgresql.py @@ -0,0 +1,407 @@ +"""Behavioral RLS acceptance input for an explicitly admitted PostgreSQL fixture. + +Canonical tenants, actors, WorkOS projections and the cutover gate must already +exist under their fixture owner. Nothing here establishes production readiness. +""" + +import json +import uuid + +import pytest +from sqlalchemy import delete, insert, select, text, update +from sqlalchemy.exc import DBAPIError, IntegrityError + +from app.models import Item, User, get_datetime_utc +from tests.test_data_namespace import isolated_data_engine + + +@pytest.fixture +def rls_fixture(canonical_actors, fixture_claims): + migration = isolated_data_engine("API_TEST_MIGRATION_DATABASE_URL") + runtime = isolated_data_engine("API_TEST_DATABASE_URL") + assert migration.url.username != runtime.url.username + with runtime.connect() as connection: + login_authority = connection.execute( + text( + "SELECT rolsuper, rolbypassrls FROM pg_roles WHERE rolname = session_user" + ) + ).one() + assert login_authority == (False, False) + user_id, foreign_user_id, item_id, foreign_item_id = ( + uuid.uuid4() for _ in range(4) + ) + tenant_id = canonical_actors["admin"]["tenant_id"] + foreign_tenant = canonical_actors["foreign_admin"]["tenant_id"] + actor = uuid.UUID(canonical_actors["admin"]["identity_entity_id"]) + foreign_actor = uuid.UUID(canonical_actors["foreign_admin"]["identity_entity_id"]) + claims = fixture_claims(canonical_actors["admin"]) + claims.update( + api_user_id=str(user_id), + api_identity_entity_id=str(actor), + api_tenant_id=tenant_id, + ) + with migration.begin() as connection: + connection.execute( + insert(User), + [ + { + "id": user_id, + "tenant_id": tenant_id, + "identity_entity_id": actor, + "email": "rls-a@example.com", + "is_active": True, + "created_at": get_datetime_utc(), + }, + { + "id": foreign_user_id, + "tenant_id": foreign_tenant, + "identity_entity_id": foreign_actor, + "email": "rls-b@example.com", + "is_active": True, + "created_at": get_datetime_utc(), + }, + ], + ) + connection.execute( + insert(Item), + [ + { + "id": item_id, + "owner_id": user_id, + "tenant_id": tenant_id, + "title": "fixture-a", + "created_at": get_datetime_utc(), + }, + { + "id": foreign_item_id, + "owner_id": foreign_user_id, + "tenant_id": foreign_tenant, + "title": "fixture-b", + "created_at": get_datetime_utc(), + }, + ], + ) + try: + yield { + "migration": migration, + "runtime": runtime, + "claims": claims, + "user_id": user_id, + "foreign_user_id": foreign_user_id, + "item_id": item_id, + "foreign_item_id": foreign_item_id, + "tenant_id": tenant_id, + "foreign_tenant": foreign_tenant, + } + finally: + with migration.begin() as connection: + connection.execute( + delete(Item).where(Item.id.in_([item_id, foreign_item_id])) + ) + connection.execute( + delete(User).where(User.id.in_([user_id, foreign_user_id])) + ) + runtime.dispose() + migration.dispose() + + +def install_claims(connection, claims): + connection.execute( + text("SELECT set_config('request.jwt.claims', :claims, true)"), + {"claims": json.dumps(claims)}, + ) + connection.execute(text("SET LOCAL ROLE authenticated")) + + +def test_rls_same_tenant_crud_and_admin_cross_tenant_denial(rls_fixture): + fixture = rls_fixture + claims = dict( + fixture["claims"], + user_role="admin", + permissions=["org:projects:read", "org:projects:write"], + ) + with fixture["runtime"].connect() as connection, connection.begin(): + install_claims(connection, claims) + role = connection.execute( + text( + "SELECT rolsuper, rolbypassrls FROM pg_roles WHERE rolname = current_user" + ) + ).one() + assert role == (False, False) + flags = connection.execute( + text( + "SELECT c.relrowsecurity, c.relforcerowsecurity FROM pg_class AS c JOIN pg_namespace AS n ON n.oid=c.relnamespace WHERE n.nspname='api' AND c.relname IN ('user', 'item')" + ) + ).all() + assert len(flags) == 2 and all(enabled and forced for enabled, forced in flags) + assert connection.execute(select(Item.id)).scalars().all() == [ + fixture["item_id"] + ] + assert connection.execute(select(User.id)).scalars().all() == [ + fixture["user_id"] + ] + assert ( + connection.execute( + update(Item) + .where(Item.id == fixture["foreign_item_id"]) + .values(title="forbidden") + ).rowcount + == 0 + ) + assert ( + connection.execute( + update(Item) + .where(Item.id == fixture["item_id"]) + .values(title="updated") + ).rowcount + == 1 + ) + item_id = uuid.uuid4() + connection.execute( + insert(Item).values( + id=item_id, + tenant_id=fixture["tenant_id"], + owner_id=fixture["user_id"], + title="new", + created_at=get_datetime_utc(), + ) + ) + assert connection.execute(delete(Item).where(Item.id == item_id)).rowcount == 1 + with pytest.raises(DBAPIError), connection.begin_nested(): + connection.execute( + insert(Item).values( + id=uuid.uuid4(), + tenant_id=fixture["foreign_tenant"], + owner_id=fixture["foreign_user_id"], + title="forbidden", + created_at=get_datetime_utc(), + ) + ) + + +@pytest.mark.parametrize( + "field,value", + [ + ("tenant_id", "foreign-fixture"), + ("owner_id", uuid.uuid4()), + ("created_at", get_datetime_utc()), + ], +) +def test_rls_attribution_cannot_be_rewritten(rls_fixture, field, value): + fixture = rls_fixture + claims = dict( + fixture["claims"], user_role="admin", permissions=["org:projects:write"] + ) + with fixture["runtime"].connect() as connection, connection.begin(): + install_claims(connection, claims) + with pytest.raises(DBAPIError), connection.begin_nested(): + connection.execute( + update(Item).where(Item.id == fixture["item_id"]).values({field: value}) + ) + + +@pytest.mark.parametrize( + "override", + [ + {"role": "admin"}, + {"client_id": "foreign-fixture-client"}, + {"iss": "https://foreign-fixture.invalid"}, + {"org_id": "org_foreign_fixture"}, + {"api_identity_entity_id": str(uuid.uuid4())}, + {"api_user_id": None}, + {"api_user_id": str(uuid.uuid4())}, + {"permissions": []}, + ], +) +def test_rls_claim_confusion_and_foreign_binding_deny(rls_fixture, override): + fixture = rls_fixture + claims = dict( + fixture["claims"], + user_role="admin", + permissions=["org:projects:read", "org:projects:write"], + ) + claims.update(override) + with fixture["runtime"].connect() as connection, connection.begin(): + install_claims(connection, claims) + assert connection.execute(select(Item.id)).scalars().all() == [] + + +def test_rls_transaction_identity_does_not_survive_commit(rls_fixture): + fixture = rls_fixture + with fixture["runtime"].connect() as connection: + with connection.begin(): + install_claims( + connection, dict(fixture["claims"], permissions=["org:projects:read"]) + ) + assert connection.execute(select(Item.id)).scalars().all() == [ + fixture["item_id"] + ] + with connection.begin(): + connection.execute(text("SET LOCAL ROLE authenticated")) + assert connection.execute(select(Item.id)).scalars().all() == [] + + +def test_rls_revoked_projected_membership_denies_previous_claims(rls_fixture): + fixture = rls_fixture + claims = dict(fixture["claims"], permissions=["org:projects:read"]) + parameters = {"subject": claims["sub"], "organization": claims["org_id"]} + with fixture["migration"].connect() as owner, owner.begin(): + statuses = owner.execute( + text( + "SELECT id, status FROM workos.workosorganizationmembership WHERE user_id=:subject AND organization_id=:organization" + ), + parameters, + ).all() + assert statuses and all( + status.strip().lower() == "active" for _, status in statuses + ) + # Exercise revocation in one fixture-owned transaction, using the same + # connection under the non-bypass runtime role; rollback preserves owner data. + owner.execute( + text( + "UPDATE workos.workosorganizationmembership SET status='inactive' WHERE user_id=:subject AND organization_id=:organization" + ), + parameters, + ) + install_claims(owner, claims) + assert owner.execute(select(Item.id)).scalars().all() == [] + owner.execute(text("RESET ROLE")) + for membership_id, status in statuses: + owner.execute( + text( + "UPDATE workos.workosorganizationmembership SET status=:status WHERE id=:id" + ), + {"id": membership_id, "status": status}, + ) + + +def test_disabled_admin_cached_claims_cannot_mutate_another_profile( + rls_fixture, canonical_actors +): + fixture = rls_fixture + target_id = uuid.uuid4() + target_actor = uuid.UUID(canonical_actors["member"]["identity_entity_id"]) + claims = dict( + fixture["claims"], + user_role="admin", + permissions=["org:projects:read", "org:projects:write"], + ) + with fixture["migration"].begin() as owner: + owner.execute( + insert(User).values( + id=target_id, + tenant_id=fixture["tenant_id"], + identity_entity_id=target_actor, + email="revocation-target@example.com", + is_active=True, + created_at=get_datetime_utc(), + ) + ) + try: + with fixture["runtime"].connect() as connection, connection.begin(): + install_claims(connection, claims) + assert ( + connection.execute( + update(User) + .where(User.id == target_id) + .values(full_name="before revocation") + ).rowcount + == 1 + ) + with fixture["migration"].begin() as owner: + owner.execute( + update(User) + .where(User.id == fixture["user_id"]) + .values(is_active=False) + ) + assert ( + connection.execute(select(User.id).where(User.id == target_id)) + .scalars() + .all() + == [] + ) + assert ( + connection.execute( + update(User) + .where(User.id == target_id) + .values(full_name="forbidden") + ).rowcount + == 0 + ) + assert ( + connection.execute(delete(User).where(User.id == target_id)).rowcount + == 0 + ) + finally: + with fixture["migration"].begin() as owner: + owner.execute( + update(User).where(User.id == fixture["user_id"]).values(is_active=True) + ) + owner.execute(delete(User).where(User.id == target_id)) + + +def test_tenant_email_uniqueness_survives_member_visibility_boundaries( + rls_fixture, canonical_actors +): + fixture = rls_fixture + target_actor = uuid.UUID(canonical_actors["member"]["identity_entity_id"]) + with fixture["migration"].connect() as owner, owner.begin(): + email = owner.execute( + select(User.email).where(User.id == fixture["user_id"]) + ).scalar_one() + with pytest.raises(IntegrityError) as error, owner.begin_nested(): + owner.execute( + insert(User).values( + id=uuid.uuid4(), + tenant_id=fixture["tenant_id"], + identity_entity_id=target_actor, + email=email, + is_active=True, + created_at=get_datetime_utc(), + ) + ) + assert error.value.orig.diag.constraint_name == "uq_user_tenant_email" + assert ( + owner.execute( + update(User) + .where(User.id == fixture["foreign_user_id"]) + .values(email=email) + ).rowcount + == 1 + ) + + +def test_native_policy_preserves_exact_permission_identity(rls_fixture): + fixture = rls_fixture + item_id = uuid.uuid4() + claims = dict( + fixture["claims"], user_role="member", permissions=["org:projects:write"] + ) + with fixture["runtime"].connect() as connection, connection.begin(): + install_claims(connection, claims) + assert connection.scalar( + text("SELECT public.has_workos_permission(:permission)"), + {"permission": "org:projects:write"}, + ) + connection.execute( + insert(Item).values( + id=item_id, + tenant_id=fixture["tenant_id"], + owner_id=fixture["user_id"], + title="exact permission", + created_at=get_datetime_utc(), + ) + ) + assert ( + connection.execute(select(Item.id).where(Item.id == item_id)).scalar_one() + == item_id + ) + install_claims(connection, dict(claims, permissions=[])) + assert ( + connection.execute( + update(Item).where(Item.id == item_id).values(title="forbidden") + ).rowcount + == 0 + ) + # Keep fixture cleanup independent of which policy a failed assertion reached. + connection.rollback() diff --git a/backend/tests/test_policy_generation.py b/backend/tests/test_policy_generation.py new file mode 100644 index 0000000000..2ba183a2b0 --- /dev/null +++ b/backend/tests/test_policy_generation.py @@ -0,0 +1,243 @@ +"""Native Alembic SQL-artifact fidelity; no policy compiler or vendor patch.""" + +import ast as python_ast +import uuid + +import pytest +from alembic.autogenerate import render_python_code +from alembic.migration import MigrationContext +from alembic.operations import ops +from alembic_utils.pg_function import PGFunction +from alembic_utils.pg_grant_table import PGGrantTable +from alembic_utils.pg_policy import PGPolicy +from alembic_utils.pg_trigger import PGTrigger +from alembic_utils.reversible_op import CreateOp, DropOp, ReplaceOp +from pglast import parse_sql +from sqlalchemy import text +from sqlalchemy.dialects import postgresql +from sqlalchemy.orm import Session + +from app.alembic.native_security import entity_writer +from app.alembic.security import entities +from tests.test_data_namespace import isolated_data_engine + +PREDICATES = [ + "'org:projects:write' = 'org:projects:write'", + "':bind_like' = ':bind_like'", + "'https://example.invalid/a:b' = 'https://example.invalid/a:b'", + r"'literal\:value' = 'literal\:value'", + r"'literal\\slash:tail' = 'literal\\slash:tail'", + "NULL::text IS NULL", + r"E'line\n:colon' = E'line\n:colon'", + "$$:bind_like$$ = $$:bind_like$$", +] + + +def serialized_statements(operation, context=None): + context = context or MigrationContext.configure(dialect=postgresql.dialect()) + migration = ops.MigrationScript( + None, ops.UpgradeOps([operation]), ops.DowngradeOps([]) + ) + entity_writer(context, (), [migration]) + rendered = render_python_code(migration.upgrade_ops) + tree = python_ast.parse("def native_migration():\n" + rendered) + statements = [] + for call in ( + node for node in python_ast.walk(tree) if isinstance(node, python_ast.Call) + ): + assert ( + isinstance(call.func, python_ast.Attribute) and call.func.attr == "execute" + ) + payload = python_ast.literal_eval(call.args[0]) + compiled = text(payload).compile(dialect=postgresql.dialect()) + assert not compiled.params + statements.extend(parse_sql(str(compiled))) + return tuple(statements) + + +@pytest.mark.parametrize("predicate", PREDICATES) +@pytest.mark.parametrize("kind", ["create", "replace", "drop", "cascade_drop"]) +def test_native_policy_artifact_preserves_literal_semantics(predicate, kind): + definition = f"AS PERMISSIVE FOR SELECT TO authenticated USING ({predicate})" + policy = PGPolicy( + schema="api", + signature="literal_fixture", + on_entity="api.item", + definition=definition, + ) + create = f"CREATE POLICY literal_fixture ON api.item {definition}" + if kind == "create": + operation, expected = CreateOp(policy), create + elif kind == "replace": + operation = ReplaceOp(policy) + expected = f"DROP POLICY IF EXISTS literal_fixture ON api.item; {create}" + else: + cascade = kind == "cascade_drop" + operation = DropOp(policy, cascade=cascade) + expected = "DROP POLICY literal_fixture ON api.item" + ( + " CASCADE" if cascade else "" + ) + assert serialized_statements(operation) == parse_sql(expected) + + +@pytest.mark.parametrize( + "definition", + [ + "FOR SELECT USING (true)", + "AS RESTRICTIVE FOR SELECT TO authenticated USING (true)", + ], +) +def test_native_policy_artifact_preserves_default_role_and_mode(definition): + policy = PGPolicy( + schema="api", + signature="mode_fixture", + on_entity="api.item", + definition=definition, + ) + assert serialized_statements(CreateOp(policy)) == parse_sql( + f"CREATE POLICY mode_fixture ON api.item {definition}" + ) + + +def test_revert_without_original_native_snapshot_fails_closed(): + policy = PGPolicy( + schema="api", + signature="snapshot_fixture", + on_entity="api.item", + definition="FOR SELECT USING (true)", + ) + with pytest.raises(RuntimeError, match="original autogeneration snapshot"): + serialized_statements(ReplaceOp(policy).reverse()) + + +@pytest.mark.parametrize("predicate", PREDICATES) +def test_revert_uses_public_factory_in_same_repeatable_read_snapshot(predicate): + engine = isolated_data_engine("API_TEST_MIGRATION_DATABASE_URL") + try: + with engine.connect().execution_options( + isolation_level="REPEATABLE READ" + ) as connection: + with connection.begin(): + snapshot = connection.scalar(text("SELECT pg_current_snapshot()::text")) + name = "serializer_" + uuid.uuid4().hex + old = PGPolicy( + schema="api", + signature=name, + on_entity="api.item", + definition=f"AS RESTRICTIVE FOR SELECT TO authenticated USING ({predicate})", + ) + connection.execute(old.to_sql_statement_create()) + actual_clause = connection.scalar( + text( + "SELECT qual FROM pg_policies WHERE schemaname='api' AND tablename='item' AND policyname=:name" + ), + {"name": name}, + ) + new = PGPolicy( + schema="api", + signature=name, + on_entity="api.item", + definition="FOR SELECT USING (false)", + ) + context = MigrationContext.configure( + connection, opts={"api_autogen_snapshot": snapshot} + ) + expected = f"DROP POLICY IF EXISTS {name} ON api.item; CREATE POLICY {name} ON api.item AS RESTRICTIVE FOR SELECT TO authenticated USING ({actual_clause})" + assert serialized_statements( + ReplaceOp(new).reverse(), context + ) == parse_sql(expected) + assert ( + connection.scalar(text("SELECT pg_current_snapshot()::text")) + == snapshot + ) + connection.rollback() + finally: + engine.dispose() + + +@pytest.mark.parametrize("kind", ["create", "replace", "drop", "cascade_drop"]) +@pytest.mark.parametrize("entity_kind", ["function", "trigger", "grant"]) +def test_generic_entity_artifacts_preserve_native_defaults_and_cascade( + entity_kind, kind +): + if entity_kind == "function": + declaration = "RETURNS text LANGUAGE sql AS $$ SELECT value || ':tail' $$" + signature = "literal_fixture(value text DEFAULT 'default:tail')" + entity = PGFunction(schema="api", signature=signature, definition=declaration) + create = f"CREATE FUNCTION api.{signature} {declaration}" + replace = f"CREATE OR REPLACE FUNCTION api.{signature} {declaration}" + drop = "DROP FUNCTION api.literal_fixture(value text)" + elif entity_kind == "trigger": + declaration = "BEFORE UPDATE ON api.item FOR EACH ROW EXECUTE FUNCTION api.protect_item_attribution()" + entity = PGTrigger( + schema="api", + signature="literal_fixture", + on_entity="api.item", + definition=declaration, + ) + create = f"CREATE TRIGGER literal_fixture {declaration}" + replace = f"DROP TRIGGER IF EXISTS literal_fixture ON api.item; {create}" + drop = "DROP TRIGGER literal_fixture ON api.item" + else: + entity = PGGrantTable( + schema="api", + table="item", + role="authenticated", + grant="UPDATE", + columns=["title", "description"], + ) + create = "GRANT UPDATE (description, title) ON api.item TO authenticated" + drop = "REVOKE UPDATE ON api.item FROM authenticated" + replace = f"{drop}; {create}" + if kind == "create": + operation, expected = CreateOp(entity), create + elif kind == "replace": + operation, expected = ReplaceOp(entity), replace + else: + operation = DropOp(entity, cascade=kind == "cascade_drop") + expected = drop + ( + " CASCADE" if kind == "cascade_drop" and entity_kind != "grant" else "" + ) + assert serialized_statements(operation) == parse_sql(expected) + + +def test_every_declared_entity_revert_uses_public_snapshot_contract(): + engine = isolated_data_engine("API_TEST_MIGRATION_DATABASE_URL") + try: + with engine.connect().execution_options( + isolation_level="REPEATABLE READ" + ) as connection: + with connection.begin(): + snapshot = connection.scalar(text("SELECT pg_current_snapshot()::text")) + context = MigrationContext.configure( + connection, opts={"api_autogen_snapshot": snapshot} + ) + for entity in entities: + with Session( + bind=connection, join_transaction_mode="create_savepoint" + ) as session: + matches = [ + candidate + for candidate in type(entity).from_database( + session, entity.schema + ) + if candidate.identity == entity.identity + ] + assert len(matches) == 1 + expected = tuple( + statement + for ddl in matches[0].to_sql_statement_create_or_replace() + for statement in parse_sql( + str(ddl.compile(dialect=postgresql.dialect())) + ) + ) + assert ( + serialized_statements(ReplaceOp(entity).reverse(), context) + == expected + ) + assert ( + connection.scalar(text("SELECT pg_current_snapshot()::text")) + == snapshot + ) + finally: + engine.dispose() diff --git a/backend/tests/test_workos_security.py b/backend/tests/test_workos_security.py new file mode 100644 index 0000000000..a659174d57 --- /dev/null +++ b/backend/tests/test_workos_security.py @@ -0,0 +1,201 @@ +"""Signed-token fixtures only: these do not establish production WorkOS readiness.""" + +from datetime import UTC, datetime, timedelta + +import jwt +import pytest +from cryptography.hazmat.primitives.asymmetric import rsa +from jwt import InvalidTokenError, PyJWK + +from app.core.config import Settings +from app.core.security import AccessTokenVerifier + + +@pytest.fixture +def auth_settings() -> Settings: + return Settings( + _env_file=None, + PROJECT_NAME="API auth fixture", + FRONTEND_HOST="http://localhost:5173", + FASTAPI_ENV="development", + DATABASE_URL="postgresql+psycopg://fixture:fixture@localhost/api_fixture", + WORKOS_CLIENT_ID="client_fixture", + WORKOS_ISSUER="https://auth.fixture.test/", + WORKOS_JWKS_URL="https://auth.fixture.test/sso/jwks/client_fixture", + WORKOS_API_HOSTNAME="auth.fixture.test", + ) + + +@pytest.fixture +def signed_token(auth_settings: Settings): + key = rsa.generate_private_key(public_exponent=65537, key_size=2048) + jwk = PyJWK.from_json(jwt.algorithms.RSAAlgorithm.to_jwk(key.public_key())) + now = datetime.now(UTC) + claims = { + "iss": auth_settings.WORKOS_ISSUER, + "client_id": auth_settings.WORKOS_CLIENT_ID, + "sub": "user_fixture", + "sid": "session_fixture", + "org_id": "org_fixture", + "role": "authenticated", + "user_role": "member", + "permissions": ["org:projects:read"], + "iat": int(now.timestamp()), + "exp": int((now + timedelta(minutes=5)).timestamp()), + } + + class FixtureKeys: + def get_signing_key_from_jwt(self, _token: str) -> PyJWK: + return jwk + + verifier = AccessTokenVerifier(auth_settings, jwks_client=FixtureKeys()) + + def encode(**changes): + payload = claims | changes + return jwt.encode( + {k: v for k, v in payload.items() if v is not None}, + key, + algorithm="RS256", + headers={"kid": "fixture"}, + ) + + return verifier, encode + + +def test_signed_selected_organization_token(signed_token): + verifier, encode = signed_token + token = verifier.verify(encode()) + assert token.subject == "user_fixture" + assert token.organization_id == "org_fixture" + assert token.permissions == frozenset({"org:projects:read"}) + + +@pytest.mark.parametrize( + "changes", + [ + {"iss": "https://other.fixture.test/"}, + {"iss": None}, + {"client_id": "client_foreign"}, + {"client_id": None}, + {"exp": 1}, + {"exp": None}, + {"exp": "9999999999"}, + {"sub": None}, + {"sub": " "}, + {"sid": None}, + {"org_id": None}, + {"role": "admin"}, + {"user_role": None}, + {"permissions": "org:projects:write"}, + {"permissions": [1]}, + {"o": {"id": "org_foreign"}}, + {"aud": "client_foreign"}, + {"roles": ["member", "admin"]}, + ], +) +def test_rejects_unbound_or_confused_token(signed_token, changes): + verifier, encode = signed_token + with pytest.raises(InvalidTokenError): + verifier.verify(encode(**changes)) + + +def test_rejects_token_signed_by_another_key(signed_token): + verifier, _ = signed_token + other = rsa.generate_private_key(public_exponent=65537, key_size=2048) + with pytest.raises(InvalidTokenError): + verifier.verify(jwt.encode({"sub": "user_fixture"}, other, algorithm="RS256")) + + +def test_production_browser_requires_custom_auth_domain(auth_settings): + values = auth_settings.model_dump() + values.update( + FASTAPI_ENV=None, + FRONTEND_HOST="https://api.fixture.test", + WORKOS_API_HOSTNAME="api.workos.com", + WORKOS_ISSUER="https://api.workos.com/", + WORKOS_JWKS_URL="https://api.workos.com/sso/jwks/client_fixture", + ) + with pytest.raises(ValueError, match="custom"): + Settings(_env_file=None, **values) + + +def test_production_accepts_custom_api_with_explicit_vendor_jwks(auth_settings): + values = auth_settings.model_dump() + values.update( + FASTAPI_ENV=None, + FRONTEND_HOST="https://api.fixture.com", + WORKOS_API_HOSTNAME="auth.fixture.com", + WORKOS_ISSUER="https://auth.fixture.com/", + WORKOS_JWKS_URL="https://api.workos.com/sso/jwks/client_fixture", + ) + config = Settings(_env_file=None, **values) + assert config.WORKOS_API_HOSTNAME == "auth.fixture.com" + + +def test_native_jwks_cache_and_key_rotation_require_tls_and_timeout( + auth_settings, monkeypatch +): + import io + import json + import ssl + from urllib.request import HTTPSHandler + + first = rsa.generate_private_key(public_exponent=65537, key_size=2048) + second = rsa.generate_private_key(public_exponent=65537, key_size=2048) + keys = [first] + calls = [] + clock = [100.0] + monkeypatch.setattr("jwt.jwks_client.time.monotonic", lambda: clock[0]) + + def fetch(request, *, timeout): + calls.append(request.full_url) + assert request.full_url == auth_settings.WORKOS_JWKS_URL + assert timeout == 5 + documents = [] + for index, key in enumerate(keys): + documents.append( + json.loads(jwt.algorithms.RSAAlgorithm.to_jwk(key.public_key())) + | { + "kid": f"fixture-{index}", + "use": "sig", + "alg": "RS256", + } + ) + return io.BytesIO(json.dumps({"keys": documents}).encode()) + + class FixtureOpener: + open = staticmethod(fetch) + + def build_opener(*handlers): + tls = next(handler for handler in handlers if isinstance(handler, HTTPSHandler)) + assert tls._context.verify_mode == ssl.CERT_REQUIRED + assert tls._context.check_hostname + return FixtureOpener() + + monkeypatch.setattr("urllib.request.build_opener", build_opener) + verifier = AccessTokenVerifier(auth_settings) + now = int(datetime.now(UTC).timestamp()) + payload = { + "iss": auth_settings.WORKOS_ISSUER, + "client_id": auth_settings.WORKOS_CLIENT_ID, + "sub": "user_fixture", + "sid": "session_fixture", + "org_id": "org_fixture", + "role": "authenticated", + "user_role": "member", + "permissions": [], + "iat": now, + "exp": now + 300, + } + first_token = jwt.encode( + payload, first, algorithm="RS256", headers={"kid": "fixture-0"} + ) + verifier.verify(first_token) + verifier.verify(first_token) + assert len(calls) == 1 + keys.append(second) + clock[0] += 31 # Native unknown-kid cooldown; cached known keys stay usable. + verifier.verify( + jwt.encode(payload, second, algorithm="RS256", headers={"kid": "fixture-1"}) + ) + assert len(calls) == 2 diff --git a/backend/tests/utils/item.py b/backend/tests/utils/item.py deleted file mode 100644 index ee51b351a6..0000000000 --- a/backend/tests/utils/item.py +++ /dev/null @@ -1,16 +0,0 @@ -from sqlmodel import Session - -from app import crud -from app.models import Item, ItemCreate -from tests.utils.user import create_random_user -from tests.utils.utils import random_lower_string - - -def create_random_item(db: Session) -> Item: - user = create_random_user(db) - owner_id = user.id - assert owner_id is not None - title = random_lower_string() - description = random_lower_string() - item_in = ItemCreate(title=title, description=description) - return crud.create_item(session=db, item_in=item_in, owner_id=owner_id) diff --git a/backend/tests/utils/user.py b/backend/tests/utils/user.py deleted file mode 100644 index 5867431ed8..0000000000 --- a/backend/tests/utils/user.py +++ /dev/null @@ -1,49 +0,0 @@ -from fastapi.testclient import TestClient -from sqlmodel import Session - -from app import crud -from app.core.config import settings -from app.models import User, UserCreate, UserUpdate -from tests.utils.utils import random_email, random_lower_string - - -def user_authentication_headers( - *, client: TestClient, email: str, password: str -) -> dict[str, str]: - data = {"username": email, "password": password} - - r = client.post(f"{settings.API_V1_STR}/login/access-token", data=data) - response = r.json() - auth_token = response["access_token"] - headers = {"Authorization": f"Bearer {auth_token}"} - return headers - - -def create_random_user(db: Session) -> User: - email = random_email() - password = random_lower_string() - user_in = UserCreate(email=email, password=password) - user = crud.create_user(session=db, user_create=user_in) - return user - - -def authentication_token_from_email( - *, client: TestClient, email: str, db: Session -) -> dict[str, str]: - """ - Return a valid token for the user with given email. - - If the user doesn't exist it is created first. - """ - password = random_lower_string() - user = crud.get_user_by_email(session=db, email=email) - if not user: - user_in_create = UserCreate(email=email, password=password) - user = crud.create_user(session=db, user_create=user_in_create) - else: - user_in_update = UserUpdate(password=password) - if not user.id: - raise Exception("User id not set") - user = crud.update_user(session=db, db_user=user, user_in=user_in_update) - - return user_authentication_headers(client=client, email=email, password=password) diff --git a/backend/tests/utils/utils.py b/backend/tests/utils/utils.py deleted file mode 100644 index 184bac44d9..0000000000 --- a/backend/tests/utils/utils.py +++ /dev/null @@ -1,26 +0,0 @@ -import random -import string - -from fastapi.testclient import TestClient - -from app.core.config import settings - - -def random_lower_string() -> str: - return "".join(random.choices(string.ascii_lowercase, k=32)) - - -def random_email() -> str: - return f"{random_lower_string()}@{random_lower_string()}.com" - - -def get_superuser_token_headers(client: TestClient) -> dict[str, str]: - login_data = { - "username": settings.FIRST_SUPERUSER, - "password": settings.FIRST_SUPERUSER_PASSWORD, - } - r = client.post(f"{settings.API_V1_STR}/login/access-token", data=login_data) - tokens = r.json() - a_token = tokens["access_token"] - headers = {"Authorization": f"Bearer {a_token}"} - return headers diff --git a/bun.lock b/bun.lock index 3da1627ede..0e7875bfc5 100644 --- a/bun.lock +++ b/bun.lock @@ -28,6 +28,7 @@ "@tanstack/react-router": "^1.170.46", "@tanstack/react-router-devtools": "^1.167.2", "@tanstack/react-table": "^9.3.1", + "@workos-inc/authkit-react": "^0.16.3", "axios": "1.20.0", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", @@ -603,6 +604,10 @@ "@vitejs/plugin-react-swc": ["@vitejs/plugin-react-swc@4.3.3", "", { "dependencies": { "@rolldown/pluginutils": "^1.0.1", "@swc/core": "^1.15.46" }, "peerDependencies": { "vite": "^4 || ^5 || ^6 || ^7 || ^8" } }, "sha512-bti8ZAcvz4Lh6/e4Uk2k3aa1TiUXbbMsahuqOHvd3MveFTkKDZOA6wQVkpj7J/+tepX/wGfe+lsGh/t24HTXMQ=="], + "@workos-inc/authkit-js": ["@workos-inc/authkit-js@0.20.5", "", {}, "sha512-5e3C0xTMMlnDlaVAIOCk/G91W83lpb9ChPolCxTOQCkCuwn3w5qfuJze+5UNOIX1RRZv6rnzyb2FRfPdSThDkw=="], + + "@workos-inc/authkit-react": ["@workos-inc/authkit-react@0.16.3", "", { "dependencies": { "@workos-inc/authkit-js": "^0.20.4" }, "peerDependencies": { "react": ">=17" } }, "sha512-0dBvUp/ZEF/yrojfDHK9T/eMmNxMtH7HbWZvA8Aum5wRn874Yr0wraAFr/wAKBRJYoYLCcfYwSEDlYTjKTk2sQ=="], + "accepts": ["accepts@1.3.8", "", { "dependencies": { "mime-types": "~2.1.34", "negotiator": "0.6.3" } }, "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw=="], "agent-base": ["agent-base@6.0.2", "", { "dependencies": { "debug": "4" } }, "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ=="], diff --git a/compose.deploy.yml b/compose.deploy.yml index 3d810f514f..53978b6af8 100644 --- a/compose.deploy.yml +++ b/compose.deploy.yml @@ -1,5 +1,4 @@ services: - proxy: restart: always ports: @@ -31,23 +30,8 @@ services: # Enable the Traefik log, for configurations and errors - --log - db: - restart: always - - adminer: - restart: always - labels: - # Route HTTPS traffic for the Adminer subdomain - - traefik.http.routers.adminer-https.rule=Host(`adminer.${DOMAIN:?Variable not set}`) - - traefik.http.routers.adminer-https.entrypoints=https - - traefik.http.routers.adminer-https.tls=true - # Use the Let's Encrypt resolver - - traefik.http.routers.adminer-https.tls.certresolver=le - backend: restart: always - environment: - FRONTEND_HOST: https://${DOMAIN:?Variable not set} labels: # Route HTTPS traffic for this domain - traefik.http.routers.backend-https.rule=Host(`${DOMAIN:?Variable not set}`) diff --git a/compose.override.yml b/compose.override.yml index 38060babf7..009e0dce04 100644 --- a/compose.override.yml +++ b/compose.override.yml @@ -1,5 +1,4 @@ services: - proxy: image: traefik:v3.7 ports: @@ -23,13 +22,6 @@ services: - --api # Enable the Dashboard and API in insecure mode for local development - --api.insecure=true - db: - ports: - - "5432:5432" - - adminer: - ports: - - "8080:8080" backend: ports: @@ -85,8 +77,6 @@ services: - backend - mailpit environment: - - FIRST_SUPERUSER=${FIRST_SUPERUSER:?Variable not set} - - FIRST_SUPERUSER_PASSWORD=${FIRST_SUPERUSER_PASSWORD:?Variable not set} - PLAYWRIGHT_BASE_URL=http://backend:8000 - VITE_API_URL=http://backend:8000 - MAILPIT_HOST=http://mailpit:8025 diff --git a/compose.yml b/compose.yml index 110eb5c3e0..05dac14817 100644 --- a/compose.yml +++ b/compose.yml @@ -1,5 +1,4 @@ services: - proxy: image: traefik:v3.7 volumes: @@ -17,55 +16,30 @@ services: # Enable the Traefik log, for configurations and errors - --log - db: - image: postgres:18 - healthcheck: - test: ["CMD-SHELL", "pg_isready -U postgres -d app"] - interval: 10s - retries: 5 - start_period: 30s - timeout: 10s - volumes: - - app-db-data:/var/lib/postgresql - environment: - - POSTGRES_PASSWORD=${POSTGRES_PASSWORD:?Variable not set} - - POSTGRES_DB=app - - adminer: - image: adminer - depends_on: - - db - environment: - - ADMINER_DESIGN=pepa-linha-dark - labels: - # Enable Traefik for this service - - traefik.enable=true - # Route HTTP traffic for the Adminer subdomain - - traefik.http.routers.adminer-http.rule=Host(`adminer.${DOMAIN:-localhost}`) - - traefik.http.routers.adminer-http.entrypoints=http - # Define the port inside of the Docker service to use - - traefik.http.services.adminer.loadbalancer.server.port=8080 - backend: image: backend:latest - depends_on: - db: - condition: service_healthy - restart: true environment: PROJECT_NAME: ${PROJECT_NAME:?Variable not set} - SECRET_KEY: ${SECRET_KEY:?Variable not set} - FIRST_SUPERUSER: ${FIRST_SUPERUSER:?Variable not set} - FIRST_SUPERUSER_PASSWORD: ${FIRST_SUPERUSER_PASSWORD:?Variable not set} - SMTP_HOST: ${SMTP_HOST} + FRONTEND_HOST: ${FRONTEND_HOST:?Variable not set} + WORKOS_CLIENT_ID: ${WORKOS_CLIENT_ID:?Variable not set} + WORKOS_ISSUER: ${WORKOS_ISSUER:?Variable not set} + WORKOS_JWKS_URL: ${WORKOS_JWKS_URL:?Variable not set} + WORKOS_API_HOSTNAME: ${WORKOS_API_HOSTNAME:?Variable not set} + SMTP_HOST: ${SMTP_HOST:-} SMTP_USER: ${SMTP_USER:-} SMTP_PASSWORD: ${SMTP_PASSWORD:-} - EMAILS_FROM_EMAIL: ${EMAILS_FROM_EMAIL} - DATABASE_URL: postgresql://postgres:${POSTGRES_PASSWORD:?Variable not set}@db:5432/app + EMAILS_FROM_EMAIL: ${EMAILS_FROM_EMAIL:-} + DATABASE_URL: ${DATABASE_URL:?Explicit non-superuser NOBYPASSRLS runtime URL required} SENTRY_DSN: ${SENTRY_DSN:-} healthcheck: - test: ["CMD", "curl", "-f", "http://localhost:8000/api/v1/utils/health-check/"] + test: + [ + "CMD", + "curl", + "-f", + "http://localhost:8000/api/v1/utils/health-check/", + ] interval: 10s timeout: 5s retries: 5 @@ -84,5 +58,10 @@ services: - traefik.http.routers.backend-http.rule=Host(`${DOMAIN:-localhost}`) - traefik.http.routers.backend-http.entrypoints=http -volumes: - app-db-data: + migrate: + image: backend:latest + profiles: ["maintenance"] + command: ["bash", "scripts/prestart.sh"] + environment: + DATABASE_URL: ${DATABASE_URL:?Runtime URL required to verify distinct authorities} + API_MIGRATION_DATABASE_URL: ${API_MIGRATION_DATABASE_URL:-} diff --git a/deployment-docker-compose.md b/deployment-docker-compose.md index 5c43fd54f8..634d025001 100644 --- a/deployment-docker-compose.md +++ b/deployment-docker-compose.md @@ -1,11 +1,14 @@ # FastAPI Project - Docker Compose Deployment -You can deploy the project to your own remote server with Docker Compose. The deployment configuration includes Traefik to handle HTTPS and route incoming traffic to the application. +Deploy only after the identity, namespace, isolation, recovery and real-provider +acceptance gates in [deployment.md](deployment.md) pass. The Compose profile uses +the existing approved product database; it does not create a parallel template +database or seed a local superuser. Traefik handles HTTPS application routing. ## Preparation * Have a remote server ready and available. -* Configure DNS records pointing to the server for the application domain and any supporting service subdomains you want to expose, such as `fastapi-project.example.com` and `adminer.fastapi-project.example.com`. +* Configure DNS for the application and the separately approved WorkOS Authentication API domain. * Install and configure [Docker](https://docs.docker.com/engine/install/) on the remote server (Docker Engine, not Docker Desktop). ## Copy the Code @@ -20,13 +23,11 @@ The `--filter=":- .gitignore"` option tells `rsync` to use the same ignore rules ### Environment Variables -Set the application domain, project name, and first superuser email: - -```bash -export DOMAIN=fastapi-project.example.com -export PROJECT_NAME="Full Stack FastAPI Project" -export FIRST_SUPERUSER=admin@example.com -``` +Set `DOMAIN`, `PROJECT_NAME`, `FRONTEND_HOST` and the explicitly approved +`WORKOS_CLIENT_ID`, `WORKOS_ISSUER`, `WORKOS_JWKS_URL`, +`WORKOS_API_HOSTNAME`. Production requires an HTTPS browser origin and custom +Authentication API hostname. These are environment/application-specific values, +not catalog/staging fallbacks. You can also configure these environment variables as needed: @@ -37,13 +38,10 @@ You can also configure these environment variables as needed: ### Secrets -Generate and set secure values for the database password, token signing key, and first superuser password: - -```bash -export POSTGRES_PASSWORD="$(python -c 'import secrets; print(secrets.token_urlsafe(32))')" -export SECRET_KEY="$(python -c 'import secrets; print(secrets.token_urlsafe(32))')" -export FIRST_SUPERUSER_PASSWORD="$(python -c 'import secrets; print(secrets.token_urlsafe(32))')" -``` +Supply `DATABASE_URL` through the secret owner for the dedicated non-superuser, +`NOBYPASSRLS` runtime login. Supply a distinct `API_MIGRATION_DATABASE_URL` only +for the reviewed migration invocation; do not put it in the backend runtime. +No WorkOS private key/API key or application password-signing secret is needed. To use an authenticated email provider, also set `SMTP_PASSWORD`. @@ -52,17 +50,27 @@ To use an authenticated email provider, also set `SMTP_PASSWORD`. ```bash cd /root/code/app/ docker compose -f compose.yml -f compose.deploy.yml build -docker compose -f compose.yml -f compose.deploy.yml run --rm backend bash scripts/prestart.sh +docker compose -f compose.yml -f compose.deploy.yml run --rm migrate docker compose -f compose.yml -f compose.deploy.yml up -d ``` The `compose.deploy.yml` file adds HTTPS and automatic certificate handling to the shared `compose.yml` configuration. Explicitly listing both files excludes the local settings from `compose.override.yml`. +The `migrate` maintenance service runs only +`alembic -c alembic-api.ini upgrade api@head`. It refuses missing schema/branch +prerequisites and never replays the legacy public ledger or seeds identities. +The backend receives runtime credentials only. Review and restore-test the +canonical baseline before migration, and read back real same/cross-tenant +operations before admitting traffic. + The backend Docker image builds the frontend, so the server does not need Bun or prebuilt frontend files. ## Deploy with GitHub Actions -The included `.github/workflows/deploy-docker-compose.yml` workflow runs the deployment commands on the server when manually triggered from GitHub Actions. +The included `.github/workflows/deploy-docker-compose.yml` is manual-only and +selects the `production` GitHub environment. Required reviewers and environment +protection are UNVERIFIED until native owner readback; the name alone is not a +protection. Do not trigger it until protection and all production gates pass. Use a self-hosted runner only for a repository whose contributors and workflow code you trust. GitHub recommends using self-hosted runners with private repositories because workflows execute directly on the runner machine. @@ -72,7 +80,11 @@ In the repository, go to **Settings** > **Secrets and variables** > **Actions** * `DOMAIN` * `PROJECT_NAME` -* `FIRST_SUPERUSER` +* `FRONTEND_HOST` +* `WORKOS_CLIENT_ID` +* `WORKOS_ISSUER` +* `WORKOS_JWKS_URL` +* `WORKOS_API_HOSTNAME` To enable emails, add these optional repository variables: @@ -84,9 +96,8 @@ To enable Sentry, add the optional `SENTRY_DSN` repository variable. Add these repository secrets: -* `POSTGRES_PASSWORD` -* `SECRET_KEY` -* `FIRST_SUPERUSER_PASSWORD` +* `DATABASE_URL` (runtime, non-bypass) +* `API_MIGRATION_DATABASE_URL` (separate migration authority) To use an authenticated email provider, add the optional `SMTP_PASSWORD` repository secret. @@ -126,4 +137,3 @@ Application (frontend and API): `https://fastapi-project.example.com` Interactive API docs: `https://fastapi-project.example.com/docs` -Adminer: `https://adminer.fastapi-project.example.com` diff --git a/deployment.md b/deployment.md index 8e445ce5db..84628532ff 100644 --- a/deployment.md +++ b/deployment.md @@ -1,78 +1,78 @@ # FastAPI Project - Deployment -Deploy the project to [FastAPI Cloud](https://fastapicloud.com) with the included GitHub Actions workflow. - -## Create the FastAPI Cloud Application - -Create an application in FastAPI Cloud and set its [Application Directory](https://fastapicloud.com/docs/builds-and-deployments/application-directory/) to `backend`. - -Connect a PostgreSQL database using the [Neon](https://fastapicloud.com/docs/integrations/neon-integration/) or [Supabase](https://fastapicloud.com/docs/integrations/supabase-integration/) integration. Both integrations configure a `DATABASE_URL` secret automatically. You can also configure `DATABASE_URL` manually for another PostgreSQL provider. - -## Configure the Application - -### Environment Variables - -Add these required [environment variables](https://fastapicloud.com/docs/builds-and-deployments/environment-variables/) to the FastAPI Cloud application: - -* `PROJECT_NAME`: The name of the project, used in the API documentation and emails. -* `FIRST_SUPERUSER`: The email address of the first superuser. -* `FRONTEND_HOST`: The public URL of the application, such as the generated `https://your-app.fastapicloud.dev` URL or a custom domain. - -To enable emails, add these optional environment variables with values from your email provider: - -* `SMTP_HOST` -* `SMTP_USER` -* `EMAILS_FROM_EMAIL` - -To enable Sentry, configure `SENTRY_DSN`. - -### Secrets - -Add these required values and mark them as secrets: - -* `SECRET_KEY`: A secret key used to sign security tokens. -* `FIRST_SUPERUSER_PASSWORD`: The password of the first superuser. -* `DATABASE_URL`: The PostgreSQL connection URL, configured automatically when using a database integration. - -To enable emails with an authenticated provider, add `SMTP_PASSWORD` as a secret. - -You can generate secure values for `SECRET_KEY` and `FIRST_SUPERUSER_PASSWORD` with: - -```bash -python -c "import secrets; print(secrets.token_urlsafe(32))" -``` - -## Configure Continuous Deployment - -The included `.github/workflows/deploy.yml` workflow builds the frontend, prepares the database, and deploys the application whenever changes are pushed to `master`. You can also run it manually from the **Actions** tab. - -Log in to FastAPI Cloud and configure the [deploy token](https://fastapicloud.com/docs/advanced-features/deploy-tokens/) and application ID as GitHub repository secrets: - -```bash -uv run fastapi login -uv run fastapi cloud setup-ci --secrets-only --app-id +Deployment is deliberately gated. Do not deploy until the reviewed API namespace, +canonical identity mappings, non-bypass runtime role, isolated tests, recovery and +real WorkOS application-settings readback have passed. Source code and fixtures +are not production admission. + +## Configure the application + +For FastAPI Cloud, use `backend` as the application directory. Bind the existing +approved product database, not a newly created template database. A provider +integration's automatically supplied administrative URL is not evidence of a +safe runtime role. + +Required non-secret settings: + +- `PROJECT_NAME` +- `FRONTEND_HOST`: exact HTTPS browser origin/redirect destination +- `WORKOS_CLIENT_ID`: the approved application +- `WORKOS_ISSUER`: exact trusted HTTPS issuer +- `WORKOS_JWKS_URL`: explicit trusted HTTPS signing JWKS +- `WORKOS_API_HOSTNAME`: approved production custom Authentication API hostname + +Required secret: `DATABASE_URL`, using the dedicated non-superuser, +`NOBYPASSRLS` runtime login. The resource server needs no WorkOS API key and +contains no local-password/global-superuser seed. Optional SMTP/Sentry settings +are described in [backend configuration](backend/README.md). + +Register and read back the effective redirect URI, allowed browser origin, +sign-out default and SDK-backed `/login` Initiate login URI on the selected +WorkOS application. Verify its custom domain and TLS. Browser AuthKit React owns +login, refresh, logout and organization selection; it uses public +`GET /api/v1/auth/config`, not build-time secrets. + +## Prepare the API namespace + +Provision canonical product schemas/identities through their existing owner and +`api` through the reviewed schema owner. Preserve canonical tenant TEXT IDs and +local actor UUIDs. Do not run the legacy public migration history, create tables +at application startup, or seed identities from email. + +Supply `API_MIGRATION_DATABASE_URL` only to the reviewed migration job. It must +use an authority distinct from the runtime login. From `backend/`: + +```console +uv run alembic -c alembic-api.ini upgrade api@head ``` -If the GitHub CLI is installed and authenticated, the command configures `FASTAPI_CLOUD_TOKEN` and `FASTAPI_CLOUD_APP_ID` automatically. Otherwise, it prints the values so you can add them in your repository under **Settings** > **Secrets and variables** > **Actions**. - -The workflow runs database migrations and creates the first superuser before deploying. In the repository's **Settings** > **Secrets and variables** > **Actions** page, add these repository variables: - -* `PROJECT_NAME` -* `FIRST_SUPERUSER` - -Add these repository secrets: - -* `DATABASE_URL` -* `SECRET_KEY` -* `FIRST_SUPERUSER_PASSWORD` - -Use the same values configured in FastAPI Cloud. For `DATABASE_URL`, use the connection URL from your database provider. The database must be reachable from GitHub-hosted runners so the preparation step can connect to it. - -The deployment workflow performs these steps: - -1. Installs and builds the frontend into `backend/app/frontend`. -2. Runs `backend/scripts/prestart.sh` to apply database migrations and create the first superuser. -3. Deploys the project with `uv run fastapi deploy`. +`scripts/prestart.sh` invokes this exact branch and no seed. Without a reviewed +API revision and owner-provisioned prerequisites it refuses application. + +## Continuous deployment admission + +Both deployment workflows are manual-only and select the `production` GitHub +environment. Its required reviewers and environment protection remain UNVERIFIED +until the native GitHub owner reads them back. An environment name alone is not +protection, and a boolean approval flag cannot establish recovery or tenant +conformance. Do not trigger deployment before those protections and every +production prerequisite are verified. + +For `.github/workflows/deploy.yml`, configure the non-secret settings above on the +actual FastAPI Cloud application and matching GitHub repository variables. +Configure `DATABASE_URL`, `API_MIGRATION_DATABASE_URL`, `FASTAPI_CLOUD_TOKEN` and +`FASTAPI_CLOUD_APP_ID` as scoped GitHub secrets. Runtime deployment must not retain +the migration credential. Do not place keys, DSNs or tokens in source or logs. + +The admitted workflow builds the frontend, runs only the API migration branch, +then invokes the native FastAPI deployment command. This documentation does not +configure credentials, provider settings, schema or a deployment. + +Before admission, run the [isolated SQL/token/browser consumers](backend/README.md), +regenerate the native OpenAPI client, and establish real direct/gateway +same-tenant CRUD and cross-tenant denial. Verify durable readback, sign-in, +sign-out, externally initiated login, revoked memberships and pooled transaction +reuse. Keep the application inactive until every required production gate passes. ## URLs diff --git a/development.md b/development.md index efd21b2f3e..0839918e95 100644 --- a/development.md +++ b/development.md @@ -2,22 +2,24 @@ ## Local Development -For local development, run PostgreSQL and Mailpit with Docker Compose, and run the FastAPI and Vite development servers locally. +Use an approved isolated copy of the canonical product PostgreSQL baseline, with +its existing tenants, identity crosswalk and WorkOS projections. An empty local +template database is not an authentication authority. Configure the explicit +runtime/WorkOS variables listed in [backend/README.md](backend/README.md), using +`FASTAPI_ENV=development` and the exact local browser origin registered with the +selected nonproduction WorkOS application. -Start the supporting services: +From the upstream root, sync its independent native solve: ```bash -docker compose up -d db mailpit +uv sync --locked --package app ``` -Then, from the `backend` directory, install the dependencies and prepare the database: +An embedding workspace must select its declared external API environment instead +of modifying the parent's Python environment. Migration generation/application +requires separate reviewed authority; it is not an automatic development seed. -```bash -uv sync -uv run bash scripts/prestart.sh -``` - -Start the FastAPI development server: +Start FastAPI from `backend/` after provisioning the approved baseline: ```bash uv run fastapi dev @@ -38,7 +40,6 @@ Backend API: Automatic interactive API documentation with Swagger UI: -Mailpit: The frontend development server uses the backend at `http://localhost:8000`, as configured in `frontend/.env`. @@ -57,7 +58,8 @@ The build is written to `backend/app/frontend` and served by FastAPI at -Adminer, database web administration: Traefik UI, to see how the routes are being handled by the proxy: @@ -99,7 +100,11 @@ docker compose watch ## The `.env` File -The tracked `.env` file contains local development defaults, passwords, and other configuration. Its hostnames use `localhost` for processes running on your machine. Docker Compose overrides hostnames such as the database and SMTP server with their Compose service names. +Local environment files may supply explicitly selected nonproduction settings. +The backend/Compose now require `DATABASE_URL` and `WORKOS_*`; legacy template +passwords are not usable credentials. Compose does not start a replacement +product database. Never commit database URLs, provider keys or production +secrets. Supply the migration URL only to the maintenance migration service. Do not store deployment secrets in `.env`. Configure them as described in the [FastAPI Cloud deployment guide](./deployment.md) or the [Docker Compose deployment guide](./deployment-docker-compose.md). diff --git a/frontend/biome.json b/frontend/biome.json index 0d1e2e7576..bfb0302524 100644 --- a/frontend/biome.json +++ b/frontend/biome.json @@ -1,6 +1,11 @@ { "$schema": "https://biomejs.dev/schemas/2.6.3/schema.json", "assist": { "actions": { "source": { "organizeImports": "on" } } }, + "vcs": { + "enabled": true, + "clientKind": "git", + "useIgnoreFile": true + }, "files": { "includes": [ "**", diff --git a/frontend/index.html b/frontend/index.html index 57621a268b..00a473529c 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -2,10 +2,9 @@ - Full Stack FastAPI Project - +
diff --git a/frontend/package.json b/frontend/package.json index db1f8d5df0..0d6cbff1a9 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -8,9 +8,10 @@ "build": "tsc -p tsconfig.build.json && vite build", "lint": "biome check --write --unsafe --no-errors-on-unmatched --files-ignore-unknown=true ./", "preview": "vite preview", - "generate-client": "openapi-ts", + "generate-client": "biome format --write openapi.json && openapi-ts", "test": "bunx playwright test", - "test:ui": "bunx playwright test --ui" + "test:ui": "bunx playwright test --ui", + "check": "biome check --no-errors-on-unmatched --files-ignore-unknown=true ./" }, "dependencies": { "@hookform/resolvers": "^6.0.1", @@ -32,6 +33,7 @@ "@tanstack/react-router": "^1.170.46", "@tanstack/react-router-devtools": "^1.167.2", "@tanstack/react-table": "^9.3.1", + "@workos-inc/authkit-react": "^0.16.3", "axios": "1.20.0", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", diff --git a/frontend/playwright.config.ts b/frontend/playwright.config.ts index bf3fcc63af..037e8d0d01 100644 --- a/frontend/playwright.config.ts +++ b/frontend/playwright.config.ts @@ -1,95 +1,18 @@ -import { defineConfig, devices } from '@playwright/test'; -import 'dotenv/config' +import { defineConfig, devices } from "@playwright/test" +import "dotenv/config" -const baseURL = process.env.PLAYWRIGHT_BASE_URL ?? 'http://localhost:5173' +const baseURL = process.env.PLAYWRIGHT_BASE_URL ?? "http://localhost:5173" -/** - * Read environment variables from file. - * https://github.com/motdotla/dotenv - */ - -/** - * See https://playwright.dev/docs/test-configuration. - */ export default defineConfig({ - testDir: './tests', - /* Run tests in files in parallel */ + testDir: "./tests", fullyParallel: true, - /* Fail the build on CI if you accidentally left test.only in the source code. */ - forbidOnly: !!process.env.CI, - /* Retry on CI only */ + forbidOnly: Boolean(process.env.CI), retries: process.env.CI ? 2 : 0, - /* Opt out of parallel tests on CI. */ workers: process.env.CI ? 1 : undefined, - /* Reporter to use. See https://playwright.dev/docs/test-reporters */ - reporter: process.env.CI ? 'blob' : 'html', - /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */ - use: { - /* Base URL to use in actions like `await page.goto('/')`. */ - baseURL, - - /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */ - trace: 'on-first-retry', + reporter: process.env.CI ? "blob" : "html", + use: { baseURL, trace: "on-first-retry" }, + projects: [{ name: "chromium", use: { ...devices["Desktop Chrome"] } }], + webServer: process.env.PLAYWRIGHT_BASE_URL ? undefined : { + command: "bun run dev", url: baseURL, reuseExistingServer: !process.env.CI, }, - - /* Configure projects for major browsers */ - projects: [ - { name: 'setup', testMatch: /.*\.setup\.ts/ }, - - { - name: 'chromium', - use: { - ...devices['Desktop Chrome'], - storageState: 'playwright/.auth/user.json', - }, - dependencies: ['setup'], - }, - - // { - // name: 'firefox', - // use: { - // ...devices['Desktop Firefox'], - // storageState: 'playwright/.auth/user.json', - // }, - // dependencies: ['setup'], - // }, - - // { - // name: 'webkit', - // use: { - // ...devices['Desktop Safari'], - // storageState: 'playwright/.auth/user.json', - // }, - // dependencies: ['setup'], - // }, - - /* Test against mobile viewports. */ - // { - // name: 'Mobile Chrome', - // use: { ...devices['Pixel 5'] }, - // }, - // { - // name: 'Mobile Safari', - // use: { ...devices['iPhone 12'] }, - // }, - - /* Test against branded browsers. */ - // { - // name: 'Microsoft Edge', - // use: { ...devices['Desktop Edge'], channel: 'msedge' }, - // }, - // { - // name: 'Google Chrome', - // use: { ...devices['Desktop Chrome'], channel: 'chrome' }, - // }, - ], - - /* Run your local dev server before starting the tests */ - webServer: process.env.PLAYWRIGHT_BASE_URL - ? undefined - : { - command: 'bun run dev', - url: baseURL, - reuseExistingServer: !process.env.CI, - }, -}); +}) diff --git a/frontend/src/client/index.ts b/frontend/src/client/index.ts index f4fdf30796..67e57a211e 100644 --- a/frontend/src/client/index.ts +++ b/frontend/src/client/index.ts @@ -1,4 +1,4 @@ // This file is auto-generated by @hey-api/openapi-ts -export { ItemsService, LoginService, type Options, PrivateService, UsersService, UtilsService } from './sdk.gen'; -export type { Body_login_login_access_token, ClientOptions, HTTPValidationError, ItemCreate, ItemPublic, itemsCreateItemData, itemsCreateItemError, itemsCreateItemErrors, itemsCreateItemResponse, itemsCreateItemResponses, itemsDeleteItemData, itemsDeleteItemError, itemsDeleteItemErrors, itemsDeleteItemResponse, itemsDeleteItemResponses, ItemsPublic, itemsReadItemData, itemsReadItemError, itemsReadItemErrors, itemsReadItemResponse, itemsReadItemResponses, itemsReadItemsData, itemsReadItemsError, itemsReadItemsErrors, itemsReadItemsResponse, itemsReadItemsResponses, itemsUpdateItemData, itemsUpdateItemError, itemsUpdateItemErrors, itemsUpdateItemResponse, itemsUpdateItemResponses, ItemUpdate, loginLoginAccessTokenData, loginLoginAccessTokenError, loginLoginAccessTokenErrors, loginLoginAccessTokenResponse, loginLoginAccessTokenResponses, loginRecoverPasswordData, loginRecoverPasswordError, loginRecoverPasswordErrors, loginRecoverPasswordHtmlContentData, loginRecoverPasswordHtmlContentError, loginRecoverPasswordHtmlContentErrors, loginRecoverPasswordHtmlContentResponse, loginRecoverPasswordHtmlContentResponses, loginRecoverPasswordResponse, loginRecoverPasswordResponses, loginResetPasswordData, loginResetPasswordError, loginResetPasswordErrors, loginResetPasswordResponse, loginResetPasswordResponses, loginTestTokenData, loginTestTokenResponse, loginTestTokenResponses, Message, NewPassword, privateCreateUserData, privateCreateUserError, privateCreateUserErrors, privateCreateUserResponse, privateCreateUserResponses, PrivateUserCreate, Token, UpdatePassword, UserCreate, UserPublic, UserRegister, usersCreateUserData, usersCreateUserError, usersCreateUserErrors, usersCreateUserResponse, usersCreateUserResponses, usersDeleteUserData, usersDeleteUserError, usersDeleteUserErrors, usersDeleteUserMeData, usersDeleteUserMeResponse, usersDeleteUserMeResponses, usersDeleteUserResponse, usersDeleteUserResponses, UsersPublic, usersReadUserByIdData, usersReadUserByIdError, usersReadUserByIdErrors, usersReadUserByIdResponse, usersReadUserByIdResponses, usersReadUserMeData, usersReadUserMeResponse, usersReadUserMeResponses, usersReadUsersData, usersReadUsersError, usersReadUsersErrors, usersReadUsersResponse, usersReadUsersResponses, usersRegisterUserData, usersRegisterUserError, usersRegisterUserErrors, usersRegisterUserResponse, usersRegisterUserResponses, usersUpdatePasswordMeData, usersUpdatePasswordMeError, usersUpdatePasswordMeErrors, usersUpdatePasswordMeResponse, usersUpdatePasswordMeResponses, usersUpdateUserData, usersUpdateUserError, usersUpdateUserErrors, usersUpdateUserMeData, usersUpdateUserMeError, usersUpdateUserMeErrors, usersUpdateUserMeResponse, usersUpdateUserMeResponses, usersUpdateUserResponse, usersUpdateUserResponses, UserUpdate, UserUpdateMe, utilsHealthCheckData, utilsHealthCheckResponse, utilsHealthCheckResponses, utilsTestEmailData, utilsTestEmailError, utilsTestEmailErrors, utilsTestEmailResponse, utilsTestEmailResponses, ValidationError } from './types.gen'; +export { AuthService, ItemsService, type Options, UsersService, UtilsService } from './sdk.gen'; +export type { AuthConfig, authReadAuthConfigData, authReadAuthConfigResponse, authReadAuthConfigResponses, ClientOptions, CurrentUserPublic, HTTPValidationError, ItemCreate, ItemPublic, itemsCreateItemData, itemsCreateItemError, itemsCreateItemErrors, itemsCreateItemResponse, itemsCreateItemResponses, itemsDeleteItemData, itemsDeleteItemError, itemsDeleteItemErrors, itemsDeleteItemResponse, itemsDeleteItemResponses, ItemsPublic, itemsReadItemData, itemsReadItemError, itemsReadItemErrors, itemsReadItemResponse, itemsReadItemResponses, itemsReadItemsData, itemsReadItemsError, itemsReadItemsErrors, itemsReadItemsResponse, itemsReadItemsResponses, itemsUpdateItemData, itemsUpdateItemError, itemsUpdateItemErrors, itemsUpdateItemResponse, itemsUpdateItemResponses, ItemUpdate, Message, UserCreate, UserPublic, usersCreateUserData, usersCreateUserError, usersCreateUserErrors, usersCreateUserResponse, usersCreateUserResponses, usersDeleteUserData, usersDeleteUserError, usersDeleteUserErrors, usersDeleteUserMeData, usersDeleteUserMeResponse, usersDeleteUserMeResponses, usersDeleteUserResponse, usersDeleteUserResponses, UsersPublic, usersReadUserByIdData, usersReadUserByIdError, usersReadUserByIdErrors, usersReadUserByIdResponse, usersReadUserByIdResponses, usersReadUserMeData, usersReadUserMeResponse, usersReadUserMeResponses, usersReadUsersData, usersReadUsersError, usersReadUsersErrors, usersReadUsersResponse, usersReadUsersResponses, usersUpdateUserData, usersUpdateUserError, usersUpdateUserErrors, usersUpdateUserMeData, usersUpdateUserMeError, usersUpdateUserMeErrors, usersUpdateUserMeResponse, usersUpdateUserMeResponses, usersUpdateUserResponse, usersUpdateUserResponses, UserUpdate, UserUpdateMe, utilsHealthCheckData, utilsHealthCheckResponse, utilsHealthCheckResponses, ValidationError } from './types.gen'; diff --git a/frontend/src/client/sdk.gen.ts b/frontend/src/client/sdk.gen.ts index b1dd2cf1d5..2fcee86ab3 100644 --- a/frontend/src/client/sdk.gen.ts +++ b/frontend/src/client/sdk.gen.ts @@ -1,8 +1,8 @@ // This file is auto-generated by @hey-api/openapi-ts -import { type Client, type Options as Options2, type TDataShape, urlSearchParamsBodySerializer } from './client'; +import type { Client, Options as Options2, TDataShape } from './client'; import { client } from './client.gen'; -import type { itemsCreateItemData, itemsCreateItemErrors, itemsCreateItemResponses, itemsDeleteItemData, itemsDeleteItemErrors, itemsDeleteItemResponses, itemsReadItemData, itemsReadItemErrors, itemsReadItemResponses, itemsReadItemsData, itemsReadItemsErrors, itemsReadItemsResponses, itemsUpdateItemData, itemsUpdateItemErrors, itemsUpdateItemResponses, loginLoginAccessTokenData, loginLoginAccessTokenErrors, loginLoginAccessTokenResponses, loginRecoverPasswordData, loginRecoverPasswordErrors, loginRecoverPasswordHtmlContentData, loginRecoverPasswordHtmlContentErrors, loginRecoverPasswordHtmlContentResponses, loginRecoverPasswordResponses, loginResetPasswordData, loginResetPasswordErrors, loginResetPasswordResponses, loginTestTokenData, loginTestTokenResponses, privateCreateUserData, privateCreateUserErrors, privateCreateUserResponses, usersCreateUserData, usersCreateUserErrors, usersCreateUserResponses, usersDeleteUserData, usersDeleteUserErrors, usersDeleteUserMeData, usersDeleteUserMeResponses, usersDeleteUserResponses, usersReadUserByIdData, usersReadUserByIdErrors, usersReadUserByIdResponses, usersReadUserMeData, usersReadUserMeResponses, usersReadUsersData, usersReadUsersErrors, usersReadUsersResponses, usersRegisterUserData, usersRegisterUserErrors, usersRegisterUserResponses, usersUpdatePasswordMeData, usersUpdatePasswordMeErrors, usersUpdatePasswordMeResponses, usersUpdateUserData, usersUpdateUserErrors, usersUpdateUserMeData, usersUpdateUserMeErrors, usersUpdateUserMeResponses, usersUpdateUserResponses, utilsHealthCheckData, utilsHealthCheckResponses, utilsTestEmailData, utilsTestEmailErrors, utilsTestEmailResponses } from './types.gen'; +import type { authReadAuthConfigData, authReadAuthConfigResponses, itemsCreateItemData, itemsCreateItemErrors, itemsCreateItemResponses, itemsDeleteItemData, itemsDeleteItemErrors, itemsDeleteItemResponses, itemsReadItemData, itemsReadItemErrors, itemsReadItemResponses, itemsReadItemsData, itemsReadItemsErrors, itemsReadItemsResponses, itemsUpdateItemData, itemsUpdateItemErrors, itemsUpdateItemResponses, usersCreateUserData, usersCreateUserErrors, usersCreateUserResponses, usersDeleteUserData, usersDeleteUserErrors, usersDeleteUserMeData, usersDeleteUserMeResponses, usersDeleteUserResponses, usersReadUserByIdData, usersReadUserByIdErrors, usersReadUserByIdResponses, usersReadUserMeData, usersReadUserMeResponses, usersReadUsersData, usersReadUsersErrors, usersReadUsersResponses, usersUpdateUserData, usersUpdateUserErrors, usersUpdateUserMeData, usersUpdateUserMeErrors, usersUpdateUserMeResponses, usersUpdateUserResponses, utilsHealthCheckData, utilsHealthCheckResponses } from './types.gen'; export type Options = Options2 & { /** @@ -18,79 +18,16 @@ export type Options; }; -export class LoginService { +export class AuthService { /** - * Login Access Token + * Read Auth Config * - * OAuth2 compatible token login, get an access token for future requests + * Public browser configuration; no API key or server session credentials. */ - public static loginAccessToken(options: Options) { - return (options.client ?? client).post({ - ...urlSearchParamsBodySerializer, + public static readAuthConfig(options?: Options) { + return (options?.client ?? client).get({ responseType: 'json', - url: '/api/v1/login/access-token', - ...options, - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - ...options.headers - } - }); - } - - /** - * Test Token - * - * Test access token - */ - public static testToken(options?: Options) { - return (options?.client ?? client).post({ - responseType: 'json', - security: [{ scheme: 'bearer', type: 'http' }], - url: '/api/v1/login/test-token', - ...options - }); - } - - /** - * Recover Password - * - * Password Recovery - */ - public static recoverPassword(options: Options) { - return (options.client ?? client).post({ - responseType: 'json', - url: '/api/v1/password-recovery/{email}', - ...options - }); - } - - /** - * Reset Password - * - * Reset password - */ - public static resetPassword(options: Options) { - return (options.client ?? client).post({ - responseType: 'json', - url: '/api/v1/reset-password/', - ...options, - headers: { - 'Content-Type': 'application/json', - ...options.headers - } - }); - } - - /** - * Recover Password Html Content - * - * HTML Content for Password Recovery - */ - public static recoverPasswordHtmlContent(options: Options) { - return (options.client ?? client).post({ - responseType: 'text', - security: [{ scheme: 'bearer', type: 'http' }], - url: '/api/v1/password-recovery-html-content/{email}', + url: '/api/v1/auth/config', ...options }); } @@ -99,8 +36,6 @@ export class LoginService { export class UsersService { /** * Read Users - * - * Retrieve users. */ public static readUsers(options?: Options) { return (options?.client ?? client).get({ @@ -114,7 +49,7 @@ export class UsersService { /** * Create User * - * Create new user. + * Create a local profile for an existing tenant-bound canonical actor. */ public static createUser(options: Options) { return (options.client ?? client).post({ @@ -131,8 +66,6 @@ export class UsersService { /** * Delete User Me - * - * Delete own user. */ public static deleteUserMe(options?: Options) { return (options?.client ?? client).delete({ @@ -145,8 +78,6 @@ export class UsersService { /** * Read User Me - * - * Get current user. */ public static readUserMe(options?: Options) { return (options?.client ?? client).get({ @@ -159,8 +90,6 @@ export class UsersService { /** * Update User Me - * - * Update own user. */ public static updateUserMe(options: Options) { return (options.client ?? client).patch({ @@ -175,45 +104,8 @@ export class UsersService { }); } - /** - * Update Password Me - * - * Update own password. - */ - public static updatePasswordMe(options: Options) { - return (options.client ?? client).patch({ - responseType: 'json', - security: [{ scheme: 'bearer', type: 'http' }], - url: '/api/v1/users/me/password', - ...options, - headers: { - 'Content-Type': 'application/json', - ...options.headers - } - }); - } - - /** - * Register User - * - * Create new user without the need to be logged in. - */ - public static registerUser(options: Options) { - return (options.client ?? client).post({ - responseType: 'json', - url: '/api/v1/users/signup', - ...options, - headers: { - 'Content-Type': 'application/json', - ...options.headers - } - }); - } - /** * Delete User - * - * Delete a user. */ public static deleteUser(options: Options) { return (options.client ?? client).delete({ @@ -226,8 +118,6 @@ export class UsersService { /** * Read User By Id - * - * Get a specific user by id. */ public static readUserById(options: Options) { return (options.client ?? client).get({ @@ -240,8 +130,6 @@ export class UsersService { /** * Update User - * - * Update a user. */ public static updateUser(options: Options) { return (options.client ?? client).patch({ @@ -258,20 +146,6 @@ export class UsersService { } export class UtilsService { - /** - * Test Email - * - * Test emails. - */ - public static testEmail(options: Options) { - return (options.client ?? client).post({ - responseType: 'json', - security: [{ scheme: 'bearer', type: 'http' }], - url: '/api/v1/utils/test-email/', - ...options - }); - } - /** * Health Check */ @@ -287,8 +161,6 @@ export class UtilsService { export class ItemsService { /** * Read Items - * - * Retrieve items. */ public static readItems(options?: Options) { return (options?.client ?? client).get({ @@ -301,8 +173,6 @@ export class ItemsService { /** * Create Item - * - * Create new item. */ public static createItem(options: Options) { return (options.client ?? client).post({ @@ -319,8 +189,6 @@ export class ItemsService { /** * Delete Item - * - * Delete an item. */ public static deleteItem(options: Options) { return (options.client ?? client).delete({ @@ -333,8 +201,6 @@ export class ItemsService { /** * Read Item - * - * Get item by ID. */ public static readItem(options: Options) { return (options.client ?? client).get({ @@ -347,8 +213,6 @@ export class ItemsService { /** * Update Item - * - * Update an item. */ public static updateItem(options: Options) { return (options.client ?? client).put({ @@ -363,22 +227,3 @@ export class ItemsService { }); } } - -export class PrivateService { - /** - * Create User - * - * Create a new user. - */ - public static createUser(options: Options) { - return (options.client ?? client).post({ - responseType: 'json', - url: '/api/v1/private/users/', - ...options, - headers: { - 'Content-Type': 'application/json', - ...options.headers - } - }); - } -} diff --git a/frontend/src/client/types.gen.ts b/frontend/src/client/types.gen.ts index 6252d88c2f..b310f66812 100644 --- a/frontend/src/client/types.gen.ts +++ b/frontend/src/client/types.gen.ts @@ -5,33 +5,67 @@ export type ClientOptions = { }; /** - * Body_login-login_access_token + * AuthConfig */ -export type Body_login_login_access_token = { +export type AuthConfig = { /** - * Grant Type + * Client Id */ - grant_type?: string | null; + client_id: string; /** - * Username + * Api Hostname */ - username: string; + api_hostname: string; /** - * Password + * Redirect Uri */ - password: string; + redirect_uri: string; +}; + +/** + * CurrentUserPublic + */ +export type CurrentUserPublic = { /** - * Scope + * Email */ - scope?: string; + email: string; /** - * Client Id + * Is Active + */ + is_active?: boolean; + /** + * Full Name */ - client_id?: string | null; + full_name?: string | null; /** - * Client Secret + * Id */ - client_secret?: string | null; + id: string; + /** + * Created At + */ + created_at: string; + /** + * Tenant Id + */ + tenant_id: string; + /** + * Identity Entity Id + */ + identity_entity_id: string; + /** + * User Role + */ + user_role: string; + /** + * Permissions + */ + permissions: Array; + /** + * Is Tenant Admin + */ + is_tenant_admin: boolean; }; /** @@ -46,6 +80,8 @@ export type HTTPValidationError = { /** * ItemCreate + * + * Item creation accepts content, never caller-supplied attribution. */ export type ItemCreate = { /** @@ -78,10 +114,14 @@ export type ItemPublic = { * Owner Id */ owner_id: string; + /** + * Tenant Id + */ + tenant_id: string; /** * Created At */ - created_at?: string | null; + created_at: string; }; /** @@ -122,70 +162,6 @@ export type Message = { message: string; }; -/** - * NewPassword - */ -export type NewPassword = { - /** - * Token - */ - token: string; - /** - * New Password - */ - new_password: string; -}; - -/** - * PrivateUserCreate - */ -export type PrivateUserCreate = { - /** - * Email - */ - email: string; - /** - * Password - */ - password: string; - /** - * Full Name - */ - full_name: string; - /** - * Is Verified - */ - is_verified?: boolean; -}; - -/** - * Token - */ -export type Token = { - /** - * Access Token - */ - access_token: string; - /** - * Token Type - */ - token_type?: string; -}; - -/** - * UpdatePassword - */ -export type UpdatePassword = { - /** - * Current Password - */ - current_password: string; - /** - * New Password - */ - new_password: string; -}; - /** * UserCreate */ @@ -198,18 +174,14 @@ export type UserCreate = { * Is Active */ is_active?: boolean; - /** - * Is Superuser - */ - is_superuser?: boolean; /** * Full Name */ full_name?: string | null; /** - * Password + * Identity Entity Id */ - password: string; + identity_entity_id: string; }; /** @@ -224,10 +196,6 @@ export type UserPublic = { * Is Active */ is_active?: boolean; - /** - * Is Superuser - */ - is_superuser?: boolean; /** * Full Name */ @@ -239,25 +207,15 @@ export type UserPublic = { /** * Created At */ - created_at?: string | null; -}; - -/** - * UserRegister - */ -export type UserRegister = { - /** - * Email - */ - email: string; + created_at: string; /** - * Password + * Tenant Id */ - password: string; + tenant_id: string; /** - * Full Name + * Identity Entity Id */ - full_name?: string | null; + identity_entity_id: string; }; /** @@ -272,18 +230,10 @@ export type UserUpdate = { * Is Active */ is_active?: boolean | null; - /** - * Is Superuser - */ - is_superuser?: boolean | null; /** * Full Name */ full_name?: string | null; - /** - * Password - */ - password?: string | null; }; /** @@ -342,131 +292,21 @@ export type ValidationError = { }; }; -export type loginLoginAccessTokenData = { - body: Body_login_login_access_token; - path?: never; - query?: never; - url: '/api/v1/login/access-token'; -}; - -export type loginLoginAccessTokenErrors = { - /** - * Validation Error - */ - 422: HTTPValidationError; -}; - -export type loginLoginAccessTokenError = loginLoginAccessTokenErrors[keyof loginLoginAccessTokenErrors]; - -export type loginLoginAccessTokenResponses = { - /** - * Successful Response - */ - 200: Token; -}; - -export type loginLoginAccessTokenResponse = loginLoginAccessTokenResponses[keyof loginLoginAccessTokenResponses]; - -export type loginTestTokenData = { - body?: never; - path?: never; - query?: never; - url: '/api/v1/login/test-token'; -}; - -export type loginTestTokenResponses = { - /** - * Successful Response - */ - 200: UserPublic; -}; - -export type loginTestTokenResponse = loginTestTokenResponses[keyof loginTestTokenResponses]; - -export type loginRecoverPasswordData = { +export type authReadAuthConfigData = { body?: never; - path: { - /** - * Email - */ - email: string; - }; - query?: never; - url: '/api/v1/password-recovery/{email}'; -}; - -export type loginRecoverPasswordErrors = { - /** - * Validation Error - */ - 422: HTTPValidationError; -}; - -export type loginRecoverPasswordError = loginRecoverPasswordErrors[keyof loginRecoverPasswordErrors]; - -export type loginRecoverPasswordResponses = { - /** - * Successful Response - */ - 200: Message; -}; - -export type loginRecoverPasswordResponse = loginRecoverPasswordResponses[keyof loginRecoverPasswordResponses]; - -export type loginResetPasswordData = { - body: NewPassword; path?: never; query?: never; - url: '/api/v1/reset-password/'; -}; - -export type loginResetPasswordErrors = { - /** - * Validation Error - */ - 422: HTTPValidationError; + url: '/api/v1/auth/config'; }; -export type loginResetPasswordError = loginResetPasswordErrors[keyof loginResetPasswordErrors]; - -export type loginResetPasswordResponses = { +export type authReadAuthConfigResponses = { /** * Successful Response */ - 200: Message; + 200: AuthConfig; }; -export type loginResetPasswordResponse = loginResetPasswordResponses[keyof loginResetPasswordResponses]; - -export type loginRecoverPasswordHtmlContentData = { - body?: never; - path: { - /** - * Email - */ - email: string; - }; - query?: never; - url: '/api/v1/password-recovery-html-content/{email}'; -}; - -export type loginRecoverPasswordHtmlContentErrors = { - /** - * Validation Error - */ - 422: HTTPValidationError; -}; - -export type loginRecoverPasswordHtmlContentError = loginRecoverPasswordHtmlContentErrors[keyof loginRecoverPasswordHtmlContentErrors]; - -export type loginRecoverPasswordHtmlContentResponses = { - /** - * Successful Response - */ - 200: string; -}; - -export type loginRecoverPasswordHtmlContentResponse = loginRecoverPasswordHtmlContentResponses[keyof loginRecoverPasswordHtmlContentResponses]; +export type authReadAuthConfigResponse = authReadAuthConfigResponses[keyof authReadAuthConfigResponses]; export type usersReadUsersData = { body?: never; @@ -554,7 +394,7 @@ export type usersReadUserMeResponses = { /** * Successful Response */ - 200: UserPublic; + 200: CurrentUserPublic; }; export type usersReadUserMeResponse = usersReadUserMeResponses[keyof usersReadUserMeResponses]; @@ -584,56 +424,6 @@ export type usersUpdateUserMeResponses = { export type usersUpdateUserMeResponse = usersUpdateUserMeResponses[keyof usersUpdateUserMeResponses]; -export type usersUpdatePasswordMeData = { - body: UpdatePassword; - path?: never; - query?: never; - url: '/api/v1/users/me/password'; -}; - -export type usersUpdatePasswordMeErrors = { - /** - * Validation Error - */ - 422: HTTPValidationError; -}; - -export type usersUpdatePasswordMeError = usersUpdatePasswordMeErrors[keyof usersUpdatePasswordMeErrors]; - -export type usersUpdatePasswordMeResponses = { - /** - * Successful Response - */ - 200: Message; -}; - -export type usersUpdatePasswordMeResponse = usersUpdatePasswordMeResponses[keyof usersUpdatePasswordMeResponses]; - -export type usersRegisterUserData = { - body: UserRegister; - path?: never; - query?: never; - url: '/api/v1/users/signup'; -}; - -export type usersRegisterUserErrors = { - /** - * Validation Error - */ - 422: HTTPValidationError; -}; - -export type usersRegisterUserError = usersRegisterUserErrors[keyof usersRegisterUserErrors]; - -export type usersRegisterUserResponses = { - /** - * Successful Response - */ - 200: UserPublic; -}; - -export type usersRegisterUserResponse = usersRegisterUserResponses[keyof usersRegisterUserResponses]; - export type usersDeleteUserData = { body?: never; path: { @@ -724,36 +514,6 @@ export type usersUpdateUserResponses = { export type usersUpdateUserResponse = usersUpdateUserResponses[keyof usersUpdateUserResponses]; -export type utilsTestEmailData = { - body?: never; - path?: never; - query: { - /** - * Email To - */ - email_to: string; - }; - url: '/api/v1/utils/test-email/'; -}; - -export type utilsTestEmailErrors = { - /** - * Validation Error - */ - 422: HTTPValidationError; -}; - -export type utilsTestEmailError = utilsTestEmailErrors[keyof utilsTestEmailErrors]; - -export type utilsTestEmailResponses = { - /** - * Successful Response - */ - 201: Message; -}; - -export type utilsTestEmailResponse = utilsTestEmailResponses[keyof utilsTestEmailResponses]; - export type utilsHealthCheckData = { body?: never; path?: never; @@ -920,28 +680,3 @@ export type itemsUpdateItemResponses = { }; export type itemsUpdateItemResponse = itemsUpdateItemResponses[keyof itemsUpdateItemResponses]; - -export type privateCreateUserData = { - body: PrivateUserCreate; - path?: never; - query?: never; - url: '/api/v1/private/users/'; -}; - -export type privateCreateUserErrors = { - /** - * Validation Error - */ - 422: HTTPValidationError; -}; - -export type privateCreateUserError = privateCreateUserErrors[keyof privateCreateUserErrors]; - -export type privateCreateUserResponses = { - /** - * Successful Response - */ - 200: UserPublic; -}; - -export type privateCreateUserResponse = privateCreateUserResponses[keyof privateCreateUserResponses]; diff --git a/frontend/src/components/Admin/AddUser.tsx b/frontend/src/components/Admin/AddUser.tsx index 0cb83b2d46..e7b1fd4853 100644 --- a/frontend/src/components/Admin/AddUser.tsx +++ b/frontend/src/components/Admin/AddUser.tsx @@ -31,24 +31,14 @@ import { LoadingButton } from "@/components/ui/loading-button" import useCustomToast from "@/hooks/useCustomToast" import { handleError } from "@/utils" -const formSchema = z - .object({ - email: z.email({ message: "Invalid email address" }), - full_name: z.string().optional(), - password: z - .string() - .min(1, { message: "Password is required" }) - .min(8, { message: "Password must be at least 8 characters" }), - confirm_password: z - .string() - .min(1, { message: "Please confirm your password" }), - is_superuser: z.boolean(), - is_active: z.boolean(), - }) - .refine((data) => data.password === data.confirm_password, { - message: "The passwords don't match", - path: ["confirm_password"], - }) +const formSchema = z.object({ + email: z.email({ message: "Invalid email address" }), + full_name: z.string().optional(), + identity_entity_id: z.uuid({ + message: "A canonical identity UUID is required", + }), + is_active: z.boolean(), +}) type FormData = z.infer @@ -64,9 +54,7 @@ const AddUser = () => { defaultValues: { email: "", full_name: "", - password: "", - confirm_password: "", - is_superuser: false, + identity_entity_id: "", is_active: false, }, }) @@ -143,63 +131,18 @@ const AddUser = () => { ( - - Set Password * - + Canonical identity UUID - + )} /> - ( - - - Confirm Password{" "} - * - - - - - - - )} - /> - - ( - - - - - Is superuser? - - )} - /> - !data.password || data.password === data.confirm_password, { - message: "The passwords don't match", - path: ["confirm_password"], - }) +const formSchema = z.object({ + email: z.email({ message: "Invalid email address" }), + full_name: z.string().optional(), + is_active: z.boolean().optional(), +}) type FormData = z.infer @@ -68,7 +56,6 @@ const EditUser = ({ user, onSuccess }: EditUserProps) => { defaultValues: { email: user.email, full_name: user.full_name ?? undefined, - is_superuser: user.is_superuser, is_active: user.is_active, }, }) @@ -87,14 +74,7 @@ const EditUser = ({ user, onSuccess }: EditUserProps) => { }, }) - const onSubmit = (data: FormData) => { - // exclude confirm_password from submission data and remove password if empty - const { confirm_password: _, ...submitData } = data - if (!submitData.password) { - delete submitData.password - } - mutation.mutate(submitData) - } + const onSubmit = (data: FormData) => mutation.mutate(data) return ( @@ -150,58 +130,6 @@ const EditUser = ({ user, onSuccess }: EditUserProps) => { )} /> - ( - - Set Password - - - - - - )} - /> - - ( - - Confirm Password - - - - - - )} - /> - - ( - - - - - Is superuser? - - )} - /> - { const [open, setOpen] = useState(false) const { user: currentUser } = useAuth() - if (user.id === currentUser?.id) { + if ( + !currentUser?.is_tenant_admin || + !currentUser.permissions.includes("org:projects:write") || + user.id === currentUser.id + ) { return null } diff --git a/frontend/src/components/Admin/columns.tsx b/frontend/src/components/Admin/columns.tsx index c77a2cf8ec..d99513f743 100644 --- a/frontend/src/components/Admin/columns.tsx +++ b/frontend/src/components/Admin/columns.tsx @@ -40,13 +40,9 @@ export const columns: ColumnDef[] = [ ), }, { - accessorKey: "is_superuser", - header: "Role", - cell: ({ row }) => ( - - {row.original.is_superuser ? "Superuser" : "User"} - - ), + accessorKey: "identity_entity_id", + header: "Canonical identity", + cell: ({ row }) => {row.original.identity_entity_id}, }, { accessorKey: "is_active", diff --git a/frontend/src/components/AuthProvider.tsx b/frontend/src/components/AuthProvider.tsx new file mode 100644 index 0000000000..2d1fb599d1 --- /dev/null +++ b/frontend/src/components/AuthProvider.tsx @@ -0,0 +1,252 @@ +import { + QueryClient, + QueryClientProvider, + useQuery, +} from "@tanstack/react-query" +import { + AuthKitProvider, + getClaims, + useAuth as useAuthKit, +} from "@workos-inc/authkit-react" +import { + createContext, + type ReactNode, + useContext, + useEffect, + useRef, + useState, +} from "react" +import { flushSync } from "react-dom" +import { z } from "zod" +import { UsersService } from "@/client" +import { client } from "@/client/client.gen" +import { createSessionTransport } from "@/lib/session-transport" + +const configSchema = z.object({ + client_id: z.string().startsWith("client_"), + api_hostname: z.string().min(1), + redirect_uri: z.url(), +}) +const baseURL = import.meta.env.VITE_API_URL ?? "" + +const SessionControl = createContext<{ + transition: (organizationId: string) => Promise + logout: () => void +} | null>(null) + +export function useSessionControl() { + const control = useContext(SessionControl) + if (!control) throw new Error("Session boundary missing") + return control +} + +export function AuthProvider({ children }: { children: ReactNode }) { + const [refreshGeneration, setRefreshGeneration] = useState(0) + const [expired, setExpired] = useState(false) + const config = useQuery({ + queryKey: ["auth-config"], + queryFn: async ({ signal }) => { + const response = await fetch(`${baseURL}/api/v1/auth/config`, { signal }) + if (!response.ok) + throw new Error("Authentication configuration unavailable") + return configSchema.parse(await response.json()) + }, + retry: false, + staleTime: Infinity, + }) + if (config.isPending) + return

Loading sign-in configuration…

+ if (config.isError) + return ( +

+ Sign-in configuration unavailable. Contact your administrator. +

+ ) + return ( + { + setExpired(false) + setRefreshGeneration((value) => value + 1) + }} + onRefreshFailure={() => setExpired(true)} + > + {expired ? ( +
+ Session expired. Sign in again +
+ ) : ( + + {children} + + )} +
+ ) +} + +function SessionBoundary({ + children, + refreshGeneration, +}: { + children: ReactNode + refreshGeneration: number +}) { + const { + user, + organizationId, + isLoading, + getAccessToken, + switchToOrganization, + signOut, + } = useAuthKit() + const [switching, setSwitching] = useState(false) + const [generation, setGeneration] = useState(0) + const [switchError, setSwitchError] = useState(false) + const [signedOut, setSignedOut] = useState(false) + const [authorizationKey, setAuthorizationKey] = useState("") + const logout = () => { + flushSync(() => setSignedOut(true)) + signOut() + } + const transition = async (nextOrganizationId: string) => { + flushSync(() => { + setSwitching(true) + setSwitchError(false) + }) + try { + await switchToOrganization({ organizationId: nextOrganizationId }) + const token = await getAccessToken() + if (getClaims(token).org_id !== nextOrganizationId) { + throw new Error("SDK did not select the requested organization") + } + } catch { + setSwitchError(true) + } finally { + setGeneration((value) => value + 1) + setSwitching(false) + } + } + if (signedOut) + return ( +

+ Signing out… Return to sign-in +

+ ) + if (isLoading || switching) return

Loading session…

+ return ( + + {switchError &&

Unable to select this organization.

} + + {children} + +
+ ) +} + +function SessionRuntime({ + children, + getAccessToken, + refreshGeneration, + authorizationKey, + onAuthorizationChange, +}: { + children: ReactNode + getAccessToken: () => Promise + refreshGeneration: number + authorizationKey: string + onAuthorizationChange: (key: string) => void +}) { + const [queryClient] = useState( + () => new QueryClient({ defaultOptions: { queries: { retry: false } } }), + ) + const [ready, setReady] = useState(false) + useEffect(() => { + const transport = createSessionTransport(getAccessToken) + client.setConfig({ + baseURL, + auth: transport.auth, + signal: transport.signal, + throwOnError: true, + }) + setReady(true) + return () => { + transport.dispose() + void queryClient.cancelQueries() + queryClient.clear() + } + }, [getAccessToken, queryClient]) + if (!ready) return

Preparing session…

+ return ( + + + {children} + + + ) +} + +function ProfileAuthorization({ + children, + refreshGeneration, + expectedAuthorizationKey, + onAuthorizationChange, + queryClient, +}: { + children: ReactNode + refreshGeneration: number + expectedAuthorizationKey: string + onAuthorizationChange: (key: string) => void + queryClient: QueryClient +}) { + const { user, organizationId, isLoading } = useAuthKit() + const previousRefresh = useRef(refreshGeneration) + const profile = useQuery({ + queryKey: ["currentUser", user?.id, organizationId], + queryFn: async ({ signal }) => + (await UsersService.readUserMe({ signal })).data, + enabled: Boolean(user && organizationId) && !isLoading, + retry: false, + }) + useEffect(() => { + if (previousRefresh.current === refreshGeneration) return + previousRefresh.current = refreshGeneration + void queryClient.invalidateQueries({ queryKey: ["currentUser"] }) + }, [refreshGeneration, queryClient]) + const authorizationKey = profile.isError + ? "denied" + : profile.data + ? JSON.stringify([ + profile.data.id, + profile.data.tenant_id, + profile.data.identity_entity_id, + profile.data.is_active, + profile.data.user_role, + profile.data.is_tenant_admin, + [...profile.data.permissions].sort(), + ]) + : null + useEffect(() => { + if (authorizationKey !== null) onAuthorizationChange(authorizationKey) + }, [authorizationKey, onAuthorizationChange]) + if ( + authorizationKey !== null && + authorizationKey !== expectedAuthorizationKey + ) { + return

Applying tenant authorization…

+ } + return children +} diff --git a/frontend/src/components/HostedSignIn.tsx b/frontend/src/components/HostedSignIn.tsx new file mode 100644 index 0000000000..50452762f5 --- /dev/null +++ b/frontend/src/components/HostedSignIn.tsx @@ -0,0 +1,29 @@ +import { useAuth } from "@workos-inc/authkit-react" +import { useEffect, useRef, useState } from "react" + +export default function HostedSignIn({ signUp = false }: { signUp?: boolean }) { + const auth = useAuth() + const started = useRef(false) + const [failed, setFailed] = useState(false) + useEffect(() => { + if (auth.isLoading || started.current) return + started.current = true + const search = new URLSearchParams(window.location.search) + const options = { + invitationToken: search.get("invitation_token") ?? undefined, + passwordResetToken: search.get("password_reset_token") ?? undefined, + organizationId: search.get("organization_id") ?? undefined, + loginHint: search.get("login_hint") ?? undefined, + } + void (signUp ? auth.signUp(options) : auth.signIn(options)).catch(() => + setFailed(true), + ) + }, [auth.isLoading, auth.signIn, auth.signUp, signUp]) + return ( +

+ {failed + ? "Unable to start sign-in. Reload to try again." + : "Redirecting to secure sign-in…"} +

+ ) +} diff --git a/frontend/src/components/Items/ItemActionsMenu.tsx b/frontend/src/components/Items/ItemActionsMenu.tsx index 1efe7bf719..b6acacb88d 100644 --- a/frontend/src/components/Items/ItemActionsMenu.tsx +++ b/frontend/src/components/Items/ItemActionsMenu.tsx @@ -8,6 +8,7 @@ import { DropdownMenuContent, DropdownMenuTrigger, } from "@/components/ui/dropdown-menu" +import useAuth from "@/hooks/useAuth" import DeleteItem from "../Items/DeleteItem" import EditItem from "../Items/EditItem" @@ -17,6 +18,8 @@ interface ItemActionsMenuProps { export const ItemActionsMenu = ({ item }: ItemActionsMenuProps) => { const [open, setOpen] = useState(false) + const { user } = useAuth() + if (!user?.permissions.includes("org:projects:write")) return null return ( diff --git a/frontend/src/components/OrganizationSwitcher.tsx b/frontend/src/components/OrganizationSwitcher.tsx new file mode 100644 index 0000000000..0c346eb75c --- /dev/null +++ b/frontend/src/components/OrganizationSwitcher.tsx @@ -0,0 +1,25 @@ +import { useState } from "react" +import { useSessionControl } from "@/components/AuthProvider" + +export default function OrganizationSwitcher() { + const { transition } = useSessionControl() + const [organizationId, setOrganizationId] = useState("") + return ( +
{ + event.preventDefault() + void transition(organizationId) + }} + > + + +
+ ) +} diff --git a/frontend/src/components/Sidebar/AppSidebar.tsx b/frontend/src/components/Sidebar/AppSidebar.tsx index 8502bcb9a4..c9795f72e9 100644 --- a/frontend/src/components/Sidebar/AppSidebar.tsx +++ b/frontend/src/components/Sidebar/AppSidebar.tsx @@ -20,7 +20,7 @@ const baseItems: Item[] = [ export function AppSidebar() { const { user: currentUser } = useAuth() - const items = currentUser?.is_superuser + const items = currentUser?.is_tenant_admin ? [...baseItems, { icon: Users, title: "Admin", path: "/admin" }] : baseItems diff --git a/frontend/src/components/Sidebar/User.tsx b/frontend/src/components/Sidebar/User.tsx index 12c6362aff..ecd1b2f4a0 100644 --- a/frontend/src/components/Sidebar/User.tsx +++ b/frontend/src/components/Sidebar/User.tsx @@ -1,6 +1,7 @@ import { Link as RouterLink } from "@tanstack/react-router" import { ChevronsUpDown, LogOut, Settings } from "lucide-react" +import type { UserPublic } from "@/client" import { Avatar, AvatarFallback } from "@/components/ui/avatar" import { DropdownMenu, @@ -40,7 +41,7 @@ function UserInfo({ fullName, email }: UserInfoProps) { ) } -export function User({ user }: { user: any }) { +export function User({ user }: { user: UserPublic | undefined }) { const { logout } = useAuth() const { isMobile, setOpenMobile } = useSidebar() @@ -65,7 +66,10 @@ export function User({ user }: { user: any }) { className="data-[state=open]:bg-sidebar-accent data-[state=open]:text-sidebar-accent-foreground" data-testid="user-menu" > - + @@ -76,7 +80,10 @@ export function User({ user }: { user: any }) { sideOffset={4} > - + diff --git a/frontend/src/components/UserSettings/ChangePassword.tsx b/frontend/src/components/UserSettings/ChangePassword.tsx deleted file mode 100644 index c2784d377f..0000000000 --- a/frontend/src/components/UserSettings/ChangePassword.tsx +++ /dev/null @@ -1,146 +0,0 @@ -import { zodResolver } from "@hookform/resolvers/zod" -import { useMutation } from "@tanstack/react-query" -import { useForm } from "react-hook-form" -import { z } from "zod" - -import { type UpdatePassword, UsersService } from "@/client" -import { - Form, - FormControl, - FormField, - FormItem, - FormLabel, - FormMessage, -} from "@/components/ui/form" -import { LoadingButton } from "@/components/ui/loading-button" -import { PasswordInput } from "@/components/ui/password-input" -import useCustomToast from "@/hooks/useCustomToast" -import { handleError } from "@/utils" - -const formSchema = z - .object({ - current_password: z - .string() - .min(1, { message: "Password is required" }) - .min(8, { message: "Password must be at least 8 characters" }), - new_password: z - .string() - .min(1, { message: "Password is required" }) - .min(8, { message: "Password must be at least 8 characters" }), - confirm_password: z - .string() - .min(1, { message: "Password confirmation is required" }), - }) - .refine((data) => data.new_password === data.confirm_password, { - message: "The passwords don't match", - path: ["confirm_password"], - }) - -type FormData = z.infer - -const ChangePassword = () => { - const { showSuccessToast, showErrorToast } = useCustomToast() - const form = useForm({ - resolver: zodResolver(formSchema), - mode: "onSubmit", - criteriaMode: "all", - defaultValues: { - current_password: "", - new_password: "", - confirm_password: "", - }, - }) - - const mutation = useMutation({ - mutationFn: (data: UpdatePassword) => - UsersService.updatePasswordMe({ body: data }), - onSuccess: () => { - showSuccessToast("Password updated successfully") - form.reset() - }, - onError: handleError.bind(showErrorToast), - }) - - const onSubmit = async (data: FormData) => { - mutation.mutate(data) - } - - return ( -
-

Change Password

-
- - ( - - Current Password - - - - - - )} - /> - - ( - - New Password - - - - - - )} - /> - - ( - - Confirm Password - - - - - - )} - /> - - - Update Password - - - -
- ) -} - -export default ChangePassword diff --git a/frontend/src/components/UserSettings/UserInformation.tsx b/frontend/src/components/UserSettings/UserInformation.tsx index 93a65aa43c..d6530e839f 100644 --- a/frontend/src/components/UserSettings/UserInformation.tsx +++ b/frontend/src/components/UserSettings/UserInformation.tsx @@ -157,7 +157,13 @@ const UserInformation = () => { ) : ( - )} diff --git a/frontend/src/components/ui/password-input.tsx b/frontend/src/components/ui/password-input.tsx deleted file mode 100644 index 9e03d1257f..0000000000 --- a/frontend/src/components/ui/password-input.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import * as React from "react" -import { Eye, EyeOff } from "lucide-react" - -import { cn } from "@/lib/utils" -import { Button } from "./button" - -interface PasswordInputProps extends React.ComponentProps<"input"> { - error?: string -} - -const PasswordInput = React.forwardRef( - ({ className, error, ...props }, ref) => { - const [showPassword, setShowPassword] = React.useState(false) - - return ( -
- - -
- ) - } -) - -PasswordInput.displayName = "PasswordInput" - -export { PasswordInput } diff --git a/frontend/src/hooks/useAuth.ts b/frontend/src/hooks/useAuth.ts index 051b222aee..355cb31a02 100644 --- a/frontend/src/hooks/useAuth.ts +++ b/frontend/src/hooks/useAuth.ts @@ -1,70 +1,22 @@ -import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query" -import { useNavigate } from "@tanstack/react-router" - -import { - type Body_login_login_access_token as AccessToken, - LoginService, - type UserPublic, - type UserRegister, - UsersService, -} from "@/client" -import { handleError } from "@/utils" -import useCustomToast from "./useCustomToast" - -const isLoggedIn = () => { - return localStorage.getItem("access_token") !== null -} - -const useAuth = () => { - const navigate = useNavigate() - const queryClient = useQueryClient() - const { showErrorToast } = useCustomToast() - - const { data: user } = useQuery({ - queryKey: ["currentUser"], - queryFn: async () => (await UsersService.readUserMe()).data, - enabled: isLoggedIn(), - }) - - const signUpMutation = useMutation({ - mutationFn: (data: UserRegister) => - UsersService.registerUser({ body: data }), - onSuccess: () => { - navigate({ to: "/login" }) - }, - onError: handleError.bind(showErrorToast), - onSettled: () => { - queryClient.invalidateQueries({ queryKey: ["users"] }) - }, +import { useQuery } from "@tanstack/react-query" +import { useAuth as useAuthKit } from "@workos-inc/authkit-react" +import { UsersService } from "@/client" +import { useSessionControl } from "@/components/AuthProvider" + +export default function useAuth() { + const auth = useAuthKit() + const { logout } = useSessionControl() + const profile = useQuery({ + queryKey: ["currentUser", auth.user?.id, auth.organizationId], + queryFn: async ({ signal }) => + (await UsersService.readUserMe({ signal })).data, + enabled: Boolean(auth.user && auth.organizationId) && !auth.isLoading, + retry: false, }) - - const login = async (data: AccessToken) => { - const response = await LoginService.loginAccessToken({ - body: data, - }) - localStorage.setItem("access_token", response.data.access_token) - } - - const loginMutation = useMutation({ - mutationFn: login, - onSuccess: () => { - navigate({ to: "/" }) - }, - onError: handleError.bind(showErrorToast), - }) - - const logout = () => { - localStorage.removeItem("access_token") - navigate({ to: "/login" }) - } - return { - signUpMutation, - loginMutation, + ...auth, + user: profile.data, + profile, logout, - user, } } - -export { isLoggedIn } -export default useAuth diff --git a/frontend/src/lib/session-transport.ts b/frontend/src/lib/session-transport.ts new file mode 100644 index 0000000000..42dd473a1d --- /dev/null +++ b/frontend/src/lib/session-transport.ts @@ -0,0 +1,15 @@ +export function createSessionTransport(getAccessToken: () => Promise) { + const controller = new AbortController() + return { + signal: controller.signal, + async auth() { + if (controller.signal.aborted) throw new Error("Session changed") + const token = await getAccessToken() + if (controller.signal.aborted) throw new Error("Session changed") + return token + }, + dispose() { + controller.abort() + }, + } +} diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index f8275a3472..b552e8df83 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -1,42 +1,14 @@ -import { - MutationCache, - QueryCache, - QueryClient, - QueryClientProvider, -} from "@tanstack/react-query" +import { QueryClient, QueryClientProvider } from "@tanstack/react-query" import { createRouter, RouterProvider } from "@tanstack/react-router" -import { AxiosError } from "axios" import { StrictMode } from "react" import ReactDOM from "react-dom/client" -import { client } from "./client/client.gen" +import { AuthProvider } from "./components/AuthProvider" import { ThemeProvider } from "./components/theme-provider" import { Toaster } from "./components/ui/sonner" import "./index.css" import { routeTree } from "./routeTree.gen" -client.setConfig({ - baseURL: import.meta.env.VITE_API_URL ?? "", - auth: () => localStorage.getItem("access_token") || "", -}) - -const handleApiError = (error: Error) => { - if ( - error instanceof AxiosError && - [401, 403].includes(error.response?.status ?? 0) - ) { - localStorage.removeItem("access_token") - window.location.href = "/login" - } -} -const queryClient = new QueryClient({ - queryCache: new QueryCache({ - onError: handleApiError, - }), - mutationCache: new MutationCache({ - onError: handleApiError, - }), -}) - +const queryClient = new QueryClient() const router = createRouter({ routeTree }) declare module "@tanstack/react-router" { interface Register { @@ -48,8 +20,10 @@ ReactDOM.createRoot(document.getElementById("root")!).render( - - + + + + , diff --git a/frontend/src/routeTree.gen.ts b/frontend/src/routeTree.gen.ts index b45f83a1d3..df6dab6fd1 100644 --- a/frontend/src/routeTree.gen.ts +++ b/frontend/src/routeTree.gen.ts @@ -11,8 +11,6 @@ import { Route as rootRouteImport } from './routes/__root' import { Route as LayoutRouteImport } from './routes/_layout' import { Route as LoginRouteImport } from './routes/login' -import { Route as RecoverPasswordRouteImport } from './routes/recover-password' -import { Route as ResetPasswordRouteImport } from './routes/reset-password' import { Route as SignupRouteImport } from './routes/signup' import { Route as LayoutIndexRouteImport } from './routes/_layout/index' import { Route as LayoutAdminRouteImport } from './routes/_layout/admin' @@ -28,16 +26,6 @@ const LoginRoute = LoginRouteImport.update({ path: '/login', getParentRoute: () => rootRouteImport, } as any) -const RecoverPasswordRoute = RecoverPasswordRouteImport.update({ - id: '/recover-password', - path: '/recover-password', - getParentRoute: () => rootRouteImport, -} as any) -const ResetPasswordRoute = ResetPasswordRouteImport.update({ - id: '/reset-password', - path: '/reset-password', - getParentRoute: () => rootRouteImport, -} as any) const SignupRoute = SignupRouteImport.update({ id: '/signup', path: '/signup', @@ -67,8 +55,6 @@ const LayoutSettingsRoute = LayoutSettingsRouteImport.update({ export interface FileRoutesByFullPath { '/': typeof LayoutIndexRoute '/login': typeof LoginRoute - '/recover-password': typeof RecoverPasswordRoute - '/reset-password': typeof ResetPasswordRoute '/signup': typeof SignupRoute '/admin': typeof LayoutAdminRoute '/items': typeof LayoutItemsRoute @@ -76,8 +62,6 @@ export interface FileRoutesByFullPath { } export interface FileRoutesByTo { '/login': typeof LoginRoute - '/recover-password': typeof RecoverPasswordRoute - '/reset-password': typeof ResetPasswordRoute '/signup': typeof SignupRoute '/admin': typeof LayoutAdminRoute '/items': typeof LayoutItemsRoute @@ -88,8 +72,6 @@ export interface FileRoutesById { __root__: typeof rootRouteImport '/_layout': typeof LayoutRouteWithChildren '/login': typeof LoginRoute - '/recover-password': typeof RecoverPasswordRoute - '/reset-password': typeof ResetPasswordRoute '/signup': typeof SignupRoute '/_layout/admin': typeof LayoutAdminRoute '/_layout/items': typeof LayoutItemsRoute @@ -98,31 +80,13 @@ export interface FileRoutesById { } export interface FileRouteTypes { fileRoutesByFullPath: FileRoutesByFullPath - fullPaths: - | '/' - | '/login' - | '/recover-password' - | '/reset-password' - | '/signup' - | '/admin' - | '/items' - | '/settings' + fullPaths: '/' | '/login' | '/signup' | '/admin' | '/items' | '/settings' fileRoutesByTo: FileRoutesByTo - to: - | '/login' - | '/recover-password' - | '/reset-password' - | '/signup' - | '/admin' - | '/items' - | '/settings' - | '/' + to: '/login' | '/signup' | '/admin' | '/items' | '/settings' | '/' id: | '__root__' | '/_layout' | '/login' - | '/recover-password' - | '/reset-password' | '/signup' | '/_layout/admin' | '/_layout/items' @@ -133,8 +97,6 @@ export interface FileRouteTypes { export interface RootRouteChildren { LayoutRoute: typeof LayoutRouteWithChildren LoginRoute: typeof LoginRoute - RecoverPasswordRoute: typeof RecoverPasswordRoute - ResetPasswordRoute: typeof ResetPasswordRoute SignupRoute: typeof SignupRoute } @@ -154,20 +116,6 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof LoginRouteImport parentRoute: typeof rootRouteImport } - '/recover-password': { - id: '/recover-password' - path: '/recover-password' - fullPath: '/recover-password' - preLoaderRoute: typeof RecoverPasswordRouteImport - parentRoute: typeof rootRouteImport - } - '/reset-password': { - id: '/reset-password' - path: '/reset-password' - fullPath: '/reset-password' - preLoaderRoute: typeof ResetPasswordRouteImport - parentRoute: typeof rootRouteImport - } '/signup': { id: '/signup' path: '/signup' @@ -226,8 +174,6 @@ const LayoutRouteWithChildren = const rootRouteChildren: RootRouteChildren = { LayoutRoute: LayoutRouteWithChildren, LoginRoute: LoginRoute, - RecoverPasswordRoute: RecoverPasswordRoute, - ResetPasswordRoute: ResetPasswordRoute, SignupRoute: SignupRoute, } export const routeTree = rootRouteImport diff --git a/frontend/src/routes/_layout.tsx b/frontend/src/routes/_layout.tsx index 7bafdf725e..a14cb1d91c 100644 --- a/frontend/src/routes/_layout.tsx +++ b/frontend/src/routes/_layout.tsx @@ -1,32 +1,59 @@ -import { createFileRoute, Outlet, redirect } from "@tanstack/react-router" - +import { createFileRoute, Outlet } from "@tanstack/react-router" import { Footer } from "@/components/Common/Footer" +import OrganizationSwitcher from "@/components/OrganizationSwitcher" import AppSidebar from "@/components/Sidebar/AppSidebar" import { SidebarInset, SidebarProvider, SidebarTrigger, } from "@/components/ui/sidebar" -import { isLoggedIn } from "@/hooks/useAuth" +import useAuth from "@/hooks/useAuth" export const Route = createFileRoute("/_layout")({ component: Layout, - beforeLoad: async () => { - if (!isLoggedIn()) { - throw redirect({ - to: "/login", - }) - } - }, }) function Layout() { + const { user, profile, isLoading, organizationId, getUser, signIn, logout } = + useAuth() + if (isLoading) return

Loading session…

+ if (!getUser()) + return ( +
+

Sign in to continue.

+ +
+ ) + if (!organizationId) + return ( +
+

Select an organization to continue.

+ + +
+ ) + if (profile.isPending) return

Loading tenant profile…

+ if (profile.isError || !user) + return ( +
+ Access to this organization is unavailable. + +
+ ) return (
+ {organizationId} +
diff --git a/frontend/src/routes/_layout/admin.tsx b/frontend/src/routes/_layout/admin.tsx index 39241c23ca..eca5e88616 100644 --- a/frontend/src/routes/_layout/admin.tsx +++ b/frontend/src/routes/_layout/admin.tsx @@ -1,5 +1,5 @@ import { useSuspenseQuery } from "@tanstack/react-query" -import { createFileRoute, redirect } from "@tanstack/react-router" +import { createFileRoute } from "@tanstack/react-router" import { Suspense } from "react" import { type UserPublic, UsersService } from "@/client" @@ -11,22 +11,15 @@ import useAuth from "@/hooks/useAuth" function getUsersQueryOptions() { return { - queryFn: async () => - (await UsersService.readUsers({ query: { skip: 0, limit: 100 } })).data, + queryFn: async ({ signal }: { signal: AbortSignal }) => + (await UsersService.readUsers({ query: { skip: 0, limit: 100 }, signal })) + .data, queryKey: ["users"], } } export const Route = createFileRoute("/_layout/admin")({ component: Admin, - beforeLoad: async () => { - const { data: user } = await UsersService.readUserMe() - if (!user.is_superuser) { - throw redirect({ - to: "/", - }) - } - }, head: () => ({ meta: [ { @@ -57,6 +50,9 @@ function UsersTable() { } function Admin() { + const { user } = useAuth() + if (!user?.is_tenant_admin || !user.permissions.includes("org:projects:read")) + return

Tenant administrator access required.

return (
@@ -66,7 +62,7 @@ function Admin() { Manage user accounts and permissions

- + {user.permissions.includes("org:projects:write") && }
diff --git a/frontend/src/routes/_layout/items.tsx b/frontend/src/routes/_layout/items.tsx index 0dbb97f950..5a7dcd4435 100644 --- a/frontend/src/routes/_layout/items.tsx +++ b/frontend/src/routes/_layout/items.tsx @@ -8,11 +8,13 @@ import { DataTable } from "@/components/Common/DataTable" import AddItem from "@/components/Items/AddItem" import { columns } from "@/components/Items/columns" import PendingItems from "@/components/Pending/PendingItems" +import useAuth from "@/hooks/useAuth" function getItemsQueryOptions() { return { - queryFn: async () => - (await ItemsService.readItems({ query: { skip: 0, limit: 100 } })).data, + queryFn: async ({ signal }: { signal: AbortSignal }) => + (await ItemsService.readItems({ query: { skip: 0, limit: 100 }, signal })) + .data, queryKey: ["items"], } } @@ -55,6 +57,9 @@ function ItemsTable() { } function Items() { + const { user } = useAuth() + if (!user?.permissions.includes("org:projects:read")) + return

Project read access required.

return (
@@ -62,7 +67,7 @@ function Items() {

Items

Create and manage your items

- + {user.permissions.includes("org:projects:write") && }
diff --git a/frontend/src/routes/_layout/settings.tsx b/frontend/src/routes/_layout/settings.tsx index e109b5ae81..af2720010b 100644 --- a/frontend/src/routes/_layout/settings.tsx +++ b/frontend/src/routes/_layout/settings.tsx @@ -1,6 +1,5 @@ import { createFileRoute } from "@tanstack/react-router" -import ChangePassword from "@/components/UserSettings/ChangePassword" import DeleteAccount from "@/components/UserSettings/DeleteAccount" import UserInformation from "@/components/UserSettings/UserInformation" import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" @@ -8,7 +7,6 @@ import useAuth from "@/hooks/useAuth" const tabsConfig = [ { value: "my-profile", title: "My profile", component: UserInformation }, - { value: "password", title: "Password", component: ChangePassword }, { value: "danger-zone", title: "Danger zone", component: DeleteAccount }, ] @@ -25,9 +23,9 @@ export const Route = createFileRoute("/_layout/settings")({ function UserSettings() { const { user: currentUser } = useAuth() - const finalTabs = currentUser?.is_superuser - ? tabsConfig.slice(0, 3) - : tabsConfig + const finalTabs = currentUser?.permissions.includes("org:projects:write") + ? tabsConfig + : tabsConfig.slice(0, 1) if (!currentUser) { return null diff --git a/frontend/src/routes/login.tsx b/frontend/src/routes/login.tsx index 2161ebdc9c..5445d4f211 100644 --- a/frontend/src/routes/login.tsx +++ b/frontend/src/routes/login.tsx @@ -1,142 +1,6 @@ -import { zodResolver } from "@hookform/resolvers/zod" -import { - createFileRoute, - Link as RouterLink, - redirect, -} from "@tanstack/react-router" -import { useForm } from "react-hook-form" -import { z } from "zod" - -import type { Body_login_login_access_token as AccessToken } from "@/client" -import { AuthLayout } from "@/components/Common/AuthLayout" -import { - Form, - FormControl, - FormField, - FormItem, - FormLabel, - FormMessage, -} from "@/components/ui/form" -import { Input } from "@/components/ui/input" -import { LoadingButton } from "@/components/ui/loading-button" -import { PasswordInput } from "@/components/ui/password-input" -import useAuth, { isLoggedIn } from "@/hooks/useAuth" - -const formSchema = z.object({ - username: z.email({ message: "Invalid email address" }), - password: z - .string() - .min(1, { message: "Password is required" }) - .min(8, { message: "Password must be at least 8 characters" }), -}) satisfies z.ZodType - -type FormData = z.infer +import { createFileRoute } from "@tanstack/react-router" +import HostedSignIn from "@/components/HostedSignIn" export const Route = createFileRoute("/login")({ - component: Login, - beforeLoad: async () => { - if (isLoggedIn()) { - throw redirect({ - to: "/", - }) - } - }, - head: () => ({ - meta: [ - { - title: "Log In - FastAPI Template", - }, - ], - }), + component: () => , }) - -function Login() { - const { loginMutation } = useAuth() - const form = useForm({ - resolver: zodResolver(formSchema), - mode: "onBlur", - criteriaMode: "all", - defaultValues: { - username: "", - password: "", - }, - }) - - const onSubmit = (data: FormData) => { - if (loginMutation.isPending) return - loginMutation.mutate(data) - } - - return ( - -
- -
-

Login to your account

-
- -
- ( - - Email - - - - - - )} - /> - - ( - -
- Password - - Forgot your password? - -
- - - - -
- )} - /> - - - Log In - -
- -
- Don't have an account yet?{" "} - - Sign up - -
-
- -
- ) -} diff --git a/frontend/src/routes/recover-password.tsx b/frontend/src/routes/recover-password.tsx deleted file mode 100644 index 38118ee456..0000000000 --- a/frontend/src/routes/recover-password.tsx +++ /dev/null @@ -1,130 +0,0 @@ -import { zodResolver } from "@hookform/resolvers/zod" -import { useMutation } from "@tanstack/react-query" -import { - createFileRoute, - Link as RouterLink, - redirect, -} from "@tanstack/react-router" -import { useForm } from "react-hook-form" -import { z } from "zod" - -import { LoginService } from "@/client" -import { AuthLayout } from "@/components/Common/AuthLayout" -import { - Form, - FormControl, - FormField, - FormItem, - FormLabel, - FormMessage, -} from "@/components/ui/form" -import { Input } from "@/components/ui/input" -import { LoadingButton } from "@/components/ui/loading-button" -import { isLoggedIn } from "@/hooks/useAuth" -import useCustomToast from "@/hooks/useCustomToast" -import { handleError } from "@/utils" - -const formSchema = z.object({ - email: z.email({ message: "Invalid email address" }), -}) - -type FormData = z.infer - -export const Route = createFileRoute("/recover-password")({ - component: RecoverPassword, - beforeLoad: async () => { - if (isLoggedIn()) { - throw redirect({ - to: "/", - }) - } - }, - head: () => ({ - meta: [ - { - title: "Recover Password - FastAPI Template", - }, - ], - }), -}) - -function RecoverPassword() { - const form = useForm({ - resolver: zodResolver(formSchema), - defaultValues: { - email: "", - }, - }) - const { showSuccessToast, showErrorToast } = useCustomToast() - - const recoverPassword = async (data: FormData) => { - await LoginService.recoverPassword({ - path: { email: data.email }, - }) - } - - const mutation = useMutation({ - mutationFn: recoverPassword, - onSuccess: () => { - showSuccessToast("Password recovery email sent successfully") - form.reset() - }, - onError: handleError.bind(showErrorToast), - }) - - const onSubmit = async (data: FormData) => { - if (mutation.isPending) return - mutation.mutate(data) - } - - return ( - -
- -
-

Password Recovery

-
- -
- ( - - Email - - - - - - )} - /> - - - Continue - -
- -
- Remember your password?{" "} - - Log in - -
-
- -
- ) -} diff --git a/frontend/src/routes/reset-password.tsx b/frontend/src/routes/reset-password.tsx deleted file mode 100644 index bbbf3eef10..0000000000 --- a/frontend/src/routes/reset-password.tsx +++ /dev/null @@ -1,166 +0,0 @@ -import { zodResolver } from "@hookform/resolvers/zod" -import { useMutation } from "@tanstack/react-query" -import { - createFileRoute, - Link as RouterLink, - redirect, - useNavigate, -} from "@tanstack/react-router" -import { useForm } from "react-hook-form" -import { z } from "zod" - -import { LoginService } from "@/client" -import { AuthLayout } from "@/components/Common/AuthLayout" -import { - Form, - FormControl, - FormField, - FormItem, - FormLabel, - FormMessage, -} from "@/components/ui/form" -import { LoadingButton } from "@/components/ui/loading-button" -import { PasswordInput } from "@/components/ui/password-input" -import { isLoggedIn } from "@/hooks/useAuth" -import useCustomToast from "@/hooks/useCustomToast" -import { handleError } from "@/utils" - -const searchSchema = z.object({ - token: z.string().catch(""), -}) - -const formSchema = z - .object({ - new_password: z - .string() - .min(1, { message: "Password is required" }) - .min(8, { message: "Password must be at least 8 characters" }), - confirm_password: z - .string() - .min(1, { message: "Password confirmation is required" }), - }) - .refine((data) => data.new_password === data.confirm_password, { - message: "The passwords don't match", - path: ["confirm_password"], - }) - -type FormData = z.infer - -export const Route = createFileRoute("/reset-password")({ - component: ResetPassword, - validateSearch: searchSchema, - beforeLoad: async ({ search }) => { - if (isLoggedIn()) { - throw redirect({ to: "/" }) - } - if (!search.token) { - throw redirect({ to: "/login" }) - } - }, - head: () => ({ - meta: [ - { - title: "Reset Password - FastAPI Template", - }, - ], - }), -}) - -function ResetPassword() { - const { token } = Route.useSearch() - const { showSuccessToast, showErrorToast } = useCustomToast() - const navigate = useNavigate() - - const form = useForm({ - resolver: zodResolver(formSchema), - mode: "onBlur", - criteriaMode: "all", - defaultValues: { - new_password: "", - confirm_password: "", - }, - }) - - const mutation = useMutation({ - mutationFn: (data: { new_password: string; token: string }) => - LoginService.resetPassword({ body: data }), - onSuccess: () => { - showSuccessToast("Password updated successfully") - form.reset() - navigate({ to: "/login" }) - }, - onError: handleError.bind(showErrorToast), - }) - - const onSubmit = (data: FormData) => { - mutation.mutate({ new_password: data.new_password, token }) - } - - return ( - -
- -
-

Reset Password

-
- -
- ( - - New Password - - - - - - )} - /> - - ( - - Confirm Password - - - - - - )} - /> - - - Reset Password - -
- -
- Remember your password?{" "} - - Log in - -
-
- -
- ) -} diff --git a/frontend/src/routes/signup.tsx b/frontend/src/routes/signup.tsx index ec4fddc725..d97e2f4049 100644 --- a/frontend/src/routes/signup.tsx +++ b/frontend/src/routes/signup.tsx @@ -1,187 +1,6 @@ -import { zodResolver } from "@hookform/resolvers/zod" -import { - createFileRoute, - Link as RouterLink, - redirect, -} from "@tanstack/react-router" -import { useForm } from "react-hook-form" -import { z } from "zod" -import { AuthLayout } from "@/components/Common/AuthLayout" -import { - Form, - FormControl, - FormField, - FormItem, - FormLabel, - FormMessage, -} from "@/components/ui/form" -import { Input } from "@/components/ui/input" -import { LoadingButton } from "@/components/ui/loading-button" -import { PasswordInput } from "@/components/ui/password-input" -import useAuth, { isLoggedIn } from "@/hooks/useAuth" - -const formSchema = z - .object({ - email: z.email({ message: "Invalid email address" }), - full_name: z.string().min(1, { message: "Full Name is required" }), - password: z - .string() - .min(1, { message: "Password is required" }) - .min(8, { message: "Password must be at least 8 characters" }), - confirm_password: z - .string() - .min(1, { message: "Password confirmation is required" }), - }) - .refine((data) => data.password === data.confirm_password, { - message: "The passwords don't match", - path: ["confirm_password"], - }) - -type FormData = z.infer +import { createFileRoute } from "@tanstack/react-router" +import HostedSignIn from "@/components/HostedSignIn" export const Route = createFileRoute("/signup")({ - component: SignUp, - beforeLoad: async () => { - if (isLoggedIn()) { - throw redirect({ - to: "/", - }) - } - }, - head: () => ({ - meta: [ - { - title: "Sign Up - FastAPI Template", - }, - ], - }), + component: () => , }) - -function SignUp() { - const { signUpMutation } = useAuth() - const form = useForm({ - resolver: zodResolver(formSchema), - mode: "onBlur", - criteriaMode: "all", - defaultValues: { - email: "", - full_name: "", - password: "", - confirm_password: "", - }, - }) - - const onSubmit = (data: FormData) => { - if (signUpMutation.isPending) return - - // exclude confirm_password from submission data - const { confirm_password: _confirm_password, ...submitData } = data - signUpMutation.mutate(submitData) - } - - return ( - -
- -
-

Create an account

-
- -
- ( - - Full Name - - - - - - )} - /> - - ( - - Email - - - - - - )} - /> - - ( - - Password - - - - - - )} - /> - - ( - - Confirm Password - - - - - - )} - /> - - - Sign Up - -
- -
- Already have an account?{" "} - - Log in - -
-
- -
- ) -} diff --git a/frontend/tests/admin.spec.ts b/frontend/tests/admin.spec.ts index cd73dbad5c..b3dda8b9a9 100644 --- a/frontend/tests/admin.spec.ts +++ b/frontend/tests/admin.spec.ts @@ -1,205 +1,44 @@ import { expect, test } from "@playwright/test" -import { firstSuperuser, firstSuperuserPassword } from "./config.ts" -import { createUser } from "./utils/privateApi" -import { randomEmail, randomPassword } from "./utils/random" -import { logInUser } from "./utils/user" +import { installAuthKitFixture } from "./utils/authkit-fixture" -test("Admin page is accessible and shows correct title", async ({ page }) => { +test("database authenticated role never enables tenant administration (network fixture)", async ({ + page, +}) => { + await installAuthKitFixture(page) + let userLists = 0 + await page.route("**/api/v1/users/?**", (route) => { + userLists++ + return route.fulfill({ json: { data: [], count: 0 } }) + }) await page.goto("/admin") - await expect(page.getByRole("heading", { name: "Users" })).toBeVisible() - await expect( - page.getByText("Manage user accounts and permissions"), - ).toBeVisible() + await expect(page.getByRole("alert")).toContainText( + "Tenant administrator access required", + ) + await expect(page.getByRole("button", { name: "Add User" })).toHaveCount(0) + expect(userLists).toBe(0) }) -test("Add User button is visible", async ({ page }) => { +test("tenant admin creates explicit actor association without passwords or local roles (network fixture)", async ({ + page, +}) => { + await installAuthKitFixture(page, { admin: true }) + await page.route("**/api/v1/users/?**", (route) => + route.fulfill({ json: { data: [], count: 0 } }), + ) await page.goto("/admin") - await expect(page.getByRole("button", { name: "Add User" })).toBeVisible() -}) - -test.describe("Admin user management", () => { - test("Create a new user successfully", async ({ page }) => { - await page.goto("/admin") - - const email = randomEmail() - const password = randomPassword() - const fullName = "Test User Admin" - - await page.getByRole("button", { name: "Add User" }).click() - - await page.getByPlaceholder("Email").fill(email) - await page.getByPlaceholder("Full name").fill(fullName) - await page.getByPlaceholder("Password").first().fill(password) - await page.getByPlaceholder("Password").last().fill(password) - - await page.getByRole("button", { name: "Save" }).click() - - await expect(page.getByText("User created successfully")).toBeVisible() - - await expect(page.getByRole("dialog")).not.toBeVisible() - - const userRow = page.getByRole("row").filter({ hasText: email }) - await expect(userRow).toBeVisible() - }) - - test("Create a superuser", async ({ page }) => { - await page.goto("/admin") - - const email = randomEmail() - const password = randomPassword() - - await page.getByRole("button", { name: "Add User" }).click() - - await page.getByPlaceholder("Email").fill(email) - await page.getByPlaceholder("Password").first().fill(password) - await page.getByPlaceholder("Password").last().fill(password) - await page.getByLabel("Is superuser?").check() - await page.getByLabel("Is active?").check() - - await page.getByRole("button", { name: "Save" }).click() - - await expect(page.getByText("User created successfully")).toBeVisible() - - await expect(page.getByRole("dialog")).not.toBeVisible() - - const userRow = page.getByRole("row").filter({ hasText: email }) - await expect(userRow.getByText("Superuser")).toBeVisible() - }) - - test("Edit a user successfully", async ({ page }) => { - await page.goto("/admin") - - const email = randomEmail() - const password = randomPassword() - const originalName = "Original Name" - const updatedName = "Updated Name" - - await page.getByRole("button", { name: "Add User" }).click() - await page.getByPlaceholder("Email").fill(email) - await page.getByPlaceholder("Full name").fill(originalName) - await page.getByPlaceholder("Password").first().fill(password) - await page.getByPlaceholder("Password").last().fill(password) - await page.getByRole("button", { name: "Save" }).click() - - await expect(page.getByText("User created successfully")).toBeVisible() - await expect(page.getByRole("dialog")).not.toBeVisible() - - const userRow = page.getByRole("row").filter({ hasText: email }) - await userRow.getByRole("button").click() - - await page.getByRole("menuitem", { name: "Edit User" }).click() - - await page.getByPlaceholder("Full name").fill(updatedName) - await page.getByRole("button", { name: "Save" }).click() - - await expect(page.getByText("User updated successfully")).toBeVisible() - await expect(page.getByText(updatedName)).toBeVisible() - }) - - test("Delete a user successfully", async ({ page }) => { - await page.goto("/admin") - - const email = randomEmail() - const password = randomPassword() - - await page.getByRole("button", { name: "Add User" }).click() - await page.getByPlaceholder("Email").fill(email) - await page.getByPlaceholder("Password").first().fill(password) - await page.getByPlaceholder("Password").last().fill(password) - await page.getByRole("button", { name: "Save" }).click() - - await expect(page.getByText("User created successfully")).toBeVisible() - - await expect(page.getByRole("dialog")).not.toBeVisible() - - const userRow = page.getByRole("row").filter({ hasText: email }) - await userRow.getByRole("button").click() - - await page.getByRole("menuitem", { name: "Delete User" }).click() - - await page.getByRole("button", { name: "Delete" }).click() - - await expect( - page.getByText("The user was deleted successfully"), - ).toBeVisible() - - await expect( - page.getByRole("row").filter({ hasText: email }), - ).not.toBeVisible() - }) - - test("Cancel user creation", async ({ page }) => { - await page.goto("/admin") - - await page.getByRole("button", { name: "Add User" }).click() - await page.getByPlaceholder("Email").fill("test@example.com") - - await page.getByRole("button", { name: "Cancel" }).click() - - await expect(page.getByRole("dialog")).not.toBeVisible() - }) - - test("Email is required and must be valid", async ({ page }) => { - await page.goto("/admin") - - await page.getByRole("button", { name: "Add User" }).click() - - await page.getByPlaceholder("Email").fill("invalid-email") - await page.getByPlaceholder("Email").blur() - - await expect(page.getByText("Invalid email address")).toBeVisible() - }) - - test("Password must be at least 8 characters", async ({ page }) => { - await page.goto("/admin") - - await page.getByRole("button", { name: "Add User" }).click() - - await page.getByPlaceholder("Email").fill(randomEmail()) - await page.getByPlaceholder("Password").first().fill("short") - await page.getByPlaceholder("Password").last().fill("short") - await page.getByRole("button", { name: "Save" }).click() - - await expect( - page.getByText("Password must be at least 8 characters"), - ).toBeVisible() - }) - - test("Passwords must match", async ({ page }) => { - await page.goto("/admin") - - await page.getByRole("button", { name: "Add User" }).click() - - await page.getByPlaceholder("Email").fill(randomEmail()) - await page.getByPlaceholder("Password").first().fill(randomPassword()) - await page.getByPlaceholder("Password").last().fill("different12345") - await page.getByPlaceholder("Password").last().blur() - - await expect(page.getByText("The passwords don't match")).toBeVisible() - }) + await page.getByRole("button", { name: "Add User" }).click() + await expect(page.getByLabel("Canonical identity UUID")).toBeVisible() + await expect(page.locator('input[type="password"]')).toHaveCount(0) + await expect(page.getByText("Is superuser?")).toHaveCount(0) }) -test.describe("Admin page access control", () => { - test.use({ storageState: { cookies: [], origins: [] } }) - - test("Non-superuser cannot access admin page", async ({ page }) => { - const email = randomEmail() - const password = randomPassword() - - await createUser({ email, password }) - await logInUser(page, email, password) - - await page.goto("/admin") - - await expect(page.getByRole("heading", { name: "Users" })).not.toBeVisible() - await expect(page).not.toHaveURL(/\/admin/) - }) - - test("Superuser can access admin page", async ({ page }) => { - await logInUser(page, firstSuperuser, firstSuperuserPassword) - - await page.goto("/admin") - - await expect(page.getByRole("heading", { name: "Users" })).toBeVisible() - }) +test("revoked membership blocks all protected child UI (network fixture)", async ({ + page, +}) => { + await installAuthKitFixture(page, { admin: true, denied: true }) + await page.goto("/admin") + await expect(page.getByRole("alert")).toContainText( + "Access to this organization is unavailable", + ) + await expect(page.getByRole("button", { name: "Add User" })).toHaveCount(0) }) diff --git a/frontend/tests/auth.setup.ts b/frontend/tests/auth.setup.ts deleted file mode 100644 index ba948af252..0000000000 --- a/frontend/tests/auth.setup.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { test as setup } from "@playwright/test" -import { firstSuperuser, firstSuperuserPassword } from "./config.ts" - -const authFile = "playwright/.auth/user.json" - -setup("authenticate", async ({ page }) => { - await page.goto("/login") - await page.getByTestId("email-input").fill(firstSuperuser) - await page.getByTestId("password-input").fill(firstSuperuserPassword) - await page.getByRole("button", { name: "Log In" }).click() - await page.waitForURL("/") - await page.context().storageState({ path: authFile }) -}) diff --git a/frontend/tests/config.ts b/frontend/tests/config.ts deleted file mode 100644 index 572dec9545..0000000000 --- a/frontend/tests/config.ts +++ /dev/null @@ -1,19 +0,0 @@ -import path from "node:path" -import { fileURLToPath } from "node:url" -import dotenv from "dotenv" - -const __filename = fileURLToPath(import.meta.url) -const __dirname = path.dirname(__filename) - -dotenv.config({ path: path.join(__dirname, "../../.env") }) - -function getEnvVar(name: string): string { - const value = process.env[name] - if (!value) { - throw new Error(`Environment variable ${name} is undefined`) - } - return value -} - -export const firstSuperuser = getEnvVar("FIRST_SUPERUSER") -export const firstSuperuserPassword = getEnvVar("FIRST_SUPERUSER_PASSWORD") diff --git a/frontend/tests/items.spec.ts b/frontend/tests/items.spec.ts index 5a437314db..1ef60eaff4 100644 --- a/frontend/tests/items.spec.ts +++ b/frontend/tests/items.spec.ts @@ -1,132 +1,142 @@ -import { expect, test } from "@playwright/test" -import { createUser } from "./utils/privateApi" -import { - randomEmail, - randomItemDescription, - randomItemTitle, - randomPassword, -} from "./utils/random" -import { logInUser } from "./utils/user" - -test("Items page is accessible and shows correct title", async ({ page }) => { - await page.goto("/items") - await expect(page.getByRole("heading", { name: "Items" })).toBeVisible() - await expect(page.getByText("Create and manage your items")).toBeVisible() -}) - -test("Add Item button is visible", async ({ page }) => { +import { expect, type Route, test } from "@playwright/test" +import { installAuthKitFixture } from "./utils/authkit-fixture" + +test("organization switch discards old queries and drafts (network fixture)", async ({ + page, +}) => { + await installAuthKitFixture(page) + await page.route("**/api/v1/items/**", (route) => { + const token = route.request().headers().authorization ?? "" + const payload = token.split(".")[1] + const org = payload + ? JSON.parse(Buffer.from(payload, "base64url").toString()).org_id + : "" + return route.fulfill({ + json: { + count: 1, + data: [ + { + id: org, + owner_id: "fixture", + tenant_id: org, + title: org, + description: "Fixture", + }, + ], + }, + }) + }) await page.goto("/items") - await expect(page.getByRole("button", { name: "Add Item" })).toBeVisible() + await expect( + page.getByRole("cell", { name: "org_fixture_a", exact: true }), + ).toBeVisible() + await page.getByRole("button", { name: "Add Item" }).click() + await page.getByLabel("Title").fill("old tenant draft") + await page.getByRole("button", { name: "Cancel" }).click() + await page.getByLabel("Organization ID").fill("org_fixture_b") + await page.getByRole("button", { name: "Switch organization" }).click() + await expect( + page.getByRole("cell", { name: "org_fixture_b", exact: true }), + ).toBeVisible() + await expect( + page.getByRole("cell", { name: "org_fixture_a", exact: true }), + ).toHaveCount(0) + await page.getByRole("button", { name: "Add Item" }).click() + await expect(page.getByLabel("Title")).toHaveValue("") }) -test.describe("Items management", () => { - test.use({ storageState: { cookies: [], origins: [] } }) - let email: string - const password = randomPassword() - - test.beforeAll(async () => { - email = randomEmail() - await createUser({ email, password }) - }) - - test.beforeEach(async ({ page }) => { - await logInUser(page, email, password) - await page.goto("/items") - }) - - test("Create a new item successfully", async ({ page }) => { - const title = randomItemTitle() - const description = randomItemDescription() - - await page.getByRole("button", { name: "Add Item" }).click() - await page.getByLabel("Title").fill(title) - await page.getByLabel("Description").fill(description) - await page.getByRole("button", { name: "Save" }).click() - - await expect(page.getByText("Item created successfully")).toBeVisible() - await expect(page.getByText(title)).toBeVisible() - }) - - test("Create item with only required fields", async ({ page }) => { - const title = randomItemTitle() - - await page.getByRole("button", { name: "Add Item" }).click() - await page.getByLabel("Title").fill(title) - await page.getByRole("button", { name: "Save" }).click() - - await expect(page.getByText("Item created successfully")).toBeVisible() - await expect(page.getByText(title)).toBeVisible() - }) - - test("Cancel item creation", async ({ page }) => { - await page.getByRole("button", { name: "Add Item" }).click() - await page.getByLabel("Title").fill("Test Item") - await page.getByRole("button", { name: "Cancel" }).click() - - await expect(page.getByRole("dialog")).not.toBeVisible() - }) - - test("Title is required", async ({ page }) => { - await page.getByRole("button", { name: "Add Item" }).click() - await page.getByLabel("Title").fill("") - await page.getByLabel("Title").blur() - - await expect(page.getByText("Title is required")).toBeVisible() +test("late old-organization response cannot repopulate the new tenant (network fixture)", async ({ + page, +}) => { + await installAuthKitFixture(page) + let staleRoute: Route | undefined + await page.route("**/api/v1/items/**", (route) => { + const payload = route.request().headers().authorization?.split(".")[1] + const org = payload + ? JSON.parse(Buffer.from(payload, "base64url").toString()).org_id + : "" + if (org === "org_fixture_a") { + staleRoute = route + return + } + return route.fulfill({ json: { count: 0, data: [] } }) }) - - test.describe("Edit and Delete", () => { - let itemTitle: string - - test.beforeEach(async ({ page }) => { - itemTitle = randomItemTitle() - - await page.getByRole("button", { name: "Add Item" }).click() - await page.getByLabel("Title").fill(itemTitle) - await page.getByRole("button", { name: "Save" }).click() - await expect(page.getByText("Item created successfully")).toBeVisible() - await expect(page.getByRole("dialog")).not.toBeVisible() - }) - - test("Edit an item successfully", async ({ page }) => { - const itemRow = page.getByRole("row").filter({ hasText: itemTitle }) - await itemRow.getByRole("button").last().click() - await page.getByRole("menuitem", { name: "Edit Item" }).click() - - const updatedTitle = randomItemTitle() - await page.getByLabel("Title").fill(updatedTitle) - await page.getByRole("button", { name: "Save" }).click() - - await expect(page.getByText("Item updated successfully")).toBeVisible() - await expect(page.getByText(updatedTitle)).toBeVisible() - }) - - test("Delete an item successfully", async ({ page }) => { - const itemRow = page.getByRole("row").filter({ hasText: itemTitle }) - await itemRow.getByRole("button").last().click() - await page.getByRole("menuitem", { name: "Delete Item" }).click() - - await page.getByRole("button", { name: "Delete" }).click() - - await expect( - page.getByText("The item was deleted successfully"), - ).toBeVisible() - await expect(page.getByText(itemTitle)).not.toBeVisible() + await page.goto("/items") + await expect.poll(() => Boolean(staleRoute)).toBe(true) + await page.getByLabel("Organization ID").fill("org_fixture_b") + await page.getByRole("button", { name: "Switch organization" }).click() + await expect(page.getByText("You don't have any items yet")).toBeVisible() + await staleRoute + ?.fulfill({ + json: { count: 1, data: [{ id: "old", title: "Old tenant secret" }] }, }) - }) + .catch(() => {}) + await expect(page.getByText("Old tenant secret")).toHaveCount(0) }) -test.describe("Items empty state", () => { - test.use({ storageState: { cookies: [], origins: [] } }) - - test("Shows empty state message when no items exist", async ({ page }) => { - const email = randomEmail() - const password = randomPassword() - await createUser({ email, password }) - await logInUser(page, email, password) - - await page.goto("/items") +test("ordinary automatic token renewal preserves an unsaved item draft (network fixture)", async ({ + page, +}) => { + await page.clock.install() + await installAuthKitFixture(page, { tokenLifetimeSeconds: 60 }) + let refreshCount = 0 + await page.route( + "https://auth.fixture.example/user_management/authenticate", + (route) => { + refreshCount++ + return route.fallback() + }, + ) + await page.route("**/api/v1/items/**", (route) => + route.fulfill({ json: { count: 0, data: [] } }), + ) + await page.goto("/items") + await page.getByRole("button", { name: "Add Item" }).click() + await page.getByLabel("Title").fill("Keep my unsaved draft") + expect(refreshCount).toBe(1) + const beforeRefresh = refreshCount + const profileRevalidated = page.waitForResponse( + (response) => new URL(response.url()).pathname === "/api/v1/users/me", + ) + await page.clock.fastForward(51000) + await expect.poll(() => refreshCount).toBeGreaterThan(beforeRefresh) + await profileRevalidated + await expect(page.getByLabel("Title")).toHaveValue("Keep my unsaved draft") +}) - await expect(page.getByText("You don't have any items yet")).toBeVisible() - await expect(page.getByText("Add a new item to get started")).toBeVisible() - }) +test("organization switch joining an in-flight refresh cannot silently remain in the old organization (network fixture)", async ({ + page, +}) => { + await page.clock.install() + await installAuthKitFixture(page, { tokenLifetimeSeconds: 60 }) + let refreshCount = 0 + let pendingRefresh: Route | undefined + await page.route( + "https://auth.fixture.example/user_management/authenticate", + (route) => { + refreshCount++ + if (refreshCount === 2) { + pendingRefresh = route + return + } + return route.fallback() + }, + ) + await page.route("**/api/v1/items/**", (route) => + route.fulfill({ json: { count: 0, data: [] } }), + ) + await page.goto("/items") + await expect( + page.getByRole("heading", { name: "Items", exact: true }), + ).toBeVisible() + expect(refreshCount).toBe(1) + await page.clock.fastForward(51000) + await expect.poll(() => Boolean(pendingRefresh)).toBe(true) + await page.getByLabel("Organization ID").fill("org_fixture_b") + await page.getByRole("button", { name: "Switch organization" }).click() + await pendingRefresh?.fallback() + await expect(page.getByRole("alert")).toContainText( + "Unable to select this organization.", + ) + await expect(page.getByText("org_fixture_b", { exact: true })).toHaveCount(0) }) diff --git a/frontend/tests/login.spec.ts b/frontend/tests/login.spec.ts index 8072ddc1fa..1dc404351c 100644 --- a/frontend/tests/login.spec.ts +++ b/frontend/tests/login.spec.ts @@ -1,117 +1,53 @@ -import { expect, type Page, test } from "@playwright/test" -import { firstSuperuser, firstSuperuserPassword } from "./config.ts" -import { randomPassword } from "./utils/random.ts" - -test.use({ storageState: { cookies: [], origins: [] } }) - -const fillForm = async (page: Page, email: string, password: string) => { - await page.getByTestId("email-input").fill(email) - await page.getByTestId("password-input").fill(password) -} - -const verifyInput = async (page: Page, testId: string) => { - const input = page.getByTestId(testId) - await expect(input).toBeVisible() - await expect(input).toHaveText("") - await expect(input).toBeEditable() -} - -test("Inputs are visible, empty and editable", async ({ page }) => { - await page.goto("/login") - - await verifyInput(page, "email-input") - await verifyInput(page, "password-input") -}) - -test("Log In button is visible", async ({ page }) => { - await page.goto("/login") - - await expect(page.getByRole("button", { name: "Log In" })).toBeVisible() -}) - -test("Forgot Password link is visible", async ({ page }) => { - await page.goto("/login") - - await expect( - page.getByRole("link", { name: "Forgot your password?" }), - ).toBeVisible() -}) - -test("Log in with valid email and password ", async ({ page }) => { - await page.goto("/login") - - await fillForm(page, firstSuperuser, firstSuperuserPassword) - await page.getByRole("button", { name: "Log In" }).click() - - await page.waitForURL("/") - - await expect( - page.getByText("Welcome back, nice to see you again!"), - ).toBeVisible() -}) - -test("Log in with invalid email", async ({ page }) => { - await page.goto("/login") - - await fillForm(page, "invalidemail", firstSuperuserPassword) - await page.getByRole("button", { name: "Log In" }).click() - - await expect(page.getByText("Invalid email address")).toBeVisible() -}) - -test("Log in with invalid password", async ({ page }) => { - const password = randomPassword() - - await page.goto("/login") - await fillForm(page, firstSuperuser, password) - await page.getByRole("button", { name: "Log In" }).click() - - await expect(page.getByText("Incorrect email or password")).toBeVisible() -}) - -test("Successful log out", async ({ page }) => { - await page.goto("/login") - - await fillForm(page, firstSuperuser, firstSuperuserPassword) - await page.getByRole("button", { name: "Log In" }).click() - - await page.waitForURL("/") - - await expect( - page.getByText("Welcome back, nice to see you again!"), - ).toBeVisible() - - await page.getByTestId("user-menu").click() - await page.getByRole("menuitem", { name: "Log out" }).click() - await page.waitForURL("/login") -}) - -test("Logged-out user cannot access protected routes", async ({ page }) => { - await page.goto("/login") - - await fillForm(page, firstSuperuser, firstSuperuserPassword) - await page.getByRole("button", { name: "Log In" }).click() - - await page.waitForURL("/") - - await expect( - page.getByText("Welcome back, nice to see you again!"), - ).toBeVisible() - - await page.getByTestId("user-menu").click() - await page.getByRole("menuitem", { name: "Log out" }).click() - await page.waitForURL("/login") - - await page.goto("/settings") - await page.waitForURL("/login") -}) - -test("Redirects to /login when token is wrong", async ({ page }) => { - await page.goto("/settings") - await page.evaluate(() => { - localStorage.setItem("access_token", "invalid_token") - }) - await page.goto("/settings") - await page.waitForURL("/login") - await expect(page).toHaveURL("/login") +import { expect, test } from "@playwright/test" + +test("missing public configuration fails closed", async ({ page }) => { + await page.route("**/api/v1/auth/config", (route) => + route.fulfill({ status: 503, json: {} }), + ) + await page.goto("/items") + await expect(page.getByRole("alert")).toContainText( + "Sign-in configuration unavailable", + ) + await expect(page.getByRole("button", { name: "Add Item" })).toHaveCount(0) +}) + +test("external login preserves invitation and reset details through the official SDK (fixture)", async ({ + page, + baseURL, +}) => { + await page.route("**/api/v1/auth/config", (route) => + route.fulfill({ + json: { + client_id: "client_fixture", + api_hostname: "auth.fixture.example", + redirect_uri: baseURL, + }, + }), + ) + await page.route( + "https://auth.fixture.example/user_management/authorize**", + (route) => + route.fulfill({ + contentType: "text/html", + body: "Fixture AuthKit destination", + }), + ) + await page.goto( + "/login?invitation_token=invite_fixture&password_reset_token=reset_fixture&organization_id=org_fixture&login_hint=fixture%40example.test", + ) + await page.waitForURL( + "https://auth.fixture.example/user_management/authorize**", + ) + const destination = new URL(page.url()) + expect(destination.searchParams.get("invitation_token")).toBe( + "invite_fixture", + ) + expect(destination.searchParams.get("password_reset_token")).toBe( + "reset_fixture", + ) + expect(destination.searchParams.get("organization_id")).toBe("org_fixture") + expect(destination.searchParams.get("login_hint")).toBe( + "fixture@example.test", + ) + expect(destination.searchParams.get("code_challenge")).toBeTruthy() }) diff --git a/frontend/tests/reset-password.spec.ts b/frontend/tests/reset-password.spec.ts deleted file mode 100644 index 0cf5417c83..0000000000 --- a/frontend/tests/reset-password.spec.ts +++ /dev/null @@ -1,114 +0,0 @@ -import { expect, test } from "@playwright/test" -import { waitForEmailHtml } from "./utils/mailpit" -import { randomEmail, randomPassword } from "./utils/random" -import { logInUser, signUpNewUser } from "./utils/user" - -test.use({ storageState: { cookies: [], origins: [] } }) - -const resetPath = "/reset-password?token=" - -test("Password Recovery title is visible", async ({ page }) => { - await page.goto("/recover-password") - - await expect( - page.getByRole("heading", { name: "Password Recovery" }), - ).toBeVisible() -}) - -test("Input is visible, empty and editable", async ({ page }) => { - await page.goto("/recover-password") - - await expect(page.getByTestId("email-input")).toBeVisible() - await expect(page.getByTestId("email-input")).toHaveText("") - await expect(page.getByTestId("email-input")).toBeEditable() -}) - -test("Continue button is visible", async ({ page }) => { - await page.goto("/recover-password") - - await expect(page.getByRole("button", { name: "Continue" })).toBeVisible() -}) - -test("User can reset password successfully using the link", async ({ - page, - request, -}) => { - const fullName = "Test User" - const email = randomEmail() - const password = randomPassword() - const newPassword = randomPassword() - - // Sign up a new user - await signUpNewUser(page, fullName, email, password) - - await page.goto("/recover-password") - await page.getByTestId("email-input").fill(email) - - await page.getByRole("button", { name: "Continue" }).click() - - const emailHtml = await waitForEmailHtml({ - request, - query: `to:${email}`, - }) - - expect(emailHtml).toContain(resetPath) - const resetUrl = emailHtml.match(/\/reset-password\?token=[^"]+/)?.[0] - expect(resetUrl).toBeDefined() - - // Set the new password and confirm it - await page.goto(resetUrl!) - - await page.getByTestId("new-password-input").fill(newPassword) - await page.getByTestId("confirm-password-input").fill(newPassword) - await page.getByRole("button", { name: "Reset Password" }).click() - await expect(page.getByText("Password updated successfully")).toBeVisible() - - // Check if the user is able to login with the new password - await logInUser(page, email, newPassword) -}) - -test("Expired or invalid reset link", async ({ page }) => { - const password = randomPassword() - const invalidUrl = "/reset-password?token=invalidtoken" - - await page.goto(invalidUrl) - - await page.getByTestId("new-password-input").fill(password) - await page.getByTestId("confirm-password-input").fill(password) - await page.getByRole("button", { name: "Reset Password" }).click() - - await expect(page.getByText("Invalid token")).toBeVisible() -}) - -test("Weak new password validation", async ({ page, request }) => { - const fullName = "Test User" - const email = randomEmail() - const password = randomPassword() - const weakPassword = "123" - - // Sign up a new user - await signUpNewUser(page, fullName, email, password) - - await page.goto("/recover-password") - await page.getByTestId("email-input").fill(email) - await page.getByRole("button", { name: "Continue" }).click() - - const emailHtml = await waitForEmailHtml({ - request, - query: `to:${email}`, - }) - - expect(emailHtml).toContain(resetPath) - const resetUrl = emailHtml.match(/\/reset-password\?token=[^"]+/)?.[0] - expect(resetUrl).toBeDefined() - - // Set a weak new password - await page.goto(resetUrl!) - await page.getByTestId("new-password-input").fill(weakPassword) - await page.getByTestId("confirm-password-input").fill(weakPassword) - await page.getByRole("button", { name: "Reset Password" }).click() - - await expect( - page.getByText("Password must be at least 8 characters"), - ).toBeVisible() -}) diff --git a/frontend/tests/session-boundary.spec.ts b/frontend/tests/session-boundary.spec.ts new file mode 100644 index 0000000000..d79d6ee4c6 --- /dev/null +++ b/frontend/tests/session-boundary.spec.ts @@ -0,0 +1,20 @@ +import { expect, test } from "@playwright/test" +import { createSessionTransport } from "../src/lib/session-transport" + +test.describe("session transport fixtures (not live authentication)", () => { + test("rejects a token resolving after organization teardown", async () => { + const transport = createSessionTransport( + async () => "old-organization-token", + ) + const pending = transport.auth() + transport.dispose() + await expect(pending).rejects.toThrow("Session changed") + expect(transport.signal.aborted).toBe(true) + }) + test("supplies the native asynchronous bearer hook and cancels requests", async () => { + const transport = createSessionTransport(async () => "fixture-token") + expect(await transport.auth()).toBe("fixture-token") + transport.dispose() + await expect(transport.auth()).rejects.toThrow("Session changed") + }) +}) diff --git a/frontend/tests/sign-up.spec.ts b/frontend/tests/sign-up.spec.ts deleted file mode 100644 index 663020bfc2..0000000000 --- a/frontend/tests/sign-up.spec.ts +++ /dev/null @@ -1,160 +0,0 @@ -import { expect, type Page, test } from "@playwright/test" - -import { randomEmail, randomPassword } from "./utils/random" - -test.use({ storageState: { cookies: [], origins: [] } }) - -const fillForm = async ( - page: Page, - full_name: string, - email: string, - password: string, - confirm_password: string, -) => { - await page.getByTestId("full-name-input").fill(full_name) - await page.getByTestId("email-input").fill(email) - await page.getByTestId("password-input").fill(password) - await page.getByTestId("confirm-password-input").fill(confirm_password) -} - -const verifyInput = async (page: Page, testId: string) => { - const input = page.getByTestId(testId) - await expect(input).toBeVisible() - await expect(input).toHaveText("") - await expect(input).toBeEditable() -} - -test("Inputs are visible, empty and editable", async ({ page }) => { - await page.goto("/signup") - - await verifyInput(page, "full-name-input") - await verifyInput(page, "email-input") - await verifyInput(page, "password-input") - await verifyInput(page, "confirm-password-input") -}) - -test("Sign Up button is visible", async ({ page }) => { - await page.goto("/signup") - - await expect(page.getByRole("button", { name: "Sign Up" })).toBeVisible() -}) - -test("Log In link is visible", async ({ page }) => { - await page.goto("/signup") - - await expect(page.getByRole("link", { name: "Log In" })).toBeVisible() -}) - -test("Sign up with valid name, email, and password", async ({ page }) => { - const full_name = "Test User" - const email = randomEmail() - const password = randomPassword() - - await page.goto("/signup") - await fillForm(page, full_name, email, password, password) - await page.getByRole("button", { name: "Sign Up" }).click() -}) - -test("Sign up with invalid email", async ({ page }) => { - await page.goto("/signup") - - await fillForm( - page, - "Playwright Test", - "invalid-email", - "changethis", - "changethis", - ) - await page.getByRole("button", { name: "Sign Up" }).click() - - await expect(page.getByText("Invalid email address")).toBeVisible() -}) - -test("Sign up with existing email", async ({ page }) => { - const fullName = "Test User" - const email = randomEmail() - const password = randomPassword() - - await page.goto("/signup") - - await fillForm(page, fullName, email, password, password) - await page.getByRole("button", { name: "Sign Up" }).click() - await expect(page).toHaveURL(/\/login$/) - - await page.goto("/signup") - - await fillForm(page, fullName, email, password, password) - await page.getByRole("button", { name: "Sign Up" }).click() - - await expect( - page.getByText("The user with this email already exists in the system"), - ).toBeVisible() -}) - -test("Sign up with weak password", async ({ page }) => { - const fullName = "Test User" - const email = randomEmail() - const password = "weak" - - await page.goto("/signup") - - await fillForm(page, fullName, email, password, password) - await page.getByRole("button", { name: "Sign Up" }).click() - - await expect( - page.getByText("Password must be at least 8 characters"), - ).toBeVisible() -}) - -test("Sign up with mismatched passwords", async ({ page }) => { - const fullName = "Test User" - const email = randomEmail() - const password = randomPassword() - const password2 = randomPassword() - - await page.goto("/signup") - - await fillForm(page, fullName, email, password, password2) - await page.getByRole("button", { name: "Sign Up" }).click() - - await expect(page.getByText("The passwords don't match")).toBeVisible() -}) - -test("Sign up with missing full name", async ({ page }) => { - const fullName = "" - const email = randomEmail() - const password = randomPassword() - - await page.goto("/signup") - - await fillForm(page, fullName, email, password, password) - await page.getByRole("button", { name: "Sign Up" }).click() - - await expect(page.getByText("Full Name is required")).toBeVisible() -}) - -test("Sign up with missing email", async ({ page }) => { - const fullName = "Test User" - const email = "" - const password = randomPassword() - - await page.goto("/signup") - - await fillForm(page, fullName, email, password, password) - await page.getByRole("button", { name: "Sign Up" }).click() - - await expect(page.getByText("Invalid email address")).toBeVisible() -}) - -test("Sign up with missing password", async ({ page }) => { - const fullName = "" - const email = randomEmail() - const password = "" - - await page.goto("/signup") - - await fillForm(page, fullName, email, password, password) - await page.getByRole("button", { name: "Sign Up" }).click() - - await expect(page.getByText("Password is required")).toBeVisible() -}) diff --git a/frontend/tests/user-settings.spec.ts b/frontend/tests/user-settings.spec.ts index 533ebb6207..e8f0bf4890 100644 --- a/frontend/tests/user-settings.spec.ts +++ b/frontend/tests/user-settings.spec.ts @@ -1,256 +1,36 @@ import { expect, test } from "@playwright/test" -import { firstSuperuser, firstSuperuserPassword } from "./config.ts" -import { createUser } from "./utils/privateApi.ts" -import { randomEmail, randomPassword } from "./utils/random" -import { logInUser, logOutUser } from "./utils/user" +import { installAuthKitFixture } from "./utils/authkit-fixture" -const tabs = ["My profile", "Password", "Danger zone"] - -test("My profile tab is active by default", async ({ page }) => { +test("profile settings do not expose local password or role editing (network fixture)", async ({ + page, +}) => { + await installAuthKitFixture(page) await page.goto("/settings") - await expect(page.getByRole("tab", { name: "My profile" })).toHaveAttribute( - "aria-selected", - "true", + await expect( + page.getByRole("heading", { name: "User Settings" }), + ).toBeVisible() + await expect( + page.getByRole("tab", { name: "Password", exact: true }), + ).toHaveCount(0) + await expect(page.locator('input[type="password"]')).toHaveCount(0) +}) + +test("logout uses SDK session logout and never stores a legacy bearer (network fixture)", async ({ + page, +}) => { + await installAuthKitFixture(page) + await page.route( + "https://auth.fixture.example/user_management/sessions/logout**", + (route) => + route.fulfill({ contentType: "text/html", body: "Fixture signed out" }), ) -}) - -test("All tabs are visible", async ({ page }) => { - await page.goto("/settings") - for (const tab of tabs) { - await expect(page.getByRole("tab", { name: tab })).toBeVisible() - } -}) - -test.describe("Edit user profile", () => { - test.use({ storageState: { cookies: [], origins: [] } }) - let email: string - let password: string - - test.beforeAll(async () => { - email = randomEmail() - password = randomPassword() - await createUser({ email, password }) - }) - - test.beforeEach(async ({ page }) => { - await logInUser(page, email, password) - await page.goto("/settings") - await page.getByRole("tab", { name: "My profile" }).click() - }) - - test("Edit user name with a valid name", async ({ page }) => { - const updatedName = "Test User 2" - - await page.getByRole("button", { name: "Edit" }).click() - await page.getByLabel("Full name").fill(updatedName) - await page.getByRole("button", { name: "Save" }).click() - - await expect(page.getByText("User updated successfully")).toBeVisible() - await expect( - page.locator("form").getByText(updatedName, { exact: true }), - ).toBeVisible() - }) - - test("Edit user email with an invalid email shows error", async ({ - page, - }) => { - await page.getByRole("button", { name: "Edit" }).click() - await page.getByLabel("Email").fill("") - await page.locator("body").click() - - await expect(page.getByText("Invalid email address")).toBeVisible() - }) -}) - -test.describe("Edit user email", () => { - test.use({ storageState: { cookies: [], origins: [] } }) - - test("Edit user email with a valid email", async ({ page }) => { - const email = randomEmail() - const password = randomPassword() - const updatedEmail = randomEmail() - - await createUser({ email, password }) - await logInUser(page, email, password) - await page.goto("/settings") - await page.getByRole("tab", { name: "My profile" }).click() - - await page.getByRole("button", { name: "Edit" }).click() - await page.getByLabel("Email").fill(updatedEmail) - await page.getByRole("button", { name: "Save" }).click() - - await expect(page.getByText("User updated successfully")).toBeVisible() - await expect( - page.locator("form").getByText(updatedEmail, { exact: true }), - ).toBeVisible() - }) -}) - -test.describe("Cancel edit actions", () => { - test.use({ storageState: { cookies: [], origins: [] } }) - - test("Cancel edit action restores original name", async ({ page }) => { - const email = randomEmail() - const password = randomPassword() - const user = await createUser({ email, password }) - - await logInUser(page, email, password) - await page.goto("/settings") - await page.getByRole("tab", { name: "My profile" }).click() - await page.getByRole("button", { name: "Edit" }).click() - await page.getByLabel("Full name").fill("Test User") - await page.getByRole("button", { name: "Cancel" }).first().click() - - await expect( - page.locator("form").getByText(user.full_name as string, { exact: true }), - ).toBeVisible() - }) - - test("Cancel edit action restores original email", async ({ page }) => { - const email = randomEmail() - const password = randomPassword() - await createUser({ email, password }) - - await logInUser(page, email, password) - await page.goto("/settings") - await page.getByRole("tab", { name: "My profile" }).click() - await page.getByRole("button", { name: "Edit" }).click() - await page.getByLabel("Email").fill(randomEmail()) - await page.getByRole("button", { name: "Cancel" }).first().click() - - await expect( - page.locator("form").getByText(email, { exact: true }), - ).toBeVisible() - }) -}) - -test.describe("Change password", () => { - test.use({ storageState: { cookies: [], origins: [] } }) - - test("Update password successfully", async ({ page }) => { - const email = randomEmail() - const password = randomPassword() - const newPassword = randomPassword() - - await createUser({ email, password }) - await logInUser(page, email, password) - - await page.goto("/settings") - await page.getByRole("tab", { name: "Password" }).click() - await page.getByTestId("current-password-input").fill(password) - await page.getByTestId("new-password-input").fill(newPassword) - await page.getByTestId("confirm-password-input").fill(newPassword) - await page.getByRole("button", { name: "Update Password" }).click() - - await expect(page.getByText("Password updated successfully")).toBeVisible() - - await logOutUser(page) - await logInUser(page, email, newPassword) - }) -}) - -test.describe("Change password validation", () => { - test.use({ storageState: { cookies: [], origins: [] } }) - let email: string - let password: string - - test.beforeAll(async () => { - email = randomEmail() - password = randomPassword() - await createUser({ email, password }) - }) - - test.beforeEach(async ({ page }) => { - await logInUser(page, email, password) - await page.goto("/settings") - await page.getByRole("tab", { name: "Password" }).click() - }) - - test("Update password with weak passwords", async ({ page }) => { - const weakPassword = "weak" - - await page.getByTestId("current-password-input").fill(password) - await page.getByTestId("new-password-input").fill(weakPassword) - await page.getByTestId("confirm-password-input").fill(weakPassword) - await page.getByRole("button", { name: "Update Password" }).click() - - await expect( - page.getByText("Password must be at least 8 characters"), - ).toBeVisible() - }) - - test("New password and confirmation password do not match", async ({ - page, - }) => { - await page.getByTestId("current-password-input").fill(password) - await page.getByTestId("new-password-input").fill(randomPassword()) - await page.getByTestId("confirm-password-input").fill(randomPassword()) - await page.getByRole("button", { name: "Update Password" }).click() - - await expect(page.getByText("The passwords don't match")).toBeVisible() - }) - - test("Current password and new password are the same", async ({ page }) => { - await page.getByTestId("current-password-input").fill(password) - await page.getByTestId("new-password-input").fill(password) - await page.getByTestId("confirm-password-input").fill(password) - await page.getByRole("button", { name: "Update Password" }).click() - - await expect( - page.getByText("New password cannot be the same as the current one"), - ).toBeVisible() - }) -}) - -test("Appearance button is visible in sidebar", async ({ page }) => { await page.goto("/settings") - await expect(page.getByTestId("theme-button")).toBeVisible() -}) - -test("User can switch between theme modes", async ({ page }) => { - await page.goto("/settings") - - await page.getByTestId("theme-button").click() - await page.getByTestId("dark-mode").click() - await expect(page.locator("html")).toHaveClass(/dark/) - - await expect(page.getByTestId("dark-mode")).not.toBeVisible() - - await page.getByTestId("theme-button").click() - await page.getByTestId("light-mode").click() - await expect(page.locator("html")).toHaveClass(/light/) -}) - -test("Selected mode is preserved across sessions", async ({ page }) => { - await page.goto("/settings") - - await page.getByTestId("theme-button").click() - if ( - await page.evaluate(() => - document.documentElement.classList.contains("dark"), - ) - ) { - await page.getByTestId("light-mode").click() - await page.getByTestId("theme-button").click() - } - - const isLightMode = await page.evaluate(() => - document.documentElement.classList.contains("light"), + await page.getByTestId("user-menu").click() + await page.getByRole("menuitem", { name: "Log Out" }).click() + await page.waitForURL( + "https://auth.fixture.example/user_management/sessions/logout**", ) - expect(isLightMode).toBe(true) - - await page.getByTestId("theme-button").click() - await page.getByTestId("dark-mode").click() - let isDarkMode = await page.evaluate(() => - document.documentElement.classList.contains("dark"), - ) - expect(isDarkMode).toBe(true) - - await logOutUser(page) - await logInUser(page, firstSuperuser, firstSuperuserPassword) - - isDarkMode = await page.evaluate(() => - document.documentElement.classList.contains("dark"), + expect(new URL(page.url()).searchParams.get("session_id")).toBe( + "session_fixture", ) - expect(isDarkMode).toBe(true) }) diff --git a/frontend/tests/utils/authkit-fixture.ts b/frontend/tests/utils/authkit-fixture.ts new file mode 100644 index 0000000000..4979508fe1 --- /dev/null +++ b/frontend/tests/utils/authkit-fixture.ts @@ -0,0 +1,82 @@ +import type { Page } from "@playwright/test" + +// Browser network fixtures exercise the real SDK/UI. They are not signed-token or live-flow evidence. +export async function installAuthKitFixture( + page: Page, + { + admin = false, + organization = "org_fixture_a", + denied = false, + tokenLifetimeSeconds = 3600, + } = {}, +) { + const origin = process.env.PLAYWRIGHT_BASE_URL ?? "http://localhost:5173" + await page.route("**/api/v1/auth/config", (route) => + route.fulfill({ + json: { + client_id: "client_fixture", + api_hostname: "auth.fixture.example", + redirect_uri: origin, + }, + }), + ) + await page + .context() + .addCookies([ + { name: "workos-has-session", value: "client_fixture", url: origin }, + ]) + await page.route( + "https://auth.fixture.example/user_management/authenticate", + async (route) => { + const body = route.request().postDataJSON() + const org = body.organization_id ?? organization + const browserTime = await page.evaluate(() => Date.now()) + const issuedAt = Math.floor(browserTime / 1000) + // The native SDK computes expiresAt from exp - iat; omitting iat forces every bearer lookup to refresh. + const claims = { + sub: "user_fixture", + sid: "session_fixture", + org_id: org, + role: "authenticated", + iat: issuedAt, + exp: issuedAt + tokenLifetimeSeconds, + permissions: [], + } + const token = `${Buffer.from(JSON.stringify({ alg: "none" })).toString("base64url")}.${Buffer.from(JSON.stringify(claims)).toString("base64url")}.fixture` + await route.fulfill({ + json: { + access_token: token, + organization_id: org, + user: { + id: "user_fixture", + email: "fixture@example.test", + first_name: "Fixture", + last_name: "User", + email_verified: true, + profile_picture_url: null, + created_at: "2026-01-01T00:00:00Z", + updated_at: "2026-01-01T00:00:00Z", + }, + }, + }) + }, + ) + await page.route("**/api/v1/users/me", (route) => + denied + ? route.fulfill({ status: 403, json: { detail: "Membership inactive" } }) + : route.fulfill({ + json: { + id: "00000000-0000-4000-8000-000000000001", + email: "fixture@example.test", + full_name: "Fixture User", + is_active: true, + tenant_id: "00000000-0000-4000-8000-000000000002", + identity_entity_id: "00000000-0000-4000-8000-000000000003", + created_at: "2026-01-01T00:00:00Z", + user_role: admin ? "admin" : "member", + permissions: ["org:projects:read", "org:projects:write"], + is_tenant_admin: admin, + }, + }), + ) +} diff --git a/frontend/tests/utils/mailpit.ts b/frontend/tests/utils/mailpit.ts deleted file mode 100644 index 6fe8ae76fa..0000000000 --- a/frontend/tests/utils/mailpit.ts +++ /dev/null @@ -1,46 +0,0 @@ -import type { APIRequestContext } from "@playwright/test" - -type EmailSummary = { - ID: string -} - -export async function waitForEmailHtml({ - request, - query, - timeout = 5000, -}: { - request: APIRequestContext - query: string - timeout?: number -}) { - const deadline = Date.now() + timeout - - while (Date.now() < deadline) { - const response = await request.get( - `${process.env.MAILPIT_HOST}/api/v1/search`, - { - params: { query, limit: 1 }, - }, - ) - const { messages }: { messages: EmailSummary[] } = await response.json() - const email = messages[0] - - if (email) { - const htmlResponse = await request.get( - `${process.env.MAILPIT_HOST}/view/${email.ID}.html`, - ) - - if (!htmlResponse.ok()) { - throw new Error( - `Could not get the HTML for email "${email.ID}": ${htmlResponse.status()}`, - ) - } - - return htmlResponse.text() - } - - await new Promise((resolve) => setTimeout(resolve, 100)) - } - - throw new Error(`Timeout while trying to get the latest email for "${query}"`) -} diff --git a/frontend/tests/utils/privateApi.ts b/frontend/tests/utils/privateApi.ts deleted file mode 100644 index fdbcacbd53..0000000000 --- a/frontend/tests/utils/privateApi.ts +++ /dev/null @@ -1,26 +0,0 @@ -// Note: the `PrivateService` is only available when generating the client -// for local environments -import { PrivateService } from "../../src/client" -import { client } from "../../src/client/client.gen" - -client.setConfig({ - baseURL: `${process.env.VITE_API_URL}`, -}) - -export const createUser = async ({ - email, - password, -}: { - email: string - password: string -}) => { - const response = await PrivateService.createUser({ - body: { - email, - password, - is_verified: true, - full_name: "Test User", - }, - }) - return response.data -} diff --git a/frontend/tests/utils/random.ts b/frontend/tests/utils/random.ts deleted file mode 100644 index 8e9cc11749..0000000000 --- a/frontend/tests/utils/random.ts +++ /dev/null @@ -1,19 +0,0 @@ -export const randomEmail = () => - `test_${Math.random().toString(36).substring(7)}@example.com` - -export const randomTeamName = () => - `Team ${Math.random().toString(36).substring(7)}` - -export const randomPassword = () => `${Math.random().toString(36).substring(2)}` - -export const slugify = (text: string) => - text - .toLowerCase() - .replace(/\s+/g, "-") - .replace(/[^\w-]+/g, "") - -export const randomItemTitle = () => - `Item ${Math.random().toString(36).substring(7)}` - -export const randomItemDescription = () => - `Description ${Math.random().toString(36).substring(7)}` diff --git a/frontend/tests/utils/user.ts b/frontend/tests/utils/user.ts deleted file mode 100644 index 33f86e3255..0000000000 --- a/frontend/tests/utils/user.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { expect, type Page } from "@playwright/test" - -export async function signUpNewUser( - page: Page, - name: string, - email: string, - password: string, -) { - await page.goto("/signup") - - await page.getByTestId("full-name-input").fill(name) - await page.getByTestId("email-input").fill(email) - await page.getByTestId("password-input").fill(password) - await page.getByTestId("confirm-password-input").fill(password) - await page.getByRole("button", { name: "Sign Up" }).click() - await page.goto("/login") -} - -export async function logInUser(page: Page, email: string, password: string) { - await page.goto("/login") - - await page.getByTestId("email-input").fill(email) - await page.getByTestId("password-input").fill(password) - await page.getByRole("button", { name: "Log In" }).click() - await page.waitForURL("/") - await expect( - page.getByText("Welcome back, nice to see you again!"), - ).toBeVisible() -} - -export async function logOutUser(page: Page) { - await page.getByTestId("user-menu").click() - await page.getByRole("menuitem", { name: "Log out" }).click() - await page.goto("/login") -} diff --git a/pyproject.toml b/pyproject.toml index 0c29cc7593..7008684820 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -34,3 +34,5 @@ extend-ignore-re = [ [tool.typos.default.extend-identifiers] alls = "alls" +# PostgreSQL RangeVar inheritance flag, exposed verbatim by pglast's native AST. +inh = "inh" diff --git a/scripts/generate-client.sh b/scripts/generate-client.sh index 78697d2902..3f49a13920 100644 --- a/scripts/generate-client.sh +++ b/scripts/generate-client.sh @@ -1,11 +1,7 @@ #! /usr/bin/env bash -set -e -set -x +set -euo pipefail -cd backend -FASTAPI_ENV=development uv run python -c "import app.main; import json; print(json.dumps(app.main.app.openapi()))" > ../openapi.json -cd .. -mv openapi.json frontend/ -bun run --filter frontend generate-client -bun run lint +uv run --no-active --directory backend --locked --no-sync \ + python scripts/export_openapi.py --output ../frontend/openapi.json "$@" +bun run --filter frontend generate-client --no-log-file diff --git a/uv.lock b/uv.lock index 1291c65360..7079169143 100644 --- a/uv.lock +++ b/uv.lock @@ -33,6 +33,22 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/3f/27/78a89b55b0904d222183164e079b4ca56208e94eff1d35ad1f1ad5be9b06/alembic-1.20.0-py3-none-any.whl", hash = "sha256:77eb101048d95f982c0353e9233404889dcd7a6fc244c107836c0e2fc9cf7d9d", size = 268719, upload-time = "2026-09-11T19:09:12.88Z" }, ] +[[package]] +name = "alembic-utils" +version = "0.8.8" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "alembic" }, + { name = "flupy" }, + { name = "parse" }, + { name = "sqlalchemy" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ec/7a/eae622a97ba1721fd7e420c60060a74852b800ac1fecbaa2e67a35941d6d/alembic_utils-0.8.8.tar.gz", hash = "sha256:99de5d13194f26536bc0322f0c1660020a305015700d8447ccfc20e7d1494e5b", size = 21638, upload-time = "2025-04-10T18:58:13.212Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/dd/01/d55bd80997df2ec1ff2fd40cd3eeadec93c4b3c5492df3c6852b29f9e393/alembic_utils-0.8.8-py3-none-any.whl", hash = "sha256:2c2545dc545833c5deb63bce2c3cde01c1807bf99da5efab2497bc8d817cb86e", size = 31044, upload-time = "2025-04-10T18:58:12.247Z" }, +] + [[package]] name = "annotated-doc" version = "0.0.4" @@ -69,16 +85,17 @@ version = "0.1.0" source = { editable = "backend" } dependencies = [ { name = "alembic" }, + { name = "alembic-utils" }, { name = "email-validator" }, { name = "emails" }, { name = "fastapi", extra = ["standard"] }, { name = "httpx" }, { name = "jinja2" }, + { name = "pglast" }, { name = "psycopg", extra = ["binary"] }, - { name = "pwdlib", extra = ["argon2", "bcrypt"] }, { name = "pydantic" }, { name = "pydantic-settings" }, - { name = "pyjwt" }, + { name = "pyjwt", extra = ["crypto"] }, { name = "python-multipart" }, { name = "sentry-sdk", extra = ["fastapi"] }, { name = "sqlmodel" }, @@ -87,6 +104,7 @@ dependencies = [ [package.dev-dependencies] dev = [ { name = "coverage" }, + { name = "httpx2" }, { name = "mypy" }, { name = "pytest" }, { name = "ruff" }, @@ -96,16 +114,17 @@ dev = [ [package.metadata] requires-dist = [ { name = "alembic", specifier = ">=1.19.1,<2.0.0" }, + { name = "alembic-utils", specifier = ">=0.8.8" }, { name = "email-validator", specifier = ">=2.1.0.post1,<3.0.0.0" }, { name = "emails", specifier = ">=1.1.2,<2.0" }, { name = "fastapi", extras = ["standard"], specifier = ">=0.141.1,<1.0.0" }, { name = "httpx", specifier = ">=0.25.1,<1.0.0" }, { name = "jinja2", specifier = ">=3.1.4,<4.0.0" }, + { name = "pglast", specifier = ">=8.7" }, { name = "psycopg", extras = ["binary"], specifier = ">=3.3.6,<4.0.0" }, - { name = "pwdlib", extras = ["argon2", "bcrypt"], specifier = ">=0.3.1" }, { name = "pydantic", specifier = ">=2.13.5" }, { name = "pydantic-settings", specifier = ">=2.2.1,<3.0.0" }, - { name = "pyjwt", specifier = ">=2.15.0,<3.0.0" }, + { name = "pyjwt", extras = ["crypto"], specifier = ">=2.15.0,<3.0.0" }, { name = "python-multipart", specifier = ">=0.0.27,<1.0.0" }, { name = "sentry-sdk", extras = ["fastapi"], specifier = ">=2.70.0,<3.0.0" }, { name = "sqlmodel", specifier = ">=0.0.46,<1.0.0" }, @@ -114,55 +133,13 @@ requires-dist = [ [package.metadata.requires-dev] dev = [ { name = "coverage", specifier = ">=7.4.3,<8.0.0" }, + { name = "httpx2", specifier = ">=2.0.0" }, { name = "mypy", specifier = ">=1.8.0,<3.0.0" }, { name = "pytest", specifier = ">=7.4.3,<10.0.0" }, { name = "ruff", specifier = ">=0.16.0,<1.0.0" }, { name = "ty", specifier = ">=0.0.25" }, ] -[[package]] -name = "argon2-cffi" -version = "25.1.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "argon2-cffi-bindings" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/0e/89/ce5af8a7d472a67cc819d5d998aa8c82c5d860608c4db9f46f1162d7dab9/argon2_cffi-25.1.0.tar.gz", hash = "sha256:694ae5cc8a42f4c4e2bf2ca0e64e51e23a040c6a517a85074683d3959e1346c1", size = 45706, upload-time = "2025-06-03T06:55:32.073Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/4f/d3/a8b22fa575b297cd6e3e3b0155c7e25db170edf1c74783d6a31a2490b8d9/argon2_cffi-25.1.0-py3-none-any.whl", hash = "sha256:fdc8b074db390fccb6eb4a3604ae7231f219aa669a2652e0f20e16ba513d5741", size = 14657, upload-time = "2025-06-03T06:55:30.804Z" }, -] - -[[package]] -name = "argon2-cffi-bindings" -version = "25.1.0" -source = { registry = "https://pypi.org/simple" } -dependencies = [ - { name = "cffi" }, -] -sdist = { url = "https://files.pythonhosted.org/packages/5c/2d/db8af0df73c1cf454f71b2bbe5e356b8c1f8041c979f505b3d3186e520a9/argon2_cffi_bindings-25.1.0.tar.gz", hash = "sha256:b957f3e6ea4d55d820e40ff76f450952807013d361a65d7f28acc0acbf29229d", size = 1783441, upload-time = "2025-07-30T10:02:05.147Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/60/97/3c0a35f46e52108d4707c44b95cfe2afcafc50800b5450c197454569b776/argon2_cffi_bindings-25.1.0-cp314-cp314t-macosx_10_13_universal2.whl", hash = "sha256:3d3f05610594151994ca9ccb3c771115bdb4daef161976a266f0dd8aa9996b8f", size = 54393, upload-time = "2025-07-30T10:01:40.97Z" }, - { url = "https://files.pythonhosted.org/packages/9d/f4/98bbd6ee89febd4f212696f13c03ca302b8552e7dbf9c8efa11ea4a388c3/argon2_cffi_bindings-25.1.0-cp314-cp314t-macosx_10_13_x86_64.whl", hash = "sha256:8b8efee945193e667a396cbc7b4fb7d357297d6234d30a489905d96caabde56b", size = 29328, upload-time = "2025-07-30T10:01:41.916Z" }, - { url = "https://files.pythonhosted.org/packages/43/24/90a01c0ef12ac91a6be05969f29944643bc1e5e461155ae6559befa8f00b/argon2_cffi_bindings-25.1.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:3c6702abc36bf3ccba3f802b799505def420a1b7039862014a65db3205967f5a", size = 31269, upload-time = "2025-07-30T10:01:42.716Z" }, - { url = "https://files.pythonhosted.org/packages/d4/d3/942aa10782b2697eee7af5e12eeff5ebb325ccfb86dd8abda54174e377e4/argon2_cffi_bindings-25.1.0-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a1c70058c6ab1e352304ac7e3b52554daadacd8d453c1752e547c76e9c99ac44", size = 86558, upload-time = "2025-07-30T10:01:43.943Z" }, - { url = "https://files.pythonhosted.org/packages/0d/82/b484f702fec5536e71836fc2dbc8c5267b3f6e78d2d539b4eaa6f0db8bf8/argon2_cffi_bindings-25.1.0-cp314-cp314t-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e2fd3bfbff3c5d74fef31a722f729bf93500910db650c925c2d6ef879a7e51cb", size = 92364, upload-time = "2025-07-30T10:01:44.887Z" }, - { url = "https://files.pythonhosted.org/packages/c9/c1/a606ff83b3f1735f3759ad0f2cd9e038a0ad11a3de3b6c673aa41c24bb7b/argon2_cffi_bindings-25.1.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:c4f9665de60b1b0e99bcd6be4f17d90339698ce954cfd8d9cf4f91c995165a92", size = 85637, upload-time = "2025-07-30T10:01:46.225Z" }, - { url = "https://files.pythonhosted.org/packages/44/b4/678503f12aceb0262f84fa201f6027ed77d71c5019ae03b399b97caa2f19/argon2_cffi_bindings-25.1.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:ba92837e4a9aa6a508c8d2d7883ed5a8f6c308c89a4790e1e447a220deb79a85", size = 91934, upload-time = "2025-07-30T10:01:47.203Z" }, - { url = "https://files.pythonhosted.org/packages/f0/c7/f36bd08ef9bd9f0a9cff9428406651f5937ce27b6c5b07b92d41f91ae541/argon2_cffi_bindings-25.1.0-cp314-cp314t-win32.whl", hash = "sha256:84a461d4d84ae1295871329b346a97f68eade8c53b6ed9a7ca2d7467f3c8ff6f", size = 28158, upload-time = "2025-07-30T10:01:48.341Z" }, - { url = "https://files.pythonhosted.org/packages/b3/80/0106a7448abb24a2c467bf7d527fe5413b7fdfa4ad6d6a96a43a62ef3988/argon2_cffi_bindings-25.1.0-cp314-cp314t-win_amd64.whl", hash = "sha256:b55aec3565b65f56455eebc9b9f34130440404f27fe21c3b375bf1ea4d8fbae6", size = 32597, upload-time = "2025-07-30T10:01:49.112Z" }, - { url = "https://files.pythonhosted.org/packages/05/b8/d663c9caea07e9180b2cb662772865230715cbd573ba3b5e81793d580316/argon2_cffi_bindings-25.1.0-cp314-cp314t-win_arm64.whl", hash = "sha256:87c33a52407e4c41f3b70a9c2d3f6056d88b10dad7695be708c5021673f55623", size = 28231, upload-time = "2025-07-30T10:01:49.92Z" }, - { url = "https://files.pythonhosted.org/packages/1d/57/96b8b9f93166147826da5f90376e784a10582dd39a393c99bb62cfcf52f0/argon2_cffi_bindings-25.1.0-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:aecba1723ae35330a008418a91ea6cfcedf6d31e5fbaa056a166462ff066d500", size = 54121, upload-time = "2025-07-30T10:01:50.815Z" }, - { url = "https://files.pythonhosted.org/packages/0a/08/a9bebdb2e0e602dde230bdde8021b29f71f7841bd54801bcfd514acb5dcf/argon2_cffi_bindings-25.1.0-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:2630b6240b495dfab90aebe159ff784d08ea999aa4b0d17efa734055a07d2f44", size = 29177, upload-time = "2025-07-30T10:01:51.681Z" }, - { url = "https://files.pythonhosted.org/packages/b6/02/d297943bcacf05e4f2a94ab6f462831dc20158614e5d067c35d4e63b9acb/argon2_cffi_bindings-25.1.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:7aef0c91e2c0fbca6fc68e7555aa60ef7008a739cbe045541e438373bc54d2b0", size = 31090, upload-time = "2025-07-30T10:01:53.184Z" }, - { url = "https://files.pythonhosted.org/packages/c1/93/44365f3d75053e53893ec6d733e4a5e3147502663554b4d864587c7828a7/argon2_cffi_bindings-25.1.0-cp39-abi3-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1e021e87faa76ae0d413b619fe2b65ab9a037f24c60a1e6cc43457ae20de6dc6", size = 81246, upload-time = "2025-07-30T10:01:54.145Z" }, - { url = "https://files.pythonhosted.org/packages/09/52/94108adfdd6e2ddf58be64f959a0b9c7d4ef2fa71086c38356d22dc501ea/argon2_cffi_bindings-25.1.0-cp39-abi3-manylinux_2_26_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d3e924cfc503018a714f94a49a149fdc0b644eaead5d1f089330399134fa028a", size = 87126, upload-time = "2025-07-30T10:01:55.074Z" }, - { url = "https://files.pythonhosted.org/packages/72/70/7a2993a12b0ffa2a9271259b79cc616e2389ed1a4d93842fac5a1f923ffd/argon2_cffi_bindings-25.1.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:c87b72589133f0346a1cb8d5ecca4b933e3c9b64656c9d175270a000e73b288d", size = 80343, upload-time = "2025-07-30T10:01:56.007Z" }, - { url = "https://files.pythonhosted.org/packages/78/9a/4e5157d893ffc712b74dbd868c7f62365618266982b64accab26bab01edc/argon2_cffi_bindings-25.1.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:1db89609c06afa1a214a69a462ea741cf735b29a57530478c06eb81dd403de99", size = 86777, upload-time = "2025-07-30T10:01:56.943Z" }, - { url = "https://files.pythonhosted.org/packages/74/cd/15777dfde1c29d96de7f18edf4cc94c385646852e7c7b0320aa91ccca583/argon2_cffi_bindings-25.1.0-cp39-abi3-win32.whl", hash = "sha256:473bcb5f82924b1becbb637b63303ec8d10e84c8d241119419897a26116515d2", size = 27180, upload-time = "2025-07-30T10:01:57.759Z" }, - { url = "https://files.pythonhosted.org/packages/e2/c6/a759ece8f1829d1f162261226fbfd2c6832b3ff7657384045286d2afa384/argon2_cffi_bindings-25.1.0-cp39-abi3-win_amd64.whl", hash = "sha256:a98cd7d17e9f7ce244c0803cad3c23a7d379c301ba618a5fa76a67d116618b98", size = 31715, upload-time = "2025-07-30T10:01:58.56Z" }, - { url = "https://files.pythonhosted.org/packages/42/b9/f8d6fa329ab25128b7e98fd83a3cb34d9db5b059a9847eddb840a0af45dd/argon2_cffi_bindings-25.1.0-cp39-abi3-win_arm64.whl", hash = "sha256:b0fdbcf513833809c882823f98dc2f931cf659d9a1429616ac3adebb49f5db94", size = 27149, upload-time = "2025-07-30T10:01:59.329Z" }, -] - [[package]] name = "ast-serialize" version = "0.8.0" @@ -227,57 +204,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/25/6c/b400476d3ceba681ab929787edc9554f6d88fcc69435eb681b00fc0457a5/ast_serialize-0.8.0-cp39-abi3-win_arm64.whl", hash = "sha256:b2a5978662fd4db463dfb4b974d2b10ac6430b98f5333aabc7051909df3561d0", size = 1083655, upload-time = "2026-08-07T11:29:00.349Z" }, ] -[[package]] -name = "bcrypt" -version = "5.0.0" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/d4/36/3329e2518d70ad8e2e5817d5a4cac6bba05a47767ec416c7d020a965f408/bcrypt-5.0.0.tar.gz", hash = "sha256:f748f7c2d6fd375cc93d3fba7ef4a9e3a092421b8dbf34d8d4dc06be9492dfdd", size = 25386, upload-time = "2025-09-25T19:50:47.829Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/f8/14/c18006f91816606a4abe294ccc5d1e6f0e42304df5a33710e9e8e95416e1/bcrypt-5.0.0-cp314-cp314t-macosx_10_12_universal2.whl", hash = "sha256:4870a52610537037adb382444fefd3706d96d663ac44cbb2f37e3919dca3d7ef", size = 481862, upload-time = "2025-09-25T19:49:28.365Z" }, - { url = "https://files.pythonhosted.org/packages/67/49/dd074d831f00e589537e07a0725cf0e220d1f0d5d8e85ad5bbff251c45aa/bcrypt-5.0.0-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:48f753100931605686f74e27a7b49238122aa761a9aefe9373265b8b7aa43ea4", size = 268544, upload-time = "2025-09-25T19:49:30.39Z" }, - { url = "https://files.pythonhosted.org/packages/f5/91/50ccba088b8c474545b034a1424d05195d9fcbaaf802ab8bfe2be5a4e0d7/bcrypt-5.0.0-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f70aadb7a809305226daedf75d90379c397b094755a710d7014b8b117df1ebbf", size = 271787, upload-time = "2025-09-25T19:49:32.144Z" }, - { url = "https://files.pythonhosted.org/packages/aa/e7/d7dba133e02abcda3b52087a7eea8c0d4f64d3e593b4fffc10c31b7061f3/bcrypt-5.0.0-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:744d3c6b164caa658adcb72cb8cc9ad9b4b75c7db507ab4bc2480474a51989da", size = 269753, upload-time = "2025-09-25T19:49:33.885Z" }, - { url = "https://files.pythonhosted.org/packages/33/fc/5b145673c4b8d01018307b5c2c1fc87a6f5a436f0ad56607aee389de8ee3/bcrypt-5.0.0-cp314-cp314t-manylinux_2_28_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:a28bc05039bdf3289d757f49d616ab3efe8cf40d8e8001ccdd621cd4f98f4fc9", size = 289587, upload-time = "2025-09-25T19:49:35.144Z" }, - { url = "https://files.pythonhosted.org/packages/27/d7/1ff22703ec6d4f90e62f1a5654b8867ef96bafb8e8102c2288333e1a6ca6/bcrypt-5.0.0-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:7f277a4b3390ab4bebe597800a90da0edae882c6196d3038a73adf446c4f969f", size = 272178, upload-time = "2025-09-25T19:49:36.793Z" }, - { url = "https://files.pythonhosted.org/packages/c8/88/815b6d558a1e4d40ece04a2f84865b0fef233513bd85fd0e40c294272d62/bcrypt-5.0.0-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:79cfa161eda8d2ddf29acad370356b47f02387153b11d46042e93a0a95127493", size = 269295, upload-time = "2025-09-25T19:49:38.164Z" }, - { url = "https://files.pythonhosted.org/packages/51/8c/e0db387c79ab4931fc89827d37608c31cc57b6edc08ccd2386139028dc0d/bcrypt-5.0.0-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:a5393eae5722bcef046a990b84dff02b954904c36a194f6cfc817d7dca6c6f0b", size = 271700, upload-time = "2025-09-25T19:49:39.917Z" }, - { url = "https://files.pythonhosted.org/packages/06/83/1570edddd150f572dbe9fc00f6203a89fc7d4226821f67328a85c330f239/bcrypt-5.0.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:7f4c94dec1b5ab5d522750cb059bb9409ea8872d4494fd152b53cca99f1ddd8c", size = 334034, upload-time = "2025-09-25T19:49:41.227Z" }, - { url = "https://files.pythonhosted.org/packages/c9/f2/ea64e51a65e56ae7a8a4ec236c2bfbdd4b23008abd50ac33fbb2d1d15424/bcrypt-5.0.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:0cae4cb350934dfd74c020525eeae0a5f79257e8a201c0c176f4b84fdbf2a4b4", size = 352766, upload-time = "2025-09-25T19:49:43.08Z" }, - { url = "https://files.pythonhosted.org/packages/d7/d4/1a388d21ee66876f27d1a1f41287897d0c0f1712ef97d395d708ba93004c/bcrypt-5.0.0-cp314-cp314t-win32.whl", hash = "sha256:b17366316c654e1ad0306a6858e189fc835eca39f7eb2cafd6aaca8ce0c40a2e", size = 152449, upload-time = "2025-09-25T19:49:44.971Z" }, - { url = "https://files.pythonhosted.org/packages/3f/61/3291c2243ae0229e5bca5d19f4032cecad5dfb05a2557169d3a69dc0ba91/bcrypt-5.0.0-cp314-cp314t-win_amd64.whl", hash = "sha256:92864f54fb48b4c718fc92a32825d0e42265a627f956bc0361fe869f1adc3e7d", size = 149310, upload-time = "2025-09-25T19:49:46.162Z" }, - { url = "https://files.pythonhosted.org/packages/3e/89/4b01c52ae0c1a681d4021e5dd3e45b111a8fb47254a274fa9a378d8d834b/bcrypt-5.0.0-cp314-cp314t-win_arm64.whl", hash = "sha256:dd19cf5184a90c873009244586396a6a884d591a5323f0e8a5922560718d4993", size = 143761, upload-time = "2025-09-25T19:49:47.345Z" }, - { url = "https://files.pythonhosted.org/packages/84/29/6237f151fbfe295fe3e074ecc6d44228faa1e842a81f6d34a02937ee1736/bcrypt-5.0.0-cp38-abi3-macosx_10_12_universal2.whl", hash = "sha256:fc746432b951e92b58317af8e0ca746efe93e66555f1b40888865ef5bf56446b", size = 494553, upload-time = "2025-09-25T19:49:49.006Z" }, - { url = "https://files.pythonhosted.org/packages/45/b6/4c1205dde5e464ea3bd88e8742e19f899c16fa8916fb8510a851fae985b5/bcrypt-5.0.0-cp38-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:c2388ca94ffee269b6038d48747f4ce8df0ffbea43f31abfa18ac72f0218effb", size = 275009, upload-time = "2025-09-25T19:49:50.581Z" }, - { url = "https://files.pythonhosted.org/packages/3b/71/427945e6ead72ccffe77894b2655b695ccf14ae1866cd977e185d606dd2f/bcrypt-5.0.0-cp38-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:560ddb6ec730386e7b3b26b8b4c88197aaed924430e7b74666a586ac997249ef", size = 278029, upload-time = "2025-09-25T19:49:52.533Z" }, - { url = "https://files.pythonhosted.org/packages/17/72/c344825e3b83c5389a369c8a8e58ffe1480b8a699f46c127c34580c4666b/bcrypt-5.0.0-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:d79e5c65dcc9af213594d6f7f1fa2c98ad3fc10431e7aa53c176b441943efbdd", size = 275907, upload-time = "2025-09-25T19:49:54.709Z" }, - { url = "https://files.pythonhosted.org/packages/0b/7e/d4e47d2df1641a36d1212e5c0514f5291e1a956a7749f1e595c07a972038/bcrypt-5.0.0-cp38-abi3-manylinux_2_28_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:2b732e7d388fa22d48920baa267ba5d97cca38070b69c0e2d37087b381c681fd", size = 296500, upload-time = "2025-09-25T19:49:56.013Z" }, - { url = "https://files.pythonhosted.org/packages/0f/c3/0ae57a68be2039287ec28bc463b82e4b8dc23f9d12c0be331f4782e19108/bcrypt-5.0.0-cp38-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:0c8e093ea2532601a6f686edbc2c6b2ec24131ff5c52f7610dd64fa4553b5464", size = 278412, upload-time = "2025-09-25T19:49:57.356Z" }, - { url = "https://files.pythonhosted.org/packages/45/2b/77424511adb11e6a99e3a00dcc7745034bee89036ad7d7e255a7e47be7d8/bcrypt-5.0.0-cp38-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:5b1589f4839a0899c146e8892efe320c0fa096568abd9b95593efac50a87cb75", size = 275486, upload-time = "2025-09-25T19:49:59.116Z" }, - { url = "https://files.pythonhosted.org/packages/43/0a/405c753f6158e0f3f14b00b462d8bca31296f7ecfc8fc8bc7919c0c7d73a/bcrypt-5.0.0-cp38-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:89042e61b5e808b67daf24a434d89bab164d4de1746b37a8d173b6b14f3db9ff", size = 277940, upload-time = "2025-09-25T19:50:00.869Z" }, - { url = "https://files.pythonhosted.org/packages/62/83/b3efc285d4aadc1fa83db385ec64dcfa1707e890eb42f03b127d66ac1b7b/bcrypt-5.0.0-cp38-abi3-musllinux_1_1_aarch64.whl", hash = "sha256:e3cf5b2560c7b5a142286f69bde914494b6d8f901aaa71e453078388a50881c4", size = 310776, upload-time = "2025-09-25T19:50:02.393Z" }, - { url = "https://files.pythonhosted.org/packages/95/7d/47ee337dacecde6d234890fe929936cb03ebc4c3a7460854bbd9c97780b8/bcrypt-5.0.0-cp38-abi3-musllinux_1_1_x86_64.whl", hash = "sha256:f632fd56fc4e61564f78b46a2269153122db34988e78b6be8b32d28507b7eaeb", size = 312922, upload-time = "2025-09-25T19:50:04.232Z" }, - { url = "https://files.pythonhosted.org/packages/d6/3a/43d494dfb728f55f4e1cf8fd435d50c16a2d75493225b54c8d06122523c6/bcrypt-5.0.0-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:801cad5ccb6b87d1b430f183269b94c24f248dddbbc5c1f78b6ed231743e001c", size = 341367, upload-time = "2025-09-25T19:50:05.559Z" }, - { url = "https://files.pythonhosted.org/packages/55/ab/a0727a4547e383e2e22a630e0f908113db37904f58719dc48d4622139b5c/bcrypt-5.0.0-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:3cf67a804fc66fc217e6914a5635000259fbbbb12e78a99488e4d5ba445a71eb", size = 359187, upload-time = "2025-09-25T19:50:06.916Z" }, - { url = "https://files.pythonhosted.org/packages/1b/bb/461f352fdca663524b4643d8b09e8435b4990f17fbf4fea6bc2a90aa0cc7/bcrypt-5.0.0-cp38-abi3-win32.whl", hash = "sha256:3abeb543874b2c0524ff40c57a4e14e5d3a66ff33fb423529c88f180fd756538", size = 153752, upload-time = "2025-09-25T19:50:08.515Z" }, - { url = "https://files.pythonhosted.org/packages/41/aa/4190e60921927b7056820291f56fc57d00d04757c8b316b2d3c0d1d6da2c/bcrypt-5.0.0-cp38-abi3-win_amd64.whl", hash = "sha256:35a77ec55b541e5e583eb3436ffbbf53b0ffa1fa16ca6782279daf95d146dcd9", size = 150881, upload-time = "2025-09-25T19:50:09.742Z" }, - { url = "https://files.pythonhosted.org/packages/54/12/cd77221719d0b39ac0b55dbd39358db1cd1246e0282e104366ebbfb8266a/bcrypt-5.0.0-cp38-abi3-win_arm64.whl", hash = "sha256:cde08734f12c6a4e28dc6755cd11d3bdfea608d93d958fffbe95a7026ebe4980", size = 144931, upload-time = "2025-09-25T19:50:11.016Z" }, - { url = "https://files.pythonhosted.org/packages/5d/ba/2af136406e1c3839aea9ecadc2f6be2bcd1eff255bd451dd39bcf302c47a/bcrypt-5.0.0-cp39-abi3-macosx_10_12_universal2.whl", hash = "sha256:0c418ca99fd47e9c59a301744d63328f17798b5947b0f791e9af3c1c499c2d0a", size = 495313, upload-time = "2025-09-25T19:50:12.309Z" }, - { url = "https://files.pythonhosted.org/packages/ac/ee/2f4985dbad090ace5ad1f7dd8ff94477fe089b5fab2040bd784a3d5f187b/bcrypt-5.0.0-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:ddb4e1500f6efdd402218ffe34d040a1196c072e07929b9820f363a1fd1f4191", size = 275290, upload-time = "2025-09-25T19:50:13.673Z" }, - { url = "https://files.pythonhosted.org/packages/e4/6e/b77ade812672d15cf50842e167eead80ac3514f3beacac8902915417f8b7/bcrypt-5.0.0-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7aeef54b60ceddb6f30ee3db090351ecf0d40ec6e2abf41430997407a46d2254", size = 278253, upload-time = "2025-09-25T19:50:15.089Z" }, - { url = "https://files.pythonhosted.org/packages/36/c4/ed00ed32f1040f7990dac7115f82273e3c03da1e1a1587a778d8cea496d8/bcrypt-5.0.0-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:f0ce778135f60799d89c9693b9b398819d15f1921ba15fe719acb3178215a7db", size = 276084, upload-time = "2025-09-25T19:50:16.699Z" }, - { url = "https://files.pythonhosted.org/packages/e7/c4/fa6e16145e145e87f1fa351bbd54b429354fd72145cd3d4e0c5157cf4c70/bcrypt-5.0.0-cp39-abi3-manylinux_2_28_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:a71f70ee269671460b37a449f5ff26982a6f2ba493b3eabdd687b4bf35f875ac", size = 297185, upload-time = "2025-09-25T19:50:18.525Z" }, - { url = "https://files.pythonhosted.org/packages/24/b4/11f8a31d8b67cca3371e046db49baa7c0594d71eb40ac8121e2fc0888db0/bcrypt-5.0.0-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:f8429e1c410b4073944f03bd778a9e066e7fad723564a52ff91841d278dfc822", size = 278656, upload-time = "2025-09-25T19:50:19.809Z" }, - { url = "https://files.pythonhosted.org/packages/ac/31/79f11865f8078e192847d2cb526e3fa27c200933c982c5b2869720fa5fce/bcrypt-5.0.0-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:edfcdcedd0d0f05850c52ba3127b1fce70b9f89e0fe5ff16517df7e81fa3cbb8", size = 275662, upload-time = "2025-09-25T19:50:21.567Z" }, - { url = "https://files.pythonhosted.org/packages/d4/8d/5e43d9584b3b3591a6f9b68f755a4da879a59712981ef5ad2a0ac1379f7a/bcrypt-5.0.0-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:611f0a17aa4a25a69362dcc299fda5c8a3d4f160e2abb3831041feb77393a14a", size = 278240, upload-time = "2025-09-25T19:50:23.305Z" }, - { url = "https://files.pythonhosted.org/packages/89/48/44590e3fc158620f680a978aafe8f87a4c4320da81ed11552f0323aa9a57/bcrypt-5.0.0-cp39-abi3-musllinux_1_1_aarch64.whl", hash = "sha256:db99dca3b1fdc3db87d7c57eac0c82281242d1eabf19dcb8a6b10eb29a2e72d1", size = 311152, upload-time = "2025-09-25T19:50:24.597Z" }, - { url = "https://files.pythonhosted.org/packages/5f/85/e4fbfc46f14f47b0d20493669a625da5827d07e8a88ee460af6cd9768b44/bcrypt-5.0.0-cp39-abi3-musllinux_1_1_x86_64.whl", hash = "sha256:5feebf85a9cefda32966d8171f5db7e3ba964b77fdfe31919622256f80f9cf42", size = 313284, upload-time = "2025-09-25T19:50:26.268Z" }, - { url = "https://files.pythonhosted.org/packages/25/ae/479f81d3f4594456a01ea2f05b132a519eff9ab5768a70430fa1132384b1/bcrypt-5.0.0-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:3ca8a166b1140436e058298a34d88032ab62f15aae1c598580333dc21d27ef10", size = 341643, upload-time = "2025-09-25T19:50:28.02Z" }, - { url = "https://files.pythonhosted.org/packages/df/d2/36a086dee1473b14276cd6ea7f61aef3b2648710b5d7f1c9e032c29b859f/bcrypt-5.0.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:61afc381250c3182d9078551e3ac3a41da14154fbff647ddf52a769f588c4172", size = 359698, upload-time = "2025-09-25T19:50:31.347Z" }, - { url = "https://files.pythonhosted.org/packages/c0/f6/688d2cd64bfd0b14d805ddb8a565e11ca1fb0fd6817175d58b10052b6d88/bcrypt-5.0.0-cp39-abi3-win32.whl", hash = "sha256:64d7ce196203e468c457c37ec22390f1a61c85c6f0b8160fd752940ccfb3a683", size = 153725, upload-time = "2025-09-25T19:50:34.384Z" }, - { url = "https://files.pythonhosted.org/packages/9f/b9/9d9a641194a730bda138b3dfe53f584d61c58cd5230e37566e83ec2ffa0d/bcrypt-5.0.0-cp39-abi3-win_amd64.whl", hash = "sha256:64ee8434b0da054d830fa8e89e1c8bf30061d539044a39524ff7dec90481e5c2", size = 150912, upload-time = "2025-09-25T19:50:35.69Z" }, - { url = "https://files.pythonhosted.org/packages/27/44/d2ef5e87509158ad2187f4dd0852df80695bb1ee0cfe0a684727b01a69e0/bcrypt-5.0.0-cp39-abi3-win_arm64.whl", hash = "sha256:f2347d3534e76bf50bca5500989d6c1d05ed64b440408057a37673282c654927", size = 144953, upload-time = "2025-09-25T19:50:37.32Z" }, -] - [[package]] name = "certifi" version = "2026.10.19" @@ -410,6 +336,69 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/96/1a/d6d16babd0a5fe4c3fae40702158c570351694e74516d8d81b86c5637448/coverage-7.16.1-py3-none-any.whl", hash = "sha256:3d8bd4e58b6a5c2018d808f297905393c6c61da466a48c3f0596a76a4900ebe4", size = 215264, upload-time = "2026-09-13T19:12:18.895Z" }, ] +[[package]] +name = "cryptography" +version = "50.0.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cffi", marker = "platform_python_implementation != 'PyPy'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9d/af/182eb91b0df3fe75c4d9f26fe70684569566745f6ba7e5c9c73a862c5252/cryptography-50.0.2.tar.gz", hash = "sha256:7b46165bb56eb4704e2eaaf86f3c940d19154535d9b0ca7d6d590b04060e00d5", size = 880623, upload-time = "2026-09-30T15:30:04.884Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e5/56/d194340cc4a57535e82e1bee9e89667ac4b7c13b5d3f59686deae3094dd5/cryptography-50.0.2-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:fa8f5efb344d6908a1ce62f4a24e2e5780f825d6f53f5f50ec5ffacac72936cb", size = 3914904, upload-time = "2026-09-30T14:43:44.339Z" }, + { url = "https://files.pythonhosted.org/packages/d9/69/c9bd862c3bf43d6399c433caf002df16e2dffd4be49bdf515cda38038711/cryptography-50.0.2-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:79def8d059362e7831389ed3be0ecdf58a89386e1271e35dd9f5af84e81bffd0", size = 4731146, upload-time = "2026-09-30T14:43:47.113Z" }, + { url = "https://files.pythonhosted.org/packages/21/69/64cef1f702bf6657e0cc186ed1a2891d50d29fb41586b254e1c07adea261/cryptography-50.0.2-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:630ebfea3bf689d075f82316324ff7433dc447fe6bc1bfc76524b74b4a9567d2", size = 4719841, upload-time = "2026-09-30T14:43:49.01Z" }, + { url = "https://files.pythonhosted.org/packages/38/6b/61a3f8d8c5e1e49a6cddccafc4015cc1c0021360ab0acb4080e7a423644a/cryptography-50.0.2-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:f9f6143a8c75945eb960d9eb98905a441394abfa24afaae239d514ffb2586480", size = 4738340, upload-time = "2026-09-30T14:43:50.932Z" }, + { url = "https://files.pythonhosted.org/packages/7b/2e/7212ca32fd43dc91f2f41db20160b268098874b4c9a0e7be94d6835f5b2e/cryptography-50.0.2-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:a582ab2ae1d34f67112cadc86702774c9ea4374df6bca6afe672817203c99134", size = 5367029, upload-time = "2026-09-30T14:43:52.911Z" }, + { url = "https://files.pythonhosted.org/packages/1a/f1/b474e930c4d910328780e3940da76f5aa5cbc48ce1fc14e44d239d9ea9db/cryptography-50.0.2-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:4061c0079120205fb760c58acab6443e217307dcf05e3702cf970e0689972856", size = 4753050, upload-time = "2026-09-30T14:43:55.272Z" }, + { url = "https://files.pythonhosted.org/packages/7c/52/9af10e80ac16b0fcc2123f9cbd5e7afbd0fd5075bb7a607c592258a39cda/cryptography-50.0.2-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:ac9ed99d81760c62fe89d5f0815cdfa1ba9a35141cf30f1c2d044f04b4803d2e", size = 4376724, upload-time = "2026-09-30T14:43:57.24Z" }, + { url = "https://files.pythonhosted.org/packages/71/37/6202e488cc1eb625ea110c292c6bda92823176e023f427d8d5660ce8d632/cryptography-50.0.2-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:87e9ce85beb6b328ba370cc6e6aea483c92617b4c95b1d33a49297eb662bfb04", size = 4737859, upload-time = "2026-09-30T14:43:59.541Z" }, + { url = "https://files.pythonhosted.org/packages/8f/30/e86d7d518489b0ae2497091a35287abcb1a2ce4037837a34afbe9b1d6964/cryptography-50.0.2-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:f265528741e048bce55c3463ed721fb0aa45a5888d8add8cfeccb3035451bbdc", size = 5324103, upload-time = "2026-09-30T14:44:01.901Z" }, + { url = "https://files.pythonhosted.org/packages/d3/69/2c833a049475e0a3444e94c7d0aca0aa51d166374a449b09e92ac98138de/cryptography-50.0.2-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:9dab55f57c74c3cad24c323bacbbd04be4705ba6eb0d92e920b1fc4837ed5079", size = 4752576, upload-time = "2026-09-30T14:44:04.545Z" }, + { url = "https://files.pythonhosted.org/packages/6c/5d/906970b83bbfc1f5bbfb677a143c181f2801f23b6a7204a3b47c42c97e65/cryptography-50.0.2-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:25784ce8b9621c90c643efb9e1e2162ab3b0224cae446ad5e70e7fcb1ce18b51", size = 4870819, upload-time = "2026-09-30T14:44:06.884Z" }, + { url = "https://files.pythonhosted.org/packages/68/e3/f2298d3bb55e0c4a91841ec4d01b3f020ba8c5fbf15ccdcc6dcf03f97025/cryptography-50.0.2-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:85d0d9a31b9098e98534226d5686b47264b95e62ce459dc2e62fdfc809f9fe93", size = 5030152, upload-time = "2026-09-30T14:44:09.443Z" }, + { url = "https://files.pythonhosted.org/packages/9a/4f/adfc442765721292fff86d314ce385d3249d22db42295c0dd057727b60f3/cryptography-50.0.2-cp311-abi3-win_amd64.whl", hash = "sha256:7afa5a6602a9f29af1f3a2965f831bae7c9d5d597b7cbb716d41ab3b7d89879c", size = 3824692, upload-time = "2026-09-30T14:44:11.671Z" }, + { url = "https://files.pythonhosted.org/packages/ce/cb/52eb3770c0d0be2702a98c6e96065ddc0a2877cf0845aa9c23397c142cd4/cryptography-50.0.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:f785f6161f202ab04d8ca194158968798e480ca058943907972da5f12e2881e8", size = 3892731, upload-time = "2026-09-30T14:44:13.485Z" }, + { url = "https://files.pythonhosted.org/packages/19/8e/aa1fc533d4546b127b45de8aa024eb5933d23eff9debfe25931e56861095/cryptography-50.0.2-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:0ecbc5652bdb6fc9eaf89a7d196e20941adfe812f43bc4ca05d9150496821047", size = 4710431, upload-time = "2026-09-30T14:44:15.427Z" }, + { url = "https://files.pythonhosted.org/packages/6a/64/72bc3f75176e7e406b748a3e3830432b8c51297b38368713df04dc04898a/cryptography-50.0.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ab50ee449bf968271e820086f10a33d101dd060370abc10bcd22279be2656539", size = 4694824, upload-time = "2026-09-30T14:44:17.69Z" }, + { url = "https://files.pythonhosted.org/packages/4e/c6/62c77550edfa5ca3f14bf44a1e6739b9fa09d6e998a11d97ed8213bccc98/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:a9f7355e6fab51f6c369b86fb7571cffa05edee2c2121e0380a37fb9ac1cd5c1", size = 4716967, upload-time = "2026-09-30T14:44:19.661Z" }, + { url = "https://files.pythonhosted.org/packages/f4/37/cce70f150c432914460157a6ecc161752e053aa5ec0ef3b3f7dc6e31039a/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:94e5e9f108ee10471288214d3d233fbfbb492840a8457eb85178d643ddeb32c7", size = 5328676, upload-time = "2026-09-30T14:44:21.744Z" }, + { url = "https://files.pythonhosted.org/packages/aa/9a/6f2f0304d634ceafdeaf23e84537336664ac419b5d07611675c2ad3f6b7a/cryptography-50.0.2-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:241449bf940a5d27309bd317e6f9a2af6932113818bb2b8f5c59ddc7ef16da18", size = 4727698, upload-time = "2026-09-30T14:44:24.178Z" }, + { url = "https://files.pythonhosted.org/packages/1d/de/66bcf9244d118663b2e1aaded8990f4640e3d7b7411870a5765f252074d2/cryptography-50.0.2-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:d8947001be83df1394050758ce0e745dd74fb134eef0a4b5124208dfc3a68c37", size = 4354821, upload-time = "2026-09-30T14:44:26.263Z" }, + { url = "https://files.pythonhosted.org/packages/bd/e6/db28a28c7b6c676addce89136de3d8db49ea825a8c863472e36e42ead4ad/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:4a20ce1e5cb4284a86692fdcba7cb8754185c6b2e5c56fcef3751cf451d3cdc2", size = 4716748, upload-time = "2026-09-30T14:44:28.447Z" }, + { url = "https://files.pythonhosted.org/packages/30/96/01546c7f69ea0e2ab790a2e4f0934a4052fb9b388147fbf83c2fd72f1e57/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:84f964e537f916e2cc85199e5a88742e964939b575ac8598b3f9d6cc416cdaf1", size = 5285085, upload-time = "2026-09-30T14:44:30.704Z" }, + { url = "https://files.pythonhosted.org/packages/6c/01/03263395f74d50b071e9e66daace3f8bef80493e5d410726f2ba8554736b/cryptography-50.0.2-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:828d49b0ff5a0e3975865571c5d91dbbdd0d38d8289b249a163e9425413a5e05", size = 4727268, upload-time = "2026-09-30T14:44:32.92Z" }, + { url = "https://files.pythonhosted.org/packages/eb/94/2bfe8f29ec0cc9c0d99359c4161adf32858e4934b72c6d100d2ac0bbe962/cryptography-50.0.2-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:deb9fde5c60e437ee4821bc9bc39ff31b42135c27e1dc61ef0a629389c1de62e", size = 4849503, upload-time = "2026-09-30T14:44:34.969Z" }, + { url = "https://files.pythonhosted.org/packages/54/44/e80651ecbf0e42b62e2bb5f5768916e07eea72e1297338956a61df361f88/cryptography-50.0.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:8c71ba2cd31fc93748c38e1b613200ff1c2665cbfd5341fe3a61cfde35a1430e", size = 5004057, upload-time = "2026-09-30T14:44:37.064Z" }, + { url = "https://files.pythonhosted.org/packages/f8/cc/1d33befb3cd7ea7e77d2d73f43f2066471da1b21f24a6156efcaabf6d2e8/cryptography-50.0.2-cp314-cp314t-win_amd64.whl", hash = "sha256:78198641e5be9521beea5aa782bb551a58068d10e6eb04c9c680c1b69f2e7d45", size = 3795868, upload-time = "2026-09-30T14:44:39.71Z" }, + { url = "https://files.pythonhosted.org/packages/2d/49/93f6a6e7a87c9aa68d44d3e1cdb5fe8f60c90d5d2f46acae9a56892816b8/cryptography-50.0.2-cp315-abi3.abi3t-macosx_11_0_arm64.whl", hash = "sha256:edc3342adf8f697fc5f59c887a304356f147b397809440ed64e2fa6af2f50f37", size = 4133708, upload-time = "2026-09-30T14:44:41.807Z" }, + { url = "https://files.pythonhosted.org/packages/8c/75/32ac2a56243d778805c16ca6a32b8f74fb757df7e28d7ecb560afafb59cf/cryptography-50.0.2-cp315-abi3.abi3t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d370b8d1dfcdf7130178137f6fbee6140774a1acc6cacefc4b42643ec11d0a3a", size = 4956267, upload-time = "2026-09-30T14:44:43.693Z" }, + { url = "https://files.pythonhosted.org/packages/aa/a4/2c8d734e43d97f0842ee9f1b7b4bfb3d0cf5e19edebf43c2afe6675c2320/cryptography-50.0.2-cp315-abi3.abi3t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:f2f9bd7f90c64fe89253f0a2c05e3c4856072660429ce8831b4235bf29403a67", size = 4966465, upload-time = "2026-09-30T14:44:45.769Z" }, + { url = "https://files.pythonhosted.org/packages/c2/58/ee288c829a6f41f6235ae9dd33d82fd19b45442b65b4c8a3da36963d9f7a/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_aarch64.whl", hash = "sha256:e275096ea1e60cc595cda2836fd4a6c725d1125108b868be17f53684d164e2cc", size = 4959356, upload-time = "2026-09-30T14:44:48.211Z" }, + { url = "https://files.pythonhosted.org/packages/92/20/9ded6d51ddd9897f6b6e81fb9ebea7951d7cc5d6c890b0ed8abf77a51a80/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_ppc64le.whl", hash = "sha256:b13478603dcd0a2479ff8e87e2c19a7d525734686fe3c49542472293a204212d", size = 5548822, upload-time = "2026-09-30T14:44:50.86Z" }, + { url = "https://files.pythonhosted.org/packages/02/a8/8df951850d6b31d2a00218f19e2b3f999523437ed7a819df7fa427942fca/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_28_x86_64.whl", hash = "sha256:58a0c478eeca76fe5e07993c5a0703def34a6dc6a0cda4f5564639b33112ffe7", size = 5001199, upload-time = "2026-09-30T14:44:53.379Z" }, + { url = "https://files.pythonhosted.org/packages/8b/f9/36b3022218ce75b7cdf068fb95f809f9bd0d820e4955ef43b90c255cc7ac/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_31_armv7l.whl", hash = "sha256:d38cdff612d06fa6a32840d5e1b1f7a27cee4a349aa9085d94a67789d6bfd408", size = 4629333, upload-time = "2026-09-30T14:44:55.635Z" }, + { url = "https://files.pythonhosted.org/packages/8c/72/20f99a219f6af47cdd1cbd978c243b92d71496e168a746138af44ded4f29/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_aarch64.whl", hash = "sha256:fdd28f912fccfec1846a94e2e1e8f9b0012f557f0c46fe4f3eb0d7a87afcf90b", size = 4958822, upload-time = "2026-09-30T14:44:59.639Z" }, + { url = "https://files.pythonhosted.org/packages/f2/20/196f112617fb08eb4d608a2a6c422373d46f9cc2857f38fc0667033c0899/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_ppc64le.whl", hash = "sha256:cbc8738fd8526d80f35cb3a40d41f41a2e7030bb3b18b09a6778ef63d291c2fd", size = 5506351, upload-time = "2026-09-30T14:45:02.267Z" }, + { url = "https://files.pythonhosted.org/packages/24/95/83378121ef3eaaaf71d4b781577ff794acb39b9e1b87a3f156898c8497ed/cryptography-50.0.2-cp315-abi3.abi3t-manylinux_2_34_x86_64.whl", hash = "sha256:e105ab60406787da31fccc883fc0f733af1efd78f0136a4599692c4083a73d0c", size = 5000859, upload-time = "2026-09-30T14:45:05.009Z" }, + { url = "https://files.pythonhosted.org/packages/22/f7/70fd7ae4d1dbfa7ba29b02e1b9068771519a86027756510b700ce81086a8/cryptography-50.0.2-cp315-abi3.abi3t-musllinux_1_2_aarch64.whl", hash = "sha256:6f8700550aa1474a91e5dc07049c46f98b423b5b1ddd0483e0b51362eeeaf5be", size = 5092151, upload-time = "2026-09-30T15:29:15.932Z" }, + { url = "https://files.pythonhosted.org/packages/d4/be/688367b74de86984bd58d8efacfc7c9e68b89a6a22ced0fb4f38db50254a/cryptography-50.0.2-cp315-abi3.abi3t-musllinux_1_2_x86_64.whl", hash = "sha256:c71be1cbfa5cd9a41ee452acf1eccd82b2c05950358b106ec8ceb83411d1a020", size = 5286120, upload-time = "2026-09-30T15:29:18.309Z" }, + { url = "https://files.pythonhosted.org/packages/39/d1/55f8a3f2ef5d1529e16835ef10cf0fe3d559ce237b46dddc440c0bba3649/cryptography-50.0.2-cp315-abi3.abi3t-win_amd64.whl", hash = "sha256:c423ab384a46c4dff7217b2ea5ba2e11cffdeab6441acd04cf65a369caf0366c", size = 4111557, upload-time = "2026-09-30T15:29:20.155Z" }, + { url = "https://files.pythonhosted.org/packages/23/ad/ac987755d00e1e64273760228d2635ae38dae2be83e3c6e0d3289d91dec3/cryptography-50.0.2-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:0ec5f09541743261e66e291b4a0cbf0fb2997aeaab6d9e9c740b9dba1b58d1c2", size = 3943588, upload-time = "2026-09-30T15:29:22.265Z" }, + { url = "https://files.pythonhosted.org/packages/d5/8d/6d585339bedf85d45044c85d8412dac53f2bb6f918e8b7777efba1787844/cryptography-50.0.2-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:c5e67125c7dca78d199ec4e116aa93dbb83494808ecbb8211a2cb09b1bf41dbd", size = 4756166, upload-time = "2026-09-30T15:29:24.58Z" }, + { url = "https://files.pythonhosted.org/packages/bf/f1/1c1f6874e8550cfddd4b688ceb38cefb6ed15ceed224d56f133f3d88c214/cryptography-50.0.2-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ee247f5c245c9a2fe7c8e2214e295918838e44e00a45a6718451e4004219e767", size = 4749145, upload-time = "2026-09-30T15:29:26.807Z" }, + { url = "https://files.pythonhosted.org/packages/c1/63/61b15dc1a8de03fe0adbe3fd7608b3ad5c73bf50993bbcb1faaa930afe33/cryptography-50.0.2-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:dfe9763530994147d9af1def057a5b9658b00e8f8fe8743d144d1e0911c2e454", size = 4763638, upload-time = "2026-09-30T15:29:28.588Z" }, + { url = "https://files.pythonhosted.org/packages/fc/35/b345bdfa40c9126df1a9d33236aa98418367931b8725f84fc3ae2b98dc59/cryptography-50.0.2-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:58ddb5a8e3179d12f19e4ea34d2d32e9d63a4baa142c875c1eb59f41b7243acd", size = 5382217, upload-time = "2026-09-30T15:29:30.589Z" }, + { url = "https://files.pythonhosted.org/packages/4f/87/ef344a9e616871f2519c22d6afcda79ddd5d35e9592d95eb6e677608d055/cryptography-50.0.2-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:f21e8a22c8605750c7af886bab299a363721264061b4ac0a30efb73cfd58efc5", size = 4781387, upload-time = "2026-09-30T15:29:32.605Z" }, + { url = "https://files.pythonhosted.org/packages/90/5b/f2fdb13cd0b96f6f932c8627bb292a45f11c64d21620a8e120aee9a3b848/cryptography-50.0.2-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:9c8402a82ea0dc4ceeab793db05f0fafa8ca139ca34fcde5df0f596103c74107", size = 4403790, upload-time = "2026-09-30T15:29:34.374Z" }, + { url = "https://files.pythonhosted.org/packages/bc/ce/7e4f662b1e3c393513569e402cfc85ac7da0bd3d5435e122a3140219eb2d/cryptography-50.0.2-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:0ddc924c04591c2811ca024d62ecad4f7f6f08af8939c211438f48a16bd23602", size = 4764319, upload-time = "2026-09-30T15:29:36.149Z" }, + { url = "https://files.pythonhosted.org/packages/3c/3f/86ff33ce34cc0de6847fb96e035a1a760d81652e38643f617c02ad32ef7a/cryptography-50.0.2-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:a6557e5f38e065ca9fbdaf7cfc7435ecb1d113aa81a022d1b51921ee7432e227", size = 5338560, upload-time = "2026-09-30T15:29:39.053Z" }, + { url = "https://files.pythonhosted.org/packages/40/cf/6b5c8e2fd9202d98988ab7cb5cc5c991704c4ad55f492ff408e4969f83f1/cryptography-50.0.2-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:1981f1db4630889b9ef7803fadef12b056f428cb6b85c27ba57b774793b6093c", size = 4780973, upload-time = "2026-09-30T15:29:41.251Z" }, + { url = "https://files.pythonhosted.org/packages/10/bf/8d6ebc7dded797bd0f0160d52188021211f011a2b164ef0ae1dac4587465/cryptography-50.0.2-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:7a8701d6b584d76e909e3d305b7d126b41439876a5aaf76cddc67fc230eafa2e", size = 4897738, upload-time = "2026-09-30T15:29:43.106Z" }, + { url = "https://files.pythonhosted.org/packages/d4/aa/f3f6e0de7e6253b8baa8b2d8fb9d50924fa75cee3d4624bd4bc1208ee923/cryptography-50.0.2-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:ce47f66801c20ec6c6632453bb5960fe38939e9306970b48b3a5a26de7745d94", size = 5058280, upload-time = "2026-09-30T15:29:44.827Z" }, + { url = "https://files.pythonhosted.org/packages/f6/b6/a1faf3a27ae9405fb34b1713cc73b2d8a26b04d5c561578fa2e6ef3e5bb9/cryptography-50.0.2-cp39-abi3-win_amd64.whl", hash = "sha256:4e81d95e5bafc2d6e34e4bed780e53e4d5b9a2f928573428aa4d35fbec1eb0de", size = 3854095, upload-time = "2026-09-30T15:29:46.782Z" }, +] + [[package]] name = "detect-installer" version = "0.1.0" @@ -573,6 +562,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/6b/fd/5390ec4f49100f3ecb9968a392f9e6d039f1e3fe0ecd28443716ff01e589/fastar-0.11.0-cp314-cp314t-win_arm64.whl", hash = "sha256:76c1359314355eafbc6989f20fb1ad565a3d10200117923b9da765a17e2f6f11", size = 461049, upload-time = "2026-04-13T17:11:25.918Z" }, ] +[[package]] +name = "flupy" +version = "1.2.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/8c/02/ae02db7bc35b395eec6ac36069a49ef4324be5bd8e034e6d66c7fac4d17a/flupy-1.2.5.tar.gz", hash = "sha256:0b984f56f010f399b5f7e7b92b9af285d2058e2239849bb516e5dcb2ccd746e6", size = 86069, upload-time = "2026-10-07T00:31:52.041Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/99/9f/58fbfd344e4a1e33929d67cfc61567a6cb55e26bc5c4a56c76fdcdd1c1da/flupy-1.2.5-py3-none-any.whl", hash = "sha256:9830dac2b8b336c9d4e35cd5648b367a31939d13e587b4f310db8db89ea8e18c", size = 12854, upload-time = "2026-10-07T00:31:53.25Z" }, +] + [[package]] name = "greenlet" version = "3.5.2" @@ -634,6 +632,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" }, ] +[[package]] +name = "httpcore2" +version = "2.16.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "h11" }, + { name = "truststore" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c0/61/afa9d6b7452f9eca73f73d45324eb0bb52f098fd5e6049bf6b8263be9b4e/httpcore2-2.16.0.tar.gz", hash = "sha256:c72cd0413563b17e1cd8354677dff887466f8ec2551679759e93126534428643", size = 69886, upload-time = "2026-10-21T07:09:45.31Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/af/c2/ce417c397afa5181f0e3c6ff01a4d01639414e1adef08730d97571297151/httpcore2-2.16.0-py3-none-any.whl", hash = "sha256:5c4358319f2602d984ad93182c9fee5160f22e9da7babdda870a5e7c4e2dc34f", size = 85070, upload-time = "2026-10-21T07:09:42.802Z" }, +] + [[package]] name = "httptools" version = "0.8.0" @@ -671,6 +682,31 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/2a/39/e50c7c3a983047577ee07d2a9e53faf5a69493943ec3f6a384bdc792deb2/httpx-0.28.1-py3-none-any.whl", hash = "sha256:d909fcccc110f8c7faf814ca82a9a4d816bc5a6dbfea25d6591d6985b8ba59ad", size = 73517, upload-time = "2024-12-06T15:37:21.509Z" }, ] +[[package]] +name = "httpx2" +version = "2.16.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "anyio", marker = "sys_platform != 'emscripten'" }, + { name = "httpcore2", marker = "sys_platform != 'emscripten'" }, + { name = "httpx2-jsfetch", marker = "sys_platform == 'emscripten'" }, + { name = "idna" }, + { name = "truststore", marker = "sys_platform != 'emscripten'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/43/73/5ca2cedf5e4e50423d1c258877865a6b62793633b561c58499f8aeb33b7e/httpx2-2.16.0.tar.gz", hash = "sha256:0d54c98128e8f2ff7fbbde0fca8c359e5f032edeaaaac443cdb7f31f685bcd7f", size = 103116, upload-time = "2026-10-21T07:09:46.348Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7b/3d/2e4bc4fd1ef9770871669adb348d612a6e4786b303a23f9935b81c48dd60/httpx2-2.16.0-py3-none-any.whl", hash = "sha256:fd2c5d7909e8d86fe92d53020c310ca0e4e431b838c207c5754b9bbf0308d49a", size = 97880, upload-time = "2026-10-21T07:09:44.01Z" }, +] + +[[package]] +name = "httpx2-jsfetch" +version = "1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/cd/c4/0e5636363151a2a1795e0a77617168b9ca438e1748ec05fc9b5687f93d64/httpx2_jsfetch-1.0.tar.gz", hash = "sha256:70a0e3eabfef7cce5ad9c629f7d01ca05e418f586646f4ddf14782e4c1454c60", size = 6872, upload-time = "2026-08-07T00:13:07.492Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9b/43/832f631d32e4f1211caa2ba368317739fe71f0b8530e4c9d15dc454bac2a/httpx2_jsfetch-1.0-py3-none-any.whl", hash = "sha256:cb916b707601e69a07721aabc8f3f6659be3a6893bc1ff5c6f9e02241df2da32", size = 6382, upload-time = "2026-08-07T00:13:06.567Z" }, +] + [[package]] name = "idna" version = "3.18" @@ -894,6 +930,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/df/b2/87e62e8c3e2f4b32e5fe99e0b86d576da1312593b39f47d8ceef365e95ed/packaging-26.2-py3-none-any.whl", hash = "sha256:5fc45236b9446107ff2415ce77c807cee2862cb6fac22b8a73826d0693b0980e", size = 100195, upload-time = "2026-04-24T20:15:22.081Z" }, ] +[[package]] +name = "parse" +version = "1.22.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9e/0f/4bada23d2848aaa61f3577181dbd83895fa49fb9beb406835ed7eaca1b96/parse-1.22.4.tar.gz", hash = "sha256:706d458feed5a81b02768d3156e8070baf6cee7d150a3a3c0cd43101a875c3b5", size = 40279, upload-time = "2026-10-20T21:16:07.702Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/8f/5f/fbe039e06108eefad9e6b1f7d915a9c73ca0451700c7d48ce05eaa3a2833/parse-1.22.4-py2.py3-none-any.whl", hash = "sha256:ae430a4477316eed4a9710f642b2db968ec89d5d82e6b0908b8169673b476847", size = 21919, upload-time = "2026-10-20T21:16:06.547Z" }, +] + [[package]] name = "pathspec" version = "1.1.1" @@ -903,6 +948,50 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f1/d9/7fb5aa316bc299258e68c73ba3bddbc499654a07f151cba08f6153988714/pathspec-1.1.1-py3-none-any.whl", hash = "sha256:a00ce642f577bf7f473932318056212bc4f8bfdf53128c78bbd5af0b9b20b189", size = 57328, upload-time = "2026-04-27T01:46:07.06Z" }, ] +[[package]] +name = "pglast" +version = "8.7" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7c/89/6e1ea9afed453506d458d4f37812644af5f5fe08347af59ca44991541068/pglast-8.7.tar.gz", hash = "sha256:7729abdc12a9949c8cc96e5cae0ba353943d3f12b0c17b09a049572bfa206e15", size = 3853324, upload-time = "2026-10-18T12:45:53.744Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d2/aa/cb1c01bbdd2a1644efdf4465d72f200402b5dab4bf76669878f6752cc981/pglast-8.7-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:bcee58ae3ee87b9372da7c5568178232cc75023f27d8c922372426450707b281", size = 1783670, upload-time = "2026-10-18T13:18:51.175Z" }, + { url = "https://files.pythonhosted.org/packages/a3/a7/5c783897615d4ce9401402990e082e40bb8728bd42f81d7e00d92e2d7c46/pglast-8.7-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:bfcf70429139d7ab34e00c0ab88227fe544a14e9fbd262cfc003b611a38472e5", size = 1706096, upload-time = "2026-10-18T13:18:52.308Z" }, + { url = "https://files.pythonhosted.org/packages/49/85/e137b52fed41cd51a2dd55409f07ff0ce209518da61a913ca75ee671f717/pglast-8.7-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d28dc7b364ad30afa4a60b61b9c92d93830c1f9f932f15649cd64d2ddce67bf4", size = 7758335, upload-time = "2026-10-18T13:18:53.526Z" }, + { url = "https://files.pythonhosted.org/packages/f9/5c/750042c8967e51e3c944bb9759e72ab3f57e5b2c5d421d05da34aa2c6b94/pglast-8.7-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3dcb2684735037e552c3c6da624a310bdea04216076399b50d293391e5b84783", size = 8007547, upload-time = "2026-10-18T13:18:55.008Z" }, + { url = "https://files.pythonhosted.org/packages/ed/7a/49ffda8f0475bbd94872c635c657ddfaf45df8e58b04f82fe470abb1c75a/pglast-8.7-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:7655411c6b6baff0e5921ef83692f9f793213c0912e67fded55161f1df5ddf95", size = 7517508, upload-time = "2026-10-18T13:18:57.101Z" }, + { url = "https://files.pythonhosted.org/packages/5e/dd/e70b5050eee9dbb7375b94d11f9c35a53b1bf415df6f8a4865f1e7cf4c36/pglast-8.7-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:96ea835dc917709bbb9e44485916acfe970201a10d66c22647ea50266bc6e92a", size = 7784249, upload-time = "2026-10-18T13:18:58.638Z" }, + { url = "https://files.pythonhosted.org/packages/80/e4/865ca30da2209df3bd025a45ea34d18a158a6f3e2e4a4e2d1e8bd998ca0e/pglast-8.7-cp314-cp314-win32.whl", hash = "sha256:b23a48cb6864d50675f80f053a1a0728e11a97f554cab1c044b95edbaf2274f5", size = 1498505, upload-time = "2026-10-18T13:19:00.187Z" }, + { url = "https://files.pythonhosted.org/packages/ad/20/4482ed6698f4b92e35cc409000160ed56c7967240a4f6cf2679b8d037525/pglast-8.7-cp314-cp314-win_amd64.whl", hash = "sha256:fccddc3c69d57f8941201c8ebd3710d54987f38c4ca540007420208913e270ac", size = 1645190, upload-time = "2026-10-18T14:23:27.615Z" }, + { url = "https://files.pythonhosted.org/packages/08/07/9f6ff1b85690724ad24271985e3048b6ec4363bb7c3a855b683b2ee9652e/pglast-8.7-cp314-cp314-win_arm64.whl", hash = "sha256:37dba5d5fdd48c8b2baac80331d03aef772adf8bd087c912485c2ba4428bbca7", size = 1500714, upload-time = "2026-10-18T14:23:28.896Z" }, + { url = "https://files.pythonhosted.org/packages/a5/e5/6887010a82b991a72ca068f28ba6d074b9c3f031e4370694aae467214c2a/pglast-8.7-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:fd4a2f1619feacdc9799b1d3ee99710499dd3f8dd71dab470fabdd0dd06d808b", size = 1832653, upload-time = "2026-10-18T14:23:30.424Z" }, + { url = "https://files.pythonhosted.org/packages/1a/47/68a5afc233439f0d859be309078392ff465e87d44ea4757540510398030b/pglast-8.7-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:1542458c0bf1f7567e39d2a4ea480140ed0814933196a5b99d5872e0355c4c25", size = 1749778, upload-time = "2026-10-18T14:23:31.902Z" }, + { url = "https://files.pythonhosted.org/packages/93/51/ee0483aa57f8ae6cc5b25d6d2f2ffb9f95703bec61039f21ef7c65fb6a34/pglast-8.7-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:047bf080e078bc66dfc8ef0ef8db694fa55414655988d479a7867e6326a54574", size = 8206217, upload-time = "2026-10-18T14:23:33.261Z" }, + { url = "https://files.pythonhosted.org/packages/2d/cb/d30746ed76b9af03184da7d72231faa3312f03f33ead696948c077d18ed9/pglast-8.7-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:26adfcb78faa1b43dd1b6871d77eed1e184252b7a8c5699ad4afb24591ab0045", size = 8378884, upload-time = "2026-10-18T14:23:34.907Z" }, + { url = "https://files.pythonhosted.org/packages/5c/05/7714f6d9e2669d62f8e59e25fe133088fe780da57ad4e85cdfc6b3eb766e/pglast-8.7-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:2a2bf49255dd533ffe82be168445428dd6949aaf4d5b810f93eeee89919172ae", size = 7876258, upload-time = "2026-10-18T14:23:36.413Z" }, + { url = "https://files.pythonhosted.org/packages/be/20/3bbbca4d7b07dbc40586855572d5c9fd7fed1d6a77e7eab759e1fd69230f/pglast-8.7-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:6fb285efd086202b8ab77ab835d7badf4b9e4dbda8ff08355faa17f72cbeb7d2", size = 8116736, upload-time = "2026-10-18T14:23:37.967Z" }, + { url = "https://files.pythonhosted.org/packages/2e/d4/80384d9029ad56d1f620ff3b2b8cb7e755b9ff993dfad91128659f2a7ac9/pglast-8.7-cp314-cp314t-win32.whl", hash = "sha256:5f388f943f81f712d196d5fbb6c0297ea9ba6996ceb74675b0c837f19a1e53a0", size = 1574035, upload-time = "2026-10-18T14:23:39.373Z" }, + { url = "https://files.pythonhosted.org/packages/6a/c7/b53a6df80370aba0ef70bdd3cbedb7c538d4ccc61fe138ee1417408033af/pglast-8.7-cp314-cp314t-win_amd64.whl", hash = "sha256:65bfd36c4b6b4f6d4269c3e392d3304a4dea718dcfaf1fa20e88b993e4f8ba14", size = 1729183, upload-time = "2026-10-18T14:23:40.712Z" }, + { url = "https://files.pythonhosted.org/packages/12/ae/707b1ca8f3577c019fcedf01f7c7c9d6099803a64d48049378aa08103311/pglast-8.7-cp314-cp314t-win_arm64.whl", hash = "sha256:c3ea28ade91d20ea9ad8695a1e8aeb2d1aa90e9217fee7532fd24b97a5e0b22a", size = 1528998, upload-time = "2026-10-18T14:23:41.772Z" }, + { url = "https://files.pythonhosted.org/packages/2e/e9/77be1fbb79b9b9b70fb18499df09a66cd9a5b5ad93e871b33f9b6192834c/pglast-8.7-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:bd41793e7cb955fa0982c9fd74078a06b8d5f3ccf59ed7368a33ee3bdd566d43", size = 1783505, upload-time = "2026-10-18T14:23:42.96Z" }, + { url = "https://files.pythonhosted.org/packages/41/6b/549a615b2e76c058ccebcd798a4666efa1ed7490e8cb1ea72a025593b297/pglast-8.7-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:a916cf71961b12c47d0987fec6765f3cd1699260153309bb63923d7b2186a7a9", size = 1705895, upload-time = "2026-10-18T14:23:44.476Z" }, + { url = "https://files.pythonhosted.org/packages/6b/6f/73bc32106c8ea9fd14e4cf7039627bb2dbba1dc91ee027f6b91a0c6cdee6/pglast-8.7-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7805828ed9d0978c4e55031045b19041449775da9e3b2ebb64e6a7428ead3773", size = 7757017, upload-time = "2026-10-18T14:23:45.748Z" }, + { url = "https://files.pythonhosted.org/packages/77/e8/8270f155860e19d43e3c39b77c2a7e281982dea7d4e520b0cd2d7bb8a2c3/pglast-8.7-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e4bec7e3c3bf264783ae2c306f13da877f7554609f8a43cfc7772a6817d73b36", size = 8030647, upload-time = "2026-10-18T14:23:47.156Z" }, + { url = "https://files.pythonhosted.org/packages/07/47/126398d642b197c9eb6f20cc98bff1c303a88299262a66f7f188b09fb9a8/pglast-8.7-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:e4478a923e668963980accbfba9cf127eb54f35fe1c63e47f9ec844898cb549e", size = 7515997, upload-time = "2026-10-18T14:23:48.854Z" }, + { url = "https://files.pythonhosted.org/packages/ae/77/d3fab9f294f71ca52fe6ff1a8762651c829fbeb5751c0d654adec9247e0f/pglast-8.7-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:6c206596d07d0babd7a4065e74ea9373b9df3f1a77986b6949a5b7628dda82a0", size = 7804257, upload-time = "2026-10-18T14:23:50.255Z" }, + { url = "https://files.pythonhosted.org/packages/07/00/364a6c34224a17e2c820d7e8f84d2fad6dfcb5e475890593f9bea1c116e7/pglast-8.7-cp315-cp315-win32.whl", hash = "sha256:4cca70274e26c23f3394a267d9c635f386da0a26de21b4b4f7f41dee68953ed1", size = 1498311, upload-time = "2026-10-18T14:23:51.648Z" }, + { url = "https://files.pythonhosted.org/packages/89/2b/63c40b9391609f68d8a4f8beeff0f6d701505fdf120ca1b41cba6e2c688e/pglast-8.7-cp315-cp315-win_amd64.whl", hash = "sha256:0ad747abcea86d4810121a160449c73fe7c8138208709949645c705b74bd7f6c", size = 1644805, upload-time = "2026-10-18T14:23:52.851Z" }, + { url = "https://files.pythonhosted.org/packages/70/09/e5ff0d467ba3581da7c58c103e524907b92834b1db0bda983135a2f10cf5/pglast-8.7-cp315-cp315-win_arm64.whl", hash = "sha256:d3ed19808f91e6469592797c88f20bc0b6a189b5ed21c8b06d415eaf13ea336f", size = 1500839, upload-time = "2026-10-18T14:23:54.305Z" }, + { url = "https://files.pythonhosted.org/packages/ad/14/2b00cce28a2f7b2efaeb9202d81087add0bd7dde0df1d814b744f854ded0/pglast-8.7-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:5e77b482cfe45867d47dab4f14d55f642b0b24b0f936e432eaf663a69d6b1af9", size = 1831870, upload-time = "2026-10-18T14:23:55.514Z" }, + { url = "https://files.pythonhosted.org/packages/59/dd/1f31c26c55ba3f8065e13bb51f97bd058b1f6d83341c5a030b5e3b405aab/pglast-8.7-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:6fb9187410cdb50f7141ec463458c234e5cf9d1e7082deda1634e4ef568f5a81", size = 1749833, upload-time = "2026-10-18T14:23:56.983Z" }, + { url = "https://files.pythonhosted.org/packages/22/91/eea66ea6c00ddddb6d80f189cc80c2abf6475aa83875883117873a49f9d5/pglast-8.7-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e2d39e179277ebb8fc250961631f37594d6f6fd733ceeb7b0f1c6083a1a95b82", size = 8202827, upload-time = "2026-10-18T14:23:58.464Z" }, + { url = "https://files.pythonhosted.org/packages/64/db/d0c78182c02c1b8d5d6e37a52ab08eefd946945af751f254660f506591f9/pglast-8.7-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:94c22e23a3829681c170d1bf9ae915206dcb15fbf3bae5b59aa4e5fec5c8d7f9", size = 8390683, upload-time = "2026-10-18T14:24:00.092Z" }, + { url = "https://files.pythonhosted.org/packages/58/a5/bb29a2b55ae30f218a00a6dcb7e5a678cc0d71a70479cff81e2e4f6de02a/pglast-8.7-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:9ab977d951b22ae740643b5d988e76cb405d83850aa67b9f7d6a9ad83f393fff", size = 7875437, upload-time = "2026-10-18T14:24:01.722Z" }, + { url = "https://files.pythonhosted.org/packages/0f/20/c0e19ba92f0e548b270a4dcece2bb0c875d1254818d1a36735a8e097132c/pglast-8.7-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:31ab45535df85411abebd01bbc1d119b1f5cefa323e145a7800ce99c3893ed64", size = 8130778, upload-time = "2026-10-18T14:24:03.131Z" }, + { url = "https://files.pythonhosted.org/packages/ee/0e/c19ff63b9af9a8a65d066e6976edcad38c8dcd4dddd8817e4fc4a292c6b2/pglast-8.7-cp315-cp315t-win32.whl", hash = "sha256:6e66e8539e8bc2a37db0e382474bca3b8674083a7e2e9d704cec287e3d65ba14", size = 1572987, upload-time = "2026-10-18T14:24:04.342Z" }, + { url = "https://files.pythonhosted.org/packages/9c/90/17a39ac90e48d8a65e6b6a93de4b2316069e056bc2bfb1804c8f33d0ee6d/pglast-8.7-cp315-cp315t-win_amd64.whl", hash = "sha256:299aaaabe9360a96d07915407214ed8072698bae694c92f7a96f484e25df8e6d", size = 1728539, upload-time = "2026-10-18T14:24:05.488Z" }, + { url = "https://files.pythonhosted.org/packages/c0/40/4bc7eee31295183b5b092f294be82843e4bc78a6d28d319af358eaf8f87b/pglast-8.7-cp315-cp315t-win_arm64.whl", hash = "sha256:cd9822c95ee9e2b0f15dd1461aca95c6e68591e98f4c1c0ca1e36c1309508065", size = 1528367, upload-time = "2026-10-18T14:24:06.818Z" }, +] + [[package]] name = "pluggy" version = "1.6.0" @@ -983,23 +1072,6 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/95/81/314320aeffd88dadeac553ff9eb10f54507ab41deccd0c69f6221d254a0a/puremagic-2.2.0-py3-none-any.whl", hash = "sha256:c4f7ed7307f056c787199acfda839555921be1df13abba61e8e6db0c787ae1d0", size = 71971, upload-time = "2026-04-08T01:39:54.169Z" }, ] -[[package]] -name = "pwdlib" -version = "0.3.1" -source = { registry = "https://pypi.org/simple" } -sdist = { url = "https://files.pythonhosted.org/packages/78/a6/644f28a21cb68920d06b264e72b864ac9bff2377f4757dd4648b5110b3ad/pwdlib-0.3.1.tar.gz", hash = "sha256:2ffd1955c92190d5bfbdc5071bf7d422568b83f943453ebd3d43d031ccba37b1", size = 216951, upload-time = "2026-08-12T08:38:38.383Z" } -wheels = [ - { url = "https://files.pythonhosted.org/packages/6b/2e/51979293b2337f508597d13ee20db1ac1d43e48086b2ed7de6da213ed46b/pwdlib-0.3.1-py3-none-any.whl", hash = "sha256:944fa439198bed8ac3ea63dac76ea4ae43e2a35f4f21e9e725e82d3c2b97d6a5", size = 9272, upload-time = "2026-08-12T08:38:37.483Z" }, -] - -[package.optional-dependencies] -argon2 = [ - { name = "argon2-cffi" }, -] -bcrypt = [ - { name = "bcrypt" }, -] - [[package]] name = "pycparser" version = "3.0" @@ -1115,6 +1187,11 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e8/55/40e45bf052ee8ee12a4dfd785519660f8effa7b065442b91646ec6828619/pyjwt-2.15.0-py3-none-any.whl", hash = "sha256:7a3742debf6b879e912dbb9819ceec1594be812452b78c5f2e2dfc56564954f8", size = 33680, upload-time = "2026-09-23T16:55:59.241Z" }, ] +[package.optional-dependencies] +crypto = [ + { name = "cryptography" }, +] + [[package]] name = "pytest" version = "9.1.1" @@ -1379,6 +1456,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/ec/bb/2799cc2ede3ed41131f8975621e7213dfc7ef4acbbaadfa440f32500c370/starlette-1.3.1-py3-none-any.whl", hash = "sha256:c7372aae11c3c3f26a42df7bd626cec2f47d03483d261d369516a615a53714c6", size = 73632, upload-time = "2026-06-12T09:23:10.017Z" }, ] +[[package]] +name = "truststore" +version = "0.10.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ee/9f/c5201d42a484c061e528825fc8e2d565f5abd50a4ced6fb7d29c4ec99b2b/truststore-0.10.5.tar.gz", hash = "sha256:30d36967ccaded5cbb38d602c433f53600036c79d502f4533a49b60a03bbefcd", size = 28091, upload-time = "2026-10-12T22:27:31.808Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/51/e9/3a7820be2bb0fe53b6bc9c3be26d3d1158004e4c3ab953aa6840b955b1e9/truststore-0.10.5-py3-none-any.whl", hash = "sha256:9aaaedaefaf06d8b206278cf8b5012bc897f485a874503501e12d776df78951c", size = 19017, upload-time = "2026-10-12T22:27:30.377Z" }, +] + [[package]] name = "ty" version = "0.0.84" From bac012f1b820c8f94104dc5cd31f2de98ae00ad1 Mon Sep 17 00:00:00 2001 From: Daniel Lynch Date: Sun, 8 Nov 2026 00:56:40 -0500 Subject: [PATCH 2/5] fix(codegen): invoke native SDK on ignored OpenAPI input --- frontend/README.md | 27 ++++++++++++--------------- frontend/package.json | 2 +- 2 files changed, 13 insertions(+), 16 deletions(-) diff --git a/frontend/README.md b/frontend/README.md index f82a0d9ec1..d84b0f28ed 100644 --- a/frontend/README.md +++ b/frontend/README.md @@ -43,31 +43,28 @@ Done, you now have an API-only app. 🤓 ## Generate Client -### Automatically - -- From the project root, run the script: +From the application root, use the declared backend environment and provisioned +frozen uv/Bun profiles: ```bash bash ./scripts/generate-client.sh ``` -- Commit the changes. - -### Manually - -- Make sure the backend is running. +The script exports FastAPI's native OpenAPI document, then invokes `openapi-ts`. +The intermediate `frontend/openapi.json` is gitignored SDK input, not an authored +source file. Generation does not run the source formatter against ignored input +or start a backend service. Commit the generated `src/client` changes with their +backend contract inputs. -- Download the OpenAPI JSON file from `http://localhost:8000/api/v1/openapi.json` and copy it to a new file `openapi.json` at the root of the `frontend` directory. - -- To generate the frontend client, run: +Regenerate whenever backend changes affect the OpenAPI schema. Check frontend +sources without rewriting them from the application root: ```bash -bun run generate-client +bun run --filter frontend check ``` -- Commit the changes. - -Regenerate the client whenever backend changes affect the OpenAPI schema. +The check runs in the frontend workspace and honors native Git ignore rules, so +Playwright's runtime artifacts are not treated as authored sources. ## Using a Remote API diff --git a/frontend/package.json b/frontend/package.json index 0d6cbff1a9..d3d1481468 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -8,7 +8,7 @@ "build": "tsc -p tsconfig.build.json && vite build", "lint": "biome check --write --unsafe --no-errors-on-unmatched --files-ignore-unknown=true ./", "preview": "vite preview", - "generate-client": "biome format --write openapi.json && openapi-ts", + "generate-client": "openapi-ts", "test": "bunx playwright test", "test:ui": "bunx playwright test --ui", "check": "biome check --no-errors-on-unmatched --files-ignore-unknown=true ./" From 2906032462e3edd8ca951fb2e7d61d10f756327f Mon Sep 17 00:00:00 2001 From: Daniel Lynch Date: Sun, 8 Nov 2026 01:23:15 -0500 Subject: [PATCH 3/5] fix(ci): preserve secure browser context for AuthKit PKCE --- .github/workflows/playwright.yml | 2 +- compose.override.yml | 16 +++++++++------- development.md | 21 +++++++++++++++++++-- frontend/Dockerfile.playwright | 2 +- 4 files changed, 30 insertions(+), 11 deletions(-) diff --git a/.github/workflows/playwright.yml b/.github/workflows/playwright.yml index 66c38cb97e..52ab4358fc 100644 --- a/.github/workflows/playwright.yml +++ b/.github/workflows/playwright.yml @@ -48,7 +48,7 @@ jobs: env: # Browser network fixtures are not backend JWT/RLS or live WorkOS proof. PROJECT_NAME: API browser fixture - FRONTEND_HOST: http://backend:8000 + FRONTEND_HOST: http://localhost:8000 FASTAPI_ENV: development WORKOS_CLIENT_ID: client_fixture WORKOS_ISSUER: https://auth.fixture.test/ diff --git a/compose.override.yml b/compose.override.yml index 009e0dce04..3a51a56536 100644 --- a/compose.override.yml +++ b/compose.override.yml @@ -73,18 +73,20 @@ services: args: - NODE_ENV=production ipc: host + # Native service networking makes the backend's loopback a browser secure + # context for AuthKit PKCE, without relaxing Chromium security. + # provenance: https://github.com/compose-spec/compose-spec/blob/3a4a6995e4a971f6173dff9130cb3e38e6738651/05-services.md + network_mode: service:backend depends_on: - - backend - - mailpit + backend: + condition: service_healthy + mailpit: + condition: service_started environment: - - PLAYWRIGHT_BASE_URL=http://backend:8000 - - VITE_API_URL=http://backend:8000 - - MAILPIT_HOST=http://mailpit:8025 + - PLAYWRIGHT_BASE_URL=${FRONTEND_HOST:?Explicit browser origin is required} # For the reports when run locally - PLAYWRIGHT_HTML_HOST=0.0.0.0 - CI=${CI:-} volumes: - ./frontend/blob-report:/app/frontend/blob-report - ./frontend/test-results:/app/frontend/test-results - ports: - - 9323:9323 diff --git a/development.md b/development.md index 0839918e95..c0c784cc96 100644 --- a/development.md +++ b/development.md @@ -78,6 +78,23 @@ Stop a locally running FastAPI server before starting the Compose backend becaus **Note**: The first time you start the stack, it might take a minute for all the services to be ready. To monitor it, use `docker compose logs`, or `docker compose logs backend` for the backend service. +### Browser fixtures in Compose + +Set `FRONTEND_HOST` to the built backend's loopback origin before running: + +```bash +docker compose run --rm playwright bunx playwright test +``` + +The Playwright container shares the backend's native network namespace and +waits for its liveness check. The browser origin comes from `FRONTEND_HOST`. +Plain HTTP service hostnames are not browser secure contexts: AuthKit's PKCE +flow requires Web Crypto, so use trusted loopback locally and HTTPS in +production. Do not disable browser security to make an insecure origin pass. +Browser fixtures do not establish live provider or SQL authorization. +Inspect generated HTML reports with the native Playwright CLI on the host; +the shared-network test container does not publish a separate report port. + ## Mailpit [Mailpit](https://mailpit.axllent.org) captures emails sent during local development instead of delivering them. The local backend connects to it at `localhost:1025`, and the Compose backend connects to the `mailpit` service. Captured emails are available at . @@ -110,7 +127,7 @@ Do not store deployment secrets in `.env`. Configure them as described in the [F ## Pre-commit Hooks and Code Linting -The project uses [prek](https://prek.j178.dev/), a modern alternative to [pre-commit](https://pre-commit.com/), for code linting and formatting. +The project uses [prek](https://prek.j178.dev/) for native check-only commit hooks. You can find a file `.pre-commit-config.yaml` with configurations at the root of the project. @@ -132,7 +149,7 @@ Now whenever you try to commit, for example with: git commit ``` -`prek` will check and format the code you are about to commit. If it modifies any files, add those files to Git again before committing. +`prek` checks the intended changes without rewriting them. Select manual formatting or SDK-generation hooks deliberately; they are not automatic commit checks. ### Run `prek` Manually diff --git a/frontend/Dockerfile.playwright b/frontend/Dockerfile.playwright index 38285101b0..94baf91504 100644 --- a/frontend/Dockerfile.playwright +++ b/frontend/Dockerfile.playwright @@ -14,6 +14,6 @@ COPY frontend/package.json /app/frontend/ WORKDIR /app/frontend -RUN bun install +RUN bun install --frozen-lockfile COPY ./frontend /app/frontend From bc396f6688ed7a5de7e8b000c11e61d25531d37c Mon Sep 17 00:00:00 2001 From: Daniel Lynch Date: Sun, 8 Nov 2026 01:59:15 -0500 Subject: [PATCH 4/5] fix(auth): align read grants and scope migration authority --- .github/workflows/deploy-docker-compose.yml | 3 +- backend/README.md | 6 ++- deployment.md | 2 +- frontend/src/routes/_layout/admin.tsx | 6 ++- frontend/src/routes/_layout/items.tsx | 5 ++- frontend/tests/admin.spec.ts | 48 +++++++++++++++++++++ frontend/tests/items.spec.ts | 43 ++++++++++++++++++ frontend/tests/utils/authkit-fixture.ts | 5 ++- 8 files changed, 110 insertions(+), 8 deletions(-) diff --git a/.github/workflows/deploy-docker-compose.yml b/.github/workflows/deploy-docker-compose.yml index c7c518753b..3a4a9a2ed4 100644 --- a/.github/workflows/deploy-docker-compose.yml +++ b/.github/workflows/deploy-docker-compose.yml @@ -27,7 +27,6 @@ jobs: WORKOS_JWKS_URL: ${{ vars.WORKOS_JWKS_URL }} WORKOS_API_HOSTNAME: ${{ vars.WORKOS_API_HOSTNAME }} DATABASE_URL: ${{ secrets.DATABASE_URL }} - API_MIGRATION_DATABASE_URL: ${{ secrets.API_MIGRATION_DATABASE_URL }} SMTP_HOST: ${{ vars.SMTP_HOST }} SMTP_USER: ${{ vars.SMTP_USER }} SMTP_PASSWORD: ${{ secrets.SMTP_PASSWORD }} @@ -41,6 +40,8 @@ jobs: - name: Build run: docker compose -f compose.yml -f compose.deploy.yml build - name: Prepare database + env: + API_MIGRATION_DATABASE_URL: ${{ secrets.API_MIGRATION_DATABASE_URL }} run: docker compose -f compose.yml -f compose.deploy.yml run --rm migrate - name: Start application run: docker compose -f compose.yml -f compose.deploy.yml up -d diff --git a/backend/README.md b/backend/README.md index b67b72ea88..5f44d56bfe 100644 --- a/backend/README.md +++ b/backend/README.md @@ -43,8 +43,10 @@ deny access. Email equality is never an identity link or provisioning rule. Local `User.id` remains a UUID; tenant IDs retain the canonical owner's TEXT type. Every business action requires `org:projects:read`/`org:projects:write` as -appropriate. Administrators are selected-tenant administrators, not global -operators. Ordinary users access their own items; tenant administrators can +appropriate. Write permission also grants read access in both the API and UI; +read permission alone never grants mutation access. Administrators are +selected-tenant administrators, not global operators. Ordinary users access +their own items; tenant administrators can access items in their selected tenant only. Account administration also requires explicit action permission. Profile changes cannot mutate tenant/identity/role; item changes cannot mutate tenant/owner attribution. diff --git a/deployment.md b/deployment.md index 84628532ff..489deb17df 100644 --- a/deployment.md +++ b/deployment.md @@ -43,7 +43,7 @@ Supply `API_MIGRATION_DATABASE_URL` only to the reviewed migration job. It must use an authority distinct from the runtime login. From `backend/`: ```console -uv run alembic -c alembic-api.ini upgrade api@head +uv run --no-active --locked --no-sync alembic -c alembic-api.ini upgrade api@head ``` `scripts/prestart.sh` invokes this exact branch and no seed. Without a reviewed diff --git a/frontend/src/routes/_layout/admin.tsx b/frontend/src/routes/_layout/admin.tsx index eca5e88616..acb2834f40 100644 --- a/frontend/src/routes/_layout/admin.tsx +++ b/frontend/src/routes/_layout/admin.tsx @@ -51,7 +51,11 @@ function UsersTable() { function Admin() { const { user } = useAuth() - if (!user?.is_tenant_admin || !user.permissions.includes("org:projects:read")) + if ( + !user?.is_tenant_admin || + (!user.permissions.includes("org:projects:read") && + !user.permissions.includes("org:projects:write")) + ) return

Tenant administrator access required.

return (
diff --git a/frontend/src/routes/_layout/items.tsx b/frontend/src/routes/_layout/items.tsx index 5a7dcd4435..b7a517d2b4 100644 --- a/frontend/src/routes/_layout/items.tsx +++ b/frontend/src/routes/_layout/items.tsx @@ -58,7 +58,10 @@ function ItemsTable() { function Items() { const { user } = useAuth() - if (!user?.permissions.includes("org:projects:read")) + if ( + !user?.permissions.includes("org:projects:read") && + !user?.permissions.includes("org:projects:write") + ) return

Project read access required.

return (
diff --git a/frontend/tests/admin.spec.ts b/frontend/tests/admin.spec.ts index b3dda8b9a9..ba2d1b269c 100644 --- a/frontend/tests/admin.spec.ts +++ b/frontend/tests/admin.spec.ts @@ -42,3 +42,51 @@ test("revoked membership blocks all protected child UI (network fixture)", async ) await expect(page.getByRole("button", { name: "Add User" })).toHaveCount(0) }) + +for (const grant of ["read", "write", "none"]) { + test(`tenant administrator ${grant} grant controls readable users and mutation UI (network fixture)`, async ({ + page, + }) => { + await installAuthKitFixture(page, { + admin: true, + permissions: grant === "none" ? [] : [`org:projects:${grant}`], + }) + let userLists = 0 + await page.route("**/api/v1/users/?**", (route) => { + userLists++ + return route.fulfill({ + json: { + data: [ + { + id: "00000000-0000-4000-8000-000000000004", + email: "readable-member@example.test", + full_name: "Readable member", + is_active: true, + tenant_id: "00000000-0000-4000-8000-000000000002", + identity_entity_id: "00000000-0000-4000-8000-000000000005", + created_at: "2026-01-01T00:00:00Z", + }, + ], + count: 1, + }, + }) + }) + await page.goto("/admin") + if (grant === "none") { + await expect(page.getByRole("alert")).toContainText( + "Tenant administrator access required", + ) + expect(userLists).toBe(0) + } else { + await expect( + page.getByRole("cell", { + name: "readable-member@example.test", + exact: true, + }), + ).toBeVisible() + } + await expect(page.getByRole("button", { name: "Add User" })).toHaveCount( + grant === "write" ? 1 : 0, + ) + }) +} diff --git a/frontend/tests/items.spec.ts b/frontend/tests/items.spec.ts index 1ef60eaff4..b8ab33f828 100644 --- a/frontend/tests/items.spec.ts +++ b/frontend/tests/items.spec.ts @@ -140,3 +140,46 @@ test("organization switch joining an in-flight refresh cannot silently remain in ) await expect(page.getByText("org_fixture_b", { exact: true })).toHaveCount(0) }) + +for (const grant of ["read", "write", "none"]) { + test(`project ${grant} grant controls readable items and mutation UI (network fixture)`, async ({ + page, + }) => { + await installAuthKitFixture(page, { + permissions: grant === "none" ? [] : [`org:projects:${grant}`], + }) + let itemLists = 0 + await page.route("**/api/v1/items/**", (route) => { + itemLists++ + return route.fulfill({ + json: { + data: [ + { + id: "00000000-0000-4000-8000-000000000006", + title: "Readable project item", + description: "Permission boundary fixture", + owner_id: "00000000-0000-4000-8000-000000000001", + tenant_id: "00000000-0000-4000-8000-000000000002", + created_at: "2026-01-01T00:00:00Z", + }, + ], + count: 1, + }, + }) + }) + await page.goto("/items") + if (grant === "none") { + await expect(page.getByRole("alert")).toContainText( + "Project read access required", + ) + expect(itemLists).toBe(0) + } else { + await expect( + page.getByRole("cell", { name: "Readable project item", exact: true }), + ).toBeVisible() + } + await expect(page.getByRole("button", { name: "Add Item" })).toHaveCount( + grant === "write" ? 1 : 0, + ) + }) +} diff --git a/frontend/tests/utils/authkit-fixture.ts b/frontend/tests/utils/authkit-fixture.ts index 4979508fe1..0994e00b0a 100644 --- a/frontend/tests/utils/authkit-fixture.ts +++ b/frontend/tests/utils/authkit-fixture.ts @@ -8,6 +8,7 @@ export async function installAuthKitFixture( organization = "org_fixture_a", denied = false, tokenLifetimeSeconds = 3600, + permissions = ["org:projects:read", "org:projects:write"], } = {}, ) { const origin = process.env.PLAYWRIGHT_BASE_URL ?? "http://localhost:5173" @@ -40,7 +41,7 @@ export async function installAuthKitFixture( role: "authenticated", iat: issuedAt, exp: issuedAt + tokenLifetimeSeconds, - permissions: [], + permissions, } const token = `${Buffer.from(JSON.stringify({ alg: "none" })).toString("base64url")}.${Buffer.from(JSON.stringify(claims)).toString("base64url")}.fixture` await route.fulfill({ @@ -74,7 +75,7 @@ export async function installAuthKitFixture( identity_entity_id: "00000000-0000-4000-8000-000000000003", created_at: "2026-01-01T00:00:00Z", user_role: admin ? "admin" : "member", - permissions: ["org:projects:read", "org:projects:write"], + permissions, is_tenant_admin: admin, }, }), From 14e103982bd6dd88c3f3d3babc7a432321482dff Mon Sep 17 00:00:00 2001 From: Daniel Lynch Date: Sun, 8 Nov 2026 02:20:21 -0500 Subject: [PATCH 5/5] docs(deploy): require provisioning before no-sync migrations --- backend/README.md | 2 +- deployment.md | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/backend/README.md b/backend/README.md index 5f44d56bfe..6bc45ad0e9 100644 --- a/backend/README.md +++ b/backend/README.md @@ -82,7 +82,7 @@ a previous request's role or claims. From this upstream repository's root: ```console -uv sync --locked --package app +uv sync --no-active --locked uv run --package app --directory backend fastapi dev ``` diff --git a/deployment.md b/deployment.md index 489deb17df..4f208256d4 100644 --- a/deployment.md +++ b/deployment.md @@ -34,6 +34,17 @@ login, refresh, logout and organization selection; it uses public ## Prepare the API namespace +Prepare the declared application environment before supplying migration +credentials. From the application root: + +```console +uv sync --no-active --locked +``` + +An embedding workspace must select its API-owned `UV_PROJECT_ENVIRONMENT`, +not the parent's environment. `--no-sync` below assumes this provisioning has +succeeded; it does not install dependencies or check environment freshness. + Provision canonical product schemas/identities through their existing owner and `api` through the reviewed schema owner. Preserve canonical tenant TEXT IDs and local actor UUIDs. Do not run the legacy public migration history, create tables