@installagent/sdk 0.6.0 → 0.8.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/dist/access-check.d.ts +32 -0
- package/dist/access-check.js +339 -0
- package/dist/client-manifest.d.ts +32 -0
- package/dist/client-manifest.js +64 -0
- package/dist/doctor.js +94 -0
- package/dist/env-fill.js +3 -35
- package/dist/env-push.js +3 -16
- package/dist/gcp-dwd.d.ts +73 -0
- package/dist/gcp-dwd.js +269 -0
- package/dist/gcp-inspect.d.ts +126 -0
- package/dist/gcp-inspect.js +292 -0
- package/dist/gcp-service-account-key.d.ts +2 -0
- package/dist/gcp-service-account-key.js +1 -0
- package/dist/gcp-setup.d.ts +58 -0
- package/dist/gcp-setup.js +318 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/op-cli.d.ts +14 -0
- package/dist/op-cli.js +35 -3
- package/dist/op-store.d.ts +60 -0
- package/dist/op-store.js +230 -0
- package/dist/pr-open.d.ts +3 -1
- package/dist/pr-open.js +9 -0
- package/dist/template-sync.d.ts +10 -0
- package/dist/template-sync.js +9 -0
- package/package.json +1 -1
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
import { execFailureDetail, execFileAsync } from "./exec.js";
|
|
2
|
+
import { GCP_PROJECT_PATTERN } from "./gcp-service-account-key.js";
|
|
3
|
+
/**
|
|
4
|
+
* `ia gcp inspect` (2026-10-25): a READ-ONLY report on one Google Cloud
|
|
5
|
+
* project, so a technician sees what a setup step will meet before running
|
|
6
|
+
* it. Every gcloud call carries `--account=` and `--project=` — this machine
|
|
7
|
+
* often has a client account active (see AGENT.md), and an implicit default
|
|
8
|
+
* is how a command lands in the wrong project. Nothing here writes to GCP.
|
|
9
|
+
*
|
|
10
|
+
* Each section fails on its own: admin@ often lacks one permission on a
|
|
11
|
+
* client project (serviceusage on half our org), and the other sections are
|
|
12
|
+
* still worth having. Human members of the IAM policy are masked to their
|
|
13
|
+
* domain (client PII); service accounts and the operator's own account stay
|
|
14
|
+
* whole. The Monitoring access token goes straight into a request header and
|
|
15
|
+
* is never logged, returned or printed.
|
|
16
|
+
*/
|
|
17
|
+
/** The org policies a setup step trips over (DWD key, Gmail push grant). */
|
|
18
|
+
export const GCP_INSPECT_POLICIES = [
|
|
19
|
+
"iam.disableServiceAccountKeyCreation",
|
|
20
|
+
"iam.allowedPolicyMemberDomains",
|
|
21
|
+
];
|
|
22
|
+
/** APIs a client setup usually needs; the report flags each as on or off. */
|
|
23
|
+
export const GCP_INSPECT_KEY_APIS = [
|
|
24
|
+
"gmail.googleapis.com",
|
|
25
|
+
"pubsub.googleapis.com",
|
|
26
|
+
"iam.googleapis.com",
|
|
27
|
+
"monitoring.googleapis.com",
|
|
28
|
+
"generativelanguage.googleapis.com",
|
|
29
|
+
"drive.googleapis.com",
|
|
30
|
+
];
|
|
31
|
+
/** A user-managed key older than this is flagged for rotation. */
|
|
32
|
+
export const GCP_KEY_MAX_AGE_DAYS = 90;
|
|
33
|
+
const EMAIL = /^[^\s@<>]+@[^\s@<>]+\.[^\s@<>]+$/;
|
|
34
|
+
const SERVICE = /^[a-z0-9.-]+\.googleapis\.com$/;
|
|
35
|
+
export function validateGcpTarget(project, account) {
|
|
36
|
+
if (!GCP_PROJECT_PATTERN.test(project)) {
|
|
37
|
+
throw new Error(`invalid GCP project "${project}" — pass the project ID (lowercase letters, digits, hyphens), not its name or number`);
|
|
38
|
+
}
|
|
39
|
+
if (!EMAIL.test(account)) {
|
|
40
|
+
throw new Error(`invalid gcloud account "${account}" — pass the Google account the commands run as, e.g. admin@installagent.com`);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
/** Every gcloud call of `ia gcp` goes through here, so none can miss the two flags. */
|
|
44
|
+
export function gcloudArgs(args, project, account) {
|
|
45
|
+
return [...args, `--account=${account}`, `--project=${project}`, "--quiet"];
|
|
46
|
+
}
|
|
47
|
+
/** `user:jane@acme.com` → `user:…@acme.com`. Service accounts and `account` itself stay whole. */
|
|
48
|
+
export function maskMember(member, account) {
|
|
49
|
+
const match = member.match(/^((?:deleted:)?(?:user|group)):([^@?]+)@([^?]+)(\?.*)?$/);
|
|
50
|
+
if (!match)
|
|
51
|
+
return member;
|
|
52
|
+
if (`${match[2]}@${match[3]}`.toLowerCase() === account.toLowerCase())
|
|
53
|
+
return member;
|
|
54
|
+
return `${match[1]}:…@${match[3]}`;
|
|
55
|
+
}
|
|
56
|
+
/** Hides everything an id could be misused with: only the OAuth project number survives. */
|
|
57
|
+
export function maskCredential(credentialId) {
|
|
58
|
+
const oauth = credentialId.match(/^oauth2:(\d+)-/);
|
|
59
|
+
if (oauth)
|
|
60
|
+
return `oauth2:${oauth[1]}-…`;
|
|
61
|
+
const sa = credentialId.match(/^serviceaccount:(\d+)$/);
|
|
62
|
+
if (sa)
|
|
63
|
+
return credentialId;
|
|
64
|
+
const kind = credentialId.split(":")[0];
|
|
65
|
+
return kind ? `${kind}:…` : "unknown";
|
|
66
|
+
}
|
|
67
|
+
export function describePolicy(raw) {
|
|
68
|
+
const policy = (raw ?? {});
|
|
69
|
+
if (policy.booleanPolicy)
|
|
70
|
+
return policy.booleanPolicy.enforced ? "enforced" : "not enforced";
|
|
71
|
+
const list = policy.listPolicy;
|
|
72
|
+
if (list) {
|
|
73
|
+
if (list.allValues === "ALLOW")
|
|
74
|
+
return "allow all";
|
|
75
|
+
if (list.allValues === "DENY")
|
|
76
|
+
return "deny all";
|
|
77
|
+
const allowed = list.allowedValues?.length ?? 0;
|
|
78
|
+
const denied = list.deniedValues?.length ?? 0;
|
|
79
|
+
if (allowed)
|
|
80
|
+
return `${allowed} allowed`;
|
|
81
|
+
if (denied)
|
|
82
|
+
return `${denied} denied`;
|
|
83
|
+
}
|
|
84
|
+
return "not set (Google default)";
|
|
85
|
+
}
|
|
86
|
+
export async function gcpInspect(options) {
|
|
87
|
+
const project = options.project.trim();
|
|
88
|
+
const account = options.account.trim();
|
|
89
|
+
validateGcpTarget(project, account);
|
|
90
|
+
const service = options.service?.trim() || "gmail.googleapis.com";
|
|
91
|
+
if (!SERVICE.test(service)) {
|
|
92
|
+
throw new Error(`invalid service "${service}" — expected e.g. gmail.googleapis.com`);
|
|
93
|
+
}
|
|
94
|
+
const hours = options.hours ?? 24;
|
|
95
|
+
if (!Number.isInteger(hours) || hours < 1 || hours > 168) {
|
|
96
|
+
throw new Error(`--hours must be a whole number from 1 to 168 (got ${hours})`);
|
|
97
|
+
}
|
|
98
|
+
const exec = options.execFileImpl ?? execFileAsync;
|
|
99
|
+
const fetchImpl = options.fetchImpl ?? fetch;
|
|
100
|
+
const now = options.now ?? (() => new Date());
|
|
101
|
+
const gcloud = async (args) => (await exec("gcloud", gcloudArgs(args, project, account))).stdout;
|
|
102
|
+
const gcloudJson = async (args) => JSON.parse((await gcloud([...args, "--format=json"])) || "null");
|
|
103
|
+
const [info, apis, policies, iamRaw] = await Promise.all([
|
|
104
|
+
section(account, async () => {
|
|
105
|
+
const raw = await gcloudJson(["projects", "describe", project]);
|
|
106
|
+
return {
|
|
107
|
+
projectId: raw.projectId,
|
|
108
|
+
projectNumber: String(raw.projectNumber),
|
|
109
|
+
name: raw.name ?? "",
|
|
110
|
+
parent: raw.parent?.type && raw.parent.id ? `${raw.parent.type}/${raw.parent.id}` : null,
|
|
111
|
+
lifecycleState: raw.lifecycleState ?? "",
|
|
112
|
+
};
|
|
113
|
+
}),
|
|
114
|
+
section(account, async () => {
|
|
115
|
+
const out = await gcloud(["services", "list", "--enabled", "--format=value(config.name)"]);
|
|
116
|
+
const enabled = out
|
|
117
|
+
.split("\n")
|
|
118
|
+
.map((line) => line.trim())
|
|
119
|
+
.filter(Boolean)
|
|
120
|
+
.sort();
|
|
121
|
+
return {
|
|
122
|
+
enabled,
|
|
123
|
+
key: GCP_INSPECT_KEY_APIS.map((s) => ({ service: s, enabled: enabled.includes(s) })),
|
|
124
|
+
};
|
|
125
|
+
}),
|
|
126
|
+
section(account, () => Promise.all(GCP_INSPECT_POLICIES.map(async (constraint) => {
|
|
127
|
+
// The legacy surface: it works without the orgpolicy API enabled on
|
|
128
|
+
// the quota project, which the newer `gcloud org-policies` needs.
|
|
129
|
+
const raw = await gcloudJson([
|
|
130
|
+
"resource-manager",
|
|
131
|
+
"org-policies",
|
|
132
|
+
"describe",
|
|
133
|
+
constraint,
|
|
134
|
+
"--effective",
|
|
135
|
+
]);
|
|
136
|
+
return { constraint, state: describePolicy(raw) };
|
|
137
|
+
}))),
|
|
138
|
+
section(account, () => gcloudJson([
|
|
139
|
+
"projects",
|
|
140
|
+
"get-iam-policy",
|
|
141
|
+
project,
|
|
142
|
+
])),
|
|
143
|
+
]);
|
|
144
|
+
const bindings = iamRaw.ok ? (iamRaw.data?.bindings ?? []) : [];
|
|
145
|
+
const iam = iamRaw.ok
|
|
146
|
+
? {
|
|
147
|
+
ok: true,
|
|
148
|
+
data: {
|
|
149
|
+
yourRoles: bindings
|
|
150
|
+
.filter((b) => (b.members ?? []).includes(`user:${account}`))
|
|
151
|
+
.map((b) => b.role)
|
|
152
|
+
.sort(),
|
|
153
|
+
bindings: bindings.map((b) => ({
|
|
154
|
+
role: b.role,
|
|
155
|
+
members: (b.members ?? []).map((m) => maskMember(m, account)),
|
|
156
|
+
})),
|
|
157
|
+
},
|
|
158
|
+
}
|
|
159
|
+
: iamRaw;
|
|
160
|
+
const serviceAccounts = await section(account, async () => {
|
|
161
|
+
const list = (await gcloudJson([
|
|
162
|
+
"iam",
|
|
163
|
+
"service-accounts",
|
|
164
|
+
"list",
|
|
165
|
+
])) ?? [];
|
|
166
|
+
return Promise.all(list.map(async (sa) => {
|
|
167
|
+
const member = `serviceAccount:${sa.email}`;
|
|
168
|
+
const keys = await section(account, async () => {
|
|
169
|
+
const raw = (await gcloudJson([
|
|
170
|
+
"iam",
|
|
171
|
+
"service-accounts",
|
|
172
|
+
"keys",
|
|
173
|
+
"list",
|
|
174
|
+
`--iam-account=${sa.email}`,
|
|
175
|
+
"--managed-by=user",
|
|
176
|
+
])) ?? [];
|
|
177
|
+
return raw.map((key) => {
|
|
178
|
+
const createdAt = key.validAfterTime ?? "";
|
|
179
|
+
const ageDays = createdAt
|
|
180
|
+
? Math.floor((now().getTime() - Date.parse(createdAt)) / 86_400_000)
|
|
181
|
+
: 0;
|
|
182
|
+
return {
|
|
183
|
+
id: key.name.split("/").pop() ?? key.name,
|
|
184
|
+
createdAt,
|
|
185
|
+
ageDays,
|
|
186
|
+
disabled: key.disabled === true,
|
|
187
|
+
old: ageDays > GCP_KEY_MAX_AGE_DAYS,
|
|
188
|
+
};
|
|
189
|
+
});
|
|
190
|
+
});
|
|
191
|
+
return {
|
|
192
|
+
email: sa.email,
|
|
193
|
+
disabled: sa.disabled === true,
|
|
194
|
+
roles: bindings
|
|
195
|
+
.filter((b) => (b.members ?? []).includes(member))
|
|
196
|
+
.map((b) => b.role)
|
|
197
|
+
.sort(),
|
|
198
|
+
keys,
|
|
199
|
+
};
|
|
200
|
+
}));
|
|
201
|
+
});
|
|
202
|
+
const projectNumber = info.ok ? info.data.projectNumber : null;
|
|
203
|
+
const apiCalls = await section(account, async () => {
|
|
204
|
+
const tokenOut = await gcloud(["auth", "print-access-token"]);
|
|
205
|
+
const token = tokenOut.trim();
|
|
206
|
+
if (!token)
|
|
207
|
+
throw new Error("gcloud returned no access token");
|
|
208
|
+
const end = now();
|
|
209
|
+
const start = new Date(end.getTime() - hours * 3_600_000);
|
|
210
|
+
const params = new URLSearchParams({
|
|
211
|
+
filter: `metric.type="serviceruntime.googleapis.com/api/request_count" AND resource.labels.service="${service}"`,
|
|
212
|
+
"interval.startTime": start.toISOString(),
|
|
213
|
+
"interval.endTime": end.toISOString(),
|
|
214
|
+
"aggregation.alignmentPeriod": `${hours * 3600}s`,
|
|
215
|
+
"aggregation.perSeriesAligner": "ALIGN_SUM",
|
|
216
|
+
"aggregation.crossSeriesReducer": "REDUCE_SUM",
|
|
217
|
+
"aggregation.groupByFields": "resource.labels.credential_id",
|
|
218
|
+
});
|
|
219
|
+
const response = await fetchImpl(`https://monitoring.googleapis.com/v3/projects/${project}/timeSeries?${params}`, { headers: { Authorization: `Bearer ${token}` } });
|
|
220
|
+
const body = (await response.json().catch(() => ({})));
|
|
221
|
+
if (!response.ok || body.error) {
|
|
222
|
+
throw new Error(`Cloud Monitoring ${response.status} ${body.error?.status ?? ""}`.trim() +
|
|
223
|
+
(response.status === 403 ? " — the account needs monitoring.timeSeries.list here" : ""));
|
|
224
|
+
}
|
|
225
|
+
const callers = (body.timeSeries ?? [])
|
|
226
|
+
.map((series) => {
|
|
227
|
+
const raw = series.resource?.labels?.credential_id ?? "";
|
|
228
|
+
const calls = (series.points ?? []).reduce((sum, p) => sum + Number(p.value?.int64Value ?? 0), 0);
|
|
229
|
+
const oauth = raw.match(/^oauth2:(\d+)-/);
|
|
230
|
+
return {
|
|
231
|
+
credential: maskCredential(raw),
|
|
232
|
+
calls,
|
|
233
|
+
ownedHere: oauth && projectNumber ? oauth[1] === projectNumber : null,
|
|
234
|
+
};
|
|
235
|
+
})
|
|
236
|
+
.sort((a, b) => b.calls - a.calls);
|
|
237
|
+
return { service, hours, callers };
|
|
238
|
+
});
|
|
239
|
+
return { project, account, info, apis, policies, serviceAccounts, iam, apiCalls };
|
|
240
|
+
}
|
|
241
|
+
async function section(account, run) {
|
|
242
|
+
try {
|
|
243
|
+
return { ok: true, data: await run() };
|
|
244
|
+
}
|
|
245
|
+
catch (error) {
|
|
246
|
+
return { ok: false, error: describeInspectFailure(error, account) };
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
/** True for a failure that no project change can fix: no gcloud, or the login expired. */
|
|
250
|
+
export function isGcloudLoginFailure(error) {
|
|
251
|
+
const { code, detail } = execFailureDetail(error);
|
|
252
|
+
return code === "ENOENT" || LOGIN_EXPIRED.test(detail);
|
|
253
|
+
}
|
|
254
|
+
const LOGIN_EXPIRED = /reauthentication|cannot prompt|do not currently have an active account/i;
|
|
255
|
+
/**
|
|
256
|
+
* stderr only — stdout of print-access-token is the token itself. `account`
|
|
257
|
+
* fills in the login command; without it the command says `<account>`.
|
|
258
|
+
*/
|
|
259
|
+
export function describeInspectFailure(error, account) {
|
|
260
|
+
const { code, detail } = execFailureDetail(error);
|
|
261
|
+
const login = `gcloud auth login ${account?.trim() || "<account>"}`;
|
|
262
|
+
if (code === "ENOENT") {
|
|
263
|
+
return `gcloud CLI not found — install the Google Cloud SDK, then \`${login}\``;
|
|
264
|
+
}
|
|
265
|
+
if (LOGIN_EXPIRED.test(detail)) {
|
|
266
|
+
return `gcloud login expired — run \`${login}\` in your own terminal, then retry`;
|
|
267
|
+
}
|
|
268
|
+
const reason = httpErrorSummary(detail) ?? firstLine(detail);
|
|
269
|
+
if (/PERMISSION_DENIED|403|does not have .*permission/i.test(detail)) {
|
|
270
|
+
return `no permission — ${reason}`;
|
|
271
|
+
}
|
|
272
|
+
return reason;
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* gcloud's "HttpError accessing <url>: response: <headers>, content <json>"
|
|
276
|
+
* puts the reason after the headers, past where firstLine cuts it.
|
|
277
|
+
*/
|
|
278
|
+
function httpErrorSummary(detail) {
|
|
279
|
+
if (!/HttpError accessing/.test(detail))
|
|
280
|
+
return null;
|
|
281
|
+
const code = detail.match(/"code":\s*(\d{3})/)?.[1];
|
|
282
|
+
const status = detail.match(/"status":\s*"([A-Z_]+)"/)?.[1];
|
|
283
|
+
const message = detail.match(/"message":\s*"((?:[^"\\]|\\.)*)"/)?.[1];
|
|
284
|
+
if (!code && !message)
|
|
285
|
+
return null;
|
|
286
|
+
const head = `HTTP ${code ?? "error"}${status ? ` ${status}` : ""}`;
|
|
287
|
+
return (message ? `${head}: ${message}` : head).slice(0, 300);
|
|
288
|
+
}
|
|
289
|
+
function firstLine(text) {
|
|
290
|
+
const line = text.split("\n").find((l) => l.trim()) ?? text;
|
|
291
|
+
return line.trim().slice(0, 300);
|
|
292
|
+
}
|
|
@@ -7,6 +7,8 @@ export interface MintGcpServiceAccountKeyOptions {
|
|
|
7
7
|
project: string;
|
|
8
8
|
/** Existing service-account email, e.g. `<name>@<project>.iam.gserviceaccount.com`. */
|
|
9
9
|
serviceAccountEmail: string;
|
|
10
|
+
/** The gcloud account to run as (`--account`). Default: gcloud's active account. */
|
|
11
|
+
account?: string;
|
|
10
12
|
/** Injectable for tests; defaults to real `execFile("gcloud", ...)`. */
|
|
11
13
|
execFileImpl?: ExecFileFn;
|
|
12
14
|
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { type ExecFileFn } from "./exec.js";
|
|
2
|
+
/**
|
|
3
|
+
* `ia gcp setup` (2026-10-25): bring one Google Cloud project to the state a
|
|
4
|
+
* client build needs — the project itself, billing, the APIs, Service Usage
|
|
5
|
+
* Admin for a team account, and one service account with NO roles.
|
|
6
|
+
*
|
|
7
|
+
* Plan by default: it only reads, then lists each step as `done` (nothing
|
|
8
|
+
* to do), `todo` (with the exact gcloud command), `blocked` (with the
|
|
9
|
+
* reason) or `unknown` (a read failed; not a blocker). `apply: true` runs the
|
|
10
|
+
* todo steps in order and stops at the first failure. Every step is
|
|
11
|
+
* check-then-skip, so a re-run after a failure continues where it stopped.
|
|
12
|
+
* It never deletes, never grants a role to the service account, never
|
|
13
|
+
* grants anything to an address outside installagent.com, and never mints a
|
|
14
|
+
* key (that is `ia secrets mint gcp-service-account-key --to-op`).
|
|
15
|
+
*/
|
|
16
|
+
export declare const GCP_TEAM_DOMAIN = "installagent.com";
|
|
17
|
+
export declare const SERVICE_USAGE_ADMIN = "roles/serviceusage.serviceUsageAdmin";
|
|
18
|
+
export type GcpStepStatus = "done" | "todo" | "blocked" | "unknown" | "ran" | "failed" | "skipped";
|
|
19
|
+
export interface GcpStep {
|
|
20
|
+
id: "project" | "billing" | "apis" | "service-usage-admin" | "service-account";
|
|
21
|
+
title: string;
|
|
22
|
+
status: GcpStepStatus;
|
|
23
|
+
/** The gcloud args (without the binary) for a todo/ran/failed step. */
|
|
24
|
+
command?: string[];
|
|
25
|
+
detail?: string;
|
|
26
|
+
}
|
|
27
|
+
export interface GcpSetupOptions {
|
|
28
|
+
project: string;
|
|
29
|
+
account: string;
|
|
30
|
+
/** Create the project when it does not exist. Needs `organization` or `folder`. */
|
|
31
|
+
create?: boolean;
|
|
32
|
+
organization?: string;
|
|
33
|
+
folder?: string;
|
|
34
|
+
/** Display name for a new project. Default: the project ID. */
|
|
35
|
+
name?: string;
|
|
36
|
+
/** Billing account to link when billing is off, e.g. 0X0X0X-0X0X0X-0X0X0X. */
|
|
37
|
+
billing?: string;
|
|
38
|
+
/** APIs to enable. Default: gmail.googleapis.com. */
|
|
39
|
+
apis?: string[];
|
|
40
|
+
/** A team account (…@installagent.com) to give Service Usage Admin. */
|
|
41
|
+
grantServiceUsage?: string;
|
|
42
|
+
/** Service-account name (the part before @). Created with no roles. */
|
|
43
|
+
serviceAccount?: string;
|
|
44
|
+
apply?: boolean;
|
|
45
|
+
execFileImpl?: ExecFileFn;
|
|
46
|
+
}
|
|
47
|
+
export interface GcpSetupResult {
|
|
48
|
+
project: string;
|
|
49
|
+
account: string;
|
|
50
|
+
applied: boolean;
|
|
51
|
+
/** False when a step is blocked (plan) or failed (apply). */
|
|
52
|
+
ok: boolean;
|
|
53
|
+
steps: GcpStep[];
|
|
54
|
+
nextSteps: string[];
|
|
55
|
+
}
|
|
56
|
+
/** One gcloud command as text a technician can paste, with the forced flags. */
|
|
57
|
+
export declare function formatGcloud(args: readonly string[]): string;
|
|
58
|
+
export declare function gcpSetup(options: GcpSetupOptions): Promise<GcpSetupResult>;
|
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
import { execFailureDetail, execFileAsync } from "./exec.js";
|
|
2
|
+
import { describeInspectFailure, gcloudArgs, validateGcpTarget } from "./gcp-inspect.js";
|
|
3
|
+
/**
|
|
4
|
+
* `ia gcp setup` (2026-10-25): bring one Google Cloud project to the state a
|
|
5
|
+
* client build needs — the project itself, billing, the APIs, Service Usage
|
|
6
|
+
* Admin for a team account, and one service account with NO roles.
|
|
7
|
+
*
|
|
8
|
+
* Plan by default: it only reads, then lists each step as `done` (nothing
|
|
9
|
+
* to do), `todo` (with the exact gcloud command), `blocked` (with the
|
|
10
|
+
* reason) or `unknown` (a read failed; not a blocker). `apply: true` runs the
|
|
11
|
+
* todo steps in order and stops at the first failure. Every step is
|
|
12
|
+
* check-then-skip, so a re-run after a failure continues where it stopped.
|
|
13
|
+
* It never deletes, never grants a role to the service account, never
|
|
14
|
+
* grants anything to an address outside installagent.com, and never mints a
|
|
15
|
+
* key (that is `ia secrets mint gcp-service-account-key --to-op`).
|
|
16
|
+
*/
|
|
17
|
+
export const GCP_TEAM_DOMAIN = "installagent.com";
|
|
18
|
+
export const SERVICE_USAGE_ADMIN = "roles/serviceusage.serviceUsageAdmin";
|
|
19
|
+
/** A new project ID: 6–30 characters, starts with a letter, no trailing hyphen. */
|
|
20
|
+
const NEW_PROJECT_ID = /^[a-z][a-z0-9-]{4,28}[a-z0-9]$/;
|
|
21
|
+
/** A service-account name: 6–30 characters, same shape. */
|
|
22
|
+
const SA_NAME = /^[a-z][a-z0-9-]{4,28}[a-z0-9]$/;
|
|
23
|
+
const SERVICE = /^[a-z0-9.-]+\.googleapis\.com$/;
|
|
24
|
+
const NUMERIC_ID = /^\d{6,20}$/;
|
|
25
|
+
const BILLING_ID = /^[0-9A-F]{6}-[0-9A-F]{6}-[0-9A-F]{6}$/;
|
|
26
|
+
/** One gcloud command as text a technician can paste, with the forced flags. */
|
|
27
|
+
export function formatGcloud(args) {
|
|
28
|
+
return ["gcloud", ...args].map((a) => (/^[\w@%+=:,./-]+$/.test(a) ? a : `'${a}'`)).join(" ");
|
|
29
|
+
}
|
|
30
|
+
export async function gcpSetup(options) {
|
|
31
|
+
const project = options.project.trim();
|
|
32
|
+
const account = options.account.trim();
|
|
33
|
+
validateGcpTarget(project, account);
|
|
34
|
+
const apis = [
|
|
35
|
+
...new Set((options.apis?.length ? options.apis : ["gmail.googleapis.com"]).map((a) => a.trim())),
|
|
36
|
+
];
|
|
37
|
+
for (const api of apis) {
|
|
38
|
+
if (!SERVICE.test(api))
|
|
39
|
+
throw new Error(`invalid API "${api}" — expected e.g. pubsub.googleapis.com`);
|
|
40
|
+
}
|
|
41
|
+
if (options.create) {
|
|
42
|
+
if (!NEW_PROJECT_ID.test(project)) {
|
|
43
|
+
throw new Error(`"${project}" cannot be a new project ID — 6–30 characters: lowercase letters, digits, hyphens`);
|
|
44
|
+
}
|
|
45
|
+
if (!options.organization === !options.folder) {
|
|
46
|
+
throw new Error("--create needs exactly one of --organization <id> or --folder <id> (ia gcp inspect shows the parent)");
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
for (const [flag, value] of [
|
|
50
|
+
["--organization", options.organization],
|
|
51
|
+
["--folder", options.folder],
|
|
52
|
+
]) {
|
|
53
|
+
if (value !== undefined && !NUMERIC_ID.test(value))
|
|
54
|
+
throw new Error(`${flag} takes the numeric ID, got "${value}"`);
|
|
55
|
+
}
|
|
56
|
+
if (options.billing !== undefined && !BILLING_ID.test(options.billing)) {
|
|
57
|
+
throw new Error(`--billing takes a billing account ID like 0X0X0X-0X0X0X-0X0X0X, got "${options.billing}"`);
|
|
58
|
+
}
|
|
59
|
+
const grantee = options.grantServiceUsage?.trim().toLowerCase();
|
|
60
|
+
if (grantee !== undefined &&
|
|
61
|
+
!new RegExp(`^[^\\s@]+@${GCP_TEAM_DOMAIN.replace(".", "\\.")}$`).test(grantee)) {
|
|
62
|
+
throw new Error(`--grant-service-usage takes an ${GCP_TEAM_DOMAIN} account only, got "${grantee}"`);
|
|
63
|
+
}
|
|
64
|
+
const saName = options.serviceAccount?.trim();
|
|
65
|
+
if (saName !== undefined && !SA_NAME.test(saName)) {
|
|
66
|
+
throw new Error(`invalid service-account name "${saName}" — 6–30 characters: lowercase letters, digits, hyphens`);
|
|
67
|
+
}
|
|
68
|
+
const exec = options.execFileImpl ?? execFileAsync;
|
|
69
|
+
const args = (a) => gcloudArgs(a, project, account);
|
|
70
|
+
const read = async (a) => (await exec("gcloud", args(a))).stdout;
|
|
71
|
+
// ── Plan: reads only ──────────────────────────────────────────────────
|
|
72
|
+
const steps = [];
|
|
73
|
+
let projectExists = true;
|
|
74
|
+
try {
|
|
75
|
+
await read(["projects", "describe", project, "--format=value(projectId)"]);
|
|
76
|
+
steps.push({ id: "project", title: `Project ${project}`, status: "done", detail: "exists" });
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
projectExists = false;
|
|
80
|
+
const detail = describeInspectFailure(error, account);
|
|
81
|
+
// gcloud says PERMISSION_DENIED for a project that does not exist too,
|
|
82
|
+
// so "missing" and "not visible" look the same; --create decides.
|
|
83
|
+
if (/login expired|gcloud CLI not found/.test(detail) || !options.create) {
|
|
84
|
+
steps.push({
|
|
85
|
+
id: "project",
|
|
86
|
+
title: `Project ${project}`,
|
|
87
|
+
status: "blocked",
|
|
88
|
+
detail: options.create
|
|
89
|
+
? detail
|
|
90
|
+
: `not found, or ${account} cannot see it (${detail}). To make it, pass --create with --organization or --folder`,
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
else {
|
|
94
|
+
const parent = options.organization
|
|
95
|
+
? `--organization=${options.organization}`
|
|
96
|
+
: `--folder=${options.folder}`;
|
|
97
|
+
steps.push({
|
|
98
|
+
id: "project",
|
|
99
|
+
title: `Project ${project}`,
|
|
100
|
+
status: "todo",
|
|
101
|
+
command: args([
|
|
102
|
+
"projects",
|
|
103
|
+
"create",
|
|
104
|
+
project,
|
|
105
|
+
parent,
|
|
106
|
+
`--name=${options.name?.trim() || project}`,
|
|
107
|
+
]),
|
|
108
|
+
detail: "will be created (the ID is global: create fails if anyone has it)",
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
const needsBilling = apis.includes("pubsub.googleapis.com");
|
|
113
|
+
if (options.billing || needsBilling) {
|
|
114
|
+
const link = options.billing
|
|
115
|
+
? args(["billing", "projects", "link", project, `--billing-account=${options.billing}`])
|
|
116
|
+
: undefined;
|
|
117
|
+
let enabled = null;
|
|
118
|
+
let readError = "";
|
|
119
|
+
if (projectExists) {
|
|
120
|
+
try {
|
|
121
|
+
enabled = /true/i.test(await read(["billing", "projects", "describe", project, "--format=value(billingEnabled)"]));
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
readError = describeInspectFailure(error, account);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
else {
|
|
128
|
+
enabled = false;
|
|
129
|
+
}
|
|
130
|
+
if (enabled) {
|
|
131
|
+
steps.push({ id: "billing", title: "Billing", status: "done", detail: "enabled" });
|
|
132
|
+
}
|
|
133
|
+
else if (enabled === false && link) {
|
|
134
|
+
steps.push({
|
|
135
|
+
id: "billing",
|
|
136
|
+
title: "Billing",
|
|
137
|
+
status: "todo",
|
|
138
|
+
command: link,
|
|
139
|
+
detail: "will be linked",
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
else if (enabled === false) {
|
|
143
|
+
steps.push({
|
|
144
|
+
id: "billing",
|
|
145
|
+
title: "Billing",
|
|
146
|
+
status: "blocked",
|
|
147
|
+
detail: "off, and Pub/Sub needs it — pass --billing <billing account ID>",
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
else {
|
|
151
|
+
steps.push({
|
|
152
|
+
id: "billing",
|
|
153
|
+
title: "Billing",
|
|
154
|
+
status: link ? "todo" : "unknown",
|
|
155
|
+
command: link,
|
|
156
|
+
detail: `could not read (${readError})${link ? "; will link" : "; Pub/Sub fails to enable if it is off"}`,
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
// A failed read enables all of them: enabling an API that is on is a no-op.
|
|
161
|
+
let missing = apis;
|
|
162
|
+
let apisNote = "";
|
|
163
|
+
if (projectExists) {
|
|
164
|
+
try {
|
|
165
|
+
const enabled = (await read(["services", "list", "--enabled", "--format=value(config.name)"]))
|
|
166
|
+
.split("\n")
|
|
167
|
+
.map((l) => l.trim());
|
|
168
|
+
missing = apis.filter((a) => !enabled.includes(a));
|
|
169
|
+
}
|
|
170
|
+
catch (error) {
|
|
171
|
+
apisNote = `could not list enabled APIs (${describeInspectFailure(error, account)}); `;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
steps.push(missing.length
|
|
175
|
+
? {
|
|
176
|
+
id: "apis",
|
|
177
|
+
title: "APIs",
|
|
178
|
+
status: "todo",
|
|
179
|
+
command: args(["services", "enable", ...missing]),
|
|
180
|
+
detail: `${apisNote}will enable ${missing.join(", ")}`,
|
|
181
|
+
}
|
|
182
|
+
: { id: "apis", title: "APIs", status: "done", detail: `${apis.join(", ")} already on` });
|
|
183
|
+
if (grantee) {
|
|
184
|
+
const member = `user:${grantee}`;
|
|
185
|
+
const grant = args([
|
|
186
|
+
"projects",
|
|
187
|
+
"add-iam-policy-binding",
|
|
188
|
+
project,
|
|
189
|
+
`--member=${member}`,
|
|
190
|
+
`--role=${SERVICE_USAGE_ADMIN}`,
|
|
191
|
+
"--condition=None",
|
|
192
|
+
]);
|
|
193
|
+
let has = false;
|
|
194
|
+
let readError = "";
|
|
195
|
+
if (projectExists) {
|
|
196
|
+
try {
|
|
197
|
+
const policy = JSON.parse((await read(["projects", "get-iam-policy", project, "--format=json"])) || "{}");
|
|
198
|
+
has = (policy.bindings ?? []).some((b) => b.role === SERVICE_USAGE_ADMIN && (b.members ?? []).includes(member));
|
|
199
|
+
}
|
|
200
|
+
catch (error) {
|
|
201
|
+
readError = describeInspectFailure(error, account);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
steps.push(has
|
|
205
|
+
? {
|
|
206
|
+
id: "service-usage-admin",
|
|
207
|
+
title: `Service Usage Admin for ${grantee}`,
|
|
208
|
+
status: "done",
|
|
209
|
+
detail: "granted",
|
|
210
|
+
}
|
|
211
|
+
: {
|
|
212
|
+
id: "service-usage-admin",
|
|
213
|
+
title: `Service Usage Admin for ${grantee}`,
|
|
214
|
+
status: "todo",
|
|
215
|
+
command: grant,
|
|
216
|
+
detail: readError
|
|
217
|
+
? `could not read IAM (${readError}); will grant (no-op if granted)`
|
|
218
|
+
: "will grant",
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
if (saName) {
|
|
222
|
+
const email = `${saName}@${project}.iam.gserviceaccount.com`;
|
|
223
|
+
let exists = false;
|
|
224
|
+
if (projectExists) {
|
|
225
|
+
try {
|
|
226
|
+
await read(["iam", "service-accounts", "describe", email, "--format=value(email)"]);
|
|
227
|
+
exists = true;
|
|
228
|
+
}
|
|
229
|
+
catch {
|
|
230
|
+
exists = false;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
steps.push(exists
|
|
234
|
+
? {
|
|
235
|
+
id: "service-account",
|
|
236
|
+
title: `Service account ${email}`,
|
|
237
|
+
status: "done",
|
|
238
|
+
detail: "exists",
|
|
239
|
+
}
|
|
240
|
+
: {
|
|
241
|
+
id: "service-account",
|
|
242
|
+
title: `Service account ${email}`,
|
|
243
|
+
status: "todo",
|
|
244
|
+
command: args([
|
|
245
|
+
"iam",
|
|
246
|
+
"service-accounts",
|
|
247
|
+
"create",
|
|
248
|
+
saName,
|
|
249
|
+
`--display-name=${saName}`,
|
|
250
|
+
]),
|
|
251
|
+
detail: "will be created with no roles",
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
const blocked = steps.some((s) => s.status === "blocked");
|
|
255
|
+
const todo = steps.some((s) => s.status === "todo");
|
|
256
|
+
const nextSteps = [];
|
|
257
|
+
if (!options.apply || blocked || !todo) {
|
|
258
|
+
if (blocked)
|
|
259
|
+
nextSteps.push("Fix the blocked step(s), then run the plan again.");
|
|
260
|
+
else if (todo)
|
|
261
|
+
nextSteps.push("Read the commands above, then run the same command with --apply.");
|
|
262
|
+
else
|
|
263
|
+
nextSteps.push("Nothing to do — the project is already set up.");
|
|
264
|
+
if (options.apply && blocked)
|
|
265
|
+
nextSteps.push("--apply ran nothing because a step is blocked.");
|
|
266
|
+
return { project, account, applied: false, ok: !blocked, steps, nextSteps };
|
|
267
|
+
}
|
|
268
|
+
// ── Apply: run the todo steps in order, stop at the first failure ─────
|
|
269
|
+
let failed = false;
|
|
270
|
+
for (const step of steps) {
|
|
271
|
+
if (step.status !== "todo" || !step.command)
|
|
272
|
+
continue;
|
|
273
|
+
if (failed) {
|
|
274
|
+
step.status = "skipped";
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
try {
|
|
278
|
+
await exec("gcloud", step.command);
|
|
279
|
+
step.status = "ran";
|
|
280
|
+
step.detail = ranDetail(step, missing);
|
|
281
|
+
}
|
|
282
|
+
catch (error) {
|
|
283
|
+
failed = true;
|
|
284
|
+
step.status = "failed";
|
|
285
|
+
step.detail = describeApplyFailure(error, account);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
if (failed)
|
|
289
|
+
nextSteps.push("Fix the failed step, then run the same command again: done steps are skipped.");
|
|
290
|
+
else
|
|
291
|
+
nextSteps.push(`Check the result: ia gcp inspect -p ${project} -a ${account}`);
|
|
292
|
+
return { project, account, applied: true, ok: !failed, steps, nextSteps };
|
|
293
|
+
}
|
|
294
|
+
/** What a step that ran did — the plan's detail says "will …". */
|
|
295
|
+
function ranDetail(step, enabledApis) {
|
|
296
|
+
switch (step.id) {
|
|
297
|
+
case "project":
|
|
298
|
+
return "created";
|
|
299
|
+
case "billing":
|
|
300
|
+
return "linked";
|
|
301
|
+
case "apis":
|
|
302
|
+
return `enabled ${enabledApis.join(", ")}`;
|
|
303
|
+
case "service-usage-admin":
|
|
304
|
+
return "granted";
|
|
305
|
+
case "service-account":
|
|
306
|
+
return "created with no roles";
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
function describeApplyFailure(error, account) {
|
|
310
|
+
const { detail } = execFailureDetail(error);
|
|
311
|
+
if (/already exists|ALREADY_EXISTS/i.test(detail)) {
|
|
312
|
+
return `already exists — if it is not ours, pick another ID. gcloud said: ${firstLine(detail)}`;
|
|
313
|
+
}
|
|
314
|
+
return describeInspectFailure(error, account);
|
|
315
|
+
}
|
|
316
|
+
function firstLine(text) {
|
|
317
|
+
return (text.split("\n").find((l) => l.trim()) ?? text).trim().slice(0, 300);
|
|
318
|
+
}
|