@ptkl/toolkit 1.4.3 → 1.5.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/README.md +14 -1
- package/dist/commands/__tests__/capabilities.test.js +83 -0
- package/dist/commands/__tests__/componentRunAs.test.js +65 -0
- package/dist/commands/__tests__/forge-bundle-layout.test.js +46 -0
- package/dist/commands/__tests__/forge-bundle-path.test.js +29 -0
- package/dist/commands/__tests__/forge-variables.test.js +16 -0
- package/dist/commands/__tests__/role.test.js +83 -0
- package/dist/commands/__tests__/runAs.test.js +63 -0
- package/dist/commands/__tests__/thunder.test.js +46 -0
- package/dist/commands/component.js +9 -3
- package/dist/commands/forge.js +106 -135
- package/dist/commands/functions.js +11 -5
- package/dist/commands/integrations/payments.js +11 -7
- package/dist/commands/project.js +0 -8
- package/dist/commands/role.js +45 -54
- package/dist/commands/satellite.js +0 -5
- package/dist/commands/template.js +7 -13
- package/dist/commands/thunder.js +19 -12
- package/dist/commands/workflow.js +10 -4
- package/dist/lib/__tests__/apiError.test.js +14 -0
- package/dist/lib/__tests__/apiErrorCapabilities.test.js +23 -0
- package/dist/lib/__tests__/forgeDevKernelPlugin.test.js +34 -0
- package/dist/lib/__tests__/forgeDevServiceExec.test.js +61 -0
- package/dist/lib/__tests__/forgeDevServiceServer.test.js +113 -0
- package/dist/lib/__tests__/forgeDevToken.test.js +85 -0
- package/dist/lib/__tests__/runIdentity.test.js +101 -0
- package/dist/lib/__tests__/thunder.test.js +101 -0
- package/dist/lib/apiError.js +83 -1
- package/dist/lib/forgeDevKernelPlugin.js +90 -4
- package/dist/lib/forgeDevServiceExec.js +49 -0
- package/dist/lib/forgeDevServiceServer.js +163 -0
- package/dist/lib/forgeDevToken.js +126 -0
- package/dist/lib/oauth/ScopePreset.js +4 -3
- package/dist/lib/oauth/__tests__/oauth.test.js +6 -3
- package/dist/lib/runIdentity.js +51 -0
- package/dist/lib/thunder.js +98 -0
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -117,7 +117,7 @@ If OAuth is not enabled on the host the command fails with a pointer to `--legac
|
|
|
117
117
|
|
|
118
118
|
**Legacy and CI.** `--legacy` (implied by `-u`, `-p` or `-t`) logs in as an API user (`/v1/user/api/auth`) or takes a token directly, e.g. `ptkl profile auth -t $TOKEN`. For CI use API-user tokens with `--legacy -t`.
|
|
119
119
|
|
|
120
|
-
Default scope is a least-privilege toolkit preset (`src/lib/oauth/ScopePreset.ts`), further limited by your own permissions in the project: apps, functions, components, templates, thunder, ratchet (read/inspect), users and roles (list), API users (`edit base_users` for list/get/edit/revoke-secret, `
|
|
120
|
+
Default scope is a least-privilege toolkit preset (`src/lib/oauth/ScopePreset.ts`), further limited by your own permissions in the project: apps, functions, components, templates, thunder, ratchet (read/inspect), users and roles (list), API users (`edit base_users` for list/get/edit/revoke-secret, `credentials::manage base_users` for new/new-secret), and `dev env_access` (non-live environments need `<env> env_access`; `dev` is the default — add others with `--add-scope "<env> env_access"`). Scope never grows by itself: re-run `ptkl profile auth` after creating resources whose per-resource permissions you need.
|
|
121
121
|
|
|
122
122
|
Access tokens (15 min) refresh transparently when a command starts, serialized across processes by a per-profile lock in `~/.ptkl` (the rotated refresh token is saved); long-running commands such as watch modes refresh only at start. If the session expired or was revoked you are asked to log in again. `profile inspect` masks tokens.
|
|
123
123
|
|
|
@@ -131,6 +131,19 @@ You can override the active profile for any command using the global `--profile`
|
|
|
131
131
|
ptkl --profile production apps upload -a app -d ./my-app
|
|
132
132
|
```
|
|
133
133
|
|
|
134
|
+
## Run identity and code capabilities
|
|
135
|
+
|
|
136
|
+
Functions, components and workflows run as a run identity. `--run-as <prn>` sets it on create and changes it on update.
|
|
137
|
+
|
|
138
|
+
Capabilities are declared per unit, inside the JSON you already send, not with flags:
|
|
139
|
+
|
|
140
|
+
- a component function: `capabilities` on the function object in `settings.functions[]` (`component update-settings`);
|
|
141
|
+
- an expression node: `data.capabilities` on the node in a workflow graph or a component's `settings.events` (`workflow create|update|install`, `component update-settings`).
|
|
142
|
+
|
|
143
|
+
Absent or `null` means none declared; an array declares exactly those permissions (`[]` = none at all). Writes are whole, so leaving the field out clears it. `get` output returns the API data unchanged.
|
|
144
|
+
|
|
145
|
+
If the API refuses a write, the message names the unit (`function:<name>` or `node:<id>`) and capability: `capability_invalid` (unit, capability), `capability_not_held` (unit, capability) and `capability_not_held_by_identity` (unit, capability, run as).
|
|
146
|
+
|
|
134
147
|
## Forge
|
|
135
148
|
|
|
136
149
|
Commands for building and running Protokol Forge apps locally.
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
const post = vi.fn(async (_url, _body) => ({ data: { ok: true } }));
|
|
3
|
+
const fnUpdate = vi.fn(async (_id, _body) => ({ data: { ok: true } }));
|
|
4
|
+
const fnGet = vi.fn();
|
|
5
|
+
const wfCreate = vi.fn(async (_body) => ({ data: { ok: true } }));
|
|
6
|
+
const wfUpdate = vi.fn(async (_id, _body) => ({ data: { ok: true } }));
|
|
7
|
+
const wfInstall = vi.fn(async (_body) => ({ data: { ok: true } }));
|
|
8
|
+
const wfGet = vi.fn();
|
|
9
|
+
vi.mock('../../lib/sdk.js', () => ({
|
|
10
|
+
platform: () => ({
|
|
11
|
+
function: () => ({ client: { post, get: vi.fn() }, update: fnUpdate, get: fnGet }),
|
|
12
|
+
getPlatformClient: () => ({ post, get: vi.fn() }),
|
|
13
|
+
}),
|
|
14
|
+
workflow: () => ({ create: wfCreate, update: wfUpdate, install: wfInstall, get: wfGet }),
|
|
15
|
+
}));
|
|
16
|
+
vi.mock('../../lib/util.js', () => ({
|
|
17
|
+
default: { getCurrentProfile: () => ({ host: 'h', token: 't', project: 'p' }) },
|
|
18
|
+
}));
|
|
19
|
+
import functions from '../functions.js';
|
|
20
|
+
import workflow from '../workflow.js';
|
|
21
|
+
const fn = (...a) => functions.register().parseAsync(['node', 'functions', ...a]);
|
|
22
|
+
const wf = (...a) => workflow.register().parseAsync(['node', 'workflow', ...a]);
|
|
23
|
+
let errors;
|
|
24
|
+
let logs;
|
|
25
|
+
beforeEach(() => {
|
|
26
|
+
vi.clearAllMocks();
|
|
27
|
+
errors = [];
|
|
28
|
+
logs = [];
|
|
29
|
+
vi.spyOn(console, 'error').mockImplementation((m) => { errors.push(String(m)); });
|
|
30
|
+
vi.spyOn(console, 'log').mockImplementation((m) => { logs.push(m); });
|
|
31
|
+
vi.spyOn(process, 'exit').mockImplementation(((c) => { throw new Error(`exit ${c}`); }));
|
|
32
|
+
});
|
|
33
|
+
describe('capabilities flags are gone', () => {
|
|
34
|
+
it('function create/update reject --capabilities and --clear-capabilities', async () => {
|
|
35
|
+
for (const flag of ['--capabilities', '--clear-capabilities']) {
|
|
36
|
+
await expect(fn('update', 'u1', '-d', '{}', flag, ...(flag === '--capabilities' ? ['a'] : []))).rejects.toThrow();
|
|
37
|
+
}
|
|
38
|
+
expect(fnUpdate).not.toHaveBeenCalled();
|
|
39
|
+
});
|
|
40
|
+
it('workflow create/update/install reject the flags', async () => {
|
|
41
|
+
for (const sub of [['create'], ['update', 'w1'], ['install']]) {
|
|
42
|
+
await expect(wf(...sub, '-d', '{}', '--capabilities', 'a')).rejects.toThrow();
|
|
43
|
+
await expect(wf(...sub, '-d', '{}', '--clear-capabilities')).rejects.toThrow();
|
|
44
|
+
}
|
|
45
|
+
expect(wfCreate).not.toHaveBeenCalled();
|
|
46
|
+
expect(wfUpdate).not.toHaveBeenCalled();
|
|
47
|
+
expect(wfInstall).not.toHaveBeenCalled();
|
|
48
|
+
});
|
|
49
|
+
it('payloads are sent unchanged, capabilities inside settings and graph included', async () => {
|
|
50
|
+
const body = { name: 'f', settings: { functions: [{ name: 'a', expr: '1', capabilities: ['read x y'] }] } };
|
|
51
|
+
await fn('update', 'u1', '-d', JSON.stringify(body));
|
|
52
|
+
expect(fnUpdate).toHaveBeenLastCalledWith('u1', body);
|
|
53
|
+
const graph = { name: 'w', nodes: [{ id: 'n1', data: { capabilities: [] } }] };
|
|
54
|
+
await wf('update', 'w1', '-d', JSON.stringify(graph));
|
|
55
|
+
expect(wfUpdate).toHaveBeenLastCalledWith('w1', graph);
|
|
56
|
+
});
|
|
57
|
+
it('get output is the API data, with no capabilities label', async () => {
|
|
58
|
+
fnGet.mockResolvedValueOnce({ data: { name: 'f' } });
|
|
59
|
+
await fn('get', 'f');
|
|
60
|
+
expect(logs[0]).toEqual({ name: 'f' });
|
|
61
|
+
wfGet.mockResolvedValueOnce({ data: { name: 'w' } });
|
|
62
|
+
await wf('get', '-r', 'w');
|
|
63
|
+
expect(logs[1]).toEqual({ name: 'w' });
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
describe('refusals print unit and capability', () => {
|
|
67
|
+
it('capability_not_held', async () => {
|
|
68
|
+
fnUpdate.mockRejectedValueOnce({ response: { status: 403, data: { error: 'capability_not_held', unit: 'function:f', capability: 'secrets::read global_env', message: 'you do not hold it' } } });
|
|
69
|
+
await expect(fn('update', 'u1', '-d', '{}')).rejects.toThrow('exit 1');
|
|
70
|
+
const out = errors.join('\n');
|
|
71
|
+
expect(out).toContain('you do not hold it');
|
|
72
|
+
expect(out).toContain('unit: function:f');
|
|
73
|
+
expect(out).toContain('capability: secrets::read global_env');
|
|
74
|
+
});
|
|
75
|
+
it('capability_not_held_by_identity', async () => {
|
|
76
|
+
wfInstall.mockRejectedValueOnce({ response: { status: 403, data: { error: 'capability_not_held_by_identity', unit: 'node:n1', capability: 'x::y z', run_as: 'prn:role:1', message: 'identity lacks it' } } });
|
|
77
|
+
await expect(wf('install', '-d', '{}')).rejects.toThrow('exit 1');
|
|
78
|
+
const out = errors.join('\n');
|
|
79
|
+
expect(out).toContain('unit: node:n1');
|
|
80
|
+
expect(out).toContain('capability: x::y z');
|
|
81
|
+
expect(out).toContain('run as: prn:role:1');
|
|
82
|
+
});
|
|
83
|
+
});
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
const post = vi.fn(async (_url, _body) => ({ data: { ok: true } }));
|
|
3
|
+
const get = vi.fn();
|
|
4
|
+
const ask = vi.fn();
|
|
5
|
+
vi.mock('@ptkl/sdk', () => ({
|
|
6
|
+
Platform: class {
|
|
7
|
+
getPlatformClient() { return { post, get }; }
|
|
8
|
+
},
|
|
9
|
+
}));
|
|
10
|
+
vi.mock('../../lib/util.js', () => ({
|
|
11
|
+
default: { getCurrentProfile: () => ({ host: 'h', token: 't', project: 'p' }) },
|
|
12
|
+
}));
|
|
13
|
+
vi.mock('../../lib/runIdentity.js', async (orig) => {
|
|
14
|
+
const mod = await orig();
|
|
15
|
+
const Real = mod.default;
|
|
16
|
+
return { ...mod, default: class extends Real {
|
|
17
|
+
constructor(http, interactive) { super(http, interactive, ask); }
|
|
18
|
+
} };
|
|
19
|
+
});
|
|
20
|
+
import component from '../component.js';
|
|
21
|
+
const run = (...args) => component.register().parseAsync(['node', 'component', ...args]);
|
|
22
|
+
const URL = '/v3/system/component/create';
|
|
23
|
+
describe('component create --run-as', () => {
|
|
24
|
+
const saved = [process.stdin.isTTY, process.stdout.isTTY];
|
|
25
|
+
const setTty = (v) => {
|
|
26
|
+
Object.defineProperty(process.stdin, 'isTTY', { value: v, configurable: true });
|
|
27
|
+
Object.defineProperty(process.stdout, 'isTTY', { value: v, configurable: true });
|
|
28
|
+
};
|
|
29
|
+
afterEach(() => {
|
|
30
|
+
Object.defineProperty(process.stdin, 'isTTY', { value: saved[0], configurable: true });
|
|
31
|
+
Object.defineProperty(process.stdout, 'isTTY', { value: saved[1], configurable: true });
|
|
32
|
+
});
|
|
33
|
+
beforeEach(() => {
|
|
34
|
+
setTty(false);
|
|
35
|
+
ask.mockReset();
|
|
36
|
+
post.mockClear();
|
|
37
|
+
get.mockReset();
|
|
38
|
+
});
|
|
39
|
+
it('sends --run-as with flag-built payload', async () => {
|
|
40
|
+
await run('create', '-n', 'N', '-t', 'tag', '--run-as', 'prn:role:1');
|
|
41
|
+
expect(post).toHaveBeenCalledWith(URL, expect.objectContaining({ name: 'N', tag: 'tag', run_as: 'prn:role:1' }));
|
|
42
|
+
});
|
|
43
|
+
it('sends --run-as with a --data payload', async () => {
|
|
44
|
+
await run('create', '-n', 'N', '-t', 'tag', '-d', '{"name":"c","tag":"t"}', '--run-as', 'prn:role:1');
|
|
45
|
+
expect(post).toHaveBeenCalledWith(URL, { name: 'c', tag: 't', run_as: 'prn:role:1' });
|
|
46
|
+
});
|
|
47
|
+
it('keeps run_as from a --data payload when no flag and no tty', async () => {
|
|
48
|
+
await run('create', '-n', 'N', '-t', 'tag', '-d', '{"name":"c","run_as":"prn:role:9"}');
|
|
49
|
+
expect(post).toHaveBeenCalledWith(URL, { name: 'c', run_as: 'prn:role:9' });
|
|
50
|
+
});
|
|
51
|
+
it('without flag or tty sends no run_as and does not fetch choices', async () => {
|
|
52
|
+
await run('create', '-n', 'N', '-t', 'tag');
|
|
53
|
+
const body = post.mock.calls[0][1];
|
|
54
|
+
expect(body).not.toHaveProperty('run_as');
|
|
55
|
+
expect(get).not.toHaveBeenCalled();
|
|
56
|
+
});
|
|
57
|
+
it('with a tty sends the picked identity', async () => {
|
|
58
|
+
setTty(true);
|
|
59
|
+
get.mockResolvedValue({ data: { identities: [{ prn: 'prn:role:1', kind: 'role', name: 'Editors' }] } });
|
|
60
|
+
ask.mockResolvedValue('prn:role:1');
|
|
61
|
+
await run('create', '-n', 'N', '-t', 'tag');
|
|
62
|
+
expect(get).toHaveBeenCalledWith('/v1/system/run-identity/choices');
|
|
63
|
+
expect(post).toHaveBeenCalledWith(URL, expect.objectContaining({ run_as: 'prn:role:1' }));
|
|
64
|
+
});
|
|
65
|
+
});
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { cpSync, existsSync, mkdtempSync, readFileSync } from 'fs';
|
|
2
|
+
import { tmpdir } from 'os';
|
|
3
|
+
import { dirname, join } from 'path';
|
|
4
|
+
import { fileURLToPath } from 'url';
|
|
5
|
+
import { beforeAll, describe, expect, it } from 'vitest';
|
|
6
|
+
import forgeCommand, { bundleFilePath } from '../forge.js';
|
|
7
|
+
// A real `forge bundle` of a fixture app, because what a bundle writes and what its manifest
|
|
8
|
+
// declares have to agree and only a build can show that. Both halves broke once: the manifest
|
|
9
|
+
// named a script the build did not emit, and `forge install` read a folder the build no longer
|
|
10
|
+
// wrote to.
|
|
11
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
12
|
+
let app;
|
|
13
|
+
let manifest;
|
|
14
|
+
describe('forge bundle', () => {
|
|
15
|
+
beforeAll(async () => {
|
|
16
|
+
app = join(mkdtempSync(join(tmpdir(), 'ptkl-bundle-')), 'app');
|
|
17
|
+
cpSync(join(here, '__fixtures__', 'bundleApp'), app, { recursive: true });
|
|
18
|
+
const cwd = process.cwd();
|
|
19
|
+
try {
|
|
20
|
+
await forgeCommand.bundle({ path: app, upload: false });
|
|
21
|
+
}
|
|
22
|
+
finally {
|
|
23
|
+
process.chdir(cwd);
|
|
24
|
+
}
|
|
25
|
+
manifest = JSON.parse(readFileSync(join(app, 'dist', 'manifest.json'), 'utf-8'));
|
|
26
|
+
}, 120_000);
|
|
27
|
+
it('splits browser files from server files, and says so in the manifest', () => {
|
|
28
|
+
expect(manifest.layout).toBe(2);
|
|
29
|
+
expect(existsSync(join(app, 'dist', 'browser', 'main.bundle.js'))).toBe(true);
|
|
30
|
+
expect(existsSync(join(app, 'dist', 'server', 'services', 'svc.js'))).toBe(true);
|
|
31
|
+
expect(existsSync(join(app, 'dist', 'server', 'install.script.js'))).toBe(true);
|
|
32
|
+
});
|
|
33
|
+
it('names a lifecycle script after its manifest key, not its entry file', () => {
|
|
34
|
+
// The fixture's install entry is src/setup.js. Naming the output after the entry emitted
|
|
35
|
+
// setup.script.js under a manifest declaring install.script.js: appservice refused the
|
|
36
|
+
// upload and `forge install` could not find it.
|
|
37
|
+
expect(manifest.scripts).toEqual({ install: 'install.script.js' });
|
|
38
|
+
expect(existsSync(join(app, 'dist', 'server', 'setup.script.js'))).toBe(false);
|
|
39
|
+
});
|
|
40
|
+
it('declares every file where the reader looks for it', () => {
|
|
41
|
+
const at = (kind, p) => bundleFilePath(join(app, 'dist'), kind, p);
|
|
42
|
+
expect(existsSync(at('server', manifest.scripts.install))).toBe(true);
|
|
43
|
+
expect(existsSync(at('server', manifest.services[0].script))).toBe(true);
|
|
44
|
+
expect(existsSync(at('browser', manifest.views.main))).toBe(true);
|
|
45
|
+
});
|
|
46
|
+
});
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { mkdtempSync, mkdirSync, writeFileSync } from 'fs';
|
|
2
|
+
import { tmpdir } from 'os';
|
|
3
|
+
import { join } from 'path';
|
|
4
|
+
import { describe, expect, it } from 'vitest';
|
|
5
|
+
import { bundleFilePath } from '../forge.js';
|
|
6
|
+
const dist = (manifest) => {
|
|
7
|
+
const dir = mkdtempSync(join(tmpdir(), 'ptkl-dist-'));
|
|
8
|
+
mkdirSync(join(dir, 'server'), { recursive: true });
|
|
9
|
+
if (manifest !== undefined)
|
|
10
|
+
writeFileSync(join(dir, 'manifest.json'), JSON.stringify(manifest));
|
|
11
|
+
return dir;
|
|
12
|
+
};
|
|
13
|
+
describe('bundleFilePath', () => {
|
|
14
|
+
it('reads a layout 2 bundle out of its kind folder, where bundle writes it', () => {
|
|
15
|
+
const dir = dist({ layout: 2 });
|
|
16
|
+
expect(bundleFilePath(dir, 'server', 'install.script.js')).toBe(join(dir, 'server', 'install.script.js'));
|
|
17
|
+
expect(bundleFilePath(dir, 'browser', 'index.js')).toBe(join(dir, 'browser', 'index.js'));
|
|
18
|
+
});
|
|
19
|
+
it('reads an older flat bundle from the root', () => {
|
|
20
|
+
const dir = dist({ name: 'app' });
|
|
21
|
+
expect(bundleFilePath(dir, 'server', 'install.script.js')).toBe(join(dir, 'install.script.js'));
|
|
22
|
+
});
|
|
23
|
+
it('falls back to flat when nothing is built, so the caller reports the missing file', () => {
|
|
24
|
+
const dir = dist();
|
|
25
|
+
expect(bundleFilePath(dir, 'server', 'install.script.js')).toBe(join(dir, 'install.script.js'));
|
|
26
|
+
writeFileSync(join(dir, 'manifest.json'), 'not json');
|
|
27
|
+
expect(bundleFilePath(dir, 'server', 'install.script.js')).toBe(join(dir, 'install.script.js'));
|
|
28
|
+
});
|
|
29
|
+
});
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { assertVariablesAreDefaults } from '../forge.js';
|
|
3
|
+
describe('assertVariablesAreDefaults', () => {
|
|
4
|
+
it('accepts an absent block, plain values and secretgen::', () => {
|
|
5
|
+
expect(() => assertVariablesAreDefaults(undefined)).not.toThrow();
|
|
6
|
+
expect(() => assertVariablesAreDefaults({ dev: { A: '1', N: { G: 'secretgen::random(32)' } }, live: {} })).not.toThrow();
|
|
7
|
+
});
|
|
8
|
+
it('refuses a secret:: value naming the key', () => {
|
|
9
|
+
expect(() => assertVariablesAreDefaults({ dev: { N: { K: 'secret::abcdefgh12' } } })).toThrow(/variables\.dev\.N\.K/);
|
|
10
|
+
expect(() => assertVariablesAreDefaults({ live: { K: 'secretref::' } })).toThrow(/variables\.live\.K/);
|
|
11
|
+
});
|
|
12
|
+
it('refuses an unknown environment or a non-object', () => {
|
|
13
|
+
expect(() => assertVariablesAreDefaults({ prod: {} })).toThrow(/unknown environment/);
|
|
14
|
+
expect(() => assertVariablesAreDefaults('x')).toThrow(/must be an object/);
|
|
15
|
+
});
|
|
16
|
+
});
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { beforeEach, describe, expect, it, vi } from "vitest";
|
|
2
|
+
import { Command } from "commander";
|
|
3
|
+
// The role command is a thin wrapper over the SDK `Users` client; these tests pin the wiring that
|
|
4
|
+
// broke in core/toolkit#10 (`role()` does not exist on the Platform client) and keep
|
|
5
|
+
// `permissions-list` from calling the roles list endpoint.
|
|
6
|
+
const mocks = vi.hoisted(() => {
|
|
7
|
+
const calls = [];
|
|
8
|
+
const record = (method) => async (...args) => {
|
|
9
|
+
calls.push({ method, args });
|
|
10
|
+
return { data: { method, args } };
|
|
11
|
+
};
|
|
12
|
+
const users = {
|
|
13
|
+
createRole: record("createRole"),
|
|
14
|
+
listRoles: record("listRoles"),
|
|
15
|
+
listPermissions: record("listPermissions"),
|
|
16
|
+
editRole: record("editRole"),
|
|
17
|
+
deleteRole: record("deleteRole"),
|
|
18
|
+
};
|
|
19
|
+
return { calls, users, platform: { user: () => users } };
|
|
20
|
+
});
|
|
21
|
+
vi.mock("../../lib/sdk.js", () => ({ platform: () => mocks.platform }));
|
|
22
|
+
vi.mock("../../lib/util.js", () => ({
|
|
23
|
+
default: {
|
|
24
|
+
getCurrentProfile: () => ({ name: "test", host: "http://platform.test", token: "t", project: "p" }),
|
|
25
|
+
},
|
|
26
|
+
}));
|
|
27
|
+
import role from "../role.js";
|
|
28
|
+
const run = async (args) => {
|
|
29
|
+
const program = new Command().name("ptkl").exitOverride();
|
|
30
|
+
program.addCommand(role.register());
|
|
31
|
+
const printed = [];
|
|
32
|
+
const log = vi.spyOn(console, "log").mockImplementation((...a) => {
|
|
33
|
+
printed.push(a.map((x) => String(x)).join(" "));
|
|
34
|
+
});
|
|
35
|
+
try {
|
|
36
|
+
await program.parseAsync(["role", ...args], { from: "user" });
|
|
37
|
+
}
|
|
38
|
+
finally {
|
|
39
|
+
log.mockRestore();
|
|
40
|
+
}
|
|
41
|
+
return { output: () => JSON.parse(printed.join("\n").replace(/\u001b\[[0-9;]*m/g, "")) };
|
|
42
|
+
};
|
|
43
|
+
describe("role command", () => {
|
|
44
|
+
beforeEach(() => {
|
|
45
|
+
mocks.calls.length = 0;
|
|
46
|
+
});
|
|
47
|
+
it("list reads roles through the users client and prints its data", async () => {
|
|
48
|
+
const { output } = await run(["list", "-f", "json"]);
|
|
49
|
+
expect(mocks.calls).toEqual([{ method: "listRoles", args: [] }]);
|
|
50
|
+
expect(output()).toEqual({ method: "listRoles", args: [] });
|
|
51
|
+
});
|
|
52
|
+
it("permissions-list reads the permissions catalogue, not the roles list", async () => {
|
|
53
|
+
const { output } = await run(["permissions-list", "-f", "json"]);
|
|
54
|
+
expect(mocks.calls).toEqual([{ method: "listPermissions", args: [] }]);
|
|
55
|
+
expect(output()).toEqual({ method: "listPermissions", args: [] });
|
|
56
|
+
});
|
|
57
|
+
it("create sends the role payload with a numeric level", async () => {
|
|
58
|
+
const { output } = await run(["create", "-n", "support", "-p", "read base_users", "-w", "ws-1", "-l", "5", "-f", "json"]);
|
|
59
|
+
const role = { name: "support", permissions: ["read base_users"], workspaces: ["ws-1"], level: 5 };
|
|
60
|
+
expect(mocks.calls).toEqual([{ method: "createRole", args: [role] }]);
|
|
61
|
+
expect(output()).toEqual({ method: "createRole", args: [role] });
|
|
62
|
+
});
|
|
63
|
+
it("create defaults the level to 0", async () => {
|
|
64
|
+
await run(["create", "-n", "support", "-p", "read base_users", "edit base_users", "-w", "ws-1", "ws-2"]);
|
|
65
|
+
expect(mocks.calls[0].args[0]).toEqual({
|
|
66
|
+
name: "support",
|
|
67
|
+
permissions: ["read base_users", "edit base_users"],
|
|
68
|
+
workspaces: ["ws-1", "ws-2"],
|
|
69
|
+
level: 0,
|
|
70
|
+
});
|
|
71
|
+
});
|
|
72
|
+
it("edit sends the uuid separately from the editable fields", async () => {
|
|
73
|
+
const { output } = await run(["edit", "-u", "role-1", "-p", "read base_users", "edit base_users", "-w", "ws-1", "-l", "7", "-f", "json"]);
|
|
74
|
+
const fields = { permissions: ["read base_users", "edit base_users"], workspaces: ["ws-1"], level: 7 };
|
|
75
|
+
expect(mocks.calls).toEqual([{ method: "editRole", args: ["role-1", fields] }]);
|
|
76
|
+
expect(output()).toEqual({ method: "editRole", args: ["role-1", fields] });
|
|
77
|
+
});
|
|
78
|
+
it("delete removes the role by uuid", async () => {
|
|
79
|
+
const { output } = await run(["delete", "-u", "role-1", "-f", "json"]);
|
|
80
|
+
expect(mocks.calls).toEqual([{ method: "deleteRole", args: ["role-1"] }]);
|
|
81
|
+
expect(output()).toEqual({ method: "deleteRole", args: ["role-1"] });
|
|
82
|
+
});
|
|
83
|
+
});
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
const post = vi.fn(async (_url, _body) => ({ data: { ok: true } }));
|
|
3
|
+
const update = vi.fn(async (_id, _body) => ({ data: { ok: true } }));
|
|
4
|
+
const get = vi.fn();
|
|
5
|
+
const ask = vi.fn();
|
|
6
|
+
vi.mock('../../lib/sdk.js', () => ({
|
|
7
|
+
platform: () => ({ function: () => ({ client: { post, get }, update }) }),
|
|
8
|
+
}));
|
|
9
|
+
vi.mock('../../lib/util.js', () => ({
|
|
10
|
+
default: { getCurrentProfile: () => ({ host: 'h', token: 't', project: 'p' }) },
|
|
11
|
+
}));
|
|
12
|
+
vi.mock('../../lib/runIdentity.js', async (orig) => {
|
|
13
|
+
const mod = await orig();
|
|
14
|
+
const Real = mod.default;
|
|
15
|
+
return { ...mod, default: class extends Real {
|
|
16
|
+
constructor(http, interactive) { super(http, interactive, ask); }
|
|
17
|
+
} };
|
|
18
|
+
});
|
|
19
|
+
import functions from '../functions.js';
|
|
20
|
+
const run = (...args) => functions.register().parseAsync(['node', 'functions', ...args]);
|
|
21
|
+
describe('functions --run-as', () => {
|
|
22
|
+
const saved = [process.stdin.isTTY, process.stdout.isTTY];
|
|
23
|
+
const setTty = (v) => {
|
|
24
|
+
Object.defineProperty(process.stdin, 'isTTY', { value: v, configurable: true });
|
|
25
|
+
Object.defineProperty(process.stdout, 'isTTY', { value: v, configurable: true });
|
|
26
|
+
};
|
|
27
|
+
afterEach(() => {
|
|
28
|
+
Object.defineProperty(process.stdin, 'isTTY', { value: saved[0], configurable: true });
|
|
29
|
+
Object.defineProperty(process.stdout, 'isTTY', { value: saved[1], configurable: true });
|
|
30
|
+
});
|
|
31
|
+
beforeEach(() => {
|
|
32
|
+
setTty(false);
|
|
33
|
+
ask.mockReset();
|
|
34
|
+
post.mockClear();
|
|
35
|
+
update.mockClear();
|
|
36
|
+
get.mockClear();
|
|
37
|
+
});
|
|
38
|
+
it('create sends --run-as as top-level run_as', async () => {
|
|
39
|
+
await run('create', '-d', '{"name":"f"}', '--run-as', 'prn:role:1');
|
|
40
|
+
expect(post).toHaveBeenCalledWith('/v1/system/function', { name: 'f', run_as: 'prn:role:1' });
|
|
41
|
+
});
|
|
42
|
+
it('create without a tty sends no run_as and does not fetch choices', async () => {
|
|
43
|
+
await run('create', '-d', '{"name":"f"}');
|
|
44
|
+
expect(post).toHaveBeenCalledWith('/v1/system/function', { name: 'f' });
|
|
45
|
+
expect(get).not.toHaveBeenCalled();
|
|
46
|
+
});
|
|
47
|
+
it('update without the flag sends no run_as', async () => {
|
|
48
|
+
await run('update', 'u1', '-d', '{"name":"g"}');
|
|
49
|
+
expect(update).toHaveBeenCalledWith('u1', { name: 'g' });
|
|
50
|
+
});
|
|
51
|
+
it('update with the flag sends run_as', async () => {
|
|
52
|
+
await run('update', 'u1', '-d', '{"name":"g"}', '--run-as', 'prn:role:1');
|
|
53
|
+
expect(update).toHaveBeenCalledWith('u1', { name: 'g', run_as: 'prn:role:1' });
|
|
54
|
+
});
|
|
55
|
+
it('create with a tty sends the picked identity', async () => {
|
|
56
|
+
setTty(true);
|
|
57
|
+
get.mockResolvedValue({ data: { identities: [{ prn: 'prn:role:1', kind: 'role', name: 'Editors' }] } });
|
|
58
|
+
ask.mockResolvedValue('prn:role:1');
|
|
59
|
+
await run('create', '-d', '{"name":"f"}');
|
|
60
|
+
expect(get).toHaveBeenCalledWith('/v1/system/run-identity/choices');
|
|
61
|
+
expect(post).toHaveBeenCalledWith('/v1/system/function', { name: 'f', run_as: 'prn:role:1' });
|
|
62
|
+
});
|
|
63
|
+
});
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
// The point of core/toolkit#17 is the request body, so these drive the real @ptkl/sdk Thunder client with
|
|
3
|
+
// only its HTTP layer stubbed: the options must survive Thunder.read()'s `const { only, ...options }` split.
|
|
4
|
+
const post = vi.fn(async (_path, _body) => ({ data: { total: 0, pages: 0, items: [] } }));
|
|
5
|
+
vi.mock('../../lib/sdk.js', async () => {
|
|
6
|
+
const { Thunder } = await import('@ptkl/sdk/beta');
|
|
7
|
+
const thunder = new Thunder({ host: 'http://h', token: 't', env: 'dev' });
|
|
8
|
+
thunder.client = { post };
|
|
9
|
+
return { thunder: () => thunder };
|
|
10
|
+
});
|
|
11
|
+
vi.mock('../../lib/util.js', () => ({
|
|
12
|
+
default: { getCurrentProfile: () => ({ name: 'p', host: 'http://h', project: 'proj', token: 't' }) },
|
|
13
|
+
}));
|
|
14
|
+
const { default: ThunderCommand } = await import('../thunder.js');
|
|
15
|
+
const { Command } = await import('commander');
|
|
16
|
+
vi.spyOn(console, 'log').mockImplementation(() => { });
|
|
17
|
+
async function run(...args) {
|
|
18
|
+
const program = new Command().exitOverride();
|
|
19
|
+
program.addCommand(ThunderCommand.register());
|
|
20
|
+
await program.parseAsync(['node', 'ptkl', 'thunder', ...args, '-f', 'json']);
|
|
21
|
+
return post.mock.calls.at(-1);
|
|
22
|
+
}
|
|
23
|
+
describe('thunder paginate request body', () => {
|
|
24
|
+
it('sends a page size and offset when no page flags are given', async () => {
|
|
25
|
+
const [path, body] = await run('paginate', '-t', 'qa-th');
|
|
26
|
+
expect(path).toBe('/v3/system/thunder');
|
|
27
|
+
expect(body).toMatchObject({ type: 'qa-th', filters: {}, flag: 'Paginate', options: { limit: 20, skip: 0 } });
|
|
28
|
+
});
|
|
29
|
+
it('sends --limit, --skip, --sort and --only on the same read', async () => {
|
|
30
|
+
const [, body] = await run('paginate', '-t', 'qa-th', '--limit', '5', '--skip', '2', '--sort', '{"data.n":-1}', '--only', 'n');
|
|
31
|
+
expect(body).toMatchObject({
|
|
32
|
+
flag: 'Paginate',
|
|
33
|
+
options: { limit: 5, skip: 2, sort: [{ Key: 'data.n', Value: -1 }] },
|
|
34
|
+
only: ['n'],
|
|
35
|
+
});
|
|
36
|
+
});
|
|
37
|
+
it('paginates from the low-level read command too', async () => {
|
|
38
|
+
const [, body] = await run('read', '-t', 'qa-th', '--flag', 'Paginate', '-l', '1');
|
|
39
|
+
expect(body).toMatchObject({ flag: 'Paginate', options: { limit: 1, skip: 0 } });
|
|
40
|
+
});
|
|
41
|
+
it('leaves find without an options block', async () => {
|
|
42
|
+
const [, body] = await run('find', '-t', 'qa-th');
|
|
43
|
+
expect(body).toMatchObject({ flag: 'Find', filters: {} });
|
|
44
|
+
expect(body.options).toBeUndefined();
|
|
45
|
+
});
|
|
46
|
+
});
|
|
@@ -4,6 +4,7 @@ import { WebSocketServer } from "ws";
|
|
|
4
4
|
import { resolve, join, dirname } from "path";
|
|
5
5
|
import { rollup } from "rollup";
|
|
6
6
|
import util from "../lib/util.js";
|
|
7
|
+
import RunIdentityService from "../lib/runIdentity.js";
|
|
7
8
|
import { Platform as Api } from "@ptkl/sdk";
|
|
8
9
|
import OutputFormatCommand from "./outputCommand.js";
|
|
9
10
|
import { mkdirSync, writeFileSync, rmSync, readdirSync, existsSync, readFileSync } from "fs";
|
|
@@ -112,13 +113,15 @@ class ComponentCommand {
|
|
|
112
113
|
.option("--scope <scope>", "Component scope")
|
|
113
114
|
.option("--publish", "Publish the initial version immediately")
|
|
114
115
|
.option("-d, --data <data>", "Full create payload as JSON string (overrides other options)")
|
|
115
|
-
.option("-i, --file <file>", "Path to a JSON file containing the full create payload")
|
|
116
|
+
.option("-i, --file <file>", "Path to a JSON file containing the full create payload")
|
|
117
|
+
.option("--run-as <prn>", "Identity the component runs as (prompted for when interactive)")).action(this.createComponent))
|
|
116
118
|
.addCommand(new Command("update-settings")
|
|
117
119
|
.description("Save/update component settings for a version")
|
|
118
120
|
.requiredOption("-r, --ref <ref>", "Component ref")
|
|
119
121
|
.requiredOption("-v, --version <version>", "Component version")
|
|
120
122
|
.option("-d, --data <data>", "Settings as JSON string")
|
|
121
123
|
.option("-i, --file <file>", "Path to a JSON file containing the settings")
|
|
124
|
+
.option("--run-as <prn>", "Change the identity the component's code runs as")
|
|
122
125
|
.action(this.updateSettings))
|
|
123
126
|
.addCommand(new OutputFormatCommand(new Command("fork-version")
|
|
124
127
|
.description("Fork a component version to create a new one")
|
|
@@ -650,7 +653,9 @@ class ComponentCommand {
|
|
|
650
653
|
...(publish !== undefined && { publish }),
|
|
651
654
|
};
|
|
652
655
|
}
|
|
653
|
-
const
|
|
656
|
+
const identity = new RunIdentityService(httpClient);
|
|
657
|
+
const runAs = await identity.forCreate(opts.runAs);
|
|
658
|
+
const { data } = await httpClient.post("/v3/system/component/create", identity.withRunAs(payload, runAs));
|
|
654
659
|
return data;
|
|
655
660
|
}
|
|
656
661
|
async updateSettings(opts) {
|
|
@@ -664,7 +669,8 @@ class ComponentCommand {
|
|
|
664
669
|
const settings = file
|
|
665
670
|
? JSON.parse(readFileSync(resolve(file), "utf-8"))
|
|
666
671
|
: JSON.parse(dataStr);
|
|
667
|
-
const
|
|
672
|
+
const identity = new RunIdentityService();
|
|
673
|
+
const { data } = await client.saveSettings(identity.withRunAs(settings, opts.runAs), version);
|
|
668
674
|
return data;
|
|
669
675
|
}
|
|
670
676
|
async forkVersion(opts) {
|