Files
silo-server/internal/streamtoken/token.go
T
CoffeeKnyte e5bf0155ad fix(playback): make revocation state converge and cutoffs credential-accurate
Five defects in revocation state and credential semantics. Lands after the
tracker-lifecycle batch on purpose: raising the over-cap TTL is only safe once
the count feeding it is trustworthy.

#13 -- a longer old revocation suppressed a newer cutoff. applyLocal kept or
replaced the WHOLE record by expiry, so when the existing revocation expired
later the new one was dropped entirely, including its newer RevokedAt. The
durable upsert did the same, with a comment documenting it as intentional.
RevokedAt is the user-kill CUTOFF, so this left a credential issued between the
two cutoffs valid -- a second admin kill after a user re-authenticates silently
failed to cut them. The two fields now merge independently: ExpiresAt stays
monotonic, RevokedAt advances to the later value, and reason follows the newer
cutoff. Both superseded comments are replaced rather than left contradicting the
code. Session-kind revocation still ignores RevokedAt, so the enforcer's
re-revoke cannot weaken a session kill.

Also fixed while here: Redis received the merged record but pub/sub published the
raw input one, so under pub/sub-only delivery (Redis down) an edge got the newer
short record without the older long expiry and lost monotonicity. Both now carry
the merged record.

#7 + M1 -- Postgres could indefinitely block the urgent Redis kill.
RevokeWithWarnings held the global opMu across all propagation, stripped the
caller's deadline with WithoutCancel, and did the durable Postgres upsert BEFORE
Redis, on a pool with no statement timeout. The local kill still applied, so
playback on that process was fine -- but edge propagation, pub/sub, the admin
response and every later revoke/unrevoke stalled behind the lock. Redis and
pub/sub now go first, and the detached context is bounded. WithoutCancel is kept
deliberately: propagation must outlive an aborted admin request.

opMu scope is deliberately NOT narrowed. mirrorToRedis is an unconditional SET
with no atomic merge, so same-process serialization is what stops an older value
overwriting a newer one; narrowing the lock would also let an unrevoke interleave
with a revoke's propagation. Bounding the context caps how long the lock can be
held, which is the actual reported harm. The remaining cross-replica race -- two
central replicas racing the same SET -- is documented, not half-fixed; it needs
A6's shared picture.

A2 / #6 -- a missed unrevoke got resurrected. In-memory tombstones already
existed, but being process-local they did not survive a restart or reach a
replica that missed the pub/sub event, so maintain's durable self-heal
re-Upserted the surviving entry and the ban returned. Tombstones are now durable,
via two nullable columns on stream_revocations rather than a second table: a
tombstone is a state of the same key, and it needs its own expiry horizon
separate from the revocation's. The upsert rejects a stale replica's write while
a tombstone is live but lets a genuinely newer revocation clear it, and warm
paths apply tombstones BEFORE revocations so an un-banned key cannot be restored
as a live kill. Tombstones are pruned on the same sweep, so the table cannot grow
without bound.

A1 / #3 -- over-cap kills reopened after 5 minutes while the token stayed
reconstructable for 24h. The TTL now derives from playback.MaxTokenTTL rather
than duplicating 24h, behind a validated setting.

Critically, the enforcer uses a revoke-if-absent path rather than re-revoking.
Expiry is monotonic and the enforcer re-evaluates every 30s, so a plain long TTL
would slide expiry forward by another full lifetime on every pass -- making a
wrong kill effectively permanent for as long as any stale record persisted, with
only an explicit unrevoke to recover it. Admin Revoke keeps its monotonic
behaviour; only the enforcer's own repeat kill is non-extending. The setting is
documented as affecting future revocations only, since monotonic expiry means it
cannot shorten one already issued.

A3 / #5 -- the user cutoff compared against a fresh time.Now() taken at request
entry, so a request from a pre-cutoff login could look post-cutoff and escape the
kill. The credential time is now the access token's iat.

Two deliberate choices worth stating. API-key credentials carry no issue time, so
they pass the zero time and, per IsRevoked's documented contract, are never
matched by a user cutoff: a user kill provably cannot cut an API-key-owned pour.
That is an accepted, logged, documented hole -- and strictly better than
time.Now(), which actively defeats the cutoff. And jellycompat uses the compat
session's CreatedAt rather than the bridged Silo token's iat, because that token
refreshes without a new Jellyfin login, so its iat would advance on refresh and
let a refreshed credential slip past a cutoff.

Stream tokens are now bound to their route: a token whose SessionID does not match
the URL's session_id is rejected with 403 instead of being silently ignored,
matching the reconstruction helper that already refused a different session.

Per-login logout cuts remain out of scope -- they need per-login identity in the
stream credential. S5 (the (sessionID, userID, startedAt) clump) is rejected as
ceremony now that A3 is the iat option rather than the generation model.

#12 (closing an RSS feed does not cut its current pour) is deferred: it needs a
namespaced revocation id that cannot collide with real session ids, that id
threaded onto public feed requests, and protection against a new feed inheriting
an old tombstone.

Part of #305.
2026-07-30 12:27:05 +00:00

122 lines
5.1 KiB
Go

package streamtoken
import (
"fmt"
"time"
"github.com/golang-jwt/jwt/v5"
)
// MaxTTL is the absolute lifetime of a stream token and therefore the longest
// a session can remain reconstructable.
const MaxTTL = 24 * time.Hour
// Claims holds everything a stateless proxy or transcode node needs
// to serve a streaming session without database access.
//
// Under token-carried reconstruction (TR-lease) the token is also the durable
// reconstruction descriptor: its claims carry the full set of byte-affecting
// encode parameters (the former Postgres "recipe card"), so a front-end that has
// lost its in-memory session can rebuild ffmpeg from the token the client
// re-presents — no shared per-session store. The ownership claims (uid/pid/mfid)
// are lookup keys re-resolved against the authority on reconstruct; they are
// never trusted on their own.
type Claims struct {
SessionID string `json:"sid"`
MediaPath string `json:"path"`
PlayMethod string `json:"method"`
TranscodeAudio bool `json:"ta,omitempty"`
TranscodeNode string `json:"tnode,omitempty"`
TranscodeTransportID string `json:"tid,omitempty"`
TargetCodec string `json:"tc,omitempty"`
TargetRes string `json:"tres,omitempty"`
AudioCodec string `json:"ac,omitempty"`
AudioChannels int `json:"ach,omitempty"`
AudioTrackIndex int `json:"ati,omitempty"`
// DVProfile is the file's Dolby Vision profile (0 = none); remux nodes
// use it to strip dangling profile 7 RPUs. Absent in older tokens, which
// decodes as 0 (no strip — the pre-existing behavior).
DVProfile int `json:"dvp,omitempty"`
// RemuxDVMode freezes whether a Profile 7 remux preserves or strips DV
// metadata. Empty is the legacy auto behavior for old tokens.
RemuxDVMode string `json:"dvm,omitempty"`
// Ownership / authorization lookup keys (re-resolved at reconstruct).
// Not trust assertions.
UserID int `json:"uid,omitempty"`
ProfileID string `json:"pid,omitempty"`
MediaFileID int `json:"mfid,omitempty"`
// Monitoring attribution (not byte-affecting, not a trust assertion): the
// origin protocol ("native" | "jellycompat") and the reported client/app
// name, carried so an edge node — which never sees the originating API path —
// can stamp them onto its live-session record for the first-class monitor view.
Origin string `json:"org,omitempty"`
ClientName string `json:"cn,omitempty"`
// Reconstruction recipe — the byte-affecting encode parameters, mirroring the
// former playback.RecipeCard. Zero for direct/remux tokens, which reconstruct
// from identity alone plus the client-supplied position.
SourceVideoCodec string `json:"svc,omitempty"`
VideoBitstreamFilter string `json:"vbsf,omitempty"`
OutputSubdir string `json:"osd,omitempty"`
SeekSeconds float64 `json:"seek,omitempty"`
StreamOriginSeconds float64 `json:"origin,omitempty"`
CopySeekAnchorResolved bool `json:"origin_ok,omitempty"`
SegmentDuration int `json:"segd,omitempty"`
StartSegmentNumber int `json:"ssn,omitempty"`
SubtitleTrackIndex int `json:"sti,omitempty"`
SubtitleBurnIn bool `json:"sbi,omitempty"`
SubtitleCodec string `json:"sbc,omitempty"`
TargetBitrateKbps int `json:"tbr,omitempty"`
TotalDuration float64 `json:"dur,omitempty"`
FastStart bool `json:"fs,omitempty"`
TargetCodecAudio string `json:"tca,omitempty"`
// Recipe staleness hint, bumped on each re-mint after a recipe mutation
// (audio/quality/seek switch). An optional client-side hint only.
Version int `json:"ver,omitempty"`
jwt.RegisteredClaims
}
// IssuedTime returns the token's iat as a time.Time, zero when absent. It is
// the credential-issue instant the revocation store's user-kill cutoff compares
// against (streamrevoke.Store.IsRevoked): a user revocation kills streams whose
// token predates it and spares ones minted after re-authentication.
func (c *Claims) IssuedTime() time.Time {
if c == nil || c.IssuedAt == nil {
return time.Time{}
}
return c.IssuedAt.Time
}
// Sign creates a signed JWT string from the given claims.
func Sign(c Claims, secret string, ttl time.Duration) (string, error) {
now := time.Now()
c.RegisteredClaims = jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(now.Add(ttl)),
IssuedAt: jwt.NewNumericDate(now),
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, c)
return token.SignedString([]byte(secret))
}
// Verify parses and validates a stream token JWT string.
func Verify(tokenString, secret string) (*Claims, error) {
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (any, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return []byte(secret), nil
})
if err != nil {
return nil, fmt.Errorf("invalid stream token: %w", err)
}
claims, ok := token.Claims.(*Claims)
if !ok || !token.Valid {
return nil, fmt.Errorf("invalid stream token claims")
}
return claims, nil
}