Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .gitleaks.toml
Original file line number Diff line number Diff line change
Expand Up @@ -1316,6 +1316,17 @@ regexes = [
'''(?s)^\s*"eng/provenance/records/go\-gowebauthnx\-legal\-r1\.json":\s*"f1680c3b153114ea4cc145264a716e4669e14212976d6584c1b3f41eda1202c4",?\s*$''',
]

[[allowlists]]
description = "AFV2-MIG-02: two verified public Go legal-record SHA-256 lines in immutable dependency receipt afv2-mig-02-r1."
condition = "AND"
targetRules = ["generic-api-key"]
paths = ['''^eng/policy/dependency\-reviews/afv2\-mig\-02\-r1\.json$''']
regexTarget = "line"
regexes = [
'''(?s)^\s*"eng/provenance/records/go\-gowebauthn\-legal\-r1\.json":\s*"fecb236888c74fd6195890d16720689d5341b51bbe8ac3a3d942171a936e4d07",?\s*$''',
'''(?s)^\s*"eng/provenance/records/go\-gowebauthnx\-legal\-r1\.json":\s*"f1680c3b153114ea4cc145264a716e4669e14212976d6584c1b3f41eda1202c4",?\s*$''',
]

[[allowlists]]
description = "AFV2-CENTER-02 RFC 6455: public WebSocket handshake example at line 196 of the reviewed historical Identity test."
condition = "AND"
Expand Down
74 changes: 74 additions & 0 deletions center/cmd/arcforges-center/contraction.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// SPDX-License-Identifier: AGPL-3.0-only

package main

import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/signal"
"syscall"
"time"

"github.com/ArcForges/Cloud/center/internal/config"
"github.com/ArcForges/Cloud/center/internal/schema"
"github.com/ArcForges/Cloud/center/internal/store/migrate"
)

func contractionCommand(args []string, lookup func(string) (string, bool), stdout, stderr io.Writer) int {
values, ok := restoreFlagValues(args, "--archive", "--metadata", "--witness-database", "--witness-role")
if !ok || migrate.ValidRoleName(values["--witness-role"]) != nil {
_, _ = fmt.Fprintln(stderr, "contraction requires new absolute --archive and --metadata paths, a new --witness-database and a new --witness-role")
return exitUsage
}
source, err := config.LoadMigration(lookup)
if err != nil {
_, _ = fmt.Fprintln(stderr, "contraction source configuration was refused")
return exitFailure
}
witness, err := config.LoadMigration(func(name string) (string, bool) {
switch name {
case config.EnvDatabaseName:
return values["--witness-database"], true
case config.EnvRuntimeRole:
return values["--witness-role"], true
default:
return lookup(name)
}
})
if err != nil || witness.Database == source.Database || witness.RuntimeRole == source.RuntimeRole {
_, _ = fmt.Fprintln(stderr, "contraction witness must name a separate database and runtime role")
return exitUsage
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
ctx, cancel := context.WithTimeout(ctx, 30*time.Minute)
defer cancel()
conn, err := connect(ctx, source.URL)
if err != nil {
_, _ = fmt.Fprintln(stderr, "contraction source connection was refused")
return exitFailure
}
defer conn.Close(context.Background())
build, err := migrate.Load(schema.Migrations())
if err != nil {
_, _ = fmt.Fprintln(stderr, "contraction migration catalogue was refused")
return exitFailure
}
options := migrate.Options{Runner: revision(), RuntimeRole: source.RuntimeRole, LockTimeout: source.LockTimeout}
result, err := migrate.ApplyContraction(ctx, conn, build, options, source, witness, values["--archive"], values["--metadata"])
if err != nil {
if result.State == migrate.StateMaintenance {
_, _ = fmt.Fprintln(stderr, err)
} else {
_, _ = fmt.Fprintln(stderr, "contraction refused:", err)
}
return exitFailure
}
if json.NewEncoder(stdout).Encode(result) != nil {
return exitFailure
}
return exitOK
}
22 changes: 15 additions & 7 deletions center/cmd/arcforges-center/ctr06_restore.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,27 +25,35 @@ import (
var restoreDigest = regexp.MustCompile(`^[0-9a-f]{64}$`)

func restoreFlags(args []string, capture bool) (map[string]string, bool) {
allowed := map[string]bool{"--archive": true, "--metadata": true}
allowed := []string{"--archive", "--metadata"}
if !capture {
allowed["--sha256"] = true
allowed["--metadata-sha256"] = true
allowed = append(allowed, "--sha256", "--metadata-sha256")
}
values, ok := restoreFlagValues(args, allowed...)
if !ok || !capture && (!restoreDigest.MatchString(values["--sha256"]) || !restoreDigest.MatchString(values["--metadata-sha256"])) {
return nil, false
}
return values, true
}

func restoreFlagValues(args []string, allowed ...string) (map[string]string, bool) {
if len(args) != len(allowed)*2 {
return nil, false
}
permitted := make(map[string]bool, len(allowed))
for _, name := range allowed {
permitted[name] = true
}
values := make(map[string]string, len(allowed))
for i := 0; i < len(args); i += 2 {
if !allowed[args[i]] || values[args[i]] != "" || args[i+1] == "" {
if !permitted[args[i]] || values[args[i]] != "" || args[i+1] == "" {
return nil, false
}
values[args[i]] = args[i+1]
}
if !filepath.IsAbs(values["--archive"]) || !filepath.IsAbs(values["--metadata"]) {
return nil, false
}
if !capture && (!restoreDigest.MatchString(values["--sha256"]) || !restoreDigest.MatchString(values["--metadata-sha256"])) {
return nil, false
}
return values, true
}

Expand Down
5 changes: 5 additions & 0 deletions center/cmd/arcforges-center/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ commands:
expand checked schema10/11 in offline maintenance with a verified backup and writer fence
migrate lifecycle --archive <new path> --metadata <new path>
expand checked schema12 to13 with a verified backup, seven-schema fence and new runtime roles
migrate contract --archive <new path> --metadata <new path> --witness-database <new database> --witness-role <new role>
verify an isolated predecessor restore before retiring drained legacy database objects
admin ensure-database create the center's database if it does not exist
admin backup-logical --archive <new path> --metadata <new path>
capture a checked logical backup and its trusted snapshot metadata
Expand Down Expand Up @@ -115,6 +117,9 @@ func run(arguments []string, lookup func(string) (string, bool), stdout, stderr
if len(arguments) >= 2 && arguments[0] == "migrate" && arguments[1] == "lifecycle" {
return transitionCommand(arguments[2:], lookup, stdout, stderr, true)
}
if len(arguments) >= 2 && arguments[0] == "migrate" && arguments[1] == "contract" {
return contractionCommand(arguments[2:], lookup, stdout, stderr)
}
command := "serve"
if len(arguments) > 0 {
command = arguments[0]
Expand Down
46 changes: 9 additions & 37 deletions center/internal/hub/hub.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ import (
"github.com/ArcForges/Cloud/center/internal/access"
"github.com/ArcForges/Cloud/center/internal/config"
"github.com/ArcForges/Cloud/center/internal/feature"
"github.com/ArcForges/Cloud/center/internal/fleet"
"github.com/ArcForges/Cloud/center/internal/ingress"
"github.com/ArcForges/Cloud/center/internal/observe"
"github.com/ArcForges/Cloud/center/internal/platform"
Expand Down Expand Up @@ -170,14 +169,11 @@ type Hub struct {
stopping bool
// heldElsewhere is set while another process holds the lease, so it is logged once.
heldElsewhere atomic.Bool
// swept is the fence whose boot sweep of the routing records committed (fleet.SweepRouted; AF-CTR-05 E2b, decisions B-1): the hub
// routes nothing under a fence before its sweep committed, and a failed sweep is retried at every wake of the lease loop.
swept atomic.Int64
nodeLocks [nodeLockStripes]chan struct{} // one-slot accept locks (lockNode)
lockSeed maphash.Seed
inFlight int // the calls this process waits for (MaxInFlightPerCenter)
wg sync.WaitGroup
keys keyring
nodeLocks [nodeLockStripes]chan struct{} // one-slot accept locks (lockNode)
lockSeed maphash.Seed
inFlight int // the calls this process waits for (MaxInFlightPerCenter)
wg sync.WaitGroup
keys keyring

stop context.CancelFunc
done chan struct{}
Expand Down Expand Up @@ -242,7 +238,6 @@ func (h *Hub) acquire(ctx context.Context) {
if err := h.clearStale(ctx, fence); err != nil {
h.logger.Warn("the channels a previous hub recorded could not be cleared", "error", err.Error())
}
h.sweep(ctx, fence)
case errors.Is(err, ErrLeaseHeld):
h.metrics.ObserveChannel("lease", "held_elsewhere")
if !h.heldElsewhere.Swap(true) {
Expand Down Expand Up @@ -289,14 +284,11 @@ func (h *Hub) leaseStep(ctx context.Context) {
return
}
remaining, held := h.lease.remaining()
fence, valid := h.lease.Fence()
_, valid := h.lease.Fence()
if !held || !valid {
h.acquire(ctx)
return
}
if h.swept.Load() != fence {
h.sweep(ctx, fence)
}
// The renewal waits for the store at most until the local expiry, so a store that does not answer never holds the stand-down back.
renewal, cancel := context.WithTimeout(ctx, remaining)
renewed, err := h.lease.Renew(renewal)
Expand Down Expand Up @@ -352,30 +344,10 @@ func (h *Hub) Stop(ctx context.Context) {
}
}

// sweep runs the boot sweep of the routing records under a fence (fleet.SweepRouted): every ACCEPTED record becomes UNKNOWN, because no
// attempt of this fence is in flight yet and an earlier one may have reached the node. Only a committed sweep lets the hub route.
func (h *Hub) sweep(ctx context.Context, fence int64) {
if h.db == nil {
return
}
swept, err := fleet.SweepRouted(ctx, h.db, fence, h.clock())
if err != nil {
h.metrics.ObserveChannel("lease", "sweep_failed")
h.logger.Warn("the routing records of a previous hub could not be swept; the hub routes nothing until they are", "error", err.Error())
return
}
h.swept.Store(fence)
h.metrics.ObserveChannel("lease", "swept")
if swept > 0 {
h.logger.Info("the routing records a previous hub left in flight are unknown now", "records", swept)
}
}

// Routable reports whether the hub routes calls, and under which fence: it holds the lease, is not stopping, and the boot sweep of
// that fence committed (decisions B-1). The routed API's admission is fenced by it.
// Routable reports whether the hub holds the active fence and is accepting
// calls. V2 receipts are reconciled under the current fence by management.
func (h *Hub) Routable() (int64, bool) {
fence, serving := h.serving()
return fence, serving && h.swept.Load() == fence
return h.serving()
}

// serving reports whether the hub admits an upgrade: it holds the lease and is not stopping.
Expand Down
16 changes: 15 additions & 1 deletion center/internal/provision/provision.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"

"github.com/ArcForges/Cloud/center/internal/schema"
"github.com/ArcForges/Cloud/center/internal/store/migrate"
)

Expand Down Expand Up @@ -102,6 +103,8 @@ type Rotation struct {
Logging migrate.Logging `json:"logging"`
Probe Probe `json:"probe"`
RuntimeURL string `json:"-"`

contractedHistory bool
}

// Probe is what the new credential proved through the pooled endpoint and, for CONNECT, through one unpooled connection.
Expand Down Expand Up @@ -176,6 +179,10 @@ func Rotate(ctx context.Context, conn *pgx.Conn, options Options) (Rotation, err
if !ready {
return errors.New("the database is not migrated or the runtime role does not exist; run arcforges-center migrate first")
}
if err := tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM platform.schema_migration WHERE version >= $1)",
schema.ContractionVersion).Scan(&rotation.contractedHistory); err != nil {
return migrate.Sanitize("identify the runtime migration reader", err)
}
if err := migrate.RequirePlainRole(ctx, tx, options.Group, false); err != nil {
return err
}
Expand Down Expand Up @@ -482,13 +489,20 @@ func probe(ctx context.Context, rotation Rotation, options Options) (Probe, erro
defer func() { _ = conn.Close(context.Background()) }()
var user, database string
var versions int
if err = conn.QueryRow(ctx, "SELECT current_user, current_database(), (SELECT count(*) FROM platform.schema_migration)").Scan(&user, &database, &versions); err != nil {
history := "platform.schema_migration"
if rotation.contractedHistory {
history = "platform.runtime_schema_history"
}
if err = conn.QueryRow(ctx, "SELECT current_user, current_database(), (SELECT count(*) FROM "+history+")").Scan(&user, &database, &versions); err != nil {
return Probe{}, migrate.Sanitize("read through the pooled endpoint", err)
}
result.ConnectedAsLogin = user == rotation.LoginRole && database == rotation.Database
result.ReadsGrantedTable = versions > 0
result.CannotCreate = refused(ctx, conn, "CREATE TABLE platform.runtime_probe (x int)")
result.CannotReadUngranted = refused(ctx, conn, "SELECT count(*) FROM platform.runtime_credential")
if rotation.contractedHistory {
result.CannotReadUngranted = result.CannotReadUngranted && refused(ctx, conn, "SELECT count(*) FROM platform.schema_migration")
}
result.CannotCreateTemporary = refused(ctx, conn, "CREATE TEMPORARY TABLE runtime_probe (x int)")
if !result.ConnectsUnpooled || !result.ConnectedAsLogin || !result.ReadsGrantedTable || !result.CannotCreate || !result.CannotReadUngranted ||
!result.CannotCreateTemporary {
Expand Down
Loading