Skip to content

Commit 907f485

Browse files
committed
fix: address authenticated media review findings
1 parent 48ed246 commit 907f485

9 files changed

Lines changed: 183 additions & 14 deletions

File tree

‎apps/server/src/assets/SourceControlMediaProxy.test.ts‎

Lines changed: 84 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,8 @@ const signedUrl = "https://storage.example/image?X-Amz-Date=20260912T120000Z&X-A
4040

4141
function fixture(input: {
4242
token?: () => string;
43+
protocol?: string;
44+
apiBaseUrl?: string;
4345
fetch: (...args: Parameters<typeof globalThis.fetch>) => ReturnType<typeof globalThis.fetch>;
4446
commands?: Array<{ command: string; args: ReadonlyArray<string> }>;
4547
}) {
@@ -52,10 +54,11 @@ function fixture(input: {
5254
const token = input.token?.() ?? "dummy-token";
5355
return {
5456
exitCode: ChildProcessSpawner.ExitCode(0),
55-
stdout: command === "gh" ? token : "",
57+
stdout:
58+
command === "gh" ? token : args[0] === "config" ? (input.protocol ?? "https") : "",
5659
stderr:
5760
command === "glab" && token
58-
? `git.example\n ✓ REST API Endpoint: https://api.git.example:3443/api/v4/\n ✓ Token found in keyring: ${token}\n`
61+
? `git.example\n ✓ REST API Endpoint: ${input.apiBaseUrl ?? "https://api.git.example:3443/api/v4/"}\n ✓ Token found in keyring: ${token}\n`
5962
: "",
6063
stdoutTruncated: false,
6164
stderrTruncated: false,
@@ -221,6 +224,83 @@ describe("source-control image delivery", () => {
221224
),
222225
);
223226

227+
for (const protocol of ["http", "", "ftp"]) {
228+
it.effect(`rejects ${protocol || "missing"} API protocol before auth status`, () => {
229+
const commands: Array<{ command: string; args: ReadonlyArray<string> }> = [];
230+
let requested = false;
231+
return Effect.gen(function* () {
232+
const proxy = yield* SourceControlMediaProxy.SourceControlMediaProxy;
233+
expect(yield* proxy.resolve(gitlab)).toBeNull();
234+
expect(commands).toEqual([
235+
{ command: "glab", args: ["config", "get", "api_protocol", "--host", "git.example"] },
236+
]);
237+
expect(requested).toBe(false);
238+
}).pipe(
239+
Effect.provide(
240+
fixture({
241+
protocol,
242+
commands,
243+
fetch: async () => {
244+
requested = true;
245+
return new Response("unexpected");
246+
},
247+
}),
248+
),
249+
);
250+
});
251+
}
252+
253+
it.effect("rejects an HTTP endpoint returned despite HTTPS configuration", () => {
254+
let requested = false;
255+
return Effect.gen(function* () {
256+
const proxy = yield* SourceControlMediaProxy.SourceControlMediaProxy;
257+
expect(yield* proxy.resolve(gitlab)).toBeNull();
258+
expect(requested).toBe(false);
259+
}).pipe(
260+
Effect.provide(
261+
fixture({
262+
apiBaseUrl: "http://api.git.example/api/v4/",
263+
fetch: async () => {
264+
requested = true;
265+
return new Response("unexpected");
266+
},
267+
}),
268+
),
269+
);
270+
});
271+
272+
for (const length of [
273+
"0",
274+
"8",
275+
"9007199254740991",
276+
"9007199254740993",
277+
"9".repeat(400),
278+
"-1",
279+
"1.5",
280+
"nope",
281+
]) {
282+
it.effect(`validates upstream content length ${length.slice(0, 20)}`, () =>
283+
Effect.gen(function* () {
284+
const proxy = yield* SourceControlMediaProxy.SourceControlMediaProxy;
285+
const delivery = yield* proxy.resolve(gitlab);
286+
expect(delivery?.kind).toBe("stream");
287+
if (delivery?.kind !== "stream") return;
288+
expect(delivery.headers["content-length"]).toBe(
289+
["0", "8", "9007199254740991"].includes(length) ? length : undefined,
290+
);
291+
}).pipe(
292+
Effect.provide(
293+
fixture({
294+
fetch: async () =>
295+
new Response(null, {
296+
headers: { "content-type": "image/png", "content-length": length },
297+
}),
298+
}),
299+
),
300+
),
301+
);
302+
}
303+
224304
it.effect("does not attach compressed lengths to a decoded media stream", () =>
225305
Effect.gen(function* () {
226306
const proxy = yield* SourceControlMediaProxy.SourceControlMediaProxy;
@@ -319,6 +399,7 @@ describe("source-control image delivery", () => {
319399
{ url: "https://storage.example/image", token: null, redirect: "manual" },
320400
]);
321401
expect(commands).toEqual([
402+
{ command: "glab", args: ["config", "get", "api_protocol", "--host", "git.example"] },
322403
{
323404
command: "glab",
324405
args: ["auth", "status", "--hostname", "git.example", "--show-token"],
@@ -364,7 +445,7 @@ describe("source-control image delivery", () => {
364445
expect(headers).toEqual([null, "token logged-in", "token logged-in"]);
365446
yield* proxy.resolve(gitlab);
366447
yield* proxy.resolve(gitlab);
367-
expect(commands.filter((command) => command.command === "glab")).toHaveLength(1);
448+
expect(commands.filter((command) => command.command === "glab")).toHaveLength(2);
368449
}).pipe(
369450
Effect.provide(
370451
fixture({

‎apps/server/src/assets/SourceControlMediaProxy.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ function redirectLocation(value: string | undefined, base: string): URL | null {
6363
}
6464
}
6565

66+
/** Stream deliveries belong to the caller's scope, which must stay open until transfer ends. */
6667
export class SourceControlMediaProxy extends Context.Service<
6768
SourceControlMediaProxy,
6869
{
@@ -115,7 +116,7 @@ export const make = Effect.gen(function* () {
115116
};
116117
}
117118
const connection = yield* credentials.gitLabConnection(reference.origin);
118-
if (connection === null) return null;
119+
if (connection === null || connection.apiBaseUrl.protocol !== "https:") return null;
119120
// A subfolder belongs to the installation, not the repository's API identifier.
120121
const subfolder = connection.apiBaseUrl.pathname
121122
.replace(/\/api\/v4\/$/u, "")
@@ -186,7 +187,10 @@ export const make = Effect.gen(function* () {
186187
headers: {
187188
...(response.headers["accept-ranges"] === "bytes" ? { "accept-ranges": "bytes" } : {}),
188189
...(response.status === 206 && contentRange ? { "content-range": contentRange } : {}),
189-
...(!encoded && contentLength && /^\d+$/u.test(contentLength)
190+
...(!encoded &&
191+
contentLength &&
192+
/^\d+$/u.test(contentLength) &&
193+
Number.isSafeInteger(Number(contentLength))
190194
? { "content-length": contentLength }
191195
: {}),
192196
},

‎apps/server/src/sourceControl/SourceControlMediaCredentials.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ const GitLabConnection = Schema.Struct({
1616
apiBaseUrl: Schema.URLFromString.check(
1717
Schema.makeFilter(
1818
(url) =>
19-
(url.protocol === "https:" || url.protocol === "http:") &&
19+
url.protocol === "https:" &&
2020
!url.username &&
2121
!url.password &&
2222
!url.search &&
@@ -29,6 +29,7 @@ const GitLabConnection = Schema.Struct({
2929

3030
const decodeGitLabConnection = Schema.decodeUnknownOption(GitLabConnection);
3131

32+
/** Reads CLI-managed credentials; unavailable logins are never cached or exposed to clients. */
3233
export class SourceControlMediaCredentials extends Context.Service<
3334
SourceControlMediaCredentials,
3435
{
@@ -64,11 +65,20 @@ export const make = Effect.gen(function* () {
6465
const gitlabCache = yield* Cache.makeWith(
6566
Effect.fn("SourceControlMediaCredentials.readGitLab")(
6667
function* (origin: string) {
68+
const host = new URL(origin).host;
69+
// auth status validates the token over the network. Reject plaintext configuration
70+
// before invoking it; config get reads the same effective setting without a request.
71+
const protocol = yield* gitlab.execute({
72+
cwd: config.stateDir,
73+
args: ["config", "get", "api_protocol", "--host", host],
74+
timeoutMs: 10_000,
75+
});
76+
if (protocol.stdout.trim() !== "https") return null;
6777
// Ask for the login host, not its possibly separate API hostname/port.
6878
// auth status obtains the effective token from config, keyring or environment.
6979
const output = yield* gitlab.execute({
7080
cwd: config.stateDir,
71-
args: ["auth", "status", "--hostname", new URL(origin).host, "--show-token"],
81+
args: ["auth", "status", "--hostname", host, "--show-token"],
7282
timeoutMs: 10_000,
7383
maxOutputBytes: 16 * 1024,
7484
});

‎apps/web/src/components/ChatMarkdown.source-control-media.test.tsx‎

Lines changed: 37 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,11 @@ vi.mock("../assets/assetUrls", async () => {
1616
state.refresh = refresh;
1717
return state.failed ? { _tag: "Failure" } : { _tag: "Success", url: state.url };
1818
},
19-
useAssetUrlRefresh: () => async () => {},
19+
useAssetUrlRefresh: () => async () => {
20+
state.failed = false;
21+
state.url = "https://t3.test/api/assets/refreshed/image";
22+
state.refresh();
23+
},
2024
};
2125
});
2226
vi.mock("@effect/atom-react", () => ({ useAtomValue: () => null }));
@@ -166,7 +170,12 @@ describe("source-control image loading", () => {
166170
</PullRequestMarkdownContext>,
167171
);
168172
});
169-
expect(renderer!.root.findByType("video").props.src).toBe(state.url);
173+
const firstUrl = state.url;
174+
expect(renderer!.root.findByType("video").props.src).toBe(firstUrl);
175+
await act(async () => renderer!.root.findByType("video").props.onError());
176+
expect(renderer!.root.findByType("video").props.src).toBe(
177+
"http://gitlab.local/acme/project/uploads/e347d7ff85358d19b72222f1174b9a4b/clip.mp4",
178+
);
170179
await act(async () => renderer!.root.findByType("video").props.onError());
171180
expect(renderer!.root.findAllByType("video")).toHaveLength(0);
172181
const retry = renderer!.root
@@ -178,6 +187,32 @@ describe("source-control image loading", () => {
178187
);
179188
expect(retry).toBeDefined();
180189
await act(async () => retry!.props.onClick());
190+
expect(state.url).not.toBe(firstUrl);
191+
expect(renderer!.root.findByType("video").props.src).toBe(state.url);
192+
});
193+
194+
it("keeps a playing signed video through refresh and uses the new URL if playback fails", async () => {
195+
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
196+
const url =
197+
"https://git.example/acme/project/uploads/e347d7ff85358d19b72222f1174b9a4b/clip.mp4";
198+
await act(async () => {
199+
renderer = create(
200+
<ChatMarkdown cwd="/worktree" environmentId={environmentId} text={`![clip](${url})`} />,
201+
);
202+
});
203+
const firstUrl = state.url;
204+
await act(async () => renderer!.root.findByType("video").props.onPlay());
205+
state.url = "https://t3.test/api/assets/background-refresh/video";
206+
await act(async () => state.refresh());
207+
expect(renderer!.root.findByType("video").props.src).toBe(firstUrl);
208+
await act(async () => renderer!.root.findByType("video").props.onError());
209+
expect(renderer!.root.findByType("video").props.src).toBe(state.url);
210+
await act(async () => renderer!.root.findByType("video").props.onError());
211+
expect(renderer!.root.findByType("video").props.src).toBe(url);
212+
await act(async () => renderer!.root.findByType("video").props.onError());
213+
expect(renderer!.root.findAllByType("video")).toHaveLength(0);
214+
state.url = "https://t3.test/api/assets/recovered/video";
215+
await act(async () => state.refresh());
181216
expect(renderer!.root.findByType("video").props.src).toBe(state.url);
182217
});
183218

‎apps/web/src/components/ChatMarkdown.tsx‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1521,6 +1521,7 @@ function ChatMarkdownVideo(props: {
15211521
readonly alt: string;
15221522
readonly copyMarkdown: string | undefined;
15231523
readonly originalUrl?: string | undefined;
1524+
readonly fallbackSrc?: string | null | undefined;
15241525
readonly sourceFailed?: boolean | undefined;
15251526
readonly style?: CSSProperties | undefined;
15261527
readonly mediaIdentity?: string | undefined;
@@ -1534,6 +1535,7 @@ function ChatMarkdownVideo(props: {
15341535
sourceFailed={props.sourceFailed}
15351536
label={props.alt}
15361537
originalUrl={props.originalUrl}
1538+
fallbackSrc={props.fallbackSrc}
15371539
style={props.style}
15381540
copyMarkdown={props.copyMarkdown}
15391541
className={cn(
@@ -1643,6 +1645,7 @@ export const ChatMarkdownAssetImage = memo(function ChatMarkdownAssetImage(props
16431645
src={src}
16441646
sourceFailed={sourceFailed}
16451647
originalUrl={props.originalUrl}
1648+
fallbackSrc={authoredUrl}
16461649
alt={props.alt}
16471650
copyMarkdown={props.copyMarkdown}
16481651
style={props.style}

‎apps/web/src/components/media/MediaVideoPlayer.tsx‎

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ interface MediaVideoPlayerProps {
1212
readonly label: string;
1313
readonly sourceFailed?: boolean | undefined;
1414
readonly originalUrl?: string | undefined;
15+
/** An explicitly playable public source to try once if the signed source fails. */
16+
readonly fallbackSrc?: string | null | undefined;
1517
readonly revision?: string | null | undefined;
1618
readonly preload?: "visible" | "metadata" | undefined;
1719
readonly autoPlay?: boolean | undefined;
@@ -31,6 +33,7 @@ export function MediaVideoPlayer({
3133
label,
3234
sourceFailed = false,
3335
originalUrl,
36+
fallbackSrc,
3437
revision = null,
3538
preload = "visible",
3639
autoPlay = false,
@@ -47,11 +50,13 @@ export function MediaVideoPlayer({
4750
src: string;
4851
revision: string | null;
4952
} | null>(null);
53+
const [fallbackFor, setFallbackFor] = useState<string | null>(null);
5054
const [failedSrc, setFailedSrc] = useState<string | null>(null);
5155
const [retrying, setRetrying] = useState(false);
5256
const [loadAttempt, setLoadAttempt] = useState(0);
5357
const [preloadedSrc, setPreloadedSrc] = useState<string | null>(null);
54-
const src = playbackSource?.src ?? latestSrc;
58+
const usingFallback = fallbackSrc != null && fallbackFor !== null && fallbackFor === latestSrc;
59+
const src = playbackSource?.src ?? (usingFallback ? fallbackSrc : latestSrc);
5560
const sourceRevision = playbackSource === null ? revision : playbackSource.revision;
5661
const failed = src !== null ? failedSrc === src : sourceFailed;
5762

@@ -116,6 +121,7 @@ export function MediaVideoPlayer({
116121
try {
117122
await onRetry?.();
118123
setPlaybackSource(null);
124+
setFallbackFor(null);
119125
setFailedSrc(null);
120126
setLoadAttempt((current) => current + 1);
121127
} catch {
@@ -177,8 +183,12 @@ export function MediaVideoPlayer({
177183
onPause={refreshPausedRevision}
178184
onEnded={refreshPausedRevision}
179185
onError={() => {
180-
if (latestSrc !== null && src !== latestSrc) setPlaybackSource(null);
181-
else setFailedSrc(src);
186+
if (src === fallbackSrc) setFailedSrc(src);
187+
else if (latestSrc !== null && src !== latestSrc) setPlaybackSource(null);
188+
else if (fallbackSrc && fallbackSrc !== src) {
189+
setPlaybackSource(null);
190+
setFallbackFor(latestSrc);
191+
} else setFailedSrc(src);
182192
}}
183193
/>
184194
) : (
@@ -191,5 +201,14 @@ export function MediaVideoPlayer({
191201
)}
192202
</span>
193203
);
194-
return actionsSource ? <MediaActions source={actionsSource}>{player}</MediaActions> : player;
204+
let activeActionsSource = actionsSource;
205+
if (actionsSource && src === fallbackSrc) {
206+
const { asset: _asset, ...directSource } = actionsSource;
207+
activeActionsSource = { ...directSource, src };
208+
}
209+
return activeActionsSource ? (
210+
<MediaActions source={activeActionsSource}>{player}</MediaActions>
211+
) : (
212+
player
213+
);
195214
}

‎apps/web/src/components/pullRequest/PullRequestMarkdown.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,7 @@ function PullRequestAttachmentVideo({
134134
<MediaVideoPlayer
135135
src={assetUrl._tag === "Success" ? assetUrl.url : assetUrl._tag === "Failure" ? url : null}
136136
originalUrl={url}
137+
fallbackSrc={url}
137138
label="Pull request video"
138139
className="w-full"
139140
videoClassName="rounded-lg border border-border/60"

‎packages/client-runtime/src/mediaSource.test.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,19 @@ const attachmentId =
88
"11111111-1111-4111-8111-111111111111-22222222-2222-4222-8222-222222222222-mp4";
99

1010
describe("resolveMediaSource", () => {
11+
it.each(["shot one.png", "Grüße 世界.mp4", "literal%20.png"])(
12+
"decodes the GitLab display filename exactly once: %s",
13+
(name) => {
14+
const url = `https://git.example/acme/project/uploads/e347d7ff85358d19b72222f1174b9a4b/${encodeURIComponent(name)}`;
15+
expect(resolveMediaSource(url, { threadId })).toMatchObject({
16+
name,
17+
access: "environment",
18+
reference: { kind: "url", url },
19+
resource: { _tag: "source-control-media", reference: { _tag: "gitlab", fileName: name } },
20+
});
21+
},
22+
);
23+
1124
describe("direct URLs", () => {
1225
it("keeps the authored URL and decodes the display name once", () => {
1326
const href = "https://cdn.example.com/clip%20one%2520%2Emp4?signature=a%2fb#t=2";

‎packages/client-runtime/src/mediaSource.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,10 @@ export function resolveMediaSource(
7171
return {
7272
kind: mimeType.startsWith("video/") ? "video" : "image",
7373
mimeType,
74-
name: fileBasename(classified.uri),
74+
name:
75+
classified.reference._tag === "gitlab"
76+
? classified.reference.fileName
77+
: fileBasename(classified.uri),
7578
...(reference ? { reference } : {}),
7679
srcFragment: "",
7780
access: "environment",

0 commit comments

Comments
 (0)