Simpl-Resultat/src-tauri/src/commands/entitlements.rs
le king fu d2ded515fd
All checks were successful
PR Check — Frontend / frontend (pull_request) Successful in 1m43s
PR Check — Rust / rust (pull_request) Successful in 9m11s
fix(license): name key-entry errors, keep the edition off the activation token, flag revoked keys
Rust (license_commands.rs)
- LicenseError gains InvalidPrefix, InvalidSignature, Malformed and
  UnknownEdition. validate_with_key returns it (ExpiredSignature maps
  to LicenseExpired), and store_license, read_license and
  validate_license_key reject with the same JSON as the network
  commands. store_license_in and read_license_in take a directory, so
  the Storage mapping is tested at the source.
- D12: the edition comes from the license key alone.
  resolve_license_entitlements no longer takes the activation token,
  and current_entitlements reads only license.key
  (entitlements_from_dir). A token that had expired (2-year server
  lifetime) or came from another machine (restored data) used to drop
  a valid key to free, while a key copied without its token kept its
  edition. get_activation_status and persist_activation_token keep the
  strict token validation, and the key keeps its strict validation
  (CWE-613).

Front
- LicenseCard names the load error, and LicenseKeyForm (extracted so a
  static render reaches it) names a refused key, through
  parseLicenseError: no raw backend string reaches the card.
- D13: a license_revoked answer is recorded in LicenseContext for the
  whole session, because the card unmounts when the user leaves
  Settings > Users. Only a different key clears it. Card-level
  message, alert icon, Activate disabled through selectCanActivate.
- Machine counter n/limit, "Not activated", activating and
  deactivating labels, dates in fr-CA/en-CA, and "No expiry date"
  beyond 50 years (licenseExpiry.ts, for the 100-year keys of
  maximus-api#63).
- license.removeLicense and license.machines.activateError removed;
  the price authFailed message points to activating the machine.

Tests: 15 new Rust tests (resolution from a data directory, named
variants, the 100-year key of #363, a key without exp) replace 3
machine-binding tests; vitest covers the card and form renders, the
context revocation, the hook wiring and the locales.
test: reproduces #347 (an expired token of this machine resolved a
valid Base key to free on 5d549d6).

Docs: CHANGELOG FR/EN, guide section 12 and in-app docs,
architecture.md, ADR 0017 amendment for #347, qa-update-cycle.md,
api-contract-prices.md.

Fixes #347
Fixes #360
Refs #363

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-29 21:39:01 -04:00

111 lines
4.4 KiB
Rust

// Centralized feature → tier mapping for license entitlements.
//
// This module is the single source of truth for which features are gated by which tier
// on the Rust side. To change what is gated where, modify FEATURE_TIERS only — never
// sprinkle edition checks throughout the codebase.
//
// Since the tier-gating work (#297-#301), UI-level gates (budget, adjustments,
// reports-advanced, multi-profile, balance) live in the TS matrix
// `src/shared/entitlements.ts` (soft-paywall, UI-only enforcement). This table
// only keeps the features actually checked through `check_entitlement` — the
// JWT `features[]` array is a namespace shared with that TS layer, so keys are
// kebab-case on both sides.
/// Editions, ordered from least to most privileged.
pub const EDITION_FREE: &str = "free";
pub const EDITION_BASE: &str = "base";
pub const EDITION_PREMIUM: &str = "premium";
/// Maps feature name → list of editions allowed to use it.
/// A feature absent from this list is denied for all editions, unless the
/// license carries it in its signed `features[]` override (see [`is_entitled`]).
const FEATURE_TIERS: &[(&str, &[&str])] = &[("auto-update", &[EDITION_BASE, EDITION_PREMIUM])];
/// Pure check: does `edition` grant access to `feature` via the static matrix?
pub fn is_feature_allowed(feature: &str, edition: &str) -> bool {
FEATURE_TIERS
.iter()
.find(|(name, _)| *name == feature)
.map(|(_, tiers)| tiers.contains(&edition))
.unwrap_or(false)
}
/// Static matrix check OR signed per-license `features[]` override.
///
/// Fail-closed in Free (CWE-863): a key that no longer validates (invalid or
/// expired) resolves to "free" with its signed features already dropped (see
/// `license_commands::current_entitlements`). As defense in depth we also
/// refuse the override here whenever the edition is free, so signed features
/// can never rescue a license that resolves to free.
pub fn is_entitled(feature: &str, edition: &str, features: &[String]) -> bool {
if edition == EDITION_FREE {
return is_feature_allowed(feature, edition);
}
is_feature_allowed(feature, edition) || features.iter().any(|f| f == feature)
}
/// Tauri command: is `feature` available right now? Edition AND signed
/// per-license feature overrides are resolved together from the license key
/// (`license_commands::current_entitlements`), then combined by
/// [`is_entitled`].
#[tauri::command]
pub fn check_entitlement(app: tauri::AppHandle, feature: String) -> Result<bool, String> {
let (edition, features) = crate::commands::license_commands::current_entitlements(&app);
Ok(is_entitled(&feature, &edition, &features))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn free_denied_auto_update() {
assert!(!is_feature_allowed("auto-update", EDITION_FREE));
}
#[test]
fn base_unlocks_auto_update() {
assert!(is_feature_allowed("auto-update", EDITION_BASE));
}
#[test]
fn premium_unlocks_auto_update() {
assert!(is_feature_allowed("auto-update", EDITION_PREMIUM));
}
#[test]
fn unknown_feature_denied() {
assert!(!is_feature_allowed("nonexistent", EDITION_PREMIUM));
}
#[test]
fn matrix_grants_without_override() {
assert!(is_entitled("auto-update", EDITION_BASE, &[]));
assert!(is_entitled("auto-update", EDITION_PREMIUM, &[]));
}
#[test]
fn unlisted_feature_denied_without_override() {
// "balance" lives in the TS matrix only — absent from FEATURE_TIERS,
// so the static path denies it for every edition.
assert!(!is_entitled("balance", EDITION_BASE, &[]));
assert!(!is_entitled("balance", EDITION_PREMIUM, &[]));
}
#[test]
fn override_grants_unlisted_feature_for_paid_editions() {
let features = vec!["balance".to_string()];
assert!(is_entitled("balance", EDITION_BASE, &features));
assert!(is_entitled("balance", EDITION_PREMIUM, &features));
}
#[test]
fn override_ignored_in_free() {
// CWE-863: signed features[] must never rescue a license that resolves
// to free (invalid or expired key) — not even for a feature that a
// paid edition would get from the static matrix.
let features = vec!["balance".to_string(), "auto-update".to_string()];
assert!(!is_entitled("balance", EDITION_FREE, &features));
assert!(!is_entitled("auto-update", EDITION_FREE, &features));
}
}