Files
SHiNE-server/SHiNE-server/shine-server-archive/src/main/java/server/archive/registration/ExternalRegistrar.java
T

84 lines
5.6 KiB
Java

package server.archive.registration;
import server.logic.ws_protocol.JSON.handlers.registration.RegistrationServiceException;
import utils.crypto.Ed25519Util;
import javax.sql.DataSource;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.*;
import java.security.SecureRandom;
/** Один активный аппаратный регистратор; транспорт не имеет доступа к приватному ключу. */
public final class ExternalRegistrar implements RegistrationCertificateSigner, AutoCloseable {
public interface Peer {
boolean open();
void send(Map<String,Object> request) throws Exception;
void disconnect();
}
public record Challenge(String nonce, long expiresAtMs, String serverLogin) {}
private record Pending(Peer peer, CompletableFuture<byte[]> result) {}
private final DataSource db;
private final String namespace, serverLogin;
private final byte[] initialKey;
private final Map<String,Pending> pending = new ConcurrentHashMap<>();
private Peer peer;
private long lastPing;
private final ScheduledExecutorService timer=Executors.newSingleThreadScheduledExecutor(r->{Thread t=new Thread(r,"registrar-watchdog");t.setDaemon(true);return t;});
public ExternalRegistrar(DataSource db,String namespace,String serverLogin) throws Exception {
this.db=db; this.namespace=namespace; this.serverLogin=serverLogin.trim();
this.initialKey=FreeRegistrationIssuer.configuredNamespaceKey(db,namespace,this.serverLogin);
timer.scheduleAtFixedRate(this::expire,5,5,TimeUnit.SECONDS);
}
public String namespace(){return namespace;}
public byte[] publicKey32(){return initialKey.clone();}
public Challenge challenge(String ns) {
if(!namespace.equals(ns)) throw new IllegalArgumentException("Wrong namespace");
byte[] nonce=new byte[32]; new SecureRandom().nextBytes(nonce);
return new Challenge(Base64.getUrlEncoder().withoutPadding().encodeToString(nonce),System.currentTimeMillis()+30000,serverLogin);
}
public boolean authenticate(Challenge c,String ns,long timeMs,byte[] sig) throws Exception {
long now=System.currentTimeMillis();
if(c==null || !namespace.equals(ns) || now>c.expiresAtMs() || timeMs<now-60000 || timeMs>now+60000) return false;
byte[] current=FreeRegistrationIssuer.configuredNamespaceKey(db,namespace,serverLogin);
if(!Arrays.equals(current,initialKey)) return false; // ротация ключа требует перезапуска конфигурации
String msg="SHINE_REGISTRAR_CONNECT_V1:"+serverLogin+":"+ns+":"+timeMs+":"+c.nonce();
return Ed25519Util.verify(msg.getBytes(StandardCharsets.UTF_8),sig,current);
}
public synchronized boolean attach(Peer p) {
if(!p.open() || (connected() && peer!=p)) return false;
if(peer!=null && peer!=p)detach(peer);
peer=p; lastPing=System.nanoTime(); return true;
}
public synchronized boolean connected(){return peer!=null && peer.open() && System.nanoTime()-lastPing<TimeUnit.SECONDS.toNanos(100);}
public synchronized void ping(Peer p){if(peer==p)lastPing=System.nanoTime();}
public synchronized boolean isPeer(Peer p){return peer==p && connected();}
public synchronized void detach(Peer p){
if(peer==p)peer=null;
pending.forEach((id,job)->{if(job.peer()==p && pending.remove(id,job))job.result().completeExceptionally(new RegistrationServiceException(503));});
}
private void expire(){Peer stale; synchronized(this){stale=connected()?null:peer;if(stale!=null)detach(stale);} if(stale!=null)stale.disconnect();}
public void result(Peer p,String id,int status,byte[] raw){
Pending job=pending.get(id);
if(job==null || job.peer()!=p || !isPeer(p) || !pending.remove(id,job))return;
if(status==200 && raw!=null && raw.length<=4096)job.result().complete(raw);
else job.result().completeExceptionally(new RegistrationServiceException(switch(status){case 400,403,409,429,500,503->status;default->500;}));
}
@Override public byte[] issue(String login,byte[] root,byte[] blockchain,byte[] client,byte[] emailHash) throws Exception {
if(!login.endsWith("@"+namespace)) throw new IllegalArgumentException("Wrong namespace");
if(!Arrays.equals(initialKey,FreeRegistrationIssuer.configuredNamespaceKey(db,namespace,serverLogin))) throw new RegistrationServiceException(503);
String id=UUID.randomUUID().toString();
Pending job;
synchronized(this){if(!connected())throw new RegistrationServiceException(503);job=new Pending(peer,new CompletableFuture<>());pending.put(id,job);}
try {
job.peer().send(Map.of("op","RegistrarSignRegistration","requestId",id,"payload",Map.of(
"login",login,"rootPublicKey",b64(root),"blockchainPublicKey",b64(blockchain),"clientPublicKey",b64(client),"emailSha256",b64(emailHash))));
return job.result().get(25,TimeUnit.SECONDS);
} catch(ExecutionException e){if(e.getCause() instanceof RegistrationServiceException x)throw x;throw new RegistrationServiceException(503);}
catch(InterruptedException e){Thread.currentThread().interrupt();throw new RegistrationServiceException(503);}
catch(Exception e){throw new RegistrationServiceException(503);}
finally{pending.remove(id,job);}
}
private static String b64(byte[] b){return Base64.getEncoder().encodeToString(b);}
@Override public void close(){timer.shutdownNow();Peer p; synchronized(this){p=peer;if(p!=null)detach(p);} if(p!=null)p.disconnect();}
}