Skip to content

Commit 6342221

Browse files
authored
Merge pull request #504 from MatrixAI/feature-demo
Preparing Polykey for Local Demo
2 parents 2b8f96e + 6b2e53d commit 6342221

File tree

12 files changed

+71
-58
lines changed

12 files changed

+71
-58
lines changed

src/PolykeyAgent.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -394,6 +394,9 @@ class PolykeyAgent {
394394
logger: logger.getChild(SessionManager.name),
395395
fresh,
396396
}));
397+
// If a recovery code is provided then we reset any sessions in case the
398+
// password changed.
399+
if (keyRingConfig.recoveryCode != null) await sessionManager.resetKey();
397400
grpcServerClient =
398401
grpcServerClient ??
399402
new GRPCServer({

src/bin/agent/CommandStart.ts

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import type { PolykeyWorkerManagerInterface } from '../../workers/types';
1010
import path from 'path';
1111
import childProcess from 'child_process';
1212
import process from 'process';
13+
import * as keysErrors from '../../keys/errors';
1314
import CommandPolykey from '../CommandPolykey';
1415
import * as binUtils from '../utils';
1516
import * as binOptions from '../utils/options';
@@ -218,11 +219,18 @@ class CommandStart extends CommandPolykey {
218219
await workerManager?.destroy();
219220
await pkAgent?.stop();
220221
});
221-
pkAgent = await PolykeyAgent.createPolykeyAgent({
222-
fs: this.fs,
223-
logger: this.logger.getChild(PolykeyAgent.name),
224-
...agentConfig,
225-
});
222+
try {
223+
pkAgent = await PolykeyAgent.createPolykeyAgent({
224+
fs: this.fs,
225+
logger: this.logger.getChild(PolykeyAgent.name),
226+
...agentConfig,
227+
});
228+
} catch (e) {
229+
if (e instanceof keysErrors.ErrorKeyPairParse) {
230+
throw new binErrors.ErrorCLIPasswordWrong();
231+
}
232+
throw e;
233+
}
226234
if (options.workers !== 0) {
227235
workerManager = await workersUtils.createWorkerManager({
228236
cores: options.workers,

src/bin/errors.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,11 @@ class ErrorCLIClientOptions<T> extends ErrorCLI<T> {
3131
exitCode = sysexits.USAGE;
3232
}
3333

34+
class ErrorCLIPasswordWrong<T> extends ErrorCLI<T> {
35+
static description = 'Wrong password, please try again';
36+
exitCode = sysexits.USAGE;
37+
}
38+
3439
class ErrorCLIPasswordMissing<T> extends ErrorCLI<T> {
3540
static description =
3641
'Password is necessary, provide it via --password-file, PK_PASSWORD or when prompted';
@@ -90,6 +95,7 @@ export {
9095
ErrorCLI,
9196
ErrorCLINodePath,
9297
ErrorCLIClientOptions,
98+
ErrorCLIPasswordWrong,
9399
ErrorCLIPasswordMissing,
94100
ErrorCLIPasswordFileRead,
95101
ErrorCLIRecoveryCodeFileRead,

src/bin/identities/CommandAuthenticate.ts

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,15 +16,10 @@ class CommandAuthenticate extends CommandPolykey {
1616
'Name of the digital identity provider',
1717
parsers.parseProviderId,
1818
);
19-
this.argument(
20-
'<identityId>',
21-
'Digital identity to authenticate',
22-
parsers.parseIdentityId,
23-
);
2419
this.addOption(binOptions.nodeId);
2520
this.addOption(binOptions.clientHost);
2621
this.addOption(binOptions.clientPort);
27-
this.action(async (providerId, identityId, options) => {
22+
this.action(async (providerId, options) => {
2823
const { default: PolykeyClient } = await import('../../PolykeyClient');
2924
const identitiesPB = await import(
3025
'../../proto/js/polykey/v1/identities/identities_pb'
@@ -59,7 +54,6 @@ class CommandAuthenticate extends CommandPolykey {
5954
});
6055
const providerMessage = new identitiesPB.Provider();
6156
providerMessage.setProviderId(providerId);
62-
providerMessage.setIdentityId(identityId);
6357
await binUtils.retryAuthentication(async (auth) => {
6458
genReadable = pkClient.grpcClient.identitiesAuthenticate(
6559
providerMessage,
@@ -90,7 +84,7 @@ class CommandAuthenticate extends CommandPolykey {
9084
case identitiesPB.AuthenticationProcess.StepCase.RESPONSE: {
9185
const authResponse = message.getResponse()!;
9286
this.logger.info(
93-
`Authenticated digital identity provider ${providerId} with identity ${identityId}`,
87+
`Authenticated digital identity provider ${providerId}`,
9488
);
9589
process.stdout.write(
9690
binUtils.outputFormatter({

src/bin/secrets/CommandGet.ts

Lines changed: 7 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,6 @@ class CommandGet extends CommandPolykey {
1515
'Path to where the secret to be retrieved, specified as <vaultName>:<directoryPath>',
1616
parsers.parseSecretPath,
1717
);
18-
this.option(
19-
'-e, --env',
20-
'Wrap the secret in an environment variable declaration',
21-
);
2218
this.addOption(binOptions.nodeId);
2319
this.addOption(binOptions.clientHost);
2420
this.addOption(binOptions.clientPort);
@@ -54,7 +50,6 @@ class CommandGet extends CommandPolykey {
5450
port: clientOptions.clientPort,
5551
logger: this.logger.getChild(PolykeyClient.name),
5652
});
57-
const isEnv: boolean = options.env ?? false;
5853
const secretMessage = new secretsPB.Secret();
5954
const vaultMessage = new vaultsPB.Vault();
6055
vaultMessage.setNameOrId(secretPath[0]);
@@ -64,28 +59,13 @@ class CommandGet extends CommandPolykey {
6459
(auth) => pkClient.grpcClient.vaultsSecretsGet(secretMessage, auth),
6560
meta,
6661
);
67-
if (isEnv) {
68-
process.stdout.write(
69-
binUtils.outputFormatter({
70-
type: options.format === 'json' ? 'json' : 'list',
71-
data: [
72-
`Export ${secretMessage
73-
.getSecretName()
74-
.toUpperCase()
75-
.replace('-', '_')}='${response.getSecretName()}`,
76-
],
77-
}),
78-
);
79-
} else {
80-
process.stdout.write(
81-
binUtils.outputFormatter({
82-
type: options.format === 'json' ? 'json' : 'list',
83-
data: [
84-
`${secretMessage.getSecretName()}:\t\t${response.getSecretName()}`,
85-
],
86-
}),
87-
);
88-
}
62+
const secretContent = response.getSecretContent_asU8();
63+
process.stdout.write(
64+
binUtils.outputFormatter({
65+
type: 'raw',
66+
data: secretContent,
67+
}),
68+
);
8969
} finally {
9070
if (pkClient! != null) await pkClient.stop();
9171
}

src/bin/utils/utils.ts

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,10 @@ function verboseToLogLevel(c: number = 0): LogLevel {
2626
}
2727

2828
type OutputObject =
29+
| {
30+
type: 'raw';
31+
data: string | Uint8Array;
32+
}
2933
| {
3034
type: 'list';
3135
data: Array<string>;
@@ -47,9 +51,11 @@ type OutputObject =
4751
data: Error;
4852
};
4953

50-
function outputFormatter(msg: OutputObject): string {
54+
function outputFormatter(msg: OutputObject): string | Uint8Array {
5155
let output = '';
52-
if (msg.type === 'list') {
56+
if (msg.type === 'raw') {
57+
return msg.data;
58+
} else if (msg.type === 'list') {
5359
for (let elem in msg.data) {
5460
// Empty string for null or undefined values
5561
if (elem == null) {
@@ -127,8 +133,9 @@ function outputFormatter(msg: OutputObject): string {
127133
output += ` - ${currError.message}`;
128134
}
129135
output += '\n';
130-
output += `${indent}exitCode\t${currError.exitCode}\n`;
131-
output += `${indent}timestamp\t${currError.timestamp}\n`;
136+
// Disabled to streamline output
137+
// output += `${indent}exitCode\t${currError.exitCode}\n`;
138+
// output += `${indent}timestamp\t${currError.timestamp}\n`;
132139
if (currError.data && !utils.isEmptyObject(currError.data)) {
133140
output += `${indent}data\t${JSON.stringify(currError.data)}\n`;
134141
}

src/identities/IdentitiesManager.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,9 @@ class IdentitiesManager {
243243
}
244244
const identities = await provider.getAuthIdentityIds();
245245
if (!identities.includes(identityId)) {
246-
throw new identitiesErrors.ErrorProviderUnauthenticated();
246+
throw new identitiesErrors.ErrorProviderIdentityMissing(
247+
`Authenticated identities: ${JSON.stringify(identities)}`,
248+
);
247249
}
248250
// Create identity claim on our node
249251
const publishedClaimProm = promise<IdentitySignedClaim>();
@@ -258,11 +260,11 @@ class IdentitiesManager {
258260
async (token) => {
259261
// Publishing in the callback to avoid adding bad claims
260262
const claim = token.toSigned();
261-
const asd = await provider.publishClaim(
263+
const identitySignedClaim = await provider.publishClaim(
262264
identityId,
263265
claim as SignedClaim<ClaimLinkIdentity>,
264266
);
265-
publishedClaimProm.resolveP(asd);
267+
publishedClaimProm.resolveP(identitySignedClaim);
266268
return token;
267269
},
268270
tran,

src/identities/errors.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,11 @@ class ErrorProviderUnauthenticated<T> extends ErrorIdentities<T> {
3838
exitCode = sysexits.NOPERM;
3939
}
4040

41+
class ErrorProviderIdentityMissing<T> extends ErrorIdentities<T> {
42+
static description = 'Identity is not authenticated with the provider';
43+
exitCode = sysexits.NOPERM;
44+
}
45+
4146
class ErrorProviderUnimplemented<T> extends ErrorIdentities<T> {
4247
static description = 'Functionality is unavailable';
4348
exitCode = sysexits.USAGE;
@@ -58,5 +63,6 @@ export {
5863
ErrorProviderAuthentication,
5964
ErrorProviderUnauthenticated,
6065
ErrorProviderUnimplemented,
66+
ErrorProviderIdentityMissing,
6167
ErrorProviderMissing,
6268
};

src/keys/utils/symmetric.ts

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -83,15 +83,21 @@ function decryptWithKey(
8383
const plainText = Buffer.allocUnsafeSlow(
8484
macAndCipherText.byteLength - macSize,
8585
);
86-
// This returns the number of bytes that has been decrypted
87-
const decrypted = sodium.crypto_aead_xchacha20poly1305_ietf_decrypt(
88-
plainText,
89-
null,
90-
macAndCipherText,
91-
additionalData,
92-
nonce,
93-
key,
94-
);
86+
let decrypted: number;
87+
try {
88+
// This returns the number of bytes that has been decrypted
89+
// It will throw if the MAC cannot be authenticated
90+
decrypted = sodium.crypto_aead_xchacha20poly1305_ietf_decrypt(
91+
plainText,
92+
null,
93+
macAndCipherText,
94+
additionalData,
95+
nonce,
96+
key,
97+
);
98+
} catch {
99+
return;
100+
}
95101
if (decrypted !== plainText.byteLength) {
96102
return;
97103
}

src/nodes/NodeManager.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ class NodeManager {
144144
const seedNodes = this.nodeConnectionManager.getSeedNodes();
145145
const allInactive = !seedNodes
146146
.map((nodeId) => this.nodeConnectionManager.hasConnection(nodeId))
147-
.reduce((a, b) => a || b);
147+
.reduce((a, b) => a || b, false);
148148
try {
149149
if (allInactive) {
150150
this.logger.debug(

0 commit comments

Comments
 (0)