chore: import upstream snapshot with attribution

This commit is contained in:
wehub-resource-sync
2026-07-13 12:08:39 +08:00
commit a0df89c693
5252 changed files with 523444 additions and 0 deletions
+40
View File
@@ -0,0 +1,40 @@
package webhooks
import (
"net/http"
"github.com/portainer/portainer/api/dataservices"
dockerclient "github.com/portainer/portainer/api/docker/client"
"github.com/portainer/portainer/api/http/security"
httperror "github.com/portainer/portainer/pkg/libhttp/error"
"github.com/gorilla/mux"
)
// Handler is the HTTP handler used to handle webhook operations.
type Handler struct {
*mux.Router
requestBouncer security.BouncerService
DataStore dataservices.DataStore
DockerClientFactory *dockerclient.ClientFactory
}
// NewHandler creates a handler to manage webhooks operations.
func NewHandler(bouncer security.BouncerService) *Handler {
h := &Handler{
Router: mux.NewRouter(),
requestBouncer: bouncer,
}
h.Handle("/webhooks",
bouncer.AuthenticatedAccess(httperror.LoggerHandler(h.webhookCreate))).Methods(http.MethodPost)
h.Handle("/webhooks/{id}",
bouncer.AuthenticatedAccess(httperror.LoggerHandler(h.webhookUpdate))).Methods(http.MethodPut)
h.Handle("/webhooks",
bouncer.AuthenticatedAccess(httperror.LoggerHandler(h.webhookList))).Methods(http.MethodGet)
h.Handle("/webhooks/{id}",
bouncer.AuthenticatedAccess(httperror.LoggerHandler(h.webhookDelete))).Methods(http.MethodDelete)
h.Handle("/webhooks/{token}",
bouncer.PublicAccess(httperror.LoggerHandler(h.webhookExecute))).Methods(http.MethodPost)
return h
}
+108
View File
@@ -0,0 +1,108 @@
package webhooks
import (
"errors"
"net/http"
portainer "github.com/portainer/portainer/api"
"github.com/portainer/portainer/api/http/security"
"github.com/portainer/portainer/api/internal/registryutils/access"
httperror "github.com/portainer/portainer/pkg/libhttp/error"
"github.com/portainer/portainer/pkg/libhttp/request"
"github.com/portainer/portainer/pkg/libhttp/response"
"github.com/google/uuid"
)
type webhookCreatePayload struct {
ResourceID string
EndpointID portainer.EndpointID
RegistryID portainer.RegistryID
// Type of webhook (1 - service)
WebhookType portainer.WebhookType
}
func (payload *webhookCreatePayload) Validate(r *http.Request) error {
if len(payload.ResourceID) == 0 {
return errors.New("Invalid ResourceID")
}
if payload.EndpointID == 0 {
return errors.New("Invalid EndpointID")
}
if payload.WebhookType != portainer.ServiceWebhook {
return errors.New("Invalid WebhookType")
}
return nil
}
// @summary Create a webhook
// @description **Access policy**: authenticated
// @security ApiKeyAuth
// @security jwt
// @tags webhooks
// @accept json
// @produce json
// @param body body webhookCreatePayload true "Webhook data"
// @success 200 {object} portainer.Webhook
// @failure 400 "Invalid request"
// @failure 409 "A webhook for this resource already exists"
// @failure 500 "Server error"
// @router /webhooks [post]
func (handler *Handler) webhookCreate(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
var payload webhookCreatePayload
err := request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return httperror.BadRequest("Invalid request payload", err)
}
webhook, err := handler.DataStore.Webhook().WebhookByResourceID(payload.ResourceID)
if err != nil && !handler.DataStore.IsErrObjectNotFound(err) {
return httperror.InternalServerError("An error occurred retrieving webhooks from the database", err)
}
if webhook != nil {
return httperror.Conflict("A webhook for this resource already exists", errors.New("A webhook for this resource already exists"))
}
endpointID := payload.EndpointID
securityContext, err := security.RetrieveRestrictedRequestContext(r)
if err != nil {
return httperror.InternalServerError("Unable to retrieve user info from request context", err)
}
if !securityContext.IsAdmin {
return httperror.Forbidden("Not authorized to create a webhook", errors.New("not authorized to create a webhook"))
}
if payload.RegistryID != 0 {
tokenData, err := security.RetrieveTokenData(r)
if err != nil {
return httperror.InternalServerError("Unable to retrieve user authentication token", err)
}
_, err = access.GetAccessibleRegistry(handler.DataStore, nil, tokenData.ID, endpointID, payload.RegistryID)
if err != nil {
return httperror.Forbidden("Permission deny to access registry", err)
}
}
token, err := uuid.NewRandom()
if err != nil {
return httperror.InternalServerError("Error creating unique token", err)
}
webhook = &portainer.Webhook{
Token: token.String(),
ResourceID: payload.ResourceID,
EndpointID: endpointID,
RegistryID: payload.RegistryID,
WebhookType: payload.WebhookType,
}
err = handler.DataStore.Webhook().Create(webhook)
if err != nil {
return httperror.InternalServerError("Unable to persist the webhook inside the database", err)
}
return response.JSON(w, webhook)
}
@@ -0,0 +1,45 @@
package webhooks
import (
"errors"
"net/http"
portainer "github.com/portainer/portainer/api"
"github.com/portainer/portainer/api/http/security"
httperror "github.com/portainer/portainer/pkg/libhttp/error"
"github.com/portainer/portainer/pkg/libhttp/request"
"github.com/portainer/portainer/pkg/libhttp/response"
)
// @summary Delete a webhook
// @description **Access policy**: authenticated
// @security ApiKeyAuth
// @security jwt
// @tags webhooks
// @param id path int true "Webhook id"
// @success 202 "Webhook deleted"
// @failure 400
// @failure 500
// @router /webhooks/{id} [delete]
func (handler *Handler) webhookDelete(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
id, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return httperror.BadRequest("Invalid webhook id", err)
}
securityContext, err := security.RetrieveRestrictedRequestContext(r)
if err != nil {
return httperror.InternalServerError("Unable to retrieve user info from request context", err)
}
if !securityContext.IsAdmin {
return httperror.Forbidden("Not authorized to delete a webhook", errors.New("not authorized to delete a webhook"))
}
err = handler.DataStore.Webhook().Delete(portainer.WebhookID(id))
if err != nil {
return httperror.InternalServerError("Unable to remove the webhook from the database", err)
}
return response.Empty(w)
}
@@ -0,0 +1,132 @@
package webhooks
import (
"context"
"errors"
"net/http"
"strings"
portainer "github.com/portainer/portainer/api"
"github.com/portainer/portainer/api/internal/registryutils"
"github.com/portainer/portainer/api/logs"
httperror "github.com/portainer/portainer/pkg/libhttp/error"
"github.com/portainer/portainer/pkg/libhttp/request"
"github.com/portainer/portainer/pkg/libhttp/response"
"github.com/rs/zerolog/log"
dockertypes "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/image"
)
// @summary Execute a webhook
// @description Acts on a passed in token UUID to restart the docker service
// @description **Access policy**: public
// @tags webhooks
// @param id path string true "Webhook token"
// @success 202 "Webhook executed"
// @failure 400
// @failure 500
// @router /webhooks/{id} [post]
func (handler *Handler) webhookExecute(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
webhookToken, err := request.RetrieveRouteVariableValue(r, "token")
if err != nil {
return httperror.InternalServerError("Invalid service id parameter", err)
}
webhook, err := handler.DataStore.Webhook().WebhookByToken(webhookToken)
if handler.DataStore.IsErrObjectNotFound(err) {
return httperror.NotFound("Unable to find a webhook with this token", err)
} else if err != nil {
return httperror.InternalServerError("Unable to retrieve webhook from the database", err)
}
resourceID := webhook.ResourceID
endpointID := webhook.EndpointID
registryID := webhook.RegistryID
webhookType := webhook.WebhookType
endpoint, err := handler.DataStore.Endpoint().Endpoint(endpointID)
if handler.DataStore.IsErrObjectNotFound(err) {
return httperror.NotFound("Unable to find an environment with the specified identifier inside the database", err)
} else if err != nil {
return httperror.InternalServerError("Unable to find an environment with the specified identifier inside the database", err)
}
imageTag, _ := request.RetrieveQueryParameter(r, "tag", true)
switch webhookType {
case portainer.ServiceWebhook:
return handler.executeServiceWebhook(w, endpoint, resourceID, registryID, imageTag)
default:
return httperror.InternalServerError("Unsupported webhook type", errors.New("Webhooks for this resource are not currently supported"))
}
}
func (handler *Handler) executeServiceWebhook(
w http.ResponseWriter,
endpoint *portainer.Endpoint,
resourceID string,
registryID portainer.RegistryID,
imageTag string,
) *httperror.HandlerError {
dockerClient, err := handler.DockerClientFactory.CreateClient(endpoint, "", nil)
if err != nil {
return httperror.InternalServerError("Error creating docker client", err)
}
defer logs.CloseAndLogErr(dockerClient)
service, _, err := dockerClient.ServiceInspectWithRaw(context.Background(), resourceID, dockertypes.ServiceInspectOptions{InsertDefaults: true})
if err != nil {
return httperror.InternalServerError("Error looking up service", err)
}
service.Spec.TaskTemplate.ForceUpdate++
imageName := strings.Split(service.Spec.TaskTemplate.ContainerSpec.Image, "@sha")[0]
service.Spec.TaskTemplate.ContainerSpec.Image = imageName
if imageTag != "" {
tagIndex := strings.LastIndex(imageName, ":")
if tagIndex == -1 {
tagIndex = len(imageName)
}
service.Spec.TaskTemplate.ContainerSpec.Image = imageName[:tagIndex] + ":" + imageTag
}
serviceUpdateOptions := dockertypes.ServiceUpdateOptions{
QueryRegistry: true,
}
if registryID != 0 {
registry, err := handler.DataStore.Registry().Read(registryID)
if err != nil {
return httperror.InternalServerError("Error getting registry", err)
}
if registry.Authentication {
if err := registryutils.EnsureRegTokenValid(handler.DataStore, registry); err != nil {
log.Warn().Err(err).Msgf("registry auth token renewal failed for registry %d", registry.ID)
}
serviceUpdateOptions.EncodedRegistryAuth, err = registryutils.GetRegistryAuthHeader(registry)
if err != nil {
return httperror.InternalServerError("Error getting registry auth header", err)
}
}
}
if imageTag != "" {
rc, err := dockerClient.ImagePull(context.Background(), service.Spec.TaskTemplate.ContainerSpec.Image, image.PullOptions{RegistryAuth: serviceUpdateOptions.EncodedRegistryAuth})
if err != nil {
return httperror.NotFound("Error pulling image with the specified tag", err)
}
defer logs.CloseAndLogErr(rc)
}
if _, err := dockerClient.ServiceUpdate(context.Background(), resourceID, service.Version, service.Spec, serviceUpdateOptions); err != nil {
return httperror.InternalServerError("Error updating service", err)
}
return response.Empty(w)
}
+68
View File
@@ -0,0 +1,68 @@
package webhooks
import (
"net/http"
portainer "github.com/portainer/portainer/api"
"github.com/portainer/portainer/api/http/security"
httperror "github.com/portainer/portainer/pkg/libhttp/error"
"github.com/portainer/portainer/pkg/libhttp/request"
"github.com/portainer/portainer/pkg/libhttp/response"
)
type webhookListOperationFilters struct {
ResourceID string `json:"ResourceID"`
EndpointID int `json:"EndpointID"`
}
// @summary List webhooks
// @description **Access policy**: authenticated
// @security ApiKeyAuth
// @security jwt
// @tags webhooks
// @accept json
// @produce json
// @param filters query string false "Filters (json-string)" example({"EndpointID":1,"ResourceID":"abc12345-abcd-2345-ab12-58005b4a0260"})
// @success 200 {array} portainer.Webhook
// @failure 400
// @failure 500
// @router /webhooks [get]
func (handler *Handler) webhookList(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
var filters webhookListOperationFilters
err := request.RetrieveJSONQueryParameter(r, "filters", &filters, true)
if err != nil {
return httperror.BadRequest("Invalid query parameter: filters", err)
}
securityContext, err := security.RetrieveRestrictedRequestContext(r)
if err != nil {
return httperror.InternalServerError("Unable to retrieve user info from request context", err)
}
if !securityContext.IsAdmin {
return response.JSON(w, []portainer.Webhook{})
}
webhooks, err := handler.DataStore.Webhook().ReadAll()
if err != nil {
return httperror.InternalServerError("Unable to retrieve webhooks from the database", err)
}
webhooks = filterWebhooks(webhooks, &filters)
return response.JSON(w, webhooks)
}
func filterWebhooks(webhooks []portainer.Webhook, filters *webhookListOperationFilters) []portainer.Webhook {
if filters.EndpointID == 0 && filters.ResourceID == "" {
return webhooks
}
filteredWebhooks := make([]portainer.Webhook, 0, len(webhooks))
for _, webhook := range webhooks {
if webhook.EndpointID == portainer.EndpointID(filters.EndpointID) && webhook.ResourceID == filters.ResourceID {
filteredWebhooks = append(filteredWebhooks, webhook)
}
}
return filteredWebhooks
}
@@ -0,0 +1,86 @@
package webhooks
import (
"errors"
"net/http"
portainer "github.com/portainer/portainer/api"
"github.com/portainer/portainer/api/http/security"
"github.com/portainer/portainer/api/internal/registryutils/access"
httperror "github.com/portainer/portainer/pkg/libhttp/error"
"github.com/portainer/portainer/pkg/libhttp/request"
"github.com/portainer/portainer/pkg/libhttp/response"
)
type webhookUpdatePayload struct {
RegistryID portainer.RegistryID
}
func (payload *webhookUpdatePayload) Validate(r *http.Request) error {
return nil
}
// @summary Update a webhook
// @description **Access policy**: authenticated
// @security ApiKeyAuth
// @security jwt
// @tags webhooks
// @accept json
// @produce json
// @param id path int true "Webhook id"
// @param body body webhookUpdatePayload true "Webhook data"
// @success 200 {object} portainer.Webhook
// @failure 400
// @failure 409
// @failure 500
// @router /webhooks/{id} [put]
func (handler *Handler) webhookUpdate(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
id, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return httperror.BadRequest("Invalid webhook id", err)
}
webhookID := portainer.WebhookID(id)
var payload webhookUpdatePayload
err = request.DecodeAndValidateJSONPayload(r, &payload)
if err != nil {
return httperror.BadRequest("Invalid request payload", err)
}
webhook, err := handler.DataStore.Webhook().Read(webhookID)
if handler.DataStore.IsErrObjectNotFound(err) {
return httperror.NotFound("Unable to find a webhooks with the specified identifier inside the database", err)
} else if err != nil {
return httperror.InternalServerError("Unable to find a webhooks with the specified identifier inside the database", err)
}
securityContext, err := security.RetrieveRestrictedRequestContext(r)
if err != nil {
return httperror.InternalServerError("Unable to retrieve user info from request context", err)
}
if !securityContext.IsAdmin {
return httperror.Forbidden("Not authorized to update a webhook", errors.New("not authorized to update a webhook"))
}
if payload.RegistryID != 0 {
tokenData, err := security.RetrieveTokenData(r)
if err != nil {
return httperror.InternalServerError("Unable to retrieve user authentication token", err)
}
_, err = access.GetAccessibleRegistry(handler.DataStore, nil, tokenData.ID, webhook.EndpointID, payload.RegistryID)
if err != nil {
return httperror.Forbidden("Permission deny to access registry", err)
}
}
webhook.RegistryID = payload.RegistryID
err = handler.DataStore.Webhook().Update(portainer.WebhookID(id), webhook)
if err != nil {
return httperror.InternalServerError("Unable to persist the webhook inside the database", err)
}
return response.JSON(w, webhook)
}