Back to skill

Security audit

Feishu Invoice Approval

Security checks for vulnerabilities and agentic risk

Overview

The skill is coherent, but it needs review because untrusted invoice images are processed by a Codex agent that can read the whole generated project directory.

Before installing, isolate Codex vision in a per-request directory containing only the invoice image and schema, keep BOT_DRY_RUN=true during testing, set a non-empty ALLOWED_SENDER_OPEN_IDS allowlist for production, and restrict retention/access for invoice images, extracted JSON, .env files, and the SQLite database.

Vulnerability Patterns
  • 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
  • Embedded Malicious CodeShips malicious scripts inside the skill and executes them locally
Findings (1)

T09 · Insecure Skill Coding Practices

Error
Location
assets/template/src/invoice_approval_bot/vision.py:58
Finding

Invoice-Borne Prompt Injection Can Expose Project Data and Forge Approval Fields

Content
View full analysis

Vulnerability Details

File Location: assets/template/src/invoice_approval_bot/vision.py:58-99
Vulnerability Type: Prompt injection through untrusted invoice images with excessive model filesystem access
Risk Level: High

python
def extract(self, image_path: Path, message_id: str) -> Dict[str, Any]:
    output_path = self.output_dir / f"{message_id}.json"
    command = [
        self.codex_bin,
        "exec",
        "--ephemeral",
        "--skip-git-repo-check",
        "--sandbox",
        "read-only",
        "--cd",
        str(self.project_dir),
        "--image",
        str(image_path),
        "--output-schema",
        str(self.schema_path),
        "--output-last-message",
        str(output_path),
        "--color",
        "never",
    ]
    if self.model:
        command.extend(["--model", self.model])
    command.append(VISION_PROMPT)

    try:
        completed = subprocess.run(
            command,
            capture_output=True,
            text=True,
            timeout=self.timeout_seconds,
            check=False,
        )
    except (OSError, subprocess.TimeoutExpired) as exc:
        raise VisionError(f"Codex vision could not start or timed out: {exc}") from exc
    if completed.returncode != 0:
        detail = (completed.stderr or completed.stdout).strip()[-1500:]
        raise VisionError(f"Codex vision failed: {detail}")
    if not output_path.exists():
        raise VisionError("Codex did not generate a structured extraction result")
    try:
        result = json.loads(output_path.read_text(encoding="utf-8"))
    except (OSError, json.JSONDecodeError) as exc:
        raise VisionError(f"Codex returned invalid JSON: {exc}") from exc
    if not isinstance(result, dict):
        raise VisionError("Codex extraction result must be a JSON object")
    return result

Technical Analysis

The service passes an ...[truncated 4000 chars]

Remediation
View remediation

Remediation Suggestions

  1. Isolate the model working directory

    • Create a fresh per-request directory containing only the invoice image and output schema.
    • Run Codex from that directory instead of project_dir.
    • Do not mount configuration, .env, databases, previous images, extracted JSON, logs, or approval records into the model-visible filesystem.
  2. Enforce isolation outside the prompt

    • Use OS-level sandboxing, a dedicated low-privilege account, container filesystem restrictions, or an equivalent allowlisted file-access boundary.
    • Treat the instruction not to follow image text as defense in depth only.
  3. Validate extracted fields as untrusted data

    • Apply strict maximum lengths and expected formats.
    • Reject unexpected multiline text, control characters, file-like content, instruction-like prose, and anomalously long summaries.
    • Independently validate invoice identifiers, dates, monetary values, tax identifiers, and arithmetic wherever possible.
  4. Reduce information returned to uploaders

    • Display only the minimum fields needed for confirmation.
    • Do not return arbitrary free-form model output or detailed internal errors.
    • Keep organization-specific configuration and prior processing data out of cards and replies.
  5. Restrict production senders

    • Require a non-empty ALLOWED_SENDER_OPEN_IDS allowlist for production deployments.
    • Fail closed when real submission is enabled without an explicit sender allowlist.
  6. Add injection-focused tests

    • Test invoice images containing instructions to read local files, disclose configuration, alter buyer fields, or forge confidence values.
    • Verify that the model process cannot access any project or historical runtime file.
    • Route anomalous extraction results to mandatory human review rather than automatic submission.
Vulnerability Patterns
  • Privilege EscalationExcessive Permissions, Sudo/Root Execution, Credential Access
  • Trigger AbuseOverly Broad Trigger, Shadow Command Trigger, Keyword Baiting Trigger
  • Behavioral ASTexec() Call, eval() Call, Dynamic Import
  • MCP Least PrivilegeUnderdeclared Capability, Wildcard Permission, Missing Permission Declaration
  • MCP Tool PoisoningHidden Instructions, Unicode Deception, Parameter Description Injection
Findings (29)

Tp4

High
Category
MCP Tool Poisoning
Confidence
99% confidence
Finding

The description claims a substantial feature set and end-to-end automation behavior, but the provided code chunk contains only minimal package metadata (version and a docstring). There is no implemented logic corresponding to the declared capabilities. This is a clear description-to-code mismatch for the supplied chunk.

Content

No source excerpt is available for this finding.

Credential Access

High
Category
Privilege Escalation
Confidence
60% confidence
Finding

Code accesses credential files (SSH keys, AWS credentials, etc.). This could indicate credential theft attempts.

Content

Scanner excerpt · assets/template/config/approval_mapping.example.json (reported line 2)May include surrounding context.

json
.env
.venv/
__pycache__/
*.py[cod]

Credential Access

High
Category
Privilege Escalation
Confidence
60% confidence
Finding

Code accesses credential files (SSH keys, AWS credentials, etc.). This could indicate credential theft attempts.

Content

Scanner excerpt · assets/template/config/scaffold-env.txt (reported line 1)May include surrounding context.

text
.env
.venv/
__pycache__/
*.py[cod]

Credential Access

High
Category
Privilege Escalation
Confidence
60% confidence
Finding

Code accesses credential files (SSH keys, AWS credentials, etc.). This could indicate credential theft attempts.

Content

Scanner excerpt · assets/template/config/scaffold-gitignore.txt (reported line 1)May include surrounding context.

text
.env
.venv/
__pycache__/
*.py[cod]

Credential Access

High
Category
Privilege Escalation
Confidence
60% confidence
Finding

Code accesses credential files (SSH keys, AWS credentials, etc.). This could indicate credential theft attempts.

Content

Scanner excerpt · assets/template/src/invoice_approval_bot/config.py (reported line 21)May include surrounding context.

python
.env
.venv/
__pycache__/
*.py[cod]

Lp1

High
Category
MCP Least Privilege
Confidence
75% confidence
Finding

The skill uses 'env' capability that is not listed in its permissions. This may indicate deceptive intent or missing permission declarations.

Content

No source excerpt is available for this finding.

Credential Access

High
Category
Privilege Escalation
Confidence
60% confidence
Finding

Code accesses credential files (SSH keys, AWS credentials, etc.). This could indicate credential theft attempts.

Content

Scanner excerpt · assets/template/src/invoice_approval_bot/config.py (reported line 60)May include surrounding context.

python
@classmethod
    def from_env(cls, project_dir: Optional[Path] = None) -> "Settings":
        root = (project_dir or Path(__file__).resolve().parents[2]).resolve()
        load_dotenv(root / ".env")

        def rooted(env_name: str, default: str) -> Path:
            value = Path(os.getenv(env_name, default))

Credential Access

High
Category
Privilege Escalation
Confidence
60% confidence
Finding

Code accesses credential files (SSH keys, AWS credentials, etc.). This could indicate credential theft attempts.

Content

Scanner excerpt · references/setup.md (reported line 28)May include surrounding context.

bash
python3 <skill-directory>/scripts/scaffold.py --target <target-directory>
cd <target-directory>
cp .env.example .env
cp config/approval_mapping.example.json config/approval_mapping.json

Credential Access

High
Category
Privilege Escalation
Confidence
60% confidence
Finding

Code accesses credential files (SSH keys, AWS credentials, etc.). This could indicate credential theft attempts.

Content

Scanner excerpt · scripts/scaffold.py (reported line 53)May include surrounding context.

python
print(f"Created Feishu invoice approval bot project at {target}")
    print("Next:")
    print(f"  1. cp {target / '.env.example'} {target / '.env'}")
    print(
        "  2. cp "
        f"{target / 'config' / 'approval_mapping.example.json'} "

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
96% confidence
Finding

The schema restricts expense_category to Chinese-only enum values and requires approval_summary to be generated as a concise Chinese reimbursement reason. This is a natural-language locale constraint embedded in the file, with no indication of user choice, opt-in, or a documented region-specific justification.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

This code exposes user-facing natural-language strings such as error messages and command descriptions only in Chinese. Under the stated policy, forcing a specific language without user opt-in is a natural-language policy violation unless the locale restriction is explicitly documented and justified, which is not evident in this file.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
97% confidence
Finding

The argparse description and subcommand help text are all user-facing strings presented only in Chinese. Because the file does not offer a language selection or indicate that the tool is intentionally limited to a Chinese-speaking audience, this conflicts with the language/locale policy.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
94% confidence
Finding

The file contains user-facing error text in Chinese, such as the validation message on this line. Because the skill does not offer a language or locale choice here, it enforces a specific language without user opt-in, which matches the language/locale policy violation criteria.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
96% confidence
Finding

These configuration exceptions use Chinese-only messages for multiple failure cases, including required field validation. This creates a consistent locale lock-in in natural-language output without any visible opt-in or justification in the file.

Content

No source excerpt is available for this finding.

subprocess module call

Medium
Category
Dangerous Code Execution
Confidence
70% confidence
Finding

subprocess module calls execute external commands. Without careful input validation, this enables command injection.

Content

Scanner excerpt · assets/template/src/invoice_approval_bot/lark.py (reported line 78)May include surrounding context.

python
input_text: Optional[str] = None,
    ) -> Dict[str, Any]:
        try:
            completed = subprocess.run(
                [self.binary, *args],
                cwd=str(cwd) if cwd else None,
                input=input_text,

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
81% confidence
Finding

This method submits an approval instance to the remote Lark API, which can trigger workflow actions affecting business records or approvals. In this file there is no confirmation prompt, user-visible disclosure, or explanatory logging around that externally visible state-changing operation.

Content

No source excerpt is available for this finding.

subprocess module call

Medium
Category
Dangerous Code Execution
Confidence
70% confidence
Finding

subprocess module calls execute external commands. Without careful input validation, this enables command injection.

Content

Scanner excerpt · assets/template/src/invoice_approval_bot/lark.py (reported line 328)May include surrounding context.

python
"bot",
                ]
                try:
                    process = subprocess.Popen(
                        command,
                        stdin=subprocess.PIPE,
                        stdout=subprocess.PIPE,

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
93% confidence
Finding

The file hard-codes SHANGHAI_TZ = timezone(timedelta(hours=8)), and invoice dates are later converted using that timezone. This is a natural-language/locale policy concern because the skill imposes a specific regional timezone without offering user opt-in or indicating that the skill is intentionally China-specific.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
88% confidence
Finding

The file’s natural-language content, including the module docstring and all generated risk messages, is exclusively in Chinese. Under the stated policy, forcing a specific language without user opt-in or a documented region-specific justification is a natural-language policy concern.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

This file contains module documentation and multiple user-facing reply strings entirely in Chinese, indicating the skill forces a specific language/locale. The policy allows locale constraints only when users are given a choice or the restriction is clearly documented and justified, which is not evident here.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
92% confidence
Finding

This file includes a natural-language comment in Chinese, indicating the skill may be authored with a fixed language context. More importantly, it also contains Chinese-only user-facing text in an exception message later in the file, which can violate language/locale policy if the skill does not offer a user choice or document a justified locale restriction.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
98% confidence
Finding

The raised ValueError uses Chinese-only text ("不可更新的字段:...") and provides no indication that language selection is supported. This is a natural-language policy concern because the skill forces one locale for runtime messaging rather than offering a user choice or documenting a justified language constraint.

Content

No source excerpt is available for this finding.

Natural-Language Policy Violations

Medium
Category
Not specified by scanner
Confidence
93% confidence
Finding

The embedded natural-language prompt mandates Chinese output, for example requiring approval_summary to be a concise Chinese reimbursement reason and using Chinese-only operating instructions. This is a locale/language constraint presented without any user opt-in or explicit justification in the file.

Content

No source excerpt is available for this finding.

subprocess module call

Medium
Category
Dangerous Code Execution
Confidence
70% confidence
Finding

subprocess module calls execute external commands. Without careful input validation, this enables command injection.

Content

Scanner excerpt · assets/template/src/invoice_approval_bot/vision.py (reported line 82)May include surrounding context.

python
command.append(VISION_PROMPT)

        try:
            completed = subprocess.run(
                command,
                capture_output=True,
                text=True,

Natural-Language Policy Violations

Low
Category
Not specified by scanner
Confidence
94% confidence
Finding

This manifest/config file contains natural-language strings such as field instructions and expense type labels entirely in Chinese, which imposes a specific language on users. Under the policy, locale-specific language should be optional or clearly justified; no such opt-in or justification is present in this file.

Content

No source excerpt is available for this finding.