646fa0f840
Add a Terraform provider that manages the Gitea token secrets engine (vault-plugin-secrets-gitea) on Vault/OpenBao, so terraform-vault can drive the engine's mount, config, and roles declaratively. - add the provider (source git.unkin.net/unkin/giteavaultsecret, prefix gitea_) - add gitea_secret_backend (mount + config with seeded admin credentials) - add gitea_secret_backend_role (username, scopes list, ttls, token_name_prefix) - add the Vault API client plumbing, conversions, and unit tests - add examples, a real terraform+Vault+mock-Gitea e2e, and Woodpecker pipelines releasing the provider zip to the artifactapi terraform registry Claude-Session: https://claude.ai/code/session_015ur3i7D2azsMAWTSVABApv
279 lines
9.8 KiB
Go
279 lines
9.8 KiB
Go
package provider
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"github.com/hashicorp/terraform-plugin-framework/path"
|
|
"github.com/hashicorp/terraform-plugin-framework/resource"
|
|
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
|
|
"github.com/hashicorp/terraform-plugin-framework/resource/schema/booldefault"
|
|
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64default"
|
|
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
|
|
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault"
|
|
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
|
|
"github.com/hashicorp/terraform-plugin-framework/types"
|
|
)
|
|
|
|
var (
|
|
_ resource.Resource = &secretBackendResource{}
|
|
_ resource.ResourceWithImportState = &secretBackendResource{}
|
|
)
|
|
|
|
const defaultPluginType = "vault-plugin-secrets-gitea"
|
|
|
|
type secretBackendResource struct {
|
|
client *vaultClient
|
|
}
|
|
|
|
type secretBackendModel struct {
|
|
Path types.String `tfsdk:"path"`
|
|
Plugin types.String `tfsdk:"plugin"`
|
|
Description types.String `tfsdk:"description"`
|
|
GiteaURL types.String `tfsdk:"gitea_url"`
|
|
AdminUsername types.String `tfsdk:"admin_username"`
|
|
AdminPassword types.String `tfsdk:"admin_password"`
|
|
AdminLoginName types.String `tfsdk:"admin_login_name"`
|
|
AdminSourceID types.Int64 `tfsdk:"admin_source_id"`
|
|
CACert types.String `tfsdk:"ca_cert"`
|
|
TLSSkipVerify types.Bool `tfsdk:"tls_skip_verify"`
|
|
RequestTimeoutSeconds types.Int64 `tfsdk:"request_timeout_seconds"`
|
|
}
|
|
|
|
func NewSecretBackendResource() resource.Resource {
|
|
return &secretBackendResource{}
|
|
}
|
|
|
|
func (r *secretBackendResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
|
|
resp.TypeName = req.ProviderTypeName + "_secret_backend"
|
|
}
|
|
|
|
func (r *secretBackendResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
|
|
resp.Schema = schema.Schema{
|
|
Description: "Mounts the Gitea secrets engine and writes its connection config and seeded admin credentials.",
|
|
Attributes: map[string]schema.Attribute{
|
|
"path": schema.StringAttribute{
|
|
Description: "Mount path for the Gitea secrets engine (e.g. \"gitea\").",
|
|
Required: true,
|
|
PlanModifiers: []planmodifier.String{
|
|
stringplanmodifier.RequiresReplace(),
|
|
},
|
|
},
|
|
"plugin": schema.StringAttribute{
|
|
Description: "Registered plugin name/type to mount.",
|
|
Optional: true,
|
|
Computed: true,
|
|
Default: stringdefault.StaticString(defaultPluginType),
|
|
PlanModifiers: []planmodifier.String{
|
|
stringplanmodifier.RequiresReplace(),
|
|
},
|
|
},
|
|
"description": schema.StringAttribute{
|
|
Description: "Human-readable description of the mount.",
|
|
Optional: true,
|
|
Computed: true,
|
|
Default: stringdefault.StaticString(""),
|
|
},
|
|
"gitea_url": schema.StringAttribute{
|
|
Description: "Base URL of the Gitea server (e.g. https://git.example.com).",
|
|
Required: true,
|
|
},
|
|
"admin_username": schema.StringAttribute{
|
|
Description: "Username of the Gitea site admin whose Basic-Auth credentials the engine uses.",
|
|
Required: true,
|
|
},
|
|
"admin_password": schema.StringAttribute{
|
|
Description: "Password of the Gitea site admin (Basic Auth). Write-only; never read back. Rotate it out of band with `vault write -f <path>/config/rotate-root`.",
|
|
Required: true,
|
|
Sensitive: true,
|
|
},
|
|
"admin_login_name": schema.StringAttribute{
|
|
Description: "login_name sent to Gitea's admin edit API during rotate-root (defaults to admin_username server-side).",
|
|
Optional: true,
|
|
},
|
|
"admin_source_id": schema.Int64Attribute{
|
|
Description: "Authentication source ID of the admin user for rotate-root (0 for local users).",
|
|
Optional: true,
|
|
Computed: true,
|
|
Default: int64default.StaticInt64(0),
|
|
},
|
|
"ca_cert": schema.StringAttribute{
|
|
Description: "PEM CA certificate that signed the Gitea server's TLS certificate.",
|
|
Optional: true,
|
|
},
|
|
"tls_skip_verify": schema.BoolAttribute{
|
|
Description: "Skip TLS verification of the Gitea server (not recommended).",
|
|
Optional: true,
|
|
Computed: true,
|
|
Default: booldefault.StaticBool(false),
|
|
},
|
|
"request_timeout_seconds": schema.Int64Attribute{
|
|
Description: "HTTP timeout in seconds for calls from the plugin to Gitea.",
|
|
Optional: true,
|
|
Computed: true,
|
|
Default: int64default.StaticInt64(30),
|
|
},
|
|
},
|
|
}
|
|
}
|
|
|
|
func (r *secretBackendResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
|
|
if req.ProviderData == nil {
|
|
return
|
|
}
|
|
client, ok := req.ProviderData.(*vaultClient)
|
|
if !ok {
|
|
resp.Diagnostics.AddError("unexpected provider data type", fmt.Sprintf("got %T", req.ProviderData))
|
|
return
|
|
}
|
|
r.client = client
|
|
}
|
|
|
|
func (r *secretBackendResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
|
|
var plan secretBackendModel
|
|
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
|
|
mountPath := strings.Trim(plan.Path.ValueString(), "/")
|
|
|
|
err := r.client.enableMount(ctx, mountPath, plan.Plugin.ValueString(), plan.Description.ValueString(), mountConfig{})
|
|
if err != nil {
|
|
if isMountAlreadyExists(err) {
|
|
resp.Diagnostics.AddError(
|
|
"mount path already in use",
|
|
fmt.Sprintf("A secrets engine is already mounted at %q. Import it or choose another path.", mountPath),
|
|
)
|
|
return
|
|
}
|
|
resp.Diagnostics.AddError("failed to enable gitea secrets engine", err.Error())
|
|
return
|
|
}
|
|
|
|
if err := r.client.write(ctx, configPath(mountPath), r.configData(plan)); err != nil {
|
|
// Roll back the mount so we don't leave a half-configured engine.
|
|
_ = r.client.disableMount(ctx, mountPath)
|
|
resp.Diagnostics.AddError("failed to write gitea config", err.Error())
|
|
return
|
|
}
|
|
|
|
plan.Path = types.StringValue(mountPath)
|
|
resp.Diagnostics.Append(resp.State.Set(ctx, plan)...)
|
|
}
|
|
|
|
func (r *secretBackendResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
|
|
var state secretBackendModel
|
|
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
|
|
mountPath := strings.Trim(state.Path.ValueString(), "/")
|
|
|
|
mount, err := r.client.mountInfo(ctx, mountPath)
|
|
if err != nil {
|
|
resp.Diagnostics.AddError("failed to read mount", err.Error())
|
|
return
|
|
}
|
|
if mount == nil {
|
|
resp.State.RemoveResource(ctx)
|
|
return
|
|
}
|
|
state.Description = types.StringValue(mount.Description)
|
|
if mount.Type != "" {
|
|
state.Plugin = types.StringValue(mount.Type)
|
|
}
|
|
|
|
cfg, err := r.client.read(ctx, configPath(mountPath))
|
|
if err != nil {
|
|
resp.Diagnostics.AddError("failed to read gitea config", err.Error())
|
|
return
|
|
}
|
|
if cfg != nil {
|
|
if v, ok := cfg["gitea_url"].(string); ok {
|
|
state.GiteaURL = types.StringValue(v)
|
|
}
|
|
if v, ok := cfg["admin_username"].(string); ok {
|
|
state.AdminUsername = types.StringValue(v)
|
|
}
|
|
if v, ok := cfg["admin_login_name"].(string); ok && v != "" {
|
|
state.AdminLoginName = types.StringValue(v)
|
|
}
|
|
if n, ok := toInt64(cfg["admin_source_id"]); ok {
|
|
state.AdminSourceID = types.Int64Value(n)
|
|
}
|
|
if v, ok := cfg["tls_skip_verify"].(bool); ok {
|
|
state.TLSSkipVerify = types.BoolValue(v)
|
|
}
|
|
if n, ok := toInt64(cfg["request_timeout_seconds"]); ok {
|
|
state.RequestTimeoutSeconds = types.Int64Value(n)
|
|
}
|
|
}
|
|
// admin_password and ca_cert are never returned by the backend; preserve the
|
|
// state values.
|
|
|
|
resp.Diagnostics.Append(resp.State.Set(ctx, state)...)
|
|
}
|
|
|
|
func (r *secretBackendResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
|
|
var plan, state secretBackendModel
|
|
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
|
|
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
|
|
mountPath := strings.Trim(state.Path.ValueString(), "/")
|
|
|
|
if !plan.Description.Equal(state.Description) {
|
|
if err := r.client.tuneMount(ctx, mountPath, plan.Description.ValueString(), mountConfig{}); err != nil {
|
|
resp.Diagnostics.AddError("failed to tune mount description", err.Error())
|
|
return
|
|
}
|
|
}
|
|
|
|
if err := r.client.write(ctx, configPath(mountPath), r.configData(plan)); err != nil {
|
|
resp.Diagnostics.AddError("failed to update gitea config", err.Error())
|
|
return
|
|
}
|
|
|
|
plan.Path = types.StringValue(mountPath)
|
|
resp.Diagnostics.Append(resp.State.Set(ctx, plan)...)
|
|
}
|
|
|
|
func (r *secretBackendResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
|
|
var state secretBackendModel
|
|
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
|
|
if resp.Diagnostics.HasError() {
|
|
return
|
|
}
|
|
if err := r.client.disableMount(ctx, strings.Trim(state.Path.ValueString(), "/")); err != nil {
|
|
resp.Diagnostics.AddError("failed to disable gitea secrets engine", err.Error())
|
|
return
|
|
}
|
|
}
|
|
|
|
func (r *secretBackendResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
|
|
resource.ImportStatePassthroughID(ctx, path.Root("path"), req, resp)
|
|
}
|
|
|
|
func (r *secretBackendResource) configData(m secretBackendModel) map[string]interface{} {
|
|
data := map[string]interface{}{
|
|
"gitea_url": m.GiteaURL.ValueString(),
|
|
"admin_username": m.AdminUsername.ValueString(),
|
|
"admin_password": m.AdminPassword.ValueString(),
|
|
"admin_source_id": m.AdminSourceID.ValueInt64(),
|
|
"tls_skip_verify": m.TLSSkipVerify.ValueBool(),
|
|
"request_timeout_seconds": m.RequestTimeoutSeconds.ValueInt64(),
|
|
}
|
|
if !m.AdminLoginName.IsNull() && !m.AdminLoginName.IsUnknown() {
|
|
data["admin_login_name"] = m.AdminLoginName.ValueString()
|
|
}
|
|
if !m.CACert.IsNull() && !m.CACert.IsUnknown() {
|
|
data["ca_cert"] = m.CACert.ValueString()
|
|
}
|
|
return data
|
|
}
|