Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Modularize passStyleOf #3571

Merged
merged 3 commits into from
Aug 4, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 12 additions & 12 deletions packages/marshal/index.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
export {
getInterfaceOf,
getErrorConstructor,
passStyleOf,
} from './src/passStyleOf.js';
export { PASS_STYLE } from './src/helpers/passStyleHelpers.js';
export { getErrorConstructor } from './src/helpers/error.js';
export { getInterfaceOf } from './src/helpers/remotable.js';

export {
pureCopy,
QCLASS,
makeMarshal,
Remotable,
Far,
} from './src/marshal.js';
export { passStyleOf, everyPassableChild } from './src/passStyleOf.js';

export { pureCopy, Remotable, Far } from './src/make-far.js';
export { QCLASS, makeMarshal } from './src/marshal.js';
export { stringify, parse } from './src/marshal-stringify.js';
export {
isStructure,
assertStructure,
sameStructure,
fulfillToStructure,
} from './src/structure.js';
59 changes: 59 additions & 0 deletions packages/marshal/src/helpers/copyArray.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// @ts-check

// eslint-disable-next-line spaced-comment
/// <reference types="ses"/>

import '../types.js';
import './internal-types.js';
/**
* TODO Why do I need these?
*
* @typedef {import('./internal-types.js').PassStyleHelper} PassStyleHelper
*/
import '@agoric/assert/exported.js';
import { assertChecker, checkNormalProperty } from './passStyleHelpers.js';

const { details: X } = assert;
const { getPrototypeOf } = Object;
const { ownKeys } = Reflect;
const { isArray, prototype: arrayPrototype } = Array;

/**
*
* @type {PassStyleHelper}
*/
export const CopyArrayHelper = harden({
styleName: 'copyArray',

canBeValid: (candidate, check = x => x) =>
check(isArray(candidate), X`Array expected: ${candidate}`),

assertValid: (candidate, passStyleOfRecur) => {
CopyArrayHelper.canBeValid(candidate, assertChecker);
assert(
getPrototypeOf(candidate) === arrayPrototype,
X`Malformed array: ${candidate}`,
TypeError,
);
// Since we're already ensured candidate is an array, it should not be
// possible for the following test to fail
checkNormalProperty(candidate, 'length', 'string', false, assertChecker);
const len = candidate.length;
for (let i = 0; i < len; i += 1) {
checkNormalProperty(candidate, i, 'number', true, assertChecker);
}
assert(
// +1 for the 'length' property itself.
ownKeys(candidate).length === len + 1,
X`Arrays must not have non-indexes: ${candidate}`,
TypeError,
);
// Recursively validate that each member is passable.
CopyArrayHelper.every(candidate, v => !!passStyleOfRecur(v));
},

every: (passable, fn) =>
// Note that we explicitly call `fn` with only the arguments we want
// to provide.
passable.every((v, i) => fn(v, i)),
});
77 changes: 77 additions & 0 deletions packages/marshal/src/helpers/copyRecord.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// @ts-check

// eslint-disable-next-line spaced-comment
/// <reference types="ses"/>

import {
assertChecker,
canBeMethod,
checkNormalProperty,
} from './passStyleHelpers.js';

import '../types.js';
import './internal-types.js';
/**
* TODO Why do I need these?
*
* @typedef {import('./internal-types.js').PassStyleHelper} PassStyleHelper
*/
import '@agoric/assert/exported.js';

const { details: X } = assert;
const { ownKeys } = Reflect;
const {
getPrototypeOf,
getOwnPropertyDescriptors,
entries,
prototype: objectPrototype,
} = Object;

/**
*
* @type {PassStyleHelper}
*/
export const CopyRecordHelper = harden({
styleName: 'copyRecord',

canBeValid: (candidate, check = x => x) => {
const proto = getPrototypeOf(candidate);
if (proto !== objectPrototype && proto !== null) {
return check(false, X`Unexpected prototype for: ${candidate}`);
}
const descs = getOwnPropertyDescriptors(candidate);
const descKeys = ownKeys(descs);

for (const descKey of descKeys) {
if (typeof descKey !== 'string') {
// Pass by copy
return check(
false,
X`Records can only have string-named own properties: ${candidate}`,
);
}
const desc = descs[descKey];
if (canBeMethod(desc.value)) {
return check(
false,
X`Records cannot contain non-far functions because they may be methods of an implicit Remotable: ${candidate}`,
);
}
}
return true;
},

assertValid: (candidate, passStyleOfRecur) => {
CopyRecordHelper.canBeValid(candidate, assertChecker);
for (const name of ownKeys(candidate)) {
checkNormalProperty(candidate, name, 'string', true, assertChecker);
}
// Recursively validate that each member is passable.
CopyRecordHelper.every(candidate, v => !!passStyleOfRecur(v));
},

every: (passable, fn) =>
// Note that we explicitly call `fn` with only the arguments we want
// to provide.
entries(passable).every(([k, v]) => fn(v, k)),
});
125 changes: 125 additions & 0 deletions packages/marshal/src/helpers/error.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
// @ts-check

// eslint-disable-next-line spaced-comment
/// <reference types="ses"/>

import '../types.js';
import './internal-types.js';
/**
* TODO Why do I need these?
*
* @typedef {import('./internal-types.js').PassStyleHelper} PassStyleHelper
*/
import '@agoric/assert/exported.js';
import { assertChecker } from './passStyleHelpers.js';

const { details: X } = assert;
const { getPrototypeOf, getOwnPropertyDescriptors } = Object;
const { ownKeys } = Reflect;

// TODO: Maintenance hazard: Coordinate with the list of errors in the SES
// whilelist. Currently, both omit AggregateError, which is now standard. Both
// must eventually include it.
erights marked this conversation as resolved.
Show resolved Hide resolved
const errorConstructors = new Map([
['Error', Error],
['EvalError', EvalError],
['RangeError', RangeError],
['ReferenceError', ReferenceError],
['SyntaxError', SyntaxError],
['TypeError', TypeError],
['URIError', URIError],
]);

export const getErrorConstructor = name => errorConstructors.get(name);
harden(getErrorConstructor);

/**
* Validating error objects are passable raises a tension between security
* vs preserving diagnostic information. For errors, we need to remember
* the error itself exists to help us diagnose a bug that's likely more
* pressing than a validity bug in the error itself. Thus, whenever it is safe
* to do so, we prefer to let the error test succeed and to couch these
* complaints as notes on the error.
*
* To resolve this, such a malformed error object will still pass
* `canBeValid(err)` with no check, so marshal can use this for top
* level error to report from, even if it would not actually validate.
* Instead, the diagnostics that `assertError` would have reported are
* attached as notes to the malformed error. Thus, a malformed
* error is passable by itself, but not as part of a passable structure.
*
* @type {PassStyleHelper}
*/
export const ErrorHelper = harden({
styleName: 'error',

canBeValid: (candidate, check = x => x) => {
// TODO: Need a better test than instanceof
if (!(candidate instanceof Error)) {
return check(false, X`Error expected: ${candidate}`);
}
const proto = getPrototypeOf(candidate);
const { name } = candidate;
const EC = getErrorConstructor(name);
if (!EC || EC.prototype !== proto) {
const note = X`Errors must inherit from an error class .prototype ${candidate}`;
// Only terminate if check throws
check(false, note);
assert.note(candidate, note);
}

const {
message: mDesc,
// Allow but ignore only extraneous own `stack` property.
stack: _optStackDesc,
...restDescs
} = getOwnPropertyDescriptors(candidate);
if (ownKeys(restDescs).length >= 1) {
const note = X`Passed Error has extra unpassed properties ${restDescs}`;
// Only terminate if check throws
check(false, note);
assert.note(candidate, note);
}
if (mDesc) {
if (typeof mDesc.value !== 'string') {
const note = X`Passed Error "message" ${mDesc} must be a string-valued data property.`;
// Only terminate if check throws
check(false, note);
assert.note(candidate, note);
}
if (mDesc.enumerable) {
const note = X`Passed Error "message" ${mDesc} must not be enumerable`;
// Only terminate if check throws
check(false, note);
assert.note(candidate, note);
}
}
return true;
},

assertValid: candidate => {
ErrorHelper.canBeValid(candidate, assertChecker);
},

every: (_passable, _fn) => true,
});

/**
* Return a new passable error that propagates the diagnostic info of the
* original, and is linked to the original as a note.
*
* @param {Error} err
* @returns {Error}
*/
export const toPassableError = err => {
const { name, message } = err;

const EC = getErrorConstructor(`${name}`) || Error;
const newError = harden(new EC(`${message}`));
// Even the cleaned up error copy, if sent to the console, should
// cause hidden diagnostic information of the original error
// to be logged.
assert.note(newError, X`copied from error ${err}`);
return newError;
};
harden(toPassableError);
45 changes: 45 additions & 0 deletions packages/marshal/src/helpers/internal-types.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// @ts-check

// eslint-disable-next-line spaced-comment
/// <reference path="../extra-types.d.ts" />

import '../types.js';
erights marked this conversation as resolved.
Show resolved Hide resolved

/**
* @callback Checker
* @param {boolean} cond
* @param {Details=} details
* @returns {boolean}
*/

/**
* The PassStyleHelper are only used to make a `passStyleOf` function.
* Thus, it should not depend on an ambient one. Rather, each helper should be
* pure, and get its `passStyleOf` or similar function from its caller.
*
* For those methods that have a last `passStyleOf` or `passStyleOfRecur`,
* they must defend against the other arguments being malicious, but may
* *assume* that `passStyleOfRecur` does what it is supposed to do.
* Each such method is not trying to defend itself against a malicious
* `passStyleOfRecur`, though it may defend against some accidents.
*
* @typedef {Object} PassStyleHelper
*
* @property {PassStyle} styleName
*
* @property {(candidate: any, check?: Checker) => boolean} canBeValid
* If `canBeValid` returns true, then the candidate would
* definitely not be valid for any of the other helpers.
* `assertValid` still needs to be called to determine if it
* actually is valid.
*
* @property {(candidate: any,
* passStyleOfRecur: PassStyleOf
* ) => void} assertValid
*
* @property {(passable: Passable,
* fn: (passable: Passable, index: any) => boolean
* ) => boolean} every
* For recuring through the nested passable structure. Like
* `Array.prototype.every`, return `false` to stop early.
*/
Loading