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 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
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"
]
]
}
}
},
"packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e"
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

}
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
206 changes: 206 additions & 0 deletions packages/contracts/src/EmailSigner.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
// 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 {IERC1271} from "./interfaces/IERC1271.sol";
import {ERC1271} from "./libraries/ERC1271.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 EmailSigner 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.
address public dkimRegistryAddr;
/// An instance of the Verifier contract.
address public verifierAddr;
/// The templateId of the sign hash command.
uint256 public templateId;

constructor() {
_disableInitializers();
}

/// @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;
if (_dkimRegistryAddr == address(0))
revert InvalidDKIMRegistryAddress();
if (address(dkimRegistryAddr) != address(0))
revert DKIMRegistryAlreadyInitialized();
dkimRegistryAddr = _dkimRegistryAddr;
emit DKIMRegistryUpdated(_dkimRegistryAddr);

if (_verifierAddr == address(0)) revert InvalidVerifierAddress();
if (address(verifierAddr) != address(0))
revert VerifierAlreadyInitialized();
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 {
if (_dkimRegistryAddr == address(0))
revert InvalidDKIMRegistryAddress();
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 {
if (_verifierAddr == address(0)) revert InvalidVerifierAddress();
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 view {
if (templateId != emailAuthMsg.templateId) revert InvalidTemplateId();
string[] memory signHashTemplate = new string[](2);
signHashTemplate[0] = "signHash";
signHashTemplate[1] = "{uint}";
if (
!IDKIMRegistry(dkimRegistryAddr).isDKIMPublicKeyHashValid(
emailAuthMsg.proof.domainName,
emailAuthMsg.proof.publicKeyHash
)
) revert InvalidDKIMPublicKeyHash();

if (accountSalt != emailAuthMsg.proof.accountSalt)
revert InvalidAccountSalt();

if (
bytes(emailAuthMsg.proof.maskedCommand).length >
IVerifier(verifierAddr).commandBytes()
) revert InvalidMaskedCommandLength();

if (
emailAuthMsg.skippedCommandPrefix >=
IVerifier(verifierAddr).commandBytes()
) revert InvalidSkippedCommandPrefixSize();

// 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 InvalidCommand();
}
}

if (!IVerifier(verifierAddr).verifyEmailProof(emailAuthMsg.proof))
revert InvalidEmailProof();
}

/// @notice Validates a signature of an EmailAuthMsg. ERC1271 compatible.
/// @param _hash The hash of the EmailAuthMsg.
/// @param _signature The signature of the EmailAuthMsg.
/// @return bytes4(0) if the signature is invalid, ERC1271.MAGIC_VALUE if the signature is valid.
function isValidSignature(
bytes32 _hash,
bytes calldata _signature
) public view returns (bytes4) {
// signature is a serialized EmailAuthMsg
EmailAuthMsg memory emailAuthMsg = abi.decode(
_signature,
(EmailAuthMsg)
);

authEmail(emailAuthMsg); // reverts if invalid
bytes32 signedHash = abi.decode(
emailAuthMsg.commandParams[0],
(bytes32)
);

// signature is valid
if (signedHash == _hash) return ERC1271.MAGIC_VALUE;

// signature is invalid
return bytes4(0);
}

/// @notice Validates a signature of an EmailAuthMsg. Legacy ERC1271 compatible.
/// @param _data The data to validate the signature against.
/// @param _signature The signature to validate.
/// @return bytes4(0) if the signature is invalid, ERC1271.MAGIC_VALUE_LEGACY if the signature is valid.
function isValidSignature(
bytes calldata _data,
bytes calldata _signature
) external view returns (bytes4) {
if (
isValidSignature(keccak256(_data), _signature) ==
ERC1271.MAGIC_VALUE
) return ERC1271.LEGACY_MAGIC_VALUE;
return bytes4(0);
}

/// @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) {
if (numBytes > bytes(str).length)
revert InvalidSkippedCommandPrefixSize();

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);
}
}
32 changes: 32 additions & 0 deletions packages/contracts/src/interfaces/IERC1271.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IERC1271 {
/**
* @dev Validates if a signature is valid for the provided data. Used in older EIP1271 versions.
* @param _data Raw data that was signed
* @param _signature Signature of the data
* @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 _signature
) external view returns (bytes4);

/**
* @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
* @param _signature Signature of the hash
* @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 _signature
) external view returns (bytes4);
}
63 changes: 63 additions & 0 deletions packages/contracts/src/interfaces/IEmailAuth.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.12;

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

/// @notice Custom errors for email authentication
interface IEmailAuthErrors {
/// @notice Thrown when the DKIM registry address is zero
error InvalidDKIMRegistryAddress();
/// @notice Thrown when attempting to initialize DKIM registry that's already set
error DKIMRegistryAlreadyInitialized();
/// @notice Thrown when the verifier address is zero
error InvalidVerifierAddress();
/// @notice Thrown when attempting to initialize verifier that's already set
error VerifierAlreadyInitialized();
/// @notice Thrown when the template ID doesn't match
error InvalidTemplateId();
/// @notice Thrown when the DKIM public key hash verification fails
error InvalidDKIMPublicKeyHash();
/// @notice Thrown when the account salt doesn't match
error InvalidAccountSalt();
/// @notice Thrown when the masked command length exceeds the maximum
error InvalidMaskedCommandLength();
/// @notice Thrown when the skipped command prefix size is invalid
error InvalidSkippedCommandPrefixSize();
/// @notice Thrown when the command format is invalid
error InvalidCommand();
/// @notice Thrown when the email proof verification fails
error InvalidEmailProof();
}

/// @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 is IEmailAuthErrors {
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;
}
24 changes: 24 additions & 0 deletions packages/contracts/src/libraries/ERC1271.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity ^0.8.20;

/**
* @title ERC-1271 Magic Values
* @dev Library that defines constants for ERC-1271 related magic values.
* @custom:security-contact bounty@safe.global
*/
library ERC1271 {
/**
* @notice ERC-1271 magic value returned on valid signatures.
* @dev Value is derived from `bytes4(keccak256("isValidSignature(bytes32,bytes)")`.
*/
bytes4 internal constant MAGIC_VALUE = 0x1626ba7e;

/**
* @notice Legacy EIP-1271 magic value returned on valid signatures.
* @dev This value was used in previous drafts of the EIP-1271 standard, but replaced by
* {MAGIC_VALUE} in the final version.
*
* Value is derived from `bytes4(keccak256("isValidSignature(bytes,bytes)")`.
*/
bytes4 internal constant LEGACY_MAGIC_VALUE = 0x20c13b0b;
}
Loading