aboutsummaryrefslogtreecommitdiffstats
path: root/configserver-flags/src/test/java/com/yahoo/vespa/configserver/flags/http/FlagsHandlerTest.java
blob: 3d37117c002ffc6e328a60f95fc97d4849081461 (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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.configserver.flags.http;

import com.yahoo.container.jdisc.HttpRequest;
import com.yahoo.container.jdisc.HttpResponse;
import com.yahoo.jdisc.http.HttpRequest.Method;
import com.yahoo.text.Utf8;
import com.yahoo.vespa.configserver.flags.FlagsDb;
import com.yahoo.vespa.configserver.flags.db.FlagsDbImpl;
import com.yahoo.vespa.curator.mock.MockCurator;
import com.yahoo.vespa.flags.FetchVector;
import com.yahoo.vespa.flags.FlagId;
import com.yahoo.vespa.flags.Flags;
import com.yahoo.vespa.flags.UnboundBooleanFlag;
import com.yahoo.yolean.Exceptions;
import org.junit.jupiter.api.Test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
 * @author hakonhall
 */
public class FlagsHandlerTest {
    private static final UnboundBooleanFlag FLAG1 = Flags.defineFeatureFlag(
            "id1", false, List.of("joe"), "2010-01-01", "2030-01-01", "desc1", "mod1");
    private static final UnboundBooleanFlag FLAG2 = Flags.defineFeatureFlag(
            "id2", true, List.of("joe"), "2010-01-01", "2030-01-01", "desc2", "mod2",
            FetchVector.Dimension.HOSTNAME, FetchVector.Dimension.INSTANCE_ID);

    private final FlagsDb flagsDb = new FlagsDbImpl(new MockCurator());
    private final FlagsHandler handler = new FlagsHandler(FlagsHandler.testContext(), flagsDb);

    @Test
    void testV1() {
        String expectedResponse = "{" +
                Stream.of("data", "defined")
                        .map(name -> "\"" + name + "\":{\"url\":\"https://foo.com:4443/flags/v1/" + name + "\"}")
                        .collect(Collectors.joining(",")) +
                "}";
        verifySuccessfulRequest(Method.GET, "", "", expectedResponse);
        verifySuccessfulRequest(Method.GET, "/", "", expectedResponse);
    }

    @Test
    void testDefined() {
        try (Flags.Replacer replacer = Flags.clearFlagsForTesting()) {
            fixUnusedWarning(replacer);
            Flags.defineFeatureFlag("id", false, List.of("joe"), "2010-01-01", "2030-01-01", "desc", "mod", FetchVector.Dimension.HOSTNAME);
            verifySuccessfulRequest(Method.GET, "/defined", "",
                    "{\"id\":{\"description\":\"desc\",\"modification-effect\":\"mod\",\"owners\":[\"joe\"],\"createdAt\":\"2010-01-01T00:00:00Z\",\"expiresAt\":\"2030-01-01T00:00:00Z\",\"dimensions\":[\"hostname\"]}}");

            verifySuccessfulRequest(Method.GET, "/defined/id", "",
                    "{\"description\":\"desc\",\"modification-effect\":\"mod\",\"owners\":[\"joe\"],\"createdAt\":\"2010-01-01T00:00:00Z\",\"expiresAt\":\"2030-01-01T00:00:00Z\",\"dimensions\":[\"hostname\"]}");
        }
    }

    private void fixUnusedWarning(Flags.Replacer replacer) { }

    @Test
    void testData() {
        // PUT flag with ID id1
        verifySuccessfulRequest(Method.PUT, "/data/" + FLAG1.id(),
                """
                        {
                          "id": "id1",
                          "rules": [
                            {
                              "value": true
                            }
                          ]
                        }""",
                "");

        // GET on ID id1 should return the same as the put.
        verifySuccessfulRequest(Method.GET, "/data/" + FLAG1.id(),
                "", "{\"id\":\"id1\",\"rules\":[{\"value\":true}]}");

        // List all flags should list only id1
        verifySuccessfulRequest(Method.GET, "/data",
                "", "{\"flags\":[{\"id\":\"id1\",\"url\":\"https://foo.com:4443/flags/v1/data/id1\"}]}");

        // Should be identical to above: suffix / on path should be ignored
        verifySuccessfulRequest(Method.GET, "/data/",
                "", "{\"flags\":[{\"id\":\"id1\",\"url\":\"https://foo.com:4443/flags/v1/data/id1\"}]}");

        // Verify absent port => absent in response
        assertEquals(handleWithPort(Method.GET, -1, "/data", "", 200),
                "{\"flags\":[{\"id\":\"id1\",\"url\":\"https://foo.com/flags/v1/data/id1\"}]}");

        // PUT id2
        verifySuccessfulRequest(Method.PUT, "/data/" + FLAG2.id(),
                """
                        {
                          "id": "id2",
                          "rules": [
                            {
                              "conditions": [
                                {
                                  "type": "whitelist",
                                  "dimension": "hostname",
                                  "values": [ "host1", "host2" ]
                                },
                                {
                                  "type": "blacklist",
                                  "dimension": "instance",
                                  "values": [ "app1", "app2" ]
                                }
                              ],
                              "value": true
                            }
                          ],
                          "attributes": {
                            "zone": "zone1"
                          }
                        }
                        """,
                "");

        // GET on id2 should now return what was put
        verifySuccessfulRequest(Method.GET, "/data/" + FLAG2.id(), "",
                "{\"id\":\"id2\",\"rules\":[{\"conditions\":[{\"type\":\"whitelist\",\"dimension\":\"hostname\",\"values\":[\"host1\",\"host2\"]},{\"type\":\"blacklist\",\"dimension\":\"instance\",\"values\":[\"app1\",\"app2\"]}],\"value\":true}],\"attributes\":{\"zone\":\"zone1\"}}");

        // The list of flag data should return id1 and id2
        verifySuccessfulRequest(Method.GET, "/data",
                "",
                "{\"flags\":[{\"id\":\"id1\",\"url\":\"https://foo.com:4443/flags/v1/data/id1\"},{\"id\":\"id2\",\"url\":\"https://foo.com:4443/flags/v1/data/id2\"}]}");

        // Putting (overriding) id1 should work silently
        verifySuccessfulRequest(Method.PUT, "/data/" + FLAG1.id(),
                """
                        {
                          "id": "id1",
                          "rules": [
                            {
                              "value": false
                            }
                          ]
                        }
                        """,
                "");

        // Verify PUT
        verifySuccessfulRequest(Method.GET, "/data/" + FLAG1.id(), "", "{\"id\":\"id1\",\"rules\":[{\"value\":false}]}");

        // Get all recursivelly displays all flag data
        verifySuccessfulRequest(Method.GET, "/data?recursive=true", "",
                "{\"flags\":[{\"id\":\"id1\",\"rules\":[{\"value\":false}]},{\"id\":\"id2\",\"rules\":[{\"conditions\":[{\"type\":\"whitelist\",\"dimension\":\"hostname\",\"values\":[\"host1\",\"host2\"]},{\"type\":\"blacklist\",\"dimension\":\"instance\",\"values\":[\"app1\",\"app2\"]}],\"value\":true}],\"attributes\":{\"zone\":\"zone1\"}}]}");

        // Deleting both flags
        verifySuccessfulRequest(Method.DELETE, "/data/" + FLAG1.id(), "", "");
        verifySuccessfulRequest(Method.DELETE, "/data/" + FLAG2.id(), "", "");

        // And the list of data flags should now be empty
        verifySuccessfulRequest(Method.GET, "/data", "", "{\"flags\":[]}");
    }

    @Test
    void testForcing() {
        assertTrue(handle(Method.PUT, "/data/" + new FlagId("undef"), "", 400).contains("There is no flag 'undef'"));

        assertTrue(handle(Method.PUT, "/data/" + new FlagId("undef") + "?force=true", "", 400).
                contains("No content to map due to end-of-input"));

        assertTrue(handle(Method.PUT, "/data/" + FLAG1.id(), "{}", 400).
                contains("Flag ID missing"));

        assertTrue(handle(Method.PUT, "/data/" + FLAG1.id(), "{\"id\": \"id1\",\"rules\": [{\"value\":\"string\"}]}", 400).
                contains("Wrong type of JsonNode: STRING"));

        assertEquals(handle(Method.PUT, "/data/" + FLAG1.id() + "?force=true", "{\"id\": \"id1\",\"rules\": [{\"value\":\"string\"}]}", 200),
                "");
    }

    private void verifySuccessfulRequest(Method method, String pathSuffix, String requestBody, String expectedResponseBody) {
        assertEquals(handle(method, pathSuffix, requestBody, 200), expectedResponseBody);
    }

    private String handle(Method method, String pathSuffix, String requestBody, int expectedStatus) {
        return handleWithPort(method, 4443, pathSuffix, requestBody, expectedStatus);
    }

    private String handleWithPort(Method method, int port, String pathSuffix, String requestBody, int expectedStatus) {
        String uri = "https://foo.com" + (port < 0 ? "" : ":" + port) + "/flags/v1" + pathSuffix;
        HttpRequest request = HttpRequest.createTestRequest(uri, method, makeInputStream(requestBody));
        HttpResponse response = handler.handle(request);
        assertEquals(expectedStatus, response.getStatus());
        assertEquals("application/json", response.getContentType());
        var outputStream = new ByteArrayOutputStream();
        Exceptions.uncheck(() -> response.render(outputStream));
        return outputStream.toString(StandardCharsets.UTF_8);
    }

    private InputStream makeInputStream(String content) {
        return new ByteArrayInputStream(Utf8.toBytes(content));
    }
}