// Package homeop is Alta's half of Home's operator endpoint // (home implementation/team-provisioning-amendment.md §3–§7): the signed // operation, the signed plan, the signed inspect challenge, every verb's // input and the result Home returns. // // Home verifies each of these by decoding it strictly and re-encoding it // with go-json-experiment's deterministic encoder, then comparing bytes // (internal/operator/protocol.go strictCanonical). So the structs here are // Home's own, field for field and tag for tag, in the same order: a field // moved here is a request Home refuses. homecompat/ checks every one of // them against Home's real verifier and engine. package homeop import ( "crypto/elliptic" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/hex" "errors" "net/mail" "net/url" "strings" "unicode" "unicode/utf8" family "amadan.net/rastrillo/rastrillo/crypto" "github.com/go-json-experiment/json" "github.com/go-json-experiment/json/jsontext" ) // Contexts and limits, as Home declares them. const ( InputContext = "oficina/home/operator-input/v1" PlanContext = "oficina/home/operator-plan/v1" InspectContext = "oficina/home/operator-inspect/v1" OwnerContext = "oficina/home/owner-seed/v1" BodyLimit = 64 << 10 InputLimit = 48 << 10 AuthorizationLimit = 16 << 10 PlanLimit = 8 << 10 // RequestLifetime is an operation's and an inspect challenge's // signed life; Home refuses more than 300 s. RequestLifetime = 300 // PlanLifetime bounds a plan; WindowLifetime is the window Paul's // confirmation opens. Home never extends either. PlanLifetime = 900 WindowLifetime = 900 // Skew is how far back Alta dates what it signs: Home refuses an // issued_at in its future, so a few seconds of clock skew must not // refuse every request. Lifetimes still count from the back-dated // issue. Skew = 30 // Baseline is the only baseline_attestation directory.initialize // accepts. Alta sends it only after Paul types it (§6 step 1). Baseline = "operator-attests-never-provisioned" // ActivationPolicy is ActivationEvidence.Policy. ActivationPolicy = "oficina/team-activation/v1" // ExistingActivationPolicy is the policy an adoption window's // activation carries; Home picks the policy from the window. ExistingActivationPolicy = "oficina/existing-app-activation/v1" // ManifestContext is the consumer manifest digest's domain string. ManifestContext = "oficina/home/consumer-manifest/v1" ) // Roles. const ( Credential = "credential" Directory = "directory" ) // Plan kinds. const ( KindInitialize = "initialize" KindCreateTeam = "create-team" KindAddApps = "add-apps" KindRetireApps = "retire-apps" ) // Verbs. const ( DirectoryInspect = "directory.inspect" DirectoryInitialize = "directory.initialize" DirectorySeedTeam = "directory.seed-team" DirectoryProvision = "directory.provision-consumer" DirectoryVerify = "directory.verify-consumer" DirectoryActivate = "directory.activate-consumer" DirectoryDisable = "directory.disable-consumer" CredentialInspect = "credential.inspect" CredentialOwnerSeed = "credential.owner-seed" CredentialRegister = "credential.register-consumer" CredentialRetire = "credential.retire-consumer" ) var ErrRefused = errors.New("homeop: refused") // Authorization is Home's signed operator authority (protocol.go). type Authorization struct { Version int `json:"version"` Purpose string `json:"purpose"` Role string `json:"role"` Origin string `json:"origin"` Installation string `json:"installation"` Registry string `json:"registry"` Device string `json:"device"` Sequence int64 `json:"sequence"` Initial bool `json:"initial_authority"` Previous string `json:"previous"` JournalSequence int64 `json:"journal_sequence"` OperationID string `json:"operation_id"` Action string `json:"action"` InputDigest string `json:"input_digest"` Issued int64 `json:"issued_at"` Expires int64 `json:"expires_at"` } type envelope struct { Version int `json:"v"` KeyID string `json:"kid"` Payload string `json:"payload"` Signature string `json:"signature"` } type wrapper struct { Version int `json:"version"` Authorization jsontext.Value `json:"signed_authorization"` Input jsontext.Value `json:"operation_input"` } // Plan is what Alta signs and submits to each role (plan.go). type Plan struct { Version int `json:"version"` Purpose string `json:"purpose"` Role string `json:"role"` Origin string `json:"origin"` Installation string `json:"installation"` Registry string `json:"registry"` Device string `json:"device"` PlanID string `json:"plan_id"` Kind string `json:"kind"` Apps []string `json:"apps"` Label string `json:"label,omitzero"` DisplayName string `json:"display_name,omitzero"` Owner string `json:"owner,omitzero"` // ExistingTeam is the team SQID an adoption plan binds, never the // dashboard label (internal/operator/plan.go). ExistingTeam string `json:"existing_team,omitzero"` Issued int64 `json:"issued_at"` Expires int64 `json:"expires_at"` } // CanonicalOrigin is Alta's one copy of Home's closed registry of the // existing suite instances (internal/home/directorydata/canonical.go): the // canonical apps' consumer id is the slug and the origin is // https://.oficina.works. It is empty for any other app. It lives // here, not in provision, because fakehome (imported by provision's tests) // needs it too. homecompat pins it against Home's own. func CanonicalOrigin(app string) string { switch app { case "docs", "sheets", "slides", "memoria", "calendar", "calls", "equipo", "base": return "https://" + app + ".oficina.works" } return "" } // InspectChallenge is .inspect's signed request (inspect.go). type InspectChallenge struct { Version int `json:"version"` Purpose string `json:"purpose"` Role string `json:"role"` Origin string `json:"origin"` Installation string `json:"installation"` Registry string `json:"registry"` Device string `json:"device"` Challenge string `json:"challenge"` Issued int64 `json:"issued_at"` Expires int64 `json:"expires_at"` } // Inspection is .inspect's answer (http_verbs.go HTTPInspection). type Inspection struct { Version int `json:"version"` Role string `json:"role"` Challenge string `json:"challenge"` Observed int64 `json:"observed_at"` Sequence int64 `json:"sequence"` Head string `json:"head"` Generation *string `json:"generation,omitempty"` TeamID int64 `json:"proposed_team_id,omitempty"` TeamSQID string `json:"proposed_team_sqid,omitempty"` PendingPlan string `json:"pending_plan,omitempty"` PendingExpires int64 `json:"pending_expires_at,omitempty"` OpenPlan string `json:"open_plan,omitempty"` WindowExpires int64 `json:"window_expires_at,omitempty"` } // InputBase opens every operation input. type InputBase struct { Version int `json:"version"` Operation string `json:"operation"` OperationID string `json:"operation_id"` } type InitializeInput struct { InputBase ExpectedGeneration *string `json:"expected_generation"` Generation string `json:"generation"` Baseline string `json:"baseline_attestation"` } type SeedInput struct { InputBase Generation string `json:"expected_generation"` TeamID int64 `json:"team_id"` TeamSQID string `json:"team_sqid"` Label string `json:"label"` Name string `json:"display_name"` Receipt jsontext.Value `json:"receipt"` } type ProvisionInput struct { InputBase Generation string `json:"expected_generation"` TeamSQID string `json:"team_sqid"` App string `json:"app"` Consumer string `json:"consumer"` Audience string `json:"audience"` Sequence int64 `json:"expected_sequence"` } type OwnerInput struct { InputBase Directory string `json:"directory"` TeamID int64 `json:"team_id"` TeamSQID string `json:"team_sqid"` Address string `json:"address"` ExistingOnly bool `json:"existing_only"` } type RegisterInput struct { InputBase Record jsontext.Value `json:"record"` } type RetireInput struct { InputBase Consumer string `json:"consumer"` } type DisableInput struct { InputBase Generation string `json:"expected_generation"` TeamSQID string `json:"team_sqid"` App string `json:"app"` Consumer string `json:"consumer"` } type VerificationInput struct { InputBase Consumer string `json:"consumer"` TeamSQID string `json:"team_sqid"` App string `json:"app"` Audience string `json:"audience"` Generation string `json:"generation"` RecordSequence int64 `json:"record_sequence"` RecordDigest string `json:"record_digest"` Epoch int64 `json:"expected_epoch"` Owner string `json:"owner_ref"` Issued int64 `json:"issued_at"` Expires int64 `json:"expires_at"` } type ActivationEvidence struct { Version int `json:"version"` Policy string `json:"policy"` Attempt string `json:"attempt_id"` Consumer string `json:"consumer"` TeamSQID string `json:"team_sqid"` App string `json:"app"` Audience string `json:"audience"` Generation string `json:"generation"` RecordSequence int64 `json:"record_sequence"` RecordDigest string `json:"record_digest"` Epoch int64 `json:"epoch"` Owner string `json:"owner_ref"` AppVersion string `json:"app_version"` ArtifactDigest string `json:"artifact_digest"` EnvironmentBinding string `json:"environment_binding"` ManifestDigest string `json:"credential_manifest_digest"` AliasHost string `json:"alias_host"` Started int64 `json:"started_at"` Completed int64 `json:"completed_at"` } type ActivationInput struct { InputBase Evidence ActivationEvidence `json:"evidence"` } // Result is the engine's result JSON (directory.go Result). type Result struct { Attempt string `json:"attempt_id,omitempty"` Expires int64 `json:"expires_at,omitempty"` Version int `json:"version"` OperationID string `json:"operation_id"` Outcome string `json:"outcome"` Generation string `json:"generation,omitempty"` TeamID int64 `json:"team_id,omitempty"` TeamSQID string `json:"team_sqid,omitempty"` Epoch int64 `json:"epoch,omitempty"` Record jsontext.Value `json:"record,omitempty"` Bearer string `json:"bearer,omitempty"` Receipt jsontext.Value `json:"receipt,omitempty"` Manifest string `json:"credential_manifest_digest,omitempty"` } // OwnerReceipt is the payload of the credential role's signed owner // receipt. Alta reads it (person_ref, expiry) but never verifies it: the // directory does. type OwnerReceipt struct { Version int `json:"version"` Purpose string `json:"purpose"` OperationID string `json:"operation_id"` Issuer string `json:"issuer"` Directory string `json:"directory"` TeamID int64 `json:"team_id"` TeamSQID string `json:"team_sqid"` PersonRef string `json:"person_ref"` Role string `json:"role"` Issued int64 `json:"issued_at"` Expires int64 `json:"expires_at"` } // Encode is Home's canonical encoding. func Encode(v any) ([]byte, error) { b, err := json.Marshal(v, json.Deterministic(true)) if err != nil { return nil, ErrRefused } return b, nil } // Decode is Home's strict decoding: valid UTF-8, no unknown members. func Decode(b []byte, v any) error { if !utf8.Valid(b) || json.Unmarshal(b, v, json.RejectUnknownMembers(true)) != nil { return ErrRefused } return nil } // Token is 32 random bytes, base64url without padding: an operation id, // a plan id, a challenge, a generation. func Token() string { b := make([]byte, 32) if _, err := rand.Read(b); err != nil { panic(err) } return base64.RawURLEncoding.EncodeToString(b) } // CanonicalToken is Home's token rule: exactly 32 bytes, canonical // unpadded base64url. func CanonicalToken(s string) bool { b, err := base64.RawURLEncoding.Strict().DecodeString(s) return err == nil && len(b) == 32 && base64.RawURLEncoding.EncodeToString(b) == s } // Digest is base64url(SHA-256(b)), Home's input digest and stream head. func Digest(b []byte) string { h := sha256.Sum256(b) return base64.RawURLEncoding.EncodeToString(h[:]) } // KeyID is hex(SHA-256(public key)), the envelope's kid. func KeyID(public []byte) string { h := sha256.Sum256(public) return hex.EncodeToString(h[:]) } // Origin is Home's origin rule. func Origin(s string) bool { if len(s) == 0 || len(s) > 253 { return false } u, e := url.Parse(s) return e == nil && u.Scheme == "https" && u.Host != "" && u.Host == strings.ToLower(u.Host) && u.User == nil && u.Path == "" && u.RawPath == "" && u.RawQuery == "" && !u.ForceQuery && u.Fragment == "" && u.RawFragment == "" && !strings.ContainsAny(u.Host, "%\\:") && !strings.HasSuffix(u.Host, ".") && u.String() == s } // OwnerAddress is the exact form owner-seed accepts: a bare address that // parses to itself. func OwnerAddress(s string) bool { if len(s) == 0 || len(s) > 320 || !utf8.ValidString(s) { return false } a, e := mail.ParseAddress(s) return e == nil && a.Address == s && a.Name == "" } // TeamName is the directory's team-name rule. func TeamName(s string) bool { if len(s) == 0 || len(s) > 255 || !utf8.ValidString(s) || strings.TrimSpace(s) == "" { return false } for _, r := range s { if unicode.IsControl(r) { return false } } return true } // PersonRef is Home's person reference shape. func PersonRef(s string) bool { if len(s) != 29 || !strings.HasPrefix(s, "pr_") { return false } for _, c := range s[3:] { if !(c >= 'a' && c <= 'z' || c >= '2' && c <= '7') { return false } } return true } // PlanPrefix is the first 8 hex digits of a plan id: what Paul matches on // both Home confirm pages. func PlanPrefix(id string) string { b, err := base64.RawURLEncoding.Strict().DecodeString(id) if err != nil || len(b) != 32 { return "" } return hex.EncodeToString(b[:4]) } // signingKey mirrors Home's check on the signer. func signingKey(k *family.Keypair) bool { if k == nil || k.SignPriv == nil { return false } p := k.SignPriv return p.Curve == elliptic.P256() && p.D != nil && p.D.Sign() > 0 && p.D.Cmp(elliptic.P256().Params().N) < 0 && p.X != nil && p.Y != nil && elliptic.P256().IsOnCurve(p.X, p.Y) } func sealEnvelope(k *family.Keypair, context string, payload []byte) ([]byte, error) { sig, err := family.Sign(k, context, payload) if err != nil { return nil, ErrRefused } return Encode(envelope{1, KeyID(k.SignPub()), base64.RawURLEncoding.EncodeToString(payload), base64.RawURLEncoding.EncodeToString(sig)}) } // EnvelopePayload returns the payload bytes of a signed envelope without // verifying it. Alta uses it to read an owner receipt Home produced. func EnvelopePayload(raw []byte) ([]byte, error) { var env envelope if Decode(raw, &env) != nil || env.Version != 1 { return nil, ErrRefused } b, err := base64.RawURLEncoding.Strict().DecodeString(env.Payload) if err != nil { return nil, ErrRefused } return b, nil } // ReadReceipt reads an owner receipt's payload. func ReadReceipt(raw []byte) (OwnerReceipt, error) { var r OwnerReceipt p, err := EnvelopePayload(raw) if err != nil || Decode(p, &r) != nil || r.Version != 1 || r.Purpose != "owner-seed" || !PersonRef(r.PersonRef) { return OwnerReceipt{}, ErrRefused } return r, nil } // Request is one signed operation: the exact bytes Alta sends (and keeps, // sealed, for exact replay) and the stream head it becomes once committed. type Request struct { Bytes []byte Head string Authorization Authorization } // SignRequest signs input under a, filling a's input digest. a must // already carry the sequence, previous head, operation id and clock. func SignRequest(k *family.Keypair, a Authorization, input any) (Request, error) { if !signingKey(k) { return Request{}, ErrRefused } in, err := Encode(input) if err != nil || len(in) > InputLimit { return Request{}, ErrRefused } a.Version, a.Purpose = 1, "operator-input" a.InputDigest = Digest(in) a.Initial = a.Sequence == 1 if !validAuthorization(a) { return Request{}, ErrRefused } payload, err := Encode(a) if err != nil { return Request{}, err } env, err := sealEnvelope(k, InputContext, payload) if err != nil || len(env) > AuthorizationLimit { return Request{}, ErrRefused } out, err := Encode(wrapper{1, env, in}) if err != nil || len(out) > BodyLimit { return Request{}, ErrRefused } return Request{Bytes: out, Head: Digest(env), Authorization: a}, nil } // ReadRequest recovers the authorization of a request Alta signed, so a // sealed request row needs no copy of it. func ReadRequest(raw []byte) (Request, error) { var w wrapper if Decode(raw, &w) != nil || w.Version != 1 { return Request{}, ErrRefused } p, err := EnvelopePayload(w.Authorization) if err != nil { return Request{}, err } var a Authorization if Decode(p, &a) != nil { return Request{}, ErrRefused } return Request{Bytes: raw, Head: Digest(w.Authorization), Authorization: a}, nil } func validAuthorization(a Authorization) bool { return a.Version == 1 && a.Purpose == "operator-input" && Origin(a.Origin) && CanonicalToken(a.Installation) && CanonicalToken(a.Registry) && CanonicalToken(a.Device) && CanonicalToken(a.OperationID) && CanonicalToken(a.InputDigest) && a.Sequence > 0 && a.Initial == (a.Sequence == 1) && a.JournalSequence > 0 && ((a.Sequence == 1 && a.Previous == "") || (a.Sequence > 1 && CanonicalToken(a.Previous))) && a.Issued > 0 && a.Expires > a.Issued && a.Expires-a.Issued <= RequestLifetime && allowedAction(a.Role, a.Action) } func allowedAction(role, a string) bool { switch role { case Credential: switch a { case CredentialOwnerSeed, CredentialRegister, CredentialRetire, CredentialInspect: return true } case Directory: switch a { case DirectoryInspect, DirectoryInitialize, DirectorySeedTeam, DirectoryProvision, DirectoryVerify, DirectoryActivate, DirectoryDisable: return true } } return false } // SignPlan signs a plan under the plan context. func SignPlan(k *family.Keypair, p Plan) ([]byte, error) { if !signingKey(k) { return nil, ErrRefused } p.Version, p.Purpose = 1, "operator-plan" if p.Apps == nil { p.Apps = []string{} } payload, err := Encode(p) if err != nil { return nil, err } out, err := sealEnvelope(k, PlanContext, payload) if err != nil || len(out) > PlanLimit { return nil, ErrRefused } return out, nil } // SignInspect signs an inspect challenge. func SignInspect(k *family.Keypair, c InspectChallenge) ([]byte, error) { if !signingKey(k) { return nil, ErrRefused } c.Version, c.Purpose = 1, "operator-inspect" payload, err := Encode(c) if err != nil { return nil, err } return sealEnvelope(k, InspectContext, payload) } // ManifestDigest is §7's credential_manifest_digest: base64url(SHA-256( // encoding/json.Marshal(["oficina/home/consumer-manifest/v1", [[id, // origin], …]]))), entries sorted by consumer id bytes. Alta computes it // only to check what step 6 returned against what it expects. func ManifestDigest(consumers map[string]string) string { return manifestDigest(consumers) }