deepdebug-local-agent 1.4.0 → 1.5.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/docs/la-protocol-v2.md +38 -4
- package/package.json +1 -1
- package/src/la-protocol-v2/content-handlers/audit.js +36 -0
- package/src/la-protocol-v2/content-handlers/config.js +48 -0
- package/src/la-protocol-v2/content-handlers/egress.js +65 -0
- package/src/la-protocol-v2/content-handlers/git-diff.js +92 -0
- package/src/la-protocol-v2/content-handlers/handler.js +170 -0
- package/src/la-protocol-v2/content-handlers/index.js +6 -0
- package/src/la-protocol-v2/content-handlers/install.js +50 -0
- package/src/la-protocol-v2/content-handlers/path-guard.js +142 -0
- package/src/la-protocol-v2/content-handlers/ref-registry.js +87 -0
- package/src/la-protocol-v2/content.js +7 -1
- package/src/la-protocol-v2/runtime.js +13 -4
- package/src/server.js +4 -1
- package/test/la-protocol-v2/content-handlers.test.js +633 -0
- package/test/la-protocol-v2/content-path-guard.test.js +214 -0
- package/test/la-protocol-v2/content-wiring.test.js +225 -0
- package/test/la-protocol-v2/helpers/content-rig.js +94 -0
- package/test/la-protocol-v2/helpers/spawn-agent.js +2 -1
- package/tools/interop/LaV2NodeContentInteropTest.java +248 -0
- package/tools/interop/README.md +17 -0
- package/tools/interop/la-interop-content-client.mjs +91 -0
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
package io.visionhammer.gateway.cloud.infrastructure.byoc;
|
|
2
|
+
|
|
3
|
+
import com.fasterxml.jackson.databind.JsonNode;
|
|
4
|
+
import io.visionhammer.gateway.cloud.application.byoc.v2.LaProtocolV2Properties;
|
|
5
|
+
import io.visionhammer.gateway.cloud.application.byoc.v2.LaV2Chunk;
|
|
6
|
+
import io.visionhammer.gateway.cloud.application.byoc.v2.LaV2InboundListener;
|
|
7
|
+
import io.visionhammer.gateway.cloud.application.byoc.v2.LaV2Metrics;
|
|
8
|
+
import io.visionhammer.gateway.cloud.application.byoc.v2.LaV2Session;
|
|
9
|
+
import io.visionhammer.gateway.cloud.application.byoc.v2.LaV2SessionStore;
|
|
10
|
+
import io.visionhammer.gateway.cloud.application.byoc.v2.LaV2TestKit;
|
|
11
|
+
import io.visionhammer.gateway.governance.application.DataPlanePolicy;
|
|
12
|
+
import io.visionhammer.gateway.identity.application.AgentAuthorizationEntity;
|
|
13
|
+
import io.visionhammer.gateway.identity.application.AgentAuthorizationStore;
|
|
14
|
+
import io.visionhammer.gateway.shared.localagent.AgentRequestSigner;
|
|
15
|
+
import io.visionhammer.gateway.workspace.application.WorkspaceRepository;
|
|
16
|
+
import org.junit.jupiter.api.Test;
|
|
17
|
+
import org.springframework.http.server.reactive.HttpHandler;
|
|
18
|
+
import org.springframework.http.server.reactive.ReactorHttpHandlerAdapter;
|
|
19
|
+
import org.springframework.web.reactive.socket.server.WebSocketService;
|
|
20
|
+
import org.springframework.web.reactive.socket.server.support.HandshakeWebSocketService;
|
|
21
|
+
import org.springframework.web.reactive.socket.server.upgrade.ReactorNettyRequestUpgradeStrategy;
|
|
22
|
+
import org.springframework.web.server.adapter.WebHttpHandlerBuilder;
|
|
23
|
+
import reactor.core.publisher.Mono;
|
|
24
|
+
import reactor.core.scheduler.Schedulers;
|
|
25
|
+
import reactor.netty.DisposableServer;
|
|
26
|
+
import reactor.netty.http.server.HttpServer;
|
|
27
|
+
|
|
28
|
+
import java.io.BufferedReader;
|
|
29
|
+
import java.io.InputStreamReader;
|
|
30
|
+
import java.nio.charset.StandardCharsets;
|
|
31
|
+
import java.security.MessageDigest;
|
|
32
|
+
import java.time.Clock;
|
|
33
|
+
import java.time.Duration;
|
|
34
|
+
import java.util.ArrayList;
|
|
35
|
+
import java.util.Collections;
|
|
36
|
+
import java.util.HexFormat;
|
|
37
|
+
import java.util.List;
|
|
38
|
+
import java.util.Map;
|
|
39
|
+
import java.util.UUID;
|
|
40
|
+
import java.util.concurrent.BlockingQueue;
|
|
41
|
+
import java.util.concurrent.LinkedBlockingQueue;
|
|
42
|
+
import java.util.concurrent.TimeUnit;
|
|
43
|
+
|
|
44
|
+
import static io.visionhammer.gateway.cloud.application.byoc.v2.LaV2TestKit.OM;
|
|
45
|
+
import static org.assertj.core.api.Assertions.assertThat;
|
|
46
|
+
import static org.junit.jupiter.api.Assumptions.assumeTrue;
|
|
47
|
+
import static org.mockito.ArgumentMatchers.any;
|
|
48
|
+
import static org.mockito.ArgumentMatchers.anyString;
|
|
49
|
+
import static org.mockito.Mockito.mock;
|
|
50
|
+
import static org.mockito.Mockito.when;
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* F3-07 interoperability: the REAL Node Local Agent content handlers (opaque ids, path guard, DLP enforce, git diff,
|
|
54
|
+
* chunking) against the REAL gateway {@link LaV2Session} behind a real Reactor Netty WebSocket on loopback, real
|
|
55
|
+
* system clock, real Ed25519 signer. Run from the gateway checkout (JDK 21):
|
|
56
|
+
*
|
|
57
|
+
* LA_REPO=/path/to/deepdebug-local-agent mvn -o test -Dtest=LaV2NodeContentInteropTest
|
|
58
|
+
*
|
|
59
|
+
* Skipped when LA_REPO is not set. Not proven here: Cloud Run / LB / TLS, Memorystore, two gateway instances, the HTTP
|
|
60
|
+
* relay endpoint (F3-06) in front of this session.
|
|
61
|
+
*/
|
|
62
|
+
class LaV2NodeContentInteropTest {
|
|
63
|
+
|
|
64
|
+
private static final String TENANT = LaV2TestKit.TENANT;
|
|
65
|
+
private static final String AGENT = LaV2TestKit.AGENT;
|
|
66
|
+
|
|
67
|
+
private static Map<String, Object> request(String kind, String ref) {
|
|
68
|
+
return Map.of("kind", kind, "ref", ref, "actor", Map.of("userId", "usr-42", "role", "member"));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
@Test
|
|
72
|
+
void realNodeContentHandlersAgainstTheRealLaV2Session() throws Exception {
|
|
73
|
+
String laRepo = System.getenv("LA_REPO");
|
|
74
|
+
assumeTrue(laRepo != null && !laRepo.isBlank(), "LA_REPO not set");
|
|
75
|
+
|
|
76
|
+
Clock clock = Clock.systemUTC();
|
|
77
|
+
LaProtocolV2Properties props = new LaProtocolV2Properties();
|
|
78
|
+
props.setEnabled(true);
|
|
79
|
+
List<String> rejected = Collections.synchronizedList(new ArrayList<>());
|
|
80
|
+
LaV2Metrics metrics = new LaV2Metrics() {
|
|
81
|
+
@Override public void rejected(String code) { rejected.add(code); }
|
|
82
|
+
};
|
|
83
|
+
LaV2InboundListener listener = (t, a, type, rid, payload) -> { };
|
|
84
|
+
AgentRequestSigner signer = new AgentRequestSigner(LaV2TestKit.PEM, "k1", clock);
|
|
85
|
+
LaV2Session.Env env = new LaV2Session.Env(LaV2TestKit.CONTRACT, props, signer, OM, clock, metrics, Schedulers.parallel(), List.of(listener));
|
|
86
|
+
|
|
87
|
+
AgentAuthorizationStore store = mock(AgentAuthorizationStore.class);
|
|
88
|
+
WorkspaceRepository workspaces = mock(WorkspaceRepository.class);
|
|
89
|
+
DataPlanePolicy policy = mock(DataPlanePolicy.class);
|
|
90
|
+
when(workspaces.findDefaultByTenantId(anyString())).thenReturn(Mono.empty());
|
|
91
|
+
when(store.save(any())).thenAnswer(i -> Mono.just(i.getArgument(0)));
|
|
92
|
+
when(store.touchLastSeen(any())).thenReturn(Mono.just(1));
|
|
93
|
+
when(policy.requiresEnforcedSigning(anyString())).thenReturn(Mono.just(true));
|
|
94
|
+
AgentAuthorizationEntity auth = new AgentAuthorizationEntity();
|
|
95
|
+
auth.setId(UUID.fromString(AGENT));
|
|
96
|
+
auth.setTenantId(UUID.fromString(TENANT));
|
|
97
|
+
auth.setAuthorizationToken("tok");
|
|
98
|
+
when(store.findByAuthorizationToken("tok")).thenReturn(Mono.just(auth));
|
|
99
|
+
AgentWebSocketHandler handler = new AgentWebSocketHandler(OM, workspaces, store, signer, null, null, null,
|
|
100
|
+
new LaV2SessionStore(env), props, policy);
|
|
101
|
+
|
|
102
|
+
WebSocketService wsService = new HandshakeWebSocketService(new ReactorNettyRequestUpgradeStrategy());
|
|
103
|
+
HttpHandler http = WebHttpHandlerBuilder.webHandler(exchange -> wsService.handleRequest(exchange, handler)).build();
|
|
104
|
+
DisposableServer server = HttpServer.create().host("127.0.0.1").port(0).handle(new ReactorHttpHandlerAdapter(http)).bindNow();
|
|
105
|
+
|
|
106
|
+
ProcessBuilder pb = new ProcessBuilder("node", laRepo + "/tools/interop/la-interop-content-client.mjs");
|
|
107
|
+
pb.environment().putAll(Map.of(
|
|
108
|
+
"GW_URL", "ws://127.0.0.1:" + server.port() + "/api/v1/agent/ws", "TOKEN", "tok", "TENANT", TENANT, "AGENT", AGENT,
|
|
109
|
+
"KEY_ID", "k1", "PUBLIC_KEY", LaV2TestKit.PUB, "MODE", "enforce", "LOCAL_AGENT_DLP_MODE", "enforce"));
|
|
110
|
+
pb.redirectErrorStream(true);
|
|
111
|
+
Process proc = pb.start();
|
|
112
|
+
BlockingQueue<JsonNode> events = new LinkedBlockingQueue<>();
|
|
113
|
+
List<String> transcript = Collections.synchronizedList(new ArrayList<>());
|
|
114
|
+
Thread reader = new Thread(() -> {
|
|
115
|
+
try (BufferedReader r = new BufferedReader(new InputStreamReader(proc.getInputStream(), StandardCharsets.UTF_8))) {
|
|
116
|
+
String line;
|
|
117
|
+
while ((line = r.readLine()) != null) {
|
|
118
|
+
transcript.add(line);
|
|
119
|
+
try {
|
|
120
|
+
events.add(OM.readTree(line));
|
|
121
|
+
} catch (Exception ignored) {
|
|
122
|
+
// node warnings
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
} catch (Exception ignored) {
|
|
126
|
+
// process ended
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
reader.setDaemon(true);
|
|
130
|
+
reader.start();
|
|
131
|
+
java.io.Writer stdin = new java.io.OutputStreamWriter(proc.getOutputStream(), StandardCharsets.UTF_8);
|
|
132
|
+
|
|
133
|
+
try {
|
|
134
|
+
JsonNode refsEvt = await(events, "refs", 20);
|
|
135
|
+
await(events, "ready", 15);
|
|
136
|
+
assertThat(handler.isAgentConnected(TENANT)).isTrue();
|
|
137
|
+
JsonNode refs = refsEvt.path("refs");
|
|
138
|
+
String ghp = refsEvt.path("ghp").asText();
|
|
139
|
+
assertThat(refs.path("envFile").isNull()).as("no id is minted for .env").isTrue();
|
|
140
|
+
|
|
141
|
+
// 1. a file with a token: served, the token masked (DLP enforce), the rest intact
|
|
142
|
+
List<LaV2Chunk> app = content("file", refs.path("app").asText(), handler);
|
|
143
|
+
assertThat(app.get(0).status()).isEqualTo("ok");
|
|
144
|
+
String appText = new String(concat(app), StandardCharsets.UTF_8);
|
|
145
|
+
assertThat(appText).contains("first line").contains("[REDACTED:github_token]").contains("last line").doesNotContain(ghp);
|
|
146
|
+
|
|
147
|
+
// 2. 1 MiB = 32 chunks, byte for byte (no secrets in it)
|
|
148
|
+
List<LaV2Chunk> big = content("file", refs.path("big").asText(), handler);
|
|
149
|
+
assertThat(big).hasSize(32);
|
|
150
|
+
assertThat(big.get(31).last()).isTrue();
|
|
151
|
+
assertThat(HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(concat(big)))).isEqualTo(refsEvt.path("bigSha256").asText());
|
|
152
|
+
assertThat(concat(big)).hasSize(refsEvt.path("bigBytes").asInt());
|
|
153
|
+
|
|
154
|
+
// 3. a token straddling the 32 KiB chunk boundary of the ORIGINAL file never appears, whole or in part
|
|
155
|
+
List<LaV2Chunk> mid = content("file", refs.path("mid").asText(), handler);
|
|
156
|
+
assertThat(mid.get(0).status()).isEqualTo("ok");
|
|
157
|
+
assertThat(mid.size()).isGreaterThanOrEqualTo(2);
|
|
158
|
+
for (LaV2Chunk c : mid) {
|
|
159
|
+
assertThat(new String(c.data(), StandardCharsets.UTF_8)).doesNotContain(ghp.substring(0, 12));
|
|
160
|
+
}
|
|
161
|
+
assertThat(new String(concat(mid), StandardCharsets.UTF_8)).contains("[REDACTED:github_token]");
|
|
162
|
+
|
|
163
|
+
// 4. an id handed out for an innocent file, later swapped for a link to a file outside the workspace: forbidden, no data
|
|
164
|
+
List<LaV2Chunk> swapped = content("file", refs.path("swapped").asText(), handler);
|
|
165
|
+
assertThat(swapped).hasSize(1);
|
|
166
|
+
assertThat(swapped.get(0).status()).isEqualTo("forbidden");
|
|
167
|
+
assertThat(swapped.get(0).data()).isEmpty();
|
|
168
|
+
|
|
169
|
+
// 5. paths are never ids: traversal, absolute, plain relative -> not_found; nothing else comes back
|
|
170
|
+
for (String ref : List.of("../../etc/passwd", "/etc/passwd", "src/app.txt", "..%2f..%2fetc%2fpasswd", "cr1_AAAAAAAAAAAAAAAAAAAAAA")) {
|
|
171
|
+
List<LaV2Chunk> r = content("file", ref, handler);
|
|
172
|
+
assertThat(r).hasSize(1);
|
|
173
|
+
assertThat(r.get(0).status()).as(ref).isEqualTo("not_found");
|
|
174
|
+
assertThat(r.get(0).data()).isEmpty();
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// 6. a binary file cannot be inspected by the DLP: withheld in enforce
|
|
178
|
+
assertThat(content("file", refs.path("bin").asText(), handler).get(0).status()).isEqualTo("forbidden");
|
|
179
|
+
|
|
180
|
+
// 7. kinds the agent does not serve yet: error + protocol_unsupported (a code of the contract)
|
|
181
|
+
List<LaV2Chunk> report = content("report", refs.path("app").asText(), handler);
|
|
182
|
+
assertThat(report.get(0).status()).isEqualTo("error");
|
|
183
|
+
assertThat(report.get(0).errorCode()).isEqualTo("protocol_unsupported");
|
|
184
|
+
|
|
185
|
+
// 8. diff of the work tree (symbolic ref, no client data in it) and of one minted file: masked
|
|
186
|
+
List<LaV2Chunk> diff = content("diff", "worktree", handler);
|
|
187
|
+
assertThat(diff.get(0).status()).isEqualTo("ok");
|
|
188
|
+
assertThat(diff.get(0).contentType()).isEqualTo("text/x-diff");
|
|
189
|
+
String diffText = new String(concat(diff), StandardCharsets.UTF_8);
|
|
190
|
+
assertThat(diffText).contains("tracked.js").contains("[REDACTED:github_token]").doesNotContain(ghp).doesNotContain("SECRET-ENV-VALUE").doesNotContain(".env");
|
|
191
|
+
assertThat(new String(concat(content("diff", refs.path("diffFile").asText(), handler)), StandardCharsets.UTF_8)).contains("tracked.js");
|
|
192
|
+
|
|
193
|
+
// 9. the consumer cancels after the first chunk (the relay's client went away): the agent is not left blocked
|
|
194
|
+
List<LaV2Chunk> first = handler.requestContent(TENANT, null, request("file", refs.path("big").asText()), "ws-1")
|
|
195
|
+
.take(1).collectList().block(Duration.ofSeconds(20));
|
|
196
|
+
assertThat(first).hasSize(1);
|
|
197
|
+
List<LaV2Chunk> afterCancel = content("file", refs.path("app").asText(), handler);
|
|
198
|
+
assertThat(afterCancel.get(0).status()).isEqualTo("ok");
|
|
199
|
+
|
|
200
|
+
// nothing the Node agent put on the wire was refused by the real gateway session
|
|
201
|
+
assertThat(rejected).as("frames the real LaV2Session rejected: %s", rejected).isEmpty();
|
|
202
|
+
// nothing in what the agent printed (events, warnings) carries content or a path
|
|
203
|
+
String printed = String.join("\n", transcript);
|
|
204
|
+
assertThat(printed).doesNotContain("OUTSIDE-SECRET").doesNotContain("SECRET-ENV-VALUE").doesNotContain("f307-interop-");
|
|
205
|
+
System.out.println("CONTENT INTEROP OK: rejected=" + rejected);
|
|
206
|
+
} finally {
|
|
207
|
+
try {
|
|
208
|
+
send(stdin, "quit");
|
|
209
|
+
} catch (Exception ignored) {
|
|
210
|
+
// gone
|
|
211
|
+
}
|
|
212
|
+
proc.waitFor(5, TimeUnit.SECONDS);
|
|
213
|
+
proc.destroyForcibly();
|
|
214
|
+
server.disposeNow();
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
private static List<LaV2Chunk> content(String kind, String ref, AgentWebSocketHandler handler) {
|
|
219
|
+
return handler.requestContent(TENANT, null, request(kind, ref), "ws-1").collectList().block(Duration.ofSeconds(30));
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
private static void send(java.io.Writer w, String line) throws Exception {
|
|
223
|
+
w.write(line + "\n");
|
|
224
|
+
w.flush();
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
private static JsonNode await(BlockingQueue<JsonNode> q, String evt, int seconds) throws Exception {
|
|
228
|
+
long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(seconds);
|
|
229
|
+
List<String> seen = new ArrayList<>();
|
|
230
|
+
while (System.nanoTime() < deadline) {
|
|
231
|
+
JsonNode n = q.poll(100, TimeUnit.MILLISECONDS);
|
|
232
|
+
if (n == null) {
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
if (evt.equals(n.path("evt").asText())) {
|
|
236
|
+
return n;
|
|
237
|
+
}
|
|
238
|
+
seen.add(n.path("evt").asText() + (n.has("code") ? ":" + n.path("code").asText() : "") + (n.has("m") ? ":" + n.path("m").asText() : ""));
|
|
239
|
+
}
|
|
240
|
+
throw new AssertionError("no '" + evt + "' event from the Node LA within " + seconds + " s; saw " + seen);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
private static byte[] concat(List<LaV2Chunk> chunks) {
|
|
244
|
+
java.io.ByteArrayOutputStream o = new java.io.ByteArrayOutputStream();
|
|
245
|
+
chunks.forEach(c -> o.writeBytes(c.data()));
|
|
246
|
+
return o.toByteArray();
|
|
247
|
+
}
|
|
248
|
+
}
|
package/tools/interop/README.md
CHANGED
|
@@ -19,3 +19,20 @@ a type with no handler -> rejected ack `protocol_unsupported`; 20 `job.event` in
|
|
|
19
19
|
with the same session id and consecutive seq; content after the resume; zero frames refused by the gateway.
|
|
20
20
|
It is skipped when `LA_REPO` is not set. It does not prove Cloud Run / the load balancer / TLS / Memorystore /
|
|
21
21
|
two gateway instances.
|
|
22
|
+
|
|
23
|
+
## F3-07: content handlers against the real `LaV2Session`
|
|
24
|
+
|
|
25
|
+
`la-interop-content-client.mjs` is a Local Agent with the REAL content handlers (opaque ids, path guard, DLP `enforce`,
|
|
26
|
+
git diff, chunking) on a temp workspace; `LaV2NodeContentInteropTest.java` drives it through `AgentWebSocketHandler.requestContent`.
|
|
27
|
+
|
|
28
|
+
```bash
|
|
29
|
+
cp tools/interop/LaV2NodeContentInteropTest.java <gateway>/src/test/java/io/visionhammer/gateway/cloud/infrastructure/byoc/
|
|
30
|
+
LA_REPO=/path/to/deepdebug-local-agent mvn -o test -Dtest=LaV2NodeContentInteropTest # JDK 21
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
It checks: a token masked in a served file; 1 MiB = 32 chunks byte for byte (sha256); a token straddling the 32 KiB
|
|
34
|
+
boundary never appears, whole or in part; an id swapped for a link to a file outside the workspace -> `forbidden`;
|
|
35
|
+
`../../etc/passwd`, `/etc/passwd`, a plain relative path and a made-up id -> `not_found`; binary -> `forbidden` in enforce;
|
|
36
|
+
`report` -> `error` + `protocol_unsupported`; the diff of the work tree masked and without `.env`; the consumer cancels
|
|
37
|
+
after the first chunk and the next request still works; zero frames refused by the gateway; nothing printed by the agent
|
|
38
|
+
carries content or a path. Negative control: with the DLP step disabled in the agent the test fails.
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// F3-07 interoperability client: the REAL Local Agent content handlers (src/la-protocol-v2/content-handlers, DLP, path
|
|
3
|
+
// guard, opaque ids) around the real v2 link, against the real gateway LaV2Session (driven by LaV2NodeContentInteropTest).
|
|
4
|
+
// Nothing is faked on the agent side except the workspace manager (one temp workspace). It prepares files, mints the
|
|
5
|
+
// opaque ids the way a future inventory would (link.content.mintRef) and prints them, one JSON per line, for the test.
|
|
6
|
+
//
|
|
7
|
+
// env: GW_URL TOKEN TENANT AGENT KEY_ID PUBLIC_KEY MODE(enforce) LOCAL_AGENT_DLP_MODE ... (LOCAL_AGENT_CONTENT_HANDLERS is forced on)
|
|
8
|
+
// stdin: "quit"
|
|
9
|
+
import crypto from "node:crypto";
|
|
10
|
+
import fs from "node:fs";
|
|
11
|
+
import os from "node:os";
|
|
12
|
+
import path from "node:path";
|
|
13
|
+
import readline from "node:readline";
|
|
14
|
+
import { execFileSync } from "node:child_process";
|
|
15
|
+
import WebSocket from "ws";
|
|
16
|
+
import { buildV2Link } from "../../src/la-protocol-v2/runtime.js";
|
|
17
|
+
import { resolveSigningConfig } from "../../src/utils/request-signing.js";
|
|
18
|
+
|
|
19
|
+
const { GW_URL, TOKEN, TENANT, AGENT, KEY_ID, PUBLIC_KEY, MODE = "enforce" } = process.env;
|
|
20
|
+
const out = (o) => process.stdout.write(JSON.stringify(o) + "\n");
|
|
21
|
+
|
|
22
|
+
const base = fs.mkdtempSync(path.join(os.tmpdir(), "f307-interop-"));
|
|
23
|
+
const ROOT = path.join(base, "ws");
|
|
24
|
+
fs.mkdirSync(ROOT);
|
|
25
|
+
const put = (rel, data) => { const p = path.join(ROOT, rel); fs.mkdirSync(path.dirname(p), { recursive: true }); fs.writeFileSync(p, data); };
|
|
26
|
+
const git = (...a) => execFileSync("git", ["-c", "user.email=t@t", "-c", "user.name=t", "-c", "commit.gpgsign=false", ...a], { cwd: ROOT, stdio: "ignore" });
|
|
27
|
+
|
|
28
|
+
export const GH = "ghp_" + "A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q7r8";
|
|
29
|
+
// letters only: the DLP phone rule masks long digit runs, which would make 1 MiB grow past the limit
|
|
30
|
+
const bigText = Buffer.from("alpha beta gamma delta epsilon zeta eta theta\n".repeat(30000)).subarray(0, 1024 * 1024);
|
|
31
|
+
const straddle = "a".repeat(32766 - 20 - 1) + "\n" + `k=${GH}\n` + "z\n".repeat(60000);
|
|
32
|
+
|
|
33
|
+
put("src/app.txt", `first line\ntoken = "${GH}"\nlast line\n`);
|
|
34
|
+
put("big.txt", bigText);
|
|
35
|
+
put("mid.txt", straddle);
|
|
36
|
+
put("swapped.txt", "innocent");
|
|
37
|
+
put("bin.png", Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0]), crypto.randomBytes(4000)]));
|
|
38
|
+
put(".env", "API=SECRET-ENV-VALUE-123456\n");
|
|
39
|
+
put("tracked.js", "const a = 1;\n");
|
|
40
|
+
fs.writeFileSync(path.join(base, "outside-secret.txt"), "OUTSIDE-SECRET-CONTENT");
|
|
41
|
+
git("init", "-q", "-b", "main"); git("add", "-f", "-A"); git("commit", "-q", "-m", "init");
|
|
42
|
+
put("tracked.js", `const a = 2;\nconst t = "${GH}";\n`);
|
|
43
|
+
|
|
44
|
+
const signing = resolveSigningConfig({
|
|
45
|
+
LOCAL_AGENT_SIGNATURE_MODE: MODE, LOCAL_AGENT_SIGNING_PUBLIC_KEYS: `${KEY_ID}=${PUBLIC_KEY}`, LOCAL_AGENT_TENANT_ID: TENANT,
|
|
46
|
+
}, { defaultFile: null, fileCfg: {} });
|
|
47
|
+
|
|
48
|
+
const env = { ...process.env, LOCAL_AGENT_CONTENT_HANDLERS: "true", LOCAL_AGENT_PROTOCOL_V2: "true" };
|
|
49
|
+
const link = await buildV2Link({
|
|
50
|
+
tenantId: TENANT, agentId: AGENT, signing, getWorkspaceRoot: () => ROOT, env,
|
|
51
|
+
wsManager: { list: () => [{ id: "ws-1", root: ROOT, tenantId: TENANT }] },
|
|
52
|
+
log: { info: () => {}, log: () => {}, warn: (m) => out({ evt: "warn", m }) },
|
|
53
|
+
});
|
|
54
|
+
const session = link.session;
|
|
55
|
+
session.on("ready", (i) => out({ evt: "ready", resumed: i.resumed, sessionId: i.sessionId }));
|
|
56
|
+
session.on("refused", (c) => out({ evt: "refused", code: c }));
|
|
57
|
+
session.on("peer-error", (c) => out({ evt: "peer-error", code: c }));
|
|
58
|
+
|
|
59
|
+
const mint = (kind, rel) => link.content.mintRef({ workspaceId: "ws-1", kind, rel })?.id ?? null;
|
|
60
|
+
const refs = {
|
|
61
|
+
app: mint("file", "src/app.txt"), big: mint("file", "big.txt"), mid: mint("file", "mid.txt"), swapped: mint("file", "swapped.txt"),
|
|
62
|
+
bin: mint("file", "bin.png"), envFile: mint("file", ".env"), diffFile: mint("diff", "tracked.js"),
|
|
63
|
+
};
|
|
64
|
+
// after the id was handed out the file becomes a link to a file OUTSIDE the workspace
|
|
65
|
+
fs.rmSync(path.join(ROOT, "swapped.txt"));
|
|
66
|
+
fs.symlinkSync(path.join(base, "outside-secret.txt"), path.join(ROOT, "swapped.txt"));
|
|
67
|
+
out({ evt: "refs", refs, bigSha256: crypto.createHash("sha256").update(bigText).digest("hex"), bigBytes: bigText.length, ghp: GH });
|
|
68
|
+
|
|
69
|
+
let ws;
|
|
70
|
+
let quitting = false;
|
|
71
|
+
function connect() {
|
|
72
|
+
ws = new WebSocket(GW_URL, { headers: { Authorization: `Bearer ${TOKEN}` } });
|
|
73
|
+
const mine = ws;
|
|
74
|
+
ws.on("open", () => {
|
|
75
|
+
const legacy = () => { out({ evt: "legacy-register" }); mine.send(JSON.stringify({ type: "register", tenantId: TENANT, port: 5055, workspacePath: null })); };
|
|
76
|
+
if (!link.begin(mine, legacy)) legacy();
|
|
77
|
+
const hb = setInterval(() => { if (mine.readyState === 1) mine.send("ping"); else clearInterval(hb); }, 5000);
|
|
78
|
+
});
|
|
79
|
+
ws.on("message", (data, isBinary) => {
|
|
80
|
+
const text = data.toString();
|
|
81
|
+
if (text === "pong") return;
|
|
82
|
+
if (link.handleMessage(mine, text, isBinary)) return;
|
|
83
|
+
out({ evt: "v1-message" });
|
|
84
|
+
});
|
|
85
|
+
ws.on("close", (code) => { out({ evt: "closed", code }); link.onClose(mine); if (!quitting) setTimeout(connect, 100); });
|
|
86
|
+
ws.on("error", () => {});
|
|
87
|
+
}
|
|
88
|
+
connect();
|
|
89
|
+
|
|
90
|
+
const done = () => { quitting = true; try { ws.terminate(); } catch { /* gone */ } link.close(); fs.rmSync(base, { recursive: true, force: true }); process.exit(0); };
|
|
91
|
+
readline.createInterface({ input: process.stdin }).on("line", (l) => { if (l.trim() === "quit") done(); }).on("close", done);
|