Skip to content
Merged
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
12 changes: 6 additions & 6 deletions packages/syft-enclave/src/syft_enclaves/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -789,8 +789,8 @@ def _set_job_permissions(
):
"""Grant inbox read to everyone who needs to see the job (referenced +
approving DOs), state read to them and the submitter, write to each
approving DO on its own approval and log request files, and read to every
approving DO on every approval file."""
approving DO on its own approval and log request files, and read to the
submitter and every approving DO on every approval file."""
job_manager = self._rds.job_client.manager
datasite = self._rds.syftbox_folder / self._rds.email
ctx = SyftPermContext(datasite=datasite)
Expand All @@ -812,12 +812,12 @@ def _set_job_permissions(
):
ctx.open(review_rel / name).grant_write_access(do_email)

# Each DO shows who approved the job, and which files. The submitter
# does not read the approval files.
# Each DO and the submitter show who approved the job, and which files.
approval_readers = list(dict.fromkeys([ref.ds_email, *approval_dos]))
for party in approval_dos:
approval_file = ctx.open(review_rel / enclave_approval_file_name(party))
for do_email in approval_dos:
approval_file.grant_read_access(do_email)
for email in approval_readers:
approval_file.grant_read_access(email)

@classmethod
def from_config(
Expand Down
84 changes: 45 additions & 39 deletions packages/syft-enclave/src/syft_enclaves/enclave_job_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,6 @@
)


# How a data owner's decision on a job shows. Any other status shows as pending.
APPROVAL_MARKS = {JobStatus.APPROVED: "✓", JobStatus.REJECTED: "✗"}
PENDING_MARK = "pending"


class PartyApprovalStatus(BaseModel):
"""Tracks approval from a single party in a multi-party (enclave) job."""

Expand Down Expand Up @@ -102,9 +97,9 @@ class EnclaveJobInfo(JobInfo):
"""Enclave-specific JobInfo with multi-party approval logic.

``_required_approvers`` is set only on the enclave, which runs the job:
there every configured data owner must approve this exact submission. A
data owner's client holds only its own approval file, so it keeps showing
the status of the files it has.
there every configured data owner must approve this exact submission. Each
data owner and the submitter hold every approval file, and read the status
from the files they hold.
"""

_required_approvers: Optional[list[str]] = None
Expand Down Expand Up @@ -186,14 +181,19 @@ def read_permissions_to_share(self) -> ReadPermissions:

@property
def status(self) -> str:
"""The job's status, the same on the enclave, each data owner and the submitter.

The runner records running, done and failed in the state. Before that,
the status comes from the approval files, as ``_party_approvals`` picks
them: on the enclave, of every data owner it is configured with.
"""
if self._state.status in (JobStatus.DONE, JobStatus.FAILED, JobStatus.RUNNING):
return self._state.status.value
if self._required_approvers is not None:
return self._status_from_required_approvers(self._required_approvers)
if not self._approval_file.exists():
approvals = _party_approvals(self.job_review_path, self._required_approvers)
if not approvals and self._required_approvers is None:
# Off the enclave, before it distributed the job: its state is pending.
return self._state.status.value
# A data owner holds every party's approval file, and shows its own.
return self._load_own_approval().status.value
return self._status_from_approvals([a for _, a in approvals])

@property
def can_approve(self) -> bool:
Expand All @@ -204,45 +204,49 @@ def can_approve(self) -> bool:
"""
return self._approval_file.exists()

def _status_from_required_approvers(self, required: list[str]) -> str:
"""Approved only when every required party approved this exact submission.
def _status_from_approvals(
self, approvals: list[Optional[PartyApprovalStatus]]
) -> str:
"""Approved only when every party approved this exact submission.

A missing or unreadable approval file counts as no approval, so removing
a file never stands in for consent. A rejection from any party wins.
With no party to approve, as on an enclave with no data owners
configured, the job is never approved.
"""
if not required:
if not approvals:
return JobStatus.PENDING.value
approvals = [load_party_approval(self.job_review_path, p) for p in required]
if any(a is not None and a.status == JobStatus.REJECTED for a in approvals):
return JobStatus.REJECTED.value
current = submission_hash(self.job_submission_path)
if all(_approves(a, current) for a in approvals):
return JobStatus.APPROVED.value
return JobStatus.PENDING.value

def read_permission_rows(self) -> list[tuple[str, str]]:
def read_permissions_repr_rows(self) -> list[tuple[str, str]]:
"""The read permission state as (label, value) rows, for display.

The enclave and each data owner also show, with a line per data owner,
whether it approved the job and which output files it approved.
Once the enclave has distributed the job, the enclave, each data owner
and the submitter also show, with a line per data owner, whether it
approved the job and which output files it approved.
"""
rows = [("Requested", format_read_permissions(self.requested_read_permissions))]
if not self._holds_approval_files:
# A party without a valid approval file has not approved: it shows as pending.
approvals = [
approval or PartyApprovalStatus(party=party)
for party, approval in _party_approvals(
self.job_review_path, self._required_approvers
)
]
if not approvals:
return rows
approvals = _party_approvals(self.job_review_path, self._required_approvers)
job_lines = [_job_approval_line(party, a) for party, a in approvals]
file_lines = [f"{party}: {_approved_output_files(a)}" for party, a in approvals]
job_lines = [_job_approval_line(a) for a in approvals]
file_lines = [f"{a.party}: {_approved_output_files(a)}" for a in approvals]
return rows + [
("Job approved", "\n".join(job_lines)),
("Output files approved", "\n".join(file_lines)),
]

@property
def _holds_approval_files(self) -> bool:
"""Whether this client holds the approval files: the enclave or a data owner."""
is_enclave = self.current_user_email == self.datasite_owner_email
return is_enclave or self._approval_file.exists()

def _restrict_to_request(
self, read_permissions: Optional[ReadPermissions]
) -> ReadPermissions:
Expand Down Expand Up @@ -405,20 +409,22 @@ def reject(self, reason: Optional[str] = None) -> None:
print(f"Job '{self.name}' rejected by {self.current_user_email}.")


def _job_approval_line(party: str, approval: Optional[PartyApprovalStatus]) -> str:
def _job_approval_line(approval: PartyApprovalStatus) -> str:
"""The party, then ✓ when it approved the job, ✗ and its reason when it
rejected it, and pending otherwise."""
status = approval.status if approval is not None else JobStatus.PENDING
line = f"{party} {APPROVAL_MARKS.get(status, PENDING_MARK)}"
if status == JobStatus.REJECTED and approval.reason:
# On one line, so that each party keeps one line.
line += f" ({' '.join(approval.reason.split())})"
return line
party = approval.party
if approval.status == JobStatus.APPROVED:
return f"{party} ✓"
if approval.status != JobStatus.REJECTED:
return f"{party} pending"
# On one line, so that each party keeps one line.
reason = " ".join((approval.reason or "").split())
return f"{party} ✗ ({reason})" if reason else f"{party} ✗"


def _approved_output_files(approval: Optional[PartyApprovalStatus]) -> str:
def _approved_output_files(approval: PartyApprovalStatus) -> str:
"""The output files the party approved, for display; "none" until it approved."""
if approval is None or approval.status != JobStatus.APPROVED:
if approval.status != JobStatus.APPROVED:
return format_read_permissions({})
return format_read_permissions(approval.approved_read_permissions)

Expand Down
9 changes: 9 additions & 0 deletions packages/syft-enclave/tests/test_enclave_job_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,15 @@ def test_approve_refuses_when_already_approved(tmp_path: Path):
job.approve()


def test_enclave_without_data_owners_never_approves(tmp_path: Path):
"""The enclave runs only an approved job, so no data owners means no run."""
job = _make_enclave_job(tmp_path)
job._state.status = JobStatus.APPROVED
on_enclave = EnclaveJobInfo.from_job_info(job, required_approvers=[])

assert on_enclave.status == "pending"


REQUESTED = {"outputs": [DO_EMAIL, DS_EMAIL], "returncode.txt": [DS_EMAIL]}


Expand Down
23 changes: 23 additions & 0 deletions packages/syft-enclave/tests/test_enclave_jobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -496,6 +496,29 @@ def test_missing_or_foreign_approval_file_does_not_count(spoil):
assert enclave.jobs["test_job"].status == "pending"


def test_run_jobs_waits_for_every_data_owner():
"""``run_jobs`` starts a job only once every configured data owner approved
it. No other party can write the state or owner record that start a run."""
enclave, do1, do2 = _job_distributed_to_both_data_owners()
job = enclave.jobs["test_job"]
datasite = enclave._rds.syftbox_folder / enclave.email
syncer = enclave._rds.sync_engine.datasite_owner_syncer
for name in ("state.yaml", "owner_record.json"):
path = str((job.job_review_path / name).relative_to(datasite))
for party in (do1.email, do2.email, job.submitted_by):
assert not syncer.check_write_permission(party, path)

do1.approve_job(do1.jobs["test_job"])
enclave.sync()
enclave.run_jobs()
assert enclave.jobs["test_job"].status == "pending"

do2.approve_job(do2.jobs["test_job"])
enclave.sync()
enclave.run_jobs()
assert enclave.jobs["test_job"].status == "done"


def test_rejection_rejects_job_and_withdraws_approval():
enclave, do1, do2 = _job_distributed_to_both_data_owners()
do1.approve_job(do1.jobs["test_job"])
Expand Down
28 changes: 16 additions & 12 deletions packages/syft-enclave/tests/test_read_permissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -677,7 +677,7 @@ def test_display_on_enclave_shows_every_party():
do1.jobs["j"].approve(share_files=readable(RETURN_CODE, ds.email))
enclave.sync()

rows = dict(enclave.jobs["j"].read_permission_rows())
rows = dict(enclave.jobs["j"].read_permissions_repr_rows())
# The request survives the distribution, which writes the approval files.
assert rows["Requested"] == (
f"returncode.txt ({ds.email}), stdout.txt ({ds.email})"
Expand All @@ -689,7 +689,7 @@ def test_display_on_enclave_shows_every_party():
}


def test_data_owner_sees_every_owner_approval():
def test_owners_and_submitter_see_every_approval():
enclave, do1, do2, ds = build_quad()
return_code = readable(RETURN_CODE, ds.email)
submit(ds, enclave, do1, do2, OK_CODE, return_code)
Expand All @@ -698,8 +698,10 @@ def test_data_owner_sees_every_owner_approval():
enclave.sync()
do2.sync()

rows = dict(do2.jobs["j"].read_permission_rows())
rows = dict(do2.jobs["j"].read_permissions_repr_rows())
assert lines(rows["Job approved"]) == {f"{do1.email} ✓", f"{do2.email} pending"}
# A data owner shows the job's status, not its own decision.
assert do1.jobs["j"].status == "pending"
assert lines(rows["Output files approved"]) == {
f"{do1.email}: returncode.txt ({ds.email})",
f"{do2.email}: none",
Expand All @@ -710,7 +712,7 @@ def test_data_owner_sees_every_owner_approval():
do1.sync()

job = do1.jobs["j"]
rows = dict(job.read_permission_rows())
rows = dict(job.read_permissions_repr_rows())
# The reason stays on the line of the data owner that rejected.
assert lines(rows["Job approved"]) == {
f"{do1.email} ✓",
Expand All @@ -720,19 +722,21 @@ def test_data_owner_sees_every_owner_approval():
f"{do1.email}: returncode.txt ({ds.email})",
f"{do2.email}: none",
}
# A data owner's status stays its own decision.
assert job.status == "approved"
assert rows["Job approved"].replace("\n", "<br>") in job._repr_html_()
job_approved = " / ".join(rows["Job approved"].splitlines())
assert f"Job approved: {job_approved};" in str(job)
# Each data owner reads every approval file, and writes only its own.
# The submitter sees the same rows as the data owners.
ds.sync()
assert ds.jobs["j"].read_permissions_repr_rows() == job.read_permissions_repr_rows()
# One rejection rejects the job, for every party.
for client in (enclave, do1, do2, ds):
assert client.jobs["j"].status == "rejected"
# Every party reads every approval file, and a data owner writes only its own.
do2_file = enclave_approval_file_name(do2.email)
assert readers_of(enclave, do2_file, [do1, do2, ds]) == [do1, do2]
assert readers_of(enclave, do2_file, [do1, do2, ds]) == [do1, do2, ds]
assert enclave_accepts_write(enclave, do2, do2_file)
assert not enclave_accepts_write(enclave, do1, do2_file)
# The submitter does not get the approval files.
assert not has_file(ds, enclave_approval_file_name(do1.email))
assert dict(ds.jobs["j"].read_permission_rows()).keys() == {"Requested"}
assert not enclave_accepts_write(enclave, ds, do2_file)


# -- the request is DS-writable after the approval ------------------------------
Expand Down Expand Up @@ -806,7 +810,7 @@ def test_display_lists_party_without_file():
review = Path(enclave._rds.job_client.jobs["j"].job_review_path)
(review / enclave_approval_file_name(do2.email)).unlink()

rows = dict(enclave.jobs["j"].read_permission_rows())
rows = dict(enclave.jobs["j"].read_permissions_repr_rows())
assert lines(rows["Job approved"]) == {
f"{do1.email} pending",
f"{do2.email} pending",
Expand Down
4 changes: 2 additions & 2 deletions packages/syft-job/src/syft_job/job.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def _set_approved_read_permissions(
self._state.approved_read_permissions = approved
return approved

def read_permission_rows(self) -> list[tuple[str, str]]:
def read_permissions_repr_rows(self) -> list[tuple[str, str]]:
"""The read permission state as (label, value) rows, for display."""
return [
("Requested", format_read_permissions(self.requested_read_permissions)),
Expand Down Expand Up @@ -645,7 +645,7 @@ def __str__(self) -> str:
# are joined with " / ", because a line can list files with commas.
rows = "; ".join(
f"{label}: {' / '.join(value.splitlines())}"
for label, value in self.read_permission_rows()
for label, value in self.read_permissions_repr_rows()
)
return f"{base} | Read permissions: {rows}"

Expand Down
2 changes: 1 addition & 1 deletion packages/syft-job/src/syft_job/job_repr.py
Original file line number Diff line number Diff line change
Expand Up @@ -469,7 +469,7 @@ def job_info_repr_html(job: "JobInfo") -> str:
policy_details, policy_section = _policy_html(job)

read_permission_details = "".join(
_detail_html(label, value) for label, value in job.read_permission_rows()
_detail_html(label, value) for label, value in job.read_permissions_repr_rows()
)

return f"""
Expand Down
2 changes: 1 addition & 1 deletion packages/syft-job/tests/test_sharing.py
Original file line number Diff line number Diff line change
Expand Up @@ -656,7 +656,7 @@ def test_display_shows_read_permissions(tmp_path):
# Only the requested file is kept, so outputs is not approved.
return_code = f"returncode.txt ({DS_EMAIL})"
requested = f"{return_code}, stderr.txt ({DS_EMAIL}), stdout.txt ({DS_EMAIL})"
assert job.read_permission_rows() == [
assert job.read_permissions_repr_rows() == [
("Requested", requested),
("Approved", return_code),
]
Expand Down
Loading