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

Refactor/email auth simplification #104

Open
wants to merge 14 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 9 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
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -40,5 +40,6 @@
"jest"
]
]
}
}
},
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why was this needed?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is not strictly needed and can be removed safely. That said, benefits are mainly consistency across environments and corepack compatibility

"packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e"
}
51 changes: 51 additions & 0 deletions packages/contracts/src/ERC1271SignatureValidator.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract ERC1271SignatureValidator {
/// Mapping to store if a hash has been signed.
mapping(bytes32 => bool) public isHashSigned;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Where is this updated?
  2. What do you think about verifying proof etc directly in isValidSignature? And state updates can be handled in higher level logic such as how contract signatures work on Safes https://github.com/safe-global/safe-smart-account/blob/1c8b24a0a438e8c2cd089a9d830d1688a47a28d5/contracts/Safe.sol#L140-L142

This way the EmailSigner can be used to verify "signatures" in a single step rather than approve + verify

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where is this updated?

this part is actually not implemented here yet. And I think your second point is a great idea for how to build this.


// Magic value returned by older versions of EIP1271 when validating data and signature
// bytes4(keccak256("isValidSignature(bytes,bytes)")). Used by Gnosis Safe and others.
bytes4 internal constant EIP1271_MAGIC_VALUE_DATA = 0x20c13b0b;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice yes, we should do that.


// Magic value returned by newer versions of EIP1271 when validating hash and signature
// bytes4(keccak256("isValidSignature(bytes32,bytes)"))
bytes4 internal constant EIP1271_MAGIC_VALUE_HASH = 0x1626ba7e;

/**
* @dev Validates if a signature is valid for the provided data. Used in older EIP1271 versions.
* @param _data Raw data that was signed
* @return Magic value 0x20c13b0b if signature is valid for the data, 0x0 otherwise
*
* MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
* MUST allow external calls
*/
function isValidSignature(
bytes calldata _data,
bytes calldata
) public view returns (bytes4) {
if (isHashSigned[keccak256(_data)]) {
return EIP1271_MAGIC_VALUE_DATA;
}
return bytes4(0);
}

/**
* @dev Validates if a signature is valid for the provided hash. Used in newer EIP1271 versions.
* @param _hash Hash of the data that was signed
* @return magicValue Magic value 0x1626ba7e if signature is valid for the hash, 0x0 otherwise
*
* MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5)
* MUST allow external calls
*/
function isValidSignature(
bytes32 _hash,
bytes calldata
) public view returns (bytes4) {
if (isHashSigned[_hash]) {
return EIP1271_MAGIC_VALUE_HASH;
}
return bytes4(0);
}
}
23 changes: 2 additions & 21 deletions packages/contracts/src/EmailAuth.sol
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,12 @@ import {CommandUtils} from "./libraries/CommandUtils.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";

/// @notice Struct to hold the email authentication/authorization message.
struct EmailAuthMsg {
/// @notice The ID of the command template that the command in the email body should satisfy.
uint templateId;
/// @notice The parameters in the command of the email body, which should be taken according to the specified command template.
bytes[] commandParams;
/// @notice The number of skipped bytes in the command.
uint skippedCommandPrefix;
/// @notice The email proof containing the zk proof and other necessary information for the email verification by the verifier contract.
EmailProof proof;
}
import {IEmailAuth, EmailAuthMsg} from "./interfaces/IEmailAuth.sol";

/// @title Email Authentication/Authorization Contract
/// @notice This contract provides functionalities for the authentication of the email sender and the authentication of the message in the command part of the email body using DKIM and custom verification logic.
/// @dev Inherits from OwnableUpgradeable and UUPSUpgradeable for upgradeability and ownership management.
contract EmailAuth is OwnableUpgradeable, UUPSUpgradeable {
contract EmailAuth is OwnableUpgradeable, UUPSUpgradeable, IEmailAuth {
/// The CREATE2 salt of this contract defined as a hash of an email address and an account code.
bytes32 public accountSalt;
/// An instance of the DKIM registry contract.
Expand All @@ -42,17 +31,9 @@ contract EmailAuth is OwnableUpgradeable, UUPSUpgradeable {
/// A boolean whether timestamp check is enabled or not.
bool public timestampCheckEnabled;

event DKIMRegistryUpdated(address indexed dkimRegistry);
event VerifierUpdated(address indexed verifier);
event CommandTemplateInserted(uint indexed templateId);
event CommandTemplateUpdated(uint indexed templateId);
event CommandTemplateDeleted(uint indexed templateId);
event EmailAuthed(
bytes32 indexed emailNullifier,
bytes32 indexed accountSalt,
bool isCodeExist,
uint templateId
);
event TimestampCheckEnabled(bool enabled);

modifier onlyController() {
Expand Down
188 changes: 188 additions & 0 deletions packages/contracts/src/EmailAuthSigner.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;

import {EmailProof} from "./utils/Verifier.sol";
import {IDKIMRegistry} from "@zk-email/contracts/DKIMRegistry.sol";
import {IVerifier, EmailProof} from "./interfaces/IVerifier.sol";
import {CommandUtils} from "./libraries/CommandUtils.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {IEmailAuth, EmailAuthMsg} from "./interfaces/IEmailAuth.sol";
import {ERC1271SignatureValidator} from "./ERC1271SignatureValidator.sol";

/// @title Email Authentication/Authorization Contract for Signature-like Usage
/// @notice This contract provides a signature-like authentication mechanism using emails.
/// Similar to how ECDSA signatures work, this contract only verifies the authenticity
/// of an email command without handling replay protection or nullifiers - these should
/// be implemented at the application level.
/// @dev Unlike EmailAuth.sol which handles nullifiers internally, this contract is designed
/// to be used like a signature verification mechanism where the calling contract manages
/// its own replay protection.
contract EmailAuthSigner is
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thoughts an EmailSigner?

OwnableUpgradeable,
UUPSUpgradeable,
IEmailAuth,
ERC1271SignatureValidator
{
/// The CREATE2 salt of this contract defined as a hash of an email address and an account code.
bytes32 public accountSalt;
/// An instance of the DKIM registry contract.
address public dkimRegistryAddr;
/// An instance of the Verifier contract.
address public verifierAddr;
/// The templateId of the sign hash command.
uint256 public templateId;

constructor() {}
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since it's a security feature, I think it's worth adding to EmailAuth constructor too


/// @notice Initialize the contract with an initial owner, account salt, DKIM registry address, and verifier address.
/// @param _initialOwner The address of the initial owner.
/// @param _accountSalt The account salt to derive CREATE2 address of this contract.
/// @param _dkimRegistryAddr The address of the DKIM registry contract.
/// @param _verifierAddr The address of the verifier contract.
/// @param _templateId The templateId of the sign hash command.
function initialize(
address _initialOwner,
bytes32 _accountSalt,
address _dkimRegistryAddr,
address _verifierAddr,
uint256 _templateId
) public initializer {
__Ownable_init(_initialOwner);
accountSalt = _accountSalt;
templateId = _templateId;
require(
_dkimRegistryAddr != address(0),
"invalid dkim registry address"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As discussed in breakout call, lets move to use custom errors if you're in agreement

);
require(
address(dkimRegistryAddr) == address(0),
"dkim registry already initialized"
);
dkimRegistryAddr = _dkimRegistryAddr;
emit DKIMRegistryUpdated(_dkimRegistryAddr);

require(_verifierAddr != address(0), "invalid verifier address");
require(
address(verifierAddr) == address(0),
"verifier already initialized"
);
verifierAddr = _verifierAddr;
emit VerifierUpdated(_verifierAddr);
}

/// @notice Updates the address of the DKIM registry contract.
/// @param _dkimRegistryAddr The new address of the DKIM registry contract.
function updateDKIMRegistry(address _dkimRegistryAddr) public onlyOwner {
require(
_dkimRegistryAddr != address(0),
"invalid dkim registry address"
);
dkimRegistryAddr = _dkimRegistryAddr;
emit DKIMRegistryUpdated(_dkimRegistryAddr);
}

/// @notice Updates the address of the verifier contract.
/// @param _verifierAddr The new address of the verifier contract.
function updateVerifier(address _verifierAddr) public onlyOwner {
require(_verifierAddr != address(0), "invalid verifier address");
verifierAddr = _verifierAddr;
emit VerifierUpdated(_verifierAddr);
}

/// @notice Authenticate the email sender and authorize the message in the email command.
/// @dev This function only verifies the authenticity of the email and command, without
/// handling replay protection. The calling contract should implement its own mechanisms
/// to prevent replay attacks, similar to how nonces are used with ECDSA signatures.
/// @param emailAuthMsg The email auth message containing all necessary information for authentication.
function authEmail(EmailAuthMsg memory emailAuthMsg) public {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Related to above comment on 1271 validation - thinking that verifySignature is executing most of this logic

require(templateId == emailAuthMsg.templateId, "invalid template id");
string[] memory signHashTemplate = new string[](2);
signHashTemplate[0] = "signHash";
signHashTemplate[1] = "{uint}";
require(
IDKIMRegistry(dkimRegistryAddr).isDKIMPublicKeyHashValid(
emailAuthMsg.proof.domainName,
emailAuthMsg.proof.publicKeyHash
) == true,
"invalid dkim public key hash"
);
require(
accountSalt == emailAuthMsg.proof.accountSalt,
"invalid account salt"
);
require(
bytes(emailAuthMsg.proof.maskedCommand).length <=
IVerifier(verifierAddr).commandBytes(),
"invalid masked command length"
);
require(
emailAuthMsg.skippedCommandPrefix <
IVerifier(verifierAddr).commandBytes(),
"invalid size of the skipped command prefix"
);

// Construct an expectedCommand from template and the values of emailAuthMsg.commandParams.
string memory trimmedMaskedCommand = removePrefix(
emailAuthMsg.proof.maskedCommand,
emailAuthMsg.skippedCommandPrefix
);
string memory expectedCommand = "";
for (uint stringCase = 0; stringCase < 3; stringCase++) {
expectedCommand = CommandUtils.computeExpectedCommand(
emailAuthMsg.commandParams,
signHashTemplate,
stringCase
);
if (Strings.equal(expectedCommand, trimmedMaskedCommand)) {
break;
}
if (stringCase == 2) {
revert("invalid command");
}
}

require(
IVerifier(verifierAddr).verifyEmailProof(emailAuthMsg.proof) ==
true,
"invalid email proof"
);

emit EmailAuthed(
emailAuthMsg.proof.emailNullifier,
emailAuthMsg.proof.accountSalt,
emailAuthMsg.proof.isCodeExist,
emailAuthMsg.templateId
);
}

/// @notice Upgrade the implementation of the proxy.
/// @param newImplementation Address of the new implementation.
function _authorizeUpgrade(
address newImplementation
) internal override onlyOwner {}

/// @notice Remove a prefix from a string.
/// @param str The original string.
/// @param numBytes The number of bytes to remove from the start of the string.
/// @return The string with the prefix removed.
function removePrefix(
string memory str,
uint numBytes
) private pure returns (string memory) {
require(
numBytes <= bytes(str).length,
"Invalid size of the removed bytes"
);

bytes memory strBytes = bytes(str);
bytes memory result = new bytes(strBytes.length - numBytes);

for (uint i = numBytes; i < strBytes.length; i++) {
result[i - numBytes] = strBytes[i];
}

return string(result);
}
}
37 changes: 37 additions & 0 deletions packages/contracts/src/interfaces/IEmailAuth.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;

import {EmailProof} from "../utils/Verifier.sol";

/// @notice Struct to hold the email authentication/authorization message.
struct EmailAuthMsg {
/// @notice The ID of the command template that the command in the email body should satisfy.
uint templateId;
/// @notice The parameters in the command of the email body, which should be taken according to the specified command template.
bytes[] commandParams;
/// @notice The number of skipped bytes in the command.
uint skippedCommandPrefix;
/// @notice The email proof containing the zk proof and other necessary information for the email verification by the verifier contract.
EmailProof proof;
}

/// @title Interface for Email Authentication/Authorization Contract
interface IEmailAuth {
event DKIMRegistryUpdated(address indexed dkimRegistry);
event VerifierUpdated(address indexed verifier);
event EmailAuthed(
bytes32 indexed emailNullifier,
bytes32 indexed accountSalt,
bool isCodeExist,
uint templateId
);

function accountSalt() external view returns (bytes32);
function dkimRegistryAddr() external view returns (address);
function verifierAddr() external view returns (address);

function updateDKIMRegistry(address _dkimRegistryAddr) external;
function updateVerifier(address _verifierAddr) external;

function authEmail(EmailAuthMsg memory emailAuthMsg) external;
}
7 changes: 4 additions & 3 deletions packages/contracts/test/DKIMRegistryUpgrade.t.sol
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import "forge-std/console.sol";

import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "../src/EmailAuth.sol";
import {IEmailAuth} from "../src/interfaces/IEmailAuth.sol";
import "../src/utils/Verifier.sol";
import "../src/utils/ECDSAOwnedDKIMRegistry.sol";
import {ERC1967Proxy} from "@openzeppelin/contracts/proxy/ERC1967/ERC1967Proxy.sol";
Expand All @@ -19,10 +20,10 @@ contract DKIMRegistryUpgradeTest is StructHelper {
vm.startPrank(deployer);
emailAuth.initialize(deployer, accountSalt, deployer);
vm.expectEmit(true, false, false, false);
emit EmailAuth.VerifierUpdated(address(verifier));
emit IEmailAuth.VerifierUpdated(address(verifier));
emailAuth.updateVerifier(address(verifier));
vm.expectEmit(true, false, false, false);
emit EmailAuth.DKIMRegistryUpdated(address(dkim));
emit IEmailAuth.DKIMRegistryUpdated(address(dkim));
emailAuth.updateDKIMRegistry(address(dkim));
UserOverrideableDKIMRegistry overrideableDkimImpl = new UserOverrideableDKIMRegistry();
ERC1967Proxy overrideableDkimProxy = new ERC1967Proxy(
Expand Down Expand Up @@ -64,7 +65,7 @@ contract DKIMRegistryUpgradeTest is StructHelper {
assertEq(emailAuth.lastTimestamp(), 0);
vm.startPrank(deployer);
vm.expectEmit(true, true, true, true);
emit EmailAuth.EmailAuthed(
emit IEmailAuth.EmailAuthed(
emailAuthMsg.proof.emailNullifier,
emailAuthMsg.proof.accountSalt,
emailAuthMsg.proof.isCodeExist,
Expand Down
Loading
Loading