main
1import { chmod, mkdtemp, rm } from 'node:fs/promises';
2import { tmpdir } from 'node:os';
3import { join } from 'node:path';
4import { afterEach, describe, expect, it } from 'vitest';
5import { ABSENT_REVISION, BASIS_POINTS } from '../../src/flags/ttl.ts';
6import { EMPTY_DOCUMENT, type ReadResult, type WriteResult } from '../../src/flags/types.ts';
7import {
8 handleOperator,
9 operatorEndpoint,
10 parseFlagArgs,
11 presentRevision,
12 rpcRevision,
13 type FlagControlBinding,
14 type OperatorDeps,
15 type OperatorEnv,
16} from '../../src/flags/operator.ts';
17import { readOperatorToken, runFlagsCli, writeOperatorTokenFile } from '../../scripts/flags-cli.ts';
19/** Null and a missing value take the fallback. An empty string and 0 stay. */
20function fill<T>(value: unknown, fallback: T): T {
21 return value === null || value === void 0 ? fallback : value as T;
22}
24/** One property. A null receiver and a missing key are holes. A stored null stays null. */
25function slot(receiver: unknown, key: string): unknown {
26 if (receiver === null || receiver === void 0) return void 0;
27 if (typeof receiver !== 'object' && typeof receiver !== 'function') return void 0;
28 return (receiver as Record<string, unknown>)[key];
29}
31const TOKEN = 'operator-test-token-value';
32const ROLLED_BACK = 0;
33const ADVANCE_MS = 4.25;
35const dirs: string[] = [];
37afterEach(async () => {
38 await Promise.all(dirs.splice(0).map(dir => rm(dir, { recursive: true, force: true })));
39});
41function deps(clock: () => number, lines: string[], order: string[]): OperatorDeps {
42 return {
43 clock,
44 log: line => lines.push(line),
45 tracing: {
46 enterSpan(name: string) {
47 order.push(`span:${name}`);
48 return { setAttribute() {}, end() { order.push('end'); } };
49 },
50 },
51 };
52}
54function request(path: string, method: string, token: string | null, body: string | void = void 0): Request {
55 const headers = new Headers();
56 if (token !== null) headers.set('authorization', `Bearer ${token}`);
57 if (body !== void 0) headers.set('content-type', 'application/json');
58 const init: RequestInit = { method, headers };
59 if (body !== void 0) init.body = body;
60 return new Request(`https://operator.test${path}`, init);
61}
63function control(impl: Partial<FlagControlBinding> = {}): FlagControlBinding {
64 return {
65 async getConfig(): Promise<ReadResult> {
66 throw new Error('getConfig was called');
67 },
68 async setRollout(): Promise<WriteResult> {
69 throw new Error('setRollout was called');
70 },
71 async setTargeting(): Promise<WriteResult> {
72 throw new Error('setTargeting was called');
73 },
74 ...impl,
75 };
76}
78describe('operator http', () => {
79 it('rejects anonymous and wrong bearers before any RPC or body read', async () => {
80 let calls = 0;
81 const env: OperatorEnv = { FLAG_OPERATOR_TOKEN: TOKEN, FLAG_CONTROL: control({ async setRollout() { calls += 1; return { kind: 'unavailable', reason: 'called' }; } }) };
82 const lines: string[] = [];
83 const missing = await handleOperator(request('/rollout', 'POST', null, '{'), env, deps(() => 0, lines, []));
84 expect(missing.status).toBe(401);
85 expect(await missing.json()).toEqual({ kind: 'unauthorized' });
86 const wrong = await handleOperator(request('/config', 'GET', 'other-operator-token'), env, deps(() => 0, lines, []));
87 expect(wrong.status).toBe(401);
88 expect(calls).toBe(0);
89 expect(lines.join('\n')).not.toContain(TOKEN);
90 const logged = JSON.parse(fill(lines[0], '{}')) as { msg: string; operator_ms: number; result: string };
91 expect(logged.msg).toBe('flags.operator');
92 expect(logged.result).toBe('unauthorized');
93 expect(logged.operator_ms).toBe(0);
94 });
96 it('fails closed when the secret or the binding is missing', async () => {
97 const lines: string[] = [];
98 const unconfigured = await handleOperator(request('/config', 'GET', TOKEN), { FLAG_OPERATOR_TOKEN: null, FLAG_CONTROL: null }, deps(() => 0, lines, []));
99 expect(unconfigured.status).toBe(503);
100 expect(await unconfigured.json()).toEqual({ kind: 'unavailable', reason: 'FLAG_OPERATOR_TOKEN is not configured' });
101 const unbound = await handleOperator(
102 request('/rollout', 'POST', TOKEN, JSON.stringify({ flag: 'ply.usage.note', basisPoints: ROLLED_BACK, expected: { kind: 'absent' } })),
103 { FLAG_OPERATOR_TOKEN: TOKEN, FLAG_CONTROL: null },
104 deps(() => 0, lines, []),
105 );
106 expect(unbound.status).toBe(503);
107 const body = await unbound.json() as { reason: string };
108 expect(body.reason).toContain('FLAG_CONTROL');
109 });
111 it('seeds an absent ruleset with optimistic concurrency and times the RPC', async () => {
112 let now = 0;
113 const order: string[] = [];
114 const lines: string[] = [];
115 let seen: Partial<{ flag: string; basisPoints: number; expected: string }> = {};
116 const env: OperatorEnv = {
117 FLAG_OPERATOR_TOKEN: TOKEN,
118 FLAG_CONTROL: control({
119 async setRollout(flag, basisPoints, expectedRevision) {
120 order.push('rpc');
121 seen = { flag, basisPoints, expected: expectedRevision };
122 now += ADVANCE_MS;
123 return { kind: 'ok', revision: '"rev"', config: EMPTY_DOCUMENT, unchanged: false, invalidated: true };
124 },
125 }),
126 };
127 const response = await handleOperator(
128 request('/rollout', 'POST', TOKEN, JSON.stringify({ flag: 'ply.usage.note', basisPoints: ROLLED_BACK, expected: { kind: 'absent' } })),
129 env,
130 deps(() => now, lines, order),
131 );
132 expect(response.status).toBe(200);
133 expect(response.headers.get('cache-control')).toBe('no-store');
134 expect(seen).toEqual({ flag: 'ply.usage.note', basisPoints: ROLLED_BACK, expected: ABSENT_REVISION });
135 expect(order[0]).toBe('span:flags.operator');
136 expect(order).toContain('rpc');
137 expect(order.at(-1)).toBe('end');
138 const logged = JSON.parse(fill(lines[0], '{}')) as { op: string; result: string; operator_ms: number; expected: string; invalidated: boolean };
139 expect(logged).toMatchObject({ op: 'setRollout', result: 'ok', operator_ms: ADVANCE_MS, expected: 'absent', invalidated: true });
140 expect(lines[0]).not.toContain(TOKEN);
141 });
143 it('returns 409 on a conflict and 503 without the thrown message', async () => {
144 const conflictEnv: OperatorEnv = {
145 FLAG_OPERATOR_TOKEN: TOKEN,
146 FLAG_CONTROL: control({
147 async setRollout() {
148 return { kind: 'conflict', expected: ABSENT_REVISION, actual: '"other"' };
149 },
150 }),
151 };
152 const conflict = await handleOperator(
153 request('/rollout', 'POST', TOKEN, JSON.stringify({ flag: 'ply.usage.note', basisPoints: ROLLED_BACK, expected: { kind: 'absent' } })),
154 conflictEnv,
155 deps(() => 0, [], []),
156 );
157 expect(conflict.status).toBe(409);
158 expect(await conflict.json()).toEqual({ kind: 'conflict', expected: ABSENT_REVISION, actual: '"other"' });
159 const throwing: OperatorEnv = {
160 FLAG_OPERATOR_TOKEN: TOKEN,
161 FLAG_CONTROL: control({
162 async getConfig() {
163 throw new Error(`secret leak ${TOKEN}`);
164 },
165 }),
166 };
167 const lines: string[] = [];
168 const failed = await handleOperator(request('/config', 'GET', TOKEN), throwing, deps(() => 0, lines, []));
169 expect(failed.status).toBe(503);
170 const text = await failed.text();
171 expect(text).toContain('flag operator failed');
172 expect(text).not.toContain(TOKEN);
173 expect(lines.join('\n')).not.toContain(TOKEN);
174 const line = lines.length > 0 ? lines[0] : '{}';
175 expect(JSON.parse(line)).toMatchObject({ result: 'unexpected', op: 'reject' });
176 });
178 it('rejects a bad expectation before calling FlagControl', async () => {
179 let calls = 0;
180 const env: OperatorEnv = {
181 FLAG_OPERATOR_TOKEN: TOKEN,
182 FLAG_CONTROL: control({ async setRollout() { calls += 1; return { kind: 'unavailable', reason: 'called' }; } }),
183 };
184 const response = await handleOperator(
185 request('/rollout', 'POST', TOKEN, JSON.stringify({ flag: 'ply.usage.note', basisPoints: ROLLED_BACK, expected: { kind: 'revision', value: '' } })),
186 env,
187 deps(() => 0, [], []),
188 );
189 expect(response.status).toBe(400);
190 expect(calls).toBe(0);
191 const absent = presentRevision('');
192 expect(absent).toBeNull();
193 expect(rpcRevision({ kind: 'absent' })).toBe(ABSENT_REVISION);
194 const present = presentRevision('"rev"');
195 expect(present).toBe('"rev"');
196 if (present) expect(rpcRevision({ kind: 'revision', value: present })).toBe('"rev"');
197 });
198});
200describe('flags cli', () => {
201 it('parses the seed command and refuses a token argument', () => {
202 const parsed = parseFlagArgs(['rollout', 'ply.usage.note', '0', '--expected', 'absent', '--url', 'https://example.test']);
203 expect(parsed).toEqual({
204 kind: 'command',
205 url: 'https://example.test',
206 command: { kind: 'setRollout', flag: 'ply.usage.note', basisPoints: ROLLED_BACK, expected: { kind: 'absent' } },
207 });
208 expect(parseFlagArgs(['rollout', 'ply.usage.note', '0', '--token', TOKEN]).kind).toBe('error');
209 expect(parseFlagArgs(['rollout', 'ply.usage.note', String(BASIS_POINTS + 1), '--expected', 'absent']).kind).toBe('error');
210 expect(operatorEndpoint('https://user:secret@example.test', '/rollout')).toBeNull();
211 expect(operatorEndpoint('https://example.test/ignored', '/config')).toBe('https://example.test/config');
212 });
214 it('requires mode 0600 and does not echo the file', async () => {
215 const dir = await mkdtemp(join(tmpdir(), 'ply-flag-token-'));
216 dirs.push(dir);
217 const path = join(dir, 'token');
218 await writeOperatorTokenFile(path, `${TOKEN}\n`, 0o644);
219 await expect(readOperatorToken(path)).rejects.toThrow(/FLAG_OPERATOR_TOKEN_FILE/);
220 await expect(readOperatorToken(path)).rejects.toThrow(/0600/);
221 try {
222 await readOperatorToken(path);
223 } catch (error) {
224 expect(String(error)).not.toContain(TOKEN);
225 }
226 await chmod(path, 0o600);
227 expect((await readOperatorToken(path)).reveal()).toBe(TOKEN);
228 });
230 it('sends the bearer and prints a redacted body', async () => {
231 const dir = await mkdtemp(join(tmpdir(), 'ply-flag-cli-'));
232 dirs.push(dir);
233 const path = join(dir, 'token');
234 await writeOperatorTokenFile(path, TOKEN, 0o600);
235 const stdout: string[] = [];
236 const stderr: string[] = [];
237 let authorization = '';
238 let body = '';
239 const code = await runFlagsCli(
240 ['rollout', 'ply.usage.note', '0', '--expected', 'absent', '--url', 'http://127.0.0.1:9'],
241 { FLAG_OPERATOR_TOKEN_FILE: path },
242 {
243 async fetch(_url, init) {
244 authorization = fill(new Headers(slot(init, 'headers') as HeadersInit).get('authorization'), '');
245 body = String(fill(slot(init, 'body'), ''));
246 return new Response(JSON.stringify({ kind: 'ok', revision: '"rev"', note: TOKEN }), { status: 200 });
247 },
248 stdout: line => stdout.push(line),
249 stderr: line => stderr.push(line),
250 readToken: readOperatorToken,
251 },
252 );
253 expect(code).toBe(0);
254 expect(authorization).toBe(`Bearer ${TOKEN}`);
255 expect(JSON.parse(body)).toMatchObject({ flag: 'ply.usage.note', basisPoints: ROLLED_BACK, expected: { kind: 'absent' } });
256 expect(stdout.join('')).toContain('[redacted]');
257 expect(stdout.join('')).not.toContain(TOKEN);
258 expect(stderr.join('')).not.toContain(TOKEN);
259 const help: string[] = [];
260 expect(await runFlagsCli([], {}, { fetch: async () => { throw new Error('fetch'); }, stdout: line => help.push(line), stderr: () => {}, readToken: readOperatorToken })).toBe(0);
261 expect(help.join('')).toContain('rollout');
262 let fetched = false;
263 const missing = await runFlagsCli(['get'], {}, {
264 fetch: async () => { fetched = true; return new Response('{}'); },
265 stdout: () => {},
266 stderr: () => {},
267 readToken: readOperatorToken,
268 });
269 expect(missing).toBe(2);
270 expect(fetched).toBe(false);
271 });
272});
Diagnostics4 git calls · 382 ms
CallStatusSizeTime0382 ms
discover200152 B4 ms
git.upload-pack discover http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=4 git.response.bytes=152 git.server.agent=gitty/1.0 git.server.object_format=sha1 git.server.caps=agent ls-refs fetch object-format git.server.fetch=shallow filter sideband-all git.protocol.version=2 git.pkt.frames=8 git.pkt.data=6 git.pkt.flush=2 git.pkt.delim=0 git.pkt.bytes=152 git.pkt.payload.max=34
ls-refs200145 B · hit4 ms
git.upload-pack ls-refs http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=ls-refs git.upstream.dur_ms=4 git.response.bytes=145 git.response.cache=HIT git.response.duration_ms=4 git.protocol.version=2 git.pkt.frames=3 git.pkt.data=2 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=145 git.pkt.payload.max=76 git.ls_refs.count=2 git.ls_refs.head=refs/heads/main
fetchblob:none · deepen 1020040 KiB · hit2 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=2 git.response.bytes=41349 git.response.cache=HIT git.response.duration_ms=2 git.fetch.filter=blob:none git.fetch.filter.requested=tree:0 git.fetch.filter.fallback=blob:none git.fetch.filter.learned=false git.fetch.wants=526b305930b8ef382f2d7a1f9c0238730a585921 git.fetch.haves.count=0 git.fetch.deepen=10 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=6 git.pkt.data=4 git.pkt.flush=1 git.pkt.delim=1 git.pkt.bytes=41349 git.pkt.payload.max=41254 git.sideband.band1.bytes=41253 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0 git.pack.objects=61 git.pack.bytes=41253 git.pack.ofs_delta=0 git.pack.ref_delta=0 git.pack.chain.max=0 git.pack.trailer=ab60efef4b7243678c75de64a4386986ee885c1c git.pack.full=61Open pack map
fetch2003.3 KiB376 ms
git.upload-pack fetch http.response.status_code=200 git.upstream.cf_ray=- git.upstream.phase=fetch git.upstream.dur_ms=376 git.response.bytes=3383 git.response.cache=MISS git.response.duration_ms=376 git.fetch.wants=b1a124c0d56847714fac6fc51a07aa31255d787c git.fetch.haves.count=0 git.fetch.deepen=0 git.fetch.thin_pack=false git.fetch.ofs_delta=true git.protocol.version=2 git.pkt.frames=3 git.pkt.data=2 git.pkt.flush=1 git.pkt.delim=0 git.pkt.bytes=3383 git.pkt.payload.max=3362 git.sideband.band1.bytes=3361 git.sideband.band2.bytes=0 git.sideband.band3.bytes=0
Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.
- Remote
- https://5ad2236b39de4c8bd8f6270ea63f3ea9.artifacts.cloudflare.net/git/public-v0/ply-web.git
- Ref
- refs/heads/main
- Commit
- 526b305930b8ef382f2d7a1f9c0238730a585921
- cf-ray
- a5e2c9d1adac4b67
- Request
- c3926611…
- Protocol
- v2 · sha1
- Agent
- gitty/1.0
- Filter
- advertised
- Fetch
- shallow filter sideband-all
- Capabilities
- agent ls-refs fetch object-format