Files
LangBot/tests/unit_tests/api/test_space_share.py
9ff492ac41 feat(space-share): prompt library and sharing prompts/skills/remote MCPs/local plugins to Space (LANG-439) (#3027)
* feat(space-share): share prompts, skills, remote MCPs and local plugins to LangBot Space (LANG-439)

- Prompt library dialog on Pipeline (messaging) and Agent (agent) prompt
  fields: search, preview, replace/append, favorites tied to the bound
  LangBot Account; share the current prompt for review
- Share to Space for Skills (file list + credential scan) and remote MCP
  servers (credentials become ${VAR} placeholders before anything leaves
  Core; stdio stays private)
- Community MCP installs with required inputs are created disabled and the
  detail page lists the placeholders to fill (unfilled_inputs)
- Locally / GitHub-installed plugins share their exact installed .lbpkg via
  the existing space-upload flow
- docs (zh/en/ja) and dev-docs contract note

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* fix(web): use a star for prompt favorites (LANG-439)

The heart is the anonymous extension like; favorites need a LangBot Account.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* fix(i18n): call messaging prompts "Messaging" in English (LANG-439)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(web): marketplace type tiles matching Space, shadcn prompt list (LANG-439)

- the in-app marketplace shows All / Plugins / MCP / Skills as tiles with a
  description and count, plugin components and Runner usage as ToggleGroup
  chips; the Filters popover is gone (same layout as space.langbot.app)
- prompt library rows use the shadcn Item component

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* style(market): soften extension type tiles; type-tinted selected state

Drop the dark outline/ring on the selected tile. Idle tiles use a muted
fill; the selected tile gets a soft type-tinted fill with an inset ring
and a solid icon badge.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* style(market): use a fixed blue for the selected All tile

The theme primary is near-black in Core, which brought back the dark
selected border on the All tile.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(web): switch market type on press and keep results while loading

Type tiles switch on mouse press (keyboard/touch still use click).
Filter changes keep the current cards dimmed until the new page arrives,
and stale responses are ignored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(web): apply library prompts in the WebUI language; one-language share note

- Prompt library applies the version matching the WebUI language (exact
  -> same family -> en_US -> original), with a language switcher.
- Share dialogs say one language is enough; other languages are
  translated automatically after upload.
- extractI18nObject falls back across Chinese scripts and to any
  available language instead of rendering an empty label.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(web): one-click LangBot Account binding from share and library

- Share dialogs: the 'bind a LangBot Account' state now has a button that
  starts the bind flow and returns to the same page; the creator-profile
  state gets a button too, with clearer copy.
- Prompt library: when no account is bound, the preview shows a
  'bind to favorite' button instead of only a disabled tab tooltip.
- Shared useSpaceBind hook.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(web): friendly empty state for templates; contributors no longer tag

- Empty template list: short, playful 'on their way, be the first to
  share' state (Space /templates, Core prompt library).
- Share dialogs drop the tags field; Space assigns tags during review.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

* feat(space-share): update an existing item; clearer identifier field

- Share dialogs list the bound account's published items of the same type
  (prompts: same kind) and offer 'Update existing': pick an identifier,
  metadata is prefilled, a changelog is asked for and the submission
  becomes the next version. Sharing something with the same identifier
  preselects update mode.
- The identifier field now looks like a normal input with the fixed
  '@creator/' prefix and a format hint.
- GET /api/v1/space-share/items proxies the Space owner item list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: multica-agent <github@multica.ai>
2026-11-14 21:20:18 +08:00

134 lines
5.4 KiB
Python

"""LANG-439: credential redaction and validation before sharing to Space."""
import io
import zipfile
import pytest
from langbot.pkg.api.http.service import space_share as share
def _server(url: str, headers: dict | None = None, mode: str = 'remote') -> dict:
return {'name': 'weather', 'mode': mode, 'extra_args': {'url': url, 'headers': headers or {}, 'timeout': 30}}
RUNTIME = {'status': 'connected', 'tools': [{'name': 'get_weather', 'description': 'Weather', 'parameters': {}}]}
def test_mcp_headers_and_query_secrets_become_placeholders():
out = share.sanitize_mcp_server(
_server(
'https://mcp.example.com/v1/sse?api_key=sk-live-abcdefghijklmnopqrstuvwxyz&region=eu',
{'Authorization': 'Bearer ghp_abcdefghijklmnopqrstuvwxyz0123456789', 'Accept': 'application/json'},
),
RUNTIME,
)
payload = out['payload']
assert 'sk-live' not in payload['url'] and 'region=eu' in payload['url']
assert payload['headers']['Authorization'] == 'Bearer ${AUTHORIZATION}'
assert payload['headers']['Accept'] == 'application/json'
names = {i['name'] for i in payload['required_inputs']}
assert names == {'AUTHORIZATION', 'API_KEY'}
assert all(i['secret'] and i['required'] for i in payload['required_inputs'])
assert payload['tools'][0]['name'] == 'get_weather'
assert {r['placeholder'] for r in out['redactions']} == names
def test_mcp_secret_in_url_path_is_redacted():
out = share.sanitize_mcp_server(_server('https://mcp.example.com/u/Zx9kP2mQ7vR4tY8wB3nL6cF1/mcp'), RUNTIME)
assert 'Zx9kP2mQ7vR4tY8wB3nL6cF1' not in out['payload']['url']
assert '${URL_TOKEN}' in out['payload']['url']
def test_mcp_existing_placeholders_are_declared_and_input_labels_applied():
out = share.sanitize_mcp_server(
_server('https://mcp.example.com/mcp', {'X-Api-Key': '${WEATHER_KEY}'}),
RUNTIME,
{'inputs': {'WEATHER_KEY': {'label': 'Weather API key', 'description': 'From the vendor console'}}},
)
(inp,) = out['payload']['required_inputs']
assert inp['name'] == 'WEATHER_KEY' and inp['label'] == 'Weather API key'
@pytest.mark.parametrize(
'server',
[
_server('https://mcp.example.com/mcp', mode='stdio'),
_server('http://mcp.example.com/mcp'),
_server('https://127.0.0.1/mcp'),
_server('https://localhost/mcp'),
_server('https://nas.local/mcp'),
_server('https://user:pw@mcp.example.com/mcp'),
],
)
def test_mcp_unshareable_configs_are_refused(server):
with pytest.raises(share.ShareError):
share.sanitize_mcp_server(server, RUNTIME)
def test_prompt_payload_detects_variables_and_findings():
payload, findings = share.build_prompt_payload(
{
'kind': 'messaging',
'language': 'zh_Hans',
'messages': [
{
'role': 'system',
'content': '你是{{shop_name}}的客服,联系 a@b.com,密钥 sk-abcdefghijklmnopqrstuvwxyz',
},
{'role': 'user', 'content': 'hi'},
],
'variables': [{'name': 'shop_name', 'description': '店铺名'}],
}
)
assert payload['variables'] == [{'name': 'shop_name', 'description': '店铺名'}]
kinds = {(f['kind'], f['severity']) for f in findings}
assert ('openai_key', 'block') in kinds and ('email', 'warn') in kinds
assert all('abcdefghijklmnop' not in f['excerpt'] for f in findings)
@pytest.mark.parametrize(
'data',
[
{'kind': 'pipeline', 'messages': [{'role': 'system', 'content': 'x'}]},
{'kind': 'agent', 'messages': [{'role': 'user', 'content': 'x'}]},
{'kind': 'agent', 'messages': [{'role': 'system', 'content': ' '}]},
{'kind': 'agent', 'messages': []},
{'kind': 'agent', 'messages': [{'role': 'system', 'content': 'a' * 40000}]},
],
)
def test_prompt_payload_rejects_invalid(data):
with pytest.raises(share.ShareError):
share.build_prompt_payload(data)
def test_skill_zip_scan():
buf = io.BytesIO()
with zipfile.ZipFile(buf, 'w') as zf:
zf.writestr('demo/SKILL.md', '---\nname: demo\n---\nUse token ghp_abcdefghijklmnopqrstuvwxyz0123456789\n')
zf.writestr('demo/run.py', 'print(1)\n')
info = share.inspect_skill_zip(buf.getvalue())
assert {f['path'] for f in info['files']} == {'demo/SKILL.md', 'demo/run.py'}
assert info['findings'][0]['kind'] == 'github_token' and info['findings'][0]['where'] == 'demo/SKILL.md'
def test_share_metadata_validation():
meta = share.validate_share_metadata(
{'name': 'Cs-Agent', 'label': {'zh_Hans': '客服'}, 'description': 'desc', 'tags': ['a', ' ', 'b']}
)
assert meta['name'] == 'cs-agent' and meta['description'] == {'en_US': 'desc'} and meta['tags'] == ['a', 'b']
with pytest.raises(share.ShareError):
share.validate_share_metadata({'name': 'x', 'label': 'a', 'description': 'b'})
def test_unfilled_mcp_placeholders_lists_names_only():
from langbot.pkg.api.http.service.mcp import unfilled_mcp_placeholders
extra = {
'url': 'https://mcp.example.com/mcp?api_key=${API_KEY}',
'headers': {'Authorization': 'Bearer ${TOKEN}', 'X-Trace': 'on', 'X-Again': '${TOKEN}'},
}
assert unfilled_mcp_placeholders(extra) == ['API_KEY', 'TOKEN']
assert unfilled_mcp_placeholders({'url': 'https://mcp.example.com/mcp', 'headers': {'A': 'real'}}) == []
assert unfilled_mcp_placeholders(None) == []