// Copyright 2025 Envoy Project Authors
//
// 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.

syntax = "proto3";

package envoy.extensions.wasm.v3;

import "envoy/config/core/v3/backoff.proto";
import "envoy/config/core/v3/base.proto";

import "google/protobuf/any.proto";
import "google/protobuf/wrappers.proto";

import "envoy/annotations/deprecation.proto";
import "udpa/annotations/status.proto";

option java_package = "io.envoyproxy.envoy.extensions.wasm.v3";
option java_outer_classname = "WasmProto";
option java_multiple_files = true;
option go_package = "github.com/envoyproxy/go-control-plane/envoy/extensions/wasm/v3;wasmv3";
option (udpa.annotations.file_status).package_version_status = ACTIVE;

// [#protodoc-title: Wasm]
// [#extension: envoy.bootstrap.wasm]

// If there is a fatal error on the VM (e.g. exception, ``abort()``), then the policy will be applied.
enum FailurePolicy {
  // No policy is specified. The default policy will be used. The default policy is ``FAIL_CLOSED``.
  UNSPECIFIED = 0;

  // New plugin instance will be created for the new request if the VM is failed. Note this will only
  // be applied to the following failures:
  //
  // * ``proxy_wasm::FailState::RuntimeError``
  //
  // This will fallback to the ``FAIL_CLOSED`` for all other failures.
  FAIL_RELOAD = 1;

  // All plugins associated with the VM will return an HTTP 503 error.
  FAIL_CLOSED = 2;

  // All plugins associated with the VM will be ignored and the filter chain will continue. This
  // makes sense when the plugin is optional.
  FAIL_OPEN = 3;
}

message ReloadConfig {
  // Backoff strategy for the VM failure reload. If not specified, the default 1s base interval
  // will be applied.
  config.core.v3.BackoffStrategy backoff = 1;
}

// Configuration for restricting Proxy-Wasm capabilities available to modules.
message CapabilityRestrictionConfig {
  // The Proxy-Wasm capabilities which will be allowed. Capabilities are mapped by
  // name. The ``SanitizationConfig`` which each capability maps to is currently unimplemented and ignored,
  // and so should be left empty.
  //
  // The capability names are given in the
  // `Proxy-Wasm ABI <https://github.com/proxy-wasm/spec/tree/master/abi-versions/vNEXT>`_.
  // Additionally, the following WASI capabilities from
  // `this list <https://github.com/WebAssembly/WASI/blob/master/phases/snapshot/docs.md#modules>`_
  // are implemented and can be allowed:
  // ``fd_write``, ``fd_read``, ``fd_seek``, ``fd_close``, ``fd_fdstat_get``, ``environ_get``, ``environ_sizes_get``,
  // ``args_get``, ``args_sizes_get``, ``proc_exit``, ``clock_time_get``, ``random_get``.
  map<string, SanitizationConfig> allowed_capabilities = 1;
}

// Configuration for sanitization of inputs to an allowed capability.
//
// .. note::
//   This is currently unimplemented.
message SanitizationConfig {
}

// Configuration for a Wasm VM.
// [#next-free-field: 8]
message VmConfig {
  // An ID which will be used along with a hash of the wasm code (or the name of the registered Null
  // VM plugin) to determine which VM will be used for the plugin. All plugins which use the same
  // ``vm_id`` and code will use the same VM. May be left blank. Sharing a VM between plugins can
  // reduce memory utilization and make sharing of data easier which may have security implications.
  // [#comment: TODO: add ref for details.]
  string vm_id = 1;

  // The Wasm runtime type, defaults to the first available Wasm engine used at Envoy build-time.
  // The priority to search for the available engine is: v8 -> wasmtime -> wamr.
  // Available Wasm runtime types are registered as extensions. The following runtimes are included
  // in Envoy code base:
  //
  // .. _extension_envoy.wasm.runtime.null:
  //
  // **envoy.wasm.runtime.null**: Null sandbox, the Wasm module must be compiled and linked into the
  // Envoy binary. The registered name is given in the ``code`` field as ``inline_string``.
  //
  // .. _extension_envoy.wasm.runtime.v8:
  //
  // **envoy.wasm.runtime.v8**: `V8 <https://v8.dev/>`_-based WebAssembly runtime.
  //
  // .. _extension_envoy.wasm.runtime.wamr:
  //
  // **envoy.wasm.runtime.wamr**: `WAMR <https://github.com/bytecodealliance/wasm-micro-runtime/>`_-based WebAssembly runtime.
  // This runtime is not enabled in the official build.
  //
  // .. _extension_envoy.wasm.runtime.wasmtime:
  //
  // **envoy.wasm.runtime.wasmtime**: `Wasmtime <https://wasmtime.dev/>`_-based WebAssembly runtime.
  // This runtime is not enabled in the official build.
  //
  // [#extension-category: envoy.wasm.runtime]
  string runtime = 2;

  // The Wasm code that Envoy will execute.
  config.core.v3.AsyncDataSource code = 3;

  // The Wasm configuration used in initialization of a new VM
  // (``proxy_on_start``). ``google.protobuf.Struct`` is serialized as JSON before
  // passing it to the plugin. ``google.protobuf.BytesValue`` and
  // ``google.protobuf.StringValue`` are passed directly without the wrapper.
  google.protobuf.Any configuration = 4;

  // Allow the wasm file to include pre-compiled code on VMs which support it.
  //
  // .. warning::
  //   This should only be enabled for trusted sources as the precompiled code is not
  //   verified.
  bool allow_precompiled = 5;

  // If true and the code needs to be remotely fetched and it is not in the cache then NACK the configuration
  // update and do a background fetch to fill the cache, otherwise fetch the code asynchronously and enter
  // warming state.
  bool nack_on_code_cache_miss = 6;

  // Specifies environment variables to be injected to this VM which will be available through
  // WASI's ``environ_get`` and ``environ_get_sizes`` system calls. Note that these functions
  // are generally called implicitly by your language's standard library. Therefore, you do not
  // need to call them directly. You can access environment variables in the same way you would
  // on native platforms.
  //
  // .. warning::
  //   Envoy rejects the configuration if there's conflict of key space.
  EnvironmentVariables environment_variables = 7;
}

message EnvironmentVariables {
  // The keys of *Envoy's* environment variables exposed to this VM. In other words, if a key exists in Envoy's environment
  // variables, then that key-value pair will be injected. Note that if a key does not exist, it will be ignored.
  repeated string host_env_keys = 1;

  // Explicitly given key-value pairs to be injected to this VM in the form of "KEY=VALUE".
  map<string, string> key_values = 2;
}

// Base Configuration for Wasm Plugins e.g. filters and services.
// [#next-free-field: 10]
message PluginConfig {
  // A unique name for a filters/services in a VM for use in identifying the filter/service if
  // multiple filters/services are handled by the same ``vm_id`` and ``root_id`` and for
  // logging/debugging.
  string name = 1;

  // A unique ID for a set of filters/services in a VM which will share a RootContext and Contexts
  // if applicable (e.g. an Wasm HttpFilter and an Wasm AccessLog). If left blank, all
  // filters/services with a blank root_id with the same ``vm_id`` will share Context(s).
  string root_id = 2;

  // Configuration for finding or starting VM.
  oneof vm {
    VmConfig vm_config = 3;
    // TODO: add referential VM configurations.
  }

  // Filter/service configuration used to configure or reconfigure a plugin
  // (``proxy_on_configure``).
  // ``google.protobuf.Struct`` is serialized as JSON before
  // passing it to the plugin. ``google.protobuf.BytesValue`` and
  // ``google.protobuf.StringValue`` are passed directly without the wrapper.
  google.protobuf.Any configuration = 4;

  // If there is a fatal error on the VM (e.g. exception, ``abort()``, ``on_start`` or ``on_configure`` return false),
  // then all plugins associated with the VM will either fail closed (by default), e.g. by returning an HTTP 503 error,
  // or fail open (if 'fail_open' is set to true) by bypassing the filter.
  //
  // .. note::
  //   When ``on_start`` or ``on_configure`` return ``false`` during xDS updates the xDS configuration will be rejected and when ``on_start`` or ``on_configure`` return ``false`` on
  //   initial startup the proxy will not start.
  //
  // This field is deprecated in favor of the ``failure_policy`` field.
  bool fail_open = 5 [deprecated = true, (envoy.annotations.deprecated_at_minor_version) = "3.0"];

  // The failure policy for the plugin.
  FailurePolicy failure_policy = 7;

  // Reload configuration. This is only applied when ``failure_policy`` is set to ``FAIL_RELOAD``.
  ReloadConfig reload_config = 8;

  // Configuration for restricting Proxy-Wasm capabilities available to modules.
  CapabilityRestrictionConfig capability_restriction_config = 6;

  // Whether or not to allow plugin onRequestHeaders and onResponseHeaders callbacks to return
  // FilterHeadersStatus::StopIteration.
  google.protobuf.BoolValue allow_on_headers_stop_iteration = 9;
}

// WasmService is configured as a built-in ``envoy.wasm_service`` :ref:`WasmService
// <config_wasm_service>` This opaque configuration will be used to create a Wasm Service.
message WasmService {
  // General plugin configuration.
  PluginConfig config = 1;

  // If true, create a single VM rather than creating one VM per worker. Such a singleton can
  // not be used with filters.
  bool singleton = 2;
}
