aboutsummaryrefslogtreecommitdiffstats
path: root/config-provisioning/src/main/java/com/yahoo/config/provision/WireguardKeyWithTimestamp.java
blob: c584ec7d8e8ccbd1bd85739c965eb021d24b884e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.config.provision;

import com.yahoo.jdisc.Timer;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Random;

/**
 * @author gjoranv
 */
public record WireguardKeyWithTimestamp(WireguardKey key, Instant timestamp) {

    public static final int KEY_ROTATION_BASE = 60;
    public static final int KEY_ROTATION_VARIANCE = 10;
    public static final int KEY_EXPIRY = KEY_ROTATION_BASE + KEY_ROTATION_VARIANCE + 5;

    public WireguardKeyWithTimestamp {
        if (key == null) throw new IllegalArgumentException("Wireguard key cannot be null");
        if (timestamp == null) timestamp = Instant.EPOCH;
    }

    public static WireguardKeyWithTimestamp from(String key, long msTimestamp) {
        return new WireguardKeyWithTimestamp(WireguardKey.from(key), Instant.ofEpochMilli(msTimestamp));
    }

    public boolean isDueForRotation(Timer timer, ChronoUnit unit, Random random) {
        return timer.currentTime().isAfter(keyRotationDueAt(unit, random));
    }

    public boolean hasExpired(Timer timer, ChronoUnit unit) {
        return timer.currentTime().isAfter(timestamp.plus(KEY_EXPIRY, unit));
    }

    private Instant keyRotationDueAt(ChronoUnit unit, Random random) {
        return timestamp.plus(KEY_ROTATION_BASE + random.nextInt(KEY_ROTATION_VARIANCE), unit);
    }

}