feat(api): crud for interface backend settings and create default peer flag (#765)
Docker / Build and Push (push) Canceled after 0s
github-pages / deploy (push) Canceled after 0s
Test / make test (push) Canceled after 0s
Docker / release (push) Canceled after 0s

This commit is contained in:
Christoph
2026-11-09 23:26:10 +01:00
parent 8bd9b6192e
commit 61c8ceaab8
6 changed files with 127 additions and 11 deletions
+15 -2
View File
@@ -51,6 +51,15 @@ definitions:
items: items:
type: string type: string
type: array type: array
Backend:
description: Backend is the configured backend ID used to manage this interface. Omit it on create to use the local backend, or on update to preserve the current backend.
example: local
minLength: 1
type: string
CreateDefaultPeer:
description: CreateDefaultPeer enables default peer creation for this interface. Defaults to false when omitted on create; preserves the current setting when omitted on update.
example: false
type: boolean
Disabled: Disabled:
description: Disabled is a flag that specifies if the interface is enabled (up) or not (down). Disabled interfaces are not able to accept connections. description: Disabled is a flag that specifies if the interface is enabled (up) or not (down). Disabled interfaces are not able to accept connections.
example: false example: false
@@ -699,7 +708,9 @@ paths:
tags: tags:
- Interfaces - Interfaces
put: put:
description: This endpoint updates an existing interface with the provided data. All required fields must be filled (e.g. name, private key, public key, ...). description: |-
This endpoint updates an existing interface with the provided data. All required fields must be filled (e.g. name, private key, public key, ...).
Backend must be a configured backend ID. Omitted Backend and CreateDefaultPeer fields preserve their existing values. Server-managed metadata is preserved.
operationId: interfaces_handleUpdatePut operationId: interfaces_handleUpdatePut
parameters: parameters:
- description: The interface identifier. - description: The interface identifier.
@@ -747,7 +758,9 @@ paths:
- Interfaces - Interfaces
/interface/new: /interface/new:
post: post:
description: This endpoint creates a new interface with the provided data. All required fields must be filled (e.g. name, private key, public key, ...). description: |-
This endpoint creates a new interface with the provided data. All required fields must be filled (e.g. name, private key, public key, ...).
Backend must be a configured backend ID. When omitted, the local backend is used. CreateDefaultPeer defaults to false when omitted, preserving legacy create behavior.
operationId: interfaces_handleCreatePost operationId: interfaces_handleCreatePost
parameters: parameters:
- description: The interface data. - description: The interface data.
@@ -113,7 +113,7 @@
] ]
}, },
"put": { "put": {
"description": "This endpoint updates an existing interface with the provided data. All required fields must be filled (e.g. name, private key, public key, ...).", "description": "This endpoint updates an existing interface with the provided data. All required fields must be filled (e.g. name, private key, public key, ...).\nBackend must be a configured backend ID. Omitted Backend and CreateDefaultPeer fields preserve their existing values. Server-managed metadata is preserved.",
"produces": [ "produces": [
"application/json" "application/json"
], ],
@@ -246,7 +246,7 @@
}, },
"/interface/new": { "/interface/new": {
"post": { "post": {
"description": "This endpoint creates a new interface with the provided data. All required fields must be filled (e.g. name, private key, public key, ...).", "description": "This endpoint creates a new interface with the provided data. All required fields must be filled (e.g. name, private key, public key, ...).\nBackend must be a configured backend ID. When omitted, the local backend is used. CreateDefaultPeer defaults to false when omitted, preserving legacy create behavior.",
"produces": [ "produces": [
"application/json" "application/json"
], ],
@@ -1601,6 +1601,17 @@
"10.11.12.1/24" "10.11.12.1/24"
] ]
}, },
"Backend": {
"description": "Backend is the configured backend ID used to manage this interface. Omit it on create to use the local backend, or on update to preserve the current backend.",
"type": "string",
"minLength": 1,
"example": "local"
},
"CreateDefaultPeer": {
"description": "CreateDefaultPeer enables default peer creation for this interface. Defaults to false when omitted on create; preserves the current setting when omitted on update.",
"type": "boolean",
"example": false
},
"Disabled": { "Disabled": {
"description": "Disabled is a flag that specifies if the interface is enabled (up) or not (down). Disabled interfaces are not able to accept connections.", "description": "Disabled is a flag that specifies if the interface is enabled (up) or not (down). Disabled interfaces are not able to accept connections.",
"type": "boolean", "type": "boolean",
@@ -52,6 +52,19 @@ definitions:
items: items:
type: string type: string
type: array type: array
Backend:
description: Backend is the configured backend ID used to manage this interface.
Omit it on create to use the local backend, or on update to preserve the
current backend.
example: local
minLength: 1
type: string
CreateDefaultPeer:
description: CreateDefaultPeer enables default peer creation for this interface.
Defaults to false when omitted on create; preserves the current setting
when omitted on update.
example: false
type: boolean
Disabled: Disabled:
description: Disabled is a flag that specifies if the interface is enabled description: Disabled is a flag that specifies if the interface is enabled
(up) or not (down). Disabled interfaces are not able to accept connections. (up) or not (down). Disabled interfaces are not able to accept connections.
@@ -755,8 +768,9 @@ paths:
tags: tags:
- Interfaces - Interfaces
put: put:
description: This endpoint updates an existing interface with the provided data. description: |-
All required fields must be filled (e.g. name, private key, public key, ...). This endpoint updates an existing interface with the provided data. All required fields must be filled (e.g. name, private key, public key, ...).
Backend must be a configured backend ID. Omitted Backend and CreateDefaultPeer fields preserve their existing values. Server-managed metadata is preserved.
operationId: interfaces_handleUpdatePut operationId: interfaces_handleUpdatePut
parameters: parameters:
- description: The interface identifier. - description: The interface identifier.
@@ -804,8 +818,9 @@ paths:
- Interfaces - Interfaces
/interface/new: /interface/new:
post: post:
description: This endpoint creates a new interface with the provided data. All description: |-
required fields must be filled (e.g. name, private key, public key, ...). This endpoint creates a new interface with the provided data. All required fields must be filled (e.g. name, private key, public key, ...).
Backend must be a configured backend ID. When omitted, the local backend is used. CreateDefaultPeer defaults to false when omitted, preserving legacy create behavior.
operationId: interfaces_handleCreatePost operationId: interfaces_handleCreatePost
parameters: parameters:
- description: The interface data. - description: The interface data.
@@ -3,6 +3,7 @@ package backend
import ( import (
"context" "context"
"fmt" "fmt"
"slices"
"github.com/h44z/wg-portal/internal/config" "github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain" "github.com/h44z/wg-portal/internal/domain"
@@ -79,6 +80,10 @@ func (s InterfaceService) Create(ctx context.Context, iface *domain.Interface) (
return nil, err return nil, err
} }
if err := s.validateBackend(iface.Backend); err != nil {
return nil, err
}
createdInterface, err := s.interfaces.CreateInterface(ctx, iface) createdInterface, err := s.interfaces.CreateInterface(ctx, iface)
if err != nil { if err != nil {
return nil, err return nil, err
@@ -101,6 +106,19 @@ func (s InterfaceService) Update(ctx context.Context, id domain.InterfaceIdentif
iface.Identifier, id, domain.ErrInvalidData) iface.Identifier, id, domain.ErrInvalidData)
} }
existingInterface, _, err := s.interfaces.GetInterfaceAndPeers(ctx, id)
if err != nil {
return nil, nil, err
}
if err := s.validateBackend(iface.Backend); err != nil {
return nil, nil, err
}
// These fields are managed by the server and cannot be changed through v1.
iface.IsDynamic = existingInterface.IsDynamic
iface.DriverType = existingInterface.DriverType
iface.LdapAllowedUsers = existingInterface.LdapAllowedUsers
updatedInterface, updatedPeers, err := s.interfaces.UpdateInterface(ctx, iface) updatedInterface, updatedPeers, err := s.interfaces.UpdateInterface(ctx, iface)
if err != nil { if err != nil {
return nil, nil, err return nil, nil, err
@@ -109,6 +127,22 @@ func (s InterfaceService) Update(ctx context.Context, id domain.InterfaceIdentif
return updatedInterface, updatedPeers, nil return updatedInterface, updatedPeers, nil
} }
// validateBackend validates against configured IDs so a typo cannot silently use
// the controller manager's fallback to the local backend.
func (s InterfaceService) validateBackend(backend domain.InterfaceBackend) error {
id := string(backend)
// Empty is the legacy representation of the local backend in domain objects.
if id == "" || id == config.LocalBackendName ||
slices.ContainsFunc(s.cfg.Backend.Mikrotik, func(b config.BackendMikrotik) bool { return b.Id == id }) ||
slices.ContainsFunc(s.cfg.Backend.Pfsense, func(b config.BackendPfsense) bool { return b.Id == id }) ||
slices.ContainsFunc(s.cfg.Backend.Opnsense, func(b config.BackendOpnsense) bool { return b.Id == id }) {
return nil
}
return fmt.Errorf("unknown interface backend %q: %w", id, domain.ErrInvalidData)
}
func (s InterfaceService) Delete(ctx context.Context, id domain.InterfaceIdentifier) error { func (s InterfaceService) Delete(ctx context.Context, id domain.InterfaceIdentifier) error {
if err := domain.ValidateAdminAccessRights(ctx); err != nil { if err := domain.ValidateAdminAccessRights(ctx); err != nil {
return err return err
@@ -2,6 +2,7 @@ package handlers
import ( import (
"context" "context"
"errors"
"net/http" "net/http"
"github.com/go-pkgz/routegroup" "github.com/go-pkgz/routegroup"
@@ -146,6 +147,7 @@ func (e InterfaceEndpoint) handlePrepareGet() http.HandlerFunc {
// @Tags Interfaces // @Tags Interfaces
// @Summary Create a new interface record. // @Summary Create a new interface record.
// @Description This endpoint creates a new interface with the provided data. All required fields must be filled (e.g. name, private key, public key, ...). // @Description This endpoint creates a new interface with the provided data. All required fields must be filled (e.g. name, private key, public key, ...).
// @Description Backend must be a configured backend ID. When omitted, the local backend is used.
// @Param request body models.Interface true "The interface data." // @Param request body models.Interface true "The interface data."
// @Produce json // @Produce json
// @Success 200 {object} models.Interface // @Success 200 {object} models.Interface
@@ -163,7 +165,7 @@ func (e InterfaceEndpoint) handleCreatePost() http.HandlerFunc {
respond.JSON(w, http.StatusBadRequest, models.Error{Code: http.StatusBadRequest, Message: err.Error()}) respond.JSON(w, http.StatusBadRequest, models.Error{Code: http.StatusBadRequest, Message: err.Error()})
return return
} }
if err := e.validator.Struct(iface); err != nil { if err := e.validateInterfaceInput(&iface); err != nil {
respond.JSON(w, http.StatusBadRequest, models.Error{Code: http.StatusBadRequest, Message: err.Error()}) respond.JSON(w, http.StatusBadRequest, models.Error{Code: http.StatusBadRequest, Message: err.Error()})
return return
} }
@@ -185,6 +187,7 @@ func (e InterfaceEndpoint) handleCreatePost() http.HandlerFunc {
// @Tags Interfaces // @Tags Interfaces
// @Summary Update an interface record. // @Summary Update an interface record.
// @Description This endpoint updates an existing interface with the provided data. All required fields must be filled (e.g. name, private key, public key, ...). // @Description This endpoint updates an existing interface with the provided data. All required fields must be filled (e.g. name, private key, public key, ...).
// @Description Backend must be a configured backend ID. Omitted Backend and CreateDefaultPeer fields preserve their existing values. Server-managed metadata is preserved.
// @Param id path string true "The interface identifier." // @Param id path string true "The interface identifier."
// @Param request body models.Interface true "The interface data." // @Param request body models.Interface true "The interface data."
// @Produce json // @Produce json
@@ -210,7 +213,7 @@ func (e InterfaceEndpoint) handleUpdatePut() http.HandlerFunc {
respond.JSON(w, http.StatusBadRequest, models.Error{Code: http.StatusBadRequest, Message: err.Error()}) respond.JSON(w, http.StatusBadRequest, models.Error{Code: http.StatusBadRequest, Message: err.Error()})
return return
} }
if err := e.validator.Struct(iface); err != nil { if err := e.validateInterfaceInput(&iface); err != nil {
respond.JSON(w, http.StatusBadRequest, models.Error{Code: http.StatusBadRequest, Message: err.Error()}) respond.JSON(w, http.StatusBadRequest, models.Error{Code: http.StatusBadRequest, Message: err.Error()})
return return
} }
@@ -221,10 +224,26 @@ func (e InterfaceEndpoint) handleUpdatePut() http.HandlerFunc {
return return
} }
domainInterface := models.NewDomainInterface(&iface)
if iface.Backend == nil || iface.CreateDefaultPeer == nil {
existing, _, err := e.interfaces.GetById(r.Context(), domain.InterfaceIdentifier(id))
if err != nil {
status, model := ParseServiceError(err)
respond.JSON(w, status, model)
return
}
if iface.Backend == nil {
domainInterface.Backend = existing.Backend
}
if iface.CreateDefaultPeer == nil {
domainInterface.CreateDefaultPeer = existing.CreateDefaultPeer
}
}
updatedInterface, updatedInterfacePeers, err := e.interfaces.Update( updatedInterface, updatedInterfacePeers, err := e.interfaces.Update(
r.Context(), r.Context(),
domain.InterfaceIdentifier(id), domain.InterfaceIdentifier(id),
models.NewDomainInterface(&iface), domainInterface,
) )
if err != nil { if err != nil {
status, model := ParseServiceError(err) status, model := ParseServiceError(err)
@@ -236,6 +255,13 @@ func (e InterfaceEndpoint) handleUpdatePut() http.HandlerFunc {
} }
} }
func (e InterfaceEndpoint) validateInterfaceInput(iface *models.Interface) error {
if iface.Backend != nil && *iface.Backend == "" {
return errors.New("interface backend must not be empty")
}
return e.validator.Struct(iface)
}
// handleDelete returns a gorm handler function. // handleDelete returns a gorm handler function.
// //
// @ID interfaces_handleDelete // @ID interfaces_handleDelete
@@ -4,6 +4,7 @@ import (
"time" "time"
"github.com/h44z/wg-portal/internal" "github.com/h44z/wg-portal/internal"
"github.com/h44z/wg-portal/internal/config"
"github.com/h44z/wg-portal/internal/domain" "github.com/h44z/wg-portal/internal/domain"
) )
@@ -15,6 +16,10 @@ type Interface struct {
DisplayName string `json:"DisplayName" binding:"omitempty,max=64" example:"My Interface"` DisplayName string `json:"DisplayName" binding:"omitempty,max=64" example:"My Interface"`
// Mode is the interface type, either 'server', 'client' or 'any'. The mode specifies how WireGuard Portal handles peers for this interface. // Mode is the interface type, either 'server', 'client' or 'any'. The mode specifies how WireGuard Portal handles peers for this interface.
Mode string `json:"Mode" example:"server" binding:"required,oneof=server client any"` Mode string `json:"Mode" example:"server" binding:"required,oneof=server client any"`
// Backend is the configured backend ID used to manage this interface. Omit it on create to use the local backend, or on update to preserve the current backend.
Backend *string `json:"Backend,omitempty" example:"local" binding:"omitempty,min=1"`
// CreateDefaultPeer enables default peer creation for this interface. Defaults to false when omitted on create; preserves the current setting when omitted on update.
CreateDefaultPeer *bool `json:"CreateDefaultPeer,omitempty" example:"false"`
// PrivateKey is the private key of the interface. // PrivateKey is the private key of the interface.
PrivateKey string `json:"PrivateKey" example:"gI6EdUSYvn8ugXOt8QQD6Yc+JyiZxIhp3GInSWRfWGE=" binding:"required,len=44"` PrivateKey string `json:"PrivateKey" example:"gI6EdUSYvn8ugXOt8QQD6Yc+JyiZxIhp3GInSWRfWGE=" binding:"required,len=44"`
// PublicKey is the public key of the server interface. The public key is used by peers to connect to the server. // PublicKey is the public key of the server interface. The public key is used by peers to connect to the server.
@@ -90,10 +95,16 @@ type Interface struct {
} }
func NewInterface(src *domain.Interface, peers []domain.Peer) *Interface { func NewInterface(src *domain.Interface, peers []domain.Peer) *Interface {
backend := string(src.Backend)
if backend == "" {
backend = config.LocalBackendName
}
iface := &Interface{ iface := &Interface{
Identifier: string(src.Identifier), Identifier: string(src.Identifier),
DisplayName: src.DisplayName, DisplayName: src.DisplayName,
Mode: string(src.Type), Mode: string(src.Type),
Backend: &backend,
CreateDefaultPeer: new(src.CreateDefaultPeer),
PrivateKey: src.PrivateKey, PrivateKey: src.PrivateKey,
PublicKey: src.PublicKey, PublicKey: src.PublicKey,
Disabled: src.IsDisabled(), Disabled: src.IsDisabled(),
@@ -198,6 +209,12 @@ func NewDomainInterface(src *Interface) *domain.Interface {
if src.Disabled { if src.Disabled {
res.Disabled = &now res.Disabled = &now
} }
if src.Backend != nil {
res.Backend = domain.InterfaceBackend(*src.Backend)
}
if src.CreateDefaultPeer != nil {
res.CreateDefaultPeer = *src.CreateDefaultPeer
}
return res return res
} }