@lightdash-tools/cli 0.2.5 → 0.3.1

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.
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Space access (v1) command implementation.
3
+ */
4
+
5
+ import type { Command } from 'commander';
6
+ import { WRITE_IDEMPOTENT, WRITE_DESTRUCTIVE, type SpaceMemberRole } from '@lightdash-tools/common';
7
+ import { getClient } from '../utils/client';
8
+ import { wrapAction } from '../utils/safety';
9
+
10
+ /**
11
+ * Registers the space access subcommands under the existing projects command.
12
+ */
13
+ export function registerSpaceAccessCommand(program: Command): void {
14
+ const projectsCmd = program.commands.find((c) => c.name() === 'projects');
15
+ if (!projectsCmd) {
16
+ throw new Error('projects command must be registered before space-access');
17
+ }
18
+
19
+ const spaceAccessCmd = projectsCmd
20
+ .command('space-access')
21
+ .description('Manage space access (v1)');
22
+
23
+ const userCmd = spaceAccessCmd.command('user').description('Manage user access to a space');
24
+
25
+ userCmd
26
+ .command('grant <projectUuid> <spaceUuid> <userUuid> <role>')
27
+ .description('Grant a user access to a space')
28
+ .action(
29
+ wrapAction(
30
+ WRITE_IDEMPOTENT,
31
+ async (projectUuid: string, spaceUuid: string, userUuid: string, role: string) => {
32
+ try {
33
+ const client = getClient();
34
+ await client.v1.spaces.grantUserAccessToSpace(projectUuid, spaceUuid, {
35
+ userUuid,
36
+ spaceRole: role as SpaceMemberRole,
37
+ });
38
+ console.error(
39
+ `Successfully granted ${role} access to user ${userUuid} in space ${spaceUuid}`,
40
+ );
41
+ } catch (error) {
42
+ console.error(
43
+ 'Error granting user access to space:',
44
+ error instanceof Error ? error.message : String(error),
45
+ );
46
+ process.exit(1);
47
+ }
48
+ },
49
+ ),
50
+ );
51
+
52
+ userCmd
53
+ .command('revoke <projectUuid> <spaceUuid> <userUuid>')
54
+ .description("Revoke a user's access to a space")
55
+ .action(
56
+ wrapAction(
57
+ WRITE_DESTRUCTIVE,
58
+ async (projectUuid: string, spaceUuid: string, userUuid: string) => {
59
+ try {
60
+ const client = getClient();
61
+ await client.v1.spaces.revokeUserAccessToSpace(projectUuid, spaceUuid, userUuid);
62
+ console.error(`Successfully revoked access for user ${userUuid} in space ${spaceUuid}`);
63
+ } catch (error) {
64
+ console.error(
65
+ 'Error revoking user access from space:',
66
+ error instanceof Error ? error.message : String(error),
67
+ );
68
+ process.exit(1);
69
+ }
70
+ },
71
+ ),
72
+ );
73
+
74
+ const groupCmd = spaceAccessCmd.command('group').description('Manage group access to a space');
75
+
76
+ groupCmd
77
+ .command('grant <projectUuid> <spaceUuid> <groupUuid> <role>')
78
+ .description('Grant a group access to a space')
79
+ .action(
80
+ wrapAction(
81
+ WRITE_IDEMPOTENT,
82
+ async (projectUuid: string, spaceUuid: string, groupUuid: string, role: string) => {
83
+ try {
84
+ const client = getClient();
85
+ await client.v1.spaces.grantGroupAccessToSpace(projectUuid, spaceUuid, {
86
+ groupUuid,
87
+ spaceRole: role as SpaceMemberRole,
88
+ });
89
+ console.error(
90
+ `Successfully granted ${role} access to group ${groupUuid} in space ${spaceUuid}`,
91
+ );
92
+ } catch (error) {
93
+ console.error(
94
+ 'Error granting group access to space:',
95
+ error instanceof Error ? error.message : String(error),
96
+ );
97
+ process.exit(1);
98
+ }
99
+ },
100
+ ),
101
+ );
102
+
103
+ groupCmd
104
+ .command('revoke <projectUuid> <spaceUuid> <groupUuid>')
105
+ .description("Revoke a group's access to a space")
106
+ .action(
107
+ wrapAction(
108
+ WRITE_DESTRUCTIVE,
109
+ async (projectUuid: string, spaceUuid: string, groupUuid: string) => {
110
+ try {
111
+ const client = getClient();
112
+ await client.v1.spaces.revokeGroupAccessToSpace(projectUuid, spaceUuid, groupUuid);
113
+ console.error(
114
+ `Successfully revoked access for group ${groupUuid} in space ${spaceUuid}`,
115
+ );
116
+ } catch (error) {
117
+ console.error(
118
+ 'Error revoking group access from space:',
119
+ error instanceof Error ? error.message : String(error),
120
+ );
121
+ process.exit(1);
122
+ }
123
+ },
124
+ ),
125
+ );
126
+ }
package/src/index.test.ts CHANGED
@@ -6,6 +6,7 @@ import { registerProjectsCommand } from './commands/projects';
6
6
  import { registerProjectRoleAssignmentsCommand } from './commands/project-role-assignments';
7
7
  import { registerProjectAccessCommand } from './commands/project-access';
8
8
  import { registerSpacesCommand } from './commands/spaces';
9
+ import { registerSpaceAccessCommand } from './commands/space-access';
9
10
  import { registerChartsCommand } from './commands/charts';
10
11
  import { registerDashboardsCommand } from './commands/dashboards';
11
12
  import { registerAiAgentsCommand } from './commands/ai-agents';
@@ -125,17 +126,19 @@ describe('CLI Command Registration', () => {
125
126
  expect(rolesCmd?.commands.some((c) => c.name() === 'assign')).toBe(true);
126
127
  });
127
128
 
128
- it('should register projects roles, access, spaces subcommands', () => {
129
+ it('should register projects roles, access, spaces, and space-access subcommands', () => {
129
130
  const program = new Command();
130
131
  registerProjectsCommand(program);
131
132
  registerProjectRoleAssignmentsCommand(program);
132
133
  registerProjectAccessCommand(program);
133
134
  registerSpacesCommand(program);
135
+ registerSpaceAccessCommand(program);
134
136
 
135
137
  const projectsCmd = program.commands.find((cmd) => cmd.name() === 'projects');
136
138
  expect(projectsCmd?.commands.some((c) => c.name() === 'roles')).toBe(true);
137
139
  expect(projectsCmd?.commands.some((c) => c.name() === 'access')).toBe(true);
138
140
  expect(projectsCmd?.commands.some((c) => c.name() === 'spaces')).toBe(true);
141
+ expect(projectsCmd?.commands.some((c) => c.name() === 'space-access')).toBe(true);
139
142
  });
140
143
 
141
144
  it('should register projects charts and dashboards subcommands', () => {
@@ -194,6 +197,7 @@ describe('CLI Command Registration', () => {
194
197
  registerProjectRoleAssignmentsCommand(program);
195
198
  registerProjectAccessCommand(program);
196
199
  registerSpacesCommand(program);
200
+ registerSpaceAccessCommand(program);
197
201
  registerChartsCommand(program);
198
202
  registerDashboardsCommand(program);
199
203
  registerAiAgentsCommand(program);
@@ -213,7 +217,7 @@ describe('CLI Command Registration', () => {
213
217
 
214
218
  it('should have --safety-mode option', () => {
215
219
  const program = new Command();
216
- program.option('--safety-mode <mode>', 'description', 'write-destructive');
220
+ program.option('--safety-mode <mode>', 'description', 'read-only');
217
221
  const option = program.options.find((opt) => opt.long === '--safety-mode');
218
222
  expect(option).toBeDefined();
219
223
  });
package/src/index.ts CHANGED
@@ -4,15 +4,18 @@
4
4
  */
5
5
 
6
6
  import { Command } from 'commander';
7
+ import { initAuditLog } from '@lightdash-tools/common';
7
8
  import { registerOrganizationCommand } from './commands/organization';
8
9
  import { registerOrganizationRolesCommand } from './commands/organization-roles';
9
10
  import { registerProjectsCommand } from './commands/projects';
10
11
  import { registerProjectRoleAssignmentsCommand } from './commands/project-role-assignments';
11
12
  import { registerProjectAccessCommand } from './commands/project-access';
12
13
  import { registerSpacesCommand } from './commands/spaces';
14
+ import { registerSpaceAccessCommand } from './commands/space-access';
13
15
  import { registerChartsCommand } from './commands/charts';
14
16
  import { registerDashboardsCommand } from './commands/dashboards';
15
17
  import { registerAiAgentsCommand } from './commands/ai-agents';
18
+ import { registerAgentsCommand } from './commands/agents';
16
19
  import { registerGroupsCommand } from './commands/groups';
17
20
  import { registerUsersCommand } from './commands/users';
18
21
  import { registerQueryCommand } from './commands/query';
@@ -22,16 +25,23 @@ import { registerSchedulersCommand } from './commands/schedulers';
22
25
  import { registerTagsCommand } from './commands/tags';
23
26
  import { registerContentCommand } from './commands/content';
24
27
 
28
+ // Initialise audit log before any command runs (uses LIGHTDASH_AUDIT_LOG env var).
29
+ initAuditLog(process.env.LIGHTDASH_AUDIT_LOG);
30
+
25
31
  const program = new Command();
26
32
 
27
33
  program
28
34
  .name('lightdash-ai')
29
35
  .description('CLI for Lightdash AI')
30
- .version('1.0.0')
36
+ .version('0.3.1')
31
37
  .option(
32
38
  '--safety-mode <mode>',
33
39
  'Safety mode (read-only, write-idempotent, write-destructive)',
34
- 'write-destructive',
40
+ 'read-only',
41
+ )
42
+ .option(
43
+ '--projects <uuids>',
44
+ 'Comma-separated list of allowed project UUIDs (security guardrail)',
35
45
  );
36
46
 
37
47
  // Register all commands (organization and projects first so subcommands can attach)
@@ -41,9 +51,11 @@ registerProjectsCommand(program);
41
51
  registerProjectRoleAssignmentsCommand(program);
42
52
  registerProjectAccessCommand(program);
43
53
  registerSpacesCommand(program);
54
+ registerSpaceAccessCommand(program);
44
55
  registerChartsCommand(program);
45
56
  registerDashboardsCommand(program);
46
57
  registerAiAgentsCommand(program);
58
+ registerAgentsCommand(program);
47
59
  registerGroupsCommand(program);
48
60
  registerUsersCommand(program);
49
61
  registerQueryCommand(program);
@@ -1,9 +1,19 @@
1
- import { isAllowed, getSafetyModeFromEnv, SafetyMode } from '@lightdash-tools/common';
1
+ import {
2
+ isAllowed,
3
+ getSafetyModeFromEnv,
4
+ SafetyMode,
5
+ logAuditEntry,
6
+ getSessionId,
7
+ areAllProjectsAllowed,
8
+ getAllowedProjectUuidsFromEnv,
9
+ extractProjectUuids,
10
+ } from '@lightdash-tools/common';
2
11
  import type { ToolAnnotations } from '@lightdash-tools/common';
3
12
  import type { Command } from 'commander';
4
13
 
5
14
  /**
6
15
  * Resolves the safety mode from the command line options or environment variables.
16
+ * CLI --safety-mode takes priority over LIGHTDASH_TOOL_SAFETY_MODE.
7
17
  */
8
18
  export function getSafetyMode(cmd: Command): SafetyMode {
9
19
  const options = cmd.optsWithGlobals() as { safetyMode?: string };
@@ -14,20 +24,110 @@ export function getSafetyMode(cmd: Command): SafetyMode {
14
24
  }
15
25
 
16
26
  /**
17
- * Wraps a CLI action with a safety check.
27
+ * Resolves the allowed project UUIDs from the command line options or environment variables.
28
+ * We specifically want the root --projects flag as the security guardrail.
29
+ * CLI root flags take priority over LIGHTDASH_TOOLS_ALLOWED_PROJECTS.
30
+ */
31
+ export function getAllowedProjects(cmd: Command): string[] {
32
+ let root = cmd;
33
+ while (root.parent) {
34
+ root = root.parent;
35
+ }
36
+ const options = root.opts() as { projects?: string };
37
+ const raw = options.projects;
38
+ if (raw) {
39
+ return raw
40
+ .split(',')
41
+ .map((s) => s.trim())
42
+ .filter(Boolean);
43
+ }
44
+ return getAllowedProjectUuidsFromEnv();
45
+ }
46
+
47
+ /** Builds a human-readable command path (e.g. "lightdash-ai charts list"). */
48
+ function getCommandPath(cmd: Command): string {
49
+ const parts: string[] = [];
50
+ let current: Command | null = cmd;
51
+ while (current) {
52
+ const n = current.name();
53
+ if (n) parts.unshift(n);
54
+ current = current.parent;
55
+ }
56
+ return parts.join(' ');
57
+ }
58
+
59
+ /**
60
+ * Wraps a CLI action with safety-mode enforcement and audit logging.
18
61
  */
19
62
  export function wrapAction<T extends unknown[]>(
20
63
  annotations: ToolAnnotations,
21
64
  action: (...args: T) => Promise<void> | void,
22
65
  ) {
23
66
  return async function (this: Command, ...args: T) {
67
+ const start = Date.now();
68
+ const commandPath = getCommandPath(this);
24
69
  const mode = getSafetyMode(this);
70
+ const allowedProjects = getAllowedProjects(this);
71
+ const targetProjects = extractProjectUuids(args);
72
+
73
+ // ── Safety Mode Enforcement ──────────────────────────────────────────────
25
74
  if (!isAllowed(mode, annotations)) {
75
+ logAuditEntry({
76
+ timestamp: new Date().toISOString(),
77
+ sessionId: getSessionId(),
78
+ tool: commandPath,
79
+ projectUuids: targetProjects.length > 0 ? targetProjects : undefined,
80
+ status: 'blocked',
81
+ durationMs: Date.now() - start,
82
+ });
26
83
  console.error(
27
84
  `Error: This command is disabled in ${mode} mode. To enable it, use --safety-mode or set LIGHTDASH_TOOL_SAFETY_MODE.`,
28
85
  );
29
86
  process.exit(1);
30
87
  }
31
- return action.apply(this, args);
88
+
89
+ // ── Project Guardrail Enforcement ────────────────────────────────────────
90
+ if (allowedProjects.length > 0) {
91
+ const deniedProjects = targetProjects.filter(
92
+ (p) => !areAllProjectsAllowed(allowedProjects, [p]),
93
+ );
94
+ if (deniedProjects.length > 0) {
95
+ logAuditEntry({
96
+ timestamp: new Date().toISOString(),
97
+ sessionId: getSessionId(),
98
+ tool: commandPath,
99
+ projectUuids: targetProjects,
100
+ status: 'blocked',
101
+ durationMs: Date.now() - start,
102
+ });
103
+ console.error(
104
+ `Error: Project(s) [${deniedProjects.join(', ')}] are not in the list of allowed projects. Allowed: [${allowedProjects.join(', ')}].`,
105
+ );
106
+ process.exit(1);
107
+ }
108
+ }
109
+
110
+ try {
111
+ const result = await action.apply(this, args);
112
+ logAuditEntry({
113
+ timestamp: new Date().toISOString(),
114
+ sessionId: getSessionId(),
115
+ tool: commandPath,
116
+ projectUuids: targetProjects.length > 0 ? targetProjects : undefined,
117
+ status: 'success',
118
+ durationMs: Date.now() - start,
119
+ });
120
+ return result;
121
+ } catch (err) {
122
+ logAuditEntry({
123
+ timestamp: new Date().toISOString(),
124
+ sessionId: getSessionId(),
125
+ tool: commandPath,
126
+ projectUuids: targetProjects.length > 0 ? targetProjects : undefined,
127
+ status: 'error',
128
+ durationMs: Date.now() - start,
129
+ });
130
+ throw err;
131
+ }
32
132
  };
33
133
  }