Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions apps/chat/serializers/chat_authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@
from portal.models import Portal


def _is_license_valid():
"""判断当前 license 是否有效;专业版、企业版据此展示授权相关能力。"""
license_validator = DatabaseModelManage.get_model("license_is_valid") or (lambda: False)
return bool(license_validator())


class AnonymousAuthenticationSerializer(serializers.Serializer):
access_token = serializers.CharField(required=False, label=_("access_token"))

Expand Down Expand Up @@ -93,6 +99,7 @@ def profile(self):
else {"theme_color": "", "header_font_color": ""},
"logo": application_access_token.application.icon,
"edition": edition,
"license_is_valid": _is_license_valid(),
"meta": {
"application_name": application_access_token.application.name,
"application_id": str(application_access_token.application_id),
Expand Down Expand Up @@ -126,6 +133,7 @@ def profile():
"meta": {"portal_name": ""},
"logo": "./favicon.ico",
"edition": edition,
"license_is_valid": _is_license_valid(),
"language": "zh-CN",
},
**result,
Expand All @@ -143,6 +151,7 @@ def profile():
"meta": {"portal_name": portal.name},
"logo": portal.logo or "./favicon.ico",
"edition": edition,
"license_is_valid": _is_license_valid(),
"language": "zh-CN",
},
**result,

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The added helper and response field are reasonable, but there are a few robustness and performance concerns.

Potential issues

  1. The fallback only handles missing/falsy values

    DatabaseModelManage.get_model("license_is_valid") or (lambda: False)

    This works if the lookup returns None, but it does not handle:

    • get_model() raising an exception
    • a truthy but non-callable value
    • a validator that itself raises

    If the lookup returns a model class instead of a zero-argument validator function, validator() may create a model instance, and bool(instance) may be True even when the license is invalid. Validate that the result is callable.

  2. No exception handling
    If the license validator raises, the entire profile endpoint will fail with a 500. A licensing check should usually fail closed but not crash the profile response:

    try:
        ...
    except Exception:
        logger.exception("Failed to validate license")
        return False
  3. Repeated evaluation / performance
    _is_license_valid() may hit the database or a license service. It is called in several response branches. Even if only one branch runs per request, computing it once and reusing the value is cleaner. If the profile endpoint is high-traffic, consider a short-lived cache with explicit invalidation when the license changes.

  4. Boolean contract is ambiguous
    bool(validator()) treats "False" as True. Make sure the registered license_is_valid callable is contractually required to return a real boolean, or explicitly check:

    return validator() is True

    Use this only if the validator is guaranteed to return True/False.

  5. Silent failure may hide misconfiguration
    Returning False when the validator is missing is probably acceptable, but log a warning so missing plugin/configuration issues are visible.

  6. Security / authorization
    license_is_valid in the profile response should be treated as UI metadata only. Do not rely on the client-side flag to enable licensed functionality; enforce license checks server-side. Also confirm that exposing license status in anonymous/portal profiles is intended.

  7. Check all profile response paths
    Ensure every profile response shape includes license_is_valid. If some branches omit it, the frontend may see inconsistent data. Also confirm edition and license_is_valid cannot contradict each other.

  8. Existing context line looks syntactically invalid
    This line in the diff context looks incomplete:

    access_token = [API_KEY], label=_("access_token"))

    If that is literal code, it will not parse. It may just be truncated diff context, but it is worth verifying.

Suggested implementation

import logging

logger = logging.getLogger(__name__)


def _is_license_valid():
    """Return whether the current license is valid.

    Fail closed, but do not let license-check failures break profile responses.
    """
    try:
        validator = DatabaseModelManage.get_model("license_is_valid")
        if not callable(validator):
            logger.warning("license_is_valid validator is missing or not callable")
            return False
        return bool(validator())
    except Exception:
        logger.exception("Failed to validate license")
        return False

Then compute once per profile request:

license_is_valid = _is_license_valid()

...
"license_is_valid": license_is_valid,

If _is_license_valid() is expensive and the license changes rarely, add a short TTL cache or invalidate the cache when the license is updated. Avoid an indefinitely cached boolean unless you have reliable invalidation.

Also add tests for:

  • missing validator
  • validator raising an exception
  • invalid license
  • valid license
  • anonymous / portal profile responses
  • all profile response branches containing the field.

Expand Down
2 changes: 2 additions & 0 deletions ui/src/api/types/chat-auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ export interface AuthProfile<Meta = Record<string, never>> {
logo: string
custom_theme?: { theme_color?: string; header_font_color?: string } | null
edition?: string
/** 当前 license 是否有效;专业版、企业版据此判断授权相关能力。 */
license_is_valid?: boolean
meta: Meta
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Verdict: The added field is syntactically valid and backward-compatible. No performance concern. The main risks are semantic/security-related.

Potential issues

  1. Optional boolean creates three states
    license_is_valid?: boolean means true, false, or undefined. Define what undefined means and fail closed. Prefer explicit checks:

    const hasValidLicense = profile.license_is_valid === true

    Avoid enabling paid features with a truthiness check that might treat unknown/missing data unexpectedly.

  2. API contract ambiguity
    If the backend always returns this field, make it required:

    license_is_valid: boolean

    If it can be missing or null, document that and normalize it. With exactOptionalPropertyTypes, assigning undefined explicitly has additional restrictions. If the API can return null, the type should be boolean | null or normalized before use.

  3. Security concern
    Do not use a client-provided license_is_valid flag as the only enforcement for professional/enterprise features. Server-side enforcement is still required. Also consider license expiry, refresh, and stale cached profiles.

  4. Possible conflict with edition
    edition?: string and license_is_valid?: boolean can disagree, e.g. edition: "enterprise" with license_is_valid: false. Define the invariant and source of truth. If more states are needed later, consider a status enum instead of a boolean.

  5. Naming/comment consistency
    license_is_valid matches the existing snake_case style (custom_theme, header_font_color), so it is consistent. Boolean predicates are also often named is_license_valid, but consistency matters more. The Chinese comment is fine if the repository uses Chinese comments; otherwise translate it for consistency.

Suggested comment

/** Whether the current license is valid. Missing/undefined must be treated as invalid. */
license_is_valid?: boolean

Tests to add

  • license_is_valid: true
  • license_is_valid: false
  • license_is_valid: undefined / missing
  • license_is_valid: null if possible from API
  • Old backend that does not return the field
  • Expired/stale license and API failure cases

Overall: no syntax issue; just clarify optionality, default behavior, and server-side enforcement.

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ const goLogin = () => {
<div class="truncate text-N600" :title="account?.username">{{ account?.username || '-' }}</div>
</div>
</div>
<template v-if="!auth.isCE">
<template v-if="auth.isPE || auth.isEE">
<div class="mb-1 flex-align-center">
<span class="mr-3">Tokens</span>
<span class="font-medium">{{ formatTokenNumber(account?.token_quota?.used_tokens ?? 0) }}</span>
Expand Down
6 changes: 4 additions & 2 deletions ui/src/stores/chat/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,10 @@ export const useChatAuthStore = defineStore('chat-auth', {
if (isPortalScope(state.scope)) return undefined
return (state.authProfile?.meta as ApplicationAuthProfileMeta | undefined)?.application_id
},
/** 社区版 */
isCE: (state) => state.authProfile?.edition === 'CE',
/** 专业版 */
isPE: (state) => state.authProfile?.edition === 'PE' && Boolean(state.authProfile.license_is_valid),
/** 企业版 */
isEE: (state) => state.authProfile?.edition === 'EE' && Boolean(state.authProfile.license_is_valid),
},

actions: {

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

No syntax error in the diff, but there are a few important issues and improvements.

Potential issues

  1. Removing isCE is a breaking change

    • Any component/test using store.isCE will now get undefined.
    • Run a search like rg "isCE" and update all usages, or keep isCE for compatibility:
      isCE: (state) => state.authProfile?.edition === 'CE',
  2. Unsafe/inconsistent authProfile access

    • This is runtime-safe because of && short-circuiting:
      state.authProfile?.edition === 'PE' && Boolean(state.authProfile.license_is_valid)
    • But the second access should also use optional chaining for consistency and to avoid TypeScript/refactor risk:
      Boolean(state.authProfile?.license_is_valid)
  3. Boolean() may hide bad API data

    • If license_is_valid can ever be a string such as "false", Boolean("false") is true.
    • Prefer strict boolean checks if the field is typed as boolean:
      state.authProfile?.license_is_valid === true
    • If the backend returns strings/numbers, normalize the value at the API boundary.
  4. Edition and license validation are conflated

    • isPE/isEE now mean “is PE/EE and licensed”, not just “is PE/EE”.
    • That can be misleading. If the UI needs to distinguish “PE but invalid license” from “CE”, add separate getters:
      isPE: (state) => state.authProfile?.edition === 'PE',
      isEE: (state) => state.authProfile?.edition === 'EE',
      hasValidLicense: (state) => state.authProfile?.license_is_valid === true,
      Then derive licensed states as needed.
  5. No explicit CE/unknown fallback

    • If edition is CE, undefined, or unknown, both isPE and isEE are false.
    • If the UI expects exactly one edition flag to be true, add an explicit isCE or handle the unknown/loading state separately.

Suggested refactor

const hasValidLicense = (state) =>
  state.authProfile?.license_is_valid === true

export const useChatAuthStore = defineStore('chat-auth', {
  // ...
  getters: {
    isCE: (state) => state.authProfile?.edition === 'CE',
    isPE: (state) =>
      state.authProfile?.edition === 'PE' && hasValidLicense(state),
    isEE: (state) =>
      state.authProfile?.edition === 'EE' && hasValidLicense(state),
  },
})

Add the correct state type to hasValidLicense in real TypeScript code. The main fixes are: keep or migrate isCE, use optional chaining consistently, and prefer === true over Boolean() unless the value is guaranteed to be boolean/coercible.

Expand Down
Loading