Back to skill

Security audit

Spotify Playlist Builder

Security checks for vulnerabilities and agentic risk

Overview

This Spotify skill is purpose-aligned, but it handles OAuth secrets and account-changing actions in ways users should review before installing.

Review this before installing if you care about Spotify account privacy. It can store reusable Spotify credentials locally, read listening history/profile data, and modify playlists. Prefer a version that uses safer secret storage or PKCE, avoids printing tokens, removes unused scopes, and asks for confirmation before playlist changes.

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 (4)

T09 · Insecure Skill Coding Practices

Warning
Location
scripts/auth.py:86
Finding
Spotify access token disclosed through standard output<![CDATA[ ## Vulnerability Details **File Location**: `scripts/auth.py:86-90` **Vulnerability Type**: Sensitive token exposure through process output **Risk Level**: Medium ### Vulnerable Code ```python save_tokens({ "access_token": new_tokens["access_token"], "refresh_token": new_tokens.get("refresh_token", tokens["refresh_token"]), }) print("Token refreshed successfully!") print(json.dumps({"access_token": new_tokens["access_token"]})) ``` ### Technical Analysis The refresh operation prints the newly issued Spotify access token to standard output. In an Agent environment, standard output may be returned to the caller, retained in execution traces, or captured by logging and orchestration systems. Although `scripts/spotify.py` captures the output when it invokes the refresh subprocess internally, `auth.py --refresh` remains directly executable. Consequently, the token can still be exposed to an Agent caller or any system that records command output. An access token is a bearer credential. Anyone who obtains it can use it without also knowing the client secret or refresh token until the access token expires or is revoked. ### Attack Path 1. A user or Agent invokes `python3 scripts/auth.py --refresh`. 2. The script reads the stored refresh token and client credentials. 3. Spotify returns a new access token. 4. The script writes the bearer token to standard output. 5. An Agent caller, command logger, execution trace collector, or other party with access to captured output obtains the token. 6. The party submits the token in an `Authorization: Bearer` header to Spotify APIs. ### Impact Assessment A disclosed access token permits API operations authorized by the token's granted OAuth scopes. In this project, those permissions include reading private playlists, modifying public and private playlists, reading recently played and top-track history, and unnecessarily reading the saved library. The token is time-limited, which c ...[truncated 92 chars]
Remediation
<![CDATA[ ## Remediation Suggestions - Remove the access-token output entirely: ```python print("Token refreshed successfully!") ``` - Keep the refreshed token only in the protected token file. - Return a non-sensitive status value if machine-readable output is required: ```python print(json.dumps({"refreshed": True})) ``` - Ensure Agent execution logs and subprocess diagnostics redact OAuth access tokens. - Revoke and reauthorize affected Spotify credentials if tokens have already been retained in accessible logs. ]]>

T09 · Insecure Skill Coding Practices

Warning
Location
scripts/auth.py:151
Finding
OAuth secrets and authorization codes accepted through command-line arguments<![CDATA[ ## Vulnerability Details **File Location**: `scripts/auth.py:151-155` and `SKILL.md:23-35` **Vulnerability Type**: Sensitive information exposure through process arguments and shell history **Risk Level**: Medium ### Vulnerable Code ```python parser = argparse.ArgumentParser(description="Spotify OAuth") parser.add_argument("--client-id", help="Spotify Client ID") parser.add_argument("--client-secret", help="Spotify Client Secret") parser.add_argument("--refresh", action="store_true", help="Refresh access token") parser.add_argument("--code", help="Authorization code (extracted from URL)") parser.add_argument("--code-url", help="Full callback URL (code extracted automatically)") ``` The documented invocation explicitly places the secret and callback URL on the command line: ```bash python3 scripts/auth.py --client-id <ID> --client-secret <SECRET> ``` ```bash python3 scripts/auth.py --client-id <ID> --client-secret <SECRET> --code-url "<FULL_REDIRECT_URL>" ``` ### Technical Analysis Command-line arguments are not a suitable transport for confidential values. Depending on the operating system and execution environment, arguments may be visible through process inspection, shell history, Agent tool-call records, command auditing, or orchestration logs. The callback URL contains a short-lived OAuth authorization code, while `--client-secret` contains a long-lived application credential. The simultaneous exposure of both values increases the risk that another party can attempt an unauthorized token exchange before the code expires. Exposure of the client secret also remains significant after the authorization code becomes invalid. ### Attack Path 1. A user follows the documented setup command and supplies the client secret as an argument. 2. If manual authorization is needed, the user also supplies the complete callback URL containing the authorization code. 3. The command is retained in shell history, Agent traces, audit log ...[truncated 935 chars]
Remediation
<![CDATA[ ## Remediation Suggestions - Read the client secret from a protected environment variable, secret manager, or interactive prompt using `getpass.getpass()`. - Accept callback URLs or authorization codes through standard input rather than command-line arguments. - Prefer OAuth Authorization Code with PKCE so authorization-code exchange does not depend solely on a reusable client secret. - Update `SKILL.md` so examples do not encourage placing secrets in command lines. - Redact sensitive arguments and callback query parameters from Agent traces and application logs. - Rotate the Spotify client secret if it has already appeared in retained history or logs. ]]>

T09 · Insecure Skill Coding Practices

Warning
Location
scripts/auth.py:95
Finding
Spotify OAuth flow does not validate a state parameter<![CDATA[ ## Vulnerability Details **File Location**: `scripts/auth.py:95-105` and `scripts/auth.py:121-126` **Vulnerability Type**: OAuth authorization-response CSRF and account-binding confusion **Risk Level**: Medium ### Vulnerable Code The authorization URL omits a `state` parameter: ```python def get_auth_url(client_id): return ( "https://accounts.spotify.com/authorize?" + urllib.parse.urlencode({ "client_id": client_id, "response_type": "code", "redirect_uri": REDIRECT_URI, "scope": SCOPES, "show_dialog": "true", }) ) ``` The callback accepts any authorization code without correlating it with the initiated authorization request: ```python def do_GET(self): query = urllib.parse.urlparse(self.path).query params = urllib.parse.parse_qs(query) if "code" in params: code_holder["code"] = params["code"][0] self.send_response(200) self.send_header("Content-Type", "text/html") self.end_headers() ``` ### Technical Analysis OAuth authorization clients should generate a cryptographically random `state` value for each authorization attempt, include it in the authorization request, and require an exact match in the callback. This implementation performs none of those steps. The callback listener trusts any request containing a `code` query parameter. Therefore, the script cannot determine whether the response belongs to the authorization attempt it initiated. Binding the listener to `127.0.0.1` limits remote network access, but it does not provide request correlation. A malicious web page opened in the same browser, a local process, or another mechanism capable of causing a request to the loopback callback may attempt to inject an unrelated authorization response. ### Attack Path 1. The victim starts the authorization script, which opens a listener on `127.0.0.1: ...[truncated 1064 chars]
Remediation
<![CDATA[ ## Remediation Suggestions - Generate a unique state value for every authorization attempt: ```python import secrets state = secrets.token_urlsafe(32) ``` - Include `state` in the Spotify authorization URL. - Retain the expected value only for the lifetime of the authorization attempt. - Require the callback's state value to match using `secrets.compare_digest`. - Reject callbacks with missing, malformed, or mismatched state before processing the code. - Add a callback timeout and stop accepting requests after the first valid response. - Prefer OAuth Authorization Code with PKCE by generating a verifier and sending its challenge during authorization. ]]>

T05 · Unauthorized Access and Privilege Escalation

Note
Location
scripts/auth.py:24
Finding
Unused Spotify saved-library permission violates least privilege<![CDATA[ ## Vulnerability Details **File Location**: `scripts/auth.py:24-27` **Vulnerability Type**: Excessive OAuth scope **Risk Level**: Low ### Vulnerable Code ```python SCOPES = ( "playlist-modify-public playlist-modify-private playlist-read-private " "user-library-read user-read-recently-played user-top-read" ) ``` ### Technical Analysis The Skill requests `user-library-read`, which authorizes access to the user's saved Spotify library. No command in `scripts/spotify.py` reads saved tracks, albums, or other saved-library content. The permission is therefore unnecessary for the declared and implemented operations. Requesting it expands the data available to any party that compromises an access token, contrary to the principle of least privilege. The remaining scopes correspond to implemented functionality: playlist creation and modification, private playlist listing, recently played history, and top-track history. ### Attack Path 1. The user authorizes the complete scope set, including `user-library-read`. 2. An access token is exposed through output, logs, local token-file access, or another compromise. 3. An attacker submits the token to Spotify endpoints authorized by `user-library-read`. 4. The attacker accesses saved-library information that the Skill itself does not need or expose as a command. ### Impact Assessment This issue does not independently disclose data. It increases the blast radius of token compromise by allowing access to the user's saved-library information beyond the minimum privileges necessary for the Skill's implemented functionality. ]]>
Remediation
<![CDATA[ ## Remediation Suggestions - Remove the unused `user-library-read` scope: ```python SCOPES = ( "playlist-modify-public playlist-modify-private playlist-read-private " "user-read-recently-played user-top-read" ) ``` - Where practical, request scopes dynamically according to the operations the user enables. - Clearly document why each requested scope is required. - Require users to reauthorize after reducing the scope set so newly issued tokens carry only necessary permissions. ]]>
Vulnerability Patterns
  • Data ExfiltrationExternal Transmission, Env Variable Harvesting, File System Enumeration
  • Privilege EscalationExcessive Permissions, Sudo/Root Execution, Credential Access
  • Excessive AgencyUnrestricted Tool Access, Autonomous Decision Making, Scope Creep
  • Rogue AgentSelf-Modification, Session Persistence
  • Trigger AbuseOverly Broad Trigger, Shadow Command Trigger, Keyword Baiting Trigger
Findings (18)

Tp4

High
Category
MCP Tool Poisoning
Confidence
96% confidence
Finding
The skill description frames this as a simple Spotify utility, but the content also instructs OAuth credential collection, token refresh, and local persistence of sensitive tokens at a fixed filesystem path. That mismatch is dangerous because users and orchestrators may authorize the skill for harmless music tasks without realizing it will collect and store credentials and access personal account data.

Credential Access

High
Category
Privilege Escalation
Content
parser = argparse.ArgumentParser(description="Spotify OAuth")
    parser.add_argument("--client-id", help="Spotify Client ID")
    parser.add_argument("--client-secret", help="Spotify Client Secret")
    parser.add_argument("--refresh", action="store_true", help="Refresh access token")
    parser.add_argument("--code", help="Authorization code (extracted from URL)")
    parser.add_argument("--code-url", help="Full callback URL (code extracted automatically)")
    args = parser.parse_args()
Confidence
70% confidence
Finding
Code accesses credential files (SSH keys, AWS credentials, etc.). This could indicate credential theft attempts.

Credential Access

High
Category
Privilege Escalation
Content
def refresh_and_retry():
    """Refresh token and return new access token."""
    try:
        subprocess.run(
            [sys.executable, os.path.join(SKILL_DIR, "auth.py"), "--refresh"],
Confidence
90% confidence
Finding
The skill accesses and refreshes Spotify access tokens from persistent local storage, which is sensitive credential material. While expected for OAuth-based API access, this becomes dangerous if token storage is weakly protected or if the agent can invoke account actions without clear user awareness, potentially enabling unauthorized access to profile and playlist operations.

Lp3

Medium
Category
MCP Least Privilege
Confidence
92% confidence
Finding
The skill advertises shell, network, and file-write capable behavior but does not declare any tool scope or permission boundaries. In practice, this means an agent could invoke credential-handling scripts, write token material to disk, and make outbound API calls without explicit guardrails, increasing the chance of overbroad execution and abuse.

Session Persistence

Medium
Category
Rogue Agent
Content
---
name: spotify-playlist
description: Build and manage Spotify playlists from natural language requests. Search tracks/artists/albums, create playlists, manage tracks, view listening history. Use when the user asks to create a playlist, find music, check what they've been listening to, or any Spotify-related request. Examples - "make me a playlist for a rainy Sunday", "what have I been listening to lately", "find songs like Bonobo".
---

# Spotify Playlist Builder
Confidence
76% confidence
Finding
The skill is designed to create persistent effects across sessions by storing tokens and modifying user playlists, which introduces session-persistence and account-state risks. If invoked unexpectedly or by a compromised agent flow, actions can outlast the current interaction and continue to affect the user's account and locally stored auth state.

Vague Triggers

Medium
Confidence
89% confidence
Finding
The trigger language is broad enough to activate on nearly any Spotify-related request, not just narrow playlist-building tasks. Overbroad invocation increases the chance the skill runs in contexts where users did not intend account access, history inspection, or state-changing actions like playlist creation and track management.

Missing User Warnings

Medium
Confidence
94% confidence
Finding
The skill encourages use of top-tracks and recently-played data for personalization without clearly warning that it will access personal listening-history information. This creates a privacy risk because users may ask for a playlist and unintentionally expose behavioral data they did not expect the skill to inspect.

Context-Inappropriate Capability

Medium
Confidence
93% confidence
Finding
The script persists access tokens, refresh tokens, client ID, and client secret in a local JSON file under the user's home directory. Even with mode 0600, storing long-lived credentials on disk increases the blast radius of local compromise, accidental backup exposure, or misuse by other tools that can read the workspace, and the skill only needs Spotify access rather than permanent credential retention.

External Transmission

Medium
Category
Data Exfiltration
Content
def exchange_code(code, client_id, client_secret):
    auth_header = base64.b64encode(f"{client_id}:{client_secret}".encode()).decode()
    resp = requests.post("https://accounts.spotify.com/api/token", data={
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": REDIRECT_URI,
Confidence
70% confidence
Finding
Data is being sent to an external URL. This could be legitimate telemetry or data exfiltration. Manual review is recommended.

External Transmission

Medium
Category
Data Exfiltration
Content
def exchange_code(code, client_id, client_secret):
    auth_header = base64.b64encode(f"{client_id}:{client_secret}".encode()).decode()
    resp = requests.post("https://accounts.spotify.com/api/token", data={
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": REDIRECT_URI,
Confidence
70% confidence
Finding
Data is being sent to an external URL. This could be legitimate telemetry or data exfiltration. Manual review is recommended.

Tainted flow: 'auth_header' from requests.post (line 75, network input) → requests.post (network output)

Medium
Category
Data Flow
Content
def exchange_code(code, client_id, client_secret):
    auth_header = base64.b64encode(f"{client_id}:{client_secret}".encode()).decode()
    resp = requests.post("https://accounts.spotify.com/api/token", data={
        "grant_type": "authorization_code",
        "code": code,
        "redirect_uri": REDIRECT_URI,
Confidence
65% confidence
Finding
Data from a source is assigned to a variable that is later passed to a sink, creating a variable-mediated taint flow.

Tainted flow: 'tokens' from requests.post (line 60, network input) → requests.post (network output)

Medium
Category
Data Flow
Content
auth_header = base64.b64encode(
        f"{tokens['client_id']}:{tokens['client_secret']}".encode()
    ).decode()
    resp = requests.post("https://accounts.spotify.com/api/token", data={
        "grant_type": "refresh_token",
        "refresh_token": tokens["refresh_token"],
    }, headers={"Authorization": f"Basic {auth_header}"})
Confidence
65% confidence
Finding
Data from a source is assigned to a variable that is later passed to a sink, creating a variable-mediated taint flow.

External Transmission

Medium
Category
Data Exfiltration
Content
TOKEN_PATH = os.path.expanduser("~/.openclaw/workspace/config/.spotify-tokens.json")
SKILL_DIR = os.path.dirname(os.path.abspath(__file__))
API_BASE = "https://api.spotify.com/v1"


def get_token():
Confidence
60% confidence
Finding
Data is being sent to an external URL. This could be legitimate telemetry or data exfiltration. Manual review is recommended.

Missing User Warnings

Medium
Confidence
84% confidence
Finding
The script silently reads persisted OAuth tokens from disk and automatically refreshes them via auth.py, which enables account access without any runtime disclosure or consent checkpoint. In an agent-integrated environment, this can make credential use opaque to the user and facilitate broader-than-expected account actions if the skill is triggered indirectly.

subprocess module call

Medium
Category
Dangerous Code Execution
Content
def refresh_and_retry():
    """Refresh token and return new access token."""
    try:
        subprocess.run(
            [sys.executable, os.path.join(SKILL_DIR, "auth.py"), "--refresh"],
            capture_output=True, check=True
        )
Confidence
70% confidence
Finding
subprocess module calls execute external commands. Without careful input validation, this enables command injection.

Missing User Warnings

Medium
Confidence
87% confidence
Finding
The api helper sends authenticated requests to Spotify and may retrieve listening history, profile, and playlist data tied to a user account, but the script provides no explicit privacy notice or minimization boundary. In a skill context, hidden transmission of account-linked data to external services can surprise users and increase privacy exposure if commands are invoked automatically.

Missing User Warnings

Medium
Confidence
91% confidence
Finding
The add and remove commands make irreversible or user-visible playlist changes immediately, with no confirmation, dry-run mode, or guardrails. In an agent setting, misinterpretation of natural-language requests or prompt-injection elsewhere could cause unintended modification or deletion of playlist contents.

Context-Inappropriate Capability

Medium
Confidence
95% confidence
Finding
The skill exposes a me command that returns profile fields including email, country, and product, even though the stated purpose is playlist building and music discovery. This expands access to account-linked personal data beyond what is necessary, increasing privacy risk if the agent invokes the command unnecessarily or surfaces the data to other components.

Static analysis

No suspicious patterns detected.