Files
portainer/api/http/handler/stacks/stack_file.go
T
agent_coder bb68acfbf6 fix(#29 review r1): stack-delete leak, rollback/retention/version tests, UX trap
F3: deleting a file-based stack now removes the stack ROOT (compose/{id}) via a
new removeStackProjectDir helper, not stack.ProjectPath (which the PR repointed to
compose/{id}/v{N}) — old version dirs + parent no longer leak. Git stacks unchanged.
F1: tests for validateRollbackTarget (rejects 0/neg/>current/hole) and the rollback
snapshot (client content ignored, target read from disk, monotonic new version, note).
F2: tests for pruneStackFileVersionDirs (deletes given dirs, swallows errors) + the
post-commit gate contract + a monotonic-version regression guard.
F4: handler tests for ?version= (negative/out-of-range -> 400, valid version served,
legacy fallback).
F5: swagger @param version on GET file; @version 2.44.0 (handler.go) + package.json
2.44.0, matching APIVersion.
F6: the version selector no longer sets rollbackTo for the current/top version and
clears it on a manual buffer edit (so edits are honored, not silently discarded);
returning to the current version restores the current content. Distinguishes real
user edits from the programmatic version-load (CodeMirror ExternalChange).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 17:28:52 +03:00

164 lines
6.5 KiB
Go

package stacks
import (
"net/http"
"strconv"
portainer "github.com/portainer/portainer/api"
gittypes "github.com/portainer/portainer/api/git/types"
httperrors "github.com/portainer/portainer/api/http/errors"
"github.com/portainer/portainer/api/http/security"
"github.com/portainer/portainer/api/stacks/stackutils"
httperror "github.com/portainer/portainer/pkg/libhttp/error"
"github.com/portainer/portainer/pkg/libhttp/request"
"github.com/portainer/portainer/pkg/libhttp/response"
"github.com/pkg/errors"
)
type stackFileResponse struct {
// Content of the Stack file
StackFileContent string `json:"StackFileContent" example:"version: 3\n services:\n web:\n image:nginx"`
}
// @id StackFileInspect
// @summary Retrieve the content of the Stack file for the specified stack
// @description Get Stack file content.
// @description **Access policy**: restricted
// @tags stacks
// @security ApiKeyAuth
// @security jwt
// @produce json
// @param id path int true "Stack identifier"
// @param version query int false "return this file version (file-based stacks)"
// @success 200 {object} stackFileResponse "Success"
// @failure 400 "Invalid request"
// @failure 403 "Permission denied"
// @failure 404 "Stack not found"
// @failure 409 "Git settings changed, redeploy required"
// @failure 500 "Server error"
// @router /stacks/{id}/file [get]
func (handler *Handler) stackFile(w http.ResponseWriter, r *http.Request) *httperror.HandlerError {
stackID, err := request.RetrieveNumericRouteVariableValue(r, "id")
if err != nil {
return httperror.BadRequest("Invalid stack identifier route variable", err)
}
stack, err := handler.DataStore.Stack().Read(portainer.StackID(stackID))
if handler.DataStore.IsErrObjectNotFound(err) {
return httperror.NotFound("Unable to find a stack with the specified identifier inside the database", err)
} else if err != nil {
return httperror.InternalServerError("Unable to find a stack with the specified identifier inside the database", err)
}
securityContext, err := security.RetrieveRestrictedRequestContext(r)
if err != nil {
return httperror.InternalServerError("Unable to retrieve info from request context", err)
}
endpoint, err := handler.DataStore.Endpoint().Endpoint(stack.EndpointID)
if handler.DataStore.IsErrObjectNotFound(err) {
if !securityContext.IsAdmin {
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)
}
canManage, err := handler.userCanManageStacks(securityContext, endpoint)
if err != nil {
return httperror.InternalServerError("Unable to verify user authorizations to validate stack deletion", err)
}
if !canManage {
errMsg := "Stack management is disabled for non-admin users"
return httperror.Forbidden(errMsg, errors.New(errMsg))
}
if endpoint != nil {
err = handler.requestBouncer.AuthorizedEndpointOperation(r, endpoint)
if err != nil {
return httperror.Forbidden("Permission denied to access environment", err)
}
if stack.Type == portainer.DockerSwarmStack || stack.Type == portainer.DockerComposeStack {
resourceControl, err := handler.DataStore.ResourceControl().ResourceControlByResourceIDAndType(stackutils.ResourceControlID(stack.EndpointID, stack.Name), portainer.StackResourceControl)
if err != nil {
return httperror.InternalServerError("Unable to retrieve a resource control associated to the stack", err)
}
access, err := handler.userCanAccessStack(securityContext, resourceControl)
if err != nil {
return httperror.InternalServerError("Unable to verify user authorizations to validate stack access", err)
}
if !access {
return httperror.Forbidden("Access denied to resource", httperrors.ErrResourceAccessDenied)
}
}
}
var gitConfig *gittypes.RepoConfig
if stack.WorkflowID != 0 {
var err error
gitConfig, _, err = loadGitConfigForStack(handler.DataStore, stack.WorkflowID, stack.ID)
if err != nil {
return httperror.InternalServerError("Unable to load git config for stack", err)
}
}
if gitStackPendingRedeploy(stack, gitConfig) {
return httperror.Conflict("Stack git settings have changed. Redeploy the stack to apply the new configuration.", errors.New("git settings updated without redeploy"))
}
projectPath := stack.ProjectPath
// Optional ?version= selects a specific past file version of a file-based (non-git) stack.
version, err := request.RetrieveNumericQueryParameter(r, "version", true)
if err != nil {
return httperror.BadRequest("Invalid query parameter: version", err)
}
// A negative version is never valid (0/absent means "current"); reject it explicitly
// rather than silently falling through to the current version.
if version < 0 {
return httperror.BadRequest("Invalid query parameter: version", errors.New("version must be a positive integer"))
}
if version > 0 && stack.WorkflowID == 0 {
if !stackFileVersionExists(stack, version) {
return httperror.BadRequest("Invalid stack file version", errors.Errorf("version %d not found in stack history", version))
}
projectPath = handler.FileService.GetStackProjectPathByVersion(strconv.Itoa(int(stack.ID)), version, "")
}
stackFileContent, err := handler.FileService.GetFileContent(projectPath, stack.EntryPoint)
if err != nil {
return httperror.InternalServerError("Unable to retrieve Compose file from disk", err)
}
return response.JSON(w, &stackFileResponse{StackFileContent: string(stackFileContent)})
}
// stackFileVersionExists reports whether the given version is present in the stack's file
// version history (or, for stacks predating the history seed, is within the current range).
func stackFileVersionExists(stack *portainer.Stack, version int) bool {
for _, v := range stack.Versions {
if v.Version == version {
return true
}
}
return len(stack.Versions) == 0 && version >= 1 && version <= stack.StackFileVersion
}
// gitStackPendingRedeploy returns true when the stack's git settings (URL or config file path)
// have been updated via "save settings" but the stack has not yet been redeployed to apply them.
// In that state the local clone is stale and the stack file cannot be read from disk.
func gitStackPendingRedeploy(stack *portainer.Stack, gitConfig *gittypes.RepoConfig) bool {
if gitConfig == nil || stack.CurrentDeploymentInfo == nil {
return false
}
return gitConfig.URL != stack.CurrentDeploymentInfo.RepositoryURL ||
gitConfig.ConfigFilePath != stack.CurrentDeploymentInfo.ConfigFilePath
}