001/*
002 * VM-Operator
003 * Copyright (C) 2024 Michael N. Lipp
004 * 
005 * This program is free software: you can redistribute it and/or modify
006 * it under the terms of the GNU Affero General Public License as
007 * published by the Free Software Foundation, either version 3 of the
008 * License, or (at your option) any later version.
009 *
010 * This program is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
013 * GNU Affero General Public License for more details.
014 *
015 * You should have received a copy of the GNU Affero General Public License
016 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
017 */
018
019package org.jdrupes.vmoperator.manager;
020
021import io.kubernetes.client.custom.V1Patch;
022import io.kubernetes.client.openapi.ApiException;
023import io.kubernetes.client.openapi.models.V1Secret;
024import io.kubernetes.client.openapi.models.V1SecretList;
025import io.kubernetes.client.util.Watch.Response;
026import io.kubernetes.client.util.generic.options.ListOptions;
027import io.kubernetes.client.util.generic.options.PatchOptions;
028import java.io.IOException;
029import java.security.NoSuchAlgorithmException;
030import java.security.SecureRandom;
031import java.time.Instant;
032import java.util.Collections;
033import java.util.LinkedList;
034import java.util.List;
035import java.util.Map;
036import java.util.Optional;
037import java.util.Scanner;
038import java.util.logging.Level;
039import static org.jdrupes.vmoperator.common.Constants.APP_NAME;
040import static org.jdrupes.vmoperator.common.Constants.VM_OP_NAME;
041import org.jdrupes.vmoperator.common.K8sClient;
042import org.jdrupes.vmoperator.common.K8sV1PodStub;
043import org.jdrupes.vmoperator.common.K8sV1SecretStub;
044import static org.jdrupes.vmoperator.manager.Constants.COMP_DISPLAY_SECRET;
045import static org.jdrupes.vmoperator.manager.Constants.DATA_DISPLAY_PASSWORD;
046import static org.jdrupes.vmoperator.manager.Constants.DATA_PASSWORD_EXPIRY;
047import org.jdrupes.vmoperator.manager.events.GetDisplayPassword;
048import org.jdrupes.vmoperator.manager.events.VmChannel;
049import org.jdrupes.vmoperator.manager.events.VmDefChanged;
050import org.jgrapes.core.Channel;
051import org.jgrapes.core.CompletionLock;
052import org.jgrapes.core.Event;
053import org.jgrapes.core.annotation.Handler;
054import org.jgrapes.util.events.ConfigurationUpdate;
055import org.jose4j.base64url.Base64;
056
057/**
058 * Watches for changes of display secrets.
059 */
060@SuppressWarnings({ "PMD.DataflowAnomalyAnalysis", "PMD.TooManyStaticImports" })
061public class DisplaySecretMonitor
062        extends AbstractMonitor<V1Secret, V1SecretList, VmChannel> {
063
064    private int passwordValidity = 10;
065    private final List<PendingGet> pendingGets
066        = Collections.synchronizedList(new LinkedList<>());
067
068    /**
069     * Instantiates a new display secrets monitor.
070     *
071     * @param componentChannel the component channel
072     */
073    public DisplaySecretMonitor(Channel componentChannel) {
074        super(componentChannel, V1Secret.class, V1SecretList.class);
075        context(K8sV1SecretStub.CONTEXT);
076        ListOptions options = new ListOptions();
077        options.setLabelSelector("app.kubernetes.io/name=" + APP_NAME + ","
078            + "app.kubernetes.io/component=" + COMP_DISPLAY_SECRET);
079        options(options);
080    }
081
082    /**
083     * On configuration update.
084     *
085     * @param event the event
086     */
087    @Handler
088    @Override
089    public void onConfigurationUpdate(ConfigurationUpdate event) {
090        super.onConfigurationUpdate(event);
091        event.structured(componentPath()).ifPresent(c -> {
092            try {
093                if (c.containsKey("passwordValidity")) {
094                    passwordValidity = Integer
095                        .parseInt((String) c.get("passwordValidity"));
096                }
097            } catch (ClassCastException e) {
098                logger.config("Malformed configuration: " + e.getMessage());
099            }
100        });
101    }
102
103    @Override
104    protected void prepareMonitoring() throws IOException, ApiException {
105        client(new K8sClient());
106    }
107
108    @Override
109    protected void handleChange(K8sClient client, Response<V1Secret> change) {
110        String vmName = change.object.getMetadata().getLabels()
111            .get("app.kubernetes.io/instance");
112        if (vmName == null) {
113            return;
114        }
115        var channel = channel(vmName).orElse(null);
116        if (channel == null || channel.vmDefinition() == null) {
117            return;
118        }
119
120        try {
121            patchPod(client, change);
122        } catch (ApiException e) {
123            logger.log(Level.WARNING, e,
124                () -> "Cannot patch pod annotations: " + e.getMessage());
125        }
126    }
127
128    private void patchPod(K8sClient client, Response<V1Secret> change)
129            throws ApiException {
130        // Force update for pod
131        ListOptions listOpts = new ListOptions();
132        listOpts.setLabelSelector(
133            "app.kubernetes.io/managed-by=" + VM_OP_NAME + ","
134                + "app.kubernetes.io/name=" + APP_NAME + ","
135                + "app.kubernetes.io/instance=" + change.object.getMetadata()
136                    .getLabels().get("app.kubernetes.io/instance"));
137        // Get pod, selected by label
138        var pods = K8sV1PodStub.list(client, namespace(), listOpts);
139
140        // If the VM is being created, the pod may not exist yet.
141        if (pods.isEmpty()) {
142            return;
143        }
144        var pod = pods.iterator().next();
145
146        // Patch pod annotation
147        PatchOptions patchOpts = new PatchOptions();
148        patchOpts.setFieldManager("kubernetes-java-kubectl-apply");
149        pod.patch(V1Patch.PATCH_FORMAT_JSON_PATCH,
150            new V1Patch("[{\"op\": \"replace\", \"path\": "
151                + "\"/metadata/annotations/vmrunner.jdrupes.org~1dpVersion\", "
152                + "\"value\": \""
153                + change.object.getMetadata().getResourceVersion()
154                + "\"}]"),
155            patchOpts);
156    }
157
158    /**
159     * On get display secrets.
160     *
161     * @param event the event
162     * @param channel the channel
163     * @throws ApiException the api exception
164     */
165    @Handler
166    @SuppressWarnings("PMD.StringInstantiation")
167    public void onGetDisplaySecrets(GetDisplayPassword event, VmChannel channel)
168            throws ApiException {
169        ListOptions options = new ListOptions();
170        options.setLabelSelector("app.kubernetes.io/name=" + APP_NAME + ","
171            + "app.kubernetes.io/component=" + COMP_DISPLAY_SECRET + ","
172            + "app.kubernetes.io/instance="
173            + event.vmDefinition().metadata().getName());
174        var stubs = K8sV1SecretStub.list(client(),
175            event.vmDefinition().metadata().getNamespace(), options);
176        if (stubs.isEmpty()) {
177            return;
178        }
179        var stub = stubs.iterator().next();
180
181        // Check validity
182        var model = stub.model().get();
183        @SuppressWarnings("PMD.StringInstantiation")
184        var expiry = Optional.ofNullable(model.getData()
185            .get(DATA_PASSWORD_EXPIRY)).map(b -> new String(b)).orElse(null);
186        if (model.getData().get(DATA_DISPLAY_PASSWORD) != null
187            && stillValid(expiry)) {
188            event.setResult(
189                new String(model.getData().get(DATA_DISPLAY_PASSWORD)));
190            return;
191        }
192        updatePassword(stub, event);
193    }
194
195    @SuppressWarnings("PMD.StringInstantiation")
196    private void updatePassword(K8sV1SecretStub stub, GetDisplayPassword event)
197            throws ApiException {
198        SecureRandom random = null;
199        try {
200            random = SecureRandom.getInstanceStrong();
201        } catch (NoSuchAlgorithmException e) { // NOPMD
202            // "Every implementation of the Java platform is required
203            // to support at least one strong SecureRandom implementation."
204        }
205        byte[] bytes = new byte[16];
206        random.nextBytes(bytes);
207        var password = Base64.encode(bytes);
208        var model = stub.model().get();
209        model.setStringData(Map.of(DATA_DISPLAY_PASSWORD, password,
210            DATA_PASSWORD_EXPIRY,
211            Long.toString(Instant.now().getEpochSecond() + passwordValidity)));
212        event.setResult(password);
213
214        // Prepare wait for confirmation (by VM status change)
215        var pending = new PendingGet(event,
216            event.vmDefinition().displayPasswordSerial().orElse(0L) + 1,
217            new CompletionLock(event, 1500));
218        pendingGets.add(pending);
219        Event.onCompletion(event, e -> {
220            pendingGets.remove(pending);
221        });
222
223        // Update, will (eventually) trigger confirmation
224        stub.update(model).getObject();
225    }
226
227    private boolean stillValid(String expiry) {
228        if (expiry == null || "never".equals(expiry)) {
229            return true;
230        }
231        @SuppressWarnings({ "PMD.CloseResource", "resource" })
232        var scanner = new Scanner(expiry);
233        if (!scanner.hasNextLong()) {
234            return false;
235        }
236        long expTime = scanner.nextLong();
237        return expTime > Instant.now().getEpochSecond() + passwordValidity;
238    }
239
240    /**
241     * On vm def changed.
242     *
243     * @param event the event
244     * @param channel the channel
245     */
246    @Handler
247    public void onVmDefChanged(VmDefChanged event, Channel channel) {
248        synchronized (pendingGets) {
249            String vmName = event.vmDefinition().metadata().getName();
250            for (var pending : pendingGets) {
251                if (pending.event.vmDefinition().metadata().getName()
252                    .equals(vmName)
253                    && event.vmDefinition().displayPasswordSerial()
254                        .map(s -> s >= pending.expectedSerial).orElse(false)) {
255                    pending.lock.remove();
256                    // pending will be removed from pendingGest by
257                    // waiting thread, see updatePassword
258                    continue;
259                }
260            }
261        }
262    }
263
264    /**
265     * The Class PendingGet.
266     */
267    @SuppressWarnings("PMD.DataClass")
268    private static class PendingGet {
269        public final GetDisplayPassword event;
270        public final long expectedSerial;
271        public final CompletionLock lock;
272
273        /**
274         * Instantiates a new pending get.
275         *
276         * @param event the event
277         * @param expectedSerial the expected serial
278         */
279        public PendingGet(GetDisplayPassword event, long expectedSerial,
280                CompletionLock lock) {
281            super();
282            this.event = event;
283            this.expectedSerial = expectedSerial;
284            this.lock = lock;
285        }
286    }
287}