// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////////

#include "tink/aead/internal/chacha20_poly1305_proto_serialization_impl.h"

#include <array>
#include <cstdint>
#include <string>
#include <utility>

#include "absl/base/attributes.h"
#include "absl/status/status.h"
#include "absl/status/statusor.h"
#include "absl/strings/string_view.h"
#include "absl/types/optional.h"
#include "tink/aead/chacha20_poly1305_key.h"
#include "tink/aead/chacha20_poly1305_parameters.h"
#include "tink/internal/key_parser.h"
#include "tink/internal/key_serializer.h"
#include "tink/internal/mutable_serialization_registry.h"
#include "tink/internal/parameters_parser.h"
#include "tink/internal/parameters_serializer.h"
#include "tink/internal/proto_key_serialization.h"
#include "tink/internal/proto_parameters_serialization.h"
#include "tink/internal/proto_parser_fields.h"
#include "tink/internal/proto_parser_message.h"
#include "tink/internal/proto_parser_secret_data_field.h"
#include "tink/internal/serialization_registry.h"
#include "tink/internal/tink_proto_structs.h"
#include "tink/partial_key_access.h"
#include "tink/restricted_data.h"
#include "tink/secret_data.h"
#include "tink/secret_key_access_token.h"

namespace crypto {
namespace tink {
namespace internal {
namespace {

using ::crypto::tink::internal::proto_parsing::Field;
using ::crypto::tink::internal::proto_parsing::Message;
using ::crypto::tink::internal::proto_parsing::SecretDataField;
using ::crypto::tink::internal::proto_parsing::Uint32Field;

using ChaCha20Poly1305ProtoParametersParserImpl =
    internal::ParametersParserImpl<internal::ProtoParametersSerialization,
                                   ChaCha20Poly1305Parameters>;
using ChaCha20Poly1305ProtoParametersSerializerImpl =
    internal::ParametersSerializerImpl<ChaCha20Poly1305Parameters,
                                       internal::ProtoParametersSerialization>;
using ChaCha20Poly1305ProtoKeyParserImpl =
    internal::KeyParserImpl<internal::ProtoKeySerialization,
                            ChaCha20Poly1305Key>;
using ChaCha20Poly1305ProtoKeySerializerImpl =
    internal::KeySerializerImpl<ChaCha20Poly1305Key,
                                internal::ProtoKeySerialization>;

class ChaCha20Poly1305KeyFormatTP : public Message {
 public:
  ChaCha20Poly1305KeyFormatTP() = default;

  // This is OK because this class doesn't contain secret data.
  using Message::SerializeAsString;

 private:
  size_t num_fields() const override { return 0; }
  const Field* field(int i) const override {
    // This should not be called since num_fields() is 0.
    return nullptr;
  }
};

class ChaCha20Poly1305KeyTP : public Message {
 public:
  ChaCha20Poly1305KeyTP() = default;

  uint32_t version() const { return version_.value(); }
  void set_version(uint32_t value) { version_.set_value(value); }

  const SecretData& key_value() const { return key_value_.value(); }
  void set_key_value(absl::string_view value) {
    *key_value_.mutable_value() = util::SecretDataFromStringView(value);
  }

 private:
  size_t num_fields() const override { return 2; }
  const Field* field(int i) const override {
    return std::array<const Field*, 2>{&version_, &key_value_}[i];
  }
  Uint32Field version_{1, ProtoFieldOptions::kImplicit};
  SecretDataField key_value_{2};
};

const absl::string_view kTypeUrl =
    "type.googleapis.com/google.crypto.tink.ChaCha20Poly1305Key";

absl::StatusOr<ChaCha20Poly1305Parameters::Variant> ToVariant(
    OutputPrefixTypeEnum output_prefix_type) {
  switch (output_prefix_type) {
    case OutputPrefixTypeEnum::kLegacy:
      ABSL_FALLTHROUGH_INTENDED;  // Parse LEGACY output prefix as CRUNCHY.
    case OutputPrefixTypeEnum::kCrunchy:
      return ChaCha20Poly1305Parameters::Variant::kCrunchy;
    case OutputPrefixTypeEnum::kRaw:
      return ChaCha20Poly1305Parameters::Variant::kNoPrefix;
    case OutputPrefixTypeEnum::kTink:
      return ChaCha20Poly1305Parameters::Variant::kTink;
    default:
      return absl::Status(
          absl::StatusCode::kInvalidArgument,
          "Could not determine ChaCha20Poly1305Parameters::Variant");
  }
}

absl::StatusOr<OutputPrefixTypeEnum> ToOutputPrefixType(
    ChaCha20Poly1305Parameters::Variant variant) {
  switch (variant) {
    case ChaCha20Poly1305Parameters::Variant::kCrunchy:
      return OutputPrefixTypeEnum::kCrunchy;
    case ChaCha20Poly1305Parameters::Variant::kNoPrefix:
      return OutputPrefixTypeEnum::kRaw;
    case ChaCha20Poly1305Parameters::Variant::kTink:
      return OutputPrefixTypeEnum::kTink;
    default:
      return absl::InvalidArgumentError(
          "Could not determine output prefix type");
  }
}

absl::StatusOr<ChaCha20Poly1305Parameters> ParseParameters(
    const internal::ProtoParametersSerialization& serialization) {
  const internal::KeyTemplateTP& key_template = serialization.GetKeyTemplate();
  if (key_template.type_url() != kTypeUrl) {
    return absl::InvalidArgumentError(
        "Wrong type URL when parsing ChaCha20Poly1305Parameters.");
  }

  ChaCha20Poly1305KeyFormatTP proto_key_format;
  if (!proto_key_format.ParseFromString(key_template.value())) {
    return absl::InvalidArgumentError(
        "Failed to parse ChaCha20Poly1305KeyFormat proto");
  }
  absl::StatusOr<ChaCha20Poly1305Parameters::Variant> variant =
      ToVariant(key_template.output_prefix_type());
  if (!variant.ok()) {
    return variant.status();
  }
  return ChaCha20Poly1305Parameters::Create(*variant);
}

absl::StatusOr<internal::ProtoParametersSerialization> SerializeParameters(
    const ChaCha20Poly1305Parameters& parameters) {
  absl::StatusOr<OutputPrefixTypeEnum> output_prefix_type =
      ToOutputPrefixType(parameters.GetVariant());
  if (!output_prefix_type.ok()) return output_prefix_type.status();

  ChaCha20Poly1305KeyFormatTP proto_key_format;
  std::string serialized_key_format = proto_key_format.SerializeAsString();
  return internal::ProtoParametersSerialization::Create(
      kTypeUrl, *output_prefix_type, serialized_key_format);
}

absl::StatusOr<ChaCha20Poly1305Key> ParseKey(
    const internal::ProtoKeySerialization& serialization,
    absl::optional<SecretKeyAccessToken> token) {
  if (serialization.TypeUrl() != kTypeUrl) {
    return absl::InvalidArgumentError(
        "Wrong type URL when parsing ChaCha20Poly1305Key.");
  }
  if (!token.has_value()) {
    return absl::InvalidArgumentError("SecretKeyAccess is required");
  }

  ChaCha20Poly1305KeyTP proto_key;
  if (!proto_key.ParseFromString(
          serialization.SerializedKeyProto().GetSecret(*token))) {
    return absl::InvalidArgumentError(
        "Failed to parse ChaCha20Poly1305Key proto");
  }
  if (proto_key.version() != 0) {
    return absl::InvalidArgumentError("Only version 0 keys are accepted.");
  }
  absl::StatusOr<ChaCha20Poly1305Parameters::Variant> variant =
      ToVariant(serialization.GetOutputPrefixTypeEnum());
  if (!variant.ok()) {
    return variant.status();
  }

  absl::StatusOr<ChaCha20Poly1305Parameters> parameters =
      ChaCha20Poly1305Parameters::Create(*variant);
  if (!parameters.ok()) return parameters.status();

  return ChaCha20Poly1305Key::Create(
      parameters->GetVariant(), RestrictedData(proto_key.key_value(), *token),
      serialization.IdRequirement(), GetPartialKeyAccess());
}

absl::StatusOr<internal::ProtoKeySerialization> SerializeKey(
    const ChaCha20Poly1305Key& key,
    absl::optional<SecretKeyAccessToken> token) {
  absl::StatusOr<RestrictedData> restricted_input =
      key.GetKeyBytes(GetPartialKeyAccess());
  if (!restricted_input.ok()) return restricted_input.status();
  if (!token.has_value()) {
    return absl::InvalidArgumentError("SecretKeyAccess is required");
  }

  ChaCha20Poly1305KeyTP proto_key;
  proto_key.set_version(0);
  proto_key.set_key_value(restricted_input->GetSecret(*token));

  absl::StatusOr<OutputPrefixTypeEnum> output_prefix_type =
      ToOutputPrefixType(key.GetParameters().GetVariant());
  if (!output_prefix_type.ok()) return output_prefix_type.status();

  SecretData serialized_key = proto_key.SerializeAsSecretData();
  return internal::ProtoKeySerialization::Create(
      kTypeUrl, RestrictedData(std::move(serialized_key), *token),
      KeyMaterialTypeEnum::kSymmetric, *output_prefix_type,
      key.GetIdRequirement());
}

ChaCha20Poly1305ProtoParametersParserImpl*
ChaCha20Poly1305ProtoParametersParser() {
  static auto* parser =
      new ChaCha20Poly1305ProtoParametersParserImpl(kTypeUrl, ParseParameters);
  return parser;
}

ChaCha20Poly1305ProtoParametersSerializerImpl*
ChaCha20Poly1305ProtoParametersSerializer() {
  static auto* serializer = new ChaCha20Poly1305ProtoParametersSerializerImpl(
      kTypeUrl, SerializeParameters);
  return serializer;
}

ChaCha20Poly1305ProtoKeyParserImpl* ChaCha20Poly1305ProtoKeyParser() {
  static auto* parser =
      new ChaCha20Poly1305ProtoKeyParserImpl(kTypeUrl, ParseKey);
  return parser;
}

ChaCha20Poly1305ProtoKeySerializerImpl* ChaCha20Poly1305ProtoKeySerializer() {
  static auto* serializer =
      new ChaCha20Poly1305ProtoKeySerializerImpl(SerializeKey);
  return serializer;
}

}  // namespace

absl::Status RegisterChaCha20Poly1305ProtoSerializationWithMutableRegistry(
    MutableSerializationRegistry& registry) {
  absl::Status status = registry.RegisterParametersParser(
      ChaCha20Poly1305ProtoParametersParser());
  if (!status.ok()) {
    return status;
  }

  status = registry.RegisterParametersSerializer(
      ChaCha20Poly1305ProtoParametersSerializer());
  if (!status.ok()) {
    return status;
  }

  status = registry.RegisterKeyParser(ChaCha20Poly1305ProtoKeyParser());
  if (!status.ok()) {
    return status;
  }

  return registry.RegisterKeySerializer(ChaCha20Poly1305ProtoKeySerializer());
}

absl::Status RegisterChaCha20Poly1305ProtoSerializationWithRegistryBuilder(
    SerializationRegistry::Builder& builder) {
  absl::Status status =
      builder.RegisterParametersParser(ChaCha20Poly1305ProtoParametersParser());
  if (!status.ok()) {
    return status;
  }

  status = builder.RegisterParametersSerializer(
      ChaCha20Poly1305ProtoParametersSerializer());
  if (!status.ok()) {
    return status;
  }

  status = builder.RegisterKeyParser(ChaCha20Poly1305ProtoKeyParser());
  if (!status.ok()) {
    return status;
  }

  return builder.RegisterKeySerializer(ChaCha20Poly1305ProtoKeySerializer());
}

}  // namespace internal
}  // namespace tink
}  // namespace crypto
