@capsulos/provider-namespace 0.0.0-stage → 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/LICENSE +202 -0
- package/dist/index.d.ts +117 -0
- package/dist/index.js +339 -0
- package/dist/index.js.map +1 -0
- package/dist/registry.d.ts +39 -0
- package/dist/registry.js +96 -0
- package/dist/registry.js.map +1 -0
- package/package.json +56 -3
- package/src/index.ts +400 -0
- package/src/namespace.test.ts +148 -0
- package/src/registry.ts +114 -0
- package/README.md +0 -3
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
// The Namespace provider against a stubbed fetch: what it asks of Namespace
|
|
2
|
+
// for a Linux image and for a macOS one, and how it reads an image from the
|
|
3
|
+
// registry. The service itself is exercised by the conformance suite.
|
|
4
|
+
import { describe, expect, it } from 'vitest';
|
|
5
|
+
import { CapsuleError } from '@capsulos/sdk';
|
|
6
|
+
import { NamespaceProvider, outsideRules, toState } from './index.js';
|
|
7
|
+
|
|
8
|
+
interface Call {
|
|
9
|
+
method: string;
|
|
10
|
+
url: string;
|
|
11
|
+
headers: Record<string, string>;
|
|
12
|
+
body: unknown;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const RPC = 'https://us.compute.namespaceapis.com/namespace.cloud.compute.v1beta.ComputeService';
|
|
16
|
+
const IMAGE = 'nscr.io/ws1/capsulos/base';
|
|
17
|
+
|
|
18
|
+
function stub(image: { os: string; architecture: string; labels?: Record<string, string> } | null, extra: (c: Call) => { status?: number; body?: unknown } | undefined = () => undefined) {
|
|
19
|
+
const calls: Call[] = [];
|
|
20
|
+
const fetchImpl = (async (input: string | URL | Request, init?: RequestInit) => {
|
|
21
|
+
const call: Call = {
|
|
22
|
+
method: init?.method ?? 'GET',
|
|
23
|
+
url: String(input),
|
|
24
|
+
headers: Object.fromEntries(Object.entries((init?.headers ?? {}) as Record<string, string>).map(([k, v]) => [k.toLowerCase(), v])),
|
|
25
|
+
body: init?.body ? JSON.parse(String(init.body)) : undefined,
|
|
26
|
+
};
|
|
27
|
+
calls.push(call);
|
|
28
|
+
const answer = (): { status?: number; body?: unknown; headers?: Record<string, string> } => {
|
|
29
|
+
const more = extra(call);
|
|
30
|
+
if (more) return more;
|
|
31
|
+
if (call.url === 'https://nscr.io/v2/ws1/capsulos/base/manifests/2.0.0') {
|
|
32
|
+
return image ? { body: { config: { digest: 'sha256:cfg' } }, headers: { 'docker-content-digest': 'sha256:man' } } : { status: 404, body: {} };
|
|
33
|
+
}
|
|
34
|
+
if (call.url === 'https://nscr.io/v2/ws1/capsulos/base/blobs/sha256:cfg') return { body: { os: image!.os, architecture: image!.architecture, config: { Labels: image!.labels ?? {} } } };
|
|
35
|
+
if (call.url === `${RPC}/CreateInstance`) return { body: { metadata: { instanceId: 'i1', ingressDomain: 'fra1.namespaced.app', status: 'CREATING' } } };
|
|
36
|
+
if (call.url === `${RPC}/DescribeInstance`) return { body: { metadata: { instanceId: 'i1', ingressDomain: 'fra1.namespaced.app', status: 'RUNNING' } } };
|
|
37
|
+
if (call.url === `${RPC}/DestroyInstance`) return { body: {} };
|
|
38
|
+
if (call.url.startsWith('https://hooks-i1.fra1.namespaced.app/')) return { body: { ok: true } };
|
|
39
|
+
return { status: 404, body: { message: 'not stubbed' } };
|
|
40
|
+
};
|
|
41
|
+
const res = answer();
|
|
42
|
+
return new Response(res.body === undefined ? null : JSON.stringify(res.body), { status: res.status ?? 200, headers: res.headers });
|
|
43
|
+
}) as typeof fetch;
|
|
44
|
+
return { calls, provider: new NamespaceProvider({ token: 'nsc_token', fetch: fetchImpl }) };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const created = (calls: Call[]) => calls.find((c) => c.url === `${RPC}/CreateInstance`)!.body as Record<string, any>;
|
|
48
|
+
|
|
49
|
+
describe('NamespaceProvider.create', () => {
|
|
50
|
+
it('runs a Linux image as a privileged container with the memory its labels ask for', async () => {
|
|
51
|
+
const { calls, provider } = stub({ os: 'linux', architecture: 'amd64', labels: { 'dev.capsulos.memory-mib': '2048' } });
|
|
52
|
+
const handle = await provider.create({ template: IMAGE, templateVersion: '2.0.0', token: 'capsule-token-0123456789', maxDurationSeconds: 600 });
|
|
53
|
+
expect(handle).toMatchObject({ id: 'i1', provider: 'namespace', state: 'running', endpoint: 'https://capsulod-i1.fra1.namespaced.app', templateVersion: '2.0.0' });
|
|
54
|
+
|
|
55
|
+
const body = created(calls);
|
|
56
|
+
// Whole GiB, and at least two per CPU.
|
|
57
|
+
expect(body.shape).toEqual({ virtualCpu: 2, memoryMegabytes: 4096, machineArch: 'amd64', os: 'linux' });
|
|
58
|
+
expect(body.containers).toEqual([
|
|
59
|
+
{
|
|
60
|
+
name: 'capsule',
|
|
61
|
+
imageRef: `${IMAGE}:2.0.0`,
|
|
62
|
+
args: ['capsulod'],
|
|
63
|
+
exportPorts: [
|
|
64
|
+
{ proto: 'HTTP', containerPort: 8080, name: 'capsulod' },
|
|
65
|
+
{ proto: 'HTTP', containerPort: 9000, name: 'hooks' },
|
|
66
|
+
],
|
|
67
|
+
privileged: true,
|
|
68
|
+
},
|
|
69
|
+
]);
|
|
70
|
+
expect(body.applications).toBeUndefined();
|
|
71
|
+
expect(body.networkPolicy).toBeUndefined();
|
|
72
|
+
expect(Date.parse(body.deadline) - Date.now()).toBeGreaterThan(590_000);
|
|
73
|
+
// Nothing of the capsule's token is left in the instance's description.
|
|
74
|
+
expect(JSON.stringify(body)).not.toContain('capsule-token');
|
|
75
|
+
|
|
76
|
+
const hook = calls.find((c) => c.url.endsWith('/run'))!;
|
|
77
|
+
expect(hook.url).toBe('https://hooks-i1.fra1.namespaced.app/aws/lambda-microvms/runtime/v1/run');
|
|
78
|
+
expect(hook.headers['x-nsc-ingress-auth']).toBe('Bearer nsc_token');
|
|
79
|
+
expect(hook.headers.authorization).toBeUndefined();
|
|
80
|
+
expect(await handle.connection.headers()).toEqual({ 'x-nsc-ingress-auth': 'Bearer nsc_token' });
|
|
81
|
+
// The registry is asked with the token as a password, the API with it as a bearer.
|
|
82
|
+
expect(calls[0]!.headers.authorization).toBe(`Basic ${Buffer.from('token:nsc_token').toString('base64')}`);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it('runs a macOS image as an application on the machine, with ingresses instead of container ports', async () => {
|
|
86
|
+
const { calls, provider } = stub({ os: 'darwin', architecture: 'arm64' });
|
|
87
|
+
await provider.create({ template: IMAGE, templateVersion: '2.0.0', token: 'capsule-token-0123456789' });
|
|
88
|
+
const body = created(calls);
|
|
89
|
+
expect(body.shape).toMatchObject({ machineArch: 'arm64', os: 'macos' });
|
|
90
|
+
expect(body.containers).toBeUndefined();
|
|
91
|
+
expect(body.applications).toEqual([{ name: 'capsule', imageRef: `${IMAGE}:2.0.0`, command: './capsulos-boot.sh' }]);
|
|
92
|
+
expect(body.ingresses).toEqual([
|
|
93
|
+
{ name: 'capsulod', mode: 'HTTP', port: 8080 },
|
|
94
|
+
{ name: 'hooks', mode: 'HTTP', port: 9000 },
|
|
95
|
+
]);
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
it('blocks what the allow list does not name when the capsule denies the internet', async () => {
|
|
99
|
+
const { calls, provider } = stub({ os: 'linux', architecture: 'amd64' });
|
|
100
|
+
await provider.create({ template: IMAGE, templateVersion: '2.0.0', token: 'capsule-token-0123456789', network: { internet: 'deny', allow: ['api.example.com:443'] } });
|
|
101
|
+
expect(created(calls).networkPolicy).toEqual({ egress: { mode: 'BLOCK', rules: [{ op: 'ALLOW', matcher: { matchDomains: ['api.example.com', 'nscr.io', '*.nscr.io', '*.namespaceblobs.com'] }, allow: {} }] } });
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
it('destroys an instance that ended in error, and names it', async () => {
|
|
105
|
+
const { calls, provider } = stub({ os: 'linux', architecture: 'amd64' }, (c) =>
|
|
106
|
+
c.url === `${RPC}/DescribeInstance` ? { body: { metadata: { instanceId: 'i1', status: 'ERROR' }, shutdownReasons: [{ message: 'image not found' }] } } : undefined,
|
|
107
|
+
);
|
|
108
|
+
const err = await provider.create({ template: IMAGE, templateVersion: '2.0.0', token: 'capsule-token-0123456789' }).catch((e: unknown) => e);
|
|
109
|
+
expect(err).toBeInstanceOf(CapsuleError);
|
|
110
|
+
expect((err as CapsuleError).message).toMatch(/image not found.*terminated instance i1/);
|
|
111
|
+
expect(calls.some((c) => c.url === `${RPC}/DestroyInstance`)).toBe(true);
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
it('an image the registry does not have is taken as Linux with the default memory', async () => {
|
|
115
|
+
const { calls, provider } = stub(null);
|
|
116
|
+
await provider.create({ template: IMAGE, templateVersion: '2.0.0', token: 'capsule-token-0123456789' });
|
|
117
|
+
expect(created(calls).shape).toEqual({ virtualCpu: 2, memoryMegabytes: 4096, machineArch: 'amd64', os: 'linux' });
|
|
118
|
+
});
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
describe('Registry', () => {
|
|
122
|
+
it('follows an index to the image and reads its labels', async () => {
|
|
123
|
+
const { provider } = stub(null, (c) => {
|
|
124
|
+
if (c.url.endsWith('/manifests/1.0.0')) return { body: { manifests: [{ digest: 'sha256:att', platform: { os: 'unknown', architecture: 'unknown' } }, { digest: 'sha256:img', platform: { os: 'linux', architecture: 'arm64' } }] } };
|
|
125
|
+
if (c.url.endsWith('/manifests/sha256:img')) return { body: { config: { digest: 'sha256:c2' } } };
|
|
126
|
+
if (c.url.endsWith('/blobs/sha256:c2')) return { body: { os: 'linux', architecture: 'arm64', created: '2026-11-17T00:00:00Z', config: { Labels: { a: 'b' } } } };
|
|
127
|
+
if (c.url.endsWith('/x/tags/list?n=1000')) return { body: { name: 'ws1/capsulos/x', tags: ['1.0.0', 'latest'] } };
|
|
128
|
+
return undefined;
|
|
129
|
+
});
|
|
130
|
+
const registry = provider.registry();
|
|
131
|
+
expect(await registry.tags('ws1/capsulos/x')).toEqual(['1.0.0', 'latest']);
|
|
132
|
+
expect((await registry.image('ws1/capsulos/x', '1.0.0'))?.config).toEqual({ os: 'linux', architecture: 'arm64', created: '2026-11-17T00:00:00Z', labels: { a: 'b' } });
|
|
133
|
+
expect(await registry.tags('ws1/capsulos/none')).toEqual([]);
|
|
134
|
+
});
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
describe('states and rules', () => {
|
|
138
|
+
it('maps Namespace states', () => {
|
|
139
|
+
expect(toState('RUNNING')).toBe('running');
|
|
140
|
+
expect(toState('CREATING')).toBe('pending');
|
|
141
|
+
expect(toState('DESTROYED')).toBe('terminated');
|
|
142
|
+
});
|
|
143
|
+
it('an empty allow list blocks everything but the registry the machine pulls its image from', () => {
|
|
144
|
+
expect(outsideRules([])).toEqual([]);
|
|
145
|
+
expect(outsideRules([], 'nscr.io')).toEqual([{ op: 'ALLOW', matcher: { matchDomains: ['nscr.io', '*.nscr.io', '*.namespaceblobs.com'] }, allow: {} }]);
|
|
146
|
+
expect(outsideRules(['api.github.com:443'], 'ghcr.io')[0]!.matcher.matchDomains).toEqual(['api.github.com', 'ghcr.io']);
|
|
147
|
+
});
|
|
148
|
+
});
|
package/src/registry.ts
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
// The workspace's image registry (nscr.io), spoken to with the plain OCI
|
|
2
|
+
// distribution API: a template version is an image there, and what capsulos
|
|
3
|
+
// needs to know about it (which declaration it is, how much memory it asks
|
|
4
|
+
// for, which system it runs on) is in the image's own configuration.
|
|
5
|
+
import { createHash } from 'node:crypto';
|
|
6
|
+
import { CapsuleError } from '@capsulos/sdk';
|
|
7
|
+
|
|
8
|
+
export interface ImageConfig {
|
|
9
|
+
os: string;
|
|
10
|
+
architecture: string;
|
|
11
|
+
created?: string;
|
|
12
|
+
labels: Record<string, string>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface RegistryOptions {
|
|
16
|
+
/** The registry's host (default nscr.io). */
|
|
17
|
+
host?: string;
|
|
18
|
+
/** A token of the workspace that may use the registry: sent as the password of the user `token`. */
|
|
19
|
+
token?: string;
|
|
20
|
+
/** A user and password instead (what `nsc docker login` left in Docker's configuration). */
|
|
21
|
+
basic?: { username: string; password: string };
|
|
22
|
+
fetch?: typeof fetch;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const ACCEPT = [
|
|
26
|
+
'application/vnd.oci.image.index.v1+json',
|
|
27
|
+
'application/vnd.docker.distribution.manifest.list.v2+json',
|
|
28
|
+
'application/vnd.oci.image.manifest.v1+json',
|
|
29
|
+
'application/vnd.docker.distribution.manifest.v2+json',
|
|
30
|
+
].join(', ');
|
|
31
|
+
|
|
32
|
+
interface Manifest {
|
|
33
|
+
config?: { digest: string };
|
|
34
|
+
manifests?: Array<{ digest: string; platform?: { os?: string; architecture?: string } }>;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export class Registry {
|
|
38
|
+
readonly host: string;
|
|
39
|
+
private readonly auth: string;
|
|
40
|
+
private readonly fetchImpl: typeof fetch;
|
|
41
|
+
|
|
42
|
+
constructor(opts: RegistryOptions) {
|
|
43
|
+
this.host = opts.host ?? 'nscr.io';
|
|
44
|
+
// The registry takes a workspace token as the password of the user `token`.
|
|
45
|
+
const { username, password } = opts.basic ?? { username: 'token', password: opts.token ?? '' };
|
|
46
|
+
this.auth = `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`;
|
|
47
|
+
this.fetchImpl = opts.fetch ?? fetch;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
private async call(method: string, path: string, accept?: string): Promise<Response> {
|
|
51
|
+
try {
|
|
52
|
+
return await this.fetchImpl(`https://${this.host}/v2/${path}`, {
|
|
53
|
+
method,
|
|
54
|
+
headers: { authorization: this.auth, ...(accept ? { accept } : {}) },
|
|
55
|
+
signal: AbortSignal.timeout(60_000),
|
|
56
|
+
});
|
|
57
|
+
} catch (err) {
|
|
58
|
+
throw new CapsuleError(`registry ${this.host} ${method} ${path}: ${err instanceof Error ? err.message : String(err)}`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The tags of a repository (`<workspace>/capsulos/<name>`); none when it does not exist. */
|
|
63
|
+
async tags(repository: string): Promise<string[]> {
|
|
64
|
+
const out: string[] = [];
|
|
65
|
+
let path: string | null = `${repository}/tags/list?n=1000`;
|
|
66
|
+
while (path) {
|
|
67
|
+
const res: Response = await this.call('GET', path);
|
|
68
|
+
if (res.status === 404) return out;
|
|
69
|
+
if (!res.ok) throw new CapsuleError(`registry ${this.host}: listing the tags of ${repository}: ${res.status} ${(await res.text()).slice(0, 200)}`, res.status);
|
|
70
|
+
out.push(...(((await res.json()) as { tags?: string[] | null }).tags ?? []));
|
|
71
|
+
const next = /<([^>]+)>;\s*rel="next"/.exec(res.headers.get('link') ?? '')?.[1];
|
|
72
|
+
path = next ? next.replace(/^\/v2\//, '') : null;
|
|
73
|
+
}
|
|
74
|
+
return out;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** The digest a tag names, and the image's configuration; null when the registry has no such image. */
|
|
78
|
+
async image(repository: string, reference: string): Promise<{ digest: string; config: ImageConfig } | null> {
|
|
79
|
+
let res = await this.call('GET', `${repository}/manifests/${reference}`, ACCEPT);
|
|
80
|
+
if (res.status === 404) return null;
|
|
81
|
+
if (!res.ok) throw new CapsuleError(`registry ${this.host}: ${repository}:${reference}: ${res.status} ${(await res.text()).slice(0, 200)}`, res.status);
|
|
82
|
+
// The digest of a manifest is the hash of its bytes: a registry that does not say it in a header (nscr.io on GET) still has it.
|
|
83
|
+
const body = Buffer.from(await res.arrayBuffer());
|
|
84
|
+
const digest = res.headers.get('docker-content-digest') || `sha256:${createHash('sha256').update(body).digest('hex')}`;
|
|
85
|
+
let manifest = JSON.parse(body.toString('utf8')) as Manifest;
|
|
86
|
+
if (manifest.manifests?.length) {
|
|
87
|
+
// An index (docker buildx adds an attestation next to the image): the image is the entry with a real platform.
|
|
88
|
+
const entry = manifest.manifests.find((m) => m.platform?.os && m.platform.os !== 'unknown') ?? manifest.manifests[0]!;
|
|
89
|
+
res = await this.call('GET', `${repository}/manifests/${entry.digest}`, ACCEPT);
|
|
90
|
+
if (!res.ok) return null;
|
|
91
|
+
manifest = (await res.json()) as Manifest;
|
|
92
|
+
}
|
|
93
|
+
if (!manifest.config?.digest) return null;
|
|
94
|
+
const blob = await this.call('GET', `${repository}/blobs/${manifest.config.digest}`);
|
|
95
|
+
if (!blob.ok) return null;
|
|
96
|
+
const cfg = (await blob.json()) as { os?: string; architecture?: string; created?: string; config?: { Labels?: Record<string, string> | null } };
|
|
97
|
+
return { digest, config: { os: cfg.os ?? 'linux', architecture: cfg.architecture ?? 'amd64', ...(cfg.created ? { created: cfg.created } : {}), labels: cfg.config?.Labels ?? {} } };
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Remove what a tag names (the registry deletes by digest). */
|
|
101
|
+
async remove(repository: string, reference: string): Promise<void> {
|
|
102
|
+
const found = await this.image(repository, reference);
|
|
103
|
+
if (!found?.digest) return;
|
|
104
|
+
const res = await this.call('DELETE', `${repository}/manifests/${found.digest}`);
|
|
105
|
+
if (!res.ok && res.status !== 404) throw new CapsuleError(`registry ${this.host}: removing ${repository}:${reference}: ${res.status} ${(await res.text()).slice(0, 200)}`, res.status);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** `nscr.io/<workspace>/capsulos/<name>` → its registry host and repository. */
|
|
110
|
+
export function splitImage(ref: string): { host: string; repository: string } {
|
|
111
|
+
const slash = ref.indexOf('/');
|
|
112
|
+
if (slash < 0) throw new CapsuleError(`${ref} is not an image of a registry: it names no host`);
|
|
113
|
+
return { host: ref.slice(0, slash), repository: ref.slice(slash + 1) };
|
|
114
|
+
}
|
package/README.md
DELETED