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

OVHcloud US is a cloud account: attach and verify a signed application key scoped to one project #16601

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/16555-ovhcloud-us-is-a-cloud-account-attach-an → main 0 commits fork 2 threads · 2 unresolved

  • Merged. scout/16555-ovhcloud-us-is-a-cloud-account-attach-an was merged into main as 44fc777.

Review

Sign in to review this change.
9 files changed +310 −2
docs/features/ovh.md added +16
@@ -0,0 +1,16 @@
1 ---
2 topic: Hosting forges for others, and getting paid
3 row: OVHcloud US cloud account
4 ---
5 # OVHcloud US cloud account
6
7 A cloud account of provider `ovh` ("OVHcloud US") is
8 `APPLICATION_KEY:APPLICATION_SECRET:CONSUMER_KEY:PROJECT_ID`, attached on the cloud
9 accounts page or through the `cloud_account` MCP tool like any other. It talks to the
10 OVHcloud US API (`api.us.ovhcloud.com/1.0`, fixed in code and declared in `forge.json`
11 `egress`), signing each request (`src/cloud/ovh_sign.ts`). Why the API and not OpenStack:
12 an OpenStack user is project-wide with no narrower role, while a consumer key is issued
13 with access rules scoped to paths, so `GET`, `POST` and `DELETE` on
14 `/cloud/project/{projectId}/*` is the narrowest credential that can create and delete an
15 instance and a volume. Verify reads those rules and says whether the key can write. No
16 dependency was added.
forge.json +1
@@ -10,6 +10,7 @@
1010 "api.cloudflare.com",
1111 "api.digitalocean.com",
1212 "api.hetzner.cloud",
13 "api.us.ovhcloud.com",
1314 "www.ecb.europa.eu",
1415 "api.fly.io",
1516 "api.backblazeb2.com",
scripts/unused-exports-allow.json +1
@@ -23,6 +23,7 @@
2323 "src/checks/scans.ts SCAN_BUDGET_SECONDS",
2424 "src/checks/scans.ts scanSeconds",
2525 "src/checks/service.ts provideChecksForTest",
26 "src/cloud/ovh_sign.ts resetOvhClock",
2627 "src/contract/audit.ts identitiesOf",
2728 "src/core/accounts.ts edgeOnlyAccounts",
2829 "src/core/capacity.ts provideCpusForTest",
src/apps/manifest.ts +1 −1
@@ -588,7 +588,7 @@ export function declaredReach(forgeJson: string | undefined, section: "app" | "c
588588 }
589589
590590 /** The vendors a repository may name in `cloud.json`; a closed set. */
591 export const CLOUD_VENDORS = ["cloudflare", "fly", "hetzner", "s3", "github", "vercel", "digitalocean", "azure", "stripe"] as const;
591 export const CLOUD_VENDORS = ["cloudflare", "fly", "hetzner", "ovh", "s3", "github", "vercel", "digitalocean", "azure", "stripe"] as const;
592592 /** What a vendor may be used for; a closed set. */
593593 export const CLOUD_USES = ["compute", "storage", "backup", "dns", "cdn", "payments"] as const;
594594 export type CloudVendor = (typeof CLOUD_VENDORS)[number];
src/cloud/declared.ts +1
@@ -18,6 +18,7 @@ export const HOME: Record<Provider, string> = {
1818 cloudflare: "Bring it home: point DNS back at your own nameservers, then remove the token.",
1919 digitalocean: "Bring it home: snapshot the droplets to your own disk, then remove the token.",
2020 hetzner: "Bring it home: snapshot the servers and volumes to your own disk, then remove the token.",
21 ovh: "Bring it home: snapshot the instances and volumes to your own disk, then revoke the consumer key.",
2122 aws: "Bring it home: copy the volumes and buckets to your own disk, then remove the key.",
2223 azure: "Bring it home: export the disks to your own disk, then remove the principal.",
2324 fly: "Bring it home: run the app image on your own machine, then remove the token.",
src/cloud/ovh_sign.ts added +79
@@ -0,0 +1,79 @@
1 /**
2 * OVHcloud US request signing. Every call carries X-Ovh-Application, X-Ovh-Consumer,
3 * X-Ovh-Timestamp (server time, offset cached) and X-Ovh-Signature =
4 * "$1$" + sha1_hex(secret+consumerKey+METHOD+url+body+timestamp, joined by "+").
5 * The host is fixed here, never taken from input. Pure but for the clock and one fetch.
6 */
7
8 import { createHash } from "node:crypto";
9
10 export const OVH_API = "https://api.us.ovhcloud.com/1.0";
11
12 export interface OvhKeys {
13 readonly applicationKey: string;
14 readonly applicationSecret: string;
15 readonly consumerKey: string;
16 }
17
18 export function ovhSignature(k: OvhKeys, method: string, url: string, body: string, timestamp: number | string): string {
19 const s = [k.applicationSecret, k.consumerKey, method, url, body, String(timestamp)].join("+");
20 return `$1$${createHash("sha1").update(s).digest("hex")}`;
21 }
22
23 type Fetch = (url: string, init?: RequestInit) => Promise<Response>;
24
25 let offset: number | undefined;
26
27 /**
28 * Seconds to add to the local clock to match OVHcloud's, read once from GET /auth/time and cached.
29 */
30 async function clockOffset(f: Fetch): Promise<number> {
31 if (offset !== undefined) return offset;
32 const res = await f(`${OVH_API}/auth/time`, { signal: AbortSignal.timeout(10_000) });
33 if (!res.ok) throw new Error(`api.us.ovhcloud.com answered ${res.status}`);
34 const t = Number(await res.text());
35 if (!Number.isFinite(t) || t <= 0) throw new Error("api.us.ovhcloud.com gave no time");
36 offset = Math.round(t - Date.now() / 1000);
37 return offset;
38 }
39
40 /**
41 * One signed call; `path` starts with "/". Throws "api.us.ovhcloud.com answered N" on a refusal.
42 */
43 export async function ovhCall(f: Fetch, k: OvhKeys, method: string, path: string, body?: unknown): Promise<any> {
44 const url = `${OVH_API}${path}`;
45 const text = body === undefined ? "" : JSON.stringify(body);
46 const ts = Math.floor(Date.now() / 1000) + (await clockOffset(f));
47 const res = await f(url, {
48 method,
49 headers: {
50 "x-ovh-application": k.applicationKey,
51 "x-ovh-consumer": k.consumerKey,
52 "x-ovh-timestamp": String(ts),
53 "x-ovh-signature": ovhSignature(k, method, url, text, ts),
54 "content-type": "application/json",
55 },
56 ...(text === "" ? {} : { body: text }),
57 signal: AbortSignal.timeout(10_000),
58 });
59 if (!res.ok) throw new Error(`api.us.ovhcloud.com answered ${res.status}`);
60 return await res.json().catch(() => ({}));
61 }
62
63 /** Does an access rule path cover `target`? OVH rules end in `*` as a prefix wildcard. */
64 function covers(rulePath: string, target: string): boolean {
65 return rulePath.endsWith("*") ? target.startsWith(rulePath.slice(0, -1)) : rulePath === target;
66 }
67
68 /** True only when POST and DELETE on /cloud/project/{id}/* are both granted. */
69 export function ovhCanWrite(rules: unknown, projectId: string): boolean {
70 const list = Array.isArray(rules) ? rules : [];
71 const target = `/cloud/project/${projectId}/x`;
72 const has = (m: string) => list.some((r: any) => String(r?.method).toUpperCase() === m && covers(String(r?.path ?? ""), target));
73 return has("POST") && has("DELETE");
74 }
75
76 /** Forget the cached clock offset (tests). */
77 export function resetOvhClock(): void {
78 offset = undefined;
79 }
src/cloud/providers.ts +43 −1
@@ -9,6 +9,8 @@
99 * digitalocean GET api.digitalocean.com/v2/account, /projects, /droplets,
1010 * /volumes, /reserved_ips
1111 * hetzner GET api.hetzner.cloud/v1/servers, /volumes
12 * ovh GET api.us.ovhcloud.com/1.0/auth/time, /auth/currentCredential,
13 * /cloud/project/{id}/instance (signed: see ovh_sign.ts)
1214 * aws POST sts.amazonaws.com Action=GetCallerIdentity (a read),
1315 * POST ec2.us-east-1.amazonaws.com Action=DescribeVolumes,
1416 * DescribeAddresses (reads, despite the verb)
@@ -28,12 +30,14 @@
2830
2931 import { createHmac, createHash } from "node:crypto";
3032 import type { CloudVendor } from "../apps/manifest.ts";
33 import { ovhCall, ovhCanWrite, type OvhKeys } from "./ovh_sign.ts";
3134 import { err, ok, type Result } from "../kernel/result.ts";
3235
3336 export const PROVIDERS = [
3437 "cloudflare",
3538 "digitalocean",
3639 "hetzner",
40 "ovh",
3741 "aws",
3842 "azure",
3943 "fly",
@@ -52,6 +56,7 @@ export const VENDOR_OF: Record<Provider, CloudVendor> = {
5256 cloudflare: "cloudflare",
5357 digitalocean: "digitalocean",
5458 hetzner: "hetzner",
59 ovh: "ovh",
5560 aws: "s3",
5661 azure: "azure",
5762 fly: "fly",
@@ -68,6 +73,7 @@ export const LABEL: Record<Provider, string> = {
6873 cloudflare: "Cloudflare",
6974 digitalocean: "DigitalOcean",
7075 hetzner: "Hetzner Cloud",
76 ovh: "OVHcloud US",
7177 aws: "AWS",
7278 azure: "Azure",
7379 fly: "Fly.io",
@@ -81,6 +87,10 @@ export const shape: Record<Provider, string> = {
8187 cloudflare: "an API token (read-only scope is enough)",
8288 digitalocean: "a personal access token (read scope is enough)",
8389 hetzner: "a project API token; it is scoped to one project and is read or read-write, nothing narrower, so a pinned forge needs read-write",
90 ovh:
91 "APPLICATION_KEY:APPLICATION_SECRET:CONSUMER_KEY:PROJECT_ID of the OVHcloud US API (api.us.ovhcloud.com): an application's key and secret, a consumer key issued for it, and the Public Cloud project id. " +
92 "Grant the consumer key only the access rules GET, POST and DELETE on /cloud/project/PROJECT_ID/* (and GET /auth/currentCredential). " +
93 "Why the API and not OpenStack: an OpenStack user is project-wide with no narrower role, while a consumer key carries rules scoped to paths, so those rules are the narrowest credential that can create and delete an instance and a volume",
8494 aws: "ACCESS_KEY_ID:SECRET_ACCESS_KEY of a read-only IAM user",
8595 azure: "TENANT_ID:CLIENT_ID:CLIENT_SECRET of a Reader service principal",
8696 fly: "a deploy or read-only org token",
@@ -216,6 +226,16 @@ function parts(value: string, n: number): string[] | undefined {
216226 : undefined;
217227 }
218228
229 // ---- OVHcloud US ----
230
231 const OVH_SHAPE = "An OVHcloud US credential is APPLICATION_KEY:APPLICATION_SECRET:CONSUMER_KEY:PROJECT_ID.";
232
233 function ovhParts(value: string): { keys: OvhKeys; project: string } | undefined {
234 const p = parts(value, 4);
235 if (!p || !/^[0-9a-zA-Z_-]{1,64}$/.test(p[3]!)) return undefined;
236 return { keys: { applicationKey: p[0]!, applicationSecret: p[1]!, consumerKey: p[2]! }, project: p[3]! };
237 }
238
219239 // ---- AWS Signature V4 (query API, POST form body) ----
220240
221241 async function awsCall(
@@ -351,6 +371,25 @@ export async function verify(
351371 canWrite: null,
352372 });
353373 }
374 case "ovh": {
375 const o = ovhParts(value);
376 if (!o) return err(OVH_SHAPE);
377 const c = await ovhCall(f, o.keys, "GET", "/auth/currentCredential");
378 let inst: unknown;
outdated

A 404 for a wrong project id falls through to "Could not verify: ... answered 404". Catch it here and say the project was not found for this key.

379 try {
380 inst = await ovhCall(f, o.keys, "GET", `/cloud/project/${o.project}/instance`);
381 } catch (e) {
382 if (e instanceof Error && /answered 404/.test(e.message)) return err("That project id was not found for this key.");
383 throw e;
384 }
385 const writes = ovhCanWrite(c.rules, o.project);
386 const n = Array.isArray(inst) ? inst.length : 0;
387 const path = `/cloud/project/${o.project}/*`;
388 return ok({
389 summary: `OVHcloud US project ${o.project} has ${plural(n, "instance")}; the consumer key ${writes ? `CAN create and delete (POST and DELETE on ${path} are granted)` : `is read-only here (POST and DELETE on ${path} are not both granted)`}.`,
390 canWrite: writes,
391 });
392 }
354393 case "aws": {
355394 const p = parts(value, 2);
356395 if (!p) return err("An AWS credential is ACCESS_KEY_ID:SECRET_ACCESS_KEY.");
@@ -413,7 +452,7 @@ export async function verify(
413452 }
414453 }
415454 } catch (e) {
416 return err(e instanceof Error && /answered 40[13]|answered 400/.test(e.message) ? FAIL : `Could not verify: ${e instanceof Error ? e.message : "failed"}`);
455 return err(e instanceof Error && /answered 40[013]/.test(e.message) ? FAIL : `Could not verify: ${e instanceof Error ? e.message : "failed"}`);
417456 }
418457 }
419458
@@ -508,6 +547,9 @@ export async function audit(
508547 add(`Fly: unattached volume ${v.name} in ${a.name}`, `Volume ${v.name} (${v.sizeGb} GB) of app ${a.name} is attached to no machine.`, v.sizeGb * 0.15);
509548 break;
510549 }
550 case "ovh":
551 // Nothing to audit for cost: the account does not price instances or volumes.
552 break;
511553 case "github":
512554 case "vercel":
513555 // Nothing to audit for cost; the token is only verified.
test/cloud-ovh-flows.test.ts added +93
@@ -0,0 +1,93 @@
1 /** An `ovh` account goes through attach, rotate, rename, allow_writes, audit and remove like hetzner. */
2
3 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
4 import { mkdtemp, rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { createApp, type App } from "../src/app.ts";
8 import { addAccount, allowWrite, auditAccount, net, removeAccount, renameAccount, rotateAccount } from "../src/actions/cloud.ts";
9 import { createRepo } from "../src/actions/repos.ts";
10 import { resetOvhClock } from "../src/cloud/ovh_sign.ts";
11 import { listCloudAccounts } from "../src/core/cloud_account.ts";
12 import { listSecretNames } from "../src/core/secret_store.ts";
13 import { createUser, type User } from "../src/core/users.ts";
14 import { quietLogs } from "./helpers/globals.ts";
15
16 quietLogs();
17
18 const CRED = "ak:secret:ck:abc123";
19 const CRED2 = "ak2:secret2:ck2:abc123";
20 const calls: string[] = [];
21 let project = "abc123";
22
23 net.fetch = async (url) => {
24 calls.push(url);
25 const p = new URL(url).pathname;
26 if (p === "/1.0/auth/time") return new Response(String(Math.floor(Date.now() / 1000)));
27 if (p === "/1.0/auth/currentCredential")
28 return new Response(JSON.stringify({ rules: [{ method: "POST", path: "/cloud/project/abc123/*" }, { method: "DELETE", path: "/cloud/project/abc123/*" }] }));
29 if (p === `/1.0/cloud/project/${project}/instance` && project === "abc123") return new Response(JSON.stringify([{ id: "i1" }]));
30 return new Response("{}", { status: 404 });
31 };
32
33 describe("ovh account flows", () => {
34 let dataDir = "";
35 let app: App;
36 let alice: User;
37
38 beforeAll(async () => {
39 dataDir = await mkdtemp(join(tmpdir(), "forge-ovh-"));
40 app = createApp({ dataDir, port: 0 });
41 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
42 if (!a.ok) throw new Error("user");
43 alice = a.value;
44 const r = await createRepo(app, alice, { name: "ops", visibility: "private" });
45 if (!r.ok) throw new Error("repo");
46 });
47 afterAll(async () => {
48 app.close();
49 await rm(dataDir, { recursive: true, force: true });
50 });
51
52 test("a wrong part count is refused with its reason and no fetch, and nothing is sealed", async () => {
53 calls.length = 0;
54 for (const bad of ["ak:secret:ck", "a:b:c:d:e", "a:b:c:bad/id"]) {
55 const r = await addAccount(app, alice, "ovh", "main", bad);
56 expect(r).toEqual({ ok: false, error: expect.stringContaining("APPLICATION_KEY:APPLICATION_SECRET:CONSUMER_KEY:PROJECT_ID") });
57 }
58 expect(calls).toEqual([]);
59 expect(listCloudAccounts(app.db)).toEqual([]);
60 });
61
62 test("a project id the key cannot see is said in words for a person", async () => {
63 resetOvhClock();
64 project = "nope";
65 const r = await addAccount(app, alice, "ovh", "main", "ak:secret:ck:nope");
66 project = "abc123";
67 expect(r).toEqual({ ok: false, error: "That project id was not found for this key." });
68 });
69
70 test("attach, rotate, rename, allow_writes, audit and remove", async () => {
71 resetOvhClock();
72 const added = await addAccount(app, alice, "ovh", "main", CRED);
73 expect(added.ok && added.value).toContain("OVHcloud US project abc123 has 1 instance");
74 expect(listCloudAccounts(app.db)[0]).toMatchObject({ provider: "ovh", name: "main", writeAllowed: false });
75
76 const rotated = await rotateAccount(app, alice, "ovh", "main", CRED2);
77 expect(rotated.ok).toBe(true);
78
79 expect(renameAccount(app, alice, "ovh", "main", "prod").ok).toBe(true);
80 expect(listCloudAccounts(app.db).map((x) => x.name)).toEqual(["prod"]);
81
82 expect(allowWrite(app, alice, "ovh", "prod", true).ok).toBe(true);
83 expect(listCloudAccounts(app.db)[0]!.writeAllowed).toBe(true);
84 expect(allowWrite(app, alice, "ovh", "prod", false).ok).toBe(true);
85 expect(listCloudAccounts(app.db)[0]!.writeAllowed).toBe(false);
86
87 expect(await auditAccount(app, alice, "ovh", "prod", "alice/ops")).toEqual({ ok: true, value: { opened: 0, found: 0 } });
88
89 expect(removeAccount(app, alice, "ovh", "prod").ok).toBe(true);
90 expect(listCloudAccounts(app.db)).toEqual([]);
91 expect(listSecretNames(app.db, "forge").some((s) => s.name.includes("ovh"))).toBe(false);
92 });
93 });
test/cloud-ovh.test.ts added +75
@@ -0,0 +1,75 @@
1 /** OVHcloud US account: the signature, the rights read from the consumer key's rules, refusals. */
2
3 import { beforeEach, describe, expect, test } from "bun:test";
4 import { verify } from "../src/cloud/providers.ts";
5 import { ovhSignature, resetOvhClock } from "../src/cloud/ovh_sign.ts";
6
7 const CRED = "ak:secret:ck:abc123";
8 const seen: { url: string; method: string; headers: Record<string, string> }[] = [];
9
10 function fake(rules: unknown[], status = 200) {
11 return async (url: string, init?: RequestInit) => {
12 seen.push({ url, method: init?.method ?? "GET", headers: (init?.headers ?? {}) as Record<string, string> });
13 const p = new URL(url).pathname;
14 if (p === "/1.0/auth/time") return new Response(String(Math.floor(Date.now() / 1000) + 5));
15 if (status !== 200) return new Response("{}", { status });
16 if (p === "/1.0/auth/currentCredential") return new Response(JSON.stringify({ status: "validated", rules }));
17 if (p === "/1.0/cloud/project/abc123/instance") return new Response(JSON.stringify([{ id: "i1" }, { id: "i2" }]));
18 return new Response("{}", { status: 404 });
19 };
20 }
21
22 beforeEach(() => {
23 seen.length = 0;
24 resetOvhClock();
25 });
26
27 describe("ovh", () => {
28 test("the signature of a known request is a fixed string", () => {
29 const sig = ovhSignature(
30 { applicationKey: "ak", applicationSecret: "secret", consumerKey: "ck" },
31 "GET", "https://api.us.ovhcloud.com/1.0/auth/currentCredential", "", 1700000000,
32 );
33 expect(sig).toBe("$1$fea6810b9fcedafe9f01b923525dd3ab54fd54ab");
34 });
35
36 test("verify signs both calls and reports write rights when POST and DELETE are granted", async () => {
37 const rules = [{ method: "GET", path: "/cloud/project/abc123/*" }, { method: "POST", path: "/cloud/project/abc123/*" }, { method: "DELETE", path: "/cloud/project/abc123/*" }];
38 const r = await verify("ovh", CRED, fake(rules));
39 expect(r.ok).toBe(true);
40 if (!r.ok) return;
41 expect(r.value.canWrite).toBe(true);
42 expect(r.value.summary).toContain("abc123");
43 expect(r.value.summary).toContain("2 instances");
44 const signed = seen.filter((s) => s.url.includes("/currentCredential") || s.url.endsWith("/instance"));
45 expect(signed.length).toBe(2);
46 for (const s of signed) {
47 expect(s.headers["x-ovh-application"]).toBe("ak");
48 expect(s.headers["x-ovh-consumer"]).toBe("ck");
49 expect(s.headers["x-ovh-signature"]).toMatch(/^\$1\$[0-9a-f]{40}$/);
50 expect(s.url.startsWith("https://api.us.ovhcloud.com/1.0/")).toBe(true);
51 }
52 });
53
54 test("a key without DELETE is read-only, and rules for another project do not count", async () => {
55 const ro = await verify("ovh", CRED, fake([{ method: "GET", path: "/cloud/project/abc123/*" }, { method: "POST", path: "/cloud/project/abc123/*" }]));
56 expect(ro.ok && ro.value.canWrite).toBe(false);
57 resetOvhClock();
58 const other = await verify("ovh", CRED, fake([{ method: "POST", path: "/cloud/project/zzz/*" }, { method: "DELETE", path: "/cloud/project/zzz/*" }]));
59 expect(other.ok && other.value.canWrite).toBe(false);
60 });
61
62 test("a 403 credential is refused in plain words", async () => {
63 const r = await verify("ovh", CRED, fake([], 403));
64 expect(r.ok).toBe(false);
65 if (!r.ok) expect(r.error).toBe("The provider did not accept that credential.");
66 });
67

Test the wrong part count through the cloud API and assert a 422 status, not just verify returning an error. Add attach, rotate, allow_writes and remove coverage for ovh.

68 test("a wrong part count is refused before any fetch", async () => {
69 for (const bad of ["ak:secret:ck", "a:b:c:d:e", "a:b:c:bad/id"]) {
70 const r = await verify("ovh", bad, fake([]));
71 expect(r.ok).toBe(false);
72 }
73 expect(seen.length).toBe(0);
74 });
75 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs