forked from harness/harness
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcommit.go
More file actions
223 lines (198 loc) · 6.57 KB
/
commit.go
File metadata and controls
223 lines (198 loc) · 6.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
// Copyright 2023 Harness, Inc.
//
// 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.
package repo
import (
"cmp"
"context"
"encoding/base64"
"fmt"
"strings"
"time"
"github.com/easysoft/gitfox/app/api/controller"
"github.com/easysoft/gitfox/app/auth"
"github.com/easysoft/gitfox/app/bootstrap"
"github.com/easysoft/gitfox/app/paths"
"github.com/easysoft/gitfox/app/services/protection"
"github.com/easysoft/gitfox/audit"
"github.com/easysoft/gitfox/errors"
"github.com/easysoft/gitfox/git"
"github.com/easysoft/gitfox/git/sha"
"github.com/easysoft/gitfox/store"
"github.com/easysoft/gitfox/types"
"github.com/easysoft/gitfox/types/enum"
"github.com/rs/zerolog/log"
)
// CommitFileAction holds file operation data.
type CommitFileAction struct {
Action git.FileAction `json:"action"`
Path string `json:"path"`
Payload string `json:"payload"`
Encoding enum.ContentEncodingType `json:"encoding"`
// SHA can be used for optimistic locking of an update action (Optional).
// The provided value is compared against the latest sha of the file that's being updated.
// If the SHA doesn't match, the update fails.
// WARNING: If no SHA is provided, the update action will blindly overwrite the file's content.
SHA sha.SHA `json:"sha"`
}
// CommitFilesOptions holds the data for file operations.
type CommitFilesOptions struct {
Title string `json:"title"`
Message string `json:"message"`
Branch string `json:"branch"`
NewBranch string `json:"new_branch"`
Actions []CommitFileAction `json:"actions"`
Author *git.Identity `json:"author"`
DryRunRules bool `json:"dry_run_rules"`
BypassRules bool `json:"bypass_rules"`
}
func (in *CommitFilesOptions) Sanitize() error {
in.Title = strings.TrimSpace(in.Title)
in.Message = strings.TrimSpace(in.Message)
// TODO: Validate title and message length.
return nil
}
func (c *Controller) CommitFiles(ctx context.Context,
session *auth.Session,
repoRef string,
in *CommitFilesOptions,
) (types.CommitFilesResponse, []types.RuleViolations, error) {
repo, err := c.getRepoCheckAccess(ctx, session, repoRef, enum.PermissionRepoPush)
if err != nil {
return types.CommitFilesResponse{}, nil, err
}
if repo.Mirror {
return types.CommitFilesResponse{}, nil, store.ErrReadOnlyMirrorRepo
}
if err := in.Sanitize(); err != nil {
return types.CommitFilesResponse{}, nil, err
}
rules, isRepoOwner, err := c.fetchRules(ctx, session, repo)
if err != nil {
return types.CommitFilesResponse{}, nil, err
}
var refAction protection.RefAction
var branchName string
if in.NewBranch != "" {
refAction = protection.RefActionCreate
branchName = in.NewBranch
} else {
refAction = protection.RefActionUpdate
branchName = in.Branch
}
violations, err := rules.RefChangeVerify(ctx, protection.RefChangeVerifyInput{
ResolveUserGroupID: c.userGroupService.ListUserIDsByGroupIDs,
Actor: &session.Principal,
AllowBypass: in.BypassRules,
IsRepoOwner: isRepoOwner,
Repo: repo,
RefAction: refAction,
RefType: protection.RefTypeBranch,
RefNames: []string{branchName},
})
if err != nil {
return types.CommitFilesResponse{}, nil, fmt.Errorf("failed to verify protection rules: %w", err)
}
if in.DryRunRules {
return types.CommitFilesResponse{
DryRunRulesOutput: types.DryRunRulesOutput{
DryRunRules: true,
RuleViolations: violations,
},
}, nil, nil
}
if protection.IsCritical(violations) {
return types.CommitFilesResponse{}, violations, nil
}
actions := make([]git.CommitFileAction, len(in.Actions))
for i, action := range in.Actions {
var rawPayload []byte
switch action.Encoding {
case enum.ContentEncodingTypeBase64:
rawPayload, err = base64.StdEncoding.DecodeString(action.Payload)
if err != nil {
return types.CommitFilesResponse{}, nil, errors.Internal(err, "failed to decode base64 payload")
}
case enum.ContentEncodingTypeUTF8:
fallthrough
default:
// by default we treat content as is
rawPayload = []byte(action.Payload)
}
actions[i] = git.CommitFileAction{
Action: action.Action,
Path: action.Path,
Payload: rawPayload,
SHA: action.SHA,
}
}
// Create internal write params. Note: This will skip the pre-commit protection rules check.
writeParams, err := controller.CreateRPCInternalWriteParams(ctx, c.urlProvider, session, repo)
if err != nil {
return types.CommitFilesResponse{}, nil, fmt.Errorf("failed to create RPC write params: %w", err)
}
now := time.Now()
commit, err := c.git.CommitFiles(ctx, &git.CommitFilesParams{
WriteParams: writeParams,
Message: git.CommitMessage(in.Title, in.Message),
Branch: in.Branch,
NewBranch: in.NewBranch,
Actions: actions,
Committer: identityFromPrincipal(bootstrap.NewSystemServiceSession().Principal),
CommitterDate: &now,
Author: cmp.Or(in.Author, identityFromPrincipal(session.Principal)),
AuthorDate: &now,
})
if err != nil {
return types.CommitFilesResponse{}, nil, err
}
if protection.IsBypassed(violations) {
err = c.auditService.Log(ctx,
session.Principal,
audit.NewResource(
audit.ResourceTypeRepository,
repo.Identifier,
audit.RepoPath,
repo.Path,
audit.BypassAction,
audit.BypassActionCommitted,
audit.BypassedResourceType,
audit.BypassedResourceTypeCommit,
audit.BypassedResourceName,
commit.CommitID.String(),
audit.ResourceName,
fmt.Sprintf(
audit.BypassSHALabelFormat,
repo.Identifier,
commit.CommitID.String()[0:6],
),
),
audit.ActionBypassed,
paths.Parent(repo.Path),
audit.WithNewObject(audit.CommitObject{
CommitSHA: commit.CommitID.String(),
RepoPath: repo.Path,
RuleViolations: violations,
}),
)
}
if err != nil {
log.Ctx(ctx).Warn().Msgf("failed to insert audit log for commit operation: %s", err)
}
return types.CommitFilesResponse{
CommitID: commit.CommitID.String(),
DryRunRulesOutput: types.DryRunRulesOutput{
RuleViolations: violations,
},
}, nil, nil
}