Search in sources :

Example 1 with TomlParseResult

use of org.apache.tuweni.toml.TomlParseResult in project couchbase-elasticsearch-connector by couchbase.

the class ConfigHelper method readPassword.

public static String readPassword(ConfigTable parent, String parentName, String keyName) {
    final String pathToPassword = parent.getString(keyName).orElseThrow(() -> new ConfigException(parentName + "." + keyName + " must not be null"));
    final File passwordFile = resolveIfRelative(pathToPassword);
    try (InputStream is = new FileInputStream(passwordFile)) {
        final TomlParseResult config = Toml.parse(resolveVariables(is));
        if (config.hasErrors()) {
        // DO NOT REPORT ERRORS, AS THAT MIGHT LEAK THE CONTENTS OF THE FILE TO AN ATTACKER
        // trying to use the connector's elevated privileges to read a completely
        // unrelated file.
        }
        final String password = config.getString("password");
        if (password == null) {
            throw new ConfigException("Failed to parse " + passwordFile + " : Expected a TOML file with contents like: password = 'swordfish'");
        }
        return password;
    } catch (FileNotFoundException e) {
        throw new ConfigException("Error reading config at " + parent.inputPositionOf(keyName) + "; File not found: " + passwordFile);
    } catch (IOException e) {
        LOGGER.error("Failed to read password from file {}", passwordFile, e);
        throw new ConfigException(e.getMessage());
    }
}
Also used : FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) File(java.io.File) FileInputStream(java.io.FileInputStream) TomlParseResult(org.apache.tuweni.toml.TomlParseResult)

Example 2 with TomlParseResult

use of org.apache.tuweni.toml.TomlParseResult in project signers by ConsenSys.

the class SigningMetadataTomlConfigLoader method getMetadataInfo.

private Optional<SigningMetadataFile> getMetadataInfo(final Path file) {
    final String filename = file.getFileName().toString();
    try {
        final TomlParseResult result = TomlConfigFileParser.loadConfigurationFromFile(file.toAbsolutePath().toString());
        final Optional<TomlTableAdapter> signingTable = getSigningTableFrom(file.getFileName().toString(), result);
        if (signingTable.isEmpty()) {
            return Optional.empty();
        }
        final String type = signingTable.get().getString("type");
        if (SignerType.fromString(type).equals(SignerType.FILE_BASED_SIGNER)) {
            return getFileBasedSigningMetadataFromToml(filename, result);
        } else if (SignerType.fromString(type).equals(SignerType.AZURE_SIGNER)) {
            return getAzureBasedSigningMetadataFromToml(file.getFileName().toString(), result);
        } else if (SignerType.fromString(type).equals(SignerType.HASHICORP_SIGNER)) {
            return getHashicorpMetadataFromToml(file, result);
        } else if (SignerType.fromString(type).equals(SignerType.RAW_SIGNER)) {
            return getRawMetadataFromToml(filename, result);
        } else {
            LOG.error("Unknown signing type in metadata: " + type);
            return Optional.empty();
        }
    } catch (final IllegalArgumentException | TomlInvalidTypeException e) {
        final String errorMsg = String.format("%s failed to decode: %s", filename, e.getMessage());
        LOG.error(errorMsg);
        return Optional.empty();
    } catch (final Exception e) {
        LOG.error("Could not load TOML file " + file, e);
        return Optional.empty();
    }
}
Also used : TomlInvalidTypeException(org.apache.tuweni.toml.TomlInvalidTypeException) TomlInvalidTypeException(org.apache.tuweni.toml.TomlInvalidTypeException) IOException(java.io.IOException) TomlParseResult(org.apache.tuweni.toml.TomlParseResult)

Example 3 with TomlParseResult

use of org.apache.tuweni.toml.TomlParseResult in project besu by hyperledger.

the class RpcAuthFileValidator method validate.

public static String validate(final CommandLine commandLine, final String filename, final String type) {
    final File authfile = new File(filename);
    if (!authfile.exists()) {
        throw new ParameterException(commandLine, "The specified RPC " + type + " authentication credential file '" + filename + "' does not exist");
    }
    final TomlParseResult tomlParseResult;
    try {
        tomlParseResult = TomlConfigFileParser.loadConfigurationFromFile(filename);
    } catch (IOException e) {
        throw new ParameterException(commandLine, "An error occurred while opening the specified RPC " + type + " authentication configuration file.");
    } catch (Exception e) {
        throw new ParameterException(commandLine, "Invalid RPC " + type + " authentication credentials file: " + e.getMessage());
    }
    if (tomlParseResult.hasErrors()) {
        throw new ParameterException(commandLine, "An error occurred while parsing the specified RPC authentication configuration file.");
    }
    if (!verifyAllUsersHavePassword(tomlParseResult)) {
        throw new ParameterException(commandLine, "RPC user specified without password.");
    }
    if (!verifyAllEntriesHaveValues(tomlParseResult)) {
        throw new ParameterException(commandLine, "RPC authentication configuration file contains invalid values.");
    }
    return filename;
}
Also used : ParameterException(picocli.CommandLine.ParameterException) IOException(java.io.IOException) File(java.io.File) ParameterException(picocli.CommandLine.ParameterException) IOException(java.io.IOException) TomlParseResult(org.apache.tuweni.toml.TomlParseResult)

Example 4 with TomlParseResult

use of org.apache.tuweni.toml.TomlParseResult in project besu by hyperledger.

the class BesuCommandTest method tomlThatConfiguresEverythingExceptPermissioningToml.

@Test
public void tomlThatConfiguresEverythingExceptPermissioningToml() throws IOException {
    // Load a TOML that configures literally everything (except permissioning TOML config)
    final URL configFile = this.getClass().getResource("/everything_config.toml");
    final Path toml = createTempFile("toml", Resources.toByteArray(configFile));
    // Parse it.
    final CommandLine.Model.CommandSpec spec = parseCommand("--config-file", toml.toString()).spec;
    final TomlParseResult tomlResult = Toml.parse(toml);
    // Verify we configured everything
    final HashSet<CommandLine.Model.OptionSpec> options = new HashSet<>(spec.options());
    // Except for meta-options
    options.remove(spec.optionsMap().get("--config-file"));
    options.remove(spec.optionsMap().get("--help"));
    options.remove(spec.optionsMap().get("--version"));
    for (final String tomlKey : tomlResult.keySet()) {
        final CommandLine.Model.OptionSpec optionSpec = spec.optionsMap().get("--" + tomlKey);
        assertThat(optionSpec).describedAs("Option '%s' should be a configurable option.", tomlKey).isNotNull();
        // Verify TOML stores it by the appropriate type
        if (optionSpec.type().equals(Boolean.class)) {
            tomlResult.getBoolean(tomlKey);
        } else if (optionSpec.isMultiValue() || optionSpec.arity().max > 1) {
            tomlResult.getArray(tomlKey);
        } else if (optionSpec.type().equals(Double.class)) {
            tomlResult.getDouble(tomlKey);
        } else if (Number.class.isAssignableFrom(optionSpec.type())) {
            tomlResult.getLong(tomlKey);
        } else if (Wei.class.isAssignableFrom(optionSpec.type())) {
            tomlResult.getLong(tomlKey);
        } else if (Fraction.class.isAssignableFrom(optionSpec.type())) {
            tomlResult.getDouble(tomlKey);
        } else if (Percentage.class.isAssignableFrom(optionSpec.type())) {
            tomlResult.getLong(tomlKey);
        } else {
            tomlResult.getString(tomlKey);
        }
        options.remove(optionSpec);
    }
    assertThat(options.stream().filter(optionSpec -> !optionSpec.hidden()).map(CommandLine.Model.OptionSpec::longestName)).isEmpty();
}
Also used : Path(java.nio.file.Path) Arrays(java.util.Arrays) PermissioningConfiguration(org.hyperledger.besu.ethereum.permissioning.PermissioningConfiguration) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Level(org.apache.logging.log4j.Level) DEV(org.hyperledger.besu.cli.config.NetworkName.DEV) WebSocketConfiguration(org.hyperledger.besu.ethereum.api.jsonrpc.websocket.WebSocketConfiguration) MORDOR(org.hyperledger.besu.cli.config.NetworkName.MORDOR) MAINNET_BOOTSTRAP_NODES(org.hyperledger.besu.ethereum.p2p.config.DefaultDiscoveryConfiguration.MAINNET_BOOTSTRAP_NODES) Arrays.asList(java.util.Arrays.asList) GenesisConfigFile(org.hyperledger.besu.config.GenesisConfigFile) Map(java.util.Map) NET(org.hyperledger.besu.ethereum.api.jsonrpc.RpcApis.NET) SmartContractPermissioningConfiguration(org.hyperledger.besu.ethereum.permissioning.SmartContractPermissioningConfiguration) BigInteger(java.math.BigInteger) JsonObject(io.vertx.core.json.JsonObject) ETH(org.hyperledger.besu.ethereum.api.jsonrpc.RpcApis.ETH) Path(java.nio.file.Path) DEPRECATION_WARNING_MSG(org.hyperledger.besu.cli.util.CommandLineUtils.DEPRECATION_WARNING_MSG) GOERLI_DISCOVERY_URL(org.hyperledger.besu.ethereum.p2p.config.DefaultDiscoveryConfiguration.GOERLI_DISCOVERY_URL) MAINNET_DISCOVERY_URL(org.hyperledger.besu.ethereum.p2p.config.DefaultDiscoveryConfiguration.MAINNET_DISCOVERY_URL) Stream(java.util.stream.Stream) StandardMetricCategory(org.hyperledger.besu.metrics.StandardMetricCategory) Mockito.atMost(org.mockito.Mockito.atMost) JwtAlgorithm(org.hyperledger.besu.ethereum.api.jsonrpc.authentication.JwtAlgorithm) PrunerConfiguration(org.hyperledger.besu.ethereum.worldstate.PrunerConfiguration) MockitoJUnitRunner(org.mockito.junit.MockitoJUnitRunner) Mockito.mock(org.mockito.Mockito.mock) Hash(org.hyperledger.besu.datatypes.Hash) RunWith(org.junit.runner.RunWith) GOERLI(org.hyperledger.besu.cli.config.NetworkName.GOERLI) Bytes(org.apache.tuweni.bytes.Bytes) DEPENDENCY_WARNING_MSG(org.hyperledger.besu.cli.util.CommandLineUtils.DEPENDENCY_WARNING_MSG) Lists(com.google.common.collect.Lists) BONSAI(org.hyperledger.besu.ethereum.worldstate.DataStorageFormat.BONSAI) ArgumentMatchers.isNotNull(org.mockito.ArgumentMatchers.isNotNull) Wei(org.hyperledger.besu.datatypes.Wei) MergeConfigOptions(org.hyperledger.besu.config.MergeConfigOptions) TimeoutOptions(org.hyperledger.besu.ethereum.api.handlers.TimeoutOptions) KOTTI(org.hyperledger.besu.cli.config.NetworkName.KOTTI) Before(org.junit.Before) TomlParseResult(org.apache.tuweni.toml.TomlParseResult) Files(java.nio.file.Files) Resources(com.google.common.io.Resources) NatMethod(org.hyperledger.besu.nat.NatMethod) Mockito.times(org.mockito.Mockito.times) GraphQLConfiguration(org.hyperledger.besu.ethereum.api.graphql.GraphQLConfiguration) IOException(java.io.IOException) FileUtils(org.apache.commons.io.FileUtils) Test(org.junit.Test) SignatureAlgorithmFactory(org.hyperledger.besu.crypto.SignatureAlgorithmFactory) MetricsConfiguration(org.hyperledger.besu.metrics.prometheus.MetricsConfiguration) File(java.io.File) DataStorageConfiguration(org.hyperledger.besu.ethereum.worldstate.DataStorageConfiguration) WEB3(org.hyperledger.besu.ethereum.api.jsonrpc.RpcApis.WEB3) Paths(java.nio.file.Paths) PrivacyParameters(org.hyperledger.besu.ethereum.core.PrivacyParameters) EnodeURLImpl(org.hyperledger.besu.ethereum.p2p.peers.EnodeURLImpl) TlsConfiguration(org.hyperledger.besu.ethereum.api.tls.TlsConfiguration) URL(java.net.URL) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) Percentage(org.hyperledger.besu.util.number.Percentage) Mockito.verifyNoInteractions(org.mockito.Mockito.verifyNoInteractions) DEFAULT_BESU_SERVICE_NAME_FILTER(org.hyperledger.besu.nat.kubernetes.KubernetesNatManager.DEFAULT_BESU_SERVICE_NAME_FILTER) RINKEBY(org.hyperledger.besu.cli.config.NetworkName.RINKEBY) GOERLI_BOOTSTRAP_NODES(org.hyperledger.besu.ethereum.p2p.config.DefaultDiscoveryConfiguration.GOERLI_BOOTSTRAP_NODES) BesuInfo(org.hyperledger.besu.BesuInfo) After(org.junit.After) CLASSIC(org.hyperledger.besu.cli.config.NetworkName.CLASSIC) Mockito.atLeast(org.mockito.Mockito.atLeast) URI(java.net.URI) ROPSTEN(org.hyperledger.besu.cli.config.NetworkName.ROPSTEN) CommandLine(picocli.CommandLine) SyncMode(org.hyperledger.besu.ethereum.eth.sync.SyncMode) DEPRECATED_AND_USELESS_WARNING_MSG(org.hyperledger.besu.cli.util.CommandLineUtils.DEPRECATED_AND_USELESS_WARNING_MSG) MiningParameters(org.hyperledger.besu.ethereum.core.MiningParameters) Collectors(java.util.stream.Collectors) Toml(org.apache.tuweni.toml.Toml) MAINNET(org.hyperledger.besu.cli.config.NetworkName.MAINNET) List(java.util.List) RpcMethod(org.hyperledger.besu.ethereum.api.jsonrpc.RpcMethod) RINKEBY_BOOTSTRAP_NODES(org.hyperledger.besu.ethereum.p2p.config.DefaultDiscoveryConfiguration.RINKEBY_BOOTSTRAP_NODES) PluginRpcRequest(org.hyperledger.besu.plugin.services.rpc.PluginRpcRequest) GasLimitCalculator(org.hyperledger.besu.ethereum.GasLimitCalculator) Optional(java.util.Optional) ENGINE(org.hyperledger.besu.ethereum.api.jsonrpc.RpcApis.ENGINE) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) AbstractAltBnPrecompiledContract(org.hyperledger.besu.evm.precompile.AbstractAltBnPrecompiledContract) PERM(org.hyperledger.besu.ethereum.api.jsonrpc.RpcApis.PERM) EthNetworkConfig(org.hyperledger.besu.cli.config.EthNetworkConfig) SynchronizerConfiguration(org.hyperledger.besu.ethereum.eth.sync.SynchronizerConfiguration) Address(org.hyperledger.besu.datatypes.Address) Function(java.util.function.Function) HashSet(java.util.HashSet) ArgumentCaptor(org.mockito.ArgumentCaptor) JsonRpcConfiguration(org.hyperledger.besu.ethereum.api.jsonrpc.JsonRpcConfiguration) UTF_8(java.nio.charset.StandardCharsets.UTF_8) StringEscapeUtils(org.apache.commons.text.StringEscapeUtils) Mockito.when(org.mockito.Mockito.when) Mockito.verify(org.mockito.Mockito.verify) EnodeURL(org.hyperledger.besu.plugin.data.EnodeURL) Mockito(org.mockito.Mockito) RINKEBY_DISCOVERY_URL(org.hyperledger.besu.ethereum.p2p.config.DefaultDiscoveryConfiguration.RINKEBY_DISCOVERY_URL) Rule(org.junit.Rule) Ignore(org.junit.Ignore) Fraction(org.hyperledger.besu.util.number.Fraction) PrivateMarkerTransactionFactory(org.hyperledger.besu.plugin.services.privacy.PrivateMarkerTransactionFactory) LocalPermissioningConfiguration(org.hyperledger.besu.ethereum.permissioning.LocalPermissioningConfiguration) Collections(java.util.Collections) PkiKeyStoreConfiguration(org.hyperledger.besu.pki.config.PkiKeyStoreConfiguration) TemporaryFolder(org.junit.rules.TemporaryFolder) Fraction(org.hyperledger.besu.util.number.Fraction) GOERLI_DISCOVERY_URL(org.hyperledger.besu.ethereum.p2p.config.DefaultDiscoveryConfiguration.GOERLI_DISCOVERY_URL) MAINNET_DISCOVERY_URL(org.hyperledger.besu.ethereum.p2p.config.DefaultDiscoveryConfiguration.MAINNET_DISCOVERY_URL) URL(java.net.URL) EnodeURL(org.hyperledger.besu.plugin.data.EnodeURL) RINKEBY_DISCOVERY_URL(org.hyperledger.besu.ethereum.p2p.config.DefaultDiscoveryConfiguration.RINKEBY_DISCOVERY_URL) TomlParseResult(org.apache.tuweni.toml.TomlParseResult) CommandLine(picocli.CommandLine) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 5 with TomlParseResult

use of org.apache.tuweni.toml.TomlParseResult in project besu by hyperledger.

the class TomlAuth method authenticate.

@Override
public void authenticate(final JsonObject authInfo, final Handler<AsyncResult<User>> resultHandler) {
    final String username = authInfo.getString("username");
    if (username == null) {
        resultHandler.handle(Future.failedFuture("No username provided"));
        return;
    }
    final String password = authInfo.getString("password");
    if (password == null) {
        resultHandler.handle(Future.failedFuture("No password provided"));
        return;
    }
    vertx.executeBlocking(f -> {
        TomlParseResult parseResult;
        try {
            parseResult = Toml.parse(options.getTomlPath());
        } catch (IOException e) {
            f.fail(e);
            return;
        }
        final TomlTable userData = parseResult.getTableOrEmpty("Users." + username);
        if (userData.isEmpty()) {
            f.fail("User not found");
            return;
        }
        final TomlUser tomlUser = readTomlUserFromTable(username, userData);
        if ("".equals(tomlUser.getPassword())) {
            f.fail("No password set for user");
            return;
        }
        checkPasswordHash(password, tomlUser.getPassword(), rs -> {
            if (rs.succeeded()) {
                f.complete(tomlUser);
            } else {
                f.fail(rs.cause());
            }
        });
    }, false, res -> {
        if (res.succeeded()) {
            resultHandler.handle(Future.succeededFuture((User) res.result()));
        } else {
            resultHandler.handle(Future.failedFuture(res.cause()));
        }
    });
}
Also used : TomlTable(org.apache.tuweni.toml.TomlTable) User(io.vertx.ext.auth.User) IOException(java.io.IOException) TomlParseResult(org.apache.tuweni.toml.TomlParseResult)

Aggregations

TomlParseResult (org.apache.tuweni.toml.TomlParseResult)10 IOException (java.io.IOException)7 File (java.io.File)4 List (java.util.List)3 Collectors (java.util.stream.Collectors)3 TomlArray (org.apache.tuweni.toml.TomlArray)3 BigInteger (java.math.BigInteger)2 Arrays (java.util.Arrays)2 Optional (java.util.Optional)2 Toml (org.apache.tuweni.toml.Toml)2 TomlTable (org.apache.tuweni.toml.TomlTable)2 ParameterException (picocli.CommandLine.ParameterException)2 Lists (com.google.common.collect.Lists)1 Resources (com.google.common.io.Resources)1 JsonObject (io.vertx.core.json.JsonObject)1 User (io.vertx.ext.auth.User)1 FileInputStream (java.io.FileInputStream)1 FileNotFoundException (java.io.FileNotFoundException)1 InputStream (java.io.InputStream)1 URI (java.net.URI)1