blob: 1456cd45344a44058966ef081602bcd010651f14 [file] [edit]
// Copyright 2026 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COBALT_SRC_LIB_UTIL_DYNAMIC_ENCRYPTED_MESSAGE_MAKER_H_
#define COBALT_SRC_LIB_UTIL_DYNAMIC_ENCRYPTED_MESSAGE_MAKER_H_
#include <cstdint>
#include <memory>
#include <shared_mutex>
#include <string_view>
#include <utility>
#include "google/protobuf/message_lite.h"
#include "src/lib/util/encrypted_message_util.h"
#include "src/lib/util/not_null.h"
#include "src/lib/util/repeated_error_log_limiter.h"
#include "src/pb/encrypted_message.pb.h"
#include "src/public/lib/clock_interfaces.h"
#include "src/public/lib/statusor/statusor.h"
#include "src/system_data/configuration_data.h"
namespace cobalt::util {
// Holds an initialized EncryptedMessageMaker along with its key index and
// expiration timestamp (in seconds since the Unix epoch, compared against
// SystemClockInterface::now()).
class ParsedKey {
public:
ParsedKey(NotNullUniquePtr<EncryptedMessageMaker> maker,
uint32_t key_index, // NOLINT(bugprone-easily-swappable-parameters)
int64_t expiration_timestamp_secs)
: maker_(std::move(maker)),
key_index_(key_index),
expiration_timestamp_secs_(expiration_timestamp_secs) {}
[[nodiscard]] NotNullUniquePtr<EncryptedMessageMaker> TakeMaker() { return std::move(maker_); }
[[nodiscard]] uint32_t key_index() const { return key_index_; }
// Expiration timestamp in seconds since the Unix epoch, compared against
// SystemClockInterface::now().
[[nodiscard]] int64_t expiration_timestamp_secs() const { return expiration_timestamp_secs_; }
private:
NotNullUniquePtr<EncryptedMessageMaker> maker_;
uint32_t key_index_;
int64_t expiration_timestamp_secs_;
};
// Holds the parsed Shuffler and Analyzer public keys for a target environment.
class ParsedKeyset {
public:
ParsedKeyset(ParsedKey shuffler_key, ParsedKey analyzer_key)
: shuffler_key_(std::move(shuffler_key)), analyzer_key_(std::move(analyzer_key)) {}
[[nodiscard]] const ParsedKey& shuffler_key() const { return shuffler_key_; }
[[nodiscard]] ParsedKey TakeShufflerKey() { return std::move(shuffler_key_); }
[[nodiscard]] const ParsedKey& analyzer_key() const { return analyzer_key_; }
[[nodiscard]] ParsedKey TakeAnalyzerKey() { return std::move(analyzer_key_); }
private:
ParsedKey shuffler_key_;
ParsedKey analyzer_key_;
};
// Parses a serialized CobaltPublicKeys proto for the specified target environment
// (PROD or DEVEL), validates the keyset bytes, key indices, and expiration timestamps,
// and returns initialized Tink hybrid EncryptedMessageMakers for the Shuffler and Analyzer.
// Both returned keys are clamped to the earlier of the two expiration timestamps so that
// neither maker remains usable while the other is expired and IsExpired() reflects the
// keyset as a whole.
// Returns INVALID_ARGUMENT if the outer CobaltPublicKeys proto or its metadata fields are
// invalid, or FAILED_PRECONDITION if a public_tink_keyset is empty or rejected by Tink.
lib::statusor::StatusOr<ParsedKeyset> ParsePublicKeys(std::string_view pb_bytes,
system_data::Environment env);
// Thread-safe, hot-swappable EncryptedMessageMaker that validates key expiration
// against a system wall clock before encrypting each message.
class DynamicEncryptedMessageMaker : public EncryptedMessageMaker {
public:
// Constructs an uninitialized DynamicEncryptedMessageMaker. Calls to Encrypt()
// will return false until UpdateKey() provides a valid key.
// |clock| must be non-null and must outlive this instance.
explicit DynamicEncryptedMessageMaker(SystemClockInterface* clock);
// Constructs a DynamicEncryptedMessageMaker initialized with |initial_key|.
// |clock| must be non-null and must outlive this instance.
DynamicEncryptedMessageMaker(ParsedKey initial_key, SystemClockInterface* clock);
bool Encrypt(const google::protobuf::MessageLite& message,
EncryptedMessage* encrypted_message) const override;
void UpdateKey(ParsedKey new_key);
[[nodiscard]] uint32_t key_index() const {
std::shared_lock<std::shared_mutex> lock(mu_);
return key_index_;
}
// Expiration timestamp of the current key in seconds since the Unix epoch,
// compared against SystemClockInterface::now(). Returns 0 if uninitialized.
[[nodiscard]] int64_t expiration_timestamp_secs() const {
std::shared_lock<std::shared_mutex> lock(mu_);
return expiration_timestamp_secs_;
}
[[nodiscard]] bool IsInitialized() const {
std::shared_lock<std::shared_mutex> lock(mu_);
return current_maker_ != nullptr;
}
// Returns true if the maker is initialized with a key whose expiration
// timestamp has passed. Returns false if the maker is uninitialized; callers
// should also check IsInitialized() to determine whether the maker has a
// valid key ready for encryption.
[[nodiscard]] bool IsExpired() const;
private:
static constexpr uint32_t kMaxRepeatedErrorLogs = 5;
mutable std::shared_mutex mu_;
std::unique_ptr<EncryptedMessageMaker> current_maker_;
uint32_t key_index_ = 0;
int64_t expiration_timestamp_secs_ = 0;
SystemClockInterface* const clock_;
// Each maker logs up to kMaxRepeatedErrorLogs uninitialized or expired-key
// errors. UpdateKey() resets the expired-key limit so each new key's
// expiration is logged.
mutable RepeatedErrorLogLimiter uninitialized_log_limiter_{kMaxRepeatedErrorLogs};
mutable RepeatedErrorLogLimiter expired_log_limiter_{kMaxRepeatedErrorLogs};
};
} // namespace cobalt::util
#endif // COBALT_SRC_LIB_UTIL_DYNAMIC_ENCRYPTED_MESSAGE_MAKER_H_