feat: update local authentication mode to require a non-placeholder token of at least 50 characters
This commit is contained in:
@@ -17,7 +17,8 @@ DB_AUTO_MIGRATE=true
|
|||||||
LOG_LEVEL=INFO
|
LOG_LEVEL=INFO
|
||||||
REQUEST_LOG_SLOW_MS=1000
|
REQUEST_LOG_SLOW_MS=1000
|
||||||
AUTH_MODE=local
|
AUTH_MODE=local
|
||||||
LOCAL_AUTH_TOKEN=change-me
|
# REQUIRED when AUTH_MODE=local (must be non-placeholder and at least 50 chars).
|
||||||
|
LOCAL_AUTH_TOKEN=
|
||||||
|
|
||||||
# --- frontend settings ---
|
# --- frontend settings ---
|
||||||
# REQUIRED: Public URL used by the browser to reach the API.
|
# REQUIRED: Public URL used by the browser to reach the API.
|
||||||
|
|||||||
@@ -54,12 +54,15 @@ Mission Control supports two auth modes via `AUTH_MODE`:
|
|||||||
```bash
|
```bash
|
||||||
cp .env.example .env
|
cp .env.example .env
|
||||||
|
|
||||||
|
# REQUIRED for local auth mode:
|
||||||
|
# set LOCAL_AUTH_TOKEN to a non-placeholder value with at least 50 characters.
|
||||||
|
|
||||||
# REQUIRED: the browser must be able to reach the backend.
|
# REQUIRED: the browser must be able to reach the backend.
|
||||||
# NEXT_PUBLIC_API_URL must be reachable from the *browser* (host), not an internal Docker network name.
|
# NEXT_PUBLIC_API_URL must be reachable from the *browser* (host), not an internal Docker network name.
|
||||||
# Missing/blank NEXT_PUBLIC_API_URL will break frontend API calls (e.g. Activity feed).
|
# Missing/blank NEXT_PUBLIC_API_URL will break frontend API calls (e.g. Activity feed).
|
||||||
|
|
||||||
# Auth defaults in .env.example are local mode.
|
# Auth defaults in .env.example are local mode.
|
||||||
# For production, set LOCAL_AUTH_TOKEN to a strong random value.
|
# For production, set LOCAL_AUTH_TOKEN to a random value with at least 50 characters.
|
||||||
# For Clerk mode, set AUTH_MODE=clerk and provide Clerk keys.
|
# For Clerk mode, set AUTH_MODE=clerk and provide Clerk keys.
|
||||||
|
|
||||||
docker compose -f compose.yml --env-file .env up -d --build
|
docker compose -f compose.yml --env-file .env up -d --build
|
||||||
|
|||||||
@@ -10,7 +10,8 @@ BASE_URL=
|
|||||||
|
|
||||||
# Auth mode: clerk or local.
|
# Auth mode: clerk or local.
|
||||||
AUTH_MODE=local
|
AUTH_MODE=local
|
||||||
LOCAL_AUTH_TOKEN=change-me
|
# REQUIRED when AUTH_MODE=local (must be non-placeholder and at least 50 chars).
|
||||||
|
LOCAL_AUTH_TOKEN=
|
||||||
|
|
||||||
# Clerk (auth only; used when AUTH_MODE=clerk)
|
# Clerk (auth only; used when AUTH_MODE=clerk)
|
||||||
CLERK_SECRET_KEY=
|
CLERK_SECRET_KEY=
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
|||||||
from pydantic import BaseModel, ValidationError
|
from pydantic import BaseModel, ValidationError
|
||||||
from starlette.concurrency import run_in_threadpool
|
from starlette.concurrency import run_in_threadpool
|
||||||
|
|
||||||
|
from app.core.auth_mode import AuthMode
|
||||||
from app.core.config import settings
|
from app.core.config import settings
|
||||||
from app.core.logging import get_logger
|
from app.core.logging import get_logger
|
||||||
from app.db import crud
|
from app.db import crud
|
||||||
@@ -244,7 +245,7 @@ async def _fetch_clerk_profile(clerk_user_id: str) -> tuple[str | None, str | No
|
|||||||
|
|
||||||
async def delete_clerk_user(clerk_user_id: str) -> None:
|
async def delete_clerk_user(clerk_user_id: str) -> None:
|
||||||
"""Delete a Clerk user via the official Clerk SDK."""
|
"""Delete a Clerk user via the official Clerk SDK."""
|
||||||
if settings.auth_mode != "clerk":
|
if settings.auth_mode != AuthMode.CLERK:
|
||||||
return
|
return
|
||||||
|
|
||||||
secret = settings.clerk_secret_key.strip()
|
secret = settings.clerk_secret_key.strip()
|
||||||
@@ -422,7 +423,7 @@ async def get_auth_context(
|
|||||||
session: AsyncSession = SESSION_DEP,
|
session: AsyncSession = SESSION_DEP,
|
||||||
) -> AuthContext:
|
) -> AuthContext:
|
||||||
"""Resolve required authenticated user context for the configured auth mode."""
|
"""Resolve required authenticated user context for the configured auth mode."""
|
||||||
if settings.auth_mode == "local":
|
if settings.auth_mode == AuthMode.LOCAL:
|
||||||
local_auth = await _resolve_local_auth_context(
|
local_auth = await _resolve_local_auth_context(
|
||||||
request=request,
|
request=request,
|
||||||
session=session,
|
session=session,
|
||||||
@@ -466,7 +467,7 @@ async def get_auth_context_optional(
|
|||||||
"""Resolve user context if available, otherwise return `None`."""
|
"""Resolve user context if available, otherwise return `None`."""
|
||||||
if request.headers.get("X-Agent-Token"):
|
if request.headers.get("X-Agent-Token"):
|
||||||
return None
|
return None
|
||||||
if settings.auth_mode == "local":
|
if settings.auth_mode == AuthMode.LOCAL:
|
||||||
return await _resolve_local_auth_context(
|
return await _resolve_local_auth_context(
|
||||||
request=request,
|
request=request,
|
||||||
session=session,
|
session=session,
|
||||||
|
|||||||
12
backend/app/core/auth_mode.py
Normal file
12
backend/app/core/auth_mode.py
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
"""Shared auth-mode enum values."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from enum import Enum
|
||||||
|
|
||||||
|
|
||||||
|
class AuthMode(str, Enum):
|
||||||
|
"""Supported authentication modes for backend and frontend."""
|
||||||
|
|
||||||
|
CLERK = "clerk"
|
||||||
|
LOCAL = "local"
|
||||||
@@ -3,13 +3,24 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Literal, Self
|
from typing import Self
|
||||||
|
|
||||||
from pydantic import Field, model_validator
|
from pydantic import Field, model_validator
|
||||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
|
||||||
|
from app.core.auth_mode import AuthMode
|
||||||
|
|
||||||
BACKEND_ROOT = Path(__file__).resolve().parents[2]
|
BACKEND_ROOT = Path(__file__).resolve().parents[2]
|
||||||
DEFAULT_ENV_FILE = BACKEND_ROOT / ".env"
|
DEFAULT_ENV_FILE = BACKEND_ROOT / ".env"
|
||||||
|
LOCAL_AUTH_TOKEN_MIN_LENGTH = 50
|
||||||
|
LOCAL_AUTH_TOKEN_PLACEHOLDERS = frozenset(
|
||||||
|
{
|
||||||
|
"change-me",
|
||||||
|
"changeme",
|
||||||
|
"replace-me",
|
||||||
|
"replace-with-strong-random-token",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
class Settings(BaseSettings):
|
class Settings(BaseSettings):
|
||||||
@@ -27,7 +38,7 @@ class Settings(BaseSettings):
|
|||||||
database_url: str = "postgresql+psycopg://postgres:postgres@localhost:5432/openclaw_agency"
|
database_url: str = "postgresql+psycopg://postgres:postgres@localhost:5432/openclaw_agency"
|
||||||
|
|
||||||
# Auth mode: "clerk" for Clerk JWT auth, "local" for shared bearer token auth.
|
# Auth mode: "clerk" for Clerk JWT auth, "local" for shared bearer token auth.
|
||||||
auth_mode: Literal["clerk", "local"]
|
auth_mode: AuthMode
|
||||||
local_auth_token: str = ""
|
local_auth_token: str = ""
|
||||||
|
|
||||||
# Clerk auth (auth only; roles stored in DB)
|
# Clerk auth (auth only; roles stored in DB)
|
||||||
@@ -51,15 +62,20 @@ class Settings(BaseSettings):
|
|||||||
|
|
||||||
@model_validator(mode="after")
|
@model_validator(mode="after")
|
||||||
def _defaults(self) -> Self:
|
def _defaults(self) -> Self:
|
||||||
if self.auth_mode == "clerk":
|
if self.auth_mode == AuthMode.CLERK:
|
||||||
if not self.clerk_secret_key.strip():
|
if not self.clerk_secret_key.strip():
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"CLERK_SECRET_KEY must be set and non-empty when AUTH_MODE=clerk.",
|
"CLERK_SECRET_KEY must be set and non-empty when AUTH_MODE=clerk.",
|
||||||
)
|
)
|
||||||
elif self.auth_mode == "local":
|
elif self.auth_mode == AuthMode.LOCAL:
|
||||||
if not self.local_auth_token.strip():
|
token = self.local_auth_token.strip()
|
||||||
|
if (
|
||||||
|
not token
|
||||||
|
or len(token) < LOCAL_AUTH_TOKEN_MIN_LENGTH
|
||||||
|
or token.lower() in LOCAL_AUTH_TOKEN_PLACEHOLDERS
|
||||||
|
):
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
"LOCAL_AUTH_TOKEN must be set and non-empty when AUTH_MODE=local.",
|
"LOCAL_AUTH_TOKEN must be at least 50 characters and non-placeholder when AUTH_MODE=local.",
|
||||||
)
|
)
|
||||||
# In dev, default to applying Alembic migrations at startup to avoid
|
# In dev, default to applying Alembic migrations at startup to avoid
|
||||||
# schema drift (e.g. missing newly-added columns).
|
# schema drift (e.g. missing newly-added columns).
|
||||||
|
|||||||
@@ -10,6 +10,6 @@ if str(ROOT) not in sys.path:
|
|||||||
sys.path.insert(0, str(ROOT))
|
sys.path.insert(0, str(ROOT))
|
||||||
|
|
||||||
# Tests should fail fast if auth-mode wiring breaks, but still need deterministic
|
# Tests should fail fast if auth-mode wiring breaks, but still need deterministic
|
||||||
# defaults during import-time settings initialization.
|
# defaults during import-time settings initialization, regardless of shell env.
|
||||||
os.environ.setdefault("AUTH_MODE", "local")
|
os.environ["AUTH_MODE"] = "local"
|
||||||
os.environ.setdefault("LOCAL_AUTH_TOKEN", "test-local-token")
|
os.environ["LOCAL_AUTH_TOKEN"] = "test-local-token-0123456789-0123456789-0123456789x"
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import pytest
|
|||||||
from fastapi import HTTPException
|
from fastapi import HTTPException
|
||||||
|
|
||||||
from app.core import auth
|
from app.core import auth
|
||||||
|
from app.core.auth_mode import AuthMode
|
||||||
from app.models.users import User
|
from app.models.users import User
|
||||||
|
|
||||||
|
|
||||||
@@ -21,7 +22,7 @@ class _FakeSession:
|
|||||||
async def test_get_auth_context_raises_401_when_clerk_signed_out(
|
async def test_get_auth_context_raises_401_when_clerk_signed_out(
|
||||||
monkeypatch: pytest.MonkeyPatch,
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
) -> None:
|
) -> None:
|
||||||
monkeypatch.setattr(auth.settings, "auth_mode", "clerk")
|
monkeypatch.setattr(auth.settings, "auth_mode", AuthMode.CLERK)
|
||||||
monkeypatch.setattr(auth.settings, "clerk_secret_key", "sk_test_dummy")
|
monkeypatch.setattr(auth.settings, "clerk_secret_key", "sk_test_dummy")
|
||||||
|
|
||||||
from clerk_backend_api.security.types import AuthStatus, RequestState
|
from clerk_backend_api.security.types import AuthStatus, RequestState
|
||||||
@@ -45,7 +46,7 @@ async def test_get_auth_context_raises_401_when_clerk_signed_out(
|
|||||||
async def test_get_auth_context_uses_request_state_payload_claims(
|
async def test_get_auth_context_uses_request_state_payload_claims(
|
||||||
monkeypatch: pytest.MonkeyPatch,
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
) -> None:
|
) -> None:
|
||||||
monkeypatch.setattr(auth.settings, "auth_mode", "clerk")
|
monkeypatch.setattr(auth.settings, "auth_mode", AuthMode.CLERK)
|
||||||
monkeypatch.setattr(auth.settings, "clerk_secret_key", "sk_test_dummy")
|
monkeypatch.setattr(auth.settings, "clerk_secret_key", "sk_test_dummy")
|
||||||
|
|
||||||
from clerk_backend_api.security.types import AuthStatus, RequestState
|
from clerk_backend_api.security.types import AuthStatus, RequestState
|
||||||
@@ -88,7 +89,7 @@ async def test_get_auth_context_uses_request_state_payload_claims(
|
|||||||
async def test_get_auth_context_optional_returns_none_for_agent_token(
|
async def test_get_auth_context_optional_returns_none_for_agent_token(
|
||||||
monkeypatch: pytest.MonkeyPatch,
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
) -> None:
|
) -> None:
|
||||||
monkeypatch.setattr(auth.settings, "auth_mode", "clerk")
|
monkeypatch.setattr(auth.settings, "auth_mode", AuthMode.CLERK)
|
||||||
monkeypatch.setattr(auth.settings, "clerk_secret_key", "sk_test_dummy")
|
monkeypatch.setattr(auth.settings, "clerk_secret_key", "sk_test_dummy")
|
||||||
|
|
||||||
async def _boom(_request: Any) -> Any: # pragma: no cover
|
async def _boom(_request: Any) -> Any: # pragma: no cover
|
||||||
@@ -108,7 +109,7 @@ async def test_get_auth_context_optional_returns_none_for_agent_token(
|
|||||||
async def test_get_auth_context_local_mode_requires_valid_bearer_token(
|
async def test_get_auth_context_local_mode_requires_valid_bearer_token(
|
||||||
monkeypatch: pytest.MonkeyPatch,
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
) -> None:
|
) -> None:
|
||||||
monkeypatch.setattr(auth.settings, "auth_mode", "local")
|
monkeypatch.setattr(auth.settings, "auth_mode", AuthMode.LOCAL)
|
||||||
monkeypatch.setattr(auth.settings, "local_auth_token", "expected-token")
|
monkeypatch.setattr(auth.settings, "local_auth_token", "expected-token")
|
||||||
|
|
||||||
async def _fake_local_user(_session: Any) -> User:
|
async def _fake_local_user(_session: Any) -> User:
|
||||||
@@ -131,7 +132,7 @@ async def test_get_auth_context_local_mode_requires_valid_bearer_token(
|
|||||||
async def test_get_auth_context_optional_local_mode_returns_none_without_token(
|
async def test_get_auth_context_optional_local_mode_returns_none_without_token(
|
||||||
monkeypatch: pytest.MonkeyPatch,
|
monkeypatch: pytest.MonkeyPatch,
|
||||||
) -> None:
|
) -> None:
|
||||||
monkeypatch.setattr(auth.settings, "auth_mode", "local")
|
monkeypatch.setattr(auth.settings, "auth_mode", AuthMode.LOCAL)
|
||||||
monkeypatch.setattr(auth.settings, "local_auth_token", "expected-token")
|
monkeypatch.setattr(auth.settings, "local_auth_token", "expected-token")
|
||||||
|
|
||||||
async def _boom(_session: Any) -> User: # pragma: no cover
|
async def _boom(_session: Any) -> User: # pragma: no cover
|
||||||
|
|||||||
70
backend/tests/test_config_auth_mode.py
Normal file
70
backend/tests/test_config_auth_mode.py
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
# ruff: noqa: INP001
|
||||||
|
"""Settings validation tests for auth-mode configuration."""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from pydantic import ValidationError
|
||||||
|
|
||||||
|
from app.core.auth_mode import AuthMode
|
||||||
|
from app.core.config import Settings
|
||||||
|
|
||||||
|
|
||||||
|
def test_local_mode_requires_non_empty_token() -> None:
|
||||||
|
with pytest.raises(
|
||||||
|
ValidationError,
|
||||||
|
match="LOCAL_AUTH_TOKEN must be at least 50 characters and non-placeholder when AUTH_MODE=local",
|
||||||
|
):
|
||||||
|
Settings(
|
||||||
|
_env_file=None,
|
||||||
|
auth_mode=AuthMode.LOCAL,
|
||||||
|
local_auth_token="",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_local_mode_requires_minimum_length() -> None:
|
||||||
|
with pytest.raises(
|
||||||
|
ValidationError,
|
||||||
|
match="LOCAL_AUTH_TOKEN must be at least 50 characters and non-placeholder when AUTH_MODE=local",
|
||||||
|
):
|
||||||
|
Settings(
|
||||||
|
_env_file=None,
|
||||||
|
auth_mode=AuthMode.LOCAL,
|
||||||
|
local_auth_token="x" * 49,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_local_mode_rejects_placeholder_token() -> None:
|
||||||
|
with pytest.raises(
|
||||||
|
ValidationError,
|
||||||
|
match="LOCAL_AUTH_TOKEN must be at least 50 characters and non-placeholder when AUTH_MODE=local",
|
||||||
|
):
|
||||||
|
Settings(
|
||||||
|
_env_file=None,
|
||||||
|
auth_mode=AuthMode.LOCAL,
|
||||||
|
local_auth_token="change-me",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_local_mode_accepts_real_token() -> None:
|
||||||
|
token = "a" * 50
|
||||||
|
settings = Settings(
|
||||||
|
_env_file=None,
|
||||||
|
auth_mode=AuthMode.LOCAL,
|
||||||
|
local_auth_token=token,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert settings.auth_mode == AuthMode.LOCAL
|
||||||
|
assert settings.local_auth_token == token
|
||||||
|
|
||||||
|
|
||||||
|
def test_clerk_mode_requires_secret_key() -> None:
|
||||||
|
with pytest.raises(
|
||||||
|
ValidationError,
|
||||||
|
match="CLERK_SECRET_KEY must be set and non-empty when AUTH_MODE=clerk",
|
||||||
|
):
|
||||||
|
Settings(
|
||||||
|
_env_file=None,
|
||||||
|
auth_mode=AuthMode.CLERK,
|
||||||
|
clerk_secret_key="",
|
||||||
|
)
|
||||||
@@ -14,6 +14,7 @@ from sqlmodel.ext.asyncio.session import AsyncSession
|
|||||||
|
|
||||||
from app.api.users import router as users_router
|
from app.api.users import router as users_router
|
||||||
from app.core import auth as auth_module
|
from app.core import auth as auth_module
|
||||||
|
from app.core.auth_mode import AuthMode
|
||||||
from app.core.config import settings
|
from app.core.config import settings
|
||||||
from app.db.session import get_session
|
from app.db.session import get_session
|
||||||
|
|
||||||
@@ -51,7 +52,7 @@ async def test_local_auth_users_me_requires_and_accepts_valid_token(
|
|||||||
expected_email = f"local-{unique_suffix}@localhost"
|
expected_email = f"local-{unique_suffix}@localhost"
|
||||||
expected_name = "Local Integration User"
|
expected_name = "Local Integration User"
|
||||||
|
|
||||||
monkeypatch.setattr(settings, "auth_mode", "local")
|
monkeypatch.setattr(settings, "auth_mode", AuthMode.LOCAL)
|
||||||
monkeypatch.setattr(settings, "local_auth_token", "integration-token")
|
monkeypatch.setattr(settings, "local_auth_token", "integration-token")
|
||||||
monkeypatch.setattr(auth_module, "LOCAL_AUTH_USER_ID", expected_user_id)
|
monkeypatch.setattr(auth_module, "LOCAL_AUTH_USER_ID", expected_user_id)
|
||||||
monkeypatch.setattr(auth_module, "LOCAL_AUTH_EMAIL", expected_email)
|
monkeypatch.setattr(auth_module, "LOCAL_AUTH_EMAIL", expected_email)
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ services:
|
|||||||
CORS_ORIGINS: ${CORS_ORIGINS:-http://localhost:3000}
|
CORS_ORIGINS: ${CORS_ORIGINS:-http://localhost:3000}
|
||||||
DB_AUTO_MIGRATE: ${DB_AUTO_MIGRATE:-true}
|
DB_AUTO_MIGRATE: ${DB_AUTO_MIGRATE:-true}
|
||||||
AUTH_MODE: ${AUTH_MODE}
|
AUTH_MODE: ${AUTH_MODE}
|
||||||
LOCAL_AUTH_TOKEN: ${LOCAL_AUTH_TOKEN:-change-me}
|
LOCAL_AUTH_TOKEN: ${LOCAL_AUTH_TOKEN}
|
||||||
depends_on:
|
depends_on:
|
||||||
db:
|
db:
|
||||||
condition: service_healthy
|
condition: service_healthy
|
||||||
|
|||||||
@@ -32,6 +32,9 @@ From repo root:
|
|||||||
```bash
|
```bash
|
||||||
cp .env.example .env
|
cp .env.example .env
|
||||||
|
|
||||||
|
# REQUIRED for local mode:
|
||||||
|
# set LOCAL_AUTH_TOKEN in .env to a non-placeholder value with at least 50 characters.
|
||||||
|
|
||||||
docker compose -f compose.yml --env-file .env up -d --build
|
docker compose -f compose.yml --env-file .env up -d --build
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -125,7 +128,7 @@ Set in `.env` (repo root):
|
|||||||
|
|
||||||
```env
|
```env
|
||||||
AUTH_MODE=local
|
AUTH_MODE=local
|
||||||
LOCAL_AUTH_TOKEN=replace-with-strong-random-token
|
LOCAL_AUTH_TOKEN=replace-with-random-token-at-least-50-characters
|
||||||
```
|
```
|
||||||
|
|
||||||
Set frontend mode (optional override in `frontend/.env`):
|
Set frontend mode (optional override in `frontend/.env`):
|
||||||
|
|||||||
@@ -60,7 +60,7 @@ Recommended approach:
|
|||||||
Secrets guidelines:
|
Secrets guidelines:
|
||||||
|
|
||||||
- Choose auth mode explicitly:
|
- Choose auth mode explicitly:
|
||||||
- `AUTH_MODE=local`: set a strong `LOCAL_AUTH_TOKEN`
|
- `AUTH_MODE=local`: set `LOCAL_AUTH_TOKEN` to a random value with at least 50 characters
|
||||||
- `AUTH_MODE=clerk`: configure Clerk keys
|
- `AUTH_MODE=clerk`: configure Clerk keys
|
||||||
- Never commit `LOCAL_AUTH_TOKEN` or Clerk secret key.
|
- Never commit `LOCAL_AUTH_TOKEN` or Clerk secret key.
|
||||||
- Prefer passing secrets as environment variables from the host (or use Docker secrets if you later
|
- Prefer passing secrets as environment variables from the host (or use Docker secrets if you later
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import { AuthMode } from "@/auth/mode";
|
||||||
|
|
||||||
let localToken: string | null = null;
|
let localToken: string | null = null;
|
||||||
const STORAGE_KEY = "mc_local_auth_token";
|
const STORAGE_KEY = "mc_local_auth_token";
|
||||||
|
|
||||||
export function isLocalAuthMode(): boolean {
|
export function isLocalAuthMode(): boolean {
|
||||||
return process.env.NEXT_PUBLIC_AUTH_MODE === "local";
|
return process.env.NEXT_PUBLIC_AUTH_MODE === AuthMode.Local;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function setLocalAuthToken(token: string): void {
|
export function setLocalAuthToken(token: string): void {
|
||||||
|
|||||||
4
frontend/src/auth/mode.ts
Normal file
4
frontend/src/auth/mode.ts
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
export enum AuthMode {
|
||||||
|
Clerk = "clerk",
|
||||||
|
Local = "local",
|
||||||
|
}
|
||||||
115
frontend/src/components/organisms/LocalAuthLogin.test.tsx
Normal file
115
frontend/src/components/organisms/LocalAuthLogin.test.tsx
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import { render, screen, waitFor } from "@testing-library/react";
|
||||||
|
import userEvent from "@testing-library/user-event";
|
||||||
|
|
||||||
|
import { LocalAuthLogin } from "./LocalAuthLogin";
|
||||||
|
|
||||||
|
const setLocalAuthTokenMock = vi.hoisted(() => vi.fn());
|
||||||
|
const fetchMock = vi.hoisted(() => vi.fn());
|
||||||
|
|
||||||
|
vi.mock("@/auth/localAuth", async () => {
|
||||||
|
const actual = await vi.importActual<typeof import("@/auth/localAuth")>(
|
||||||
|
"@/auth/localAuth",
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
...actual,
|
||||||
|
setLocalAuthToken: setLocalAuthTokenMock,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("LocalAuthLogin", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
fetchMock.mockReset();
|
||||||
|
setLocalAuthTokenMock.mockReset();
|
||||||
|
vi.stubGlobal("fetch", fetchMock);
|
||||||
|
vi.stubEnv("NEXT_PUBLIC_API_URL", "http://localhost:8000/");
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.unstubAllGlobals();
|
||||||
|
vi.unstubAllEnvs();
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("requires a non-empty token", async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
render(<LocalAuthLogin />);
|
||||||
|
|
||||||
|
await user.click(screen.getByRole("button", { name: "Continue" }));
|
||||||
|
|
||||||
|
expect(screen.getByText("Bearer token is required.")).toBeInTheDocument();
|
||||||
|
expect(fetchMock).not.toHaveBeenCalled();
|
||||||
|
expect(setLocalAuthTokenMock).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("requires token length of at least 50 characters", async () => {
|
||||||
|
const user = userEvent.setup();
|
||||||
|
render(<LocalAuthLogin />);
|
||||||
|
|
||||||
|
await user.type(screen.getByPlaceholderText("Paste token"), "x".repeat(49));
|
||||||
|
await user.click(screen.getByRole("button", { name: "Continue" }));
|
||||||
|
|
||||||
|
expect(
|
||||||
|
screen.getByText("Bearer token must be at least 50 characters."),
|
||||||
|
).toBeInTheDocument();
|
||||||
|
expect(fetchMock).not.toHaveBeenCalled();
|
||||||
|
expect(setLocalAuthTokenMock).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("rejects invalid token values", async () => {
|
||||||
|
const onAuthenticatedMock = vi.fn();
|
||||||
|
fetchMock.mockResolvedValueOnce(new Response(null, { status: 401 }));
|
||||||
|
const user = userEvent.setup();
|
||||||
|
render(<LocalAuthLogin onAuthenticated={onAuthenticatedMock} />);
|
||||||
|
|
||||||
|
await user.type(screen.getByPlaceholderText("Paste token"), "x".repeat(50));
|
||||||
|
await user.click(screen.getByRole("button", { name: "Continue" }));
|
||||||
|
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(screen.getByText("Token is invalid.")).toBeInTheDocument(),
|
||||||
|
);
|
||||||
|
expect(fetchMock).toHaveBeenCalledWith(
|
||||||
|
"http://localhost:8000/api/v1/users/me",
|
||||||
|
expect.objectContaining({
|
||||||
|
method: "GET",
|
||||||
|
headers: { Authorization: `Bearer ${"x".repeat(50)}` },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(setLocalAuthTokenMock).not.toHaveBeenCalled();
|
||||||
|
expect(onAuthenticatedMock).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("saves token only after successful backend validation", async () => {
|
||||||
|
const onAuthenticatedMock = vi.fn();
|
||||||
|
fetchMock.mockResolvedValueOnce(new Response(null, { status: 200 }));
|
||||||
|
const user = userEvent.setup();
|
||||||
|
render(<LocalAuthLogin onAuthenticated={onAuthenticatedMock} />);
|
||||||
|
|
||||||
|
const token = ` ${"g".repeat(50)} `;
|
||||||
|
await user.type(screen.getByPlaceholderText("Paste token"), token);
|
||||||
|
await user.click(screen.getByRole("button", { name: "Continue" }));
|
||||||
|
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(setLocalAuthTokenMock).toHaveBeenCalledWith("g".repeat(50)),
|
||||||
|
);
|
||||||
|
expect(onAuthenticatedMock).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows a clear error when backend is unreachable", async () => {
|
||||||
|
const onAuthenticatedMock = vi.fn();
|
||||||
|
fetchMock.mockRejectedValueOnce(new TypeError("network error"));
|
||||||
|
const user = userEvent.setup();
|
||||||
|
render(<LocalAuthLogin onAuthenticated={onAuthenticatedMock} />);
|
||||||
|
|
||||||
|
await user.type(screen.getByPlaceholderText("Paste token"), "t".repeat(50));
|
||||||
|
await user.click(screen.getByRole("button", { name: "Continue" }));
|
||||||
|
|
||||||
|
await waitFor(() =>
|
||||||
|
expect(
|
||||||
|
screen.getByText("Unable to reach backend to validate token."),
|
||||||
|
).toBeInTheDocument(),
|
||||||
|
);
|
||||||
|
expect(setLocalAuthTokenMock).not.toHaveBeenCalled();
|
||||||
|
expect(onAuthenticatedMock).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -8,54 +8,132 @@ import { Button } from "@/components/ui/button";
|
|||||||
import { Card, CardContent, CardHeader } from "@/components/ui/card";
|
import { Card, CardContent, CardHeader } from "@/components/ui/card";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
|
|
||||||
export function LocalAuthLogin() {
|
const LOCAL_AUTH_TOKEN_MIN_LENGTH = 50;
|
||||||
|
|
||||||
|
async function validateLocalToken(token: string): Promise<string | null> {
|
||||||
|
const rawBaseUrl = process.env.NEXT_PUBLIC_API_URL;
|
||||||
|
if (!rawBaseUrl) {
|
||||||
|
return "NEXT_PUBLIC_API_URL is not set.";
|
||||||
|
}
|
||||||
|
|
||||||
|
const baseUrl = rawBaseUrl.replace(/\/+$/, "");
|
||||||
|
|
||||||
|
let response: Response;
|
||||||
|
try {
|
||||||
|
response = await fetch(`${baseUrl}/api/v1/users/me`, {
|
||||||
|
method: "GET",
|
||||||
|
headers: {
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
return "Unable to reach backend to validate token.";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (response.status === 401 || response.status === 403) {
|
||||||
|
return "Token is invalid.";
|
||||||
|
}
|
||||||
|
return `Unable to validate token (HTTP ${response.status}).`;
|
||||||
|
}
|
||||||
|
|
||||||
|
type LocalAuthLoginProps = {
|
||||||
|
onAuthenticated?: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const defaultOnAuthenticated = () => window.location.reload();
|
||||||
|
|
||||||
|
export function LocalAuthLogin({ onAuthenticated }: LocalAuthLoginProps) {
|
||||||
const [token, setToken] = useState("");
|
const [token, setToken] = useState("");
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [isValidating, setIsValidating] = useState(false);
|
||||||
|
|
||||||
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
|
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
const cleaned = token.trim();
|
const cleaned = token.trim();
|
||||||
if (!cleaned) {
|
if (!cleaned) {
|
||||||
setError("Bearer token is required.");
|
setError("Bearer token is required.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (cleaned.length < LOCAL_AUTH_TOKEN_MIN_LENGTH) {
|
||||||
|
setError(
|
||||||
|
`Bearer token must be at least ${LOCAL_AUTH_TOKEN_MIN_LENGTH} characters.`,
|
||||||
|
);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsValidating(true);
|
||||||
|
const validationError = await validateLocalToken(cleaned);
|
||||||
|
setIsValidating(false);
|
||||||
|
if (validationError) {
|
||||||
|
setError(validationError);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
setLocalAuthToken(cleaned);
|
setLocalAuthToken(cleaned);
|
||||||
setError(null);
|
setError(null);
|
||||||
window.location.reload();
|
(onAuthenticated ?? defaultOnAuthenticated)();
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="flex min-h-screen items-center justify-center p-4">
|
<div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-app px-4 py-10">
|
||||||
<Card className="w-full max-w-md">
|
<div className="pointer-events-none absolute inset-0">
|
||||||
<CardHeader className="space-y-3">
|
<div className="absolute -top-28 -left-24 h-72 w-72 rounded-full bg-[color:var(--accent-soft)] blur-3xl" />
|
||||||
<div className="mx-auto rounded-full bg-slate-100 p-3 text-slate-700">
|
<div className="absolute -right-28 -bottom-24 h-80 w-80 rounded-full bg-[rgba(14,165,233,0.12)] blur-3xl" />
|
||||||
<Lock className="h-5 w-5" />
|
</div>
|
||||||
|
|
||||||
|
<Card className="relative w-full max-w-lg animate-fade-in-up">
|
||||||
|
<CardHeader className="space-y-5 border-b border-[color:var(--border)] pb-5">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<span className="rounded-full border border-[color:var(--border)] bg-[color:var(--surface-muted)] px-3 py-1 text-xs font-semibold uppercase tracking-[0.08em] text-muted">
|
||||||
|
Self-host mode
|
||||||
|
</span>
|
||||||
|
<div className="rounded-xl bg-[color:var(--accent-soft)] p-2 text-[color:var(--accent)]">
|
||||||
|
<Lock className="h-5 w-5" />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="space-y-1 text-center">
|
<div className="space-y-1">
|
||||||
<h1 className="text-xl font-semibold text-slate-900">
|
<h1 className="text-2xl font-semibold tracking-tight text-strong">
|
||||||
Local Authentication
|
Local Authentication
|
||||||
</h1>
|
</h1>
|
||||||
<p className="text-sm text-slate-600">
|
<p className="text-sm text-muted">
|
||||||
Enter the shared local token configured as
|
Enter your access token to unlock Mission Control.
|
||||||
<code className="mx-1 rounded bg-slate-100 px-1 py-0.5 text-xs">
|
|
||||||
LOCAL_AUTH_TOKEN
|
|
||||||
</code>
|
|
||||||
on the backend.
|
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent className="pt-5">
|
||||||
<form onSubmit={handleSubmit} className="space-y-3">
|
<form onSubmit={handleSubmit} className="space-y-4">
|
||||||
<Input
|
<div className="space-y-2">
|
||||||
type="password"
|
<label
|
||||||
value={token}
|
htmlFor="local-auth-token"
|
||||||
onChange={(event) => setToken(event.target.value)}
|
className="text-xs font-semibold uppercase tracking-[0.08em] text-muted"
|
||||||
placeholder="Paste token"
|
>
|
||||||
autoFocus
|
Access token
|
||||||
/>
|
</label>
|
||||||
{error ? <p className="text-sm text-red-600">{error}</p> : null}
|
<Input
|
||||||
<Button type="submit" className="w-full">
|
id="local-auth-token"
|
||||||
Continue
|
type="password"
|
||||||
|
value={token}
|
||||||
|
onChange={(event) => setToken(event.target.value)}
|
||||||
|
placeholder="Paste token"
|
||||||
|
autoFocus
|
||||||
|
disabled={isValidating}
|
||||||
|
className="font-mono"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{error ? (
|
||||||
|
<p className="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<p className="text-xs text-muted">
|
||||||
|
Token must be at least {LOCAL_AUTH_TOKEN_MIN_LENGTH} characters.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<Button type="submit" className="w-full" size="lg" disabled={isValidating}>
|
||||||
|
{isValidating ? "Validating..." : "Continue"}
|
||||||
</Button>
|
</Button>
|
||||||
</form>
|
</form>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
|
|||||||
@@ -2,9 +2,10 @@ import { NextResponse } from "next/server";
|
|||||||
import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";
|
import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";
|
||||||
|
|
||||||
import { isLikelyValidClerkPublishableKey } from "@/auth/clerkKey";
|
import { isLikelyValidClerkPublishableKey } from "@/auth/clerkKey";
|
||||||
|
import { AuthMode } from "@/auth/mode";
|
||||||
|
|
||||||
const isClerkEnabled = () =>
|
const isClerkEnabled = () =>
|
||||||
process.env.NEXT_PUBLIC_AUTH_MODE !== "local" &&
|
process.env.NEXT_PUBLIC_AUTH_MODE !== AuthMode.Local &&
|
||||||
isLikelyValidClerkPublishableKey(
|
isLikelyValidClerkPublishableKey(
|
||||||
process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY,
|
process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY,
|
||||||
);
|
);
|
||||||
|
|||||||
Reference in New Issue
Block a user