Public: anyone can read this; the crew can change it.

Infrastructure reads Azure: each subscription a project, its resources from Resource Graph #17921

opened this

Merged 21h 27m ago, live in production

sold/azure-reads → main 0 commits

  • Merged. sold/azure-reads was merged into main as 509de83.

Review

Sign in to review this change.
5 files changed +229 −4
docs/CLOUD.md +1
@@ -79,6 +79,7 @@ A duty reads DigitalOcean and Hetzner every 5 minutes, and AWS and Cloudflare ev
7979
8080 - **AWS** (`src/cloud/aws_read.ts`). Attach `ACCESS_KEY_ID:SECRET_ACCESS_KEY`, or with `:SESSION_TOKEN` for a temporary key, of an IAM user that holds only the AWS managed policies ViewOnlyAccess and AWSBillingReadOnlyAccess. A project is a region the account has enabled, plus `global`. Read in each region: EC2 instances, EBS volumes, own snapshots and AMIs, Elastic IPs, NAT gateways, load balancers, RDS instances and snapshots (instance and cluster), log groups, Lambda functions, DynamoDB tables, ECR repositories, ECS clusters, services and running tasks (a task's launch type, vCPU and memory, and the service it is of; its environment overrides are not kept). In `global`: S3 buckets and Route 53 zones. Each keeps its state and what uses it. GovCloud and China are not read.
8181 - **Cloudflare** (`src/cloud/cloudflare_read.ts`). A project is a Cloudflare account: zones, R2 buckets (the default jurisdiction), Workers and Pages projects, as the token's permissions allow (Zone Read, Workers R2 Storage Read, Workers Scripts Read, Pages Read; Account Settings Read to list the accounts). R2's code 10042 (no R2 subscription) is a fact about the account with no buckets, not a gap, unless buckets were seen there before: those are kept, as a gap.
82 - **Azure** (`src/cloud/azure_read.ts`). A project is a subscription the service principal may read (the Reader role). Its resources come from one Azure Resource Graph query over every such subscription, paged by its skip token; a resource's group is its label, and a type the forge has no kind for is listed as a service with its Azure type. Fewer than Azure's total is a gap, not the list. Azure's costs are not read yet. The key is `TENANT_ID:CLIENT_ID:CLIENT_SECRET`, read every 6 hours.
8283 - **What could not be read** is kept with the provider's reason (`cloud_unread`), and the rows of it kept from before stay. It never reads as "nothing there". An answer over 8 MiB, cut short or malformed is one of these.
8384 - **Cost.** A resource's amount is a list price from the Places catalog or not known (null), never 0 for not known. No Cloudflare resource has a list price, and an AWS one has it as below. A region's cost is its bill, and the list prices are never added to it; they stand for a region only where no bill is kept by region. An AWS account's bill is Cost Explorer's `GetCostAndUsage`, last month and this month so far by service and region, unblended and before credits and refunds (`src/cloud/aws_cost.ts`). AWS charges $0.01 a request, so it is asked for once a UTC day, ten pages at most, the requests counted; a failed asking is not repeated that day. An account removed and added again under its name the same day is not asked for twice; one attached under another name, or renamed, is a new one and may cost up to ten cents more that day. If AWS refuses to group by region with a validation error, it is asked once more by service alone and the region is kept as not known. An answer that lists no cost for a month the kept bill has one for is refused, and the kept bill stands with that error. The forge never switches Cost Explorer on.
8485 - **AWS list prices** (`src/cloud/aws_terms.ts`, `src/cloud/aws_prices.ts`). Priced a month of 730 hours, in US dollars, rounded up to a cent: EBS volumes (gp2, gp3, io1, io2, st1, sc1 and magnetic, with provisioned IOPS and throughput), Elastic IPs from Amazon's pool, zonal NAT gateways and load balancers by the hour alone, running on-demand Linux instances, running on-demand Linux tasks on Fargate (x86 and ARM: vCPU, memory and storage past 20 GiB, as if each ran all month), and RDS for MySQL, PostgreSQL and MariaDB (hours and storage). A stopped instance is $0 and its disks are their own rows; a stopped database is its storage. Each keeps when AWS's file was read and says what it leaves out of what can apply to that thing (`CloudResource.listed`). Null, not $0: snapshots and images (the size is not what is billed), gp3a and io2a (billed by what is used), Windows and licensed instances, spot, dedicated, Local Zones, Outposts, regional NAT gateways, Aurora and clusters, other database engines, RDS gp3 of 400 GiB or more, and everything billed by use. A Fargate Spot or Windows task, one not on Fargate, one not running and one whose answer lacks a field (all of them are optional in `DescribeTasks`) have no price and say which. An ECS service has no price of its own: it says "Its tasks, about $9.02 a month at list price", and only the tasks are in a sum.
src/cloud/azure_read.ts added +146
@@ -0,0 +1,146 @@
1 /**
2 * What an Azure service principal can see, as projects: one a subscription. Its resources come from
3 * Azure Resource Graph, one query for every subscription it may read (the Reader role), paged by
4 * its skip token. GETs and that one query; nothing is changed. Azure's prices are not read here.
5 */
6
7 import { cappedText } from "./capped_text.ts";
8 import { Reasoned, exactId, reasonOf, type Found, type Inventory, type ResourceKind } from "./inventory.ts";
9 import { ARM, azureToken, type Fetch } from "./providers.ts";
10 import { nameText, text } from "./watch.ts";
11
12 const HOST = "management.azure.com";
13 const MAX_PAGES = 100;
14 const NEEDS = "the Reader role on the subscription";
15
16 /** One call, following no redirect, its answer capped; the status and Azure's error code alone on a refusal. */
17 async function call(f: Fetch, token: string, path: string, body?: unknown): Promise<any> {
18 const res = await f(`${ARM}${path}`, {
19 method: body === undefined ? "GET" : "POST",
20 headers: { authorization: `Bearer ${token}`, ...(body === undefined ? {} : { "content-type": "application/json" }) },
21 ...(body === undefined ? {} : { body: JSON.stringify(body) }),
22 redirect: "error",
23 signal: AbortSignal.timeout(20_000),
24 });
25 const said = await cappedText(res, HOST);
26 let parsed: any;
27 try {
28 parsed = JSON.parse(said);
29 } catch {
30 throw new Error(res.ok ? "the answer was not whole JSON" : `${HOST} answered ${res.status}`);
31 }
32 if (res.status !== 200) {
33 const code: unknown = parsed?.error?.code;
34 throw new Error(`${HOST} answered ${res.status}${typeof code === "string" && /^[A-Za-z]{1,60}$/.test(code) ? ` (${code})` : ""}`);
35 }
36 return parsed;
37 }
38
39 /** Azure's resource types, lower case, as the forge's kinds; any other keeps its own type as its size. */
40 const KINDS: Readonly<Record<string, ResourceKind>> = {
41 "microsoft.compute/virtualmachines": "machine",
42 "microsoft.compute/virtualmachinescalesets": "machine",
43 "microsoft.compute/disks": "volume",
44 "microsoft.compute/snapshots": "snapshot",
45 "microsoft.compute/images": "image",
46 "microsoft.compute/galleries/images": "image",
47 "microsoft.network/publicipaddresses": "address",
48 "microsoft.network/networksecuritygroups": "firewall",
49 "microsoft.network/azurefirewalls": "firewall",
50 "microsoft.network/natgateways": "nat",
51 "microsoft.network/loadbalancers": "balancer",
52 "microsoft.network/applicationgateways": "balancer",
53 "microsoft.network/frontdoors": "balancer",
54 "microsoft.cdn/profiles": "balancer",
55 "microsoft.network/dnszones": "zone",
56 "microsoft.network/privatednszones": "zone",
57 "microsoft.storage/storageaccounts": "bucket",
58 "microsoft.sql/servers": "database",
59 "microsoft.sql/servers/databases": "database",
60 "microsoft.dbforpostgresql/flexibleservers": "database",
61 "microsoft.dbformysql/flexibleservers": "database",
62 "microsoft.documentdb/databaseaccounts": "database",
63 "microsoft.cache/redis": "database",
64 "microsoft.web/sites": "site",
65 "microsoft.web/staticsites": "site",
66 "microsoft.containerregistry/registries": "registry",
67 "microsoft.containerservice/managedclusters": "cluster",
68 "microsoft.app/containerapps": "service",
69 "microsoft.containerinstance/containergroups": "task",
70 "microsoft.operationalinsights/workspaces": "logs",
71 "microsoft.insights/components": "logs",
72 };
73 /** A type the forge has no kind for is still listed: as a service, its Azure type as its size. */
74 const kindOf = (type: string): ResourceKind => KINDS[type.toLowerCase()] ?? "service";
75
76 const QUERY = "Resources | project id, name, type, location, resourceGroup, subscriptionId, sku, properties.provisioningState, managedBy | order by id asc";
77
78 /** Every page of the query, by its skip token. Fewer than Azure's total is not the list. */
79 async function resources(f: Fetch, token: string, subscriptions: readonly string[]): Promise<any[]> {
80 const out: any[] = [];
81 let skip = "";
82 for (let page = 0; page < MAX_PAGES; page++) {
83 const body = await call(f, token, "/providers/Microsoft.ResourceGraph/resources?api-version=2022-10-01", {
84 subscriptions,
85 query: QUERY,
86 options: { resultFormat: "objectArray", $top: 1000, ...(skip === "" ? {} : { $skipToken: skip }) },
87 });
88 if (!Array.isArray(body?.data)) throw new Error("the answer was not a list");
89 out.push(...body.data);
90 skip = typeof body.$skipToken === "string" ? body.$skipToken : "";
91 if (skip === "") {
92 const total = body.totalRecords;
93 if (typeof total === "number" && out.length < total) throw new Error(`Azure listed ${out.length} of ${total}: not read whole`);
94 return out;
95 }
96 }
97 throw new Error(`more than ${MAX_PAGES} pages: not read whole`);
98 }
99
100 /** Read what the principal sees: its subscriptions, and each one's resources with their group. */
101 export async function readAzure(f: Fetch, key: string): Promise<Inventory> {
102 let token: string | undefined;
103 try {
104 token = await azureToken(f, key);
105 } catch (e) {
106 throw new Reasoned(reasonOf(e, "a service principal's TENANT_ID:CLIENT_ID:CLIENT_SECRET"));
107 }
108 if (token === undefined) throw new Reasoned("An Azure credential is TENANT_ID:CLIENT_ID:CLIENT_SECRET.");
109 let subs: any[];
110 try {
111 const body = await call(f, token, "/subscriptions?api-version=2022-12-01");
112 subs = Array.isArray(body?.value) ? body.value.filter((s: any) => /^[0-9a-f-]{36}$/i.test(String(s?.subscriptionId))) : [];
113 } catch (e) {
114 throw new Reasoned(reasonOf(e, NEEDS));
115 }
116 if (subs.length === 0) throw new Reasoned(`the principal sees no subscription: give it ${NEEDS}`);
117 const projects = subs.map((s, i) => ({ id: String(s.subscriptionId).toLowerCase(), name: nameText(s.displayName) || String(s.subscriptionId), isDefault: i === 0 }));
118 const ids = new Set(projects.map((p) => p.id));
119 const things: Found[] = [];
120 const gaps: Inventory["gaps"][number][] = [];
121 try {
122 for (const r of await resources(f, token, [...ids])) {
123 const project = String(r.subscriptionId ?? "").toLowerCase();
124 if (!ids.has(project)) continue;
125 const type = String(r.type ?? "");
126 const kind = kindOf(type);
127 const sku = r.sku?.name ?? r.sku?.tier;
128 things.push({
129 kind,
130 id: exactId(String(r.id ?? "")),
131 project,
132 name: nameText(r.name),
133 region: text(r.location),
134 size: KINDS[type.toLowerCase()] === undefined ? text(type) : text(sku),
135 label: text(r.resourceGroup),
136 state: text(r.properties_provisioningState ?? r["properties.provisioningState"]),
137 attachedTo: typeof r.managedBy === "string" && r.managedBy !== "" ? [exactId(r.managedBy)] : null,
138 madeFrom: "",
139 createdAt: "",
140 });
141 }
142 } catch (e) {
143 for (const p of projects) gaps.push({ project: p.id, kind: "project", reason: reasonOf(e, NEEDS) });
144 }
145 return { projects, things, gaps };
146 }
src/cloud/projects.ts +4 −2
@@ -29,6 +29,7 @@ import { PRICE_AGE_MS, awsPrices } from "./aws_prices.ts";
2929 import { AWS_GLOBAL, readAws } from "./aws_read.ts";
3030 import { leftOut, sourceOf, type Priced } from "./aws_terms.ts";
3131 import { priced } from "./ceiling.ts";
32 import { readAzure } from "./azure_read.ts";
3233 import { readCloudflare } from "./cloudflare_read.ts";
3334 import { reasonOf, type Found, type Gap, type Inventory, type PartOf, type ResourceKind } from "./inventory.ts";
3435 import { VOLUME_GIB } from "./places.ts";
@@ -38,13 +39,13 @@ import { WATCHED, judge, pages, nameText, quotedName, text } from "./watch.ts";
3839 import type { Seen } from "./watch_read.ts";
3940
4041 /** The clouds read into projects. */
41 export const PROJECT_CLOUDS = ["digitalocean", "hetzner", "aws", "cloudflare"] as const;
42 export const PROJECT_CLOUDS = ["digitalocean", "hetzner", "aws", "cloudflare", "azure"] as const;
4243
4344 /**
4445 * How often the duty reads an account again. A whole AWS account is some 250 audited calls, so it
4546 * and Cloudflare are read every six hours; Read now and a key just checked read them at once.
4647 */
47 export const readEveryMs = (provider: string): number => (provider === "aws" || provider === "cloudflare" ? 6 * 3_600_000 : 0);
48 export const readEveryMs = (provider: string): number => (provider === "aws" || provider === "cloudflare" || provider === "azure" ? 6 * 3_600_000 : 0);
4849
4950 export interface CloudProject {
5051 readonly provider: string;
@@ -131,6 +132,7 @@ async function readWhole(db: Database, provider: string, account: string, f: Fet
131132 const bucket = db.query("SELECT 1 FROM cloud_resource WHERE cloud_provider = ?1 AND cloud_account_id = ?2 AND cloud_project_id = ?3 AND kind = 'bucket' LIMIT 1");
132133 return ofInventory(await readCloudflare(f, token, keptProjects(db, provider, account), (id) => bucket.get(provider, account, id) !== null));
133134 }
135 if (provider === "azure") return ofInventory(await readAzure(f, token));
134136 if (provider !== "aws") throw new Error(`${provider} is not read into projects`);
135137 const key = awsKey(token);
136138 if (key === undefined) throw new Error("the key is not ACCESS_KEY_ID:SECRET_ACCESS_KEY");
src/cloud/providers.ts +2 −2
@@ -331,7 +331,7 @@ const tag = (xml: string, t: string): string[] =>
331331
332332 // ---- Azure ----
333333
334 async function azureToken(f: Fetch, value: string): Promise<string | undefined> {
334 export async function azureToken(f: Fetch, value: string): Promise<string | undefined> {
335335 const p = parts(value, 3);
336336 if (!p || !/^[0-9a-zA-Z.-]+$/.test(p[0]!)) return undefined;
337337 const res = await json(
@@ -351,7 +351,7 @@ async function azureToken(f: Fetch, value: string): Promise<string | undefined>
351351 return typeof res.access_token === "string" ? res.access_token : undefined;
352352 }
353353
354 const ARM = "https://management.azure.com";
354 export const ARM = "https://management.azure.com";
355355
356356 // ---- Fly ----
357357
test/cloud-azure.test.ts added +76
@@ -0,0 +1,76 @@
1 /**
2 * Azure as projects (src/cloud/azure_read.ts): a service principal's subscriptions, and their
3 * resources from one Resource Graph query, paged by its skip token. Azure is faked here.
4 */
5 import { expect, test } from "bun:test";
6 import { readAzure } from "../src/cloud/azure_read.ts";
7 import { PROJECT_CLOUDS } from "../src/cloud/projects.ts";
8 import type { Fetch } from "../src/cloud/providers.ts";
9
10 const SUB = "11111111-2222-3333-4444-555555555555";
11 const KEY = "contoso.onmicrosoft.com:client-id:client-secret";
12 const vm = (name: string) => ({
13 id: `/subscriptions/${SUB}/resourceGroups/web/providers/Microsoft.Compute/virtualMachines/${name}`,
14 name,
15 type: "Microsoft.Compute/virtualMachines",
16 location: "eastus",
17 resourceGroup: "web",
18 subscriptionId: SUB,
19 sku: null,
20 properties_provisioningState: "Succeeded",
21 managedBy: "",
22 });
23
24 /** An Azure that signs in, lists one subscription, and answers the query in two pages. */
25 function azure(over: { graph?: (body: any) => Response; subs?: () => Response } = {}): { f: Fetch; calls: string[] } {
26 const calls: string[] = [];
27 const f: Fetch = async (url, init) => {
28 const u = new URL(url);
29 calls.push(`${init?.method ?? "GET"} ${u.host}${u.pathname}`);
30 if (u.host === "login.microsoftonline.com") return Response.json({ access_token: "t" });
31 if (u.pathname === "/subscriptions") return over.subs?.() ?? Response.json({ value: [{ subscriptionId: SUB, displayName: "Contoso prod" }] });
32 const body = JSON.parse(String(init?.body ?? "{}"));
33 if (over.graph !== undefined) return over.graph(body);
34 return body.options?.$skipToken === undefined
35 ? Response.json({ totalRecords: 3, data: [vm("one"), vm("two")], $skipToken: "next" })
36 : Response.json({
37 totalRecords: 3,
38 data: [{ id: `/subscriptions/${SUB}/resourceGroups/web/providers/Microsoft.Web/sites/shop`, name: "shop", type: "Microsoft.Web/sites", location: "eastus", resourceGroup: "web", subscriptionId: SUB }],
39 });
40 };
41 return { f, calls };
42 }
43
44 test("Azure is read into projects: one a subscription, every resource on every page, its group as its label", async () => {
45 expect(PROJECT_CLOUDS).toContain("azure");
46 const { f, calls } = azure();
47 const read = await readAzure(f, KEY);
48 expect(read.projects).toEqual([{ id: SUB, name: "Contoso prod", isDefault: true }]);
49 expect(read.things.map((t) => [t.kind, t.name, t.label, t.region, t.state])).toEqual([
50 ["machine", "one", "web", "eastus", "Succeeded"],
51 ["machine", "two", "web", "eastus", "Succeeded"],
52 ["site", "shop", "web", "eastus", ""],
53 ]);
54 expect(read.gaps).toEqual([]);
55 // A sign-in, the subscriptions, and the query twice: nothing else, and nothing that writes.
56 expect(calls).toEqual([
57 "POST login.microsoftonline.com/contoso.onmicrosoft.com/oauth2/v2.0/token",
58 "GET management.azure.com/subscriptions",
59 "POST management.azure.com/providers/Microsoft.ResourceGraph/resources",
60 "POST management.azure.com/providers/Microsoft.ResourceGraph/resources",
61 ]);
62 });
63
64 test("a type the forge has no kind for is listed with its Azure type; fewer than Azure's total is a gap, not the list", async () => {
65 const odd = { id: `/subscriptions/${SUB}/x`, name: "vault", type: "Microsoft.KeyVault/vaults", location: "eastus", resourceGroup: "sec", subscriptionId: SUB };
66 const one = await readAzure(azure({ graph: () => Response.json({ totalRecords: 1, data: [odd] }) }).f, KEY);
67 expect(one.things.map((t) => [t.kind, t.size])).toEqual([["service", "Microsoft.KeyVault/vaults"]]);
68 const short = await readAzure(azure({ graph: () => Response.json({ totalRecords: 5, data: [odd] }) }).f, KEY);
69 expect(short.things).toEqual([]);
70 expect(short.gaps.map((g) => g.reason)).toEqual(["Azure listed 1 of 5: not read whole"]);
71 });
72
73 test("a key that is not three parts, and a principal with no subscription, say so", async () => {
74 await expect(readAzure(azure().f, "AKIDEXAMPLE:secret")).rejects.toThrow("An Azure credential is TENANT_ID:CLIENT_ID:CLIENT_SECRET.");
75 await expect(readAzure(azure({ subs: () => Response.json({ value: [] }) }).f, KEY)).rejects.toThrow("the principal sees no subscription");
76 });

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs