fffleet-orchestrator 2.9.0 → 2.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -18,7 +18,11 @@ docker run -p 5000:5000 -e FFFLEET_TOKEN=... -e FFFLEET_WORKER_TOKEN=... ghcr.io
18
18
  | `FFFLEET_CLIENTS_FILE` | | Apps that may log in (`POST /v1/auth/token`). Add one with `fffleet-orchestrator add-client <id> --scope jobs`. |
19
19
  | `FFFLEET_SIGNING_KEY_FILE` | | Ed25519 key for tokens, created when missing. Without it tokens end at a restart. |
20
20
  | `FFFLEET_TOKEN_TTL_SECONDS` | `3600` | |
21
- | `FFFLEET_WORKER_TOKEN` | | Token workers register with. The orchestrator also sends it when it calls workers. |
21
+ | `FFFLEET_WORKER_TOKEN` | | Token workers register with. The orchestrator also sends it when it calls workers. With an issuer configured and no worker token, only issuer tokens with the `worker` scope and autoscaled workers' join secrets may register. |
22
+ | `FFFLEET_OIDC_ISSUER`, `FFFLEET_OIDC_JWKS_URL`, `FFFLEET_OIDC_AUDIENCE` | | Also accept tokens (RS256 or EdDSA) from an external OIDC issuer: expected `iss`, where its public keys are, and this orchestrator's resource identifier (`aud`). See [External issuer](https://github.com/jsilvanus/fffleet#external-issuer-service-tokens). |
23
+ | `FFFLEET_OIDC_SCOPES` | `fleet:submit=jobs,fleet:work=worker,fleet:dispatch=dispatch,fleet:admin=admin,fleet:metrics=metrics` | Issuer scope names to fffleet scopes (`external=internal`, comma separated). |
24
+ | `FFFLEET_OIDC_WORKER_ID_PREFIX` | | A `worker` token may also register worker ids that start with this (otherwise the id must equal the token's `sub`). |
25
+ | `FFFLEET_OIDC_TOKEN_URL`, `FFFLEET_OIDC_DISPATCH_CLIENT_ID`, `FFFLEET_OIDC_DISPATCH_CLIENT_SECRET`, `FFFLEET_OIDC_DISPATCH_RESOURCE` | | The orchestrator's own login for calling workers that registered with an issuer token (scope `fleet:dispatch`, `FFFLEET_OIDC_DISPATCH_SCOPE` to change it; the resource is the workers' audience). |
22
26
  | `FFFLEET_HEARTBEAT_TIMEOUT_MS` | `15000` | |
23
27
  | `FFFLEET_MAX_QUEUED` | `1000` | Above this, submissions get 503. |
24
28
  | `FFFLEET_STATE_FILE` | | SQLite file that keeps jobs across restarts (needs Node 22.13 or later; the Docker image has it). Without it a restart forgets the queue. |
@@ -27,7 +27,37 @@ if (configPath) {
27
27
  }
28
28
  }
29
29
 
30
+ // Tokens from an external OIDC issuer (service tokens). FFFLEET_OIDC_AUDIENCE is this orchestrator's resource identifier.
31
+ const oidc = env.FFFLEET_OIDC_ISSUER
32
+ ? {
33
+ issuer: env.FFFLEET_OIDC_ISSUER,
34
+ jwksUrl: env.FFFLEET_OIDC_JWKS_URL,
35
+ audience: env.FFFLEET_OIDC_AUDIENCE,
36
+ scopes: env.FFFLEET_OIDC_SCOPES || null,
37
+ workerIdPrefix: env.FFFLEET_OIDC_WORKER_ID_PREFIX || null,
38
+ // The orchestrator's own login for calling workers: FFFLEET_OIDC_DISPATCH_RESOURCE is the workers' audience.
39
+ dispatch: env.FFFLEET_OIDC_DISPATCH_CLIENT_ID
40
+ ? {
41
+ tokenUrl: env.FFFLEET_OIDC_TOKEN_URL,
42
+ clientId: env.FFFLEET_OIDC_DISPATCH_CLIENT_ID,
43
+ clientSecret: env.FFFLEET_OIDC_DISPATCH_CLIENT_SECRET,
44
+ resource: env.FFFLEET_OIDC_DISPATCH_RESOURCE || undefined,
45
+ scope: env.FFFLEET_OIDC_DISPATCH_SCOPE || undefined,
46
+ }
47
+ : null,
48
+ }
49
+ : null;
50
+ if (oidc && !(oidc.jwksUrl && oidc.audience)) {
51
+ console.error('[fffleet-orchestrator] FFFLEET_OIDC_ISSUER needs FFFLEET_OIDC_JWKS_URL and FFFLEET_OIDC_AUDIENCE');
52
+ process.exit(1);
53
+ }
54
+ if (oidc?.dispatch && !(oidc.dispatch.tokenUrl && oidc.dispatch.clientSecret)) {
55
+ console.error('[fffleet-orchestrator] FFFLEET_OIDC_DISPATCH_CLIENT_ID needs FFFLEET_OIDC_TOKEN_URL and FFFLEET_OIDC_DISPATCH_CLIENT_SECRET');
56
+ process.exit(1);
57
+ }
58
+
30
59
  const orchestrator = createOrchestrator({
60
+ oidc,
31
61
  scaling,
32
62
  placement,
33
63
  port: Number(env.PORT ?? 5000),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fffleet-orchestrator",
3
- "version": "2.9.0",
3
+ "version": "2.10.0",
4
4
  "description": "fffleet orchestrator: schedules ffmpeg jobs across a pool of fffleet workers",
5
5
  "type": "module",
6
6
  "main": "./src/orchestrator.js",
@@ -21,7 +21,7 @@
21
21
  "test": "node --test test/*.test.js"
22
22
  },
23
23
  "dependencies": {
24
- "fffleet": "^2.9.0"
24
+ "fffleet": "^2.10.0"
25
25
  },
26
26
  "keywords": [
27
27
  "ffmpeg",
@@ -5,10 +5,10 @@ import { createProviders } from './providers/index.js';
5
5
  import { openSqliteJobStore } from './job-store.js';
6
6
  import { serveUi } from './ui.js';
7
7
  import { randomUUID } from 'node:crypto';
8
- import { FleetError, JobRecord, byPriority, canonicalJson, followJobEvents, implicitRequirements, normalizeKinds, normalizeSlots, parseSpec, pruneFinished, resolveVariant, satisfies } from 'fffleet';
8
+ import { FleetError, JobRecord, createTokenProvider, byPriority, canonicalJson, followJobEvents, implicitRequirements, normalizeKinds, normalizeSlots, parseSpec, pruneFinished, resolveVariant, satisfies } from 'fffleet';
9
9
  import {
10
10
  Registry, allowed, checkBearer, close, createApiHandler, createAuthenticator, createClientStore, createTokenSigner, createTokenVerifier,
11
- bearerOf, getStream, issueToken, jobMetrics, listen, loadSigningKey, processMetrics, readBody, readJson, send, sendError,
11
+ bearerOf, createExternalIssuer, getStream, issueToken, jobMetrics, listen, loadSigningKey, processMetrics, readBody, readJson, send, sendError,
12
12
  } from 'fffleet/server';
13
13
 
14
14
  const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version;
@@ -36,6 +36,10 @@ const REDISPATCH_DELAY_MS = 500;
36
36
  * @param {{ publicUrl: string | null, autoscale: object, pools: object[] } | null} [opts.scaling] Where to start more workers (see loadConfig). Without it the pool is whatever registers.
37
37
  * @param {Record<string, object>} [opts.providers] Provider instances by pool name, replacing the built-in ones (tests).
38
38
  * @param {Buffer | string | null} [opts.joinKey] Key the workers' join secrets derive from. Default: the signing key's file contents, else random.
39
+ * @param {object | null} [opts.oidc] Tokens from an external OIDC issuer (service tokens): { issuer, jwksUrl, audience, scopes?, workerIdPrefix?, dispatch?, fetch? }.
40
+ * `audience` is this orchestrator's resource identifier. `scopes` maps external scope names to jobs/worker/dispatch/admin/metrics (default fleet:submit, fleet:work, fleet:dispatch, fleet:admin, fleet:metrics).
41
+ * `workerIdPrefix`: a worker token may also register ids that start with it (otherwise the id must equal the token's `sub`).
42
+ * `dispatch`: { tokenUrl, clientId, clientSecret, resource, scope? } the orchestrator logs in with to call workers that did not register with a long-lived secret; `resource` is the workers' audience.
39
43
  * @param {string | null} [opts.workerToken] Bearer token workers register with; also sent to workers.
40
44
  * @param {number} [opts.heartbeatTimeoutMs] A worker silent this long is dropped and its jobs fail.
41
45
  * @param {number} [opts.sweepMs]
@@ -61,6 +65,7 @@ export function createOrchestrator({
61
65
  placement: placementRules = [],
62
66
  providers: providerOverrides = {},
63
67
  joinKey = null,
68
+ oidc = null,
64
69
  workerToken = null,
65
70
  heartbeatTimeoutMs = 15000,
66
71
  sweepMs = 1000,
@@ -100,11 +105,45 @@ export function createOrchestrator({
100
105
  };
101
106
  const clientStore = createClientStore(clients);
102
107
  const signer = createTokenSigner({ privateKey: signingKey ?? loadSigningKey(signingKeyFile), ttlSeconds: tokenTtlSeconds });
103
- const authenticate = createAuthenticator({
108
+ const external = oidc ? createExternalIssuer({ issuer: oidc.issuer, jwksUrl: oidc.jwksUrl, audience: oidc.audience, scopes: oidc.scopes, fetch: oidc.fetch }) : null;
109
+ const authenticateRaw = createAuthenticator({
104
110
  token,
105
111
  verify: clientStore ? createTokenVerifier({ getKey: kid => (kid === signer.kid ? signer.publicKey : null) }) : null,
106
112
  isActive: sub => clientStore?.has(sub) ?? false,
113
+ external,
107
114
  });
115
+ // A client id that exists in the clients file and also comes with a token from the issuer would share jobs: say so once.
116
+ const warnedIds = new Set();
117
+ const authenticate = async req => {
118
+ const who = await authenticateRaw(req);
119
+ if (who && external && clientStore?.has(who.sub) && !warnedIds.has(who.sub)) {
120
+ const given = bearerOf(req);
121
+ if (given && given.split('.').length === 3 && token !== given) {
122
+ try {
123
+ if (JSON.parse(Buffer.from(given.split('.')[1], 'base64url').toString('utf8')).iss === external.issuer) {
124
+ warnedIds.add(who.sub);
125
+ log(`client id "${who.sub}" exists in the clients file and in the external issuer: both owners are the same, so they share jobs`);
126
+ }
127
+ } catch {
128
+ // Not our concern here; the token was already accepted.
129
+ }
130
+ }
131
+ }
132
+ return who;
133
+ };
134
+ // The orchestrator calls workers that registered with an issuer token (which expires) with its own dispatch token.
135
+ const dispatchLogin = oidc?.dispatch ? createTokenProvider({ tokenUrl: oidc.dispatch.tokenUrl, resource: oidc.dispatch.resource, clientId: oidc.dispatch.clientId, clientSecret: oidc.dispatch.clientSecret, scope: oidc.dispatch.scope ?? 'fleet:dispatch', fetch: oidc.fetch }) : null;
136
+ let dispatchToken = null;
137
+ let dispatchTimer = null;
138
+ async function refreshDispatchToken() {
139
+ if (!dispatchLogin) return;
140
+ try {
141
+ dispatchToken = await dispatchLogin.get();
142
+ } catch (err) {
143
+ log(`dispatch login failed: ${err.message}`);
144
+ }
145
+ }
146
+ const workerIdAllowed = (who, id) => who.sub === id || (oidc?.workerIdPrefix ? id.startsWith(oidc.workerIdPrefix) : false);
108
147
 
109
148
  let autoscaler = null;
110
149
  const registry = new Registry();
@@ -152,9 +191,10 @@ export function createOrchestrator({
152
191
  * @typedef {JobRecord & { worker?: Worker | null, pool?: string, follow?: AbortController, assignedAt?: number, released?: boolean }} Job
153
192
  */
154
193
 
155
- // A worker is called with the token it registered with: the shared worker token, or its own join secret.
194
+ // A worker is called with the secret it registered with (the shared worker token or its own join secret),
195
+ // else with the dispatch token, else with the shared worker token.
156
196
  const workerHeaders = (worker, extra = {}) => {
157
- const t = worker?.token ?? workerToken;
197
+ const t = worker?.token ?? (dispatchToken || workerToken);
158
198
  return { ...extra, ...(t ? { authorization: `Bearer ${t}` } : {}) };
159
199
  };
160
200
 
@@ -584,13 +624,24 @@ export function createOrchestrator({
584
624
  try {
585
625
  const body = await readJson(req);
586
626
  const given = bearerOf(req);
587
- // The shared worker token, or the join secret of a worker this orchestrator started itself.
588
- const ok = checkBearer(req, workerToken) || (given && body && autoscaler?.acceptsJoin(body.id, given));
627
+ // The shared worker token (open when none is set and no issuer is configured), or the join secret of a
628
+ // worker this orchestrator started itself, or a token with the `worker` scope for this worker id.
629
+ let ok = (workerToken ? checkBearer(req, workerToken) : !oidc) || (given && body && autoscaler?.acceptsJoin(body.id, given));
630
+ let bearer = given;
631
+ if (!ok && given && body && typeof body.id === 'string') {
632
+ const who = await authenticate(req);
633
+ // Admin tokens (the static token, `admin` clients) never register workers, as before: workers get the `worker` scope.
634
+ if (who && who.scopes.has('worker') && !who.admin && workerIdAllowed(who, body.id)) {
635
+ ok = true;
636
+ // A token that expires is not kept: the worker is called with the dispatch token.
637
+ bearer = null;
638
+ }
639
+ }
589
640
  if (!ok) {
590
641
  send(res, 401, { error: { code: 'UNAUTHORIZED', message: 'missing or wrong worker token' } });
591
642
  return true;
592
643
  }
593
- send(res, 200, register(body, given));
644
+ send(res, 200, register(body, bearer));
594
645
  } catch (err) {
595
646
  sendError(res, err);
596
647
  }
@@ -646,9 +697,16 @@ export function createOrchestrator({
646
697
  async start() {
647
698
  if (!jobStore && stateFile) jobStore = await openSqliteJobStore(stateFile);
648
699
  if (jobStore) restore();
700
+ if (oidc && scaling && !joinKey && !scaling.autoscale.joinSecret && scaling.pools.some(p => p.provider !== 'process')) {
701
+ throw new Error('with oidc enabled, autoscale.joinSecret (or joinKey) is required so autoscaled workers\' join secrets do not derive from the signing key');
702
+ }
649
703
  ({ server, url } = await listen(createApiHandler({ backend, authenticate, metrics: () => registry.render(), extraRoutes }), { port, host }));
650
704
  if (!token && !clientStore) log('no FFFLEET_TOKEN and no clients file: the job API is open to anyone who can reach it');
651
- if ((token || clientStore) && !workerToken && !scaling) log('no FFFLEET_WORKER_TOKEN: anyone who can reach this orchestrator can register a worker and receive jobs (docs/security.md)');
705
+ if ((token || clientStore) && !oidc && !workerToken && !scaling) log('no FFFLEET_WORKER_TOKEN: anyone who can reach this orchestrator can register a worker and receive jobs (docs/security.md)');
706
+ if (oidc && !oidc.dispatch && !workerToken) log('oidc without dispatch credentials and without FFFLEET_WORKER_TOKEN: workers that register with an issuer token are called without credentials (see docs/security.md)');
707
+ await refreshDispatchToken();
708
+ dispatchTimer = setInterval(refreshDispatchToken, 30000);
709
+ dispatchTimer.unref?.();
652
710
  sweeper = setInterval(sweep, sweepMs);
653
711
  sweeper.unref?.();
654
712
  log(`fffleet-orchestrator listening on ${url}`);
@@ -682,6 +740,7 @@ export function createOrchestrator({
682
740
  async stop() {
683
741
  await autoscaler?.stop();
684
742
  clearInterval(sweeper);
743
+ clearInterval(dispatchTimer);
685
744
  clearTimeout(pumpTimer);
686
745
  for (const job of jobs.values()) job.follow?.abort();
687
746
  if (server) await close(server);