Skip to content

Conversation

@HardMax71
Copy link
Owner

@HardMax71 HardMax71 commented Feb 9, 2026


Summary by cubic

Switched auth and execution status to enums, moved session checks to /auth/me, and centralized duplicate-user handling. Removed unused DLQ stats and events aggregation endpoints, restricted DLQ routes to admins, and simplified event list responses.

  • Refactors

    • Auth: role uses UserRole across API/SDK/tests; UserResponse now includes role/is_active/is_superuser; registration creates USER; duplicate users return 409 "User already exists"; client/session checks use GET /api/v1/auth/me.
    • DLQ: removed /api/v1/dlq/stats and related models/repo methods; all /dlq routes now require admin_user; simplified RetryPolicy creation.
    • Events: removed /api/v1/events/aggregate and related models/service/repo/tests; list endpoints return EventListResponse via model_validate.
    • Execution: status now uses ExecutionStatus in APIs/services; publish_execution_event(status) accepts ExecutionStatus; record_execution_scheduled() no longer takes a status arg.
  • Migration

    • Update types to use UserRole and ExecutionStatus.
    • Registration: remove role from payloads; handle 409 "User already exists"; create admins via admin endpoints.
    • Replace /api/v1/auth/verify-token with GET /api/v1/auth/me; remove any use of TokenValidationResponse.
    • Remove any use of /api/v1/dlq/stats and /api/v1/events/aggregate and related SDK types.

Written for commit b0aed8d. Summary will update on new commits.

Summary by CodeRabbit

  • Bug Fixes

    • Login and registration now use the stored user role; duplicate-registration error changed to "User already exists".
    • Client-side auth verifies via current user profile fetch instead of the removed token-verify flow.
  • Schema Updates

    • Login and User responses now require a typed role and include is_active and is_superuser; token-validation response removed.
  • Breaking Changes

    • Token verification endpoint, DLQ statistics and event-aggregation/type-listing endpoints and related public types removed from the API.

@coderabbitai
Copy link

coderabbitai bot commented Feb 9, 2026

📝 Walkthrough

Walkthrough

Removed the /verify-token endpoint and TokenValidationResponse; auth verification now uses current-user profile fetching. User role typing standardized to UserRole. Duplicate-email conflict handling moved to user repository. DLQ statistics, event-aggregation, and related types/endpoints were removed. Frontend SDK/types, auth store, interceptors, OpenAPI and tests updated accordingly.

Changes

Cohort / File(s) Summary
Backend — Auth & user
backend/app/api/routes/auth.py, backend/app/db/repositories/user_repository.py, backend/app/schemas_pydantic/user.py
Removed /verify-token route and TokenValidationResponse; login/register now use UserRole and return validated Pydantic responses; create_user now catches DuplicateKeyError and raises ConflictError("User already exists").
Backend — DLQ removals
backend/app/api/routes/dlq.py, backend/app/db/repositories/dlq_repository.py, backend/app/dlq/models.py, backend/app/dlq/__init__.py, backend/app/schemas_pydantic/dlq.py
Removed DLQ statistics models, get_dlq_stats repository method and /stats endpoint, and pruned related exports/types.
Backend — Events aggregation removal
backend/app/api/routes/events.py, backend/app/db/repositories/event_repository.py, backend/app/domain/events/..., backend/app/schemas_pydantic/events.py, backend/app/services/event_service.py
Deleted event aggregation and event-type listing endpoints, repository/service methods, EventAggregationResult type and EventAggregationRequest schema; replaced some response construction with model_validate(..., from_attributes=True).
Backend — Middleware & tests
backend/app/core/middlewares/cache.py, backend/tests/conftest.py, backend/tests/e2e/*
Removed cache policy for /api/v1/auth/verify-token; test fixtures updated to use UserRole and to promote non-USER roles post-register; removed verify-token and DLQ-stats tests and adjusted expectations (e.g., "User already exists").
Frontend — API SDK / types / index
frontend/src/lib/api/sdk.gen.ts, frontend/src/lib/api/types.gen.ts, frontend/src/lib/api/index.ts
Removed generated verifyToken API and related DLQ/aggregate API typings; changed LoginResponse.role and UserResponse fields to UserRole; updated exported SDK/type lists to match pruned API surface.
Frontend — Auth store, interceptors & tests
frontend/src/stores/auth.svelte.ts, frontend/src/lib/api-interceptors.ts, frontend/src/stores/__tests__/auth.test.ts
Verification now fetches /api/v1/auth/me (profile) instead of verify-token; auth store derives userId/email/role from profile and reads CSRF from cookie; interceptors removed verify-token from auth endpoints; tests updated to mock profile flows.
Docs / OpenAPI
docs/reference/openapi.json
Removed /api/v1/auth/verify-token and TokenValidationResponse; removed DLQ stats and event-aggregate/type endpoints/schemas; updated user/login schemas to reference UserRole and mark role, is_active, is_superuser, user_id required; changed register 409 description to "User already exists".

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Client
  participant FrontendStore as Frontend\nAuth Store
  participant API as Backend\nAPI (/api/v1/auth)
  participant DB as User\nRepository/DB

  Client->>FrontendStore: trigger verifyAuth / initialize
  FrontendStore->>API: GET /api/v1/auth/me
  API->>DB: validate session/token & fetch user profile
  DB-->>API: user profile (username, email, role, is_active)
  API-->>FrontendStore: 200 OK + profile
  FrontendStore->>FrontendStore: set user context (userId, userEmail, role), read CSRF cookie
  FrontendStore-->>Client: auth confirmed (state updated)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 I nibbled tokens down to a thread,
Now I hop to profiles where users are fed.
Roles are enums, duplicates get checked,
DLQ stats hopped off — fewer things to inspect.
Hooray — fresh carrots, and tests pass ahead!

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Title check ❓ Inconclusive The title 'Fix/endpoints' is vague and does not clearly describe the main changes in this pull request. Use a more descriptive title that captures the primary changes, such as 'Refactor authentication to use UserRole enum and remove verify-token endpoint' or 'Replace token verification with user profile endpoint and centralize role handling'.
✅ Passed checks (2 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 92.11% which is sufficient. The required threshold is 80.00%.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/endpoints

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@backend/app/api/routes/auth.py`:
- Around line 168-176: The code currently uses the request-supplied user.role
when building DomainUserCreate which allows privilege escalation; change the
creation to always set role to UserRole.USER (import UserRole from
app.domain.enums if missing) instead of user.role — e.g. keep hashed_password =
security_service.get_password_hash(user.password) and pass role=UserRole.USER
into DomainUserCreate so self-registered accounts cannot set elevated roles.

In `@backend/app/db/repositories/user_repository.py`:
- Around line 21-24: The DuplicateKeyError catch in the doc.insert() flow
currently always raises ConflictError("Email already registered"), which
mislabels non-email unique violations; modify the except block for
DuplicateKeyError to inspect e.details (or e.args) to determine the conflicting
key (e.g., check for "email", "username", "user_id" in the error detail) and
raise a contextual ConflictError like "Email already registered" or "Username
already registered" accordingly, falling back to a generic "User already exists"
if the key can't be determined; keep the original exception as the cause (raise
... from e) and update any tests that assert the exact message in
UserDocument-related operations.

Copy link

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 3 files

Prompt for AI agents (all issues)

Check if these issues are valid — if so, understand the root cause of each and fix them.


<file name="backend/app/db/repositories/user_repository.py">

<violation number="1" location="backend/app/db/repositories/user_repository.py:24">
P3: DuplicateKeyError can be raised for unique username or user_id as well as email, so always returning "Email already registered" can mislead clients. Use a generic conflict message or detect which field is duplicated.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
docs/reference/openapi.json (1)

16017-16090: ⚠️ Potential issue | 🟡 Minor

Document is_superuser as legacy; role is the source of truth.

The backend always returns role, is_active, and is_superuser as required fields in UserResponse. However, is_superuser is always initialized to false and never modified in the service layer—authorization decisions should use role (UserRole enum) instead. Add documentation to clarify this legacy field and guide clients to prefer role.

✍️ Recommended documentation clarification
           "is_superuser": {
             "type": "boolean",
-            "title": "Is Superuser"
+            "title": "Is Superuser",
+            "description": "Legacy field; always false. Use `role` for authorization decisions."
           },
🧹 Nitpick comments (2)
frontend/src/stores/auth.svelte.ts (1)

219-219: CSRF cookie value may need decodeURIComponent.

The regex extracts the raw cookie value, but cookie values can be URI-encoded. If the CSRF token ever contains characters like =, %, or ;, the raw match won't give you the correct value.

Suggested fix
-                this.csrfToken = document.cookie.match(/(?:^|;\s*)csrf_token=([^;]*)/)?.[1] ?? null;
+                const rawCsrf = document.cookie.match(/(?:^|;\s*)csrf_token=([^;]*)/)?.[1];
+                this.csrfToken = rawCsrf ? decodeURIComponent(rawCsrf) : null;
frontend/src/stores/__tests__/auth.test.ts (1)

241-304: Consider adding a test for CSRF cookie extraction in verifyAuth.

The verifyAuth method now reads csrfToken from document.cookie (Line 219 of auth.svelte.ts) instead of from the API response. None of the existing tests verify that authStore.csrfToken is correctly set after verifyAuth succeeds. A test that sets document.cookie with a csrf_token value and asserts authStore.csrfToken after verification would close this gap.

…ger, extra endpoint isnt used at all

- also register endpoint fix (instead of calling register with role allowing default users to create admins, - letting only admins in admin/users do it, also fix for conftest setting admin for CI tests)
…o removed uncalled endpoints and tests for them

+ regen of types+openapi spec
@sonarqubecloud
Copy link

sonarqubecloud bot commented Feb 9, 2026

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant