Spaces:
Running

File size: 6,033 Bytes
06d4bbc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Strict, local ownership-transfer contract; no network or application imports."""
import copy
import hashlib
import json
import re
from pathlib import Path

OWNER_FIELDS = ("researcher_identity_id", "submitter_orcid", "orcid_id")


def digest(value):
    return hashlib.sha256((json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2, allow_nan=False) + "\n").encode()).hexdigest()


def maintenance(root):
    path = Path(root) / "submission_policy/registry.json"
    try:
        data = json.loads(path.read_bytes())
    except FileNotFoundError:
        return None
    return data.get("orcid_maintenance")


def check_access(registry, *, subject=None, owner=None):
    pending = registry.get("orcid_maintenance") or {}
    if pending and (pending.get("phase") == "applying" or subject == pending.get("hf_subject")
                    or owner in (pending.get("old_orcid"), pending.get("new_orcid"))):
        raise ValueError("Researcher Identity is under administrator maintenance; retry after verification.")


def owner_change(before, after, old, new):
    expected = copy.deepcopy(before)
    changed = False
    for field in OWNER_FIELDS:
        if expected.get(field) == old:
            expected[field] = new
            changed = True
    return changed and expected == after


def validate_transfer(operation, record):
    required = {"operation_id", "hf_subject", "old_orcid", "new_orcid", "administrator", "approval_digest",
                "original_owner_approval", "supervisor_approval", "administrator_approval", "verified_at", "completed_at",
                "source_digest", "files", "terminal_changes", "profile_evidence"}
    if set(record) != required or record["operation_id"] != operation or not re.fullmatch(r"[0-9a-f]{32}", operation):
        raise ValueError("Invalid ownership transfer audit")
    if record["old_orcid"] == record["new_orcid"]:
        raise ValueError("Invalid ownership transfer identities")
    for field in ("old_orcid", "new_orcid"):
        if not re.fullmatch(r"\d{4}-\d{4}-\d{4}-[\dX]{4}", record[field]):
            raise ValueError("Invalid ownership transfer identities")
    for field in ("hf_subject", "administrator", "original_owner_approval", "supervisor_approval", "administrator_approval", "verified_at", "completed_at"):
        if not isinstance(record[field], str) or not record[field].strip():
            raise ValueError("Incomplete ownership transfer approval")
    for field in ("approval_digest", "source_digest"):
        if not re.fullmatch(r"[0-9a-f]{64}", record[field]):
            raise ValueError("Invalid ownership transfer digest")
    if record['approval_digest'] != digest({key: record[key] for key in ('original_owner_approval', 'supervisor_approval', 'administrator_approval')}):
        raise ValueError('Ownership transfer approvals changed')
    for path, proof in record['files'].items():
        if path.startswith('/') or '..' in Path(path).parts or '\\' in path or set(proof) != {'before', 'after'} or any(not re.fullmatch(r'[0-9a-f]{64}', value) for value in proof.values()):
            raise ValueError('Invalid transfer file proof')
    if set(record['profile_evidence']) != {'profile_revisions', 'rules_acceptances'} or any(
            set(proof) != {'count', 'digest'} or type(proof['count']) is not int or proof['count'] < 0
            or not re.fullmatch(r'[0-9a-f]{64}', proof['digest']) for proof in record['profile_evidence'].values()):
        raise ValueError('Invalid historical profile evidence')
    for proof in record["terminal_changes"].values():
        if set(proof) != {"before", "after", "prior_commit"} or any(not re.fullmatch(r"[0-9a-f]{64}", proof[key]) for key in ("before", "after")) or not re.fullmatch(r"[0-9a-f]{40}", proof["prior_commit"]):
            raise ValueError("Invalid terminal transfer proof")


def former_owners(registry, current, subject):
    result = {current}
    changed = True
    audits = registry.get("orcid_transfers") or {}
    for operation, record in audits.items():
        validate_transfer(operation, record)
    while changed:
        changed = False
        for record in audits.values():
            if record["hf_subject"] == subject and record["new_orcid"] in result and record["old_orcid"] not in result:
                result.add(record["old_orcid"])
                changed = True
    return result


def approved_terminal(root, identity, before, after):
    registry = json.loads((Path(root) / "submission_policy/registry.json").read_bytes())
    for operation, record in (registry.get("orcid_transfers") or {}).items():
        validate_transfer(operation, record)
        proof = record["terminal_changes"].get(identity)
        if proof and proof["before"] == digest(before) and proof["after"] == digest(after) and owner_change(before, after, record["old_orcid"], record["new_orcid"]):
            return operation, proof
    return None


def unconfirmed_transfers(root, receipts):
    registry = json.loads((Path(root) / "submission_policy/registry.json").read_bytes())
    result = set()
    for operation, record in (registry.get("orcid_transfers") or {}).items():
        validate_transfer(operation, record)
        for identity, proof in record["terminal_changes"].items():
            receipt = receipts.get(identity) or {}
            fingerprints = {receipt.get("fingerprint"), *[entry.get("fingerprint") for entry in receipt.get("ownership_versions", [])]}
            if proof["after"] not in fingerprints:
                result.add(identity)
    return result


def pending_transfer_audits(root, state):
    registry = json.loads((Path(root) / 'submission_policy/registry.json').read_bytes())
    confirmed = (state.get('last_result') or {}).get('orcid_transfer_digests') or {}
    result = {}
    for operation, record in (registry.get('orcid_transfers') or {}).items():
        validate_transfer(operation, record)
        if confirmed.get(operation) != digest(record):
            result[operation] = digest(record)
    return result