Assembly64Credentials.java

package ui.assembly64;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Base64;
import java.util.Map;
import java.util.Properties;

import static java.nio.charset.StandardCharsets.UTF_8;
import static server.restful.common.IServletSystemProperties.Assembly64Servlet.DEFAULT_CREDENTIALS_FILE;

/**
 * Private backend configuration. Never put these properties in the exported player configuration or server DTOs.
 */
final class Assembly64Credentials {
    static final String FILE_PROPERTY = "jsidplay2.assembly64.credentials";

    private final Properties properties = new Properties();

    static Assembly64Credentials load() throws IOException {
        Assembly64Credentials credentials = new Assembly64Credentials();
        try {
            String filename = System.getProperty(FILE_PROPERTY);
            if (filename != null) {
                credentials.read(Path.of(filename));
            } else {
                for (String dir : new String[]{System.getProperty("user.dir"), System.getProperty("user.home")}) {
                    Path file = new File(dir, DEFAULT_CREDENTIALS_FILE).toPath();
                    if (Files.exists(file)) credentials.read(file);
                }
            }
        } catch (IOException | IllegalArgumentException e) {
            // Configuration errors must not echo property values into HTTP responses or logs.
            throw new IOException("Cannot read private Assembly64 credentials configuration");
        }
        return credentials;
    }

    private void read(Path file) throws IOException {
        try (InputStream input = Files.newInputStream(file)) {
            properties.load(input);
        }
    }

    boolean isProtected(Integer serverId) {
        String prefix = (serverId == null ? HomeServer.CONFIGURED_SERVER : serverId) + ".";
        return properties.stringPropertyNames().stream().anyMatch(key -> key.startsWith(prefix));
    }

    void requireAccess(Integer serverId, boolean adminAccess) {
        if (!adminAccess && isProtected(serverId)) throw new Assembly64AccessDeniedException();
    }

    Map<String, String> headers(HomeServer server, boolean adminAccess) throws IOException {
        requireAccess(server.getId(), adminAccess);
        if (!isProtected(server.getId())) return Map.of();
        String prefix = server.getId() + ".";
        String url = properties.getProperty(prefix + "url");
        String username = properties.getProperty(prefix + "username");
        String password = properties.getProperty(prefix + "password");
        try {
            URI pinned = new URI(url == null ? "" : url.replaceAll("/+$", ""));
            URI selected = new URI(server.getUrl().replaceAll("/+$", ""));
            if (pinned.getHost() == null || pinned.getUserInfo() != null || pinned.getQuery() != null
                    || pinned.getFragment() != null || !pinned.equals(selected)
                    || username == null || username.isBlank() || username.contains(":")
                    || password == null || password.isEmpty()) {
                throw new IOException("Invalid or mismatched private Assembly64 credentials configuration");
            }
        } catch (URISyntaxException | NullPointerException e) {
            throw new IOException("Invalid private Assembly64 server URL");
        }
        return Map.of("Authorization", "Basic " + Base64.getEncoder().encodeToString((username + ":" + password).getBytes(UTF_8)));
    }
}