package requester import ( "context" "crypto/rand" "crypto/sha256" "crypto/subtle" "encoding/hex" "encoding/json" "errors" "fmt" "slices" "strconv" "strings" "time" "github.com/bluesky-social/indigo/atproto/syntax" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" commonv1 "github.com/johnandersen777/socialweb-computer-kcp/api/common/v1alpha1" "github.com/johnandersen777/socialweb-computer-kcp/api/v1alpha1" "github.com/johnandersen777/socialweb-computer-kcp/internal/atproto/cloudinit" "github.com/johnandersen777/socialweb-computer-kcp/internal/atproto/market" atprotooauth "github.com/johnandersen777/socialweb-computer-kcp/internal/atproto/oauth" ) const ( ContractAssociationLifetime = market.ContractAssociationLifetime // ContractExpiresAtLabel on a ComputeContract is the unix time (seconds) its // compute.vm asks the bidder to end the VM at (compute.vm expiresAt). ContractExpiresAtLabel = v1alpha1.ContractExpiresAtLabel associationRetryFirst = 2 * time.Second associationRetryMax = 5 * time.Minute associationRetryAttempts = 12 associationNonceBytes = 24 associationStepTimeout = 30 * time.Second ) var errAssociationRefused = errors.New("requester: the association is refused") type contractAssociation struct { subject string rkey string ref commonv1.StrongRef expiresAt time.Time finished bool } func associationSubject(contract v1alpha1.ComputeContract, state *v1alpha1.NodeClaimContract) string { a := contract.Spec.Association if a == nil { return "" } subject := strings.TrimSpace(a.Subject) switch { case a.FromGuest && subject != "": return "" case subject != "": return subject case a.FromGuest && state != nil && state.GuestRequester != nil && state.GuestRequester.State == v1alpha1.ContractGuestRequesterVerified: return strings.TrimSpace(state.GuestRequester.Did) } return "" } func DefaultAssociation(spec *v1alpha1.ComputeContractSpec) { if spec.Agent != nil && spec.Association == nil { spec.Association = &v1alpha1.ComputeContractAssociation{FromGuest: true, RefFile: cloudinit.DefaultAssociationRefFile} } if a := spec.Association; a != nil && a.FromGuest && !slices.Contains(spec.GuestTools, v1alpha1.GuestToolSocialwebComputer) { spec.GuestTools = append(slices.Clip(spec.GuestTools), v1alpha1.GuestToolSocialwebComputer) } } func fromGuest(contract v1alpha1.ComputeContract) bool { DefaultAssociation(&contract.Spec) a := contract.Spec.Association return a != nil && a.FromGuest && strings.TrimSpace(a.Subject) == "" } func associationRefFile(contract v1alpha1.ComputeContract) (string, error) { if contract.Spec.Association == nil { return cloudinit.DefaultAssociationRefFile, nil } return cloudinit.AssociationRefPath(contract.Spec.Association.RefFile) } func (q *Requester) endorsementRefused(ctx context.Context) error { granted, known, err := q.oauthGrants(ctx) if err != nil || !known || !atprotooauth.KnownGrant(granted) || len(atprotooauth.MissingScopes([]string{atprotooauth.RepoEndorsementWrite}, granted)) == 0 { return nil } q.log.Warn("requester_endorsement_skipped", "hint", "the oauth session was not granted the optional scope "+atprotooauth.RepoEndorsementWrite+ "; sign in again to grant it; the agent stays unassociated until then") return fmt.Errorf("%w: the oauth session was not granted %s", errAssociationRefused, atprotooauth.RepoEndorsementWrite) } func (r *contractRunner) associationWritten(subject string) bool { r.mu.Lock() defer r.mu.Unlock() return r.association != nil && r.association.subject == subject } func (r *contractRunner) associationFinished(subject string) bool { r.mu.Lock() defer r.mu.Unlock() return r.association != nil && r.association.subject == subject && r.association.finished } func guestPending(state *v1alpha1.NodeClaimContract) bool { return state != nil && state.GuestRequester != nil && state.GuestRequester.State == v1alpha1.ContractGuestRequesterPending } func (r *contractRunner) associationPending(contract v1alpha1.ComputeContract) bool { state := contract.Status.Contract if state == nil || state.Accept == nil || state.Accept.URI == "" || contract.Spec.Release || contract.DeletionTimestamp != nil { return false } if fromGuest(contract) && guestPending(state) { return true } subject := associationSubject(contract, state) return subject != "" && !r.associationFinished(subject) } func (r *contractRunner) associateLater(contract v1alpha1.ComputeContract) { if r.associationPending(contract) { r.kickAssociation() } } func (r *contractRunner) kickAssociation() { select { case r.associationKick <- struct{}{}: default: } } func (r *contractRunner) associationStep(ctx context.Context, state *v1alpha1.NodeClaimContract) { if state == nil || r.isGone() { return } stepCtx, cancel := context.WithTimeout(ctx, associationStepTimeout) defer cancel() r.ensureAssociation(stepCtx, state.Accept, state) } func (r *contractRunner) associationFailed(ctx context.Context, step string, err error) bool { refused := errors.Is(err, errAssociationRefused) || errors.Is(err, errAtircLeaseMissing) r.log().Warn("requester_association_failed", "step", step, "err", err.Error(), "retry", !refused) message := step + ": " + err.Error() r.mu.Lock() attempts := r.associationAttempts if !refused { r.associationAttempts++ } r.mu.Unlock() terminal := refused || attempts >= associationRetryAttempts switch { case refused: case terminal: message += fmt.Sprintf(" (gave up after %d attempts)", attempts) default: delay := min(associationRetryFirst< 0 { r.log().Info("requester_record_delete_skipped", "reason", "the session was not granted delete on these collections; sign in again to grant it", "collections", slices.Compact(slices.Sorted(slices.Values(unscoped)))) } r.log().Info("requester_contract_records_deleted", "deleted", deleted, "of", len(refs)) } // The payload and market.event an outbound ContractEvent was published at (publishContractEvent's rkeys, every // generation up to its current one): found even when its status never recorded them (the invocation that published // it stopped first). func (q *Requester) contractEventRefs(event v1alpha1.ContractEvent) []commonv1.StrongRef { if event.UID == "" { return nil } var out []commonv1.StrongRef for g := int64(1); g <= max(event.Generation, 1); g++ { uid := string(event.UID) if g > 1 { uid += "-g" + strconv.FormatInt(g, 10) } if nsid := event.Spec.NSID; nsid != "" { out = append(out, commonv1.StrongRef{URI: "at://" + q.repoDID + "/" + nsid + "/" + sessionRKey("contract-event", uid)}) } out = append(out, commonv1.StrongRef{URI: "at://" + q.repoDID + "/" + market.EventNSID + "/" + sessionRKey("contract-event-envelope", uid)}) } return out } func uniqueRefs(in []commonv1.StrongRef) []commonv1.StrongRef { seen := map[string]bool{} out := in[:0] for _, ref := range in { if !seen[ref.URI] { seen[ref.URI] = true out = append(out, ref) } } return out } func bundleRef(path, value string) commonv1.StrongRef { sum := sha256.Sum256([]byte(value)) return commonv1.StrongRef{URI: path, CID: "sha256:" + hex.EncodeToString(sum[:])} } func SecretsUpdatedEventName(contract string, ref commonv1.StrongRef) string { return "secrets-updated-" + market.SessionRKey("secretsUpdated", contract, ref.URI, ref.CID) } func (r *contractRunner) notifySecretsUpdated(ctx context.Context, contract v1alpha1.ComputeContract, ref commonv1.StrongRef) error { q := r.q if q.deps.ContractEvents == nil { return errors.New("the requester has no ContractEvents handle") } if contract.UID == "" { return errors.New("the contract has no uid yet") } name := SecretsUpdatedEventName(contract.Name, ref) if _, known := q.contractEvents.Get(name); known { return nil } event := v1alpha1.ContractEvent{ ObjectMeta: metav1.ObjectMeta{Name: name, OwnerReferences: []metav1.OwnerReference{contractOwnerReference(contract)}}, Spec: v1alpha1.ContractEventSpec{ ContractRef: commonv1.LocalObjectRef{Name: contract.Name}, Direction: v1alpha1.ContractEventOutbound, NSID: market.ComputeEventsGuestSecretsUpdatedNSID, }, } if err := q.deps.ContractEvents.ApplyContractEvent(ctx, event); err != nil { return err } q.contractEvents.Put(name, event) r.log().Info("requester_secrets_updated_sent", "contractEvent", name, "association", ref.URI) return nil } func (r *contractRunner) onGuestRequester(ctx context.Context, state *v1alpha1.NodeClaimContract, parsed *GuestEvent) { contract := r.snapshot() refuse := func(reason string) { r.log().Warn("requester_guest_requester_refused", "did", parsed.RequesterDID, "event", parsed.Event.URI, "reason", reason) } switch { case !fromGuest(contract): refuse("the contract has no spec.association.fromGuest") return case contract.Spec.Release || contract.DeletionTimestamp != nil: refuse("the contract is releasing") return } if r.recordGuestRequester(ctx, state, parsed) { r.proveGuestRequester(ctx, state) } } func (r *contractRunner) recordGuestRequester(ctx context.Context, state *v1alpha1.NodeClaimContract, parsed *GuestEvent) bool { refuse := func(reason string) bool { r.log().Warn("requester_guest_requester_refused", "did", parsed.RequesterDID, "event", parsed.Event.URI, "reason", reason) return false } switch { case !fromGuest(r.snapshot()): return refuse("the contract has no spec.association.fromGuest") case state.GuestRequester != nil && state.GuestRequester.Did == parsed.RequesterDID: return false case state.GuestRequester != nil: return refuse("the guest already reported " + state.GuestRequester.Did) } if err := market.ValidGuestRequesterDID(parsed.RequesterDID, r.q.repoDID); err != nil { return refuse(err.Error()) } state.GuestRequester = &v1alpha1.ContractGuestRequester{Did: parsed.RequesterDID, State: v1alpha1.ContractGuestRequesterPending, Message: "proving control of the reported DID", ReportedAt: parsed.ObservedAt, Event: commonv1.StrongRef{URI: parsed.Event.URI, CID: parsed.Event.CID}, Payload: commonv1.StrongRef{URI: parsed.Payload.URI, CID: parsed.Payload.CID}} if err := r.writeGuestRequester(ctx, state); err != nil { state.GuestRequester = nil return refuse("recording the reported DID failed: " + err.Error()) } r.mu.Lock() r.associationAttempts = 0 r.mu.Unlock() r.log().Info("requester_guest_requester_reported", "did", parsed.RequesterDID) return true } func (r *contractRunner) writeGuestRequester(ctx context.Context, state *v1alpha1.NodeClaimContract) error { contract := r.snapshot() phase, message := contract.Status.Phase, contract.Status.Message if phase == "" { phase = v1alpha1.ComputeContractHeld } return r.writeStatus(ctx, phase, message, state, r.currentBids(), r.currentChosen(), "associating", 1) } func (r *contractRunner) settleGuestRequester(ctx context.Context, state *v1alpha1.NodeClaimContract, to v1alpha1.ContractGuestRequesterState, message string) error { previous := *state.GuestRequester state.GuestRequester.State, state.GuestRequester.Message = to, message if err := r.writeGuestRequester(ctx, state); err != nil { *state.GuestRequester = previous return err } return nil } func (r *contractRunner) proveGuestRequester(ctx context.Context, state *v1alpha1.NodeClaimContract) { q := r.q contract := r.snapshot() if !guestPending(state) || state.Accept == nil || state.Accept.URI == "" { return } accept := *state.Accept did := state.GuestRequester.Did fail := func(step string, err error) { if !r.associationFailed(ctx, step, err) { return } if err := r.settleGuestRequester(ctx, state, v1alpha1.ContractGuestRequesterRefused, step+": "+err.Error()); err != nil { r.log().Warn("requester_guest_requester_status_failed", "err", err.Error()) } } refuse := func(reason string) { fail("the guest requester's association request", fmt.Errorf("%w: %s", errAssociationRefused, reason)) } if err := market.ValidGuestRequesterDID(did, q.repoDID); err != nil { refuse(err.Error()) return } request, ok, err := r.associationRequest(ctx, contract, accept) switch { case err != nil: fail("the association request entry", err) return case !ok: refuse("the contract's bundle holds no association request for " + accept.URI) return } rkey := q.repoDID got, err := q.repo.GetRecord(ctx, did, market.AssociationRequestNSID, rkey) if err != nil { fail("reading "+did+"'s "+market.AssociationRequestNSID+"/"+rkey, err) return } asked, err := market.ParseAssociationRequest(got.Value) switch { case err != nil: refuse("the association request record is invalid: " + err.Error()) return case market.ATURIAuthority(got.URI) != did: refuse("the association request record is not in " + did + "'s repo") return case asked.Principal != q.repoDID || asked.Contract != accept.URI: refuse("the association request record names another principal or contract") return case subtle.ConstantTimeCompare([]byte(asked.Nonce), []byte(request.Nonce)) != 1: refuse("the association request record carries another nonce") return } state.GuestRequester.Accounts = guestAccounts(asked.Accounts, q.repoDID, did) if err := r.settleGuestRequester(ctx, state, v1alpha1.ContractGuestRequesterVerified, "the association request "+got.URI+" matches"); err != nil { fail("record the verified guest requester", err) return } r.log().Info("requester_guest_requester", "did", did, "request", got.URI, "accounts", state.GuestRequester.Accounts) r.ensureAssociation(ctx, state.Accept, state) r.ensureAgentPeer(ctx, r.snapshot(), state) } func contractExpiresAt(label string) string { sec, err := strconv.ParseInt(strings.TrimSpace(label), 10, 64) if err != nil || sec <= 0 { return "" } return market.FormatTime(time.Unix(sec, 0)) }