bambuddy/SECURITY.md
maziggy 396e9aa09e security: harden path-traversal class across routes + services; fifth CI backstop
Two attacker-controlled strings were being joined to library_dir with no
  resolve + containment check in the project ZIP import endpoint:

    - linked_folders[*].name from the request's project.json
    - per-entry zf.namelist() paths from the ZIP itself

  An absolute path in either field collapsed the join (Path("/lib") / "/etc"
  becomes Path("/etc") because pathlib discards the left side when the right
  is absolute) and the next write_bytes landed wherever the attacker chose.

  Adjacent finding from the routes audit: GET /archives/{id}/photos/{filename}
  had NO validation on filename and FileResponse-served arbitrary paths -
  the DELETE counterpart at least gated on the photos membership check.

  Adjacent finding from the services audit: ArchiveService.attach_timelapse
  wrote archive_dir / filename where filename ultimately came from a printer's
  FTP listing (compromised-printer threat model) or the /timelapse/select
  query param. A malicious printer that exposes a directory entry with ..
  segments could write the timelapse outside the archive directory.

  New backend/app/utils/safe_path.py::safe_join_under(parent, *parts) is the
  single source of truth: rejects empty / null-byte / absolute parts up-front,
  joins under parent, resolves both sides, asserts is_relative_to. Returns the
  resolved canonical path on success, raises HTTPException(400) on escape, or
  PathTraversalError when http=False (for service-layer callers that need to
  match a non-HTTP return contract).

  Wired into the import vectors, both archive photo handlers, and the
  attach_timelapse service. The full audit sweep inspected every Path/Name
  join in backend/app/api/routes/ AND backend/app/services/ - 25 route-layer
  sites + 8 service-layer sites confirmed safe and tagged with
  # SEC-PATH-OK: <reason> so future audits trust the inline guard at a glance.

  Fifth CI backstop test_route_path_arithmetic_is_safe_joined_or_marked
  AST-walks both layers and fails the build on any <dir-like>/<bare variable>
  join that doesn't either route through safe_join_under or carry the marker.
  The services layer is in scope because it receives values verbatim from the
  routes AND from external sources Bambuddy has no control over (the printer
  FTP-listing case above).

  SECURITY.md gets a fifth rule + a fifth row in the CI test mapping table;
  the rule now names the printer FTP-listing case explicitly so future
  services-layer audits set the right expectation.

--------------

  fix(library): suppress warning storm when bulk-uploading ZIPs of empty/stub STL files

  Uploading a ZIP of stub or empty STL files (e.g. the 24-byte
  "solid test\nendsolid test" shape) produced one WARNING per file in
  stl_thumbnail.py::generate_stl_thumbnail. The warnings were technically
  correct - trimesh returns a valid Mesh with zero vertices, the safeguard
  matches, and the function returns None so the library entry is still
  created without a thumbnail - but the volume turned a successful upload
  into thousands of WARNING lines in the journal.

  Two changes:

  1. The per-file "Failed to load STL or empty mesh" message in
     stl_thumbnail.py is now logger.debug instead of logger.warning. It's
     a per-file content observation, not an actionable error; the caller
     already handles None correctly. The branch now catches the rare
     "large enough but trimesh still can't parse it" case, visible in
     debug logs without spamming production.

  2. New module constant MIN_USABLE_STL_BYTES = 200 (smallest binary STL
     with one triangle is 134B, smallest ASCII ~150B; 200 is a safe floor
     below any real STL). The three thumbnail call sites in library.py
     (extract_zip_file, single-file upload, _backfill_external_stl_thumbnails)
     pre-skip files below this size before calling generate_stl_thumbnail.
     Stubs never enter the trimesh pipeline at all.

  Behavior is unchanged for real STLs: any file >=200 bytes runs through
  the existing pipeline, MAX_VERTICES still triggers simplification at
  100k vertices for the 256x256 thumbnail render, large files still get
  thumbnails.

------------

  fix(stl-thumbnail): silence matplotlib first-import noise (writable cache + font_manager log level)

  On first STL upload, three matplotlib-internal log lines surfaced:

    WARNING [matplotlib] /opt/claude/.config/matplotlib is not a writable directory
    INFO    [matplotlib.font_manager] Failed to extract font properties from NotoColorEmoji.ttf
    INFO    [matplotlib.font_manager] generated new fontManager

  The writable-dir warning fired because Bambuddy's $HOME isn't writable for
  matplotlib's default config path; matplotlib fell back to /tmp/matplotlib-XXX
  which lost the font cache on every host reboot, so font_manager rebuilt it
  each cold start - producing another batch of INFO lines.

  Fix is two small additions in stl_thumbnail.py before the matplotlib import:

  1. New _configure_matplotlib_cache() sets MPLCONFIGDIR to
     settings.base_dir/.cache/matplotlib (mkdir if missing) so the cache
     persists across container restarts and the writable-dir warning never
     fires. Respects an externally-set MPLCONFIGDIR so operators who chose
     their own path aren't overridden. Best-effort with a debug fallback if
     settings can't be imported or the mkdir fails.

  2. logging.getLogger("matplotlib.font_manager").setLevel(WARNING) at module
     import demotes the per-font INFO scan that fires when font_manager
     builds its cache cold. Real font warnings (>= WARNING) still surface.

  3 new tests: font_manager logger at WARNING after module import;
  _configure_matplotlib_cache creates the directory under base_dir and sets
  MPLCONFIGDIR; an externally-set MPLCONFIGDIR is preserved verbatim.
  5516 backend tests green, frontend gates clean.
2026-06-02 12:12:54 +02:00

189 lines
7.6 KiB
Markdown

# Security Policy
## Reporting a Vulnerability
The Bambuddy team takes security seriously. We appreciate your efforts to responsibly disclose your findings.
### How to Report
**Please DO NOT report security vulnerabilities through public GitHub.**
Instead, please report them via email to:
**security@bambuddy.cool**
### What to Include
Please include the following information in your report:
- **Description** of the vulnerability
- **Steps to reproduce** the issue
- **Affected versions** of Bambuddy
- **Potential impact** of the vulnerability
- **Any suggested fixes** (if you have them)
### What to Expect
- **Acknowledgment**: We will acknowledge receipt of your report within 48 hours
- **Assessment**: We will investigate and validate the issue within 7 days
- **Updates**: We will keep you informed of our progress
- **Resolution**: We aim to release a fix within 30 days for critical issues
- **Credit**: We will credit you in our release notes (unless you prefer to remain anonymous)
## Supported Versions
| Version | Supported |
| ------- | ------------------ |
| 0.1.x | :white_check_mark: |
| 0.2.x | :white_check_mark: |
## Security Considerations
### Network Security
Bambuddy communicates with your printers over your local network using:
- **MQTT over TLS** (port 8883) - Encrypted printer communication
- **FTPS** (port 990) - Encrypted file transfers
### Recommendations
1. **Run on trusted network**: Bambuddy should only be accessible on your local network
2. **Use reverse proxy**: If exposing to the internet, use a reverse proxy with HTTPS
3. **Keep updated**: Always run the latest version for security patches
4. **Secure API keys**: Treat API keys like passwords; don't share them publicly
5. **Developer Mode**: Use your printer's Developer Mode access code; don't share it
### Known Security Features
- API key authentication for external access
- No default credentials
- Local-only by default (no cloud dependency)
- TLS encryption for printer communication
## Scope
The following are **in scope** for security reports:
- Authentication/authorization bypasses
- Remote code execution
- SQL injection
- Cross-site scripting (XSS)
- Cross-site request forgery (CSRF)
- Sensitive data exposure
- Insecure direct object references
The following are **out of scope**:
- Issues in dependencies (report to the upstream project)
- Social engineering attacks
- Physical attacks
- Denial of service (DoS) attacks
- Issues requiring physical access to the server
## Bambuddy Security Stance
The following rules apply to every PR that touches authentication,
authorization, permission gating, secret handling, or any code that
decides whether to allow or deny an action. They are not aspirational —
each one is enforced by a CI test that fails the build on violation.
### 1. Default-deny, allowlist over denylist
At any security boundary, the safe default is to deny and the
exceptions are listed explicitly. Denylists fail open on growth — every
new resource added to the codebase is implicitly granted access until
someone remembers to deny it. Allowlists fail closed: an unmapped new
resource gets a 403, which is loud and recoverable.
Concretely:
- `_APIKEY_SCOPE_BY_PERMISSION` in `backend/app/core/auth.py` is the
load-bearing API-key authorization map. Every `Permission` enum value
must be either present here with a scope flag, or present in
`_APIKEY_DENIED_PERMISSIONS`. Unmapped permissions return 403.
- Route auth dependencies are explicit, not implicit. A route without a
`Depends(require_*)` decorator must be listed in the route-audit
`PUBLIC_ROUTES` allowlist with a justification comment, or CI fails.
### 2. Fail-closed in auth code
No `except Exception:` (or bare `except:`) in authentication,
authorization, or permission code may return a permissive value
(`None`, `True`, an admin user, an empty filter that lets everything
through, etc.). The catch-all either re-raises or returns a denial.
This is CWE-636 "Not Failing Securely" — see
<https://cwe.mitre.org/data/definitions/636.html>.
The lint scope is `backend/app/core/auth.py`,
`backend/app/core/permissions.py`,
`backend/app/api/routes/auth*.py`. Any `except Exception:` block in
those files must be tagged `# SEC-AUTH-EXC: <reason>` on the same
line; CI fails otherwise. (We use a standalone marker rather than
`# noqa: ...` because ruff reserves the latter syntax for its own
error codes.)
### 3. No hardcoded fallback secrets
Production secrets (JWT signing keys, encryption keys, OAuth client
secrets, API tokens) have no string-literal fallback in source. The
codebase reads them from env vars or generates them on first run; if a
secret is missing AND cannot be generated, the app refuses to start
rather than booting with a known value. CI greps the source for
`-change-in-production`-shaped strings and fails on any hit.
### 4. Negative-path tests required for any auth change
Any PR that adds or modifies an auth dependency, permission check, or
scope flag includes tests for the negative paths:
- "No credentials → 401"
- "Wrong credentials → 401"
- "Right credentials, wrong scope → 403"
- "Expired / revoked credentials → 401"
A test asserting the happy path passes is necessary but not sufficient.
The failure modes are where the vulnerabilities live. The structural
backstops above catch *categories* of regression; the negative-path
tests catch *specific* regressions in the new code.
### 5. Path joins under a trusted parent use the safe-join helper
Anywhere a Bambuddy code path joins a string from outside the function's
scope (request body, query/path param, `UploadFile.filename`, ZIP
`namelist()` entry, tarfile member, **printer FTP-listing entry**) under
a trusted directory, the join must route through
`backend.app.utils.safe_path.safe_join_under(parent, *parts)`. The helper
resolves the joined path and asserts it is a descendant of the parent —
defeating both absolute-path collapse (`Path("/a") / "/b"``Path("/b")`)
and `..` traversal.
Sites that have an inline guard (an explicit resolve + `is_relative_to`,
a basename-stripping helper like `_safe_filename`, or a pre-validated
alphanumeric filter) carry a `# SEC-PATH-OK: <reason>` marker on the
same line. CI walks **both** `backend/app/api/routes/` and
`backend/app/services/` and fails the build on any
``<dir-like> / <variable>`` join without either the helper or the
marker. The services layer is in scope because it receives values from
the routes verbatim and from external sources Bambuddy has no control
over (the compromised-printer threat model: a malicious printer can
serve crafted FTP-listing entries that flow straight into a path join).
### Where these rules live in the codebase
| Rule | Enforcement | Location |
|------|-------------|----------|
| 1. Allowlist over denylist (Permission) | `test_every_permission_has_a_classification` | `backend/tests/integration/test_auth_apikey_rbac.py` |
| 1. Allowlist over denylist (routes) | `test_routes_have_explicit_auth_deps` | `backend/tests/unit/test_route_auth_coverage.py` |
| 2. Fail-closed in auth code | `test_no_fail_open_in_auth_modules` | `backend/tests/unit/test_no_fail_open_in_auth.py` |
| 3. No hardcoded fallback secrets | `test_no_hardcoded_secrets` | `backend/tests/unit/test_no_hardcoded_secrets.py` |
| 4. Negative-path tests required | Reviewer responsibility (no automated CI gate yet) | PR review |
| 5. Safe-join under trusted parent | `test_route_path_arithmetic_is_safe_joined_or_marked` | `backend/tests/unit/test_no_unsafe_path_joins.py` |
If you are adding a CI rule, update this table. If you are removing a
CI rule, you are removing a security backstop and the PR description
must explain why.
---
Thank you for helping keep Bambuddy and its users safe!