Lizenz-Connector: Rechte aus Scopes, 403 getrennt, Widerruf, Idempotenz, /ready (#43)

- Service-Token: Schreibfähigkeiten nur gemäß ausdrücklich eingetragenen
  Scopes (neues Verbindungsfeld; ohne Eintrag nur lesend), da das
  Lizenzsystem keine Scope-Introspektion bietet. Benutzer/Passwort wie
  bisher (ohne Widerruf).
- 403 = fehlendes Recht (UNSUPPORTED, kein Re-Login), 401 = Anmeldung.
- terminate → POST /licenses/{id}/revoke (nur mit licenses:revoke).
- Lebenszyklus mit Idempotency-Key kc:<Auftrags-ID>.
- healthCheck über /ready (Fallback /).
Tests: Scope-Teilmengen, nur-lesend, Widerruf/Verlängerung mit Key,
403 vs. 401, Health. 22 Connector-Tests grün.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Claude (KI) 2026-10-06 13:04:30 +02:00
parent 546e667081
commit 5dba9f6de2
3 changed files with 78 additions and 18 deletions

View file

@ -25,13 +25,14 @@ Benötigte Scopes eines Service-Tokens (laut Verwaltungs-Client): `programs:read
| `explicit_expiry` | festes Ablaufdatum bei Anlage |
| `customer_info` | Kundenkontext bei Anlage (Name, E-Mail, Kontakt, Kundennummer, Bestell-/Vertragsnummer, Quelle „Kundencenter“) |
`capabilities()`: Lesen immer; Schreiben (`lifecycle.*`, `secret.reveal`) derzeit, sobald Zugangsdaten vorhanden sind. **Offen (#43):** Fähigkeiten aus den tatsächlich erlaubten Token-Scopes ableiten.
`capabilities()`: Lesen immer. Schreiben nur gemäß Rechten (#43): Mit Service-Token zählen die in der Verbindung eingetragenen **Scopes** (Feld „Scopes des Service-Tokens“ – das Lizenzsystem bietet keine Introspektion; ohne Eintrag ist die Verbindung nur lesend): `licenses:suspend` → sperren/entsperren, `licenses:extend` → verlängern, `licenses:write` → anlegen, `licenses:read` → Schlüssel anzeigen, `licenses:revoke` → widerrufen (`terminate`, destruktiv). Mit Benutzer/Passwort (Lizenzsystem-Benutzer = alle Rechte) wie bisher ohne Widerruf. Ein 403 (fehlender Scope) wird als „fehlendes Recht“ gemeldet und nicht als Anmeldefehler; nur 401 löst beim Altweg eine erneute Anmeldung aus. Lebenszyklus-Aufrufe senden `Idempotency-Key: kc:<Auftrags-ID>`. Health prüft `/ready` (Fallback `/`).
## 3. Endpunkte, die das Kundencenter nutzt
| Methode/Pfad | Zweck | Wo |
|---|---|---|
| `GET /` | Health + Features | Connector |
| `GET /ready` (Fallback `GET /`) | Health inkl. Datenbank | Connector |
| `GET /` | Features | Connector |
| `POST /token` | Login (Altweg) | Connector, Verwaltung |
| `GET /programs/?limit=1000` | Programme (Namen) | Katalog, Abgleich, Anlage |
| `GET /products/groups` | Produktkatalog (Gruppen → Produkte, Preis, Dauer, Module, Plan, Kundengrenze, Add-ons) | Katalogimport, Vergabe |
@ -42,7 +43,7 @@ Benötigte Scopes eines Service-Tokens (laut Verwaltungs-Client): `programs:read
| `POST /licenses/` | Lizenz anlegen (Programm, Produkt, Nutzer-Grenze, Dauer, Kundenkontext) | Bereitstellung, Verwaltung |
| `POST /licenses/trials` | Trial vergeben | Verwaltung |
| `PUT /licenses/{id}` | Felder ändern (Altweg sperren/verlängern) | Connector, Verwaltung |
| `POST /licenses/{id}/{suspend\|unsuspend\|extend\|revoke}` | Lebenszyklus, `Idempotency-Key` | Connector (`lifecycle`), Verwaltung |
| `POST /licenses/{id}/{suspend\|unsuspend\|extend\|revoke}` | Lebenszyklus, `Idempotency-Key` (Connector: `kc:<Auftrags-ID>`) | Connector (`lifecycle`, Widerruf = `terminate`), Verwaltung |
| `POST /licenses/{id}/entitlement` | Plan/Module/Kundengrenze setzen (Entitlement-Version) | Verwaltung |
Fehlerabbildung (`admin.ts`): 401/403 → `AUTH_FAILED`, 404 → `NOT_FOUND`, 409 → `CONFLICT`, 400/422 → `INVALID_INPUT` (Text aus `detail`), 429 → `RATE_LIMITED`, sonst `UPSTREAM_ERROR`; Zeitüberschreitung 15 s → `TIMEOUT`.

View file

@ -87,6 +87,11 @@ export function createLicensingConnector(deps: LicensingDeps = {}): Connector {
} catch { return []; }
}
const hasToken = (ctx: ConnectorContext) => !!ctx.secrets.token;
/** Scopes eines Service-Tokens. Das Lizenzsystem bietet keine Introspektion – deshalb werden sie in der Verbindung
* ausdrücklich eingetragen (so wie beim Anlegen des Tokens vergeben). Ohne Eintrag gilt ein Token als nur lesend. */
const tokenScopes = (ctx: ConnectorContext) => new Set(String(ctx.config.scopes ?? '').split(/[\s,]+/).map((x) => x.trim()).filter(Boolean));
/** Darf die Verbindung diesen Scope nutzen? Benutzer/Passwort = Lizenzsystem-Benutzer mit allen Rechten. */
const allows = (ctx: ConnectorContext, scope: string) => hasToken(ctx) ? tokenScopes(ctx).has(scope) : !!(ctx.secrets.username && ctx.secrets.password);
const hasAuth = (ctx: ConnectorContext) => hasToken(ctx) || !!(ctx.secrets.username && ctx.secrets.password);
async function authHeaders(ctx: ConnectorContext, force = false): Promise<Record<string, string>> {
@ -101,10 +106,16 @@ export function createLicensingConnector(deps: LicensingDeps = {}): Connector {
try { return { authorization: `Bearer ${await token}` }; } catch (e) { tokenCache.delete(key); throw e; }
}
/** Anfrage mit einmaligem Re-Login bei abgelaufenem Token. */
async function call<T>(ctx: ConnectorContext, method: 'GET' | 'PUT' | 'POST', path: string, body?: unknown): Promise<T> {
const go = async (force: boolean) => httpJson<T>(method, `${base(ctx)}${path}`, { headers: await authHeaders(ctx, force), body }, deps);
async function call<T>(ctx: ConnectorContext, method: 'GET' | 'PUT' | 'POST', path: string, body?: unknown, headers: Record<string, string> = {}): Promise<T> {
const go = async (force: boolean) => httpJson<T>(method, `${base(ctx)}${path}`, { headers: { ...(await authHeaders(ctx, force)), ...headers }, body }, deps);
try { return await go(false); }
catch (e) { if (e instanceof ConnectorError && e.code === 'AUTH_FAILED' && hasAuth(ctx) && !hasToken(ctx)) return go(true); throw e; }
catch (e) {
if (!(e instanceof ConnectorError) || e.code !== 'AUTH_FAILED') throw e;
// 403 = angemeldet, aber ohne Recht (Scope): kein erneuter Login, klare Meldung statt „Anmeldung fehlgeschlagen“
if (/HTTP 403/.test(e.detail ?? '')) throw new ConnectorError('UNSUPPORTED', 'Dem Zugang fehlt das Recht (Scope) für diese Aktion im Lizenzsystem');
if (hasAuth(ctx) && !hasToken(ctx)) return go(true); // 401 mit Benutzer/Passwort: Token abgelaufen → einmal neu anmelden
throw e;
}
}
const map = (l: RawLicense, programs: Map<number, string>, zone: string): NormalizedResource => mapLicense(l, programs, zone, now());
@ -115,12 +126,18 @@ export function createLicensingConnector(deps: LicensingDeps = {}): Connector {
{ name: 'baseUrl', label: 'Basis-URL', required: true, placeholder: 'http://127.0.0.1:8001' },
{ name: 'timezone', label: 'Zeitzone des Lizenzsystems', placeholder: 'Europe/Berlin', advanced: true, help: 'Nur bei älteren Lizenzsystemen relevant (neuere liefern UTC).' },
{ name: 'token', label: 'Service-Token (empfohlen, nur die nötigen Rechte)', secret: true },
{ name: 'scopes', label: 'Scopes des Service-Tokens', placeholder: 'licenses:read licenses:write licenses:suspend licenses:extend programs:read products:read', help: 'Genau wie beim Anlegen des Tokens vergeben (Leerzeichen oder Komma). Ohne Angabe ist die Verbindung nur lesend. licenses:revoke schaltet „Widerrufen“ frei.' },
{ name: 'username', label: 'Alternativ: API-Benutzer', secret: true, advanced: true, help: 'Nur nötig, wenn Sie keinen Service-Token verwenden.' },
{ name: 'password', label: 'Alternativ: API-Passwort', secret: true, advanced: true },
],
async capabilities(ctx) {
const c: Capability[] = ['catalog.list', 'resources.list', 'resources.get', 'status.read'];
if (hasAuth(ctx)) c.push('lifecycle.suspend', 'lifecycle.unsuspend', 'lifecycle.extend', 'lifecycle.create', 'secret.reveal'); // Änderungen brauchen einen authentifizierten Benutzer
// Schreibrechte nur gemäß tatsächlich erlaubten Scopes (Service-Token) bzw. für einen API-Benutzer (alle Rechte).
if (allows(ctx, 'licenses:suspend')) c.push('lifecycle.suspend', 'lifecycle.unsuspend');
if (allows(ctx, 'licenses:extend')) c.push('lifecycle.extend');
if (allows(ctx, 'licenses:write')) c.push('lifecycle.create');
if (allows(ctx, 'licenses:read')) c.push('secret.reveal');
if (hasToken(ctx) && allows(ctx, 'licenses:revoke')) c.push('lifecycle.terminate'); // Widerruf nur mit ausdrücklich vergebenem Scope
const f = await features(ctx);
if (f.includes('key_prefix')) c.push('license.key_prefix');
if (f.includes('explicit_expiry')) c.push('license.expiry');
@ -129,7 +146,12 @@ export function createLicensingConnector(deps: LicensingDeps = {}): Connector {
},
async healthCheck(ctx) {
const t0 = Date.now();
try { await httpJson('GET', `${base(ctx)}/`, {}, { ...deps, retries: 0, timeoutMs: 5000 }); return { ok: true, latencyMs: Date.now() - t0 }; }
// /ready prüft auch die Datenbank des Lizenzsystems; ältere Versionen ohne /ready → GET /
try {
try { await httpJson('GET', `${base(ctx)}/ready`, {}, { ...deps, retries: 0, timeoutMs: 5000 }); }
catch (e) { if (!(e instanceof ConnectorError && e.code === 'NOT_FOUND')) throw e; await httpJson('GET', `${base(ctx)}/`, {}, { ...deps, retries: 0, timeoutMs: 5000 }); }
return { ok: true, latencyMs: Date.now() - t0 };
}
catch (e) { return { ok: false, latencyMs: Date.now() - t0, message: e instanceof ConnectorError ? e.message : 'Unbekannter Fehler' }; }
},
/**
@ -228,11 +250,15 @@ export function createLicensingConnector(deps: LicensingDeps = {}): Connector {
const id = encodeURIComponent(req.externalRef); const f = await features(ctx); const zone = f.includes('utc_timestamps') ? 'UTC' : tz(ctx);
const until = req.action === 'extend' ? String(req.params?.until ?? '') : '';
if (req.action === 'extend' && Number.isNaN(Date.parse(until))) throw new ConnectorError('BAD_CONFIG', 'until fehlt');
if (!['suspend', 'unsuspend', 'extend'].includes(req.action)) throw new ConnectorError('UNSUPPORTED');
// Neuere Lizenzsysteme: eigene Lebenszyklus-Endpunkte (Status, Zeitstempel und Protokoll bleiben konsistent). Alle setzen einen Zielzustand.
if (!['suspend', 'unsuspend', 'extend', 'terminate'].includes(req.action)) throw new ConnectorError('UNSUPPORTED');
if (req.action === 'terminate' && !f.includes('lifecycle')) throw new ConnectorError('UNSUPPORTED', 'Widerruf braucht ein Lizenzsystem mit Lebenszyklus-Endpunkten');
// Neuere Lizenzsysteme: eigene Lebenszyklus-Endpunkte (Status, Zeitstempel und Protokoll bleiben konsistent). Alle setzen einen
// Zielzustand; der Idempotency-Key (Auftrags-ID) sorgt dafür, dass eine Wiederholung nicht doppelt wirkt (z. B. Verlängerung).
if (f.includes('lifecycle')) {
const reason = 'Kundencenter';
const r = await call<{ license?: RawLicense }>(ctx, 'POST', `/licenses/${id}/${req.action}`, req.action === 'extend' ? { until: new Date(until).toISOString(), reason } : { reason });
const path = req.action === 'terminate' ? 'revoke' : req.action;
const r = await call<{ license?: RawLicense }>(ctx, 'POST', `/licenses/${id}/${path}`, req.action === 'extend' ? { until: new Date(until).toISOString(), reason } : { reason },
req.idempotencyKey ? { 'Idempotency-Key': `kc:${req.idempotencyKey}` } : {});
if (!r?.license || typeof r.license.id !== 'number') throw new ConnectorError('INVALID_RESPONSE');
return { resource: map(r.license, new Map(), zone) };
}

View file

@ -15,32 +15,35 @@ const GROUPS = [
];
const lic = (o: object = {}) => ({ id: 18, program_id: 1, product_id: 6, license_key: 'aaaaaaaa-1111-4222-8333-bbbbbbbbbbbb', user_limit: null, duration_type: 'MONTH', starts_at: '2026-09-01T10:00:00Z', expires_at: '2026-10-01T10:00:00Z', is_active: true, status: 'active', blocked: false, suspended_at: null, revoked_at: null, product: { name: 'Premium' }, activation: null, activations: [], ...o });
const json = (b: unknown, status = 200) => new Response(JSON.stringify(b), { status, headers: { 'content-type': 'application/json' } });
interface Call { method: string; path: string; auth?: string; body?: any }
interface Call { method: string; path: string; auth?: string; body?: any; idem?: string }
const api = (opts: { licenses?: object[]; features?: string[] | null; log?: Call[] } = {}) => {
const log = opts.log ?? [];
return (async (url: string, init: RequestInit) => {
const u = new URL(url); const h = (init.headers ?? {}) as Record<string, string>; const body = init.body && !String(init.body).includes('=') ? JSON.parse(init.body as string) : init.body;
log.push({ method: init.method!, path: u.pathname, auth: h.authorization, body });
log.push({ method: init.method!, path: u.pathname, auth: h.authorization, body, idem: h['Idempotency-Key'] });
if (u.pathname === '/ready') return json({ status: 'ready' });
if (h.authorization === 'Bearer svc-readonly' && init.method !== 'GET') return json({ detail: 'Missing scope' }, 403);
if (u.pathname === '/') return json({ message: 'ok', features: opts.features === undefined ? (FEATURES_OVERRIDE ?? FEATURES) : opts.features ?? undefined });
if (h.authorization !== 'Bearer svc-token-1' && u.pathname !== '/token') return json({}, 401);
if (!['Bearer svc-token-1', 'Bearer svc-readonly'].includes(h.authorization) && u.pathname !== '/token') return json({}, 401);
if (u.pathname === '/programs/') return json(PROGRAMS);
if (u.pathname === '/products/groups') return json(GROUPS);
if (u.pathname === '/licenses/' && init.method === 'GET') return json(opts.licenses ?? [lic()]);
if (/^\/licenses\/\d+$/.test(u.pathname) && init.method === 'GET') return json(lic({ id: Number(u.pathname.split('/')[2]) }));
if (u.pathname === '/licenses/' && init.method === 'POST') return json(lic({ id: 99, product_id: body.product_id === 6 ? 6 : null, expires_at: body.expires_at ?? null }), 201);
const m = /^\/licenses\/(\d+)\/(suspend|unsuspend|extend)$/.exec(u.pathname);
if (m && init.method === 'POST') return json({ changed: true, action: m[2], license: lic({ id: Number(m[1]), is_active: m[2] !== 'suspend', suspended_at: m[2] === 'suspend' ? '2026-09-26T12:00:00Z' : null, status: m[2] === 'suspend' ? 'suspended' : 'active', expires_at: m[2] === 'extend' ? body.until : '2026-10-01T10:00:00Z' }) });
const m = /^\/licenses\/(\d+)\/(suspend|unsuspend|extend|revoke)$/.exec(u.pathname);
if (m && init.method === 'POST') return json({ changed: true, action: m[2], license: lic({ id: Number(m[1]), is_active: !['suspend', 'revoke'].includes(m[2]!), revoked_at: m[2] === 'revoke' ? '2026-09-26T12:00:00Z' : null, suspended_at: m[2] === 'suspend' ? '2026-09-26T12:00:00Z' : null, status: m[2] === 'suspend' ? 'suspended' : 'active', expires_at: m[2] === 'extend' ? body.until : '2026-10-01T10:00:00Z' }) });
return json({}, 404);
}) as unknown as typeof fetch;
};
const ctx = { config: { baseUrl: 'http://lic.test', timezone: 'Europe/Berlin' }, secrets: { token: 'svc-token-1' }, correlationId: 'c' };
const ALL_SCOPES = 'licenses:read licenses:write licenses:suspend licenses:extend licenses:revoke programs:read products:read';
const ctx = { config: { baseUrl: 'http://lic.test', timezone: 'Europe/Berlin', scopes: ALL_SCOPES }, secrets: { token: 'svc-token-1' }, correlationId: 'c' };
const mk = (o: Parameters<typeof api>[0] = {}) => createLicensingConnector({ fetchImpl: api(o), sleep: async () => {}, now: () => new Date('2026-09-26T12:00:00Z') });
describe('Lizenz-Connector (neues Lizenzsystem)', () => {
it('erfüllt den Vertrag mit Service-Token (kein Login)', async () => {
const log: Call[] = []; await runContract(expect as never, mk({ log }), ctx);
expect(log.some((l) => l.path === '/token')).toBe(false);
expect(log.filter((l) => l.path !== '/').every((l) => l.auth === 'Bearer svc-token-1')).toBe(true);
expect(log.filter((l) => !['/', '/ready'].includes(l.path)).every((l) => l.auth === 'Bearer svc-token-1')).toBe(true); // Monitoring-Endpunkte sind öffentlich
});
it('liest den Produktkatalog des Lizenzsystems (Preis, Dauer, Features) ohne Schlüssel', async () => {
const items = await mk().listCatalog!(ctx);
@ -111,3 +114,33 @@ describe('Lizenz-Connector (neues Lizenzsystem)', () => {
expect(await mk().capabilities({ ...ctx, secrets: {} })).not.toContain('lifecycle.suspend'); // ohne Zugang nur lesend
});
});
describe('Lizenz-Connector: Rechte aus Scopes, Widerruf, Idempotenz, Health (#43)', () => {
it('Service-Token ohne eingetragene Scopes ist nur lesend; Teilmengen schalten nur ihre Aktionen frei', async () => {
const ro = { ...ctx, config: { ...ctx.config, scopes: '' } };
const caps = await mk().capabilities(ro);
expect(caps).toEqual(expect.arrayContaining(['resources.list', 'catalog.list']));
for (const w of ['lifecycle.create', 'lifecycle.suspend', 'lifecycle.extend', 'lifecycle.terminate', 'secret.reveal']) expect(caps).not.toContain(w);
const some = await mk().capabilities({ ...ctx, config: { ...ctx.config, scopes: 'licenses:read, licenses:suspend' } });
expect(some).toEqual(expect.arrayContaining(['lifecycle.suspend', 'lifecycle.unsuspend', 'secret.reveal']));
expect(some).not.toContain('lifecycle.extend'); expect(some).not.toContain('lifecycle.terminate'); expect(some).not.toContain('lifecycle.create');
expect(await mk().capabilities(ctx)).toContain('lifecycle.terminate');
});
it('Widerruf über /revoke mit Idempotency-Key aus der Auftrags-ID; Verlängerung ebenso', async () => {
const log: Call[] = []; const c = mk({ log });
const r = await c.execute!(ctx, { action: 'terminate', externalRef: '18', params: {}, idempotencyKey: 'job-123' } as never);
expect(r.resource.state).toBe('suspended');
expect(log.find((x) => x.path === '/licenses/18/revoke')).toMatchObject({ method: 'POST', idem: 'kc:job-123' });
await c.execute!(ctx, { action: 'extend', externalRef: '18', params: { until: '2027-01-01T00:00:00Z' }, idempotencyKey: 'job-124' } as never);
expect(log.find((x) => x.path === '/licenses/18/extend')?.idem).toBe('kc:job-124');
});
it('403 (fehlender Scope) wird als fehlendes Recht gemeldet, nicht als Anmeldefehler', async () => {
const c = mk(); const ro = { ...ctx, secrets: { token: 'svc-readonly' } };
await expect(c.execute!(ro, { action: 'suspend', externalRef: '18', params: {}, idempotencyKey: 'j' } as never)).rejects.toMatchObject({ code: 'UNSUPPORTED' });
await expect(c.execute!({ ...ctx, secrets: { token: 'falsch' } }, { action: 'suspend', externalRef: '18', params: {}, idempotencyKey: 'j' } as never)).rejects.toMatchObject({ code: 'AUTH_FAILED' });
});
it('Health nutzt /ready', async () => {
const log: Call[] = []; expect((await mk({ log }).healthCheck(ctx)).ok).toBe(true);
expect(log.map((x) => x.path)).toEqual(['/ready']);
});
});