summaryrefslogtreecommitdiffstats
path: root/jdisc-cloud-aws/src/test/java/com/yahoo/jdisc/cloud/aws/VespaAwsCredentialsProviderTest.java
blob: 2725d28651eea6755b344e134d4ad4aee5ebb0ad (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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
package com.yahoo.jdisc.cloud.aws;

import com.amazonaws.auth.AWSCredentials;
import com.yahoo.test.ManualClock;
import com.yahoo.vespa.test.file.TestFileSystem;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.Duration;
import java.time.Instant;

public class VespaAwsCredentialsProviderTest {

    @Test
    void refreshes_credentials() throws IOException {
        Path credentialsPath = TestFileSystem.create().getPath("/credentials.json");
        ManualClock clock = new ManualClock(Instant.now());

        Instant originalExpiry = clock.instant().plus(Duration.ofHours(12));
        writeCredentials(credentialsPath, originalExpiry);
        VespaAwsCredentialsProvider credentialsProvider = new VespaAwsCredentialsProvider(credentialsPath, clock);

        AWSCredentials credentials = credentialsProvider.getCredentials();
        Assertions.assertEquals(originalExpiry.toString(), credentials.getAWSAccessKeyId());

        Instant updatedExpiry = clock.instant().plus(Duration.ofHours(24));
        writeCredentials(credentialsPath, updatedExpiry);
        // File updated, but old credentials still valid
        credentials = credentialsProvider.getCredentials();
        Assertions.assertEquals(originalExpiry.toString(), credentials.getAWSAccessKeyId());

        // Credentials refreshes when it is < 30 minutes left until expiry
        clock.advance(Duration.ofHours(11).plus(Duration.ofMinutes(31)));
        credentials = credentialsProvider.getCredentials();
        Assertions.assertEquals(updatedExpiry.toString(), credentials.getAWSAccessKeyId());

    }

    private void writeCredentials(Path path, Instant expiry) throws IOException {
        String content = """
                {
                   "awsAccessKey": "%1$s",
                   "awsSecretKey": "%1$s",
                   "sessionToken": "%1$s",
                   "expiry": "%1$s"
                 }""".formatted(expiry.toString());
        Files.writeString(path, content);
    }
}