-
Notifications
You must be signed in to change notification settings - Fork 17
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
zkfriendly
wants to merge
14
commits into
main
Choose a base branch
from
refactor/email-auth-simplification
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
352acc8
chore: explicitly define packag manager
zkfriendly a2e4cd9
feat: simplified email signer authenticator
zkfriendly 45dd9a6
feat: implement IEmailAuth interface and refactor EmailAuth contract …
zkfriendly ec5df70
feat: integrate templateId into EmailAuthSigner and update related tests
zkfriendly 8b41189
docs: enhance EmailAuthSigner documentation for signature-like usage …
zkfriendly 1859c24
feat: ISignatureValidator with support for _data, _signature
zkfriendly 7cca7cb
feat: update ISignatureValidator to support both data and hash signat…
zkfriendly 51a99b2
feat: refactor EmailAuthSigner to inherit from SignatureValidator and…
zkfriendly 5ee69da
feat: rename SignatureValidator to ERC1271SignatureValidator and upda…
zkfriendly e74cff9
refactor: rename EmailAuthSigner to EmailSigner and update related te…
zkfriendly 6d4938f
refactor: replace require statements with custom errors in EmailSigne…
zkfriendly 6e6cb3f
refactor: remove ERC1271SignatureValidator and introduce IERC1271 int…
zkfriendly 6cd3cf8
feat: add ERC1271 signature validation methods to EmailSigner contract
zkfriendly d25d6a9
refactor: update EmailSigner constructor to disable initializers and …
zkfriendly File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
why was this needed?
There was a problem hiding this comment.
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