Skip to content

Commit 92f7b13

Browse files
author
Vaclav Berny
committed
fix(pr): authenticate Azure DevOps attachment previews
1 parent c274a25 commit 92f7b13

21 files changed

Lines changed: 618 additions & 47 deletions

‎apps/mobile/src/features/pull-requests/PullRequestMedia.tsx‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { createContext, useContext, useMemo, useState } from "react";
22
import { pullRequestMediaSource, pullRequestImageSource } from "./pullRequestMediaSource";
33
import { useFilePreviewGallery } from "../../components/FilePreviewGallery";
44
import type { AssetResource, EnvironmentId } from "@t3tools/contracts";
5-
import { githubMediaFetchUrl } from "@t3tools/shared/githubMedia";
5+
import { pullRequestMediaResource } from "@t3tools/client-runtime/pull-request-markdown";
66
import { videoMimeType } from "@t3tools/shared/video";
77
import { Pressable, View } from "react-native";
88
import { Image } from "expo-image";
@@ -25,10 +25,9 @@ export const PullRequestMediaContext = createContext<{
2525

2626
export function usePullRequestMediaUrl(url: string) {
2727
const context = useContext(PullRequestMediaContext);
28-
const fetchUrl = githubMediaFetchUrl(url);
2928
const resource = useMemo<AssetResource | null>(
30-
() => (context && fetchUrl ? { _tag: "github-media", cwd: context.cwd, url: fetchUrl } : null),
31-
[context, fetchUrl],
29+
() => (context ? pullRequestMediaResource(url, context.cwd) : null),
30+
[context, url],
3231
);
3332
const asset = useAssetUrlState(context?.environmentId ?? null, resource);
3433
const refresh = useRefreshAssetUrl(context?.environmentId ?? null, resource);

‎apps/mobile/src/features/pull-requests/pullRequestMediaSource.test.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,27 @@ const location = { environmentId: EnvironmentId.make("test"), cwd: "/repo" };
88
const url = "https://github.com/user-attachments/assets/abc-123";
99

1010
describe("PR media previews", () => {
11+
it("renews Azure video and image capabilities in the destination environment", () => {
12+
const azure =
13+
"https://dev.azure.com/org/project/_apis/git/repositories/repo/pullRequests/42/attachments/demo.mp4";
14+
const source = {
15+
type: "media" as const,
16+
name: "Demo",
17+
mimeType: "video/mp4",
18+
...pullRequestMediaSource(azure, location),
19+
};
20+
expect(source).toMatchObject({
21+
environmentId: location.environmentId,
22+
resource: { _tag: "azure-devops-media", cwd: "/repo", url: azure },
23+
});
24+
expect(mediaVideoPreviewUri(source, null)).toBeNull();
25+
expect(mediaVideoPreviewUri(source, "https://signed/renewed")).toBe("https://signed/renewed");
26+
expect(mediaVideoThumbnailKey(source)).toContain("azure-devops-media");
27+
expect(pullRequestImageSource(azure.replace(".mp4", ".gif"), location)).toMatchObject({
28+
kind: "image",
29+
resource: { _tag: "azure-devops-media" },
30+
});
31+
});
1132
it("keeps a video resource pending until resolved and accepts refreshed capabilities", () => {
1233
const source = {
1334
type: "media" as const,

‎apps/mobile/src/features/pull-requests/pullRequestMediaSource.ts‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import type { EnvironmentId } from "@t3tools/contracts";
2-
import { githubMediaFetchUrl } from "@t3tools/shared/githubMedia";
2+
import { pullRequestMediaResource } from "@t3tools/client-runtime/pull-request-markdown";
33
import type { FilePreviewItem } from "../../components/FilePreviewModal.types";
44

55
export interface PullRequestMediaLocation {
@@ -9,11 +9,11 @@ export interface PullRequestMediaLocation {
99

1010
/** Keep the original resource identity so previewers can resolve and renew its capability. */
1111
export function pullRequestMediaSource(url: string, location: PullRequestMediaLocation | null) {
12-
const fetchUrl = githubMediaFetchUrl(url);
13-
return location && fetchUrl
12+
const resource = location ? pullRequestMediaResource(url, location.cwd) : null;
13+
return location && resource
1414
? {
1515
environmentId: location.environmentId,
16-
resource: { _tag: "github-media" as const, cwd: location.cwd, url: fetchUrl },
16+
resource,
1717
}
1818
: { uri: url };
1919
}

‎apps/mobile/src/lib/videoPreviewSource.ts‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,14 @@ export type MediaVideoPreviewSource = {
1717
readonly environmentId: EnvironmentId;
1818
readonly resource: Extract<
1919
AssetResource,
20-
{ readonly _tag: "attachment" | "media-file" | "draft-workspace-file" | "github-media" }
20+
{
21+
readonly _tag:
22+
| "attachment"
23+
| "media-file"
24+
| "draft-workspace-file"
25+
| "github-media"
26+
| "azure-devops-media";
27+
}
2128
>;
2229
}
2330
);
@@ -45,10 +52,10 @@ export function mediaVideoThumbnailKey(source: MediaVideoPreviewSource): string
4552
source.resource.path,
4653
source.srcFragment ?? "",
4754
]
48-
: source.resource._tag === "github-media"
55+
: source.resource._tag === "github-media" || source.resource._tag === "azure-devops-media"
4956
? [
5057
"media-video",
51-
"github-media",
58+
source.resource._tag,
5259
source.environmentId,
5360
source.resource.cwd,
5461
source.resource.url,

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

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,34 @@ const layerTest = Layer.mergeAll(
121121
).pipe(Layer.provideMerge(NodeServices.layer));
122122

123123
describe("AssetAccess", () => {
124+
it.effect("signs Azure attachments and refuses arbitrary URLs or tampered capabilities", () =>
125+
Effect.gen(function* () {
126+
const url =
127+
"https://dev.azure.com/org/project/_apis/git/repositories/repo/pullRequests/42/attachments/demo.gif";
128+
const signed = yield* issueAssetUrl({
129+
resource: { _tag: "azure-devops-media", cwd: "/repo", url },
130+
});
131+
const suffix = signed.relativeUrl.slice(`${ASSET_ROUTE_PREFIX}/`.length);
132+
const slash = suffix.indexOf("/");
133+
const token = suffix.slice(0, slash);
134+
const name = suffix.slice(slash + 1);
135+
expect(yield* resolveAsset(token, name)).toEqual({
136+
kind: "azure-devops-media",
137+
cwd: "/repo",
138+
url,
139+
expiresAt: signed.expiresAt,
140+
});
141+
expect(yield* resolveAsset(`${token}tampered`, name)).toBeNull();
142+
const error = yield* issueAssetUrl({
143+
resource: {
144+
_tag: "azure-devops-media",
145+
cwd: "/repo",
146+
url: "https://example.test/private.gif",
147+
},
148+
}).pipe(Effect.flip);
149+
expect(error._tag).toBe("AssetAzureDevOpsMediaUrlValidationError");
150+
}).pipe(Effect.provide(layerTest)),
151+
);
124152
describe("readMcpAppHtml", () => {
125153
it.effect("accepts snapshots at the stored HTML byte limit", () =>
126154
Effect.gen(function* () {

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

Lines changed: 32 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1+
import { azureDevOpsMediaLocation } from "@t3tools/shared/azureDevOpsMedia";
12
import type { AssetResource } from "@t3tools/contracts";
23
import {
34
AssetAttachmentNotFoundError,
45
AssetGitHubMediaUrlValidationError,
6+
AssetAzureDevOpsMediaUrlValidationError,
57
AssetPreviewTypeValidationError,
68
AssetProjectFaviconInspectionError,
79
AssetProjectFaviconNotFoundError,
@@ -159,7 +161,16 @@ const AssetClaimsSchema = Schema.Union([
159161
Schema.Struct({
160162
version: Schema.Literal(1),
161163
kind: Schema.Literal("github-media"),
162-
/** Already narrowed to a GitHub media host at mint time; the signature is what keeps it there. */
164+
/** Already narrowed to a provider media endpoint at mint time; the signature is what keeps it there. */
165+
url: Schema.String,
166+
cwd: Schema.String,
167+
expiresAt: Schema.Number,
168+
}),
169+
170+
Schema.Struct({
171+
version: Schema.Literal(1),
172+
kind: Schema.Literal("azure-devops-media"),
173+
/** Already narrowed to a provider media endpoint at mint time; the signature is what keeps it there. */
163174
url: Schema.String,
164175
cwd: Schema.String,
165176
expiresAt: Schema.Number,
@@ -187,7 +198,7 @@ export type ResolvedAsset =
187198
readonly mimeType: string;
188199
}
189200
| {
190-
readonly kind: "github-media";
201+
readonly kind: "github-media" | "azure-devops-media";
191202
readonly url: string;
192203
readonly cwd: string;
193204
readonly expiresAt: number;
@@ -765,14 +776,20 @@ export const issueAssetUrl = Effect.fn("AssetAccess.issueAssetUrl")(function* (i
765776
fileName = "native-app-icon.png";
766777
break;
767778
}
768-
case "github-media": {
769-
const fetchUrl = githubMediaFetchUrl(input.resource.url);
779+
case "github-media":
780+
case "azure-devops-media": {
781+
const azure = input.resource._tag === "azure-devops-media";
782+
const fetchUrl = azure
783+
? (azureDevOpsMediaLocation(input.resource.url)?.fetchUrl ?? null)
784+
: githubMediaFetchUrl(input.resource.url);
770785
if (fetchUrl === null) {
771-
return yield* new AssetGitHubMediaUrlValidationError({});
786+
return yield* azure
787+
? new AssetAzureDevOpsMediaUrlValidationError({})
788+
: new AssetGitHubMediaUrlValidationError({});
772789
}
773790
claims = {
774791
version: 1,
775-
kind: "github-media",
792+
kind: input.resource._tag,
776793
url: fetchUrl,
777794
cwd: input.resource.cwd,
778795
expiresAt,
@@ -889,7 +906,15 @@ export const resolveAsset = Effect.fn("AssetAccess.resolveAsset")(function* (
889906

890907
if (claims.kind === "github-media") {
891908
return {
892-
kind: "github-media",
909+
kind: claims.kind,
910+
url: claims.url,
911+
cwd: claims.cwd,
912+
expiresAt: claims.expiresAt,
913+
} satisfies ResolvedAsset;
914+
}
915+
if (claims.kind === "azure-devops-media") {
916+
return {
917+
kind: claims.kind,
893918
url: claims.url,
894919
cwd: claims.cwd,
895920
expiresAt: claims.expiresAt,
Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
2+
import * as NodeServices from "@effect/platform-node/NodeServices";
3+
import * as NodeHttpPlatform from "@effect/platform-node/NodeHttpPlatform";
4+
import { expect, it } from "@effect/vitest";
5+
import * as AzureDevOpsCli from "@t3tools/source-control-azure-devops/server/AzureDevOpsCli";
6+
import * as Effect from "effect/Effect";
7+
import * as FileSystem from "effect/FileSystem";
8+
import * as Layer from "effect/Layer";
9+
import { HttpServerResponse } from "effect/http";
10+
import * as AzureDevOpsMedia from "./AzureDevOpsMedia.ts";
11+
import { assetFileResponse } from "../http.ts";
12+
13+
const base =
14+
"https://dev.azure.com/org/project/_apis/git/repositories/repo/pullRequests/42/attachments/demo";
15+
16+
it.effect(
17+
"downloads with Azure CLI auth, reuses bytes for video ranges, and cleans up files on shutdown",
18+
() =>
19+
Effect.gen(function* () {
20+
const fs = yield* FileSystem.FileSystem;
21+
let downloaded = "";
22+
const calls: ReadonlyArray<string>[] = [];
23+
const cli = Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({
24+
execute: ({ cwd, args }) =>
25+
Effect.gen(function* () {
26+
expect(cwd).toBe("/repo");
27+
calls.push(args);
28+
yield* fs
29+
.writeFileString(args[args.indexOf("--out-file") + 1]!, "0123456789")
30+
.pipe(Effect.orDie);
31+
return {
32+
exitCode: ChildProcessSpawner.ExitCode(0),
33+
stdout: "",
34+
stderr: "",
35+
stdoutTruncated: false,
36+
stderrTruncated: false,
37+
};
38+
}),
39+
});
40+
yield* Effect.gen(function* () {
41+
const media = yield* AzureDevOpsMedia.AzureDevOpsMedia;
42+
yield* Effect.scoped(
43+
Effect.gen(function* () {
44+
const file = yield* media.get({ cwd: "/repo", url: `${base}.mp4` });
45+
downloaded = file.path;
46+
expect(calls[0]).toEqual([
47+
"devops",
48+
"invoke",
49+
"--organization",
50+
"https://dev.azure.com/org",
51+
"--area",
52+
"git",
53+
"--resource",
54+
"pullRequestAttachments",
55+
"--api-version",
56+
"7.1",
57+
"--route-parameters",
58+
"project=project",
59+
"repositoryId=repo",
60+
"pullRequestId=42",
61+
"fileName=demo.mp4",
62+
"--accept-media-type",
63+
"application/octet-stream",
64+
"--out-file",
65+
file.path,
66+
"--only-show-errors",
67+
"--output",
68+
"none",
69+
]);
70+
const full = HttpServerResponse.toWeb(yield* assetFileResponse(file));
71+
expect(full.headers.get("content-type")).toBe("video/mp4");
72+
expect(yield* Effect.promise(() => full.text())).toBe("0123456789");
73+
const again = yield* media.get({ cwd: "/repo", url: `${base}.mp4` });
74+
const ranged = HttpServerResponse.toWeb(yield* assetFileResponse(again, "bytes=2-5"));
75+
expect(ranged.status).toBe(206);
76+
expect(ranged.headers.get("content-range")).toBe("bytes 2-5/10");
77+
expect(yield* Effect.promise(() => ranged.text())).toBe("2345");
78+
expect(calls).toHaveLength(1);
79+
const image = HttpServerResponse.toWeb(
80+
yield* assetFileResponse(yield* media.get({ cwd: "/repo", url: `${base}.gif` })),
81+
);
82+
expect(image.headers.get("content-type")).toBe("image/gif");
83+
expect(yield* Effect.promise(() => image.text())).toBe("0123456789");
84+
}),
85+
);
86+
expect(yield* fs.exists(downloaded)).toBe(true);
87+
}).pipe(Effect.provide(AzureDevOpsMedia.layer.pipe(Layer.provide(cli))));
88+
expect(yield* fs.exists(downloaded)).toBe(false);
89+
}).pipe(Effect.provide(Layer.merge(NodeServices.layer, NodeHttpPlatform.layer))),
90+
);
91+
92+
it.effect("rejects unsupported endpoints before invoking Azure CLI", () => {
93+
let calls = 0;
94+
return Effect.gen(function* () {
95+
const media = yield* AzureDevOpsMedia.AzureDevOpsMedia;
96+
for (const url of ["https://example.test/a.gif", `${base}.html`]) {
97+
const error = yield* media.get({ cwd: "/repo", url }).pipe(Effect.flip);
98+
expect(error.message).toBe("Failed to load Azure DevOps attachment.");
99+
}
100+
expect(calls).toBe(0);
101+
}).pipe(
102+
Effect.provide(
103+
AzureDevOpsMedia.layer
104+
.pipe(
105+
Layer.provide(
106+
Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({
107+
execute: () => {
108+
calls++;
109+
return Effect.die("Unexpected download");
110+
},
111+
}),
112+
),
113+
)
114+
.pipe(Layer.provideMerge(NodeServices.layer)),
115+
),
116+
);
117+
});
118+
119+
it.effect("retries after a failed authenticated download", () => {
120+
let calls = 0;
121+
return Effect.gen(function* () {
122+
const media = yield* AzureDevOpsMedia.AzureDevOpsMedia;
123+
const fs = yield* FileSystem.FileSystem;
124+
const input = { cwd: "/repo", url: `${base}.gif` };
125+
expect((yield* media.get(input).pipe(Effect.flip)).message).toBe(
126+
"Failed to load Azure DevOps attachment.",
127+
);
128+
expect(yield* fs.readFileString((yield* media.get(input)).path)).toBe("GIF89a");
129+
expect(calls).toBe(2);
130+
}).pipe(
131+
Effect.provide(
132+
AzureDevOpsMedia.layer
133+
.pipe(
134+
Layer.provide(
135+
Layer.mock(AzureDevOpsCli.AzureDevOpsCli)({
136+
execute: ({ args }) =>
137+
Effect.gen(function* () {
138+
if (++calls === 1)
139+
return yield* new AzureDevOpsCli.AzureDevOpsCliAuthenticationError({
140+
operation: "execute",
141+
command: "az",
142+
cwd: "/repo",
143+
argumentCount: args.length,
144+
cause: "signed out",
145+
});
146+
const fs = yield* FileSystem.FileSystem;
147+
yield* fs
148+
.writeFileString(args[args.indexOf("--out-file") + 1]!, "GIF89a")
149+
.pipe(Effect.orDie);
150+
return {
151+
exitCode: ChildProcessSpawner.ExitCode(0),
152+
stdout: "",
153+
stderr: "",
154+
stdoutTruncated: false,
155+
stderrTruncated: false,
156+
};
157+
}).pipe(Effect.provide(NodeServices.layer)),
158+
}),
159+
),
160+
)
161+
.pipe(Layer.provideMerge(NodeServices.layer)),
162+
),
163+
);
164+
});

0 commit comments

Comments
 (0)