mirror of
https://github.com/lukaszraczylo/traefik-llmgateway.git
synced 2026-12-06 11:03:52 +00:00
* feat(auth): add oidc config and per-identity overrides Add Config.OIDC with issuer, audiences, claim and group-map settings. The constructor validates the settings and applies defaults. A users-config entry with oidcIdentity is now a per-identity override. It sets the accounting name and the limits for one OIDC identity. It must not set an API key, groups, grants or admin. The admin config view sanitizes the issuer URL like a base URL. * feat(auth): verify oidc jwt access tokens locally Add a stdlib-only JWS verifier for OIDC access tokens. It accepts RS256, RS384, RS512, PS256, ES256 and ES384 only. It rejects "none", HMAC algorithms and a header algorithm that does not match the key. The verifier checks iss, exp and nbf with 60 seconds of skew, aud or azp against the configured audiences, and email_verified on request. JWKS parsing skips encryption keys and unsupported key types. It rejects an EC point that is not on its curve. * feat(auth): fetch oidc discovery, jwks and userinfo Add the OIDC provider client. It reads the discovery document on first use and checks that its issuer equals the configured issuer. It caches the JWKS and refreshes it every jwksRefresh. An unknown kid starts a refetch at most once per 60 seconds. A failed fetch is held for 5 seconds, and the last good keys stay in use. One fetch runs at a time, and each IdP response is capped at 1 MiB. * feat(auth): map oidc claims to cached virtual users Add the OIDC authenticator. It verifies a JWT locally, or an opaque token at the userinfo endpoint when that path is on. It then maps the group claim to configured gateway groups. A valid token with no mapped group gets a forbidden verdict. The virtual user is named "oidc:<identity>", or takes the override name. Its limits merge the override with the group memberLimits per field. Verdicts are cached until the token expires or cacheTTL ends. A refusal is cached for 30 seconds. An IdP outage is not cached. Virtual users are held in an LRU bounded by maxUsers. * feat(auth): admit oidc bearer tokens as virtual users With oidc configured, a Bearer token that matches no configured key goes to the OIDC authenticator. A configured key always wins first, and the anonymous fallbacks keep their previous order. A valid token without a mapped group gets 403 permission_error, in the route's own error shape. An invalid token gets 401 as before. The admin API and the metrics route stay key-only. All routes now use one requireAuth helper. The auth failure log line names the OIDC refusal reason. The yaegi-check harness signs RS256, PS256 and ES256 tokens and runs them through the interpreted plugin. * feat(admin): list oidc virtual users across replicas The admin snapshot now lists OIDC virtual users with source "oidc". Each one counts in the memberCount of every mapped group. Scope checks and the rejection prune after a users-file reload see them too. With Redis configured, each replica records the users it admits in the llmgw:oidc:users hash, at most once per minute per user. The snapshot reads the hash at most once every two seconds. It hides users whose groups are all gone, and users not seen for 32 days. Without Redis the list holds only the users this replica has seen. * feat(admin): badge oidc users The user panel shows an "OIDC" badge for a virtual user that an OIDC bearer token admitted. The consumer source type now includes "oidc". * docs(auth): document oidc virtual users Add the "OIDC users (Open WebUI)" section and the OIDCConfig reference table. The section covers precedence, 401 against 403, the oidc: name prefix, per-person overrides, the token cache, the Redis registry and the userinfo audience limit. It also lists the Open WebUI connection steps. * fix(auth): harden oidc key fetch, userinfo and jwks handling The discovery and JWKS fetch now runs on its own 5s deadline, so one caller's cancel cannot fail it for every request. Discovery failures now use the same 5s retry hold on the userinfo path. Userinfo calls are capped at 16 in flight. Only an IdP 401 or 403 is cached as a rejection. Timeouts, 5xx and 429 are not cached. Refused tokens use their own cache, so a flood cannot evict valid verdicts. An unknown kid is not cached, because the keys can be stale. A disallowed alg is refused before any key fetch. The jwks_uri and userinfo_endpoint must be https or loopback http. A malformed key, or an RSA key under 2048 bits, is skipped instead of failing the set. The identity is case-folded only for the email claim. IdP failure causes are logged, rate-gated, and the no_group reason names the identity. The Redis registry deletes records past the 32-day retention. * fix(auth): close oidc audit leads on azp and userinfo slots A JWT now passes the audience check only when aud names a configured audience. The azp claim counts only with the new acceptAzp option, because a token that the client obtained for another service carries the same azp. Concurrent requests with one cold token now share one verification. A userinfo call waits up to 2s for a free slot instead of failing at once, and it no longer waits on the key fetch lock once discovery is cached. The IdP client does not follow redirects. A bearer over 16384 bytes and an identity over 256 bytes get 401. Email identities fold only ASCII A-Z, so a look-alike character stays a separate identity.
234 lines
12 KiB
Vue
234 lines
12 KiB
Vue
<script setup lang="ts">
|
|
import { Badge, Button, DescriptionItem, DescriptionList, StatusDot } from '@perfect-design/ui'
|
|
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
|
|
|
import LimitsForm from '@/components/forms/LimitsForm.vue'
|
|
import { useNow } from '@/composables/useNow'
|
|
import { providerAccessCell } from '@/lib/access-matrix'
|
|
import { kindLabel } from '@/lib/events-filter'
|
|
import { formatCompactCount, userSourceLabel } from '@/lib/format'
|
|
import { formatLastSeen } from '@/lib/last-seen'
|
|
import { loadState } from '@/lib/load-state'
|
|
import { effectiveLimitRows, meterModel } from '@/lib/meters'
|
|
import { useConsumersStore } from '@/stores/consumers'
|
|
import { useDashboardStore } from '@/stores/dashboard'
|
|
import { useEventsStore } from '@/stores/events'
|
|
import { useFiltersStore } from '@/stores/filters'
|
|
import { useNavStore } from '@/stores/nav'
|
|
import DetailPanel from '@/widgets/DetailPanel.vue'
|
|
import MeterBar from '@/widgets/MeterBar.vue'
|
|
import ModelName from '@/widgets/ModelName.vue'
|
|
import PanelSection from '@/widgets/PanelSection.vue'
|
|
import StateView from '@/widgets/StateView.vue'
|
|
import type { ViewState } from '@/widgets/StateView.vue'
|
|
|
|
const EVENT_ROWS = 8
|
|
const THROTTLE_KINDS: ReadonlySet<string> = new Set(['rate_limit', 'paced'])
|
|
|
|
const props = defineProps<{ id: string }>()
|
|
const emit = defineEmits<{ close: [] }>()
|
|
|
|
const dashboard = useDashboardStore()
|
|
const consumers = useConsumersStore()
|
|
const events = useEventsStore()
|
|
const filters = useFiltersStore()
|
|
const nav = useNavStore()
|
|
const { now, start: startClock, stop: stopClock } = useNow()
|
|
|
|
const entry = computed(() => dashboard.usage?.users.find((u) => u.id === props.id))
|
|
const consumer = computed(() => consumers.data?.users.find((u) => u.name === props.id))
|
|
const groups = computed(() => entry.value?.groups ?? (entry.value?.groupName ? [entry.value.groupName] : []))
|
|
|
|
// --- Meters + effective limits ---------------------------------------------
|
|
|
|
const meters = computed(() => (entry.value ? meterModel(entry.value, entry.value.limits) : []))
|
|
const limitRows = computed(() => effectiveLimitRows(entry.value?.limits, entry.value?.limitSources))
|
|
const exempt = computed(() => entry.value?.exemptRequestsPerMonth ?? 0)
|
|
|
|
// --- Models used ------------------------------------------------------------
|
|
|
|
const userModelStats = computed(() => dashboard.overview?.features.userModelStats ?? false)
|
|
const detail = computed(() => consumers.models[props.id])
|
|
const modelRows = computed(() =>
|
|
[...(detail.value?.totals?.rows ?? [])].sort((a, b) => (b.values.req ?? 0) - (a.values.req ?? 0)),
|
|
)
|
|
const modelsState = computed<ViewState>(() => {
|
|
if (dashboard.overview !== null && (!userModelStats.value || detail.value?.unavailable)) return 'empty'
|
|
const s = loadState({ loading: detail.value?.loading ?? true, hasData: detail.value?.totals != null, error: detail.value?.error ?? '' })
|
|
if (s === 'skeleton') return 'loading'
|
|
if (s === 'error') return 'error'
|
|
return modelRows.value.length === 0 ? 'empty' : 'ready'
|
|
})
|
|
const modelsEmptyTitle = computed(() => (userModelStats.value ? 'No model traffic in this range' : 'Per-user model statistics are off'))
|
|
const modelsEmptyDescription = computed(() => (userModelStats.value ? undefined : 'Enable admin.stats.userModel to see which models this user calls.'))
|
|
|
|
function loadModels(): Promise<void> {
|
|
return userModelStats.value ? consumers.fetchUserModels(props.id, filters.window, filters.span) : Promise.resolve()
|
|
}
|
|
|
|
// --- Throttle events --------------------------------------------------------
|
|
|
|
const throttled = computed(() => events.events.filter((e) => e.user === props.id && THROTTLE_KINDS.has(e.kind)).slice(0, EVENT_ROWS))
|
|
const eventsState = computed<ViewState>(() => {
|
|
const s = loadState({ loading: events.refreshing, hasData: events.lastUpdated !== null, error: events.error })
|
|
if (s === 'skeleton') return 'loading'
|
|
if (s === 'error') return 'error'
|
|
return throttled.value.length === 0 ? 'empty' : 'ready'
|
|
})
|
|
const EVENT_TONE: Record<string, 'warning' | 'info'> = { rate_limit: 'warning', paced: 'info' }
|
|
|
|
function clock(iso: string): string {
|
|
const d = new Date(iso)
|
|
return Number.isNaN(d.getTime()) ? '' : d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false })
|
|
}
|
|
|
|
// --- Access ----------------------------------------------------------------
|
|
|
|
const groupRows = computed(() => (consumers.data?.groups ?? []).filter((g) => groups.value.includes(g.name)))
|
|
interface ProviderAccess {
|
|
name: string
|
|
detail: string
|
|
zero: boolean
|
|
allowed: number
|
|
}
|
|
|
|
// With several groups, the most permissive one decides what the user can reach.
|
|
const providers = computed<ProviderAccess[]>(() => {
|
|
const best = new Map<string, ProviderAccess>()
|
|
for (const g of groupRows.value) {
|
|
for (const name of g.allowedProviders) {
|
|
const cell = providerAccessCell(g, name)
|
|
const allowed = g.modelAccess[name]?.allowed ?? Number.POSITIVE_INFINITY
|
|
const prev = best.get(name)
|
|
if (!prev || allowed > prev.allowed) best.set(name, { name, detail: cell.detail ?? '', zero: cell.zero === true, allowed })
|
|
}
|
|
}
|
|
return [...best.values()].sort((a, b) => a.name.localeCompare(b.name))
|
|
})
|
|
const accessState = computed<ViewState>(() => (consumers.data ? 'ready' : consumers.error ? 'error' : 'loading'))
|
|
|
|
// --- Snippet -----------------------------------------------------------------
|
|
|
|
const snippetOpen = ref(false)
|
|
const groupNames = computed(() => (consumers.data?.groups ?? []).map((g) => g.name))
|
|
const userNames = computed(() => (consumers.data?.users ?? []).map((u) => u.name))
|
|
|
|
watch([() => props.id, () => filters.range, userModelStats], () => void loadModels())
|
|
watch(() => props.id, () => (snippetOpen.value = false))
|
|
onMounted(() => {
|
|
startClock()
|
|
events.startPolling()
|
|
void consumers.ensureConsumers()
|
|
void loadModels()
|
|
})
|
|
onUnmounted(() => {
|
|
stopClock()
|
|
events.stopPolling()
|
|
})
|
|
</script>
|
|
|
|
<template>
|
|
<DetailPanel kind="user" :id="id" :title="id" @close="emit('close')">
|
|
<div class="flex flex-col divide-y px-1 pb-4" data-testid="user-panel">
|
|
<div v-if="!entry" class="text-muted-foreground py-3 text-sm">No usage scope for this user yet. It appears after their first request.</div>
|
|
<template v-else>
|
|
<div class="flex flex-wrap items-center gap-2 pb-3 text-sm">
|
|
<Badge v-if="consumer?.admin" tone="danger" size="sm">admin</Badge>
|
|
<Badge v-if="consumer?.source" tone="neutral" variant="outline" size="sm" data-testid="user-source">{{ userSourceLabel(consumer.source) }}</Badge>
|
|
<button
|
|
v-for="g in groups"
|
|
:key="g"
|
|
type="button"
|
|
class="hover:bg-accent rounded-md border px-2 py-0.5 text-xs"
|
|
@click="nav.openPanel('group', g)"
|
|
>
|
|
{{ g }}
|
|
</button>
|
|
<span class="text-muted-foreground ml-auto text-xs">last seen {{ formatLastSeen(entry.lastSeen, now) }}</span>
|
|
</div>
|
|
|
|
<PanelSection title="Meters">
|
|
<div v-if="meters.length" class="flex flex-col gap-3">
|
|
<MeterBar v-for="m in meters" :key="m.label" :meter="m" />
|
|
</div>
|
|
<p v-else class="text-muted-foreground m-0 text-sm">No limits apply to this user.</p>
|
|
</PanelSection>
|
|
|
|
<PanelSection title="Effective limits">
|
|
<DescriptionList v-if="limitRows.length || exempt" variant="inline" size="sm" density="compact">
|
|
<DescriptionItem v-for="r in limitRows" :key="r.key" :term="r.label">
|
|
<span class="flex flex-col items-end text-right">
|
|
<span :class="r.prose ? '' : 'font-mono tabular-nums'">{{ r.value }}</span>
|
|
<span v-if="r.source" class="text-muted-foreground text-xs">{{ r.source }}</span>
|
|
</span>
|
|
</DescriptionItem>
|
|
<DescriptionItem v-if="exempt" term="Exempt requests/month">
|
|
<span class="flex flex-col items-end text-right">
|
|
<span class="font-mono tabular-nums">{{ formatCompactCount(exempt) }}</span>
|
|
<span class="text-muted-foreground text-xs">limitExemptKinds</span>
|
|
</span>
|
|
</DescriptionItem>
|
|
</DescriptionList>
|
|
<p v-else class="text-muted-foreground m-0 text-sm">No limits set.</p>
|
|
</PanelSection>
|
|
|
|
<PanelSection title="Models used">
|
|
<StateView :state="modelsState" :empty-title="modelsEmptyTitle" :empty-description="modelsEmptyDescription" :error-message="detail?.error" :rows="3" @retry="loadModels()">
|
|
<ul class="m-0 flex list-none flex-col p-0" aria-label="Models used">
|
|
<li v-for="m in modelRows" :key="m.id" class="flex h-8 items-center justify-between gap-3 px-2 text-sm">
|
|
<ModelName :id="m.id" class="min-w-0" />
|
|
<span class="shrink-0 text-right font-mono text-xs tabular-nums">{{ formatCompactCount(m.values.req ?? 0) }} req</span>
|
|
</li>
|
|
</ul>
|
|
</StateView>
|
|
</PanelSection>
|
|
|
|
<PanelSection title="Recent rate-limit and paced events">
|
|
<StateView :state="eventsState" empty-title="No recent throttling" :error-message="events.error" :rows="2" @retry="events.refresh()">
|
|
<ul class="m-0 flex list-none flex-col p-0" aria-label="Recent throttle events">
|
|
<li v-for="(e, i) in throttled" :key="`${e.time}-${i}`" class="flex h-8 items-center gap-2 px-2 text-sm" :title="e.message">
|
|
<StatusDot class="shrink-0" :tone="EVENT_TONE[e.kind] ?? 'neutral'" size="md" />
|
|
<span class="text-muted-foreground shrink-0 font-mono text-xs">{{ clock(e.time) }}</span>
|
|
<span class="text-muted-foreground shrink-0">{{ kindLabel(e.kind) }}</span>
|
|
<span class="min-w-0 flex-1 truncate">{{ e.model || e.provider || e.route }}</span>
|
|
</li>
|
|
</ul>
|
|
</StateView>
|
|
</PanelSection>
|
|
|
|
<PanelSection title="Access">
|
|
<StateView :state="accessState" :error-message="consumers.error" :rows="2" @retry="consumers.fetchConsumers()">
|
|
<DescriptionList variant="stacked" size="sm" density="compact">
|
|
<DescriptionItem term="Providers">
|
|
<span v-if="providers.length === 0" class="text-muted-foreground">None granted by group</span>
|
|
<span v-else class="flex flex-wrap gap-1">
|
|
<Badge v-for="p in providers" :key="p.name" :tone="p.zero ? 'warning' : 'neutral'" variant="outline" size="sm" class="font-mono" :title="p.zero ? 'Provider granted, but no model matches the group model list' : undefined">{{ p.name }}<template v-if="p.detail"> · {{ p.detail }}</template></Badge>
|
|
</span>
|
|
</DescriptionItem>
|
|
<DescriptionItem v-if="consumer?.providers?.length" term="Personal providers">
|
|
<span class="flex flex-wrap gap-1">
|
|
<Badge v-for="p in consumer.providers" :key="p" tone="neutral" variant="outline" size="sm" class="font-mono">{{ p }}</Badge>
|
|
</span>
|
|
</DescriptionItem>
|
|
<DescriptionItem v-if="consumer?.models?.length" term="Personal models">
|
|
<span class="flex flex-col gap-1">
|
|
<ModelName v-for="m in consumer.models" :id="m" :key="m" />
|
|
</span>
|
|
</DescriptionItem>
|
|
</DescriptionList>
|
|
</StateView>
|
|
</PanelSection>
|
|
|
|
<PanelSection title="Change limits">
|
|
<div>
|
|
<Button variant="outline" size="sm" :aria-expanded="snippetOpen" @click="snippetOpen = !snippetOpen">
|
|
{{ snippetOpen ? 'Hide limits snippet' : 'Generate limits snippet' }}
|
|
</Button>
|
|
</div>
|
|
<LimitsForm v-if="snippetOpen" :group-names="groupNames" :user-names="userNames" preset-kind="user" :preset-name="id" />
|
|
</PanelSection>
|
|
</template>
|
|
</div>
|
|
</DetailPanel>
|
|
</template>
|