001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.apache.juneau.rest.server.mcp.v20260728;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020
021import java.security.SecureRandom;
022import java.util.Base64;
023import java.util.Optional;
024
025import javax.crypto.KeyGenerator;
026import javax.crypto.SecretKey;
027
028/**
029 * Built-in default {@link KeyProvider}: a random AES-256 key with a random {@code keyId}, both fixed for the
030 * lifetime of the instance.
031 *
032 * <p>
033 * <b>Not restart-durable and not shareable across process instances by design</b> &mdash; mirrors
034 * {@code AeadRequestStateCodec}'s pre-{@code KeyProvider} ephemeral-key behavior exactly, including the
035 * cross-instance-unseal-fails guarantee (see {@code AeadRequestStateCodec_Test}'s {@code a06}), just relocated
036 * one layer down. Operators who need cross-restart or multi-instance RESUME must supply {@link StaticKeyProvider}
037 * (or a custom {@link KeyProvider}) instead of relying on this default.
038 *
039 * @since 10.0.0
040 */
041public class EphemeralKeyProvider implements KeyProvider {
042
043   private static final int KEY_BITS = 256;
044   // 8 random bytes -> 11 base64url chars (unpadded): short but collision-safe for a per-process identifier.
045   private static final int KEY_ID_BYTES = 8;
046
047   private static final Base64.Encoder B64URL = Base64.getUrlEncoder().withoutPadding();
048
049   private final KeyedSecret current;
050
051   /**
052    * Constructor. Generates a fresh, per-instance AES-256 key and a fresh, per-instance random {@code keyId}.
053    */
054   public EphemeralKeyProvider() {
055      try {
056         var gen = KeyGenerator.getInstance("AES");
057         gen.init(KEY_BITS);
058         var key = gen.generateKey();
059         var idBytes = new byte[KEY_ID_BYTES];
060         new SecureRandom().nextBytes(idBytes);
061         current = new KeyedSecret(B64URL.encodeToString(idBytes), key);
062      } catch (Exception e) { // HTT every JDK guarantees AES-256 key generation via the standard JCE provider
063         throw rex(e, "Failed to generate AES key");
064      }
065   }
066
067   @Override /* KeyProvider */
068   public KeyedSecret currentKey() {
069      return current;
070   }
071
072   @Override /* KeyProvider */
073   public Optional<SecretKey> resolveKey(String keyId) {
074      return eq(keyId, current.keyId()) ? Optional.of(current.key()) : Optional.empty();
075   }
076}