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.commons.secret;
018
019import static org.apache.juneau.commons.utils.Shorts.*;
020
021import java.util.*;
022
023/**
024 * A <b>read-only</b> {@link SecretStore} backed by {@link System#getenv(String)}.
025 *
026 * <p>
027 * Gives 12-factor deployments a zero-dependency way to feed secrets in as environment variables: {@link #find} and
028 * {@link #exists} resolve straight from the process environment.  Because the environment is immutable from within the
029 * process, the mutating operations are unsupported:
030 * <ul>
031 *    <li>{@link #store(String, char[])} throws {@link UnsupportedOperationException}.
032 *    <li>{@link #delete(String)} throws {@link UnsupportedOperationException}.
033 * </ul>
034 *
035 * <p>
036 * Note that environment variables are inherently more exposed than a dedicated secret backend (they are visible to
037 * child processes and to anything that can read the process environment), so this store trades secrecy strength for
038 * deployment simplicity.  The retrieved value is never {@code toString()}'d, logged, or dumped by this class.
039 *
040 * @since 10.0.0
041 */
042public class EnvVarSecretStore implements SecretStore {
043
044   @Override /* SecretStore */
045   public void store(String key, char[] secret) {
046      throw uoex("EnvVarSecretStore is read-only; environment variables cannot be modified from within the process.");
047   }
048
049   @Override /* SecretStore */
050   public Optional<char[]> find(String key) {
051      reqnn("key", key);
052      var v = System.getenv(key);
053      return v == null ? oe() : o(v.toCharArray());
054   }
055
056   @Override /* SecretStore */
057   public boolean exists(String key) {
058      reqnn("key", key);
059      return System.getenv(key) != null;
060   }
061
062   @Override /* SecretStore */
063   public boolean delete(String key) {
064      throw uoex("EnvVarSecretStore is read-only; environment variables cannot be modified from within the process.");
065   }
066}