Back to skill

Security audit

Smart Cache

Security checks for vulnerabilities and agentic risk

Overview

The skill mostly matches its cache purpose, but it stores AI prompts locally and has optional network features that can expose cached data or API keys without enough safeguards.

Review this before installing if you handle secrets, private prompts, or regulated data. Use a local-only configuration where possible, avoid storing sensitive prompts, do not expose HTTP mode beyond localhost without authentication, and configure provider-specific API keys carefully because the current OpenAI path may reuse a DashScope key.

Vulnerability Patterns
  • Unauthorized Access and Privilege EscalationObtains permissions beyond the task's legitimate needs
  • Insecure Skill Coding PracticesFinds exploitable flaws such as hardcoded secrets or command injection
  • Skill Instruction HijackingAlters the agent's session goals or safety constraints when the skill loads
  • Agent Memory PoisoningWrites attacker-controlled rules into memory that affect later sessions
  • Remote Payload Retrieval and ExecutionFetches external code whose behavior can change after review
Findings (2)

T09 · Insecure Skill Coding Practices

Warning
Location
scripts/embeddings.py:29
Finding

Cross-Provider API Credential Disclosure

Content
View full analysis

Vulnerability Details

File Location: scripts/embeddings.py, lines 29-100
Vulnerability Type: Cross-provider credential confusion and sensitive credential disclosure
Risk Level: Medium

Vulnerable Code

python
def get_api_key() -> Optional[str]:
    api_key = os.environ.get("OPENAI_API_KEY") or os.environ.get("DASHSCOPE_API_KEY")
    if api_key:
        return api_key

    config_path = Path.home() / ".qclaw" / "smart-cache" / "config.json"
    if config_path.exists():
        with open(config_path, 'r', encoding='utf-8') as f:
            config = json.load(f)
            return config.get("api_key") or config.get("openai_api_key")

    return None
python
class OpenAIEmbeddings(EmbeddingsProvider):
    def __init__(self, api_key: Optional[str] = None, model: str = "text-embedding-3-small"):
        self.api_key = api_key or get_api_key()
        self.model = model

    def get_embeddings(self, texts: List[str]) -> Optional[List[List[float]]]:
        import urllib.request
        import urllib.error

        url = "https://api.openai.com/v1/embeddings"

        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.api_key}"
        }

        data = {
            "model": self.model,
            "input": texts
        }

Technical Analysis

The OpenAI provider uses the provider-agnostic get_api_key() function. That function returns OPENAI_API_KEY when available, but silently falls back to DASHSCOPE_API_KEY. The selected credential is subsequently placed in a bearer authorization header and transmitted to the OpenAI API.

Credentials for separate providers represent distinct trust boundaries. An OpenAI request should only access an explicitly configured OpenAI credential. Falling back to a DashScope credential exceeds the minimum credential privileges required by the selected provider and disclos ...[truncated 1546 chars]

Remediation
View remediation

Remediation Suggestions

  1. Resolve credentials separately for each provider:
    • OpenAI must read only OPENAI_API_KEY or an OpenAI-specific configuration field.
    • DashScope must read only DASHSCOPE_API_KEY or a DashScope-specific configuration field.
  2. Replace the generic configuration field with provider-bound fields such as openai_api_key and dashscope_api_key.
  3. If a generic credential must remain for compatibility, require an explicit matching embedding_provider value before using it.
  4. Fail closed when the selected provider's credential is unavailable rather than falling back to another provider's credential.
  5. Add tests confirming that OpenAIEmbeddings never consumes DASHSCOPE_API_KEY and that DashScopeEmbeddings never consumes OPENAI_API_KEY.
  6. Avoid printing credentials. The existing command that displays the final four characters should also be reconsidered for shared terminal logs.

T05 · Unauthorized Access and Privilege Escalation

Warning
Location
scripts/mcp_server.py:340
Finding

Unauthenticated HTTP MCP Interface Allows Cache Disclosure, Poisoning, and Deletion

Content
View full analysis

Vulnerability Details

File Location: scripts/mcp_server.py, lines 340-425
Vulnerability Type: Missing authentication and authorization on sensitive HTTP operations
Risk Level: Medium

Vulnerable Code

python
class MCPHandler(BaseHTTPRequestHandler):
    def do_POST(self):
        content_length = int(self.headers.get('Content-Length', 0))
        body = self.rfile.read(content_length).decode('utf-8')
        request = json.loads(body)

        try:
            method = self.path.strip('/')
            params = json.loads(request.get('params', '{}'))

            if method == "initialize":
                result = server.handle_initialize(params)
            elif method == "tools/list":
                result = server.handle_tools_list(params)
            elif method == "tools/call":
                result = server.handle_tools_call(params)
            else:
                raise ValueError(f"Unknown method: {method}")

            response = protocol.build_response(result)

        except Exception as e:
            response = protocol.build_response(error=str(e))

        self.send_response(200)
        self.send_header('Content-Type', 'application/json')
        self.end_headers()
        self.wfile.write(json.dumps(response, ensure_ascii=False).encode())
python
httpd = HTTPServer((host, port), MCPHandler)
httpd.serve_forever()
python
parser.add_argument(
    "--host",
    default="localhost",
    help="HTTP server listening address"
)

The unauthenticated tools/call route reaches operations including:

python
elif name == "cache_store":
    success = self.cache.store(
        args["query"],
        args["response"],
        tokens=args.get("tokens", 0),
        cache_type=args.get("cache_type", "both")
    )
    return {"success": success}

elif name == "cache_clean":
    mode = args.get("mode", "expired")

...[truncated 2799 chars]
Remediation
View remediation

Remediation Suggestions

  1. Enforce loopback-only binding unless secure authentication is explicitly configured.
  2. Require authentication for every HTTP MCP request, using a securely generated token, mutual TLS, or an authenticated reverse proxy.
  3. Implement authorization boundaries:
    • Permit cache queries only to authorized clients.
    • Require elevated administrative authorization for cache_store.
    • Require separate administrative authorization and explicit confirmation for cache_clean with mode: all.
  4. Add a strict maximum request-body size before reading from self.rfile.
  5. Add rate limiting and quotas for queries, writes, and destructive operations.
  6. Validate all tool arguments, including threshold ranges, token values, cache types, and cleanup modes.
  7. Use TLS whenever the interface is accessible beyond the local host.
  8. Document that external binding is unsafe without authentication and transport protection.
  9. Consider removing HTTP mode if stdio mode satisfies the intended integration requirements.
Vulnerability Patterns
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • Excessive AgencyUnrestricted Tool Access, Autonomous Decision Making, Scope Creep
  • MCP Least PrivilegeUnderdeclared Capability, Wildcard Permission, Missing Permission Declaration
  • MCP Tool PoisoningHidden Instructions, Unicode Deception, Parameter Description Injection
  • Prompt InjectionInstruction Override, Hidden Instructions, Exfiltration Commands
Findings (22)

Tp4

High
Category
MCP Tool Poisoning
Confidence
99% confidence
Finding

声明描述的是一个具有明确缓存功能的实用技能,但实际代码只是示例/占位内容,仅输出字符串,不具备所宣称的核心能力。虽然代码没有表现出额外的未声明危险能力,但其主要用途与声明严重不符,因此应判定为描述与行为不匹配。

Content

No source excerpt is available for this finding.

Undeclared Tool Scope

Medium
Category
MCP Least Privilege
Confidence
91% confidence
Finding

The skill documents capabilities that imply file access, environment-variable access, and network/API use, but it does not declare any tool scope or permissions boundaries. This weakens reviewability and can cause a host agent to grant broader access than users expect, especially because the skill also mentions local data storage and external embedding providers.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The documented clean --all command irreversibly deletes all cached data, but the documentation does not flag it as destructive. This increases the risk of accidental data loss, especially in an automation or copy-paste workflow where users may not realize the command removes all locally stored responses and statistics.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
93% confidence
Finding

The semantic-cache workflow states that query text is converted to embeddings using third-party providers, which means user content may be sent externally. Without a prominent privacy and data-transmission warning, users may unknowingly expose sensitive prompts, cached context, or regulated data.

Content

No source excerpt is available for this finding.

Description-Behavior Mismatch

Medium
Category
Not specified by scanner
Confidence
88% confidence
Finding

The skill is presented as a local cache system, but it also documents HTTP server operation and external embedding API usage. That expands the attack surface beyond a local utility: an HTTP service can expose cached data remotely, and external embedding calls can transmit user prompts off-device.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
90% confidence
Finding

The file's docstrings, examples, comments, and sample I/O are presented entirely in Chinese, which imposes a specific language context without any opt-in or explanation that the skill is region-specific. Under the stated policy, locale or language constraints should either be optional or clearly justified.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The cache persists raw user queries and model responses under a predictable local path in the user's home directory, which can capture sensitive prompts, secrets, and private outputs without any built-in disclosure, consent flow, minimization, or protection. In an AI assistant context, cached content often includes credentials, personal data, or proprietary business information, so silent disk persistence materially increases confidentiality risk on shared or compromised systems.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
90% confidence
Finding

The l2_cache table includes a query_embedding BLOB column, reinforcing the documented claim of semantic caching. But no code writes to or reads from query_embedding; instead, L2 matching scans raw queries and compares them with character n-grams, so the code's structure contradicts the implied embedding-based intent.

Content

No source excerpt is available for this finding.

Intent-Code Divergence

Medium
Category
Not specified by scanner
Confidence
96% confidence
Finding

The manifest and docstrings describe L2 as 语义/semantic matching, which implies meaning-based similarity. However, L150-L166 implements only character bigram Jaccard similarity, and L293-L295 uses that directly for matching; this is a lexical similarity heuristic rather than true semantic caching.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
94% confidence
Finding

The tool stores raw user queries and model responses in a local SQLite database under the user's home directory with no consent flow, warning, redaction, or encryption. Because prompts and responses often contain secrets, personal data, or proprietary content, this creates a real confidentiality risk if the local machine, account, backups, or developer tooling accesses the cache file.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
96% confidence
Finding

clean_all() deletes all rows from both cache tables, which is an irreversible destructive action. The CLI prints only a success message after deletion and does not require confirmation or provide a prior warning beyond the terse command name/help text.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
91% confidence
Finding

This code sends raw input texts to the OpenAI embeddings API, which is an external third-party service. In a caching skill, those texts may contain sensitive prompts, user data, or internal context, so transmitting them without explicit disclosure/consent creates a real privacy and data-handling risk even though the network behavior is functionally intended.

Content

No source excerpt is available for this finding.

External Transmission

Medium
Category
Data Exfiltration
Confidence
60% confidence
Finding

Data is being sent to an external URL. This could be legitimate telemetry or data exfiltration. Manual review is recommended.

Content

Scanner excerpt · scripts/embeddings.py (reported line 95)May include surrounding context.

python
import urllib.request
        import urllib.error

        url = "https://api.openai.com/v1/embeddings"

        headers = {
            "Content-Type": "application/json",

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
91% confidence
Finding

This code transmits input texts to DashScope's remote embedding endpoint without any explicit warning, consent flow, or sensitivity checks. Because the skill is a semantic cache, it is especially likely to process arbitrary user prompts and assistant context, which can include confidential material that should not be silently sent to an external API.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
86% confidence
Finding

The cache_clean tool allows deletion of expired entries or all cached data with no confirmation, safeguard, or role check. In an MCP or HTTP context, a mistaken call or unauthorized caller could wipe useful cached state and reduce service reliability, and in HTTP mode this becomes more concerning because the destructive operation is remotely reachable.

Content

No source excerpt is available for this finding.

Description-Behavior Mismatch

Medium
Category
Not specified by scanner
Confidence
91% confidence
Finding

The skill adds an HTTP server mode that exposes cache query, storage, statistics, and cleaning operations over a network-accessible interface, which expands the attack surface beyond the stated local-cache purpose. Even though it defaults to localhost, host and port are configurable and there is no authentication, authorization, or transport protection, so accidental or intentional exposure can permit unauthorized cache access or deletion.

Content

No source excerpt is available for this finding.

Context-Inappropriate Capability

Medium
Category
Not specified by scanner
Confidence
87% confidence
Finding

Providing an HTTP-accessible service is inconsistent with a local assistant cache skill and creates unnecessary service exposure. This matters because the server exposes state-changing operations such as cache_store and cache_clean without any security boundary, increasing the chance of misuse, data leakage from cached responses, or destructive cache tampering if the interface becomes reachable.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Low
Category
Not specified by scanner
Confidence
84% confidence
Finding

The manifest description forces a specific language presentation without indicating that users may choose another language or that the skill is region-specific. Under the policy rule, a fixed language/locale without opt-in can be a natural-language policy issue.

Content

No source excerpt is available for this finding.

Context-Inappropriate Capability

Low
Category
Not specified by scanner
Confidence
79% confidence
Finding

The manifest presents the skill as a local intelligent cache for reducing repeated AI calls. Accessing environment variables for provider credentials introduces a capability beyond simple local caching and is only indirectly related to the core stated purpose.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Low
Category
Not specified by scanner
Confidence
92% confidence
Finding

Docstrings, CLI descriptions, help text, and status output are consistently written in Chinese, which forces a locale/language assumption on all users. The file does not provide a language-selection mechanism or document that the tool is intentionally limited to a Chinese-speaking context.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Low
Category
Not specified by scanner
Confidence
84% confidence
Finding

The module description, docstrings, error messages, and CLI output are written in Chinese throughout, which effectively constrains user interaction to a single language. There is no opt-in, language selection mechanism, or documented reason that this skill must be Chinese-only.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Low
Category
Not specified by scanner
Confidence
82% confidence
Finding

The module-level description is written only in Chinese and presents the skill behavior in that language, with no indication that users may choose another language or locale. This can violate language/locale policy when a skill implicitly forces a specific language without offering user choice.

Content

No source excerpt is available for this finding.