Skip to content

feat: support 3D-RBAC stateful token authentication#19

Open
SoukNow wants to merge 1 commit into
Go1c:mainfrom
SoukNow:feat/support-3d-rbac-auth
Open

feat: support 3D-RBAC stateful token authentication#19
SoukNow wants to merge 1 commit into
Go1c:mainfrom
SoukNow:feat/support-3d-rbac-auth

Conversation

@SoukNow
Copy link
Copy Markdown

@SoukNow SoukNow commented May 15, 2026

What

Adapt CLI to support the upgraded fast-note-sync-service 3D-RBAC authentication.

Why

The service upgraded from single stateless token to stateful multi-dimensional
(protocol, client, function) validation token, breaking the old auth flow.

Changes

  • Add client/clientName/clientVersion query params to WebSocket URL
  • Enhance ClientInfo message with platform detection fields
  • Add client_type config field (default: fns-cli)
  • Add Docker deployment support (Dockerfile + docker-compose.yml)
  • Update README with new token management instructions and Scope examples
  • Bump version to 0.2.0

Testing

All 46 unit tests pass.

Summary by Sourcery

Add 3D-RBAC-aware client identification and platform metadata to the CLI authentication flow and introduce containerized deployment support.

New Features:

  • Include client identification fields in WebSocket connections and client info messages for 3D-RBAC token authentication.
  • Add configurable client_type option to the CLI configuration.
  • Provide Docker and docker-compose definitions for running the CLI in a containerized environment.

Enhancements:

  • Enrich client info payload with platform and device flags derived from the runtime environment.
  • Bump CLI version to 0.2.0.

Documentation:

  • Update README and example config to document JWT-based token management, scopes, and the new client_type setting.

Tests:

  • Adjust client tests to cover the new client_type configuration field.

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented May 15, 2026

Reviewer's Guide

Adds 3D-RBAC-compatible, stateful token authentication support to the CLI by extending client configuration and WebSocket handshake metadata, updates docs for JWT token/scopes, and introduces Docker-based deployment artifacts alongside a minor version bump.

Sequence diagram for WebSocket auth handshake with 3D-RBAC metadata

sequenceDiagram
    participant CLI as FnsCliClient
    participant Service as FastNoteSyncService

    CLI->>Service: WebSocket connect /api/user/sync?lang=zh-cn&count&client&clientName&clientVersion
    Service-->>CLI: [auth response]
    CLI->>CLI: _on_auth_response(msg)
    CLI->>Service: _raw_send(WSMessage ACTION_CLIENT_INFO {name,version,type,isDesktop,isMobile,...})
    CLI->>Service: _flush_queue()
Loading

File-Level Changes

Change Details Files
Include 3D-RBAC client metadata in WebSocket connections and client info messages.
  • Append client type, client name, and client version as query parameters on the WebSocket URL when connecting.
  • Populate ClientInfo payload with dynamic version, configurable client type, and platform detection flags (desktop vs. OS booleans) during auth response handling.
  • Wire the package version into the client module to avoid hard-coded version strings.
fns_cli/client.py
fns_cli/__init__.py
tests/test_client.py
Extend client configuration to support a configurable client type for authentication.
  • Add client_type field with default value to ClientConfig dataclass.
  • Load client_type from config.yaml when present, falling back to the default.
  • Update example config.yaml and test configuration factory to include client_type.
fns_cli/config.py
config.yaml
tests/test_client.py
Document new JWT-based token management and 3D-RBAC scopes for the CLI.
  • Clarify that the token is now a JWT obtained from the Token Management panel rather than a generic API token.
  • Describe the token creation flow in the web UI, including client type, scopes, and expiry configuration.
  • Provide example scopes for common use cases and update environment variable docs to reference JWT tokens.
README.md
Add Docker-based deployment support for the CLI.
  • Introduce a Dockerfile that installs dependencies, copies CLI code, defines volumes for config and vault, and sets the module entrypoint and default command.
  • Add a docker-compose.yml service that builds the image, mounts config and vault directories, and exposes environment variable overrides.
  • Create a .dockerignore file to control the Docker build context (file contents not shown in diff).
Dockerfile
docker-compose.yml
.dockerignore
Bump CLI version to reflect the new authentication and deployment features.
  • Increment package version from 0.1.0 to 0.2.0 and ensure it is used consistently across the codebase.
fns_cli/__init__.py
fns_cli/client.py

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Copy Markdown

@sourcery-ai sourcery-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.

Hey - I've found 3 issues, and left some high level feedback:

  • In client.py you added platform flags using sys.platform but there is no corresponding import sys in the file, which will cause a runtime error when sending ClientInfo.
  • You now have both a configurable client_type and a hard-coded clientName=FastNodeSync-CLI in the WebSocket URL; consider deriving clientName (and possibly the ClientInfo.name) from the config to avoid mismatches when users change client_type.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `client.py` you added platform flags using `sys.platform` but there is no corresponding `import sys` in the file, which will cause a runtime error when sending `ClientInfo`.
- You now have both a configurable `client_type` and a hard-coded `clientName=FastNodeSync-CLI` in the WebSocket URL; consider deriving `clientName` (and possibly the `ClientInfo.name`) from the config to avoid mismatches when users change `client_type`.

## Individual Comments

### Comment 1
<location path="Dockerfile" line_range="1-10" />
<code_context>
+FROM python:3.13-slim
+
+WORKDIR /app
+
+# Install dependencies first for better layer caching
+COPY requirements.txt .
+RUN pip install --no-cache-dir -r requirements.txt
+
+# Copy application code
+COPY fns_cli/ ./fns_cli/
+
+# Default config mount point
+VOLUME ["/app/config", "/app/vault"]
+
+ENV PYTHONUNBUFFERED=1
+
+ENTRYPOINT ["python", "-m", "fns_cli.main"]
+CMD ["run", "-c", "/app/config/config.yaml"]
</code_context>
<issue_to_address>
**🚨 issue (security):** The container runs as root; consider adding a non-root user for improved security.

Running the container as `root` amplifies the impact of any compromise of the CLI or its dependencies. Please add a dedicated non-root user (e.g., `fns`), `chown` `/app`, `/app/config`, and `/app/vault` to that user, and switch to it with `USER`. This usually needs no code changes and significantly reduces risk.
</issue_to_address>

### Comment 2
<location path="tests/test_client.py" line_range="24" />
<code_context>
     config = MagicMock()
     config.client.reconnect_base_delay = 1
     config.client.reconnect_max_retries = 3
+    config.client.client_type = "fns-cli"
     config.server.token = "token"
     config.ws_api = "wss://example.com"
</code_context>
<issue_to_address>
**suggestion (testing):** Add tests to verify the new WebSocket URL query parameters (`client`, `clientName`, `clientVersion`).

Right now the tests only set `config.client.client_type` but never verify that `_connect` (or its public entrypoint) actually uses these values. Please add/extend a test that drives a real connection attempt and asserts that the final WebSocket URL includes:
- `client=fns-cli` (or the configured value)
- `clientName=FastNodeSync-CLI`
- `clientVersion` equal to `fns_cli.__version__`.

This will guard against regressions in URL construction for the new query parameters.

Suggested implementation:

```python
    config = MagicMock()
    config.client.reconnect_base_delay = 1
    config.client.reconnect_max_retries = 3
    config.client.client_type = "fns-cli"
    config.server.token = "token"
    config.ws_api = "wss://example.com"
    return config


def test_websocket_url_includes_client_query_params(mocker):
    from urllib.parse import urlparse, parse_qs
    import fns_cli

    # Arrange
    config = _make_config()  # adjust to the actual helper/factory name if different
    client = FastNodeSyncClient(config)  # adjust to the actual client class under test

    # Patch the websocket connect function used by the client to initiate connections
    mock_connect = mocker.patch(
        "fns_cli.client.websocket.connect", autospec=True
    )  # adjust import path to match implementation

    # Act: trigger a connection attempt (use the public entrypoint if available)
    client._connect()  # or client.connect(), depending on what is exposed

    # Assert: inspect the URL used for the WebSocket connection
    called_url = mock_connect.call_args[0][0]
    parsed = urlparse(called_url)
    qs = parse_qs(parsed.query)

    assert qs["client"] == [config.client.client_type]
    assert qs["clientName"] == ["FastNodeSync-CLI"]
    assert qs["clientVersion"] == [fns_cli.__version__]

```

To integrate this test with the existing codebase, you will likely need to:

1. Replace `_make_config()` with the actual helper/fixture used to construct the `config` `MagicMock`. If this is a pytest fixture (e.g. `config`), change the test signature to accept it instead of calling a function.
2. Replace `FastNodeSyncClient` with the actual client class name being tested (for example, `WebsocketClient` or similar).
3. Adjust the `mocker.patch` target `"fns_cli.client.websocket.connect"` to point to the exact function used by your `_connect` implementation (e.g. `"fns_cli.client._websocket_connect"` or `"fns_cli.client.websocket.WebSocketApp"`), and adapt how you extract the URL from `call_args` if the signature differs.
4. Prefer calling the public entrypoint used to start a connection (e.g. `client.connect()` or `client.start()`) instead of `client._connect()` if such a method exists, so the test remains resilient to internal refactors.
5. If your code constructs the WebSocket URL in a separate helper, ensure this test exercises that same path (not a duplicated or test-only code path).
</issue_to_address>

### Comment 3
<location path="README.md" line_range="97" />
<code_context>

 **How to obtain a token**

+> **Note:** Since service version with 3D-RBAC, tokens are now JWT-based and managed via the web UI.
+
 1. Open the Fast Note Sync Service web UI (e.g. `https://your-server-address`)
</code_context>
<issue_to_address>
**suggestion (typo):** Consider adding an article before "service version" for grammatical correctness.

The wording "Since service version with 3D-RBAC" is ungrammatical. Consider revising to "Since the service version with 3D-RBAC" or "Since the 3D-RBAC-enabled service version" to improve clarity.

```suggestion
> **Note:** Since the 3D-RBAC-enabled service version, tokens are now JWT-based and managed via the web UI.
```
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment thread Dockerfile
Comment on lines +1 to +10
FROM python:3.13-slim

WORKDIR /app

# Install dependencies first for better layer caching
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy application code
COPY fns_cli/ ./fns_cli/
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🚨 issue (security): The container runs as root; consider adding a non-root user for improved security.

Running the container as root amplifies the impact of any compromise of the CLI or its dependencies. Please add a dedicated non-root user (e.g., fns), chown /app, /app/config, and /app/vault to that user, and switch to it with USER. This usually needs no code changes and significantly reduces risk.

Comment thread tests/test_client.py
config = MagicMock()
config.client.reconnect_base_delay = 1
config.client.reconnect_max_retries = 3
config.client.client_type = "fns-cli"
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion (testing): Add tests to verify the new WebSocket URL query parameters (client, clientName, clientVersion).

Right now the tests only set config.client.client_type but never verify that _connect (or its public entrypoint) actually uses these values. Please add/extend a test that drives a real connection attempt and asserts that the final WebSocket URL includes:

  • client=fns-cli (or the configured value)
  • clientName=FastNodeSync-CLI
  • clientVersion equal to fns_cli.__version__.

This will guard against regressions in URL construction for the new query parameters.

Suggested implementation:

    config = MagicMock()
    config.client.reconnect_base_delay = 1
    config.client.reconnect_max_retries = 3
    config.client.client_type = "fns-cli"
    config.server.token = "token"
    config.ws_api = "wss://example.com"
    return config


def test_websocket_url_includes_client_query_params(mocker):
    from urllib.parse import urlparse, parse_qs
    import fns_cli

    # Arrange
    config = _make_config()  # adjust to the actual helper/factory name if different
    client = FastNodeSyncClient(config)  # adjust to the actual client class under test

    # Patch the websocket connect function used by the client to initiate connections
    mock_connect = mocker.patch(
        "fns_cli.client.websocket.connect", autospec=True
    )  # adjust import path to match implementation

    # Act: trigger a connection attempt (use the public entrypoint if available)
    client._connect()  # or client.connect(), depending on what is exposed

    # Assert: inspect the URL used for the WebSocket connection
    called_url = mock_connect.call_args[0][0]
    parsed = urlparse(called_url)
    qs = parse_qs(parsed.query)

    assert qs["client"] == [config.client.client_type]
    assert qs["clientName"] == ["FastNodeSync-CLI"]
    assert qs["clientVersion"] == [fns_cli.__version__]

To integrate this test with the existing codebase, you will likely need to:

  1. Replace _make_config() with the actual helper/fixture used to construct the config MagicMock. If this is a pytest fixture (e.g. config), change the test signature to accept it instead of calling a function.
  2. Replace FastNodeSyncClient with the actual client class name being tested (for example, WebsocketClient or similar).
  3. Adjust the mocker.patch target "fns_cli.client.websocket.connect" to point to the exact function used by your _connect implementation (e.g. "fns_cli.client._websocket_connect" or "fns_cli.client.websocket.WebSocketApp"), and adapt how you extract the URL from call_args if the signature differs.
  4. Prefer calling the public entrypoint used to start a connection (e.g. client.connect() or client.start()) instead of client._connect() if such a method exists, so the test remains resilient to internal refactors.
  5. If your code constructs the WebSocket URL in a separate helper, ensure this test exercises that same path (not a duplicated or test-only code path).

Comment thread README.md

**How to obtain a token**

> **Note:** Since service version with 3D-RBAC, tokens are now JWT-based and managed via the web UI.
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

suggestion (typo): Consider adding an article before "service version" for grammatical correctness.

The wording "Since service version with 3D-RBAC" is ungrammatical. Consider revising to "Since the service version with 3D-RBAC" or "Since the 3D-RBAC-enabled service version" to improve clarity.

Suggested change
> **Note:** Since service version with 3D-RBAC, tokens are now JWT-based and managed via the web UI.
> **Note:** Since the 3D-RBAC-enabled service version, tokens are now JWT-based and managed via the web UI.

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