From 685a4bf48b3c5bd23d7ef5f78e46569c353f8a8e Mon Sep 17 00:00:00 2001 From: Philipp Polte Date: Thu, 19 Nov 2026 08:05:17 +0100 Subject: [PATCH] feat: plugin marketplace of the gateway for Claude Code A managed profile can name a Claude Code plugin marketplace that its gateway serves behind the same credential (Marketplace: Name, URL). KeyZapper writes it as an extraKnownMarketplaces entry next to the profile and removes it with the assignment. The new helper command headers prints the profile's credential as an Authorization header, which is what Claude Code expects from a headersHelper. A marketplace on another host than the profile's endpoint is not written, so the credential never leaves the gateway. Co-Authored-By: Claude Fable 5.2 --- README.de.md | 3 +- README.md | 3 +- desktop/core/src/helper.rs | 13 +++++++-- desktop/core/src/managed.rs | 7 ++++- desktop/core/src/models.rs | 20 +++++++++++-- desktop/core/src/settings.rs | 46 ++++++++++++++++++++++++++++++ desktop/core/tests/core_tests.rs | 49 ++++++++++++++++++++++++++++++++ desktop/locales/en.json | 2 +- desktop/src-tauri/src/model.rs | 1 + 9 files changed, 136 insertions(+), 8 deletions(-) diff --git a/README.de.md b/README.de.md index bb76506..de2a00e 100644 --- a/README.de.md +++ b/README.de.md @@ -293,8 +293,9 @@ Verwaltete Einstellungen haben Vorrang vor Projekteinstellungen; KeyZapper brich | Schlüssel | Typ | Wirkung | |---|---|---| -| `ManagedProfiles` | Array von Dicts: `Name`, `Endpoint`, optional `OpusModel`, `SonnetModel`, `HaikuModel`, `ModelAlias`, `Environment` (Dict), `ID`, `Type` (`apiKey` Standard oder `oidc`), `OIDCIssuer`, `OIDCClientID`, `OIDCScope`, `OIDCTokenType`, `Office`, `ClaudeDesktop` (Dicts, siehe unten) | Profile werden automatisch angelegt und sind nicht editier- oder löschbar; Entwickler tragen nur den Key ein (oder melden sich für SSO an) und können *Claude in Office* und *Claude Desktop (SSO)* für das Profil selbst einschalten, wo die IT beides nicht setzt (siehe unten). Ohne `ID` wird die Profil-ID aus `Name` abgeleitet, eine Umbenennung erzeugt also ein neues Profil. Bei SSO (`oidc`) sind `OIDCIssuer` und `OIDCClientID` erforderlich; `OIDCScope` Standard `openid profile offline_access`; `OIDCTokenType` ist `access` (Standard) oder `id`, andere Werte verwerfen das Profil. | +| `ManagedProfiles` | Array von Dicts: `Name`, `Endpoint`, optional `OpusModel`, `SonnetModel`, `HaikuModel`, `ModelAlias`, `Environment` (Dict), `ID`, `Type` (`apiKey` Standard oder `oidc`), `OIDCIssuer`, `OIDCClientID`, `OIDCScope`, `OIDCTokenType`, `Office`, `ClaudeDesktop`, `Marketplace` (Dicts, siehe unten) | Profile werden automatisch angelegt und sind nicht editier- oder löschbar; Entwickler tragen nur den Key ein (oder melden sich für SSO an) und können *Claude in Office* und *Claude Desktop (SSO)* für das Profil selbst einschalten, wo die IT beides nicht setzt (siehe unten). Ohne `ID` wird die Profil-ID aus `Name` abgeleitet, eine Umbenennung erzeugt also ein neues Profil. Bei SSO (`oidc`) sind `OIDCIssuer` und `OIDCClientID` erforderlich; `OIDCScope` Standard `openid profile offline_access`; `OIDCTokenType` ist `access` (Standard) oder `id`, andere Werte verwerfen das Profil. | | `ClaudeDesktop` (innerhalb eines `ManagedProfiles`-Eintrags) | Dict: `OIDCIssuer`, `OIDCClientID`, optional `GatewayURL` (Standard: `Endpoint` des Profils), `Scopes`, `BearerTokenType` (`id_token` Standard oder `access_token`), `CredentialKind` (`external-idp` Standard oder `interactive`), `Config` (Dict weiterer Claude-Desktop-Schlüssel), `AutoApply` (Bool, Standard `false`) | Claude Desktop meldet sich selbst mit dem OIDC-Client des Gateways an, wenn dieses Profil dafür gewählt ist (siehe [Claude-Tools](#claude-tools)). `external-idp` braucht Claude Desktop ab 2.7032.0; solange ältere Versionen im Einsatz sind, `interactive` setzen. Ein Block mit unbrauchbaren Werten (auch ein unbekanntes `CredentialKind`) bleibt erhalten; KeyZapper schreibt dann nichts für Claude Desktop. Die Schlüssel entsprechen der Claude-Desktop-Konfiguration: `GatewayURL` → `inferenceGatewayBaseUrl`, `OIDCIssuer`/`OIDCClientID`/`Scopes`/`BearerTokenType` → `issuer`, `clientId`, `scopes` und `bearerTokenType` des OIDC-Blocks, `CredentialKind` → `inferenceCredentialKind`; `inferenceProvider: gateway` und `appendOfflineAccess: true` werden immer geschrieben, alles Weitere (Telemetrie, Banner, erlaubte Hosts, …) gehört in `Config`. Ohne das Dict können Entwickler *Claude Desktop (SSO)* im Profil selbst ausfüllen; das Dict der IT ersetzt ihren Eintrag. | +| `Marketplace` (innerhalb eines `ManagedProfiles`-Eintrags) | Dict: `Name`, `URL` | Plugin-Marketplace für Claude Code, den das Gateway hinter derselben Anmeldung ausliefert. KeyZapper schreibt ihn mit dem Profil als `extraKnownMarketplaces`-Eintrag (Quelle `url`, `headersHelper` = `keyzapper-helper headers --profile `, der das Token des Profils als `Authorization`-Header liefert) und entfernt ihn mit der Zuordnung wieder; Claude Code braucht dafür `headersHelper` (ab 2.1.238). `Name` ist der Name aus der `marketplace.json`, `URL` deren https-Adresse auf dem Host von `Endpoint`; für einen anderen Host schreibt KeyZapper nichts, damit das Token das Gateway nicht verlässt. Für Claude Desktop gehört der Marketplace in `ClaudeDesktop` › `Config` (`allowedPluginMarketplaces`). | | `Office` (innerhalb eines `ManagedProfiles`-Eintrags) | Dict: `Enabled` (Bool, Standard `true`), `AddinID`, `GatewayURL`, `EntraClientID`, `EntraScope`, `DisabledFeatures` (Array oder kommagetrennter String) | Richtet [Claude in Microsoft 365](#claude-in-microsoft-365-über-das-profil) aus diesem Profil ein. Werte werden getrimmt. Ein Block mit unbrauchbaren Werten bleibt erhalten und wird in der Profilkarte gemeldet; dann wird nichts geschrieben. Ohne das Dict können Entwickler *Claude in Office* im Profil selbst einschalten; das Dict der IT ersetzt ihren Eintrag. | | `AllowedGatewayHosts` | Array von Strings (`host` oder `*.domain`) | Profile nur für diese Hosts. Der Helper gibt Keys für andere Hosts nicht heraus (Exit 78). Gilt nur für den Gateway-Host; der IdP-Host muss nicht gelistet sein. Leer bedeutet keine Einschränkung. | | `DefaultEndpoint`, `DefaultModelAlias` | String | Vorbelegung beim Anlegen eigener Profile | diff --git a/README.md b/README.md index 514112e..f27bd98 100644 --- a/README.md +++ b/README.md @@ -289,8 +289,9 @@ outrank project settings; KeyZapper aborts binding on conflict. | Key | Type | Effect | |---|---|---| -| `ManagedProfiles` | Array of dicts: `Name`, `Endpoint`, optional `OpusModel`, `SonnetModel`, `HaikuModel`, `ModelAlias`, `Environment` (dict), `ID`, `Type` (`apiKey` default or `oidc`), `OIDCIssuer`, `OIDCClientID`, `OIDCScope`, `OIDCTokenType`, `Office`, `ClaudeDesktop` (dicts, see below) | Profiles are created automatically and cannot be edited or deleted; developers only enter the key (or sign in for SSO) and may switch on *Claude in Office* and *Claude Desktop (SSO)* for the profile where IT sets neither (see below). Without `ID` the profile ID is derived from `Name`, so renaming creates a new profile. For SSO (`oidc` type), `OIDCIssuer` and `OIDCClientID` are required; `OIDCScope` defaults to `openid profile offline_access`; `OIDCTokenType` is `access` (default) or `id`, other values discard the profile. | +| `ManagedProfiles` | Array of dicts: `Name`, `Endpoint`, optional `OpusModel`, `SonnetModel`, `HaikuModel`, `ModelAlias`, `Environment` (dict), `ID`, `Type` (`apiKey` default or `oidc`), `OIDCIssuer`, `OIDCClientID`, `OIDCScope`, `OIDCTokenType`, `Office`, `ClaudeDesktop`, `Marketplace` (dicts, see below) | Profiles are created automatically and cannot be edited or deleted; developers only enter the key (or sign in for SSO) and may switch on *Claude in Office* and *Claude Desktop (SSO)* for the profile where IT sets neither (see below). Without `ID` the profile ID is derived from `Name`, so renaming creates a new profile. For SSO (`oidc` type), `OIDCIssuer` and `OIDCClientID` are required; `OIDCScope` defaults to `openid profile offline_access`; `OIDCTokenType` is `access` (default) or `id`, other values discard the profile. | | `ClaudeDesktop` (inside a `ManagedProfiles` entry) | Dict: `OIDCIssuer`, `OIDCClientID`, optional `GatewayURL` (default: the profile's `Endpoint`), `Scopes`, `BearerTokenType` (`id_token` default or `access_token`), `CredentialKind` (`external-idp` default or `interactive`), `Config` (dict of further Claude Desktop keys), `AutoApply` (Bool, default `false`) | Claude Desktop signs in itself with the gateway's OIDC client when this profile is chosen for it (see [Claude tools](#claude-tools)). The keys map to Claude Desktop's configuration: `GatewayURL` → `inferenceGatewayBaseUrl`, `OIDCIssuer`/`OIDCClientID`/`Scopes`/`BearerTokenType` → the `issuer`, `clientId`, `scopes` and `bearerTokenType` of the OIDC block, `CredentialKind` → `inferenceCredentialKind`; `inferenceProvider: gateway` and `appendOfflineAccess: true` are always written, everything else (telemetry, banner, allowed hosts, …) goes into `Config`. Without the dict, developers may fill in *Claude Desktop (SSO)* in the profile themselves; the dict from IT replaces their entry. `external-idp` needs Claude Desktop 2.7032.0 or newer; set `interactive` while older versions are in use. A block with unusable values (also an unknown `CredentialKind`) is kept; KeyZapper then writes nothing for Claude Desktop. | +| `Marketplace` (inside a `ManagedProfiles` entry) | Dict: `Name`, `URL` | Plugin marketplace for Claude Code that the gateway serves behind the same sign-in. KeyZapper writes it with the profile as an `extraKnownMarketplaces` entry (source `url`, `headersHelper` = `keyzapper-helper headers --profile `, which prints the profile's token as an `Authorization` header) and removes it again with the assignment; Claude Code needs `headersHelper` for it (2.1.238 or newer). `Name` is the name in the `marketplace.json`, `URL` its https address on the host of `Endpoint`; for another host KeyZapper writes nothing, so the token never leaves the gateway. For Claude Desktop the marketplace belongs in `ClaudeDesktop` › `Config` (`allowedPluginMarketplaces`). | | `Office` (inside a `ManagedProfiles` entry) | Dict: `Enabled` (Bool, default `true`), `AddinID`, `GatewayURL`, `EntraClientID`, `EntraScope`, `DisabledFeatures` (array or comma-separated string) | Sets up [Claude in Microsoft 365](#claude-in-microsoft-365-through-the-profile) from this profile. Without the dict, developers may switch on *Claude in Office* in the profile themselves; the dict from IT replaces their entry. Values are trimmed. A block with unusable values is kept and reported on the profile card; nothing is written then. | | `AllowedGatewayHosts` | Array of strings (`host` or `*.domain`) | Profiles only for these hosts. The helper does not release keys for other hosts (exit 78). Applies to the gateway host only; the IdP host need not be listed. Empty means no restriction. | | `DefaultEndpoint`, `DefaultModelAlias` | String | Prefill when creating your own profiles | diff --git a/desktop/core/src/helper.rs b/desktop/core/src/helper.rs index b9467aa..63bfd97 100644 --- a/desktop/core/src/helper.rs +++ b/desktop/core/src/helper.rs @@ -2,6 +2,8 @@ //! //! ```text //! keyzapper-helper credential --profile # key on stdout (no newline), used as apiKeyHelper +//! keyzapper-helper headers --profile # like credential, as {"Authorization":"Bearer "}: the +//! # headersHelper of a plugin marketplace on the gateway //! keyzapper-helper pool --profile # like credential; once its budget is used up, the key with //! # the most budget left on the same endpoint (hidden pool mode) //! keyzapper-helper store --profile # key on stdin (never as argument) @@ -64,9 +66,16 @@ impl HelperCommand { } pub fn run(&self, args: &[String], stdin: impl FnOnce() -> String) -> Output { - let commands = ["credential", "pool", "store", "status", "delete"]; + let commands = ["credential", "headers", "pool", "store", "status", "delete"]; if args.len() != 3 || args[1] != "--profile" || !commands.contains(&args[0].as_str()) { - return fail(ExitCode::Usage, l!("Aufruf: %@ credential|pool|store|status|delete --profile ", EXECUTABLE_NAME)); + return fail(ExitCode::Usage, l!("Aufruf: %@ credential|headers|pool|store|status|delete --profile ", EXECUTABLE_NAME)); + } + if args[0] == "headers" { + let mut output = self.run(&["credential".into(), args[1].clone(), args[2].clone()], stdin); + if output.exit_code == ExitCode::Ok { + output.stdout = serde_json::json!({ "Authorization": format!("Bearer {}", output.stdout) }).to_string(); + } + return output; } let Some(id) = parse_id(&args[2]) else { return fail(ExitCode::UnknownProfile, l!("Ungültige Profil-ID: %@", args[2])) }; let state = match self.metadata.load() { diff --git a/desktop/core/src/managed.rs b/desktop/core/src/managed.rs index f83fb5d..2001c7b 100644 --- a/desktop/core/src/managed.rs +++ b/desktop/core/src/managed.rs @@ -4,7 +4,7 @@ use crate::claude_desktop::{BearerTokenType, CredentialKind, DesktopSso}; use crate::claude_office::OfficeClient; -use crate::models::{AuthType, OidcTokenType}; +use crate::models::{AuthType, OidcTokenType, PluginMarketplace}; use serde_json::{Map, Value}; use sha2::{Digest, Sha256}; use std::collections::BTreeMap; @@ -33,6 +33,7 @@ pub struct ManagedProfile { pub oidc_token_type: OidcTokenType, pub office: Option, pub claude_desktop: Option, + pub marketplace: Option, } #[derive(Clone, Debug, PartialEq)] @@ -209,6 +210,10 @@ fn managed_profile(dict: &Map) -> Option { oidc_token_type, office: dict.get("Office").and_then(Value::as_object).map(office_client), claude_desktop: dict.get("ClaudeDesktop").and_then(Value::as_object).map(desktop_sso), + marketplace: dict.get("Marketplace").and_then(Value::as_object).map(|m| { + let trimmed = |key: &str| as_string(m.get(key)).map(|v| v.trim().to_string()).unwrap_or_default(); + PluginMarketplace { name: trimmed("Name"), url: trimmed("URL") } + }), }) } diff --git a/desktop/core/src/models.rs b/desktop/core/src/models.rs index 6e42ee8..a1ebecc 100644 --- a/desktop/core/src/models.rs +++ b/desktop/core/src/models.rs @@ -53,6 +53,16 @@ impl OidcTokenType { } } +/// A Claude Code plugin marketplace the profile's gateway serves behind the same credential as the model calls. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase", default)] +pub struct PluginMarketplace { + /// Name as in the marketplace's `marketplace.json` (`/plugin install @`). + pub name: String, + /// https URL of the `marketplace.json`. + pub url: String, +} + #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Profile { @@ -93,6 +103,9 @@ pub struct Profile { /// Claude Desktop signs in itself with the gateway's OIDC client instead of using the helper; None = helper. #[serde(default, skip_serializing_if = "Option::is_none")] pub claude_desktop: Option, + /// Plugin marketplace of the gateway, written to Claude Code's `extraKnownMarketplaces`; None = none. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub marketplace: Option, } fn placeholder_credential() -> CredentialReference { @@ -134,7 +147,7 @@ impl Profile { let credential = CredentialReference::for_id(&id); Self { id, name, endpoint, model_alias, opus_model: None, sonnet_model: None, haiku_model: None, environment: None, credential, auth_type: AuthType::ApiKey, oidc_issuer: None, oidc_client_id: None, oidc_scope: None, - oidc_token_type: OidcTokenType::Access, office: None, claude_desktop: None } + oidc_token_type: OidcTokenType::Access, office: None, claude_desktop: None, marketplace: None } } pub fn is_sso(&self) -> bool { @@ -556,12 +569,15 @@ pub struct WorkspaceBinding { /// Models of one tenant of a multi-tenant gateway instead of the profile's own; None = as in the profile. #[serde(default, skip_serializing_if = "Option::is_none")] pub models: Option, + /// Exactly the `extraKnownMarketplaces` entries the app wrote, so only those are reverted. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub marketplaces: BTreeMap, } impl WorkspaceBinding { pub fn new(path: String, profile_id: String) -> Self { Self { id: new_id(), path, profile_id, managed_values: BTreeMap::new(), git_exclude_entry: None, pooled: None, - mcp_server_ids: vec![], mcp_managed: BTreeMap::new(), mcp_git_exclude_entry: None, models: None } + mcp_server_ids: vec![], mcp_managed: BTreeMap::new(), mcp_git_exclude_entry: None, models: None, marketplaces: BTreeMap::new() } } pub fn is_pooled(&self) -> bool { diff --git a/desktop/core/src/settings.rs b/desktop/core/src/settings.rs index f150a73..bf1e22f 100644 --- a/desktop/core/src/settings.rs +++ b/desktop/core/src/settings.rs @@ -3,7 +3,9 @@ use crate::errors::{Error, Result, SettingsConflict}; use crate::json::{self, Object}; +use crate::managed::{host_of, is_secure_endpoint}; use crate::models::{ModelSelection, Profile, WorkspaceBinding}; +use serde_json::{json, Value}; use crate::{git, l, paths}; use std::collections::BTreeMap; use std::path::{Path, PathBuf}; @@ -205,6 +207,23 @@ impl SettingsBinder { values } + /// The `extraKnownMarketplaces` entry for the profile's plugin marketplace: Claude Code fetches it with the + /// headers `keyzapper-helper headers` prints, i.e. the profile's own credential. Nothing for a marketplace on + /// another host than the profile's endpoint (the credential must not leave the gateway), an unusable name or + /// URL, or a helper path beyond Claude Code's limits for `headersHelper` (500 printable ASCII characters). + pub fn desired_marketplaces(&self, root: &str, profile: &Profile) -> BTreeMap { + let Some(marketplace) = profile.marketplace.as_ref().filter(|_| !profile.is_subscription()) else { return BTreeMap::new() }; + let helper = format!("{} headers --profile {}", helper_invocation(&self.helper_path, root), profile.id); + let name_ok = !marketplace.name.is_empty() && marketplace.name.chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c)); + let url_ok = is_secure_endpoint(&marketplace.url) && host_of(&marketplace.url) == host_of(&profile.endpoint); + let helper_ok = helper.len() <= 500 && helper.chars().all(|c| c == ' ' || c.is_ascii_graphic()) && !helper.contains(" "); + if !(name_ok && url_ok && helper_ok) { + return BTreeMap::new(); + } + let entry = json!({ "source": { "source": "url", "url": marketplace.url, "headersHelper": helper }, "autoUpdate": true }); + BTreeMap::from([(marketplace.name.clone(), entry)]) + } + // MARK: Apply / revert /// `selection` is the binding's tenant model set (None = as in the profile); callers re-applying a binding pass @@ -221,6 +240,8 @@ impl SettingsBinder { } let desired = self.desired_values_for(&root, profile, pooled, selection); let previous_values = previous.map(|p| p.managed_values.clone()).unwrap_or_default(); + let marketplaces = self.desired_marketplaces(&root, profile); + let previous_marketplaces = previous.map(|p| p.marketplaces.clone()).unwrap_or_default(); let mut outer = self.environment_conflicts(&root, &BTreeMap::new()); outer.extend(wsl_helper_conflict(&self.helper_path, &root)); let blocking: Vec<_> = outer.iter().filter(|c| c.blocking).cloned().collect(); @@ -234,6 +255,7 @@ impl SettingsBinder { return Err(Error::SettingsConflicts(local)); } apply_values(settings, &desired, &previous_values); + apply_marketplaces(settings, &marketplaces, &previous_marketplaces); Ok(()) }) })?; @@ -249,6 +271,7 @@ impl SettingsBinder { mcp_managed: previous.map(|p| p.mcp_managed.clone()).unwrap_or_default(), mcp_git_exclude_entry: previous.and_then(|p| p.mcp_git_exclude_entry.clone()), models: selection.filter(|_| !profile.is_subscription()).cloned(), + marketplaces, }; Ok(ApplyResult { binding, changed, warnings: outer }) } @@ -260,6 +283,7 @@ impl SettingsBinder { if is_directory(&binding.path) { with_lock(|| mutate_settings(&local_settings_file(&binding.path), |s| { kept = revert_values(s, &binding.managed_values); + apply_marketplaces(s, &BTreeMap::new(), &binding.marketplaces); Ok(()) }))?; if let Some(line) = &binding.git_exclude_entry { @@ -282,12 +306,15 @@ impl SettingsBinder { } let desired = self.desired_values(profile, false, None); let previous_values = previous.map(|p| p.managed_values.clone()).unwrap_or_default(); + let marketplaces = self.desired_marketplaces("", profile); + let previous_marketplaces = previous.map(|p| p.marketplaces.clone()).unwrap_or_default(); let changed = with_lock(|| { mutate_settings(Path::new(&self.user_settings_path), |settings| { if !settings.contains_key("$schema") { settings.insert("$schema".into(), SCHEMA_URL.into()); } apply_values(settings, &desired, &previous_values); + apply_marketplaces(settings, &marketplaces, &previous_marketplaces); Ok(()) }) })?; @@ -296,6 +323,7 @@ impl SettingsBinder { binding.id = previous.id.clone(); } binding.managed_values = desired; + binding.marketplaces = marketplaces; Ok(ApplyResult { binding, changed, warnings: managed }) } @@ -304,6 +332,7 @@ impl SettingsBinder { let mut kept = Vec::new(); with_lock(|| mutate_settings(Path::new(&self.user_settings_path), |s| { kept = revert_values(s, &binding.managed_values); + apply_marketplaces(s, &BTreeMap::new(), &binding.marketplaces); Ok(()) }))?; kept.sort(); @@ -495,6 +524,23 @@ fn apply_values(settings: &mut Object, desired: &BTreeMap, previ } } +/// Writes the app's `extraKnownMarketplaces` entries and removes the ones it wrote before and no longer wants, +/// unless someone changed them since. Entries of other marketplaces stay as they are. +fn apply_marketplaces(settings: &mut Object, desired: &BTreeMap, previous: &BTreeMap) { + const KEY: &str = "extraKnownMarketplaces"; + if desired.is_empty() && previous.is_empty() { + return; + } + let mut known = settings.get(KEY).and_then(Value::as_object).cloned().unwrap_or_default(); + known.retain(|name, entry| desired.contains_key(name) || previous.get(name) != Some(&*entry)); + known.extend(desired.iter().map(|(name, entry)| (name.clone(), entry.clone()))); + if known.is_empty() { + settings.remove(KEY); + } else { + settings.insert(KEY.into(), Value::Object(known)); + } +} + fn revert_values(settings: &mut Object, managed: &BTreeMap) -> Vec { let mut kept = Vec::new(); for (key, value) in managed { diff --git a/desktop/core/tests/core_tests.rs b/desktop/core/tests/core_tests.rs index e58796f..2b302f8 100644 --- a/desktop/core/tests/core_tests.rs +++ b/desktop/core/tests/core_tests.rs @@ -478,6 +478,55 @@ fn helper_returns_only_requested_key_and_never_falls_back() { assert_eq!(h.run(&args("export", BETA), String::new).exit_code, ExitCode::Usage); } +#[test] +fn helper_prints_the_credential_as_marketplace_headers() { + let dir = temp_dir("helper-headers"); + let h = helper(&dir, BTreeMap::new()); + h.metadata.save(&AppState { profiles: vec![sample()], ..AppState::default() }).unwrap(); + let missing = h.run(&args("headers", ALPHA), String::new); + assert_eq!((missing.exit_code, missing.stdout.as_str()), (ExitCode::MissingCredential, "")); + h.run(&args("store", ALPHA), || "sk-al\"pha".into()); + let out = h.run(&args("headers", ALPHA), String::new); + assert_eq!(out.exit_code, ExitCode::Ok); + assert_eq!(serde_json::from_str::(&out.stdout).unwrap(), json!({"Authorization": "Bearer sk-al\"pha"})); +} + +#[test] +fn marketplace_of_the_profile_is_written_and_reverted_with_the_binding() { + use keyzapper_core::models::PluginMarketplace; + let root = temp_dir("marketplace"); + write(&local(&root), json!({"extraKnownMarketplaces": {"other": {"source": {"source": "github", "repo": "a/b"}}}})); + let b = binder(); + let marketplace = |url: &str| Some(PluginMarketplace { name: "acme-plugins".into(), url: url.into() }); + let mut profile = sample(); + let url = format!("{}/marketplace.json", profile.endpoint.trim_end_matches('/')); + profile.marketplace = marketplace(&url); + + let applied = b.apply(&profile, &root, None, false, None).unwrap().binding; + let source = &read(&local(&root))["extraKnownMarketplaces"]["acme-plugins"]["source"]; + assert_eq!((source["source"].as_str(), source["url"].as_str()), (Some("url"), Some(url.as_str()))); + assert_eq!(source["headersHelper"].as_str(), read(&local(&root))["apiKeyHelper"].as_str().map(|h| h.replace(" credential ", " headers ")).as_deref()); + + // The credential never goes to another host than the gateway; dropping the marketplace removes only the own entry. + profile.marketplace = marketplace("https://elsewhere.example.test/marketplace.json"); + let dropped = b.apply(&profile, &root, Some(&applied), false, None).unwrap().binding; + assert!(dropped.marketplaces.is_empty()); + assert_eq!(read(&local(&root))["extraKnownMarketplaces"], json!({"other": {"source": {"source": "github", "repo": "a/b"}}})); + + profile.marketplace = marketplace(&url); + let again = b.apply(&profile, &root, Some(&dropped), false, None).unwrap().binding; + b.revert(&again).unwrap(); + assert_eq!(read(&local(&root)), json!({"extraKnownMarketplaces": {"other": {"source": {"source": "github", "repo": "a/b"}}}})); +} + +#[test] +fn the_marketplace_block_of_a_managed_profile_is_read_trimmed() { + let values = json!({"ManagedProfiles": [{"Name": "Firma", "Endpoint": "https://gw.example.test", + "Marketplace": {"Name": " acme-plugins ", "URL": "https://gw.example.test/marketplace.json"}}]}); + let marketplace = ManagedConfig::from_values(values.as_object().unwrap()).profiles.remove(0).marketplace.unwrap(); + assert_eq!((marketplace.name.as_str(), marketplace.url.as_str()), ("acme-plugins", "https://gw.example.test/marketplace.json")); +} + #[test] fn helper_respects_gateway_allowlist() { let dir = temp_dir("helper"); diff --git a/desktop/locales/en.json b/desktop/locales/en.json index 7a53e35..bb16a9f 100644 --- a/desktop/locales/en.json +++ b/desktop/locales/en.json @@ -86,7 +86,7 @@ "Art": "Type", "Auf diesem System nicht unterstützt.": "Not supported on this system.", "Aufgaben und Projekte": "Tasks and projects", - "Aufruf: %@ credential|pool|store|status|delete --profile ": "Usage: %@ credential|pool|store|status|delete --profile ", + "Aufruf: %@ credential|headers|pool|store|status|delete --profile ": "Usage: %@ credential|headers|pool|store|status|delete --profile ", "Ausgelassen, weil ein eigener Server so heißt: %@": "Left out because one of your own servers has this name: %@", "Auswählen …": "Choose…", "Automatisch (vom Gateway)": "Automatic (from the gateway)", diff --git a/desktop/src-tauri/src/model.rs b/desktop/src-tauri/src/model.rs index beb8415..7141fc7 100644 --- a/desktop/src-tauri/src/model.rs +++ b/desktop/src-tauri/src/model.rs @@ -404,6 +404,7 @@ impl Model { profile.oidc_client_id = managed.oidc_client_id.clone(); profile.oidc_scope = managed.oidc_scope.clone(); profile.oidc_token_type = managed.oidc_token_type; + profile.marketplace = managed.marketplace.clone(); // Claude in Office and Claude Desktop's sign-in are IT's where it sets them; otherwise the user's own block // stays, so a managed profile can be tried with them (a block IT drops stays as the user's own until it is // switched off).