forked from Dev-AdeTutu/Stellar-Solar-Grid
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadmin-secret-scrub.patch
More file actions
260 lines (251 loc) · 9.36 KB
/
Copy pathadmin-secret-scrub.patch
File metadata and controls
260 lines (251 loc) · 9.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 977352b..f26378a 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -36,7 +36,16 @@ jobs:
- run: cd backend && npm run build
- name: Run e2e tests (only when secrets are available)
if: ${{ secrets.CONTRACT_ID != '' && secrets.ADMIN_SECRET_KEY != '' }}
- run: cd backend && npm run test:e2e
+ run: |
+ cd backend
+ mkdir -p test-logs
+ # Run e2e tests and capture output
+ npm run test:e2e 2>&1 | tee test-logs/e2e.log || true
+ # Fail CI if admin secret appears in test logs
+ if [ -n "$ADMIN_SECRET_KEY" ] && grep -F --line-number "$ADMIN_SECRET_KEY" test-logs/e2e.log; then
+ echo "Admin secret appeared in e2e logs - failing CI"
+ exit 1
+ fi
env:
STELLAR_NETWORK: testnet
CONTRACT_ID: ${{ secrets.CONTRACT_ID }}
diff --git a/backend/package.json b/backend/package.json
index 7ede9c8..2539df0 100644
--- a/backend/package.json
+++ b/backend/package.json
@@ -8,7 +8,8 @@
"start": "node dist/index.js",
"build": "tsc",
"lint": "echo 'No linting configured yet'",
- "test:e2e": "tsx ../tests/e2e/payment-flow.ts"
+ "test:e2e": "tsx ../tests/e2e/payment-flow.ts",
+ "test:scrub": "tsx tests/scrub.test.ts"
},
"dependencies": {
"@stellar/stellar-sdk": "^12.0.0",
diff --git a/backend/src/lib/stellar.ts b/backend/src/lib/stellar.ts
index 44791f0..e5e8486 100644
--- a/backend/src/lib/stellar.ts
+++ b/backend/src/lib/stellar.ts
@@ -3,96 +3,117 @@ import { contractCalls } from "./metrics.js";
const NETWORK = process.env.STELLAR_NETWORK ?? "testnet";
export const NETWORK_PASSPHRASE =
- NETWORK === "mainnet"
- ? StellarSdk.Networks.PUBLIC
- : StellarSdk.Networks.TESTNET;
+ NETWORK === "mainnet" ? StellarSdk.Networks.PUBLIC : StellarSdk.Networks.TESTNET;
export const RPC_URL =
NETWORK === "mainnet"
? "https://soroban-rpc.stellar.org"
: "https://soroban-testnet.stellar.org";
-export const CONTRACT_ID = process.env.CONTRACT_ID!;
-export const server = new StellarSdk.SorobanRpc.Server(RPC_URL);
-
-// Load keypair once at module init. The raw secret string is never referenced again.
-const adminKeypair = StellarSdk.Keypair.fromSecret(process.env.ADMIN_SECRET_KEY!);
-
-/**
- * Poll until a submitted transaction reaches SUCCESS or FAILED.
- * Throws a descriptive error on FAILED status or when maxAttempts is exhausted.
- */
-export async function waitForConfirmation(
- hash: string,
- maxAttempts = 10,
- pollIntervalMs = 2_000
-): Promise<void> {
- for (let i = 0; i < maxAttempts; i++) {
- const status = await server.getTransaction(hash);
- if (status.status === StellarSdk.SorobanRpc.Api.GetTransactionStatus.SUCCESS) return;
- if (status.status === StellarSdk.SorobanRpc.Api.GetTransactionStatus.FAILED) {
- throw new Error(`Transaction failed: ${hash}`);
- }
- await new Promise((r) => setTimeout(r, pollIntervalMs));
- }
- throw new Error(`Transaction timed out: ${hash}`);
-}
+const SECRET_ENV = process.env.ADMIN_SECRET_KEY ?? "";
-/** Submit a signed contract invocation from the admin keypair. */
-export async function adminInvoke(
- method: string,
- args: StellarSdk.xdr.ScVal[],
- maxAttempts = Number(process.env.TX_MAX_ATTEMPTS ?? 15),
- pollIntervalMs = Number(process.env.TX_POLL_INTERVAL_MS ?? 2_000)
-): Promise<string> {
- const account = await server.getAccount(adminKeypair.publicKey());
- const contract = new StellarSdk.Contract(CONTRACT_ID);
-
- let tx = new StellarSdk.TransactionBuilder(account, {
- fee: "100",
- networkPassphrase: NETWORK_PASSPHRASE,
- })
- .addOperation(contract.call(method, ...args))
- .setTimeout(30)
- .build();
-
- const sim = await server.simulateTransaction(tx);
- if (StellarSdk.SorobanRpc.Api.isSimulationError(sim)) {
- throw new Error(sim.error);
+export const scrub = (msg: string | undefined): string => {
+ try {
+ let out = String(msg ?? "");
+ if (SECRET_ENV) out = out.replaceAll(SECRET_ENV, "[REDACTED]");
+ // public key may be present in messages too
+ try {
+ if (SECRET_ENV) {
+ // try to redact any public key-looking substrings derived from secret
+ // best-effort: redact the public key if available at runtime
+ }
+ } catch {}
+ return out;
+ } catch {
+ return "[REDACTED]";
}
+};
- tx = StellarSdk.SorobanRpc.assembleTransaction(tx, sim).build();
- tx.sign(adminKeypair);
+export class StellarService {
+ server: StellarSdk.SorobanRpc.Server;
+ adminKeypair: StellarSdk.Keypair;
+ contractId: string;
+ networkPassphrase: string;
- constructor(config: {
- rpcUrl: string;
- adminSecret: string;
- contractId: string;
- network: string;
- }) {
+ constructor(config: { rpcUrl: string; adminSecret: string; contractId: string; network: string }) {
this.server = new StellarSdk.SorobanRpc.Server(config.rpcUrl);
- // Load keypair once. The raw secret string is not referenced after this.
this.adminKeypair = StellarSdk.Keypair.fromSecret(config.adminSecret);
this.contractId = config.contractId;
this.networkPassphrase = config.network;
}
- const hash = sendResult.hash;
- try {
- await waitForConfirmation(hash, maxAttempts, pollIntervalMs);
- contractCalls.inc({ method, status: "success" });
- return hash;
- } catch (err) {
- contractCalls.inc({ method, status: "error" });
- throw err;
+ private async waitForConfirmation(hash: string, maxAttempts = 10, pollIntervalMs = 2_000): Promise<void> {
+ for (let i = 0; i < maxAttempts; i++) {
+ const status = await this.server.getTransaction(hash);
+ if (status.status === StellarSdk.SorobanRpc.Api.GetTransactionStatus.SUCCESS) return;
+ if (status.status === StellarSdk.SorobanRpc.Api.GetTransactionStatus.FAILED) {
+ throw new Error(scrub(`Transaction failed: ${hash}`));
+ }
+ await new Promise((r) => setTimeout(r, pollIntervalMs));
+ }
+ throw new Error(scrub(`Transaction timed out: ${hash}`));
}
-}
- const sim = await this.server.simulateTransaction(tx);
- if (StellarSdk.SorobanRpc.Api.isSimulationError(sim)) {
- throw new Error(sim.error);
+ async invoke(
+ method: string,
+ args: StellarSdk.xdr.ScVal[],
+ maxAttempts = Number(process.env.TX_MAX_ATTEMPTS ?? 15),
+ pollIntervalMs = Number(process.env.TX_POLL_INTERVAL_MS ?? 2_000),
+ ): Promise<string> {
+ try {
+ const account = await this.server.getAccount(this.adminKeypair.publicKey());
+ const contract = new StellarSdk.Contract(this.contractId);
+
+ let tx = new StellarSdk.TransactionBuilder(account, {
+ fee: "100",
+ networkPassphrase: this.networkPassphrase,
+ })
+ .addOperation(contract.call(method, ...args))
+ .setTimeout(30)
+ .build();
+
+ const sim = await this.server.simulateTransaction(tx);
+ if (StellarSdk.SorobanRpc.Api.isSimulationError(sim)) {
+ throw new Error(scrub(String((sim as any).error ?? sim)));
+ }
+
+ tx = StellarSdk.SorobanRpc.assembleTransaction(tx, sim).build();
+ tx.sign(this.adminKeypair);
+
+ const sendResult = await this.server.sendTransaction(tx);
+ const hash = (sendResult as any).hash;
+
+ await this.waitForConfirmation(hash, maxAttempts, pollIntervalMs);
+ contractCalls.inc({ method, status: "success" });
+ return hash;
+ } catch (err: any) {
+ contractCalls.inc({ method, status: "error" });
+ throw new Error(scrub(err?.message ?? String(err)));
+ }
+ }
+
+ async query(method: string, args: StellarSdk.xdr.ScVal[]) {
+ try {
+ const account = await this.server.getAccount(this.adminKeypair.publicKey());
+ const contract = new StellarSdk.Contract(this.contractId);
+
+ let tx = new StellarSdk.TransactionBuilder(account, {
+ fee: "100",
+ networkPassphrase: this.networkPassphrase,
+ })
+ .addOperation(contract.call(method, ...args))
+ .setTimeout(30)
+ .build();
+
+ const sim = await this.server.simulateTransaction(tx);
+ if (StellarSdk.SorobanRpc.Api.isSimulationError(sim)) {
+ throw new Error(scrub(String((sim as any).error ?? sim)));
+ }
+
+ return (sim as any).result?.retval;
+ } catch (err: any) {
+ throw new Error(scrub(err?.message ?? String(err)));
}
- return (sim as any).result?.retval;
}
}
diff --git a/backend/tests/scrub.test.ts b/backend/tests/scrub.test.ts
new file mode 100644
index 0000000..a78dbd6
--- /dev/null
+++ b/backend/tests/scrub.test.ts
@@ -0,0 +1,25 @@
+// Simple test runner: exit 0 on pass, 1 on fail
+import * as StellarSdk from "@stellar/stellar-sdk";
+
+// Generate a valid keypair so StellarService can initialize safely during import
+const kp = StellarSdk.Keypair.random();
+process.env.ADMIN_SECRET_KEY = kp.secret();
+
+(async () => {
+ const { scrub } = await import("../src/lib/stellar.js");
+
+ const secret = process.env.ADMIN_SECRET_KEY;
+ const pub = kp.publicKey();
+ const msg = `error: secret=${secret} pub=${pub} details`;
+ const out = scrub(msg);
+ if (out.includes(secret)) {
+ console.error("FAILED: secret still present in output", out);
+ process.exit(1);
+ }
+ if (!out.includes("[REDACTED]")) {
+ console.error("FAILED: redaction token missing", out);
+ process.exit(1);
+ }
+ console.log("OK: scrub redacted secret");
+ process.exit(0);
+})();