[mirror] Scalable static site server for Git forges (like GitHub Pages)
at main 11 kB view raw
1package git_pages 2 3import ( 4 "cmp" 5 "context" 6 "fmt" 7 "io" 8 "net/http" 9 "os" 10 "os/exec" 11 "path" 12 "path/filepath" 13 "strconv" 14 "strings" 15 "time" 16 17 exponential "github.com/jpillora/backoff" 18 "github.com/kankanreno/go-snowflake" 19 "github.com/prometheus/client_golang/prometheus" 20 "github.com/prometheus/client_golang/prometheus/promauto" 21 "google.golang.org/protobuf/encoding/protojson" 22 "google.golang.org/protobuf/proto" 23 timestamppb "google.golang.org/protobuf/types/known/timestamppb" 24) 25 26var ( 27 auditNotifyOkCount = promauto.NewCounter(prometheus.CounterOpts{ 28 Name: "git_pages_audit_notify_ok", 29 Help: "Count of successful audit notifications", 30 }) 31 auditNotifyErrorCount = promauto.NewCounter(prometheus.CounterOpts{ 32 Name: "git_pages_audit_notify_error", 33 Help: "Count of failed audit notifications", 34 }) 35) 36 37type principalKey struct{} 38 39var PrincipalKey = principalKey{} 40 41func WithPrincipal(ctx context.Context) context.Context { 42 principal := &Principal{} 43 return context.WithValue(ctx, PrincipalKey, principal) 44} 45 46func GetPrincipal(ctx context.Context) *Principal { 47 if principal, ok := ctx.Value(PrincipalKey).(*Principal); ok { 48 return principal 49 } 50 return nil 51} 52 53type AuditID int64 54 55func GenerateAuditID() AuditID { 56 inner, err := snowflake.NextID() 57 if err != nil { 58 panic(err) 59 } 60 return AuditID(inner) 61} 62 63func ParseAuditID(repr string) (AuditID, error) { 64 inner, err := strconv.ParseInt(repr, 16, 64) 65 if err != nil { 66 return AuditID(0), err 67 } 68 return AuditID(inner), nil 69} 70 71func (id AuditID) String() string { 72 return fmt.Sprintf("%016x", int64(id)) 73} 74 75func (id AuditID) CompareTime(when time.Time) int { 76 idMillis := int64(id) >> (snowflake.MachineIDLength + snowflake.SequenceLength) 77 whenMillis := when.UTC().UnixNano() / 1e6 78 return cmp.Compare(idMillis, whenMillis) 79} 80 81func EncodeAuditRecord(record *AuditRecord) (data []byte) { 82 data, err := proto.MarshalOptions{Deterministic: true}.Marshal(record) 83 if err != nil { 84 panic(err) 85 } 86 return 87} 88 89func DecodeAuditRecord(data []byte) (record *AuditRecord, err error) { 90 record = &AuditRecord{} 91 err = proto.Unmarshal(data, record) 92 return 93} 94 95func (record *AuditRecord) GetAuditID() AuditID { 96 return AuditID(record.GetId()) 97} 98 99func (record *AuditRecord) DescribePrincipal() string { 100 var items []string 101 if record.Principal != nil { 102 if record.Principal.GetIpAddress() != "" { 103 items = append(items, record.Principal.GetIpAddress()) 104 } 105 if record.Principal.GetCliAdmin() { 106 items = append(items, "<cli-admin>") 107 } 108 } 109 if len(items) > 0 { 110 return strings.Join(items, ";") 111 } else { 112 return "<unknown>" 113 } 114} 115 116func (record *AuditRecord) DescribeResource() string { 117 desc := "<unknown>" 118 if record.Domain != nil && record.Project != nil { 119 desc = path.Join(*record.Domain, *record.Project) 120 } else if record.Domain != nil { 121 desc = *record.Domain 122 } 123 return desc 124} 125 126type AuditRecordScope int 127 128const ( 129 AuditRecordComplete AuditRecordScope = iota 130 AuditRecordNoManifest 131) 132 133func AuditRecordJSON(record *AuditRecord, scope AuditRecordScope) []byte { 134 switch scope { 135 case AuditRecordComplete: 136 // as-is 137 case AuditRecordNoManifest: 138 // trim the manifest 139 newRecord := &AuditRecord{} 140 proto.Merge(newRecord, record) 141 newRecord.Manifest = nil 142 record = newRecord 143 } 144 145 json, err := protojson.MarshalOptions{ 146 Multiline: true, 147 EmitDefaultValues: true, 148 }.Marshal(record) 149 if err != nil { 150 panic(err) 151 } 152 return json 153} 154 155// This function receives `id` and `record` separately because the record itself may have its 156// ID missing or mismatched. While this is very unlikely, using the actual primary key as 157// the filename is more robust. 158func ExtractAuditRecord(ctx context.Context, id AuditID, record *AuditRecord, dest string) error { 159 const mode = 0o400 // readable by current user, not writable 160 161 err := os.WriteFile(filepath.Join(dest, fmt.Sprintf("%s-event.json", id)), 162 AuditRecordJSON(record, AuditRecordNoManifest), mode) 163 if err != nil { 164 return err 165 } 166 167 if record.Manifest != nil { 168 err = os.WriteFile(filepath.Join(dest, fmt.Sprintf("%s-manifest.json", id)), 169 ManifestJSON(record.Manifest), mode) 170 if err != nil { 171 return err 172 } 173 174 archive, err := os.OpenFile(filepath.Join(dest, fmt.Sprintf("%s-archive.tar", id)), 175 os.O_CREATE|os.O_TRUNC|os.O_WRONLY, mode) 176 if err != nil { 177 return err 178 } 179 defer archive.Close() 180 181 err = CollectTar(ctx, archive, record.Manifest, ManifestMetadata{}) 182 if err != nil { 183 return err 184 } 185 } 186 187 return nil 188} 189 190func AuditEventProcessor(command string, args []string) (http.Handler, error) { 191 var err error 192 193 // Resolve the command to an absolute path, as it will be run from a different current 194 // directory, which would break e.g. `git-pages -audit-server tcp/:3004 ./handler.sh`. 195 if command, err = exec.LookPath(command); err != nil { 196 return nil, err 197 } 198 if command, err = filepath.Abs(command); err != nil { 199 return nil, err 200 } 201 202 router := http.NewServeMux() 203 router.Handle("GET /", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 204 // Go will cancel the request context if the client drops the connection. We don't want 205 // that to interrupt processing. However, we also want the client (not the server) to 206 // handle retries, so instead of spawning a goroutine to process the event, we do this 207 // within the HTTP handler. If an error is returned, the notify goroutine in the worker 208 // will retry the HTTP request (with backoff) until it succeeds. 209 // 210 // This is a somewhat idiosyncratic design and it's not clear that this is the best 211 // possible approach (e.g. if the worker gets restarted and the event processing fails, 212 // it will not be retried), but it should do the job for now. It is expected that 213 // some form of observability is used to highlight event processor errors. 214 ctx := context.WithoutCancel(r.Context()) 215 216 id, err := ParseAuditID(r.URL.RawQuery) 217 if err != nil { 218 logc.Printf(ctx, "audit process err: malformed query\n") 219 http.Error(w, "malformed query", http.StatusBadRequest) 220 return 221 } else { 222 logc.Printf(ctx, "audit process %s", id) 223 } 224 225 record, err := backend.QueryAuditLog(ctx, id) 226 if err != nil { 227 logc.Printf(ctx, "audit process err: missing record\n") 228 http.Error(w, "missing record", http.StatusNotFound) 229 return 230 } 231 232 args := append(args, id.String(), record.GetEvent().String()) 233 cmd := exec.CommandContext(ctx, command, args...) 234 if cmd.Dir, err = os.MkdirTemp("", "auditRecord"); err != nil { 235 panic(fmt.Errorf("mkdtemp: %w", err)) 236 } 237 defer os.RemoveAll(cmd.Dir) 238 239 if err = ExtractAuditRecord(ctx, id, record, cmd.Dir); err != nil { 240 logc.Printf(ctx, "audit process %s err: %s\n", id, err) 241 http.Error(w, err.Error(), http.StatusInternalServerError) 242 return 243 } 244 245 output, err := cmd.CombinedOutput() 246 if err != nil { 247 logc.Printf(ctx, "audit process %s err: %s; %s\n", id, err, string(output)) 248 w.WriteHeader(http.StatusServiceUnavailable) 249 if len(output) == 0 { 250 fmt.Fprintln(w, err.Error()) 251 } 252 } else { 253 logc.Printf(ctx, "audit process %s ok: %s\n", id, string(output)) 254 w.WriteHeader(http.StatusOK) 255 } 256 w.Write(output) 257 })) 258 return router, nil 259} 260 261type auditedBackend struct { 262 Backend 263} 264 265var _ Backend = (*auditedBackend)(nil) 266 267func NewAuditedBackend(backend Backend) Backend { 268 return &auditedBackend{backend} 269} 270 271// This function does not retry appending audit records; as such, if it returns an error, 272// this error must interrupt whatever operation it was auditing. A corollary is that it is 273// possible that appending an audit record succeeds but the audited operation fails. 274// This is considered fine since the purpose of auditing is to record end user intent, not 275// to be a 100% accurate reflection of performed actions. When in doubt, the audit records 276// should be examined together with the application logs. 277func (audited *auditedBackend) appendNewAuditRecord(ctx context.Context, record *AuditRecord) (err error) { 278 if config.Audit.Collect { 279 id := GenerateAuditID() 280 record.Id = proto.Int64(int64(id)) 281 record.Timestamp = timestamppb.Now() 282 record.Principal = GetPrincipal(ctx) 283 284 err = audited.Backend.AppendAuditLog(ctx, id, record) 285 if err != nil { 286 err = fmt.Errorf("audit: %w", err) 287 } else { 288 var subject string 289 if record.Project == nil { 290 subject = *record.Domain 291 } else { 292 subject = path.Join(*record.Domain, *record.Project) 293 } 294 logc.Printf(ctx, "audit %s ok: %s %s\n", subject, id, record.Event.String()) 295 296 // Send a notification to the audit server, if configured, and try to make sure 297 // it is delivered by retrying with exponential backoff on errors. 298 notifyAudit(context.WithoutCancel(ctx), id) 299 } 300 } 301 return 302} 303 304func notifyAudit(ctx context.Context, id AuditID) { 305 if config.Audit.NotifyURL != nil { 306 notifyURL := config.Audit.NotifyURL.URL 307 notifyURL.RawQuery = id.String() 308 309 // See also the explanation in `AuditEventProcessor` above. 310 go func() { 311 backoff := exponential.Backoff{ 312 Jitter: true, 313 Min: time.Second * 1, 314 Max: time.Second * 60, 315 } 316 for { 317 resp, err := http.Get(notifyURL.String()) 318 var body []byte 319 if err == nil { 320 defer resp.Body.Close() 321 body, _ = io.ReadAll(resp.Body) 322 } 323 if err == nil && resp.StatusCode == http.StatusOK { 324 logc.Printf(ctx, "audit notify %s ok: %s\n", id, string(body)) 325 auditNotifyOkCount.Inc() 326 break 327 } else { 328 sleepFor := backoff.Duration() 329 if err != nil { 330 logc.Printf(ctx, "audit notify %s err: %s (retry in %s)", 331 id, err, sleepFor) 332 } else { 333 logc.Printf(ctx, "audit notify %s fail: %s (retry in %s); %s", 334 id, resp.Status, sleepFor, string(body)) 335 } 336 auditNotifyErrorCount.Inc() 337 time.Sleep(sleepFor) 338 } 339 } 340 }() 341 } 342} 343 344func (audited *auditedBackend) CommitManifest( 345 ctx context.Context, name string, manifest *Manifest, opts ModifyManifestOptions, 346) (err error) { 347 domain, project, ok := strings.Cut(name, "/") 348 if !ok { 349 panic("malformed manifest name") 350 } 351 audited.appendNewAuditRecord(ctx, &AuditRecord{ 352 Event: AuditEvent_CommitManifest.Enum(), 353 Domain: proto.String(domain), 354 Project: proto.String(project), 355 Manifest: manifest, 356 }) 357 358 return audited.Backend.CommitManifest(ctx, name, manifest, opts) 359} 360 361func (audited *auditedBackend) DeleteManifest( 362 ctx context.Context, name string, opts ModifyManifestOptions, 363) (err error) { 364 domain, project, ok := strings.Cut(name, "/") 365 if !ok { 366 panic("malformed manifest name") 367 } 368 audited.appendNewAuditRecord(ctx, &AuditRecord{ 369 Event: AuditEvent_DeleteManifest.Enum(), 370 Domain: proto.String(domain), 371 Project: proto.String(project), 372 }) 373 374 return audited.Backend.DeleteManifest(ctx, name, opts) 375} 376 377func (audited *auditedBackend) FreezeDomain(ctx context.Context, domain string) (err error) { 378 audited.appendNewAuditRecord(ctx, &AuditRecord{ 379 Event: AuditEvent_FreezeDomain.Enum(), 380 Domain: proto.String(domain), 381 }) 382 383 return audited.Backend.FreezeDomain(ctx, domain) 384} 385 386func (audited *auditedBackend) UnfreezeDomain(ctx context.Context, domain string) (err error) { 387 audited.appendNewAuditRecord(ctx, &AuditRecord{ 388 Event: AuditEvent_UnfreezeDomain.Enum(), 389 Domain: proto.String(domain), 390 }) 391 392 return audited.Backend.UnfreezeDomain(ctx, domain) 393}