@openupstream/cli 0.5.0 → 0.6.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/dist/index.js CHANGED
@@ -24,6 +24,10 @@
24
24
  * oup job stop <name> <run>
25
25
  * oup job logs <name> [<run>] [--tail <n>] [-f] [--timestamps] the newest run by default
26
26
  * oup secret list | set <NAME> | delete <NAME> a value is read from stdin
27
+ * oup key list | create <name> | show <name> | rotate <name> | delete <name> | restore <name>
28
+ * oup key grant <name> (--service <name> | --job <name>) --access encrypt|decrypt|both
29
+ * oup key revoke <name> (--service <name> | --job <name>)
30
+ * oup key log <name> [--limit <n>] [--json] who encrypted and decrypted, kept 30 days
27
31
  * oup bucket list | create <name> | show <name> | show-access-key <name> | export-env <name> [--file <path>] | delete <name>
28
32
  * oup domain list | add <hostname> | verify <hostname> | delete <hostname>
29
33
  * oup route list | add <address> --bucket <name> [--spa] | add <address> --service <name> | delete <address>
@@ -31,7 +35,7 @@
31
35
  * oup site deploy <dir> --bucket <name> [--keep] [--force]
32
36
  * oup version
33
37
  *
34
- * Database, service, job, secret, bucket, domain, route and usage commands act on the linked Project; `--project`
38
+ * Database, service, job, secret, key, bucket, domain, route and usage commands act on the linked Project; `--project`
35
39
  * or `OUP_PROJECT` names another.
36
40
  *
37
41
  * `OUP_API_KEY` (a madAuth API key or an Account token) replaces `oup login`, e.g. in CI, with
@@ -59,7 +63,10 @@ import { formatServices, planServiceDeploy, waitUntilRunning } from './services.
59
63
  import { LISTEN_HOST, connectionUrl, listen, parseAccess, parsePort, portFree, prepareRole, serveTunnel } from './proxy.js';
60
64
  import { dnsRecords, domainNamed, formatDomains, formatRoutes, hostnameOf, hostnameProblem, ingressOf, parseAddress, routeInput, routeRefusal } from './routes.js';
61
65
  import { apiAccess } from './session.js';
66
+ import { deletionNotice, formatKey, formatKeyCalls, formatKeys, grantHolder, parseCallLimit, parseKeyAccess } from './keys.js';
62
67
  import { readSecretValue } from './stdin.js';
68
+ import { ENVIRONMENT_FLAGS, ENVIRONMENT_OPTIONS, desiredEnvironment, removedNames } from './environment.js';
69
+ import { formatSecrets, secretSetMessage } from './secrets.js';
63
70
  import { waitUntil } from './wait.js';
64
71
  import { formatUsage } from './usage.js';
65
72
  import { formatSites } from './sites.js';
@@ -94,6 +101,10 @@ const USAGE = `usage:
94
101
  oup service show <name>
95
102
  oup service deploy <name> --image <ref> [--port <n> | --no-port] [--replicas <n>] [--memory <MB>] [--cpu <millicores>]
96
103
  [--site <site>] [--registry-user <user> --registry-password-stdin] [--no-wait]
104
+ [--secret <NAME>]… [--env <NAME>=<value>]… [--env-file <path>]… [--no-secrets] [--no-env]
105
+ [--add-secret <NAME>]… [--remove-secret <NAME>]… [--set-env <NAME>=<value>]… [--unset-env <NAME>]…
106
+ [--database <name>[:owner]]… [--no-databases] [--add-database <name>[:owner]]… [--remove-database <name>]…
107
+ [--pre-deploy <job> | --no-pre-deploy]
97
108
  oup service logs <name> [--tail <n>] [-f | --follow] [--timestamps]
98
109
  oup service delete <name>
99
110
  oup job list
@@ -101,6 +112,9 @@ const USAGE = `usage:
101
112
  oup job deploy <name> --image <ref> [--schedule <cron> | --no-schedule] [--time-zone <IANA name>]
102
113
  [--timeout <seconds>] [--memory <MB>] [--cpu <millicores>] [--site <site>]
103
114
  [--registry-user <user> --registry-password-stdin] [--no-wait] [--no-command | -- <command> <arg>…]
115
+ [--secret <NAME>]… [--env <NAME>=<value>]… [--env-file <path>]… [--no-secrets] [--no-env]
116
+ [--add-secret <NAME>]… [--remove-secret <NAME>]… [--set-env <NAME>=<value>]… [--unset-env <NAME>]…
117
+ [--database <name>[:owner]]… [--no-databases] [--add-database <name>[:owner]]… [--remove-database <name>]…
104
118
  oup job run <name> [--env NAME=value]… [--no-wait] [-- <arg>…]
105
119
  oup job runs <name>
106
120
  oup job stop <name> <run>
@@ -109,6 +123,15 @@ const USAGE = `usage:
109
123
  oup secret list
110
124
  oup secret set <NAME> (the value from stdin)
111
125
  oup secret delete <NAME>
126
+ oup key list
127
+ oup key create <name>
128
+ oup key show <name>
129
+ oup key rotate <name> (a new version; what older ones encrypted still decrypts)
130
+ oup key delete <name> (pending deletion for 7 days, then erased for good)
131
+ oup key restore <name> (while it is pending deletion)
132
+ oup key grant <name> (--service <name> | --job <name>) --access encrypt|decrypt|both
133
+ oup key revoke <name> (--service <name> | --job <name>)
134
+ oup key log <name> [--limit <n>] [--json] (its calls, newest first, kept 30 days)
112
135
  oup bucket list
113
136
  oup bucket create <name>
114
137
  oup bucket show <name>
@@ -129,7 +152,7 @@ const USAGE = `usage:
129
152
  oup site deploy <dir> --bucket <name> [--keep] [--force]
130
153
  oup version
131
154
 
132
- Database, service, job, secret, bucket, domain, route and usage commands take --project <name|id>; without
155
+ Database, service, job, secret, key, bucket, domain, route and usage commands take --project <name|id>; without
133
156
  it, the Project linked to this directory (oup link) or OUP_PROJECT.
134
157
 
135
158
  pg create gives a Database 256 MB and 1 GB unless told otherwise. pg restore
@@ -148,6 +171,32 @@ every table, write also changes rows, owner acts as app, the role the
148
171
  Project's Services use, so migrations work; owner connections go to the
149
172
  primary, so migration tools' locks work, at most 5 at once.
150
173
 
174
+ A Service or Job gets the Secrets its deploy names and no others: --secret
175
+ NAME (the Secret must exist: oup secret set), and plain settings as
176
+ Variables: --env NAME=value or --env-file with one NAME=value per line.
177
+ These state the whole list: given for a Service that exists, they replace
178
+ what it has, and oup prints the names that go; --no-secrets and --no-env
179
+ empty one. To change one entry and keep the rest: --add-secret,
180
+ --remove-secret, --set-env, --unset-env. Without any of them a deploy
181
+ leaves both lists as they are. A Variable is shown to everyone who may read
182
+ the Project: credentials belong in a Secret.
183
+
184
+ A Service or Job reaches the Databases its deploy names and no others:
185
+ --database main gives it DATABASE_URL as a Postgres role of its own
186
+ (svc_<name> or job_<name>), which can connect and nothing else until the
187
+ Database's owner grants it rights in SQL, e.g. GRANT oup_write TO svc_api.
188
+ --database main:owner gives it the owner's connection, for the Job that
189
+ changes the schema and runs those grants. Without --database it gets no
190
+ DATABASE_URL. The flags work like --secret: --database states the whole
191
+ list, --no-databases empties it, --add-database and --remove-database
192
+ change one entry.
193
+
194
+ --pre-deploy <job> names a Job of the Project that is run, and waited for,
195
+ before each rollout of the Service: a migration, for example. Deploy the
196
+ Job first, so it runs the new image. When its run fails, nothing is rolled
197
+ out, the Service runs what it ran before, and oup service deploy exits 1
198
+ and says where the run's output is. --no-pre-deploy takes it off.
199
+
151
200
  member acts on your only Account, or on --account. An owner may do
152
201
  everything, the Account's Members included; a developer every Project and
153
202
  everything in it; a Member with role none only what their grants give. A
@@ -514,6 +563,9 @@ async function service(args) {
514
563
  image: { type: 'string' },
515
564
  port: { type: 'string' },
516
565
  'no-port': { type: 'boolean' },
566
+ ...ENVIRONMENT_OPTIONS,
567
+ 'pre-deploy': { type: 'string' },
568
+ 'no-pre-deploy': { type: 'boolean' },
517
569
  replicas: { type: 'string' },
518
570
  memory: { type: 'string' },
519
571
  cpu: { type: 'string' },
@@ -534,6 +586,10 @@ async function service(args) {
534
586
  if (verb !== 'logs' && logFlag !== undefined) {
535
587
  return fail(`oup service ${verb} does not take --${logFlag}`);
536
588
  }
589
+ const environmentFlag = [...ENVIRONMENT_FLAGS, 'pre-deploy', 'no-pre-deploy'].find((flag) => values[flag] !== undefined);
590
+ if (verb !== 'deploy' && environmentFlag !== undefined) {
591
+ return fail(`oup service ${verb} does not take --${environmentFlag}`);
592
+ }
537
593
  const { client, project } = await inProject(values.project);
538
594
  const services = await client.listServices(project.id);
539
595
  if (!services.ok) {
@@ -582,7 +638,22 @@ async function serviceDeploy(client, project, existing, flags) {
582
638
  if (flags.port !== undefined && flags['no-port'] === true) {
583
639
  return fail('--port and --no-port exclude each other');
584
640
  }
641
+ if (flags['pre-deploy'] !== undefined && flags['no-pre-deploy'] === true) {
642
+ return fail('--pre-deploy and --no-pre-deploy exclude each other');
643
+ }
644
+ // The Job that is run, and waited for, before each rollout (decision 173): named by the flag, else as it is.
645
+ const jobs = flags['pre-deploy'] !== undefined || existing?.preDeployJobId != null ? await client.listJobs(project.id) : undefined;
646
+ if (jobs !== undefined && !jobs.ok) {
647
+ return fail(jobs.error.message);
648
+ }
649
+ const namedJob = flags['pre-deploy'] === undefined ? undefined : jobs?.value.find((job) => job.name === flags['pre-deploy']);
650
+ if (flags['pre-deploy'] !== undefined && namedJob === undefined) {
651
+ return fail(`no Job ${flags['pre-deploy']} in ${project.name}; deploy it first (oup job deploy)`);
652
+ }
653
+ const preDeployJobId = flags['no-pre-deploy'] === true ? null : namedJob?.id;
654
+ const preDeployJob = preDeployJobId === null ? undefined : (namedJob ?? jobs?.value.find((job) => job.id === existing?.preDeployJobId));
585
655
  const registryAuth = await registryAuthFrom(flags);
656
+ const environment = await environmentFrom(existing, flags);
586
657
  const port = flags['no-port'] === true ? null : count('port', flags.port);
587
658
  const replicas = count('replicas', flags.replicas);
588
659
  const memoryMb = count('memory', flags.memory);
@@ -596,6 +667,8 @@ async function serviceDeploy(client, project, existing, flags) {
596
667
  ...(cpuMillicores === undefined ? {} : { cpuMillicores }),
597
668
  ...(flags.site === undefined || !isSite(flags.site) ? {} : { homeSite: flags.site }),
598
669
  ...(registryAuth === undefined ? {} : { registryAuth }),
670
+ environment,
671
+ ...(preDeployJobId === undefined ? {} : { preDeployJobId }),
599
672
  };
600
673
  const plan = planServiceDeploy(existing, desired);
601
674
  const deployed = plan.kind === 'invalid'
@@ -608,17 +681,28 @@ async function serviceDeploy(client, project, existing, flags) {
608
681
  if (!deployed.ok) {
609
682
  return fail(deployed.error.message);
610
683
  }
684
+ if (plan.kind === 'update') {
685
+ reportRemoved(flags.name, existing, plan.patch);
686
+ }
611
687
  const verb = plan.kind === 'create' ? 'Created' : plan.kind === 'update' ? 'Changed' : 'Deployed';
612
688
  console.log(`${verb} ${flags.name}: ${deployed.value.image} at ${deployed.value.imageDigest}`);
613
689
  if (flags['no-wait'] === true) {
614
690
  return;
615
691
  }
692
+ if (preDeployJob !== undefined) {
693
+ console.log(` runs the Job ${preDeployJob.name} first and rolls out once it has succeeded`);
694
+ }
616
695
  const running = await waitUntilRunning(() => client.getService(project.id, deployed.value.id), {
617
- timeoutMs: 5 * 60_000,
696
+ // The pre-deploy run may take as long as its Job's timeout, before the rollout's own five minutes.
697
+ timeoutMs: 5 * 60_000 + (preDeployJob?.timeoutSeconds ?? 0) * 1000,
618
698
  intervalMs: 3_000,
619
699
  report: (state) => console.log(` ${state}`),
620
700
  });
621
- return running.ok ? undefined : fail(`${flags.name} is not running: ${running.error}`);
701
+ if (running.ok) {
702
+ return;
703
+ }
704
+ const log = 'preDeployRun' in running && running.preDeployRun != null && preDeployJob !== undefined ? `; its output: oup job logs ${preDeployJob.name} ${running.preDeployRun}` : '';
705
+ return fail(`${flags.name} is not running: ${running.error}${log}`);
622
706
  }
623
707
  const logQuery = (tail, follow) => ({
624
708
  ...(tail === undefined ? {} : { tail }),
@@ -633,6 +717,35 @@ async function printLogs(opened, options) {
633
717
  console.log(formatLogEntry(entry, options));
634
718
  }
635
719
  }
720
+ /**
721
+ * The Secrets and Variables the flags ask for (environment.ts), with the
722
+ * `--env-file`s read here.
723
+ */
724
+ async function environmentFrom(existing, flags) {
725
+ const files = [];
726
+ for (const path of flags['env-file'] ?? []) {
727
+ const text = await readFile(path, 'utf8').then((content) => ({ ok: true, content }), (error) => ({ ok: false, error }));
728
+ if (!text.ok) {
729
+ return fail(`cannot read ${path}: ${text.error instanceof Error ? text.error.message : String(text.error)}`);
730
+ }
731
+ files.push({ path, text: text.content });
732
+ }
733
+ const desired = desiredEnvironment(existing, flags, files);
734
+ return desired.ok ? desired.value : fail(desired.error);
735
+ }
736
+ /** Says which names a change takes away: stating a whole list drops what is not repeated. */
737
+ function reportRemoved(name, existing, change) {
738
+ const removed = removedNames(existing, change);
739
+ if (removed.secrets.length > 0) {
740
+ console.log(`${name} no longer names the ${removed.secrets.length === 1 ? 'Secret' : 'Secrets'} ${removed.secrets.join(', ')}`);
741
+ }
742
+ if (removed.variables.length > 0) {
743
+ console.log(`${name} loses the ${removed.variables.length === 1 ? 'Variable' : 'Variables'} ${removed.variables.join(', ')}`);
744
+ }
745
+ if (removed.databases.length > 0) {
746
+ console.log(`${name} no longer reaches the ${removed.databases.length === 1 ? 'Database' : 'Databases'} ${removed.databases.join(', ')}`);
747
+ }
748
+ }
636
749
  /** Registry credentials from `--registry-user` and the password on stdin; undefined without them. */
637
750
  async function registryAuthFrom(flags) {
638
751
  const username = flags['registry-user'];
@@ -663,7 +776,7 @@ async function job(args) {
663
776
  cpu: { type: 'string' },
664
777
  site: { type: 'string' },
665
778
  'no-command': { type: 'boolean' },
666
- env: { type: 'string', multiple: true },
779
+ ...ENVIRONMENT_OPTIONS,
667
780
  'registry-user': { type: 'string' },
668
781
  'registry-password-stdin': { type: 'boolean' },
669
782
  'no-wait': { type: 'boolean' },
@@ -757,6 +870,7 @@ async function jobDeploy(client, project, existing, flags) {
757
870
  return fail('nothing after --; leave it out to keep the command');
758
871
  }
759
872
  const registryAuth = await registryAuthFrom(flags);
873
+ const environment = await environmentFrom(existing, flags);
760
874
  const timeoutSeconds = count('timeout', flags.timeout);
761
875
  const memoryMb = count('memory', flags.memory);
762
876
  const cpuMillicores = count('cpu', flags.cpu);
@@ -772,6 +886,7 @@ async function jobDeploy(client, project, existing, flags) {
772
886
  ...(flags['time-zone'] === undefined ? {} : { timeZone: flags['time-zone'] }),
773
887
  ...(flags.site === undefined || !isSite(flags.site) ? {} : { homeSite: flags.site }),
774
888
  ...(registryAuth === undefined ? {} : { registryAuth }),
889
+ environment,
775
890
  };
776
891
  const plan = planJobDeploy(existing, desired);
777
892
  const deployed = plan.kind === 'create'
@@ -782,6 +897,9 @@ async function jobDeploy(client, project, existing, flags) {
782
897
  if (!deployed.ok) {
783
898
  return fail(deployed.error.message);
784
899
  }
900
+ if (plan.kind === 'update') {
901
+ reportRemoved(flags.name, existing, plan.patch);
902
+ }
785
903
  const verb = plan.kind === 'create' ? 'Created' : plan.kind === 'update' ? 'Changed' : 'Deployed';
786
904
  const when = deployed.value.schedule === null ? 'on demand' : `on ${deployed.value.schedule} (${deployed.value.timeZone ?? 'UTC'})`;
787
905
  console.log(`${verb} ${flags.name}, ${when}: ${deployed.value.image} at ${deployed.value.imageDigest}`);
@@ -824,6 +942,99 @@ async function jobRun(client, project, target, options) {
824
942
  const outcome = outcomeOf(finished.value);
825
943
  return finished.value.state === 'succeeded' ? console.log(outcome) : fail(`${started.value.id} ${outcome}`);
826
944
  }
945
+ /** `oup key`: a Project's Keys (decision 167). No verb shows or takes key material: it never leaves the platform. */
946
+ async function key(args) {
947
+ const [verb, ...rest] = args;
948
+ const { values, positionals } = parseArgs({
949
+ args: rest,
950
+ allowPositionals: true,
951
+ options: { project: { type: 'string' }, service: { type: 'string' }, job: { type: 'string' }, access: { type: 'string' }, limit: { type: 'string' }, json: { type: 'boolean' } },
952
+ });
953
+ const [name] = positionals;
954
+ if (verb === undefined || (verb !== 'list' && name === undefined)) {
955
+ return fail(USAGE);
956
+ }
957
+ const { client, project } = await inProject(values.project);
958
+ /** The Service or Job a grant is for, by its name in the Project. */
959
+ const holder = async () => {
960
+ const wanted = grantHolder(values.service, values.job);
961
+ if (!wanted.ok) {
962
+ return fail(wanted.error);
963
+ }
964
+ const listed = wanted.value.holder === 'service' ? await client.listServices(project.id) : await client.listJobs(project.id);
965
+ if (!listed.ok) {
966
+ return fail(listed.error.message);
967
+ }
968
+ const what = `the ${wanted.value.holder === 'service' ? 'Service' : 'Job'} ${wanted.value.name}`;
969
+ const found = listed.value.find((candidate) => candidate.name === wanted.value.name);
970
+ return found === undefined ? fail(`no ${what.slice(4)} in ${project.name}`) : { id: found.id, what };
971
+ };
972
+ const list = async () => {
973
+ const keys = await client.listKeys(project.id);
974
+ return keys.ok ? keys.value : fail(keys.error.message);
975
+ };
976
+ /** The Key `name` of the Project, for the verbs that act on one. */
977
+ const named = async () => (await list()).find((candidate) => candidate.name === name) ?? fail(`no Key ${name} in ${project.name}`);
978
+ switch (verb) {
979
+ case 'list': {
980
+ const keys = await list();
981
+ return console.log(keys.length === 0 ? `No Keys in ${project.name}.` : formatKeys(keys).join('\n'));
982
+ }
983
+ case 'create': {
984
+ const created = await client.createKey(project.id, { name: name });
985
+ return created.ok ? console.log(`Created the Key ${created.value.name} in ${project.name}.`) : fail(created.error.message);
986
+ }
987
+ case 'show':
988
+ return console.log(formatKey(await named()).join('\n'));
989
+ case 'rotate': {
990
+ const rotated = await client.rotateKey(project.id, (await named()).id);
991
+ return rotated.ok
992
+ ? console.log(`${rotated.value.name} is at version ${rotated.value.version}; what older versions encrypted still decrypts.`)
993
+ : fail(rotated.error.message);
994
+ }
995
+ case 'delete': {
996
+ const deleted = await client.deleteKey(project.id, (await named()).id);
997
+ return deleted.ok ? console.log(deletionNotice(deleted.value, project.name)) : fail(deleted.error.message);
998
+ }
999
+ case 'restore': {
1000
+ const restored = await client.restoreKey(project.id, (await named()).id);
1001
+ return restored.ok ? console.log(`Restored ${restored.value.name} in ${project.name}; it is active again.`) : fail(restored.error.message);
1002
+ }
1003
+ case 'grant': {
1004
+ const access = parseKeyAccess(values.access);
1005
+ if (!access.ok) {
1006
+ return fail(access.error);
1007
+ }
1008
+ const { id, what } = await holder();
1009
+ const granted = await client.putKeyGrant(project.id, (await named()).id, id, { access: access.value });
1010
+ return granted.ok
1011
+ ? console.log(`${what[0]?.toUpperCase()}${what.slice(1)} may ${access.value === 'both' ? 'encrypt and decrypt' : access.value} with ${name}.` +
1012
+ (values.service === undefined ? '' : ' Its first grant on any Key restarts the Service once, to give its pods their token.'))
1013
+ : fail(granted.error.message);
1014
+ }
1015
+ case 'log': {
1016
+ const limit = parseCallLimit(values.limit);
1017
+ if (!limit.ok) {
1018
+ return fail(limit.error);
1019
+ }
1020
+ const calls = await client.listKeyCalls(project.id, (await named()).id, { limit: limit.value });
1021
+ if (!calls.ok) {
1022
+ return fail(calls.error.message);
1023
+ }
1024
+ if (values.json === true) {
1025
+ return console.log(JSON.stringify(calls.value, null, 2));
1026
+ }
1027
+ return console.log(calls.value.length === 0 ? `No calls of ${name} in the last 30 days.` : formatKeyCalls(calls.value).join('\n'));
1028
+ }
1029
+ case 'revoke': {
1030
+ const { id, what } = await holder();
1031
+ const revoked = await client.deleteKeyGrant(project.id, (await named()).id, id);
1032
+ return revoked.ok ? console.log(`Took the grant on ${name} from ${what}; its next call is refused.`) : fail(revoked.error.message);
1033
+ }
1034
+ default:
1035
+ return fail(USAGE);
1036
+ }
1037
+ }
827
1038
  async function secret(args) {
828
1039
  const [verb, ...rest] = args;
829
1040
  const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { project: { type: 'string' } } });
@@ -838,7 +1049,7 @@ async function secret(args) {
838
1049
  if (!secrets.ok) {
839
1050
  return fail(secrets.error.message);
840
1051
  }
841
- console.log(secrets.value.length === 0 ? `No Secrets in ${project.name}.` : secrets.value.map((s) => `${s.name.padEnd(32)} ${s.updatedAt}`).join('\n'));
1052
+ console.log(secrets.value.length === 0 ? `No Secrets in ${project.name}.` : formatSecrets(secrets.value).join('\n'));
842
1053
  return;
843
1054
  }
844
1055
  case 'set': {
@@ -851,7 +1062,7 @@ async function secret(args) {
851
1062
  return fail(`no value for ${name} on stdin; pipe it in, e.g. printf %s "$VALUE" | oup secret set ${name}`);
852
1063
  }
853
1064
  const stored = await client.putSecret(project.id, { name: name, value });
854
- return stored.ok ? console.log(`Set ${name} in ${project.name}; its Services restart with it.`) : fail(stored.error.message);
1065
+ return stored.ok ? console.log(secretSetMessage(stored.value, project.name)) : fail(stored.error.message);
855
1066
  }
856
1067
  case 'delete': {
857
1068
  const deleted = await client.deleteSecret(project.id, name);
@@ -1365,6 +1576,8 @@ const run = async () => {
1365
1576
  return job(rest);
1366
1577
  case 'secret':
1367
1578
  return secret(rest);
1579
+ case 'key':
1580
+ return key(rest);
1368
1581
  case 'bucket':
1369
1582
  return bucket(rest);
1370
1583
  case 'domain':